repo_name
stringlengths
6
130
hexsha
list
file_path
list
code
list
apis
list
possible_versions
list
jaingaurav3/ML_sample
[ "4e53de198f7965fa96f0db44717df27032df4b48" ]
[ "utils/datasets.py" ]
[ "import os\nimport numpy as np\nimport pandas as pd\nfrom sklearn.datasets.samples_generator import make_swiss_roll\nimport torch\nimport torchvision\nfrom torchvision import transforms\nimport glob\nimport random\n\nimport config as cfg\nimport utils.metadata as meta\nfrom . import csv_loader\nfrom . import img_loader\n\n# Datasets\n# pytorch.org/docs/master/torchvision/datasets.html\n# https://github.com/bfortuner/pytorch-cheatsheet/blob/master/pytorch-cheatsheet.ipynb\n\n\ndef get_iris_data():\n fpath = \"../data/iris.csv\"\n url = \"https://raw.githubusercontent.com/pydata/pandas/master/pandas/tests/data/iris.csv\"\n df = csv_loader.load_or_download_df(fpath, url)\n return df\n\n\ndef get_sin_data():\n rng = np.random.RandomState(1)\n X = np.sort(5 * rng.rand(80, 1), axis=0)\n y = np.sin(X).ravel()\n y[::5] += 3 * (0.5 - rng.rand(16))\n return X,y\n\n\ndef get_housing_data():\n # https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html\n fpath = \"../data/housing.csv\"\n url = \"https://raw.githubusercontent.com/ggallo/boston-housing/master/housing.csv\"\n df = csv_loader.load_or_download_df(fpath, url)\n return df\n\n\ndef get_advertising_data():\n fpath = \"../data/advertising.csv\"\n url = \"http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv\"\n df = csv_loader.load_or_download_df(fpath, url)\n df = df.drop(df.columns[0], axis=1)\n return df\n\n\ndef get_swiss_roll_data(n_samples=1000):\n noise = 0.2\n X, _ = make_swiss_roll(n_samples, noise)\n X = X.astype('float32')[:, [0, 2]]\n return X, _\n\n\ndef get_swiss_roll_loader(n_samples=1000):\n X, _ = get_swiss_roll_data(n_samples)\n dataset = torch.utils.data.dataset.TensorDataset(\n torch.FloatTensor(X), torch.FloatTensor(_))\n loader = torch.utils.data.dataloader.DataLoader(\n dataset, batch_size=100, shuffle=True)\n return loader\n\n\ndef get_mnist_loader():\n MNIST_MEAN = np.array([0.1307,])\n MNIST_STD = np.array([0.3081,])\n normTransform = transforms.Normalize(MNIST_MEAN, MNIST_STD)\n\n trainTransform = transforms.Compose([\n transforms.ToTensor(),\n normTransform\n ])\n testTransform = transforms.Compose([\n transforms.ToTensor(),\n normTransform\n ])\n\n trainset = torchvision.datasets.MNIST(root='../data', train=True,\n download=True, transform=trainTransform)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=128,\n shuffle=True, num_workers=2)\n\n testset = torchvision.datasets.MNIST(root='../data', train=False,\n download=True, transform=testTransform)\n testloader = torch.utils.data.DataLoader(testset, batch_size=128,\n shuffle=False, num_workers=2)\n\n return trainloader, testloader\n\n\ndef get_cifar_loader():\n # https://github.com/pytorch/tutorials/blob/master/beginner_source/blitz/cifar10_tutorial.py\n CIFAR_MEAN = np.array([0.49139968, 0.48215827, 0.44653124])\n CIFAR_STD = np.array([0.24703233, 0.24348505, 0.26158768])\n normTransform = transforms.Normalize(CIFAR_MEAN, CIFAR_STD)\n\n trainTransform = transforms.Compose([\n transforms.RandomCrop(32),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normTransform\n ])\n testTransform = transforms.Compose([\n transforms.ToTensor(),\n normTransform\n ])\n\n trainset = torchvision.datasets.CIFAR10(root='../data', train=True,\n download=True, transform=trainTransform)\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=64,\n shuffle=True, num_workers=2)\n\n testset = torchvision.datasets.CIFAR10(root='../data', train=False,\n download=True, transform=testTransform)\n testloader = torch.utils.data.DataLoader(testset, batch_size=64,\n shuffle=False, num_workers=2)\n\n classes = ('plane', 'car', 'bird', 'cat',\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n return trainloader, testloader, classes\n\n\ndef get_catsdogs_loader(imgs_dir):\n # Need to download Kaggle cats/dogs competition\n # And move ALL images into single directory\n classes = ['cat','dog']\n class_to_idx, idx_to_class = meta.get_key_int_maps(classes)\n\n def get_targs_from_fpaths(fpaths):\n targs = []\n for fpath in fpaths:\n classname = fpath.split('/')[-1].split('.')[0]\n # For one-hot sigmoid\n #targ = meta.onehot_encode_class(\n # class_to_idx, classname)\n targs.append(class_to_idx[classname])\n return targs\n\n normalize = transforms.Normalize(\n mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n trainTransform = transforms.Compose([\n transforms.RandomSizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize\n ])\n testTransform = transforms.Compose([\n transforms.Scale(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize\n ])\n\n fpaths = glob.glob(imgs_dir + '*.jpg')\n random.shuffle(fpaths)\n trn_fpaths = fpaths[:20000]\n val_fpaths = fpaths[20000:]\n\n trn_targs = get_targs_from_fpaths(trn_fpaths)\n val_targs = get_targs_from_fpaths(val_fpaths)\n\n img_reader = 'pil'\n trn_dataset = FileDataset(\n trn_fpaths, img_reader, trn_targs, trainTransform)\n val_dataset = FileDataset(\n val_fpaths, img_reader, val_targs, testTransform)\n\n trn_loader = torch.utils.data.DataLoader(\n trn_dataset, batch_size=64,\n shuffle=True, num_workers=4)\n val_loader = torch.utils.data.DataLoader(\n val_dataset, batch_size=64,\n shuffle=False, num_workers=2)\n\n return trn_loader, val_loader, classes\n\n\nloaders = {\n 'pil': img_loader.pil_loader,\n 'tns': img_loader.tensor_loader,\n 'npy': img_loader.numpy_loader,\n 'io': img_loader.io_loader\n}\n\n\nclass FileDataset(torch.utils.data.Dataset):\n def __init__(self, fpaths,\n img_loader='pil',\n targets=None,\n transform=None,\n target_transform=None):\n self.fpaths = fpaths\n self.loader = self._get_loader(img_loader)\n self.targets = targets\n self.transform = transform\n self.target_transform = target_transform\n\n def _get_loader(self, loader_type):\n return loaders[loader_type]\n\n def _get_target(self, index):\n if self.targets is None:\n return 1\n target = self.targets[index]\n if self.target_transform is not None:\n return self.target_transform(target)\n return int(target)\n\n def _get_input(self, index):\n img_path = self.fpaths[index]\n img = self.loader(img_path)\n if self.transform is not None:\n img = self.transform(img)\n return img\n\n def __getitem__(self, index):\n input_ = self._get_input(index)\n target = self._get_target(index)\n img_path = self.fpaths[index]\n return input_, target, img_path\n\n def __len__(self):\n return len(self.fpaths)\n" ]
[ [ "numpy.array", "torch.utils.data.DataLoader", "numpy.sin", "torch.FloatTensor", "sklearn.datasets.samples_generator.make_swiss_roll", "torch.utils.data.dataloader.DataLoader", "numpy.random.RandomState" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
hiepnth/people-counting-pose
[ "8cdaab5281847c296b305643842053d496e2e4e8" ]
[ "video_pose_ed.py" ]
[ "import sys\nimport os\n\nimport math\n\nimport imageio\nfrom moviepy.editor import *\n\nimport time\n\ndef read_video(video_name):\n # Read video from file\n video_name_input = 'testset/' + video_name\n video = VideoFileClip(video_name_input)\n return video\n\ndef video2frame(video_name):\n video = read_video(video_name)\n\n video_frame_number = int(video.duration * video.fps) ## duration: second / fps: frame per second\n video_frame_ciphers = math.ceil(math.log(video_frame_number, 10)) ## ex. 720 -> 3\n\n if not os.path.exists('testset/' + video_name):\n os.makedirs('testset/' + video_name)\n\n for i in range(0, video_frame_number):\n video.save_frame('testset/' + video_name + '/frame_' + str(i).zfill(video_frame_ciphers) + '.jpg', i/video.fps)\n\ndef video2poseframe(video_name):\n import numpy as np\n\n sys.path.append(os.path.dirname(__file__) + \"/../\")\n\n from scipy.misc import imread, imsave\n\n from config import load_config\n from dataset.factory import create as create_dataset\n from nnet import predict\n from util import visualize\n from dataset.pose_dataset import data_to_input\n\n from multiperson.detections import extract_detections\n from multiperson.predict import SpatialModel, eval_graph, get_person_conf_multicut\n from multiperson.visualize import PersonDraw, visualize_detections\n\n import matplotlib.pyplot as plt\n\n from PIL import Image, ImageDraw\n\n import random\n\n cfg = load_config(\"demo/pose_cfg_multi.yaml\")\n\n dataset = create_dataset(cfg)\n\n sm = SpatialModel(cfg)\n sm.load()\n\n # Load and setup CNN part detector\n sess, inputs, outputs = predict.setup_pose_prediction(cfg)\n\n ################\n\n video = read_video(video_name)\n\n video_frame_number = int(video.duration * video.fps) ## duration: second / fps: frame per second\n video_frame_ciphers = math.ceil(math.log(video_frame_number, 10)) ## ex. 720 -> 3\n\n if not os.path.exists('testset/' + video_name):\n os.makedirs('testset/' + video_name)\n\n for i in range(0, video_frame_number):\n image = video.get_frame(i/video.fps)\n\n ######################\n\n image_batch = data_to_input(image)\n\n # Compute prediction with the CNN\n outputs_np = sess.run(outputs, feed_dict={inputs: image_batch})\n scmap, locref, pairwise_diff = predict.extract_cnn_output(outputs_np, cfg, dataset.pairwise_stats)\n\n detections = extract_detections(cfg, scmap, locref, pairwise_diff)\n unLab, pos_array, unary_array, pwidx_array, pw_array = eval_graph(sm, detections)\n person_conf_multi = get_person_conf_multicut(sm, unLab, unary_array, pos_array)\n\n print('person_conf_multi: ')\n print(type(person_conf_multi))\n print(person_conf_multi)\n\n # Add library to save image\n image_img = Image.fromarray(image)\n\n # Save image with points of pose\n draw = ImageDraw.Draw(image_img)\n\n people_num = 0\n point_num = 17\n print('person_conf_multi.size: ')\n print(person_conf_multi.size)\n people_num = person_conf_multi.size / (point_num * 2)\n people_num = int(people_num)\n print('people_num: ')\n print(people_num)\n\n point_i = 0 # index of points\n point_r = 5 # radius of points\n\n people_real_num = 0\n for people_i in range(0, people_num):\n point_color_r = random.randrange(0, 256)\n point_color_g = random.randrange(0, 256)\n point_color_b = random.randrange(0, 256)\n point_color = (point_color_r, point_color_g, point_color_b, 255)\n point_count = 0\n for point_i in range(0, point_num):\n if person_conf_multi[people_i][point_i][0] + person_conf_multi[people_i][point_i][1] != 0: # If coordinates of point is (0, 0) == meaningless data\n point_count = point_count + 1\n if point_count > 5: # If there are more than 5 point in person, we define he/she is REAL PERSON\n people_real_num = people_real_num + 1\n for point_i in range(0, point_num):\n draw.ellipse((person_conf_multi[people_i][point_i][0] - point_r, person_conf_multi[people_i][point_i][1] - point_r, person_conf_multi[people_i][point_i][0] + point_r, person_conf_multi[people_i][point_i][1] + point_r), fill=point_color)\n\n print('people_real_num: ')\n print(people_real_num)\n\n video_name_result = 'testset/' + video_name + '/frame_pose_' + str(i).zfill(video_frame_ciphers) + '.jpg'\n image_img.save(video_name_result, \"JPG\")\n\n\ndef video2posevideo(video_name):\n time_start = time.clock()\n\n import numpy as np\n\n sys.path.append(os.path.dirname(__file__) + \"/../\")\n\n from scipy.misc import imread, imsave\n\n from config import load_config\n from dataset.factory import create as create_dataset\n from nnet import predict\n from util import visualize\n from dataset.pose_dataset import data_to_input\n\n from multiperson.detections import extract_detections\n from multiperson.predict import SpatialModel, eval_graph, get_person_conf_multicut\n from multiperson.visualize import PersonDraw, visualize_detections\n\n import matplotlib.pyplot as plt\n\n from PIL import Image, ImageDraw, ImageFont\n font = ImageFont.truetype(\"./font/NotoSans-Bold.ttf\", 24)\n\n import random\n\n cfg = load_config(\"demo/pose_cfg_multi.yaml\")\n\n dataset = create_dataset(cfg)\n\n sm = SpatialModel(cfg)\n sm.load()\n\n draw_multi = PersonDraw()\n\n # Load and setup CNN part detector\n sess, inputs, outputs = predict.setup_pose_prediction(cfg)\n\n ################\n\n video = read_video(video_name)\n\n video_frame_number = int(video.duration * video.fps) ## duration: second / fps: frame per second\n video_frame_ciphers = math.ceil(math.log(video_frame_number, 10)) ## ex. 720 -> 3\n\n pose_frame_list = []\n\n point_r = 3 # radius of points\n point_min = 10 # threshold of points - If there are more than point_min points in person, we define he/she is REAL PERSON\n part_min = 3 # threshold of parts - If there are more than part_min parts in person, we define he/she is REAL PERSON / part means head, arm and leg\n point_num = 17 # There are 17 points in 1 person\n\n def ellipse_set(person_conf_multi, people_i, point_i):\n return (person_conf_multi[people_i][point_i][0] - point_r, person_conf_multi[people_i][point_i][1] - point_r, person_conf_multi[people_i][point_i][0] + point_r, person_conf_multi[people_i][point_i][1] + point_r)\n\n def line_set(person_conf_multi, people_i, point_i, point_j):\n return (person_conf_multi[people_i][point_i][0], person_conf_multi[people_i][point_i][1], person_conf_multi[people_i][point_j][0], person_conf_multi[people_i][point_j][1])\n\n def draw_ellipse_and_line(draw, person_conf_multi, people_i, a, b, c, point_color):\n draw.ellipse(ellipse_set(person_conf_multi, people_i, a), fill=point_color)\n draw.ellipse(ellipse_set(person_conf_multi, people_i, b), fill=point_color)\n draw.ellipse(ellipse_set(person_conf_multi, people_i, c), fill=point_color)\n draw.line(line_set(person_conf_multi, people_i, a, b), fill=point_color, width=5)\n draw.line(line_set(person_conf_multi, people_i, b, c), fill=point_color, width=5)\n\n for i in range(0, video_frame_number):\n image = video.get_frame(i/video.fps)\n\n ######################\n\n image_batch = data_to_input(image)\n\n # Compute prediction with the CNN\n outputs_np = sess.run(outputs, feed_dict={inputs: image_batch})\n scmap, locref, pairwise_diff = predict.extract_cnn_output(outputs_np, cfg, dataset.pairwise_stats)\n\n detections = extract_detections(cfg, scmap, locref, pairwise_diff)\n unLab, pos_array, unary_array, pwidx_array, pw_array = eval_graph(sm, detections)\n person_conf_multi = get_person_conf_multicut(sm, unLab, unary_array, pos_array)\n\n # print('person_conf_multi: ')\n # print(type(person_conf_multi))\n # print(person_conf_multi)\n\n # Add library to save image\n image_img = Image.fromarray(image)\n\n # Save image with points of pose\n draw = ImageDraw.Draw(image_img)\n\n people_num = 0\n people_real_num = 0\n people_part_num = 0\n\n people_num = person_conf_multi.size / (point_num * 2)\n people_num = int(people_num)\n print('people_num: ' + str(people_num))\n\n for people_i in range(0, people_num):\n point_color_r = random.randrange(0, 256)\n point_color_g = random.randrange(0, 256)\n point_color_b = random.randrange(0, 256)\n point_color = (point_color_r, point_color_g, point_color_b, 255)\n point_list = []\n point_count = 0\n point_i = 0 # index of points\n part_count = 0 # count of parts in THAT person\n\n # To find rectangle which include that people - list of points x, y coordinates\n people_x = []\n people_y = []\n\n for point_i in range(0, point_num):\n if person_conf_multi[people_i][point_i][0] + person_conf_multi[people_i][point_i][1] != 0: # If coordinates of point is (0, 0) == meaningless data\n point_count = point_count + 1\n point_list.append(point_i)\n\n # Draw each parts\n if (5 in point_list) and (7 in point_list) and (9 in point_list): # Draw left arm\n draw_ellipse_and_line(draw, person_conf_multi, people_i, 5, 7, 9, point_color)\n part_count = part_count + 1\n if (6 in point_list) and (8 in point_list) and (10 in point_list): # Draw right arm\n draw_ellipse_and_line(draw, person_conf_multi, people_i, 6, 8, 10, point_color)\n part_count = part_count + 1\n if (11 in point_list) and (13 in point_list) and (15 in point_list): # Draw left leg\n draw_ellipse_and_line(draw, person_conf_multi, people_i, 11, 13, 15, point_color)\n part_count = part_count + 1\n if (12 in point_list) and (14 in point_list) and (16 in point_list): # Draw right leg\n draw_ellipse_and_line(draw, person_conf_multi, people_i, 12, 14, 16, point_color)\n part_count = part_count + 1\n if point_count >= point_min:\n people_real_num = people_real_num + 1\n for point_i in range(0, point_num):\n if person_conf_multi[people_i][point_i][0] + person_conf_multi[people_i][point_i][1] != 0: # If coordinates of point is (0, 0) == meaningless data\n draw.ellipse(ellipse_set(person_conf_multi, people_i, point_i), fill=point_color)\n people_x.append(person_conf_multi[people_i][point_i][0])\n people_y.append(person_conf_multi[people_i][point_i][1])\n # Draw rectangle which include that people\n draw.rectangle([min(people_x), min(people_y), max(people_x), max(people_y)], fill=point_color, outline=5)\n\n\n if part_count >= part_min:\n people_part_num = people_part_num + 1\n\n draw.text((0, 0), 'People(by point): ' + str(people_real_num) + ' (threshold = ' + str(point_min) + ')', (0,0,0), font=font)\n draw.text((0, 32), 'People(by line): ' + str(people_part_num) + ' (threshold = ' + str(part_min) + ')', (0,0,0), font=font)\n draw.text((0, 64), 'Frame: ' + str(i) + '/' + str(video_frame_number), (0,0,0), font=font)\n draw.text((0, 96), 'Total time required: ' + str(round(time.clock() - time_start, 1)) + 'sec', (0,0,0))\n\n print('people_real_num: ' + str(people_real_num))\n print('people_part_num: ' + str(people_part_num))\n print('frame: ' + str(i))\n\n image_img_numpy = np.asarray(image_img)\n\n pose_frame_list.append(image_img_numpy)\n\n video_pose = ImageSequenceClip(pose_frame_list, fps=video.fps)\n video_pose.write_videofile(\"testset/\" + video_name + \"_pose.mp4\", fps=video.fps)\n\n print(\"Time(s): \" + str(time.clock() - time_start))\n" ]
[ [ "numpy.asarray" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
meghdeepj/Social-Navigation-Simulator
[ "806d304081bf5ff4fc7a0a58defb050627375865", "806d304081bf5ff4fc7a0a58defb050627375865" ]
[ "gym_collision_avoidance/envs/policies/SOCIALFORCEPolicy.py", "gym_collision_avoidance/envs/policies/NAVIGAN/scripts/sgan/utils.py" ]
[ "import os\nimport math\nimport sys\nimport torch\nimport numpy as np\n\n\nfrom gym_collision_avoidance.envs.policies.InternalPolicy import InternalPolicy\nfrom gym_collision_avoidance.envs import Config\nfrom gym_collision_avoidance.envs.util import *\n\nfrom gym_collision_avoidance.envs.policies import socialforce\n\nimport copy\nimport argparse\n\n# Filter list by Boolean list \n# Using itertools.compress \nfrom itertools import compress\n\nclass SOCIALFORCEPolicy(InternalPolicy):\n def __init__(self):\n InternalPolicy.__init__(self, str=\"SOCIALFORCE\")\n self.dt = Config.DT\n self.obs_seq_len = 8\n\n self.is_init = False\n\n\n \n\n def init(self,agents):\n \n self.total_agents_num = [None]*self.n_agents\n\n self.is_init = True\n\n def find_next_action(self, obs, agents, i , full_agent_list = None, active_agent_mask = None):\n\n agent_index = i\n\n #check if elements before index contains non active agents, if yes, remove them, thus calculate the index shift\n before_index = np.array(active_agent_mask)[:agent_index]\n\n #see how many non active agents are before index, minus them calculate index shift\n agent_index = agent_index - len( before_index[ before_index==False ] )\n\n agents = list(compress(full_agent_list, active_agent_mask))\n\n \n observation_array = [] #observation array for social force, consist of N row of agents, each row = vector (x, y, v_x, v_y, d_x, d_y, [tau])\n \n if not self.is_init: #Execute one time per init (complete simulation iteration)\n self.n_agents = len(agents)\n self.init(agents)\n\n\n #initialize the observation vector because when starts, social force seems to require a starting vel for agents to move\n for a in range(self.n_agents):\n pos_difference = agents[a].goal_global_frame - agents[a].pos_global_frame \n dist_next_waypoint = ( pos_difference / (np.linalg.norm( pos_difference ,ord=1)+0.0000001) ) * ( agents[a].pref_speed )\n\n vel_next_waypoint = dist_next_waypoint \n \n observation_array.append( [ agents[a].pos_global_frame[0], agents[a].pos_global_frame[1], vel_next_waypoint[0], vel_next_waypoint[1], agents[a].goal_global_frame[0], agents[a].goal_global_frame[1] ] )\n\n\n else:\n ##added for dynamic num of agents compatibility\n self.n_agents = len(agents)\n self.init(agents)\n\n for a in range(self.n_agents):\n if agents[a].speed_global_frame<= agents[a].pref_speed/3:\n pos_difference = agents[a].goal_global_frame - agents[a].pos_global_frame \n dist_next_waypoint = ( pos_difference / (np.linalg.norm( pos_difference ,ord=1)+0.0000001) ) * ( agents[a].pref_speed )\n\n vel_next_waypoint = dist_next_waypoint \n \n observation_array.append( [ agents[a].pos_global_frame[0], agents[a].pos_global_frame[1], vel_next_waypoint[0], vel_next_waypoint[1], agents[a].goal_global_frame[0], agents[a].goal_global_frame[1] ] )\n\n else:\n \n observation_array.append( [ agents[a].pos_global_frame[0], agents[a].pos_global_frame[1], agents[a].vel_global_frame[0], agents[a].vel_global_frame[1], agents[a].goal_global_frame[0], agents[a].goal_global_frame[1] ] )\n\n #print(\"goal\")\n #print(agents[agent_index].goal_global_frame)\n \n initial_state = np.array( observation_array )\n s=None\n #s = socialforce.Simulator(initial_state, delta_t=0.1)\n s = socialforce.Simulator(initial_state, delta_t=0.1)\n states = np.stack([s.step().state.copy() for _ in range(1)]) #step one time only\n\n #print(\"states\")\n #print(states)\n\n next_waypoint_x = states[:, agent_index, 0][0]\n next_waypoint_y = states[:, agent_index, 1][0]\n \n next_waypoint_vel_x = states[:, agent_index, 2][0]\n next_waypoint_vel_y = states[:, agent_index, 3][0]\n\n self.next_waypoint = np.array( [ next_waypoint_x , next_waypoint_y ] )\n \n goal_direction = self.next_waypoint - agents[agent_index].pos_global_frame\n self.dist_to_goal = math.sqrt(goal_direction[0]**2 + goal_direction[1]**2)\n if self.dist_to_goal > 1e-8:\n ref_prll = goal_direction / agents[agent_index].dist_to_goal\n else:\n ref_prll = goal_direction\n ref_orth = np.array([-ref_prll[1], ref_prll[0]]) # rotate by 90 deg\n\n ref_prll_angle_global_frame = np.arctan2(ref_prll[1],\n ref_prll[0])\n heading_ego_frame = wrap( agents[agent_index].heading_global_frame -\n ref_prll_angle_global_frame)\n\n \n\n vel_global_frame = np.array( [ next_waypoint_vel_x , next_waypoint_vel_y ] )#( self.next_waypoint - agents[agent_index].pos_global_frame) / agents[agent_index].dt_nominal\n\n speed_global_frame = np.linalg.norm(vel_global_frame)\n if speed_global_frame > agents[agent_index].pref_speed: speed_global_frame = agents[agent_index].pref_speed\n\n #But in reality, the format of action is [speed, heading_delta]\n\n action = np.array([speed_global_frame, -heading_ego_frame])\n #print(\"action\")\n #print(action)\n \n return action\n\n #agents[agent_index].set_state( next_waypoint_x , next_waypoint_y, next_waypoint_vel_x, next_waypoint_vel_y )\n \n #resultant_speed_global_frame = agents[agent_index].speed_global_frame\n #resultant_delta_heading_global_frame = agents[agent_index].delta_heading_global_frame\n \n ###########################################################POSITION APPROACH##########################################################################\n## print(\"position\")\n## print(agents[agent_index].pos_global_frame)\n## next_waypoint_x = states[:, agent_index, 0][0]\n## next_waypoint_y = states[:, agent_index, 1][0]\n##\n## next_waypoint = np.array( [ next_waypoint_x, next_waypoint_y ] )\n## print(\"next_waypoint\")\n## print(next_waypoint)\n##\n##\n## \n## pos_difference = next_waypoint - agents[agent_index].pos_global_frame \n## dist_next_waypoint = ( pos_difference / (np.linalg.norm( pos_difference ,ord=1)+0.0000001) ) * ( agents[agent_index].pref_speed * 0.1)\n##\n## position_x = agents[agent_index].pos_global_frame[0] + dist_next_waypoint[0]\n## position_y = agents[agent_index].pos_global_frame[1] + dist_next_waypoint[1]\n## agents[agent_index].set_state( position_x , position_y )\n## \n## resultant_speed_global_frame = agents[agent_index].speed_global_frame\n## resultant_delta_heading_global_frame = agents[agent_index].delta_heading_global_frame\n\n #Although documentation and code comment mentioned that action is consisted with [heading delta, speed]\n #But in reality, the format of action is [speed, heading_delta]\n ###########################################################################################################################################\n\n", "import os\nimport time\nimport torch\nimport numpy as np\nimport inspect\nfrom contextlib import contextmanager\nimport subprocess\n\n\ndef int_tuple(s):\n return tuple(int(i) for i in s.split(','))\n\n\ndef find_nan(variable, var_name):\n variable_n = variable.data.cpu().numpy()\n if np.isnan(variable_n).any():\n exit('%s has nan' % var_name)\n\n\ndef bool_flag(s):\n if s == '1':\n return True\n elif s == '0':\n return False\n msg = 'Invalid value \"%s\" for bool flag (should be 0 or 1)'\n raise ValueError(msg % s)\n\n\ndef lineno():\n return str(inspect.currentframe().f_back.f_lineno)\n\n\ndef get_total_norm(parameters, norm_type=2):\n if norm_type == float('inf'):\n total_norm = max(p.grad.data.abs().max() for p in parameters)\n else:\n total_norm = 0\n for p in parameters:\n try:\n param_norm = p.grad.data.norm(norm_type)\n total_norm += param_norm**norm_type\n total_norm = total_norm**(1. / norm_type)\n except:\n continue\n return total_norm\n\n\n@contextmanager\ndef timeit(msg, should_time=True):\n if should_time:\n torch.cuda.synchronize()\n t0 = time.time()\n yield\n if should_time:\n torch.cuda.synchronize()\n t1 = time.time()\n duration = (t1 - t0) * 1000.0\n print('%s: %.2f ms' % (msg, duration))\n\n\ndef get_gpu_memory():\n torch.cuda.synchronize()\n opts = [\n 'nvidia-smi', '-q', '--gpu=' + str(1), '|', 'grep', '\"Used GPU Memory\"'\n ]\n cmd = str.join(' ', opts)\n ps = subprocess.Popen(\n cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n output = ps.communicate()[0].decode('utf-8')\n output = output.split(\"\\n\")[0].split(\":\")\n consumed_mem = int(output[1].strip().split(\" \")[0])\n return consumed_mem\n\n\ndef get_dset_path(dset_name, dset_type):\n _dir = os.path.dirname(__file__)\n _dir = _dir.split(\"/\")[:-1]\n _dir = \"/\".join(_dir)\n return os.path.join(_dir, 'datasets', dset_name, dset_type)\n\n\ndef relative_to_abs(rel_traj, start_pos):\n \"\"\"\n Inputs:\n - rel_traj: pytorch tensor of shape (seq_len, batch, 2)\n - start_pos: pytorch tensor of shape (batch, 2)\n Outputs:\n - abs_traj: pytorch tensor of shape (seq_len, batch, 2)\n \"\"\"\n # batch, seq_len, 2\n rel_traj = rel_traj.permute(1, 0, 2)\n # displacement = torch.cumsum(rel_traj, dim=1)\n start_pos = torch.unsqueeze(start_pos, dim=1)\n abs_traj = rel_traj + start_pos\n return abs_traj.permute(1, 0, 2)\n" ]
[ [ "numpy.arctan2", "numpy.array", "numpy.linalg.norm" ], [ "numpy.isnan", "torch.cuda.synchronize", "torch.unsqueeze" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ManavR123/cs_285_project
[ "2a0496345c2a8de06338ae7e44ca3775a9291f4c" ]
[ "deeptutor/scripts/run.py" ]
[ "import os\nimport pickle\n\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom deeptutor.envs.DashEnv import *\nfrom deeptutor.envs.EFCEnv import EFCEnv\nfrom deeptutor.envs.HRLEnv import *\nfrom deeptutor.infrastructure.utils import *\nfrom deeptutor.tutors.LeitnerTutor import LeitnerTutor\nfrom deeptutor.tutors.RandTutor import RandTutor\nfrom deeptutor.tutors.PPOTutor import PPOTutor\nfrom deeptutor.tutors.SACTutor import SACTutor\nfrom deeptutor.tutors.DQNTutor import DQNTutor\nfrom deeptutor.tutors.MLPTRPOTutor import MLPTRPOTutor\nfrom deeptutor.tutors.GRUTRPOTutor import GRUTRPOTutor\nfrom deeptutor.tutors.SuperMnemoTutor import SuperMnemoTutor\nfrom deeptutor.tutors.ThresholdTutor import ThresholdTutor\n\n\ndef load_rewards(tutor_name, data_dir):\n filename = os.path.join(data_dir, f\"{tutor_name}_reward_logs.pkl\")\n if not os.path.exists(filename):\n return {}\n with open(filename, \"rb\") as f:\n return pickle.load(f)[\"rewards\"]\n\n\ndef main():\n override = True # override existing data\n data_dir = os.path.join(os.getcwd(), \"data\")\n n_steps = 200\n n_items = 30\n const_delay = 5\n discount = 0.99\n n_reps = 10\n n_eps = 100\n env_kwargs = {\n \"n_items\": n_items,\n \"n_steps\": n_steps,\n \"discount\": discount,\n \"sample_delay\": sample_const_delay(const_delay),\n }\n reward_funcs = [\n \"likelihood\",\n \"log_likelihood\"\n ]\n envs = [\n (\"EFC\", EFCEnv),\n (\"HLR\", HLREnv),\n (\"DASH\", DASHEnv)\n ]\n\n tutor_builders = [\n # (\"Random\", RandTutor),\n # (\"Leitner\", LeitnerTutor),\n # (\"SuperMnemo\", SuperMnemoTutor),\n # (\"Threshold\", ThresholdTutor),\n # (\"MLPTRPO\", MLPTRPOTutor),\n # (\"GRUTRPO\", GRUTRPOTutor),\n # (\"PPO\", PPOTutor),\n (\"DQN\", DQNTutor),\n ]\n\n rl_tutors = [MLPTRPOTutor, GRUTRPOTutor, PPOTutor, DQNTutor]\n\n reward_logs = {\n \"n_steps\": n_steps,\n \"n_items\": n_items,\n \"discount\": discount,\n \"const_delay\": const_delay,\n \"n_reps\": n_reps,\n \"n_eps\": n_eps,\n \"reward_funcs\": reward_funcs,\n }\n\n for i, (tutor_name, build_tutor) in enumerate(tutor_builders):\n print(f\"Training {tutor_name}\")\n rewards = load_rewards(tutor_name, data_dir)\n for h, (base_env_name, base_env) in enumerate(envs):\n for m, reward_func in enumerate(reward_funcs):\n env_name = (\n base_env_name + \"-\" + (\"L\" if reward_func == \"likelihood\" else \"LL\")\n )\n print(f\"Environment: {env_name}\")\n if env_name in rewards.keys() and not override:\n print(\"Skipping\\n\")\n continue\n R = np.zeros((n_eps, n_reps))\n for j in tqdm(range(n_reps)):\n np.random.seed(j)\n env = base_env(**env_kwargs, reward_func=reward_func)\n if build_tutor in rl_tutors:\n rl_env = make_rl_student_env(env)\n agent = build_tutor(n_items)\n R[:, j] = agent.train(rl_env, n_eps=n_eps, seed=j)\n else:\n if \"Thresh\" in tutor_name:\n agent = build_tutor(n_items, env=env)\n else:\n agent = build_tutor(n_items)\n R[:, j] = agent.train(env, n_eps=n_eps)\n rewards[env_name] = R\n reward_logs[\"rewards\"] = rewards\n with open(os.path.join(data_dir, f\"{tutor_name}_reward_logs.pkl\"), \"wb\") as f:\n pickle.dump(reward_logs, f, pickle.HIGHEST_PROTOCOL)\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.zeros", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
linkinpark213/pytorch-lstm-toy
[ "a89eba74a3606dab125d394e63e4a585319227f1" ]
[ "test.py" ]
[ "import torch\nimport numpy as np\nimport torch.utils.data\nfrom net import SurnameLSTM\nfrom data import SurnameDataset\n\nif __name__ == '__main__':\n net = SurnameLSTM()\n state_dict = torch.load('model.pth')\n net.load_state_dict(state_dict)\n\n dataset = SurnameDataset(subset='val')\n data_loader = torch.utils.data.DataLoader(dataset, batch_size=64, shuffle=True)\n sample = iter(data_loader).__next__()\n\n pred = np.argmax(net(sample['values']).detach().numpy(), axis=1)\n gt = np.array(sample['raw_label'])\n\n accuracy = np.average(np.where(pred == gt, 1, 0))\n print('Accuracy on the validation data: {:.1f} %'.format(accuracy * 100))\n\n print('Please enter a surname to val:')\n input_name = input()\n name = input_name.lower()\n name_ascii = np.array([ord(c) for c in name])\n name_ascii = np.pad(name_ascii, ((0, 12 - name_ascii.__len__())), mode='constant', constant_values=0).astype(\n np.float32)\n name_ascii = torch.tensor([name_ascii])\n\n pred = np.argmax(net(name_ascii).detach().numpy(), axis=1)\n print('Mr / Ms. {}, I guess you are {}!'.format(input_name, ['English', 'Chinese', 'Japanese'][pred[0]]))\n" ]
[ [ "torch.load", "torch.utils.data.DataLoader", "torch.tensor", "numpy.array", "numpy.where" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ronaldosvieira/rl
[ "01e7ac1a6fabe7a74171ce45e220232fdb23280b" ]
[ "main.py" ]
[ "import numpy as np\n\nclass Reward:\n\tpass\n\nclass StaticReward(Reward):\n\tdef __init__(self, value):\n\t\tself.value = value\n\n\tdef get(self):\n\t\treturn value\n\nclass NormalReward(Reward):\n\tdef __init__(self, mean, std):\n\t\tself.mean = mean\n\t\tself.std = std\n\n\tdef get(self):\n\t\treturn np.random.normal(self.mean, self.std)\n\nclass Bandit:\n\tdef __init__(self, arms):\n\t\tself.no_of_arms = arms\n\t\tself.arms = [np.random.normal(0, 1) for _ in range(arms)]\n\n\tdef step(self, arm):\n\t\treturn np.random.normal(self.arms[arm], 1)\n\nclass MDP:\n\t\"\"\"\n\tRepresents a Markov Decision Process.\n\t\"\"\"\n\tdef __init__(self, S, A, R, p):\n\t\t\"\"\"\n\t\tParameters\n\t\t----------\n\t\tS : int\n\t\t\tNumber of states\n\t\tA : matrix\n\t\t\tA[s][a] is True iff a is permitted in s\n\t\tR : list\n\t\t\tA list of reward generators\n\t\tp : matrix\n\t\t\tp[s][a][s'] = p(s'|s,a)\n\t\t\"\"\"\n\n\t\tself.S = list(range(S))\n\t\tself.A, self.R, self.p = A, R, p\n\t\tself.no_of_states = S\n\t\tself.no_of_actions = len(A[0])\n\n\tdef step(self, s, a):\n\t\t\"\"\"Given a state and an action, returns a new state and a reward.\n\n\t\tParameters\n\t\t----------\n\t\ts : int\n\t\t\tCurrent state\n\t\ta : int\n\t\t\tAction to take\n\t\t\"\"\"\n\n\t\ts_prime = np.random.choice(self.no_of_states, p = self.p[s][a])\n\t\tr = self.R[s_prime].get()\n\n\t\treturn s_prime, r\n\ndef epsilon_greedy(no_of_arms, epsilon, Q, N):\n\tif np.random.random() > epsilon:\n\t\t# greedy\n\t\taction = np.argmax(Q)\n\telse:\n\t\t# random\n\t\taction = np.random.choice(no_of_arms)\n\n\treturn action\n\ndef main():\n\tno_of_arms = 10\n\tno_of_steps = 1000\n\tepsilon = 0.1\n\n\tno_of_runs = 2000\n\n\t#bandit = Bandit(no_of_arms)\n\n\tarms = np.random.normal(0, 1, no_of_arms)\n\n\tS = 1\n\tA = [[True] * no_of_arms]\n\tR = [NormalReward(m, 1) for m in arms]\n\tp = [[[1] for _ in range(no_of_arms)]]\n\n\tbandit = MDP(S, A, R, p)\n\t\n\t#optimal_action = np.argmax(bandit.arms)\n\toptimal_action = np.argmax(arms)\n\n\tnp.random.seed(1)\n\n\tQ = [[0] * no_of_arms] * no_of_runs\n\tN = [[0] * no_of_arms] * no_of_runs\n\n\tmean_rewards = [0] * no_of_steps\n\n\tfor j in range(no_of_steps):\n\t\tfor i in range(no_of_runs):\n\t\t\taction = epsilon_greedy(no_of_arms, epsilon, Q[i], N[i])\n\n\t\t\t#reward = bandit.step(action)\n\t\t\t_, reward = bandit.step(0, action)\n\n\t\t\tmean_rewards[j] += reward\n\n\t\t\tN[i][action] += 1\n\t\t\tQ[i][action] += (1 / N[i][action]) * (reward - Q[i][action])\n\n\t\tmean_rewards[j] /= no_of_runs\n\nif __name__ == '__main__':\n\tmain()" ]
[ [ "numpy.random.random", "numpy.random.seed", "numpy.random.choice", "numpy.random.normal", "numpy.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
senisioi/Romanian-Transformers
[ "45f4c4513fd0a5a81f4a20a5d63b4b9cd1d10b43" ]
[ "corpus/text_cleaner.py" ]
[ "import re, multiprocessing\nfrom tqdm import tqdm\nimport numpy as np\n\nclass Cleaner():\n def __init__(self, num_threads=1): # right now, it's single threaded\n self.num_threads = min(num_threads, int(multiprocessing.cpu_count()/2))\n\n \"\"\"\n S- ar putea să fie necesar să- l recitiţi.\n \"\"\"\n self.r1 = re.compile(r\"([\\w]+-)[\\s]([\\w]+)\", re.IGNORECASE)\n\n \"\"\"\n {LL/ AAAA}\n Humalog Mix50 100 U/ ml\n \"\"\"\n self.r2 = re.compile(r\"([\\w]+/)\\s([\\w]+)\", re.IGNORECASE)\n\n \"\"\"\n All unicode dashes to normal '-', see https://www.fileformat.info/info/unicode/category/Pd/list.htm\n includes bull : • \\u2022\n \"\"\"\n self.r3 = re.compile(r\"([■\\u2022\\u007E\\u00AD\\u058A\\u05BE\\u1400\\u1806\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2053\\u207B\\u208B\\u2212\\u2E17\\u2E3A\\u2E3B\\u301C\\u3030\\u30A0\\uFE31\\uFE32\\uFE63\\uFF0D]+)\", re.UNICODE)\n\n \"\"\"\n spaces after comma in numbers: 1, 4% -> 1,4%\n \"\"\"\n self.r4 = re.compile(r\"([\\d]+,)\\s([\\d]+)\", re.IGNORECASE)\n\n \"\"\"\n soft hyphens #\\u00AD\n \"\"\"\n self.r5 = re.compile(r\"[\\u00AD]\")\n\n \"\"\"\n remove URLS\n \"\"\"\n self.r6 = re.compile(r'(?:www|http)\\S+|<\\S+|\\w+\\/*>')\n\n \"\"\"\n remove emails\n \"\"\"\n self.r7 = re.compile(r'([^@]+@[^@]+\\.[^@]+)')\n\n \"\"\"\n table separators\n \"\"\"\n self.r8 = re.compile(r'[\\─\\─]+')\n self.r9 = re.compile(r'[\\-\\-]+')\n\n \"\"\"\n multiple spaces\n \"\"\"\n self.space = re.compile(' +')\n\n \"\"\"\n forbiden chars that cause a lot of bad sentences\n \"\"\"\n self.forbidden_chars = \"ºþÈ™ÓÑÄÈîƒ\"\n\n def process(self, lines, percent_max_numeric=0.7, percent_max_non_ascii=0.40, min_line_length=20, verbose=False, disable_pbar=True):\n skipped_because_min_length = np.array([0,0], dtype=np.uint64)\n skipped_alpha_count = np.array([0,0], dtype=np.uint64)\n skipped_because_max_numeric = np.array([0,0], dtype=np.uint64)\n skipped_because_max_non_ascii = np.array([0,0], dtype=np.uint64)\n skipped_because_forbidden_chars = np.array([0,0], dtype=np.uint64)\n total_original_length = 0\n total_clean_length = 0\n output = []\n for line in tqdm(lines, disable = disable_pbar):\n line = line.strip()\n\n # get stats about line\n length = len(line)\n total_original_length += length\n\n if length < min_line_length:\n skipped_because_min_length += np.array([1,length], dtype=np.uint64)\n continue\n\n line = bytes(line, 'utf-8').decode('utf-8', 'ignore') # strip not utf-8 chars\n\n digit_count = 0\n alpha_count = 0\n ascii_count = 0\n forbidden_char = False\n for char in line:\n if char in self.forbidden_chars:\n forbidden_char = True\n break\n if char.isnumeric():\n digit_count+=1\n if char.isalpha():\n alpha_count+=1\n if char.isascii():\n ascii_count+=1\n\n # reject if forbidden char\n if forbidden_char:\n skipped_because_forbidden_chars += np.array([1,length], dtype=np.uint64)\n continue\n\n # reject if number of letters is too small\n if alpha_count == 0 or alpha_count / length < 0.5:\n skipped_alpha_count += np.array([1,length], dtype=np.uint64)\n if verbose:\n print(\"Skipping alpha={:.3f}: [{}]\".format(alpha_count / length, line))\n continue\n\n # reject if too many numbers\n if digit_count / alpha_count >= percent_max_numeric and digit_count > 6:\n skipped_because_max_numeric += np.array([1,length], dtype=np.uint64)\n if verbose:\n print(\"Skipping digit={:.3f}: [{}]\".format(digit_count / alpha_count, line))\n continue\n # reject if too many non-ascii\n if ascii_count / alpha_count < percent_max_non_ascii and length > 15:\n skipped_because_max_non_ascii += np.array([1,length], dtype=np.uint64)\n if verbose:\n print(\"Skipping ascii={:.3f}: [{}]\".format(digit_count / alpha_count, line))\n continue\n\n #skip lines that appear to be ascii tables │\n if (line.strip()[0] == '|' and line.count('|') > 2) or (line.strip()[0] == '│' and line.count('│') > 2):\n skipped_because_forbidden_chars += np.array([1,length], dtype=np.uint64)\n if verbose:\n print(\"Skipping table line: [{}]\".format(line))\n continue\n\n # clean line\n #print(\"\\nbef: {}\".format(line))\n line = self.r1.sub(r\"\\1\\2\", line)\n line = self.r2.sub(r\"\\1\\2\", line)\n line = self.r3.sub(\"-\", line)\n line = self.r4.sub(r\"\\1\\2\", line)\n line = self.r5.sub(\"\", line)\n line = self.r6.sub(\"\", line)\n line = self.r7.sub(\"\", line)\n # separators\n line = self.r8.sub(\"\", line)\n line = self.r9.sub(\"\", line)\n\n line = line.replace(\"( ă)\", \"(ă)\")\n line = line.replace(\"ţ\", \"ț\")\n line = line.replace(\"ş\", \"ș\")\n line = line.replace(\"Ţ\", \"Ț\")\n line = line.replace(\"Ş\", \"Ș\")\n line = line.replace(\"â\", \"â\")\n\n #print(\"aft: {}\".format(line))\n\n line = self.space.sub(' ', line).strip()\n\n # check that after processing the line is not too short\n if len(line) < min_line_length:\n skipped_because_min_length += np.array([1,length], dtype=np.uint64)\n continue\n\n total_clean_length += len(line)\n output.append(line+\"\\n\")\n\n # pack stats\n stats = {}\n stats[\"skipped_because_min_length\"] = skipped_because_min_length\n stats[\"skipped_alpha_count\"] = skipped_alpha_count\n stats[\"skipped_because_max_numeric\"] = skipped_because_max_numeric\n stats[\"skipped_because_max_non_ascii\"] = skipped_because_max_non_ascii\n stats[\"skipped_because_forbidden_chars\"] = skipped_because_forbidden_chars\n stats[\"total_original_length\"] = total_original_length\n stats[\"total_clean_length\"] = total_clean_length\n\n return output, stats\n\n def add_stats(self, a, b):\n \"\"\"\n Add two stats dict that are returned by the process function.\n This is used for multiple files\n :param a: stats dict\n :param b: stats dict\n :return: stats dict\n \"\"\"\n stats = {}\n stats[\"skipped_because_min_length\"] = a[\"skipped_because_min_length\"] + b[\"skipped_because_min_length\"]\n stats[\"skipped_alpha_count\"] = a[\"skipped_alpha_count\"] + b[\"skipped_alpha_count\"]\n stats[\"skipped_because_max_numeric\"] = a[\"skipped_because_max_numeric\"] + b[\"skipped_because_max_numeric\"]\n stats[\"skipped_because_max_non_ascii\"] = a[\"skipped_because_max_non_ascii\"] + b[\"skipped_because_max_non_ascii\"]\n stats[\"skipped_because_forbidden_chars\"] = a[\"skipped_because_forbidden_chars\"] + b[\"skipped_because_forbidden_chars\"]\n stats[\"total_original_length\"] = a[\"total_original_length\"] + b[\"total_original_length\"]\n stats[\"total_clean_length\"] = a[\"total_clean_length\"] + b[\"total_clean_length\"]\n return stats\n\n def print_stats(self, stats):\n print(\"\\nCleaning statistics:\")\n print(\"Total original length (chars) = {}\".format(stats[\"total_original_length\"]))\n print(\"Total length after cleaning (chars) = {}\".format(stats[\"total_clean_length\"]))\n print(\"Percent data kept = {:.3f} %\".format(100.*stats[\"total_clean_length\"]/stats[\"total_original_length\"]))\n\n print(\"Skipped because line length was below minimum (lines/chars): {} \".format(stats[\"skipped_because_min_length\"]))\n print(\"Skipped because line had forbidden characters (lines/chars): {} \".format(stats[\"skipped_because_forbidden_chars\"]))\n print(\"Skipped because alpha count was below minimum (lines/chars): {} \".format(stats[\"skipped_alpha_count\"]))\n print(\"Skipped because digit count was above maximum (lines/chars): {} \".format(stats[\"skipped_because_max_numeric\"]))\n print(\"Skipped because too many non-ascii characters (lines/chars): {} \".format(stats[\"skipped_because_max_non_ascii\"]))\n\ntext = [\" - ~~~~~Păstraţi acest prospect. S- ar putea să fie necesar să- l recitiţi.\",\n \"- Dacă aveţi orice întrebări suplimentare, adresaţi- vă medicului dumneavoastră sau farmacistului.\\n\",\n \"{LL/ AAAA}\\n\",\n \"MANUALUL UTILIZATORULUI\\n\",\n \"Vezi textul manualului mai jos.\\n\",\n \"303 Informaţii detaliate privind acest medicament sunt disponibile pe website- ul Agenţiei Europene a Medicamentului (EMEA): http: // www. emea. europa. eu /.\\n\",\n \"304 PROSPECT:­ \\n\",\n \"INFORMAŢII PENTRU UTILIZATOR\",\n \"Humalog Mix50 100 U/ ml • • • ~~~~\",\n \"Τηλ: +30 210 629 4600 España Lilly S. A.\",\n \"Tel: + 34- 91 663 50 00 France Lilly France S. A. S.\",\n \"Tél: +33 - (0) 1 55 49 34 34 Ireland Eli Lilly and Company (Ireland) Limited Tel: + 353 - (0) 1 661 4377 Ísland Icepharma hf.\",\n \"Sími + 354 540 8000 Italia Eli Lilly Italia S. p. A.\",\n \"Tel: + 39 - 055 42571 Κύπρος Phadisco Ltd Τηλ: +357 22 715000 \",\n \"Luxembourg/ Luxemburg Eli Lilly Benelux S. A.\",\n \"Tél/ Tel: + 32 - (0) 2 548 84 84 Magyarország Lilly Hungária Kft.\",\n \"Tel: + 36 1 328 5100 Malta Charles de Giorgio Ltd.\",\n \"Κύπρος Βαρνάβας Χατζηπαναγής Λτδ 7 Ανδροκλέους CY- 1060 Λευκωσία Tηλ\"]\n\n#tt = []\n#for i in range(100000):\n# tt.extend(text)\n#print(len(tt))\n\"\"\"\nc = Cleaner(1)\nlines, s1 = c.process(text)\nlines, s2 = c.process(text)\n\nstats = c.add_stats(s1, s2)\n\nc.print_stats(s1)\nc.print_stats(s2)\nc.print_stats(stats)\nprint(\"DONE\")\n\"\"\"\n\n\n\n\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ksburaya/aphantasia
[ "de9d430dee7108abfcb1b19eb2d8d806b8e5d899" ]
[ "illustrip.py" ]
[ "# coding: UTF-8\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport argparse\nimport numpy as np\nimport shutil\nimport PIL\nimport time\nfrom imageio import imread, imsave\nfrom googletrans import Translator\n\nimport torch\nimport torchvision\nimport torch.nn.functional as F\nfrom torchvision import transforms as T\n\nimport clip\nos.environ['KMP_DUPLICATE_LIB_OK']='True'\n\nfrom clip_fft import to_valid_rgb, fft_image, resume_fft, pixel_image\nfrom utils import slice_imgs, derivat, sim_func, slerp, basename, file_list, img_list, img_read, pad_up_to, txt_clean, latent_anima, cvshow, checkout, save_cfg, old_torch\nimport transforms\ntry: # progress bar for notebooks \n get_ipython().__class__.__name__\n from progress_bar import ProgressIPy as ProgressBar\nexcept: # normal console\n from progress_bar import ProgressBar\n\nclip_models = ['ViT-B/16', 'ViT-B/32', 'RN50', 'RN50x4', 'RN50x16', 'RN101']\n\ndef get_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-s', '--size', default='1280-720', help='Output resolution')\n parser.add_argument('-t', '--in_txt', default=None, help='Text string or file to process (main topic)')\n parser.add_argument('-pre', '--in_txt_pre', default=None, help='Prefix for input text')\n parser.add_argument('-post', '--in_txt_post', default=None, help='Postfix for input text')\n parser.add_argument('-t2', '--in_txt2', default=None, help='Text string or file to process (style)')\n parser.add_argument('-t0', '--in_txt0', default=None, help='input text to subtract')\n parser.add_argument('-im', '--in_img', default=None, help='input image or directory with images')\n parser.add_argument('-w0', '--weight0', default=0.3, type=float, help='weight for subtraction')\n parser.add_argument('-w2', '--weight2', default=0.5, type=float, help='weight for style')\n parser.add_argument('-wi', '--weight_img', default=0.5, type=float, help='weight for images')\n parser.add_argument('-r', '--resume', default=None, help='Resume from saved params or from an image')\n parser.add_argument( '--out_dir', default='_out')\n parser.add_argument('-tr', '--translate', action='store_true', help='Translate with Google Translate')\n parser.add_argument( '--invert', action='store_true', help='Invert criteria')\n parser.add_argument('-v', '--verbose', default=True, type=bool)\n # training\n parser.add_argument( '--gen', default='RGB', help='Generation (optimization) method: FFT or RGB')\n parser.add_argument('-m', '--model', default='ViT-B/32', choices=clip_models, help='Select CLIP model to use')\n parser.add_argument( '--steps', default=300, type=int, help='Iterations (frames) per scene (text line)')\n parser.add_argument( '--samples', default=100, type=int, help='Samples to evaluate per frame')\n parser.add_argument('-lr', '--lrate', default=1, type=float, help='Learning rate')\n # motion\n parser.add_argument('-opt', '--opt_step', default=1, type=int, help='How many optimizing steps per save/transform step')\n parser.add_argument('-sm', '--smooth', action='store_true', help='Smoothen interframe jittering for FFT method')\n parser.add_argument('-it', '--interpol', default=True, help='Interpolate topics? (or change by cut)')\n parser.add_argument( '--fstep', default=100, type=int, help='How many frames before changing motion')\n parser.add_argument( '--scale', default=0.012, type=float)\n parser.add_argument( '--shift', default=10., type=float, help='in pixels')\n parser.add_argument( '--angle', default=0.8, type=float, help='in degrees')\n parser.add_argument( '--shear', default=0.4, type=float)\n parser.add_argument( '--anima', default=True, help='Animate motion')\n # tweaks\n parser.add_argument('-a', '--align', default='overscan', choices=['central', 'uniform', 'overscan', 'overmax'], help='Sampling distribution')\n parser.add_argument('-tf', '--transform', default='custom', choices=['none', 'custom', 'elastic'], help='use augmenting transforms?')\n parser.add_argument( '--contrast', default=1.2, type=float)\n parser.add_argument( '--colors', default=2, type=float)\n parser.add_argument('-sh', '--sharp', default=None, type=float)\n parser.add_argument('-mc', '--macro', default=0.4, type=float, help='Endorse macro forms 0..1 ')\n parser.add_argument('-e', '--enforce', default=0, type=float, help='Enforce details (by boosting similarity between two parallel samples)')\n parser.add_argument('-x', '--expand', default=0, type=float, help='Boosts diversity (by enforcing difference between prev/next samples)')\n parser.add_argument('-n', '--noise', default=2., type=float, help='Add noise to make composition sparse (FFT only)') # 0.04\n parser.add_argument( '--sim', default='mix', help='Similarity function (angular/spherical/mixed; None = cossim)')\n parser.add_argument( '--rem', default=None, help='Dummy text to add to project name')\n a = parser.parse_args()\n\n if a.size is not None: a.size = [int(s) for s in a.size.split('-')][::-1]\n if len(a.size)==1: a.size = a.size * 2\n a.gen = a.gen.upper()\n a.invert = -1. if a.invert is True else 1.\n \n # Overriding some parameters, depending on other settings\n if a.gen == 'RGB':\n a.smooth = False\n a.align = 'overscan'\n if a.sharp is None: a.sharp = -1. if a.gen == 'RGB' else 1.\n if a.model == 'ViT-B/16': a.sim = 'cossim'\n\n return a\n\ndef frame_transform(img, size, angle, shift, scale, shear):\n if old_torch(): # 1.7.1\n img = T.functional.affine(img, angle, shift, scale, shear, fillcolor=0, resample=PIL.Image.BILINEAR)\n img = T.functional.center_crop(img, size)\n img = pad_up_to(img, size)\n else: # 1.8+\n img = T.functional.affine(img, angle, shift, scale, shear, fill=0, interpolation=T.InterpolationMode.BILINEAR)\n img = T.functional.center_crop(img, size) # on 1.8+ also pads\n return img\n\ndef main():\n a = get_args()\n \n # Load CLIP models\n model_clip, _ = clip.load(a.model, jit=old_torch())\n try:\n a.modsize = model_clip.visual.input_resolution \n except:\n a.modsize = 288 if a.model == 'RN50x4' else 384 if a.model == 'RN50x16' else 224\n if a.verbose is True: print(' using model', a.model)\n xmem = {'ViT-B/16':0.25, 'RN50':0.5, 'RN50x4':0.16, 'RN50x16':0.06, 'RN101':0.33}\n if a.model in xmem.keys():\n a.samples = int(a.samples * xmem[a.model])\n\n if a.translate:\n translator = Translator()\n\n if a.enforce != 0:\n a.samples = int(a.samples * 0.5)\n\n if 'elastic' in a.transform:\n trform_f = transforms.transforms_elastic \n a.samples = int(a.samples * 0.95)\n elif 'custom' in a.transform:\n trform_f = transforms.transforms_custom \n a.samples = int(a.samples * 0.95)\n else:\n trform_f = transforms.normalize()\n\n def enc_text(txt):\n if a.translate:\n txt = translator.translate(txt, dest='en').text\n emb = model_clip.encode_text(clip.tokenize(txt).cuda()[:77])\n return emb.detach().clone()\n\n def enc_image(img_file):\n img_t = torch.from_numpy(img_read(img_file)/255.).unsqueeze(0).permute(0,3,1,2).cuda()[:,:3,:,:]\n in_sliced = slice_imgs([img_t], a.samples, a.modsize, transforms.normalize(), a.align)[0]\n emb = model_clip.encode_image(in_sliced)\n return emb.detach().clone()\n\n # Encode inputs\n count = 0\n texts = []\n styles = []\n images = []\n \n if a.in_txt is not None:\n if os.path.isfile(a.in_txt):\n with open(a.in_txt, 'r', encoding=\"utf-8\") as f:\n texts = f.readlines()\n texts = [tt.strip() for tt in texts if len(tt.strip()) > 0 and tt[0] != '#']\n else:\n texts = [a.in_txt]\n if a.in_txt_pre is not None:\n texts = [' '.join([a.in_txt_pre, tt]).strip() for tt in texts]\n if a.in_txt_post is not None:\n texts = [' '.join([tt, a.in_txt_post]).strip() for tt in texts]\n key_txt_encs = [enc_text(txt) for txt in texts]\n count = max(count, len(key_txt_encs))\n\n if a.in_txt2 is not None:\n if os.path.isfile(a.in_txt2):\n with open(a.in_txt2, 'r', encoding=\"utf-8\") as f:\n styles = f.readlines()\n styles = [tt.strip() for tt in styles if len(tt.strip()) > 0 and tt[0] != '#']\n else:\n styles = [a.in_txt2]\n key_styl_encs = [enc_text(style) for style in styles]\n count = max(count, len(key_styl_encs))\n\n if a.in_img is not None and os.path.exists(a.in_img):\n images = file_list(a.in_img) if os.path.isdir(a.in_img) else [a.in_img]\n key_img_encs = [enc_image(image) for image in images]\n count = max(count, len(key_img_encs))\n \n assert count > 0, \"No inputs found!\"\n \n if a.in_txt0 is not None:\n if a.verbose is True: print(' subtract text:', a.in_txt0)\n if a.translate:\n a.in_txt0 = translator.translate(a.in_txt0, dest='en').text\n # if a.verbose is True: print(' translated to:', a.in_txt0) \n anti_txt_encs = [enc_text(txt) for txt in a.in_txt0.split('.')]\n\n if a.verbose is True: print(' samples:', a.samples)\n\n global params_tmp\n shape = [1, 3, *a.size]\n\n if a.gen == 'RGB':\n params_tmp, _, sz = pixel_image(shape, a.resume)\n params_tmp = params_tmp[0].cuda().detach()\n else:\n params_tmp, sz = resume_fft(a.resume, shape, decay=1.5, sd=1)\n if sz is not None: a.size = sz\n\n # [glob]steps = for save/move, opt_steps = for optimization cycle\n steps = a.steps\n glob_steps = count * steps\n opt_steps = steps * a.opt_step\n if glob_steps == a.fstep: a.fstep = glob_steps // 2 # otherwise no motion\n\n workname = basename(a.in_txt) if a.in_txt is not None else basename(a.in_img)\n workname = txt_clean(workname)\n workdir = os.path.join(a.out_dir, workname)\n if a.rem is not None: workdir += '-%s' % a.rem\n if 'RN' in a.model.upper(): workdir += '-%s' % a.model\n if a.noise > 0: workdir += '-n%.2g' % a.noise\n if a.macro > 0: workdir += '-m%.2g' % a.macro\n if a.smooth is True: workdir += '-sm'\n if a.transform != 'custom': workdir += '-tf%s' % a.transform\n if a.gen == 'RGB': workdir += '-rgb'\n tempdir = os.path.join(workdir, 'ttt')\n os.makedirs(tempdir, exist_ok=True)\n save_cfg(a, workdir)\n if a.in_txt is not None and os.path.isfile(a.in_txt):\n shutil.copy(a.in_txt, os.path.join(workdir, os.path.basename(a.in_txt)))\n if a.in_txt2 is not None and os.path.isfile(a.in_txt2):\n shutil.copy(a.in_txt2, os.path.join(workdir, os.path.basename(a.in_txt2)))\n\n midp = 0.5\n if a.anima:\n if a.gen == 'RGB': # zoom in\n m_scale = latent_anima([1], glob_steps, a.fstep, uniform=True, cubic=True, start_lat=[-0.3], verbose=False)\n m_scale = 1 + (m_scale + 0.3) * a.scale\n else:\n m_scale = latent_anima([1], glob_steps, a.fstep, uniform=True, cubic=True, start_lat=[0.6], verbose=False)\n m_scale = 1 - (m_scale-0.6) * a.scale\n m_shift = latent_anima([2], glob_steps, a.fstep, uniform=True, cubic=True, start_lat=[midp,midp], verbose=False)\n m_angle = latent_anima([1], glob_steps, a.fstep, uniform=True, cubic=True, start_lat=[midp], verbose=False)\n m_shear = latent_anima([1], glob_steps, a.fstep, uniform=True, cubic=True, start_lat=[midp], verbose=False)\n m_shift = (midp-m_shift) * a.shift * abs(m_scale-1) / a.scale\n m_angle = (midp-m_angle) * a.angle * abs(m_scale-1) / a.scale\n m_shear = (midp-m_shear) * a.shear * abs(m_scale-1) / a.scale\n \n def get_encs(encs, num):\n cnt = len(encs)\n if cnt == 0: return []\n enc_1 = encs[min(num, cnt-1)]\n enc_2 = encs[min(num+1, cnt-1)]\n return slerp(enc_1, enc_2, opt_steps)\n\n prev_enc = 0\n def process(num):\n global params_tmp, opt_state, params, image_f, optimizer\n\n if a.interpol is True: # linear topics interpolation\n txt_encs = get_encs(key_txt_encs, num)\n styl_encs = get_encs(key_styl_encs, num)\n img_encs = get_encs(key_img_encs, num)\n else: # change by cut\n txt_encs = [key_txt_encs[min(num, len(key_txt_encs)-1)][0]] * opt_steps if len(key_txt_encs) > 0 else []\n styl_encs = [key_styl_encs[min(num, len(key_styl_encs)-1)][0]] * opt_steps if len(key_styl_encs) > 0 else []\n img_encs = [key_img_encs[min(num, len(key_img_encs)-1)][0]] * opt_steps if len(key_img_encs) > 0 else []\n \n if a.verbose is True: \n if len(texts) > 0: print(' ref text: ', texts[min(num, len(texts)-1)][:80])\n if len(styles) > 0: print(' ref style: ', styles[min(num, len(styles)-1)][:80])\n if len(images) > 0: print(' ref image: ', basename(images[min(num, len(images)-1)])[:80])\n \n pbar = ProgressBar(steps)\n for ii in range(opt_steps):\n glob_step = num * steps + ii // a.opt_step # save/transform\n loss = 0\n \n txt_enc = txt_encs[ii % len(txt_encs)].unsqueeze(0) if len(txt_encs) > 0 else None\n styl_enc = styl_encs[ii % len(styl_encs)].unsqueeze(0) if len(styl_encs) > 0 else None\n img_enc = img_encs[ii % len(img_encs)].unsqueeze(0) if len(img_encs) > 0 else None\n \n # MOTION: transform frame, reload params\n if ii % a.opt_step == 0:\n \n scale = m_scale[glob_step] if a.anima else 1 + a.scale\n shift = tuple(m_shift[glob_step]) if a.anima else [0, a.shift]\n angle = m_angle[glob_step][0] if a.anima else a.angle\n shear = m_shear[glob_step][0] if a.anima else a.shear\n\n if a.gen == 'RGB':\n img_tmp = frame_transform(params_tmp, a.size, angle, shift, scale, shear)\n params, image_f, _ = pixel_image([1, 3, *a.size], resume=img_tmp)\n\n else: # FFT\n if old_torch(): # 1.7.1\n img_tmp = torch.irfft(params_tmp, 2, normalized=True, signal_sizes=a.size)\n img_tmp = frame_transform(img_tmp, a.size, angle, shift, scale, shear)\n params_tmp = torch.rfft(img_tmp, 2, normalized=True)\n else: # 1.8+\n if type(params_tmp) is not torch.complex64:\n params_tmp = torch.view_as_complex(params_tmp)\n img_tmp = torch.fft.irfftn(params_tmp, s=a.size, norm='ortho')\n img_tmp = frame_transform(img_tmp, a.size, angle, shift, scale, shear)\n params_tmp = torch.fft.rfftn(img_tmp, s=a.size, dim=[2,3], norm='ortho')\n params_tmp = torch.view_as_real(params_tmp)\n params, image_f, _ = fft_image([1, 3, *a.size], sd=1, resume=params_tmp)\n\n optimizer = torch.optim.Adam(params, a.lrate)\n # optimizer = torch.optim.AdamW(params, a.lrate, weight_decay=0.01, amsgrad=True)\n image_f = to_valid_rgb(image_f, colors = a.colors)\n del img_tmp\n \n if a.smooth is True and num + ii > 0:\n optimizer.load_state_dict(opt_state)\n\n noise = a.noise * (torch.rand(1, 1, a.size[0], a.size[1]//2+1, 1)-0.5).cuda() if a.noise>0 else 0.\n img_out = image_f(noise)\n \n img_sliced = slice_imgs([img_out], a.samples, a.modsize, trform_f, a.align, a.macro)[0]\n out_enc = model_clip.encode_image(img_sliced)\n\n if a.gen == 'RGB': # empirical hack\n loss += 1.66 * abs(img_out.mean((2,3)) - 0.45).sum() # fix brightness\n loss += 1.66 * abs(img_out.std((2,3)) - 0.17).sum() # fix contrast\n\n if txt_enc is not None:\n loss -= a.invert * sim_func(txt_enc, out_enc, a.sim)\n if styl_enc is not None:\n loss -= a.weight2 * sim_func(styl_enc, out_enc, a.sim)\n if img_enc is not None:\n loss -= a.weight_img * sim_func(img_enc, out_enc, a.sim)\n if a.in_txt0 is not None: # subtract text\n for anti_txt_enc in anti_txt_encs:\n loss += 0.3 * sim_func(anti_txt_enc, out_enc, a.sim)\n if a.sharp != 0: # scharr|sobel|naive\n loss -= a.sharp * derivat(img_out, mode='naive')\n if a.enforce != 0:\n img_sliced = slice_imgs([image_f(noise)], a.samples, a.modsize, trform_f, a.align, a.macro)[0]\n out_enc2 = model_clip.encode_image(img_sliced)\n loss -= a.enforce * sim_func(out_enc, out_enc2, a.sim)\n del out_enc2; torch.cuda.empty_cache()\n if a.expand > 0:\n global prev_enc\n if ii > 0:\n loss += a.expand * sim_func(prev_enc, out_enc, a.sim)\n prev_enc = out_enc.detach().clone()\n del img_out, img_sliced, out_enc; torch.cuda.empty_cache()\n\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n if ii % a.opt_step == a.opt_step-1:\n params_tmp = params[0].detach().clone()\n if a.smooth is True:\n opt_state = optimizer.state_dict()\n\n if ii % a.opt_step == 0:\n with torch.no_grad():\n img_t = image_f(contrast=a.contrast)[0].permute(1,2,0)\n img = torch.clip(img_t*255, 0, 255).cpu().numpy().astype(np.uint8)\n imsave(os.path.join(tempdir, '%06d.jpg' % glob_step), img, quality=95)\n if a.verbose is True: cvshow(img)\n del img, img_t\n pbar.upd()\n\n params_tmp = params[0].detach().clone()\n \n glob_start = time.time()\n try:\n for i in range(count):\n process(i)\n except KeyboardInterrupt:\n pass\n\n os.system('ffmpeg -v warning -y -i %s/\\%%06d.jpg \"%s.mp4\"' % (tempdir, os.path.join(workdir, workname)))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "torch.optim.Adam", "torch.view_as_real", "torch.fft.rfftn", "torch.cuda.empty_cache", "torch.rfft", "torch.view_as_complex", "torch.clip", "torch.no_grad", "torch.rand", "torch.fft.irfftn", "torch.irfft" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cptq/smooth-ot
[ "a165c0c949730ec0490a0670352e04c39762062c" ]
[ "smoothot/tests/test_projection.py" ]
[ "import numpy as np\nfrom sklearn.utils.testing import assert_array_almost_equal\n\nfrom smoothot.projection import projection_simplex\n\n\ndef _projection_simplex(v, z=1):\n \"\"\"\n Old implementation for test and benchmark purposes.\n The arguments v and z should be a vector and a scalar, respectively.\n \"\"\"\n n_features = v.shape[0]\n u = np.sort(v)[::-1]\n cssv = np.cumsum(u) - z\n ind = np.arange(n_features) + 1\n cond = u - cssv / ind > 0\n rho = ind[cond][-1]\n theta = cssv[cond][-1] / float(rho)\n w = np.maximum(v - theta, 0)\n return w\n\n\ndef test_projection_simplex():\n rng = np.random.RandomState(0)\n V = rng.rand(100, 10)\n\n # Axis = None case.\n w = projection_simplex(V[0], z=1, axis=None)\n w2 = _projection_simplex(V[0], z=1)\n assert_array_almost_equal(w, w2)\n\n w = projection_simplex(V, z=1, axis=None)\n w2 = _projection_simplex(V.ravel(), z=1)\n assert_array_almost_equal(w, w2)\n\n # Axis = 1 case.\n W = projection_simplex(V, axis=1)\n\n # Check same as with for loop.\n W2 = np.array([_projection_simplex(V[i]) for i in range(V.shape[0])])\n assert_array_almost_equal(W, W2)\n\n # Check works with vector z.\n W3 = projection_simplex(V, np.ones(V.shape[0]), axis=1)\n assert_array_almost_equal(W, W3)\n\n # Axis = 0 case.\n W = projection_simplex(V, axis=0)\n\n # Check same as with for loop.\n W2 = np.array([_projection_simplex(V[:, i]) for i in range(V.shape[1])]).T\n assert_array_almost_equal(W, W2)\n\n # Check works with vector z.\n W3 = projection_simplex(V, np.ones(V.shape[1]), axis=0)\n assert_array_almost_equal(W, W3)\n" ]
[ [ "sklearn.utils.testing.assert_array_almost_equal", "numpy.maximum", "numpy.arange", "numpy.cumsum", "numpy.sort", "numpy.ones", "numpy.random.RandomState" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Macielyoung/sentence_representation_matching
[ "aa33147eb870a805f69dbc54c2177b11a94cf814", "aa33147eb870a805f69dbc54c2177b11a94cf814" ]
[ "simcse/train_unsup.py", "esimcse/loading.py" ]
[ "# -*- coding: utf-8 -*-\n# @Time : 2021/6/10\n# @Author : kaka\n\n\nimport argparse\nimport logging\nimport os\nfrom config import Params\n\nfrom datasets import load_dataset\nimport torch\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\nfrom transformers import AutoTokenizer\nimport numpy as np\nfrom SimCSE import SimCSE\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n # parser.add_argument(\"train_file\", type=str, help=\"train text file\")\n # parser.add_argument(\"--pretrained\", type=str, default=\"hfl/chinese-bert-wwm-ext\", help=\"huggingface pretrained model\")\n # parser.add_argument(\"--model_out\", type=str, default=\"./finder_model\", help=\"model output path\")\n parser.add_argument(\"--num_proc\", type=int, default=1, help=\"dataset process thread num\")\n parser.add_argument(\"--max_length\", type=int, default=64, help=\"sentence max length\")\n parser.add_argument(\"--batch_size\", type=int, default=32, help=\"batch size\")\n parser.add_argument(\"--epochs\", type=int, default=101, help=\"epochs\")\n parser.add_argument(\"--lr\", type=float, default=1e-5, help=\"learning rate\")\n parser.add_argument(\"--tao\", type=float, default=0.05, help=\"temperature\")\n parser.add_argument(\"--device\", type=str, default=\"cuda\", help=\"device\")\n parser.add_argument(\"--display_interval\", type=int, default=500, help=\"display interval\")\n parser.add_argument(\"--save_interval\", type=int, default=10, help=\"save interval\")\n parser.add_argument(\"--pool_type\", type=str, default=\"pooler\", help=\"pool_type\")\n parser.add_argument(\"--dropout_rate\", type=float, default=0.3, help=\"dropout_rate\")\n args = parser.parse_args()\n return args\n\n\ndef read_data(args):\n with open(Params.dialogues_file, 'r') as f:\n sentences = f.readlines()\n dl = DataLoader(sentences,\n batch_size=args.batch_size)\n return dl\n\n\ndef duplicate_batch(batch, tokenzier, args):\n '''\n 句子进行重复\n '''\n new_batch = []\n for sentence in batch:\n new_batch.append(sentence)\n new_batch.append(sentence)\n batch_encoding = tokenzier(new_batch,\n padding=True,\n truncation=True,\n max_length=args.max_length,\n return_tensors='pt')\n return batch_encoding\n\n\ndef compute_loss(y_pred, tao=0.05, device=\"cuda\"):\n idxs = torch.arange(0, y_pred.shape[0], device=device)\n y_true = idxs + 1 - idxs % 2 * 2\n similarities = F.cosine_similarity(y_pred.unsqueeze(1), y_pred.unsqueeze(0), dim=2)\n similarities = similarities - torch.eye(y_pred.shape[0], device=device) * 1e12\n similarities = similarities / tao\n loss = F.cross_entropy(similarities, y_true)\n return torch.mean(loss)\n\n\ndef train(args):\n tokenizer = AutoTokenizer.from_pretrained(Params.pretrained_model_path)\n dl = read_data(args)\n model = SimCSE(Params.pretrained_model_path, args.pool_type, args.dropout_rate).to(args.device)\n optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr)\n\n model.train()\n batch_idx = 0\n min_loss = 10000000\n for epoch_idx in range(args.epochs):\n epoch_losses = []\n for data in tqdm(dl):\n batch_idx += 1\n new_batch_data = duplicate_batch(data, tokenizer, args)\n pred = model(input_ids=new_batch_data[\"input_ids\"].to(args.device),\n attention_mask=new_batch_data[\"attention_mask\"].to(args.device),\n token_type_ids=new_batch_data[\"token_type_ids\"].to(args.device))\n loss = compute_loss(pred, args.tao, args.device)\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n loss = loss.item()\n epoch_losses.append(loss)\n if batch_idx % args.display_interval == 0:\n logging.info(f\"epoch: {epoch_idx}, batch_idx: {batch_idx}, loss: {loss:>10f}\")\n avg_epoch_loss = np.mean(epoch_losses)\n if avg_epoch_loss < min_loss:\n min_loss = avg_epoch_loss\n torch.save({\n 'epoch': epoch_idx,\n 'model_state_dict': model.state_dict(),\n 'loss': avg_epoch_loss\n }, Params.simcse_model_path)\n \n\ndef main():\n args = parse_args()\n train(args)\n\n\nif __name__ == \"__main__\":\n log_fmt = \"%(asctime)s|%(name)s|%(levelname)s|%(message)s\"\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n main()\n", "from transformers import AutoTokenizer\nimport pandas as pd\nimport re\nimport random\n# import paddlehub as hub\n# import synonyms\nfrom config import Params\n\n\nclass DataLoading:\n def __init__(self, question_file, qa_file, pretrained_model):\n self.question_file = question_file\n self.qa_file = qa_file\n self.tokenizer = AutoTokenizer.from_pretrained(pretrained_model)\n # self.lac = hub.Module(name=\"lac\")\n \n \n def load_chat(self):\n question_df = pd.read_csv(self.question_file)\n # print(question_df.shape)\n question_df = question_df.fillna(\"\")\n question_df['length'] = question_df.apply(lambda x: len(x['content']), axis=1)\n question_df['content'] = question_df.apply(lambda x: self.preprocess_sentence(x['content']), axis=1)\n question_df = question_df[(question_df.content != \"\") & (question_df.length < 32)]\n questions = list(question_df.content.unique())\n return questions\n \n \n def read_qa(self):\n qa_df = pd.read_csv(self.qa_file)\n qa_questions = list(qa_df['question'])\n qa_questions = [self.preprocess_sentence(item) for item in qa_questions]\n return qa_questions\n \n \n def load_data(self):\n chat_questions = self.load_chat()\n qa_questions = self.read_qa()\n questions = chat_questions + qa_questions\n return questions\n \n \n def preprocess_sentence(self, sentence):\n text = re.sub(\"\\[(.*?)\\]\", \"\", sentence)\n text = re.sub(\"\\【(.*?)\\】\", \"\", text)\n text = text.replace(\"\\n\", \"\")\n text = re.sub(\"\\/:[a-zA-Z@)(]*\", \"\", text)\n new_text = re.sub(\"[0-9]*\", \"\", text)\n if new_text == \"\":\n return new_text\n return text\n \n \n def repeat_word(self, sentence):\n '''\n @function: 重复句子中的部分token\n \n @input:\n sentence: string,输入语句\n \n @return:\n dup_sentence: string,重复token后生成的句子\n '''\n word_tokens = self.tokenizer.tokenize(sentence)\n \n # dup_len ∈ [0, max(2, int(dup_rate ∗ N))]\n max_len = max(2, int(Params.dup_rate * len(word_tokens)))\n # 防止随机挑选的数值大于token数量\n dup_len = min(random.choice(range(max_len+1)), len(word_tokens))\n \n random_indices = random.sample(range(len(word_tokens)), dup_len)\n # print(max_len, dup_len, random_indices)\n \n dup_word_tokens = []\n for index, word in enumerate(word_tokens):\n dup_word_tokens.append(word)\n if index in random_indices:\n dup_word_tokens.append(word)\n dup_sentence = \"\".join(dup_word_tokens)\n return dup_sentence\n \n \n def lexical_analysis(self, sentence):\n # 句子词性分析\n spec_words = []\n inputs = {\"text\": [sentence]}\n results = self.lac.lexical_analysis(data=inputs)[0]\n words, tags = results['word'], results['tag']\n for word, tag in zip(words, tags):\n if tag in ['v', 'n', 'ad', 'vd', 'vn']:\n spec_words.append(word)\n spec_words = list(set(spec_words))\n return spec_words\n \n \n def get_synonym_wordpair(self, word):\n synonym_pair = []\n sim_words, sim_values = synonyms.nearby(word)\n for sim_word, sim_value in zip(sim_words, sim_values):\n if sim_word != word and sim_value > 0.85:\n synonym_pair = [word, sim_word, sim_value]\n break\n return synonym_pair\n \n \n def get_synonym_sentence(self, sentence):\n # 获取需要找同义词的词语列表(包含动词、名词、副词等)\n spec_words = self.lexical_analysis(sentence)\n spec_wordpairs = [self.get_synonym_wordpair(word) for word in spec_words]\n spec_wordpairs = [pair for pair in spec_wordpairs if pair != []]\n # print(spec_wordpairs)\n \n # 最多替换两个词语,并取相似度最高的前k个词语替换\n replaced_num = min(len(spec_wordpairs), 2)\n spec_wordpairs = sorted(spec_wordpairs, key=lambda x: x[2], reverse=True)\n replaced_pairs = spec_wordpairs[:replaced_num]\n # print(replaced_pairs)\n for pair in replaced_pairs:\n word = pair[0]\n sim_word = pair[1]\n sentence = sentence.replace(word, sim_word)\n return sentence\n \n \n def generate_pos_dataset(self, questions):\n # 使用重复单词的方法生成相似样本对正例\n pos_question_pairs = []\n for qid, question in enumerate(questions):\n pos_question = self.repeat_word(question)\n pos_question_pairs.append([question, pos_question])\n if qid % 10000 == 0:\n print(\"qid: {}, question: {}, pos_question: {}\".format(qid, question, pos_question), flush=True)\n return pos_question_pairs\n \n \n def generate_pos_dataset2(self, questions):\n # 使用同样的句子作为正样本对\n pos_question_pairs = []\n for qid, question in enumerate(questions):\n # pos_question = self.repeat_word(question)\n pos_question = question\n pos_question_pairs.append([question, pos_question])\n if qid % 10000 == 0:\n print(\"qid: {}, question: {}, pos_question: {}\".format(qid, question, pos_question), flush=True)\n return pos_question_pairs\n \n \n def generate_pos_dataset3(self, questions):\n # 使用同义词替换作为正样本对\n pos_question_pairs = []\n for qid, question in enumerate(questions):\n pos_question = self.get_synonym_sentence(question)\n pos_question_pairs.append([question, pos_question])\n if qid % 10000 == 0:\n print(\"qid: {}, question: {}, pos_question: {}\".format(qid, question, pos_question), flush=True)\n return pos_question_pairs\n \n \n def grep_spec_question(self, questions):\n spec_questions = [question for question in questions if re.match(r'''\\?|?|谁|何|哪|啥|什么|几|多少|怎|么|咋|如何|为什么|怎么|吗|呢|难道|岂|究竟|何尝|何必|能''', question) is not None]\n return spec_questions\n \n \n def save_question_pairs(self, pos_question_pairs, pair_path):\n question_pairs = [{'question': pair[0], 'pos_question': pair[1]} for pair in pos_question_pairs]\n question_df = pd.DataFrame(question_pairs)\n question_df.to_csv(pair_path)\n \n \n def save_questions(self, questions, question_path):\n questions = [item+\"\\n\" for item in questions]\n with open(question_path, 'w') as f:\n f.writelines(questions)\n \n \nif __name__ == \"__main__\":\n data_loading = DataLoading(Params.question_file, Params.qa_file, Params.pretrained_model)\n # questions = data_loading.load_data()\n # print(len(questions))\n # print(questions[:10])\n \n # question = \"666你好\"\n # text = data_loading.preprocess_sentence(question)\n # print(text)\n \n questions = data_loading.load_data()\n print(\"question num: {}\".format(len(questions)))\n spec_questions = data_loading.grep_spec_question(questions)\n question_path = \"data/user_questions.txt\"\n data_loading.save_questions(spec_questions, question_path)\n \n # sentence = \"担心交钱以后,没有后续服务了\"\n # sim_sentence = data_loading.get_synonym_sentence(sentence)\n # print(sim_sentence)\n \n # questions = data_loading.load_data()\n # print(\"question num: {}\".format(len(questions)))\n \n # pos_question_pairs = data_loading.generate_pos_dataset3(questions)\n # print(\"question pair num: {}\".format(len(pos_question_pairs)))\n \n # data_loading.save_question_pairs(pos_question_pairs, Params.pair_file)\n # print(\"save pos pair file done\")" ]
[ [ "torch.mean", "torch.nn.functional.cross_entropy", "torch.utils.data.DataLoader", "torch.eye", "numpy.mean", "torch.arange" ], [ "pandas.read_csv", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.3", "1.1", "1.5", "1.2" ], "scipy": [], "tensorflow": [] } ]
ph7klw76/Data_science_project
[ "5b99c49d44e6858269c4220135ea4c2e0f0bcdef" ]
[ "Economic Growth & GDP per capita.py" ]
[ "import pandas as pd\ndata=pd.read_csv(\"C:/Users/user/Documents/API_NY.GDP.PCAP.CD_DS2_en_csv_v2_1068945.csv\") #your raw data obtained from world bank\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfulldataonly=data.dropna()\nlistofcountry=fulldataonly['Country Name']\nlistofcountry=list(listofcountry) \n\n\ndef findcountryrow(country):\n for i in range(len(data['Country Name'])):\n if data['Country Name'][i]==country:\n return i\n else:\n print(\"error, country not found\") # find which row is the country\n\nlistyear=list(range(1960,2018))\nx=[]\ny=[]\nmydata=[]\n\n#for country in range(len(listofcountry)):\n# for year in listyear:\n# y0=data.loc[findcountryrow(listofcountry[country]),str(year)]\n# y1=data.loc[findcountryrow(listofcountry[country]),str(year+1)]\n# delta=(y1-y0)/y0\n# x.append(y0)\n# y.append(delta)\n# mydata.append([y0,delta])\n\n\nfulllistofcountry=data['Country Name']\nfulllistofcountry=list(fulllistofcountry) \n\nfor country in range(len(fulllistofcountry)):\n for year in listyear: \n if (pd.notnull(data.loc[country,str(year)]))&(pd.notnull(data.loc[country,str(year+1)])):\n y0=data.loc[country,str(year)]\n y1=data.loc[country,str(year+1)]\n delta=((y1-y0)/y0)*100\n x.append(y0)\n y.append(delta)\n mydata.append([y0,delta])\n \nmydata.sort(key=lambda x: x[0])\ncount=0\nGDP, myGDP=[],[]\nGrowth, myGrowth=[],[]\nmysd=[]\nnaverage=500\naveragedatax,averagedatay=[],[]\nimport statistics as s\nfor i in range(len(mydata)):\n if count<naverage:\n GDP.append(mydata[i][0])\n Growth.append(mydata[i][1])\n count+=1\n if count==naverage:\n myGDP=s.mean(GDP)\n myGrowth=s.mean(Growth)\n mysd.append(s.stdev(Growth))\n averagedatax.append(myGDP)\n averagedatay.append(myGrowth)\n count=0\n GDP=[]\n Growth=[]\n if i==len(mydata)-1:\n myGDP=s.mean(GDP)\n myGrowth=s.mean(Growth)\n mysd.append(s.stdev(Growth))\n averagedatax.append(myGDP)\n averagedatay.append(myGrowth)\n \n \nplt.xscale('log')\nplt.xlim(100,200000)\nplt.xlabel(' GDP per capita in US dollar',size=15) \nplt.ylabel('GDP growth rate %',size=15) \nplt.title('Dependence of Economic Growth Rate with GDP per capita',size=15) \nplt.scatter(averagedatax,averagedatay)\n\n\n# histogram=mydata[0:1800]\n# per=[]\n# for gdp, percentage in histogram:\n# per.append(percentage)\n# plt.xlim(-50,60)\n# plt.xlabel('GDP per capita Growth %',size=15)\n# plt.ylabel('Density Function',size=15)\n# plt.title('Economic Growth for different countries for 1960-2018', size=15)\n# plt.hist(x=per, bins='auto', density=True)\n" ]
[ [ "pandas.read_csv", "matplotlib.pyplot.title", "matplotlib.pyplot.scatter", "matplotlib.pyplot.xlim", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xscale", "matplotlib.pyplot.ylabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
HzcIrving/DLRL_PlayGround
[ "0db9a4bdb87130d1d26aea1591ef74cbe6aaa43b" ]
[ "VIT/Train.py" ]
[ "#! /usr/bin/enc python\n# -*- coding: utf-8 -*-\n# author: Irving He \n# email: [email protected]\n\nimport logging\nimport argparse\nimport os\nimport random\nimport numpy as np\nfrom tqdm import tqdm\n\nimport datetime\nfrom datetime import timedelta\n\nimport torch\nimport torch.distributed as dist\n\nfrom Data_utils import get_loader\nfrom Data_utils import CONFIGS\nfrom Model import VITransModel\nfrom Utils import WarmupCosineSchedule,WarmupLinearSchedule\nfrom Utils import set_seed, AverageMeter, simple_accuracy, model_save\n\nfrom tensorboardX import SummaryWriter\n\ndef count_parameters(model):\n params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n return params/1000000\n\n\"\"\"Config\"\"\"\nclass VITConfig:\n log_dir = \"./TB_log/\"\n dataset = \"cifar10\" # \"cifar100\"\n model_type = \"ViT-B_16\"\n pretrained_dir = \"./Pretrained/imagenet21k_ViT-B_16.npz\" # 预训练模型存放位置\n save_dir = \"./Model/\"\n record_algo = \"Pretrained_VIT_Cifar10_ViTB16_\"\n test_cycles = datetime.datetime.now().strftime('%Y%m%d_%H%M')\n decay_type = \"cosine\" # \"cosine\", \"linear\" 决定了学习率Scheduler类型\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n TB_log = True\n\n img_size = 224\n train_batch_size = 64 #512\n eval_batch_size = 32 #64\n eval_every = 100 # Run prediction on validation set every so many steps.\n learning_rate = 3e-2 # SGD起始学习率\n weight_decay = 0 #\n num_steps = 10000 # Total number of training epochs to perform.\n warmup_steps = 500 # 开始的Warmup Step数\n max_grad_norm = 1.0\n\n local_rank = -1 # local_rank for distributed training on gpus\n seed = 42\n gradient_accumulation_steps = 1 # Number of updates steps to accumulate before performing a backward/update pass.\n\n\n\"\"\"Model Valid Process\"\"\"\ndef valid(args,model,writer,test_loader,global_step):\n \"\"\"\n :param args: 参数Config\n :param model: 需验证模型\n :param writer: TB写入\n :param test_loader: 测试数据集\n :param global_step: 全局step\n :return:\n \"\"\"\n # Validation\n eval_losses = AverageMeter()\n\n model.eval()\n all_preds, all_label = [],[]\n epoch_iterator = tqdm(test_loader,\n desc=\"Validating... (loss=X.X)\",\n bar_format=\"{l_bar}{r_bar}\",\n dynamic_ncols=True)\n loss_fct = torch.nn.CrossEntropyLoss()\n global_eval_step = 0\n for step, batch in enumerate(epoch_iterator):\n global_eval_step += 1\n batch = tuple(t.to(args.device) for t in batch)\n x,y = batch\n with torch.no_grad():\n logits = model(x)[0]\n eval_loss = loss_fct(logits,y)\n eval_losses.update(eval_loss.item()) #滑动平均\n preds = torch.argmax(logits,dim=-1)\n\n if len(all_preds) == 0:\n all_preds.append(preds.detach().cpu().numpy())\n all_label.append(y.detach().cpu().numpy())\n else:\n # append在后面\n all_preds[0] = np.append(all_preds[0], preds.detach().cpu().numpy(), axis=0)\n all_label[0] = np.append(all_label[0], y.detach().cpu().numpy(), axis=0)\n\n epoch_iterator.set_description(\"Validating... (loss=%2.5f)\" % eval_losses.val)\n writer.add_scalar(\"Train/loss\", scalar_value=eval_losses.val, global_step=global_eval_step)\n\n all_preds, all_label = all_preds[0], all_label[0]\n # all_preds: numpy.array; all_label: numpy.array;\n accuracy = simple_accuracy(all_preds,all_label)\n\n writer.add_scalar(\"test/accuracy\",scalar_value=accuracy,global_step=global_step)\n\n return accuracy\n\n\"\"\"Model Training Process\"\"\"\ndef train(args=VITConfig()):\n \"\"\"\n :param args:\n - log_dir\n \"\"\"\n # 模型准备\n pretrained_model_config = CONFIGS[args.model_type]\n num_classes = 10 if args.dataset == \"cifar10\" else 100\n\n model = VITransModel(pretrained_model_config, args.img_size, zero_head=True, num_classes=num_classes)\n model.load_from(np.load(args.pretrained_dir))\n model.to(device=args.device)\n num_params = count_parameters(model)\n\n if args.TB_log:\n os.makedirs(args.log_dir, exist_ok=True)\n writer = SummaryWriter(logdir=args.log_dir + args.record_algo + args.test_cycles)\n\n args.train_batch_size = args.train_batch_size // args.gradient_accumulation_steps\n\n # 1. DATA准备\n train_loader, test_loader = get_loader(args)\n\n # 2. 准备优化器以及Scheduler\n optimizer = torch.optim.SGD(model.parameters(),\n lr = args.learning_rate, # init lr\n momentum=0.9,\n weight_decay=args.weight_decay)\n\n t_total = args.num_steps # Total time steps\n if args.decay_type == \"cosine\":\n scheduler = WarmupCosineSchedule(optimizer, warmup_steps=args.warmup_steps, t_total=t_total)\n else:\n scheduler = WarmupLinearSchedule(optimizer, warmup_steps=args.warmup_steps, t_total=t_total)\n\n # 3. Training\n model.zero_grad()\n set_seed(args.seed)\n losses = AverageMeter()\n global_step = 0\n best_acc = 0\n while True:\n model.train()\n\n # 一个数据迭代器\n epoch_iterator = tqdm(train_loader,\n desc=\"Training (X / X Steps) (loss=X.X)\",\n bar_format=\"{l_bar}{r_bar}\",\n dynamic_ncols=True)\n\n for step, batch in enumerate(epoch_iterator):\n batch = tuple(t.to(args.device) for t in batch)\n x,y = batch # XData, YLabel\n loss = model.forward(x,y)\n loss.backward()\n\n if (step+1)%args.gradient_accumulation_steps == 0:\n losses.update(loss.item()*args.gradient_accumulation_steps)\n torch.nn.utils.clip_grad_norm(model.parameters(),1.0)\n scheduler.step()\n optimizer.step()\n optimizer.zero_grad()\n global_step += 1\n\n # Print Training Info\n epoch_iterator.set_description(\n \"Training (%d / %d Steps) (loss=%2.5f)\" % (global_step, t_total, losses.val)\n )\n\n writer.add_scalar(\"Train/loss\",scalar_value=losses.val, global_step=global_step)\n writer.add_scalar(\"Train/lr\", scalar_value=scheduler.get_lr()[0], global_step=global_step)\n\n # Valid ...\n if global_step % args.eval_every == 0:\n accuracy = valid(args, model, writer, test_loader, global_step)\n if best_acc < accuracy:\n best_acc = accuracy\n model_save(args.record_algo+args.test_cycles,model)\n model.train()\n\n if global_step % t_total == 0:\n break\n\n losses.reset()\n if global_step % t_total == 0:\n break\n\n writer.close()\n print(\"===\"*30)\n print(\"Best Accuracy: \\t%f\" % best_acc)\n print(\"End Training!\")\n print(\"===\"*30)\n\n\nif __name__ == \"__main__\":\n train()\n # all_preds = []\n # all_labels = []\n #\n # all_pred = torch.tensor([1,0,1,1,0,1])\n # all_label = torch.tensor([1,1,1,1,1,1])\n #\n # all_preds.append(all_pred)\n # all_labels.append(all_label)\n # print(all_preds)\n # all_preds[0] = np.append(all_preds[0],all_label,axis=0)\n # all_labels[0] = np.append(all_labels[0],all_pred,axis=0)\n # print(type(all_preds[0]))\n # print(type(all_labels[0]))\n # acc = simple_accuracy(all_preds[0],all_labels[0])\n # print(acc)" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.no_grad", "torch.cuda.is_available", "numpy.load", "torch.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ElnuraMusaoglu/KernelizedCorrelationFilter
[ "282a6312be23f6c4bce3b38c19045a1d1a3bce3b" ]
[ "hog_cpp/fhog/get_hog.py" ]
[ "from hog_cpp.fhog import fhog\nimport numpy as np\n\n'''\nhttps://github.com/lawpdas/fhog-python\n'''\n\ndef get_hog(img):\n M = np.zeros(img.shape[:2], dtype='float32')\n O = np.zeros(img.shape[:2], dtype='float32')\n H = np.zeros([img.shape[0] // 4, img.shape[1] // 4, 32], dtype='float32') # python3\n fhog.gradientMag(img.astype(np.float32), M, O)\n fhog.gradientHist(M, O, H)\n H = H[:, :, :31]\n\n return H\n\n\n\n'''\nif __name__ == \"__main__\":\n img_path = 'D:/DATASET/OTB100/Basketball/img/0001.jpg'\n img = cv2.imread(img_path)\n\n sub = img[0:40, 0:40]\n\n H = get_hog(sub)\n print(H)\n'''" ]
[ [ "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
rajputakhil/ludwig
[ "dd1a37ea1018db6624f05d72c34ae8b0f7068e6c", "dd1a37ea1018db6624f05d72c34ae8b0f7068e6c", "dd1a37ea1018db6624f05d72c34ae8b0f7068e6c", "dd1a37ea1018db6624f05d72c34ae8b0f7068e6c" ]
[ "ludwig/models/modules/recurrent_modules.py", "ludwig/utils/visualization_utils.py", "ludwig/utils/misc.py", "ludwig/models/modules/reduction_modules.py" ]
[ "# coding=utf-8\r\n# Copyright (c) 2019 Uber Technologies, Inc.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the 'License');\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\nimport collections\r\nimport logging\r\n\r\nimport tensorflow as tf\r\nfrom tensorflow.contrib.rnn import MultiRNNCell, LSTMStateTuple\r\nfrom tensorflow.python.framework import dtypes, tensor_shape\r\nfrom tensorflow.python.framework import ops\r\nfrom tensorflow.python.util import nest\r\n\r\nfrom ludwig.models.modules.fully_connected_modules import fc_layer\r\nfrom ludwig.models.modules.initializer_modules import get_initializer\r\nfrom ludwig.models.modules.reduction_modules import reduce_sequence\r\nfrom ludwig.utils.tf_utils import sequence_length_3D, sequence_length_2D\r\n\r\n\r\ndef get_cell_fun(cell_type):\r\n if cell_type == 'rnn':\r\n cell_fn = tf.nn.rnn_cell.BasicRNNCell\r\n elif cell_type == 'lstm':\r\n # allows for optional peephole connections and cell clipping\r\n cell_fn = tf.nn.rnn_cell.LSTMCell\r\n elif cell_type == 'lstm_block':\r\n # Faster version of basic LSTM\r\n cell_fn = tf.contrib.rnn.LSTMBlockCell\r\n elif cell_type == 'lstm_ln':\r\n cell_fn = tf.contrib.rnn.LayerNormBasicLSTMCell\r\n elif cell_type == 'lstm_cudnn':\r\n cell_fn = tf.contrib.cudnn_rnn.CudnnCompatibleLSTMCell\r\n elif cell_type == 'gru':\r\n cell_fn = tf.nn.rnn_cell.GRUCell\r\n elif cell_type == 'gru_block':\r\n # Faster version of GRU (25% faster in my tests)\r\n cell_fn = tf.contrib.rnn.GRUBlockCell\r\n elif cell_type == 'gru_cudnn':\r\n # Faster version of GRU (25% faster in my tests)\r\n cell_fn = tf.contrib.cudnn_rnn.CudnnCompatibleGRUCell\r\n else:\r\n cell_fn = tf.nn.rnn_cell.BasicRNNCell\r\n return cell_fn\r\n\r\n\r\nclass Projection(tf.layers.Layer):\r\n def __init__(self, projection_weights, projection_biases, name=None,\r\n **kwargs):\r\n super(Projection, self).__init__(name=name, **kwargs)\r\n self.projection_weights = projection_weights\r\n self.projection_biases = projection_biases\r\n\r\n def call(self, inputs, **kwargs):\r\n inputs_shape = inputs.shape.as_list()\r\n weights_shape = self.projection_weights.shape.as_list()\r\n assert inputs_shape[-1] == weights_shape[0]\r\n inputs = tf.reshape(inputs, [-1, inputs_shape[-1]])\r\n\r\n outputs = tf.matmul(inputs, self.projection_weights)\r\n if self.projection_biases is not None:\r\n outputs = tf.nn.bias_add(outputs, self.projection_biases)\r\n\r\n outputs_shape = inputs_shape\r\n outputs_shape[0] = -1 # batch_size\r\n outputs_shape[-1] = weights_shape[1]\r\n outputs = tf.reshape(outputs, outputs_shape)\r\n return outputs\r\n\r\n def compute_output_shape(self, input_shape):\r\n input_shape = tensor_shape.TensorShape(input_shape).as_list()\r\n output_shape = input_shape\r\n output_shape[-1] = self.projection_biases.shape.as_list()[0]\r\n # output_shape = [input_shape[0], self.projection_biases.shape.as_list()[0]]\r\n return tensor_shape.TensorShape(output_shape)\r\n\r\n\r\nclass BasicDecoderOutput(\r\n collections.namedtuple('BasicDecoderOutput',\r\n ('rnn_output', 'sample_id', 'projection_input'))):\r\n pass\r\n\r\n\r\nclass BasicDecoder(tf.contrib.seq2seq.BasicDecoder):\r\n def _projection_input_size(self):\r\n return self._cell.output_size\r\n\r\n @property\r\n def output_size(self):\r\n return BasicDecoderOutput(\r\n rnn_output=self._rnn_output_size(),\r\n sample_id=self._helper.sample_ids_shape,\r\n projection_input=self._projection_input_size())\r\n\r\n @property\r\n def output_dtype(self):\r\n dtype = nest.flatten(self._initial_state)[0].dtype\r\n return BasicDecoderOutput(\r\n nest.map_structure(lambda _: dtype, self._rnn_output_size()),\r\n self._helper.sample_ids_dtype,\r\n nest.map_structure(lambda _: dtype, self._projection_input_size()))\r\n\r\n def step(self, time, inputs, state, name=None):\r\n with ops.name_scope(name, 'BasicDecoderStep', (time, inputs, state)):\r\n cell_outputs, cell_state = self._cell(inputs, state)\r\n projection_inputs = cell_outputs # get projection_inputs to compute sampled_softmax_cross_entropy_loss\r\n if self._output_layer is not None:\r\n cell_outputs = self._output_layer(cell_outputs)\r\n sample_ids = self._helper.sample(\r\n time=time, outputs=cell_outputs, state=cell_state)\r\n (finished, next_inputs, next_state) = self._helper.next_inputs(\r\n time=time,\r\n outputs=cell_outputs,\r\n state=cell_state,\r\n sample_ids=sample_ids)\r\n outputs = BasicDecoderOutput(cell_outputs, sample_ids,\r\n projection_inputs)\r\n return (outputs, next_state, next_inputs, finished)\r\n\r\n\r\nclass TimeseriesTrainingHelper(tf.contrib.seq2seq.TrainingHelper):\r\n def sample(self, time, outputs, name=None, **unused_kwargs):\r\n with ops.name_scope(name, 'TrainingHelperSample', [time, outputs]):\r\n return tf.zeros(tf.shape(outputs)[:-1], dtype=dtypes.int32)\r\n\r\n\r\nclass RecurrentStack:\r\n def __init__(\r\n self,\r\n state_size=256,\r\n cell_type='rnn',\r\n num_layers=1,\r\n bidirectional=False,\r\n dropout=False,\r\n regularize=True,\r\n reduce_output='last',\r\n **kwargs\r\n ):\r\n self.state_size = state_size\r\n self.cell_type = cell_type\r\n self.num_layers = num_layers\r\n self.bidirectional = bidirectional\r\n self.dropout = dropout\r\n self.regularize = regularize\r\n self.reduce_output = reduce_output\r\n\r\n def __call__(\r\n self,\r\n input_sequence,\r\n regularizer,\r\n dropout_rate,\r\n is_training=True\r\n ):\r\n if not self.regularize:\r\n regularizer = None\r\n\r\n # Calculate the length of input_sequence and the batch size\r\n sequence_length = sequence_length_3D(input_sequence)\r\n\r\n # RNN cell\r\n cell_fn = get_cell_fun(self.cell_type)\r\n\r\n # initial state\r\n # init_state = tf.get_variable(\r\n # 'init_state',\r\n # [1, state_size],\r\n # initializer=tf.constant_initializer(0.0),\r\n # )\r\n # init_state = tf.tile(init_state, [batch_size, 1])\r\n\r\n # main RNN operation\r\n with tf.variable_scope('rnn_stack', reuse=tf.AUTO_REUSE,\r\n regularizer=regularizer) as vs:\r\n if self.bidirectional:\r\n # forward direction cell\r\n fw_cell = lambda state_size: cell_fn(state_size)\r\n bw_cell = lambda state_size: cell_fn(state_size)\r\n fw_cells = [fw_cell(self.state_size) for _ in\r\n range(self.num_layers)]\r\n bw_cells = [bw_cell(self.state_size) for _ in\r\n range(self.num_layers)]\r\n rnn_outputs, final_state_fw, final_state_bw = tf.contrib.rnn.stack_bidirectional_dynamic_rnn(\r\n cells_fw=fw_cells,\r\n cells_bw=bw_cells,\r\n dtype=tf.float32,\r\n sequence_length=sequence_length,\r\n inputs=input_sequence\r\n )\r\n\r\n else:\r\n cell = lambda state_size: cell_fn(state_size)\r\n cells = MultiRNNCell(\r\n [cell(self.state_size) for _ in range(self.num_layers)],\r\n state_is_tuple=True)\r\n rnn_outputs, final_state = tf.nn.dynamic_rnn(\r\n cells,\r\n input_sequence,\r\n sequence_length=sequence_length,\r\n dtype=tf.float32)\r\n # initial_state=init_state)\r\n\r\n for v in tf.global_variables():\r\n if v.name.startswith(vs.name):\r\n logging.debug(' {}: {}'.format(v.name, v))\r\n logging.debug(' rnn_outputs: {0}'.format(rnn_outputs))\r\n\r\n rnn_output = reduce_sequence(rnn_outputs, self.reduce_output)\r\n logging.debug(' reduced_rnn_output: {0}'.format(rnn_output))\r\n\r\n # dropout\r\n if self.dropout and dropout_rate is not None:\r\n rnn_output = tf.layers.dropout(\r\n rnn_output,\r\n rate=dropout_rate,\r\n training=is_training\r\n )\r\n logging.debug(' dropout_rnn: {0}'.format(rnn_output))\r\n\r\n return rnn_output, rnn_output.shape.as_list()[-1]\r\n\r\n\r\ndef recurrent_decoder(encoder_outputs, targets, max_sequence_length, vocab_size,\r\n cell_type='rnn', state_size=256, embedding_size=50,\r\n num_layers=1,\r\n attention_mechanism=None, beam_width=1, projection=True,\r\n tied_target_embeddings=True, embeddings=None,\r\n initializer=None, regularizer=None,\r\n is_timeseries=False):\r\n with tf.variable_scope('rnn_decoder', reuse=tf.AUTO_REUSE,\r\n regularizer=regularizer):\r\n\r\n # ================ Setup ================\r\n if beam_width > 1 and is_timeseries:\r\n raise ValueError('Invalid beam_width: {}'.format(beam_width))\r\n\r\n GO_SYMBOL = vocab_size\r\n END_SYMBOL = 0\r\n batch_size = tf.shape(encoder_outputs)[0]\r\n\r\n # ================ Projection ================\r\n # Project the encoder outputs to the size of the decoder state\r\n encoder_outputs_size = encoder_outputs.shape[-1]\r\n if projection and encoder_outputs_size != state_size:\r\n with tf.variable_scope('projection'):\r\n encoder_output_rank = len(encoder_outputs.shape)\r\n if encoder_output_rank > 2:\r\n sequence_length = tf.shape(encoder_outputs)[1]\r\n encoder_outputs = tf.reshape(encoder_outputs,\r\n [-1, encoder_outputs_size])\r\n encoder_outputs = fc_layer(encoder_outputs,\r\n encoder_outputs.shape[-1],\r\n state_size,\r\n activation=None,\r\n initializer=initializer)\r\n encoder_outputs = tf.reshape(encoder_outputs,\r\n [-1, sequence_length,\r\n state_size])\r\n else:\r\n encoder_outputs = fc_layer(encoder_outputs,\r\n encoder_outputs.shape[-1],\r\n state_size,\r\n activation=None,\r\n initializer=initializer)\r\n\r\n # ================ Targets sequence ================\r\n # Calculate the length of inputs and the batch size\r\n with tf.variable_scope('sequence'):\r\n targets_sequence_length = sequence_length_2D(targets)\r\n start_tokens = tf.tile([GO_SYMBOL], [batch_size])\r\n end_tokens = tf.tile([END_SYMBOL], [batch_size])\r\n if is_timeseries:\r\n start_tokens = tf.cast(start_tokens, tf.float32)\r\n end_tokens = tf.cast(end_tokens, tf.float32)\r\n targets_with_go = tf.concat([\r\n tf.expand_dims(start_tokens, 1),\r\n targets,\r\n tf.expand_dims(end_tokens, 1)], 1)\r\n logging.debug(' targets_with_go: {0}'.format(targets_with_go))\r\n targets_sequence_length_with_eos = targets_sequence_length + 1 # the EOS symbol is 0 so it's not increasing the real length of the sequence\r\n\r\n # ================ Embeddings ================\r\n if is_timeseries:\r\n targets_embedded = tf.expand_dims(targets_with_go, -1)\r\n targets_embeddings = None\r\n else:\r\n with tf.variable_scope('embedding'):\r\n if embeddings is not None:\r\n embedding_size = embeddings.shape.as_list()[-1]\r\n if tied_target_embeddings:\r\n state_size = embedding_size\r\n elif tied_target_embeddings:\r\n embedding_size = state_size\r\n\r\n if embeddings is not None:\r\n embedding_go = tf.get_variable('embedding_GO',\r\n initializer=tf.random_uniform(\r\n [1, embedding_size],\r\n -1.0, 1.0))\r\n targets_embeddings = tf.concat([embeddings, embedding_go],\r\n axis=0)\r\n else:\r\n initializer_obj = get_initializer(initializer)\r\n targets_embeddings = tf.get_variable(\r\n 'embeddings',\r\n initializer=initializer_obj(\r\n [vocab_size + 1, embedding_size]),\r\n regularizer=regularizer\r\n )\r\n logging.debug(\r\n ' targets_embeddings: {0}'.format(targets_embeddings))\r\n\r\n targets_embedded = tf.nn.embedding_lookup(targets_embeddings,\r\n targets_with_go,\r\n name='decoder_input_embeddings')\r\n logging.debug(' targets_embedded: {0}'.format(targets_embedded))\r\n\r\n # ================ Class prediction ================\r\n if tied_target_embeddings:\r\n class_weights = tf.transpose(targets_embeddings)\r\n else:\r\n initializer_obj = get_initializer(initializer)\r\n class_weights = tf.get_variable(\r\n 'class_weights',\r\n initializer=initializer_obj([state_size, vocab_size + 1]),\r\n regularizer=regularizer\r\n )\r\n logging.debug(' class_weights: {0}'.format(class_weights))\r\n class_biases = tf.get_variable('class_biases', [vocab_size + 1])\r\n logging.debug(' class_biases: {0}'.format(class_biases))\r\n projection_layer = Projection(class_weights, class_biases)\r\n\r\n # ================ RNN ================\r\n initial_state = encoder_outputs\r\n with tf.variable_scope('rnn_cells') as vs:\r\n # Cell\r\n cell_fun = get_cell_fun(cell_type)\r\n\r\n if num_layers == 1:\r\n cell = cell_fun(state_size)\r\n if cell_type.startswith('lstm'):\r\n initial_state = LSTMStateTuple(c=initial_state,\r\n h=initial_state)\r\n elif num_layers > 1:\r\n cell = MultiRNNCell(\r\n [cell_fun(state_size) for _ in range(num_layers)],\r\n state_is_tuple=True)\r\n if cell_type.startswith('lstm'):\r\n initial_state = LSTMStateTuple(c=initial_state,\r\n h=initial_state)\r\n initial_state = tuple([initial_state] * num_layers)\r\n else:\r\n raise ValueError('num_layers in recurrent decoser: {}. '\r\n 'Number of layers in a recurrenct decoder cannot be <= 0'.format(\r\n num_layers))\r\n\r\n # Attention\r\n if attention_mechanism is not None:\r\n if attention_mechanism == 'bahdanau':\r\n attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(\r\n num_units=state_size, memory=encoder_outputs,\r\n memory_sequence_length=sequence_length_3D(\r\n encoder_outputs))\r\n elif attention_mechanism == 'luong':\r\n attention_mechanism = tf.contrib.seq2seq.LuongAttention(\r\n num_units=state_size, memory=encoder_outputs,\r\n memory_sequence_length=sequence_length_3D(\r\n encoder_outputs))\r\n else:\r\n raise ValueError(\r\n 'Attention mechanism {} not supported'.format(\r\n attention_mechanism))\r\n cell = tf.contrib.seq2seq.AttentionWrapper(\r\n cell, attention_mechanism, attention_layer_size=state_size)\r\n initial_state = cell.zero_state(dtype=tf.float32,\r\n batch_size=batch_size)\r\n\r\n for v in tf.global_variables():\r\n if v.name.startswith(vs.name):\r\n logging.debug(' {}: {}'.format(v.name, v))\r\n\r\n # ================ Decoding ================\r\n def decode(initial_state, cell, helper, beam_width=1,\r\n projection_layer=None):\r\n # The decoder itself\r\n if beam_width > 1:\r\n # Tile inputs for beam search decoder\r\n beam_initial_state = tf.contrib.seq2seq.tile_batch(\r\n initial_state, beam_width)\r\n decoder = tf.contrib.seq2seq.BeamSearchDecoder(\r\n cell=cell,\r\n embedding=targets_embeddings,\r\n start_tokens=start_tokens,\r\n end_token=END_SYMBOL,\r\n initial_state=beam_initial_state,\r\n beam_width=beam_width,\r\n output_layer=projection_layer)\r\n else:\r\n decoder = BasicDecoder(\r\n cell=cell, helper=helper,\r\n initial_state=initial_state,\r\n output_layer=projection_layer)\r\n\r\n # The decoding operation\r\n outputs = tf.contrib.seq2seq.dynamic_decode(\r\n decoder=decoder,\r\n output_time_major=False,\r\n impute_finished=False if beam_width > 1 else True,\r\n maximum_iterations=max_sequence_length\r\n )\r\n\r\n return outputs\r\n\r\n # ================ Decoding helpers ================\r\n if is_timeseries:\r\n train_helper = TimeseriesTrainingHelper(\r\n inputs=targets_embedded,\r\n sequence_length=targets_sequence_length_with_eos)\r\n final_outputs_pred, final_state_pred, final_sequence_lengths_pred = decode(\r\n initial_state,\r\n cell,\r\n train_helper,\r\n projection_layer=projection_layer)\r\n eval_logits = final_outputs_pred.rnn_output\r\n train_logits = final_outputs_pred.projection_input\r\n predictions_sequence = tf.reshape(eval_logits, [batch_size, -1])\r\n predictions_sequence_length_with_eos = final_sequence_lengths_pred\r\n\r\n else:\r\n train_helper = tf.contrib.seq2seq.TrainingHelper(\r\n inputs=targets_embedded,\r\n sequence_length=targets_sequence_length_with_eos)\r\n final_outputs_train, final_state_train, final_sequence_lengths_train, = decode(\r\n initial_state,\r\n cell,\r\n train_helper,\r\n projection_layer=projection_layer)\r\n eval_logits = final_outputs_train.rnn_output\r\n train_logits = final_outputs_train.projection_input\r\n # train_predictions = final_outputs_train.sample_id\r\n\r\n pred_helper = tf.contrib.seq2seq.GreedyEmbeddingHelper(\r\n embedding=targets_embeddings,\r\n start_tokens=start_tokens,\r\n end_token=END_SYMBOL)\r\n final_outputs_pred, final_state_pred, final_sequence_lengths_pred = decode(\r\n initial_state,\r\n cell,\r\n pred_helper,\r\n beam_width,\r\n projection_layer=projection_layer)\r\n\r\n if beam_width > 1:\r\n predictions_sequence = final_outputs_pred.beam_search_decoder_output.predicted_ids[\r\n :, :, 0]\r\n # final_outputs_pred..predicted_ids[:,:,0] would work too, but it contains -1s for padding\r\n predictions_sequence_scores = final_outputs_pred.beam_search_decoder_output.scores[\r\n :, :, 0]\r\n predictions_sequence_length_with_eos = final_sequence_lengths_pred[\r\n :, 0]\r\n else:\r\n predictions_sequence = final_outputs_pred.sample_id\r\n predictions_sequence_scores = final_outputs_pred.rnn_output\r\n predictions_sequence_length_with_eos = final_sequence_lengths_pred\r\n\r\n logging.debug(' train_logits: {0}'.format(train_logits))\r\n logging.debug(' eval_logits: {0}'.format(eval_logits))\r\n logging.debug(' predictions_sequence: {0}'.format(predictions_sequence))\r\n logging.debug(' predictions_sequence_scores: {0}'.format(\r\n predictions_sequence_scores))\r\n\r\n return predictions_sequence, predictions_sequence_scores, predictions_sequence_length_with_eos, \\\r\n targets_sequence_length_with_eos, eval_logits, train_logits, class_weights, class_biases\r\n", "#! /usr/bin/env python\r\n# coding=utf-8\r\n# Copyright (c) 2019 Uber Technologies, Inc.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\nfrom __future__ import absolute_import\r\nfrom __future__ import division\r\n\r\nfrom collections import Counter\r\nfrom sys import platform\r\n\r\nimport copy\r\nimport logging\r\nimport matplotlib as mpl\r\n\r\nif platform == \"darwin\": # OS X\r\n mpl.use('TkAgg')\r\nimport matplotlib.patches as patches\r\nimport matplotlib.path as path\r\nimport matplotlib.patheffects as PathEffects\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport seaborn as sns\r\nfrom matplotlib import ticker\r\nfrom matplotlib.lines import Line2D\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\n\r\n\r\n# plt.rc('xtick', labelsize='x-large')\r\n# plt.rc('ytick', labelsize='x-large')\r\n# plt.rc('axes', labelsize='x-large')\r\n\r\ndef learning_curves_plot(train_values, vali_values, metric, algorithm_names=None,\r\n title=None):\r\n num_algorithms = len(train_values)\r\n max_len = max([len(tv) for tv in train_values])\r\n\r\n fig, ax = plt.subplots()\r\n\r\n sns.set_style('whitegrid')\r\n\r\n if title is not None:\r\n ax.set_title(title)\r\n\r\n if num_algorithms == 1:\r\n colors = plt.get_cmap('tab10').colors\r\n else: # num_algorithms > 1\r\n colors = plt.get_cmap('tab20').colors\r\n\r\n ax.grid(which='both')\r\n ax.grid(which='minor', alpha=0.5)\r\n ax.grid(which='major', alpha=0.75)\r\n ax.set_xlabel('epochs')\r\n ax.set_ylabel(metric.replace('_', ' '))\r\n\r\n xs = list(range(1, max_len + 1))\r\n\r\n for i in range(num_algorithms):\r\n name_prefix = algorithm_names[\r\n i] + ' ' if algorithm_names is not None and i < len(\r\n algorithm_names) else ''\r\n ax.plot(xs, train_values[i], label=name_prefix + 'training',\r\n color=colors[i * 2], linewidth=3)\r\n if i < len(vali_values):\r\n ax.plot(xs, vali_values[i], label=name_prefix + 'validation',\r\n color=colors[i * 2 + 1], linewidth=3)\r\n\r\n ax.legend()\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef compare_classifiers_plot(scores, metrics, algoritm_names=None,\r\n adaptive=False, decimals=4, title=None):\r\n assert len(scores) == len(metrics)\r\n assert len(scores) > 0\r\n\r\n num_metrics = len(metrics)\r\n\r\n sns.set_style('whitegrid')\r\n\r\n fig, ax = plt.subplots()\r\n\r\n ax.grid(which='both')\r\n ax.grid(which='minor', alpha=0.5)\r\n ax.grid(which='major', alpha=0.75)\r\n ax.set_xticklabels([], minor=True)\r\n\r\n if title is not None:\r\n ax.set_title(title)\r\n\r\n width = 0.8 / num_metrics if num_metrics > 1 else 0.4\r\n ticks = np.arange(len(scores[0]))\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n if adaptive:\r\n maximum = max([max(score) for score in scores])\r\n else:\r\n ax.set_xlim([0, 1])\r\n ax.set_xticks(np.linspace(0.0, 1.0, num=21), minor=True)\r\n ax.set_xticks(np.linspace(0.0, 1.0, num=11))\r\n maximum = 1\r\n\r\n half_total_width = 0.4 if num_metrics > 1 else 0.2\r\n ax.set_yticks(ticks + half_total_width - width / 2)\r\n ax.set_yticklabels(algoritm_names if algoritm_names is not None else '')\r\n ax.invert_yaxis() # labels read top-to-bottom\r\n\r\n for i, metric in enumerate(metrics):\r\n ax.barh(ticks + (i * width), scores[i], width, label=metric,\r\n color=colors[i])\r\n\r\n for j, v in enumerate(scores[i]):\r\n if v < maximum * (0.025 * decimals + 0.1):\r\n x = v + maximum * 0.01\r\n horizontal_alignment = 'left'\r\n else:\r\n x = v - maximum * 0.01\r\n horizontal_alignment = 'right'\r\n txt = ax.text(x, ticks[j] + (i * width),\r\n ('{:.' + str(decimals) + 'f}').format(v),\r\n color='white',\r\n fontweight='bold', verticalalignment='center',\r\n horizontalalignment=horizontal_alignment)\r\n txt.set_path_effects(\r\n [PathEffects.withStroke(linewidth=3, foreground='black')])\r\n\r\n plt.setp(ax.get_xminorticklabels(), visible=False)\r\n\r\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef compare_classifiers_line_plot(xs, scores, metric, algorithm_names=None,\r\n title=None):\r\n sns.set_style('whitegrid')\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n fig, ax = plt.subplots()\r\n\r\n ax.grid(which='both')\r\n ax.grid(which='minor', alpha=0.5)\r\n ax.grid(which='major', alpha=0.75)\r\n\r\n if title is not None:\r\n ax.set_title(title)\r\n\r\n ax.set_xticks(xs)\r\n ax.set_xticklabels(xs)\r\n ax.set_xlabel('k')\r\n ax.set_ylabel(metric)\r\n\r\n for i, score in enumerate(scores):\r\n ax.plot(xs, score,\r\n label=algorithm_names[\r\n i] if algorithm_names is not None and i < len(\r\n algorithm_names) else 'Algorithm {}'.format(i),\r\n color=colors[i], linewidth=3, marker='o')\r\n\r\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef compare_classifiers_multiclass_multimetric_plot(scores, metrics,\r\n labels=None, title=None):\r\n assert len(scores) > 0\r\n\r\n sns.set_style('whitegrid')\r\n\r\n fig, ax = plt.subplots()\r\n\r\n if title is not None:\r\n ax.set_title(title)\r\n\r\n width = 0.9 / len(scores)\r\n ticks = np.arange(len(scores[0]))\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n ax.set_xlabel('class')\r\n ax.set_xticks(ticks + width)\r\n if labels is not None:\r\n ax.set_xticklabels(labels, rotation=90)\r\n else:\r\n ax.set_xticklabels(ticks, rotation=90)\r\n\r\n for i, score in enumerate(scores):\r\n ax.bar(ticks + i * width, score, width, label=metrics[i],\r\n color=colors[i])\r\n\r\n ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef radar_chart(ground_truth, predictions, algorithms=None, log_scale=False,\r\n title=None):\r\n sns.set_style('whitegrid')\r\n\r\n if title is not None:\r\n plt.title(title)\r\n\r\n ground_truth = ground_truth[0:10]\r\n predictions = [pred[0:10] for pred in predictions]\r\n\r\n gt_argsort = np.argsort(-ground_truth) # sort deacreasing\r\n logging.info(gt_argsort)\r\n ground_truth = ground_truth[gt_argsort]\r\n predictions = [pred[gt_argsort] for pred in predictions]\r\n\r\n maximum = max(max(ground_truth), max([max(p) for p in predictions]))\r\n\r\n ax = plt.subplot(111, polar=True)\r\n ax.set_theta_zero_location('N')\r\n ax.set_theta_direction(-1)\r\n ax.set_rmax(maximum)\r\n ax.set_rlabel_position(305)\r\n ax.set_ylabel('Probability')\r\n # ax.set_rscale('log')\r\n ax.grid(True)\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n num_classes = len(ground_truth)\r\n\r\n # Set ticks to the number of properties (in radians)\r\n t = np.arange(0, 2 * np.pi, 2 * np.pi / num_classes)\r\n ax.set_xticks(t, [])\r\n ax.set_xticklabels(np.arange(0, num_classes))\r\n\r\n # Set yticks from 0 to 10\r\n # ax.set_yticks(np.linspace(0, 10, 11))\r\n # Set axes limits\r\n # ax.set_rlim(0, 1)\r\n # ax.set_rscale('log')\r\n\r\n def draw_polygon(values, label, color='grey'):\r\n points = [(x, y) for x, y in zip(t, values)]\r\n points.append(points[0])\r\n points = np.array(points)\r\n\r\n codes = [path.Path.MOVETO, ] + \\\r\n [path.Path.LINETO, ] * (len(values) - 1) + \\\r\n [path.Path.CLOSEPOLY]\r\n _path = path.Path(points, codes)\r\n _patch = patches.PathPatch(_path, fill=True, color=color, linewidth=0,\r\n alpha=.2)\r\n ax.add_patch(_patch)\r\n _patch = patches.PathPatch(_path, fill=False, color=color, linewidth=3)\r\n ax.add_patch(_patch)\r\n\r\n # Draw circles at value points\r\n # line = ax.scatter(points[:, 0], points[:, 1], linewidth=3,\r\n # s=50, color='white', edgecolor=color, zorder=10)\r\n ax.plot(points[:, 0], points[:, 1], linewidth=3, marker='o',\r\n fillstyle='full',\r\n markerfacecolor='white',\r\n markeredgecolor=color,\r\n markeredgewidth=2,\r\n color=color, zorder=10, label=label)\r\n\r\n draw_polygon(ground_truth, 'Ground Truth')\r\n\r\n # Draw polygon representing values\r\n for i, alg_predictions in enumerate(predictions):\r\n draw_polygon(alg_predictions, algorithms[i], colors[i])\r\n\r\n ax.legend(frameon=True, loc='upper left')\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef pie(ax, values, **kwargs):\r\n total = sum(values)\r\n\r\n def formatter(pct):\r\n if pct > 0:\r\n return '{:0.0f}\\n({:0.1f}%)'.format(pct * total / 100, pct)\r\n else:\r\n return ''\r\n\r\n wedges, _, labels = ax.pie(values, autopct=formatter, **kwargs)\r\n return wedges\r\n\r\n\r\ndef donut(inside_values, inside_labels, outside_values, outside_labels,\r\n outside_groups, title=None):\r\n fig, ax = plt.subplots()\r\n\r\n if title is not None:\r\n ax.set_title(title)\r\n\r\n ax.axis('equal')\r\n\r\n width = 0.35\r\n colors_tab20c = list(plt.get_cmap('tab20c').colors)\r\n colors_set2 = list(plt.get_cmap('Set2').colors)\r\n colors_set3 = list(plt.get_cmap('Set3').colors)\r\n colors_pastel1 = list(plt.get_cmap('Pastel1').colors)\r\n\r\n # swap green and red\r\n # for i in range(4):\r\n # tmp = colors[4 + i]\r\n # colors[4 + i] = colors[8 + i]\r\n # colors[8 + i] = tmp\r\n\r\n colors = []\r\n colors.extend(colors_tab20c[8:12])\r\n colors.append(colors_set2[5])\r\n colors.append(colors_set3[11])\r\n colors.append(colors_set3[1])\r\n colors.append(colors_pastel1[5])\r\n colors.extend(colors_tab20c[4:8])\r\n\r\n inside_colors = [colors[x * 4] for x in range(len(inside_values))]\r\n\r\n group_count = Counter(outside_groups)\r\n outside_colors = [colors[(i * 4) + ((j % 3) + 1)]\r\n for i in list(set(outside_groups))\r\n for j in range(group_count[i])]\r\n\r\n outside = pie(ax, outside_values, radius=1, pctdistance=1 - width / 2,\r\n colors=outside_colors, startangle=90, counterclock=False,\r\n textprops={'color': 'w', 'weight': 'bold',\r\n 'path_effects': [\r\n PathEffects.withStroke(linewidth=3,\r\n foreground='black')]})\r\n inside = pie(ax, inside_values, radius=1 - width,\r\n pctdistance=1 - (width / 2) / (1 - width),\r\n colors=inside_colors, startangle=90, counterclock=False,\r\n textprops={'color': 'w', 'weight': 'bold',\r\n 'path_effects': [PathEffects.withStroke(linewidth=3,\r\n foreground='black')]})\r\n plt.setp(inside + outside, width=width, edgecolor='white')\r\n\r\n wedges = []\r\n labels = []\r\n so_far = 0\r\n for i in list(set(outside_groups)):\r\n wedges.append(inside[i])\r\n labels.append(inside_labels[i])\r\n for j in range(group_count[i]):\r\n wedges.append(outside[so_far])\r\n labels.append(outside_labels[so_far])\r\n so_far += 1\r\n\r\n ax.legend(wedges, labels, frameon=True)\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef confidence_fitlering_plot(thresholds, accuracies, dataset_kepts,\r\n algorithm_names=None, title=None):\r\n assert len(accuracies) == len(dataset_kepts)\r\n num_algorithms = len(accuracies)\r\n\r\n sns.set_style('whitegrid')\r\n\r\n if num_algorithms == 1:\r\n colors = plt.get_cmap('tab10').colors\r\n else: # num_algorithms > 1\r\n colors = plt.get_cmap('tab20').colors\r\n\r\n y_ticks_minor = np.linspace(0.0, 1.0, num=21)\r\n y_ticks_major = np.linspace(0.0, 1.0, num=11)\r\n y_ticks_major_labels = ['{:3.0f}%'.format(y * 100) for y in y_ticks_major]\r\n\r\n fig, ax1 = plt.subplots()\r\n\r\n if title is not None:\r\n ax1.set_title(title)\r\n\r\n ax1.grid(which='both')\r\n ax1.grid(which='minor', alpha=0.5)\r\n ax1.grid(which='major', alpha=0.75)\r\n ax1.set_xticks([x for idx, x in enumerate(thresholds) if idx % 2 == 0])\r\n ax1.set_xticks(thresholds, minor=True)\r\n\r\n ax1.set_xlim(-0.05, 1.05)\r\n ax1.set_xlabel('confidence threshold')\r\n\r\n ax1.set_ylim(0, 1.05)\r\n ax1.set_yticks(y_ticks_major)\r\n ax1.set_yticklabels(y_ticks_major_labels)\r\n ax1.set_yticks(y_ticks_minor, minor=True)\r\n\r\n ax2 = ax1.twinx()\r\n\r\n ax2.set_ylim(0, 1.05)\r\n ax2.set_yticks(y_ticks_major)\r\n ax2.set_yticklabels(y_ticks_major_labels)\r\n ax2.set_yticks(y_ticks_minor, minor=True)\r\n\r\n for i in range(len(accuracies)):\r\n algorithm_name = algorithm_names[\r\n i] + ' ' if algorithm_names is not None and i < len(\r\n algorithm_names) else ''\r\n ax1.plot(thresholds, accuracies[i],\r\n label='{} accuracy'.format(algorithm_name),\r\n color=colors[i * 2],\r\n linewidth=3)\r\n ax1.plot(thresholds, dataset_kepts[i],\r\n label='{} data coverage'.format(algorithm_name),\r\n color=colors[i * 2 + 1], linewidth=3)\r\n\r\n ax1.legend(frameon=True, loc=3)\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef confidence_fitlering_data_vs_acc_plot(accuracies, dataset_kepts,\r\n model_names=None,\r\n dotted=False,\r\n decimal_digits=0,\r\n y_label='accuracy',\r\n title=None):\r\n assert len(accuracies) == len(dataset_kepts)\r\n\r\n sns.set_style('whitegrid')\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n max_dataset_kept = max(\r\n [max(dataset_kept) for dataset_kept in dataset_kepts])\r\n\r\n x_ticks_minor = np.linspace(0.0, max_dataset_kept, num=21)\r\n x_ticks_major = np.linspace(0.0, max_dataset_kept, num=11)\r\n x_ticks_major_labels = [\r\n '{value:3.{decimal_digits}f}%'.format(\r\n decimal_digits=decimal_digits,\r\n value=x * 100\r\n ) for x in x_ticks_major\r\n ]\r\n y_ticks_minor = np.linspace(0.0, 1.0, num=21)\r\n y_ticks_major = np.linspace(0.0, 1.0, num=11)\r\n\r\n fig, ax = plt.subplots()\r\n\r\n if title is not None:\r\n ax.set_title(title)\r\n\r\n ax.grid(which='both')\r\n ax.grid(which='minor', alpha=0.5)\r\n ax.grid(which='major', alpha=0.75)\r\n ax.set_xticks(x_ticks_major)\r\n ax.set_xticks(x_ticks_minor, minor=True)\r\n ax.set_xticklabels(x_ticks_major_labels)\r\n ax.set_xlim(0, max_dataset_kept)\r\n ax.set_xlabel('data coverage')\r\n\r\n ax.set_ylim(0, 1)\r\n ax.set_yticks(y_ticks_major)\r\n ax.set_yticks(y_ticks_minor, minor=True)\r\n ax.set_ylabel(y_label)\r\n\r\n for i in range(len(accuracies)):\r\n curr_dotted = dotted[i] if isinstance(dotted,\r\n (list, tuple)) and i < len(\r\n dotted) else dotted\r\n algorithm_name = model_names[\r\n i] + ' ' if model_names is not None and i < len(\r\n model_names) else ''\r\n ax.plot(dataset_kepts[i], accuracies[i], label=algorithm_name,\r\n color=colors[i],\r\n linewidth=3, linestyle=':' if curr_dotted else '-')\r\n\r\n ax.legend(frameon=True, loc=3)\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef confidence_fitlering_data_vs_acc_multiline_plot(accuracies, dataset_kepts,\r\n models_names,\r\n title=None):\r\n assert len(accuracies) == len(dataset_kepts)\r\n\r\n sns.set_style('whitegrid')\r\n\r\n colors = plt.get_cmap('tab20').colors\r\n\r\n max_dataset_kept = max(\r\n [max(dataset_kept) for dataset_kept in dataset_kepts])\r\n\r\n x_ticks_minor = np.linspace(0.0, max_dataset_kept, num=21)\r\n x_ticks_major = np.linspace(0.0, max_dataset_kept, num=11)\r\n x_ticks_major_labels = ['{:3.0f}%'.format(x * 100) for x in x_ticks_major]\r\n y_ticks_minor = np.linspace(0.0, 1.0, num=21)\r\n y_ticks_major = np.linspace(0.0, 1.0, num=11)\r\n\r\n fig, ax = plt.subplots()\r\n\r\n if title is not None:\r\n ax.set_title(title)\r\n\r\n ax.grid(which='both')\r\n ax.grid(which='minor', alpha=0.5)\r\n ax.grid(which='major', alpha=0.75)\r\n ax.set_xticks(x_ticks_major)\r\n ax.set_xticks(x_ticks_minor, minor=True)\r\n ax.set_xticklabels(x_ticks_major_labels)\r\n ax.set_xlim(0, max_dataset_kept)\r\n ax.set_xlabel('data coverage')\r\n\r\n ax.set_ylim(0, 1)\r\n ax.set_yticks(y_ticks_major)\r\n ax.set_yticks(y_ticks_minor, minor=True)\r\n ax.set_ylabel('accuracy')\r\n\r\n for i in range(len(accuracies)):\r\n ax.plot(dataset_kepts[i], accuracies[i], color=colors[0],\r\n linewidth=1.0, alpha=0.35)\r\n\r\n legend_elements = [Line2D([0], [0], linewidth=1.0, color=colors[0])]\r\n ax.legend(legend_elements, models_names)\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef confidence_fitlering_3d_plot(thresholds_1, thresholds_2, accuracies,\r\n dataset_kepts, threshold_fields=None,\r\n title=None):\r\n assert len(accuracies) == len(dataset_kepts)\r\n assert len(thresholds_1) == len(thresholds_2)\r\n\r\n thresholds_1, thresholds_2 = np.meshgrid(thresholds_1, thresholds_2)\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n sns.set_style('white')\r\n\r\n z_ticks_minor = np.linspace(0.0, 1.0, num=21)\r\n z_ticks_major = np.linspace(0.0, 1.0, num=11)\r\n z_ticks_major_labels = ['{:3.0f}%'.format(z * 100) for z in z_ticks_major]\r\n\r\n fig = plt.figure()\r\n ax = Axes3D\r\n ax = fig.add_subplot(111, projection='3d')\r\n\r\n if title is not None:\r\n ax.set_title(title)\r\n\r\n ax.grid(which='both')\r\n ax.grid(which='minor', alpha=0.5)\r\n ax.grid(which='major', alpha=0.75)\r\n\r\n ax.set_xlabel('{} probability'.format(threshold_fields[0]))\r\n ax.set_ylabel('{} probability'.format(threshold_fields[1]))\r\n\r\n ax.set_xlim(np.min(thresholds_1), np.max(thresholds_1))\r\n ax.set_ylim(np.min(thresholds_2), np.max(thresholds_2))\r\n ax.set_zlim(0, 1)\r\n ax.set_zticks(z_ticks_major)\r\n ax.set_zticklabels(z_ticks_major_labels)\r\n ax.set_zticks(z_ticks_minor, minor=True)\r\n\r\n # ORRIBLE HACK, IT'S THE ONLY WAY TO REMOVE PADDING\r\n from mpl_toolkits.mplot3d.axis3d import Axis\r\n if not hasattr(Axis, '_get_coord_info_old'):\r\n def _get_coord_info_new(self, renderer):\r\n mins, maxs, centers, deltas, tc, highs = self._get_coord_info_old(\r\n renderer)\r\n mins += deltas / 4\r\n maxs -= deltas / 4\r\n return mins, maxs, centers, deltas, tc, highs\r\n\r\n Axis._get_coord_info_old = Axis._get_coord_info\r\n Axis._get_coord_info = _get_coord_info_new\r\n # END OF HORRIBLE HACK\r\n\r\n surf_1 = ax.plot_surface(thresholds_1, thresholds_2, accuracies,\r\n alpha=0.5,\r\n label='accuracy',\r\n cmap=plt.get_cmap('winter'),\r\n edgecolor='none')\r\n surf_2 = ax.plot_surface(thresholds_1, thresholds_2, dataset_kepts,\r\n alpha=0.5,\r\n label='data coverage',\r\n cmap=plt.get_cmap('autumn'),\r\n edgecolor='none')\r\n\r\n handle_1 = copy.copy(surf_1)\r\n handle_2 = copy.copy(surf_2)\r\n\r\n handle_1.set_color(colors[0])\r\n handle_2.set_color(colors[1])\r\n\r\n handle_1._edgecolors2d = handle_1._edgecolors3d\r\n handle_2._edgecolors2d = handle_2._edgecolors3d\r\n\r\n handle_1._facecolors2d = handle_1._facecolors3d\r\n handle_2._facecolors2d = handle_2._facecolors3d\r\n\r\n ax.legend(frameon=True, loc=3, handles=[handle_1, handle_2])\r\n\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef threshold_vs_metric_plot(thresholds, scores, algorithm_names=None,\r\n title=None):\r\n sns.set_style('whitegrid')\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n # y_ticks_minor = np.linspace(0.0, 1.0, num=21)\r\n # y_ticks_major = np.linspace(0.0, 1.0, num=11)\r\n # y_ticks_major_labels = ['{:3.0f}%'.format(y * 100) for y in y_ticks_major]\r\n\r\n fig, ax1 = plt.subplots()\r\n\r\n if title is not None:\r\n ax1.set_title(title)\r\n\r\n ax1.grid(which='both')\r\n ax1.grid(which='minor', alpha=0.5)\r\n ax1.grid(which='major', alpha=0.75)\r\n ax1.set_xticks([x for idx, x in enumerate(thresholds) if idx % 2 == 0])\r\n ax1.set_xticks(thresholds, minor=True)\r\n\r\n # ax1.set_xlim(0, 1)\r\n ax1.set_xlabel('confidence threshold')\r\n\r\n # ax1.set_ylim(0, 1)\r\n # ax1.set_yticks(y_ticks_major)\r\n # ax1.set_yticklabels(y_ticks_major_labels)\r\n # ax1.set_yticks(y_ticks_minor, minor=True)\r\n\r\n for i in range(len(scores)):\r\n algorithm_name = algorithm_names[\r\n i] + ' ' if algorithm_names is not None and i < len(\r\n algorithm_names) else ''\r\n ax1.plot(thresholds, scores[i], label=algorithm_name, color=colors[i],\r\n linewidth=3, marker='o')\r\n\r\n ax1.legend(frameon=True)\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef roc_curves(fpr_tprs, algorithm_names=None, title=None, graded_color=False):\r\n sns.set_style('whitegrid')\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n colormap = plt.get_cmap('RdYlGn')\r\n\r\n y_ticks_minor = np.linspace(0.0, 1.0, num=21)\r\n y_ticks_major = np.linspace(0.0, 1.0, num=11)\r\n\r\n fig, ax = plt.subplots()\r\n\r\n if title is not None:\r\n ax.set_title(title)\r\n\r\n ax.grid(which='both')\r\n ax.grid(which='minor', alpha=0.5)\r\n ax.grid(which='major', alpha=0.75)\r\n\r\n ax.set_xlim(0, 1)\r\n ax.set_xlabel('False positive rate')\r\n\r\n ax.set_ylim(0, 1)\r\n ax.set_yticks(y_ticks_major)\r\n ax.set_yticks(y_ticks_minor, minor=True)\r\n ax.set_ylabel('True positive rate')\r\n\r\n plt.plot([0, 1], [0, 1], color='black', linewidth=3, linestyle='--')\r\n\r\n for i in range(len(fpr_tprs)):\r\n algorithm_name = algorithm_names[\r\n i] + ' ' if algorithm_names is not None and i < len(\r\n algorithm_names) else ''\r\n color = colormap(i / len(fpr_tprs)) if graded_color else colors[i]\r\n ax.plot(fpr_tprs[i][0], fpr_tprs[i][1], label=algorithm_name,\r\n color=color,\r\n linewidth=3)\r\n\r\n ax.legend(frameon=True)\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef calibration_plot(fraction_positives, mean_predicted_values,\r\n algorithm_names=None):\r\n assert len(fraction_positives) == len(mean_predicted_values)\r\n\r\n sns.set_style('whitegrid')\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n num_algorithms = len(fraction_positives)\r\n\r\n plt.figure(figsize=(9, 9))\r\n plt.grid(which='both')\r\n plt.grid(which='minor', alpha=0.5)\r\n plt.grid(which='major', alpha=0.75)\r\n\r\n plt.plot([0, 1], [0, 1], 'k:', label='Perfectly calibrated')\r\n\r\n for i in range(num_algorithms):\r\n # ax1.plot(mean_predicted_values[i], fraction_positives[i],\r\n # label=algorithms[i] if algorithm_names is not None and i < len(algorithms) else '')\r\n\r\n # sns.tsplot(mean_predicted_values[i], fraction_positives[i], ax=ax1, color=colors[i])\r\n\r\n sns.regplot(mean_predicted_values[i], fraction_positives[i],\r\n order=3, x_estimator=np.mean, color=colors[i], marker='o',\r\n scatter_kws={'s': 40},\r\n label=algorithm_names[\r\n i] if algorithm_names is not None and i < len(\r\n algorithm_names) else '')\r\n\r\n ticks = np.linspace(0.0, 1.0, num=11)\r\n plt.xlim([-0.05, 1.05])\r\n plt.xticks(ticks)\r\n plt.xlabel('Predicted probability')\r\n plt.ylabel('Observed probability')\r\n plt.ylim([-0.05, 1.05])\r\n plt.yticks(ticks)\r\n plt.legend(loc='lower right')\r\n plt.title('Calibration (reliability curve)')\r\n\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef brier_plot(brier_scores, algorithm_names=None, title=None):\r\n sns.set_style('whitegrid')\r\n\r\n if title is not None:\r\n plt.title(title)\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n plt.grid(which='both')\r\n plt.grid(which='minor', alpha=0.5)\r\n plt.grid(which='major', alpha=0.75)\r\n plt.xlabel('class')\r\n plt.ylabel('brier')\r\n\r\n x = np.array(range(brier_scores.shape[0]))\r\n for i in range(brier_scores.shape[1]):\r\n plt.plot(brier_scores[:, i],\r\n label=algorithm_names[\r\n i] + ' ' if algorithm_names is not None and i < len(\r\n algorithm_names) else '',\r\n color=colors[i], linewidth=3)\r\n\r\n plt.legend()\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef predictions_distribution_plot(probabilities, algorithm_names=None):\r\n sns.set_style('whitegrid')\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n num_algorithms = len(probabilities)\r\n\r\n plt.figure(figsize=(9, 9))\r\n plt.grid(which='both')\r\n plt.grid(which='minor', alpha=0.5)\r\n plt.grid(which='major', alpha=0.75)\r\n\r\n for i in range(num_algorithms):\r\n plt.hist(probabilities[i], range=(0, 1), bins=41, color=colors[i],\r\n label=algorithm_names[\r\n i] if algorithm_names is not None and i < len(\r\n algorithm_names) else '',\r\n histtype='stepfilled', alpha=0.5, lw=2)\r\n\r\n plt.xlabel('Mean predicted value')\r\n plt.xlim([0, 1])\r\n plt.xticks(np.linspace(0.0, 1.0, num=21))\r\n plt.ylabel('Count')\r\n plt.legend(loc='upper center', ncol=2)\r\n\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef confusion_matrix_plot(confusion_matrix, labels=None, field=None):\r\n mpl.rcParams.update({'figure.autolayout': True})\r\n fig, ax = plt.subplots()\r\n\r\n ax.invert_yaxis()\r\n ax.xaxis.tick_top()\r\n ax.xaxis.set_label_position('top')\r\n\r\n cax = ax.matshow(confusion_matrix, cmap='viridis')\r\n\r\n ax.xaxis.set_major_locator(ticker.MultipleLocator(1))\r\n ax.yaxis.set_major_locator(ticker.MultipleLocator(1))\r\n ax.set_xticklabels([''] + labels, rotation=45, ha='left')\r\n ax.set_yticklabels([''] + labels)\r\n ax.grid(False)\r\n ax.tick_params(axis='both', which='both', length=0)\r\n fig.colorbar(cax, ax=ax, extend='max')\r\n ax.set_xlabel('Predicted {}'.format(field))\r\n ax.set_ylabel('Actual {}'.format(field))\r\n\r\n plt.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef double_axis_line_plot(y1_sorted, y2, y1_name, y2_name, labels=None,\r\n title=None):\r\n sns.set_style('whitegrid')\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n fig, ax1 = plt.subplots()\r\n\r\n if title is not None:\r\n ax1.set_title(title)\r\n\r\n # ax1.grid(which='both')\r\n # ax1.grid(which='minor', alpha=0.5)\r\n # ax1.grid(which='major', alpha=0.75)\r\n\r\n ax1.set_xlabel('class (sorted by {})'.format(y1_name))\r\n ax1.set_xlim(0, len(y1_sorted) - 1)\r\n if labels is not None:\r\n ax1.set_xticklabels(labels, rotation=45, ha='right')\r\n ax1.set_xticks(np.arange(len(labels)))\r\n\r\n ax1.set_ylabel(y2_name, color=colors[1])\r\n ax1.tick_params('y', colors=colors[1])\r\n ax1.set_ylim(min(y2), max(y2))\r\n\r\n ax2 = ax1.twinx()\r\n ax2.set_ylabel(y1_name, color=colors[0])\r\n ax2.tick_params('y', colors=colors[0])\r\n ax2.set_ylim(min(y1_sorted), max(y1_sorted))\r\n\r\n ax1.plot(y2, label=y2_name, color=colors[1],\r\n linewidth=3)\r\n ax2.plot(y1_sorted, label=y1_name, color=colors[0],\r\n linewidth=4.0)\r\n\r\n fig.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef plot_matrix(matrix, cmap='hot'):\r\n plt.matshow(matrix, cmap=cmap)\r\n plt.show()\r\n\r\n\r\ndef plot_distributions(distributions, labels=None, title=None):\r\n sns.set_style('whitegrid')\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n fig, ax1 = plt.subplots()\r\n\r\n if title is not None:\r\n ax1.set_title(title)\r\n\r\n ax1.grid(which='both')\r\n ax1.grid(which='minor', alpha=0.5)\r\n ax1.grid(which='major', alpha=0.75)\r\n\r\n ax1.set_xlabel('class')\r\n\r\n ax1.set_ylabel('p')\r\n ax1.tick_params('y')\r\n\r\n for i, distribution in enumerate(distributions):\r\n ax1.plot(distribution, color=colors[i], alpha=0.6,\r\n label=labels[i] if labels is not None and i < len(\r\n labels) else 'Distribution {}'.format(i))\r\n\r\n ax1.legend(frameon=True)\r\n fig.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef plot_distributions_difference(distribution, labels=None, title=None):\r\n sns.set_style('whitegrid')\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n fig, ax1 = plt.subplots()\r\n\r\n if title is not None:\r\n ax1.set_title(title)\r\n\r\n ax1.grid(which='both')\r\n ax1.grid(which='minor', alpha=0.5)\r\n ax1.grid(which='major', alpha=0.75)\r\n\r\n ax1.set_xlabel('class')\r\n\r\n ax1.set_ylabel('p')\r\n ax1.tick_params('y')\r\n\r\n ax1.plot(distribution, color=colors[0])\r\n\r\n fig.tight_layout()\r\n plt.show()\r\n\r\n\r\ndef bar_plot(xs, ys, decimals=4, labels=None, title=None):\r\n assert len(xs) == len(ys)\r\n assert len(xs) > 0\r\n\r\n sns.set_style('whitegrid')\r\n\r\n fig, ax = plt.subplots()\r\n\r\n ax.grid(which='both')\r\n ax.grid(which='minor', alpha=0.5)\r\n ax.grid(which='major', alpha=0.75)\r\n\r\n if title is not None:\r\n ax.set_title(title)\r\n\r\n colors = plt.get_cmap('tab10').colors\r\n\r\n ax.invert_yaxis() # labels read top-to-bottom\r\n\r\n maximum = ys.max()\r\n ticks = np.arange(len(xs))\r\n ax.set_yticks(ticks)\r\n if labels is None:\r\n ax.set_yticklabels(xs)\r\n else:\r\n ax.set_yticklabels(labels)\r\n\r\n ax.barh(ticks, ys, color=colors[0], align='center')\r\n\r\n for i, v in enumerate(ys):\r\n if v < maximum * (0.025 * decimals + 0.1):\r\n x = v + maximum * 0.01\r\n horizontal_alignment = 'left'\r\n else:\r\n x = v - maximum * 0.01\r\n horizontal_alignment = 'right'\r\n txt = ax.text(x, ticks[i], ('{:.' + str(decimals) + 'f}').format(v),\r\n color='white',\r\n fontweight='bold', verticalalignment='center',\r\n horizontalalignment=horizontal_alignment)\r\n txt.set_path_effects(\r\n [PathEffects.withStroke(linewidth=3, foreground='black')])\r\n\r\n plt.tight_layout()\r\n plt.show()\r\n", "#! /usr/bin/env python\r\n# coding=utf-8\r\n# Copyright (c) 2019 Uber Technologies, Inc.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\nimport copy\r\nimport os\r\nimport random\r\nimport subprocess\r\nimport sys\r\nfrom collections import OrderedDict, Mapping\r\n\r\nimport numpy\r\n\r\nimport ludwig.globals\r\n\r\n\r\ndef get_experiment_description(model_definition,\r\n dataset_type='generic',\r\n data_csv=None,\r\n data_hdf5=None,\r\n metadata_json=None,\r\n data_train_csv=None,\r\n data_validation_csv=None,\r\n data_test_csv=None,\r\n data_train_hdf5=None,\r\n data_validation_hdf5=None,\r\n data_test_hdf5=None,\r\n random_seed=None):\r\n description = OrderedDict()\r\n description['ludwig_version'] = ludwig.globals.LUDWIG_VERSION\r\n description['command'] = ' '.join(sys.argv)\r\n\r\n try:\r\n is_a_git_repo = subprocess.call(['git', 'branch'],\r\n stderr=subprocess.STDOUT,\r\n stdout=open(os.devnull, 'w')) == 0\r\n if is_a_git_repo:\r\n description['commit_hash'] = \\\r\n subprocess.check_output(['git', 'rev-parse', 'HEAD']).decode(\r\n 'utf-8')[:12]\r\n except:\r\n pass\r\n\r\n description['dataset_type'] = dataset_type\r\n if random_seed is not None:\r\n description['random_seed'] = random_seed\r\n if data_csv is not None:\r\n description['input_data'] = data_csv\r\n elif data_hdf5 is not None and metadata_json is not None:\r\n description['input_data'] = data_hdf5\r\n description['input_metadata'] = metadata_json\r\n elif data_train_csv is not None:\r\n description['input_data_train'] = data_train_csv\r\n if data_validation_csv is not None:\r\n description['input_data_validation'] = data_validation_csv\r\n if data_test_csv is not None:\r\n description['input_data_test'] = data_test_csv\r\n elif data_train_hdf5 is not None and metadata_json is not None:\r\n description['input_data_train'] = data_train_hdf5\r\n if data_validation_hdf5 is not None:\r\n description['input_data_validation'] = data_validation_hdf5\r\n if data_test_hdf5 is not None:\r\n description['input_data_test'] = data_test_hdf5\r\n description['input_metadata'] = metadata_json\r\n description['model_definition'] = model_definition\r\n\r\n return description\r\n\r\n\r\ndef set_random_seed(random_seed):\r\n os.environ['PYTHONHASHSEED'] = str(random_seed)\r\n random.seed(random_seed)\r\n numpy.random.seed(random_seed)\r\n\r\n\r\ndef merge_dict(dct, merge_dct):\r\n \"\"\" Recursive dict merge. Inspired by :meth:``dict.update()``, instead of\r\n updating only top-level keys, dict_merge recurses down into dicts nested\r\n to an arbitrary depth, updating keys. The ``merge_dct`` is merged into\r\n ``dct``.\r\n :param dct: dict onto which the merge is executed\r\n :param merge_dct: dct merged into dct\r\n :return: None\r\n \"\"\"\r\n dct = copy.deepcopy(dct)\r\n for k, v in merge_dct.items():\r\n if (k in dct and isinstance(dct[k], dict)\r\n and isinstance(merge_dct[k], Mapping)):\r\n dct[k] = merge_dict(dct[k], merge_dct[k])\r\n else:\r\n dct[k] = merge_dct[k]\r\n return dct\r\n\r\n\r\ndef sum_dicts(dicts, dict_type=dict):\r\n summed_dict = dict_type()\r\n for d in dicts:\r\n for key, value in d.items():\r\n if key in summed_dict:\r\n prev_value = summed_dict[key]\r\n if isinstance(value, (dict, OrderedDict)):\r\n summed_dict[key] = sum_dicts([prev_value, value],\r\n dict_type=type(value))\r\n elif isinstance(value, numpy.ndarray):\r\n summed_dict[key] = numpy.concatenate((prev_value, value))\r\n else:\r\n summed_dict[key] = prev_value + value\r\n else:\r\n summed_dict[key] = value\r\n return summed_dict\r\n\r\n\r\ndef get_from_registry(key, registry):\r\n if hasattr(key, 'lower'):\r\n key = key.lower()\r\n if key in registry:\r\n return registry[key]\r\n else:\r\n raise ValueError(\r\n 'Key {} not supported, available options: {}'.format(\r\n key, registry.keys()\r\n )\r\n )\r\n\r\n\r\ndef set_default_value(dictionary, key, value):\r\n if key not in dictionary:\r\n dictionary[key] = value\r\n", "# coding=utf-8\r\n# Copyright (c) 2019 Uber Technologies, Inc.\r\n#\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n#\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n#\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\n# ==============================================================================\r\nimport logging\r\n\r\nimport tensorflow as tf\r\n\r\nfrom ludwig.models.modules.attention_modules import \\\r\n reduce_feed_forward_attention\r\nfrom ludwig.utils.misc import get_from_registry\r\nfrom ludwig.utils.tf_utils import sequence_length_3D\r\n\r\n\r\ndef reduce_last(sequence, **kwargs):\r\n batch_size = tf.shape(sequence)[0]\r\n sequence_length = sequence_length_3D(sequence)\r\n # gather the correct outputs from the the RNN outputs (the outputs after sequence_length are all 0s)\r\n return tf.gather_nd(sequence, tf.stack(\r\n [tf.range(batch_size), tf.maximum(sequence_length - 1, 0)], axis=1))\r\n\r\n\r\ndef reduce_sum(sequence, **kwargs):\r\n return tf.reduce_sum(sequence, axis=1)\r\n\r\n\r\ndef reduce_mean(sequence, **kwargs):\r\n return tf.reduce_mean(sequence, axis=1)\r\n\r\n\r\ndef reduce_max(sequence, **kwargs):\r\n return tf.reduce_max(sequence, axis=1)\r\n\r\n\r\ndef reduce_concat(sequence, **kwargs):\r\n if sequence.shape.as_list()[-2] is None or sequence.shape.as_list()[\r\n -1] is None:\r\n # this the case of outputs coming from rnn encoders\r\n logging.warning(' WARNING: '\r\n 'The sequence length dimension is undefined '\r\n '(probably because of an RNN based encoder), '\r\n 'so the sequence cannot be reduced by concatenation. '\r\n 'Last will be used instead.')\r\n return reduce_last(sequence, **kwargs)\r\n else:\r\n return tf.reshape(sequence,\r\n [-1, sequence.shape[-2] * sequence.shape[-1]])\r\n\r\n\r\ndef dont_reduce(sequence, **kwargs):\r\n return sequence\r\n\r\n\r\nreduce_mode_registry = {\r\n 'last': reduce_last,\r\n 'sum': reduce_sum,\r\n 'mean': reduce_mean,\r\n 'avg': reduce_mean,\r\n 'max': reduce_max,\r\n 'concat': reduce_concat,\r\n 'attention': reduce_feed_forward_attention,\r\n 'none': dont_reduce,\r\n 'None': dont_reduce,\r\n None: dont_reduce\r\n}\r\n\r\n\r\ndef reduce_sequence(sequence, mode):\r\n reduce_mode = get_from_registry(\r\n mode,\r\n reduce_mode_registry\r\n )\r\n return reduce_mode(sequence)\r\n\r\n\r\ndef reduce_sequence_list(sequence_list, mode):\r\n reduce_mode = get_from_registry(\r\n mode,\r\n reduce_mode_registry\r\n )\r\n reduced_list = []\r\n for sequence in sequence_list:\r\n reduced_list.append(reduce_mode(sequence))\r\n if len(reduced_list) > 1:\r\n if reduce_mode == dont_reduce:\r\n reduced_output = tf.concat(reduced_list, 2)\r\n else:\r\n reduced_output = tf.concat(reduced_list, 1)\r\n else:\r\n reduced_output = reduced_list[0]\r\n return reduced_output\r\n" ]
[ [ "tensorflow.get_variable", "tensorflow.python.framework.tensor_shape.TensorShape", "tensorflow.nn.dynamic_rnn", "tensorflow.concat", "tensorflow.layers.dropout", "tensorflow.global_variables", "tensorflow.cast", "tensorflow.tile", "tensorflow.matmul", "tensorflow.shape", "tensorflow.contrib.rnn.LSTMStateTuple", "tensorflow.contrib.seq2seq.AttentionWrapper", "tensorflow.nn.embedding_lookup", "tensorflow.nn.bias_add", "tensorflow.contrib.seq2seq.dynamic_decode", "tensorflow.contrib.seq2seq.TrainingHelper", "tensorflow.contrib.seq2seq.GreedyEmbeddingHelper", "tensorflow.transpose", "tensorflow.contrib.rnn.stack_bidirectional_dynamic_rnn", "tensorflow.reshape", "tensorflow.expand_dims", "tensorflow.contrib.seq2seq.BeamSearchDecoder", "tensorflow.contrib.seq2seq.tile_batch", "tensorflow.python.framework.ops.name_scope", "tensorflow.variable_scope", "tensorflow.random_uniform", "tensorflow.python.util.nest.flatten" ], [ "matplotlib.pyplot.legend", "matplotlib.ticker.MultipleLocator", "numpy.linspace", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.plot", "numpy.max", "matplotlib.pyplot.matshow", "matplotlib.patches.PathPatch", "matplotlib.pyplot.tight_layout", "numpy.arange", "matplotlib.pyplot.subplot", "matplotlib.patheffects.withStroke", "matplotlib.pyplot.figure", "matplotlib.pyplot.title", "numpy.min", "matplotlib.pyplot.ylim", "matplotlib.path.Path", "matplotlib.rcParams.update", "numpy.argsort", "numpy.meshgrid", "matplotlib.pyplot.show", "numpy.array", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.yticks", "matplotlib.use", "matplotlib.lines.Line2D", "matplotlib.pyplot.subplots", "matplotlib.pyplot.xlim", "matplotlib.pyplot.setp", "matplotlib.pyplot.grid", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.xticks" ], [ "numpy.concatenate", "numpy.random.seed" ], [ "tensorflow.reduce_max", "tensorflow.concat", "tensorflow.range", "tensorflow.shape", "tensorflow.reduce_mean", "tensorflow.reduce_sum", "tensorflow.maximum", "tensorflow.reshape" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
wangxiaoyunanne/TAGCN
[ "9f2df35e1586f49efcd6d4706e3edd2499c1c6f1" ]
[ "layers.py" ]
[ "from inits import *\nimport tensorflow as tf\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\n# global unique layer ID dictionary for layer name assignment\n_LAYER_UIDS = {}\n\n\ndef get_layer_uid(layer_name=''):\n \"\"\"Helper function, assigns unique layer IDs.\"\"\"\n if layer_name not in _LAYER_UIDS:\n _LAYER_UIDS[layer_name] = 1\n return 1\n else:\n _LAYER_UIDS[layer_name] += 1\n return _LAYER_UIDS[layer_name]\n\n\ndef sparse_dropout(x, keep_prob, noise_shape):\n \"\"\"Dropout for sparse tensors.\"\"\"\n random_tensor = keep_prob\n random_tensor += tf.random_uniform(noise_shape)\n dropout_mask = tf.cast(tf.floor(random_tensor), dtype=tf.bool)\n pre_out = tf.sparse_retain(x, dropout_mask)\n return pre_out * (1./keep_prob)\n\n\ndef dot(x, y, sparse=False):\n \"\"\"Wrapper for tf.matmul (sparse vs dense).\"\"\"\n if sparse:\n res = tf.sparse_tensor_dense_matmul(x, y)\n else:\n res = tf.matmul(x, y)\n return res\n\n\nclass Layer(object):\n \"\"\"Base layer class. Defines basic API for all layer objects.\n Implementation inspired by keras (http://keras.io).\n\n # Properties\n name: String, defines the variable scope of the layer.\n logging: Boolean, switches Tensorflow histogram logging on/off\n\n # Methods\n _call(inputs): Defines computation graph of layer\n (i.e. takes input, returns output)\n __call__(inputs): Wrapper for _call()\n _log_vars(): Log all variables\n \"\"\"\n\n def __init__(self, **kwargs):\n allowed_kwargs = {'name', 'logging'}\n for kwarg in kwargs.keys():\n assert kwarg in allowed_kwargs, 'Invalid keyword argument: ' + kwarg\n name = kwargs.get('name')\n if not name:\n layer = self.__class__.__name__.lower()\n name = layer + '_' + str(get_layer_uid(layer))\n self.name = name\n self.vars = {}\n logging = kwargs.get('logging', False)\n self.logging = logging\n self.sparse_inputs = False\n\n def _call(self, inputs):\n return inputs\n\n def __call__(self, inputs):\n with tf.name_scope(self.name):\n if self.logging and not self.sparse_inputs:\n tf.summary.histogram(self.name + '/inputs', inputs)\n outputs = self._call(inputs)\n if self.logging:\n tf.summary.histogram(self.name + '/outputs', outputs)\n return outputs\n\n def _log_vars(self):\n for var in self.vars:\n tf.summary.histogram(self.name + '/vars/' + var, self.vars[var])\n\n\n\n\nclass Dense(Layer):\n \"\"\"Dense layer.\"\"\"\n def __init__(self, input_dim, output_dim, placeholders, dropout=0., sparse_inputs=False,\n act=tf.nn.relu, bias=False, featureless=False, **kwargs):\n super(Dense, self).__init__(**kwargs)\n\n if dropout:\n self.dropout = placeholders['dropout']\n else:\n self.dropout = 0.\n\n self.act = act\n self.sparse_inputs = sparse_inputs\n self.featureless = featureless\n self.bias = bias\n\n # helper variable for sparse dropout\n self.num_features_nonzero = placeholders['num_features_nonzero']\n\n with tf.variable_scope(self.name + '_vars'):\n self.vars['weights'] = glorot([input_dim, output_dim],\n name='weights')\n if self.bias:\n self.vars['bias'] = zeros([output_dim], name='bias')\n\n if self.logging:\n self._log_vars()\n\n def _call(self, inputs):\n x = inputs\n\n # dropout\n if self.sparse_inputs:\n x = sparse_dropout(x, 1-self.dropout, self.num_features_nonzero)\n else:\n x = tf.nn.dropout(x, 1-self.dropout)\n\n # transform\n output = dot(x, self.vars['weights'], sparse=self.sparse_inputs)\n\n # bias\n if self.bias:\n output += self.vars['bias']\n\n return self.act(output)\n\nclass GraphConvolution(Layer):\n \"\"\"Graph convolution layer.\"\"\"\n def __init__(self, input_dim, output_dim, placeholders, dropout=0.,\n sparse_inputs=False, act=tf.nn.relu, bias=False,\n featureless=False, **kwargs):\n super(GraphConvolution, self).__init__(**kwargs)\n\n if dropout:\n self.dropout = placeholders['dropout']\n else:\n self.dropout = 0.\n\n self.act = act\n self.support = placeholders['support']\n self.sparse_inputs = sparse_inputs\n self.featureless = featureless\n self.bias = bias\n\n # helper variable for sparse dropout\n self.num_features_nonzero = placeholders['num_features_nonzero']\n\n with tf.variable_scope(self.name + '_vars'):\n for i in range(len(self.support)):\n self.vars['weights_' + str(i)] = glorot([input_dim, output_dim],\n name='weights_' + str(i))\n if self.bias:\n self.vars['bias'] = zeros([output_dim], name='bias')\n\n if self.logging:\n self._log_vars()\n\n def _call(self, inputs):\n x = inputs\n\n # dropout\n if self.sparse_inputs:\n x = sparse_dropout(x, 1-self.dropout, self.num_features_nonzero)\n else:\n x = tf.nn.dropout(x, 1-self.dropout)\n\n # convolve\n supports = list()\n for i in range(len(self.support)):\n if not self.featureless:\n pre_sup = dot(x, self.vars['weights_' + str(i)],\n sparse=self.sparse_inputs)\n else:\n pre_sup = self.vars['weights_' + str(i)]\n support = dot(self.support[i], pre_sup, sparse=True)\n supports.append(support)\n output = tf.add_n(supports)\n\n # bias\n if self.bias:\n output += self.vars['bias']\n\n return self.act(output)\n\n\n\nclass TAGraphConvolution(Layer):\n \"\"\"Graph convolution layer.\"\"\"\n def __init__(self, input_dim, output_dim, placeholders, dropout=0.,\n sparse_inputs=False, act=tf.nn.relu, bias=False,\n featureless=False, **kwargs):\n super(TAGraphConvolution, self).__init__(**kwargs)\n\n if dropout:\n self.dropout = placeholders['dropout']\n else:\n self.dropout = 0.\n\n self.act = act\n self.support = placeholders['support']\n self.sparse_inputs = sparse_inputs\n self.featureless = featureless\n self.bias = bias\n\n # helper variable for sparse dropout\n self.num_features_nonzero = placeholders['num_features_nonzero']\n\n with tf.variable_scope(self.name + '_vars'):\n for k in range(2):\n self.vars['weights_' + str(k)] = tf.get_variable(shape=[input_dim, output_dim], name=('weights_' + str(k)), initializer=tf.contrib.layers.xavier_initializer())\n\n if self.bias:\n # self.vars['bias'] = ones([1],name='bias')\n # self.vars['bias'] = self.vars['bias'] * np.ones([2708,output_dim],dtype=np.float32)\n self.vars['bias'] = zeros([output_dim], name='bias') # zeros([2708,output_dim], name='bias')\n\n self.conv = np.zeros(output_dim,dtype=np.float32)\n\n if self.logging:\n self._log_vars()\n\n def _call(self, inputs):\n x = inputs\n\n # dropout\n if self.sparse_inputs:\n x = sparse_dropout(x, 1-self.dropout, self.num_features_nonzero)\n else:\n x = tf.nn.dropout(x, 1-self.dropout)\n\n # convolve\n supports = list()\n for k in range(2):\n\n w_k = self.support[:,:,k]\n\n # s = tf.matmul(w_k,x) #\n\n G_k = self.vars['weights_' + str(k)]\n\n res = dot(x,G_k,sparse=self.sparse_inputs) # res = tf.matmul(s,G_k)\n res = dot(w_k,res)\n supports.append(res)\n\n output = tf.add_n(supports)\n # self.conv = tf.add(self.conv,res)\n\n # bias\n if self.bias:\n output += self.vars['bias'] # self.conv += self.vars['bias']\n\n return self.act(output) # self.conv\n" ]
[ [ "tensorflow.matmul", "tensorflow.floor", "tensorflow.sparse_retain", "tensorflow.sparse_tensor_dense_matmul", "tensorflow.add_n", "tensorflow.name_scope", "tensorflow.contrib.layers.xavier_initializer", "tensorflow.variable_scope", "tensorflow.nn.dropout", "tensorflow.random_uniform", "tensorflow.summary.histogram" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
wla80/pandas
[ "dccfee53ff68dfa2c42a7571f26ba640694aa547" ]
[ "pandas/tests/indexes/datetimes/test_arithmetic.py" ]
[ "# -*- coding: utf-8 -*-\nimport warnings\nfrom datetime import datetime, timedelta\nimport operator\n\nimport pytest\n\nimport numpy as np\n\nimport pandas as pd\nfrom pandas.compat.numpy import np_datetime64_compat\nimport pandas.util.testing as tm\nfrom pandas.errors import PerformanceWarning, NullFrequencyError\nfrom pandas import (Timestamp, Timedelta, Series,\n DatetimeIndex, TimedeltaIndex,\n date_range)\nfrom pandas._libs import tslib\nfrom pandas._libs.tslibs.offsets import shift_months\n\n\[email protected](params=[None, 'UTC', 'Asia/Tokyo',\n 'US/Eastern', 'dateutil/Asia/Singapore',\n 'dateutil/US/Pacific'])\ndef tz(request):\n return request.param\n\n\[email protected](params=[pd.offsets.Hour(2), timedelta(hours=2),\n np.timedelta64(2, 'h'), Timedelta(hours=2)],\n ids=str)\ndef delta(request):\n # Several ways of representing two hours\n return request.param\n\n\[email protected](\n params=[\n datetime(2011, 1, 1),\n DatetimeIndex(['2011-01-01', '2011-01-02']),\n DatetimeIndex(['2011-01-01', '2011-01-02']).tz_localize('US/Eastern'),\n np.datetime64('2011-01-01'),\n Timestamp('2011-01-01')],\n ids=lambda x: type(x).__name__)\ndef addend(request):\n return request.param\n\n\nclass TestDatetimeIndexComparisons(object):\n @pytest.mark.parametrize('other', [datetime(2016, 1, 1),\n Timestamp('2016-01-01'),\n np.datetime64('2016-01-01')])\n def test_dti_cmp_datetimelike(self, other, tz):\n dti = pd.date_range('2016-01-01', periods=2, tz=tz)\n if tz is not None:\n if isinstance(other, np.datetime64):\n # no tzaware version available\n return\n elif isinstance(other, Timestamp):\n other = other.tz_localize(dti.tzinfo)\n else:\n other = tslib._localize_pydatetime(other, dti.tzinfo)\n\n result = dti == other\n expected = np.array([True, False])\n tm.assert_numpy_array_equal(result, expected)\n\n result = dti > other\n expected = np.array([False, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = dti >= other\n expected = np.array([True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = dti < other\n expected = np.array([False, False])\n tm.assert_numpy_array_equal(result, expected)\n\n result = dti <= other\n expected = np.array([True, False])\n tm.assert_numpy_array_equal(result, expected)\n\n def dti_cmp_non_datetime(self, tz):\n # GH#19301 by convention datetime.date is not considered comparable\n # to Timestamp or DatetimeIndex. This may change in the future.\n dti = pd.date_range('2016-01-01', periods=2, tz=tz)\n\n other = datetime(2016, 1, 1).date()\n assert not (dti == other).any()\n assert (dti != other).all()\n with pytest.raises(TypeError):\n dti < other\n with pytest.raises(TypeError):\n dti <= other\n with pytest.raises(TypeError):\n dti > other\n with pytest.raises(TypeError):\n dti >= other\n\n @pytest.mark.parametrize('other', [None, np.nan, pd.NaT])\n def test_dti_eq_null_scalar(self, other, tz):\n # GH#19301\n dti = pd.date_range('2016-01-01', periods=2, tz=tz)\n assert not (dti == other).any()\n\n @pytest.mark.parametrize('other', [None, np.nan, pd.NaT])\n def test_dti_ne_null_scalar(self, other, tz):\n # GH#19301\n dti = pd.date_range('2016-01-01', periods=2, tz=tz)\n assert (dti != other).all()\n\n @pytest.mark.parametrize('other', [None, np.nan])\n def test_dti_cmp_null_scalar_inequality(self, tz, other):\n # GH#19301\n dti = pd.date_range('2016-01-01', periods=2, tz=tz)\n\n with pytest.raises(TypeError):\n dti < other\n with pytest.raises(TypeError):\n dti <= other\n with pytest.raises(TypeError):\n dti > other\n with pytest.raises(TypeError):\n dti >= other\n\n def test_dti_cmp_nat(self):\n left = pd.DatetimeIndex([pd.Timestamp('2011-01-01'), pd.NaT,\n pd.Timestamp('2011-01-03')])\n right = pd.DatetimeIndex([pd.NaT, pd.NaT, pd.Timestamp('2011-01-03')])\n\n for lhs, rhs in [(left, right),\n (left.astype(object), right.astype(object))]:\n result = rhs == lhs\n expected = np.array([False, False, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = lhs != rhs\n expected = np.array([True, True, False])\n tm.assert_numpy_array_equal(result, expected)\n\n expected = np.array([False, False, False])\n tm.assert_numpy_array_equal(lhs == pd.NaT, expected)\n tm.assert_numpy_array_equal(pd.NaT == rhs, expected)\n\n expected = np.array([True, True, True])\n tm.assert_numpy_array_equal(lhs != pd.NaT, expected)\n tm.assert_numpy_array_equal(pd.NaT != lhs, expected)\n\n expected = np.array([False, False, False])\n tm.assert_numpy_array_equal(lhs < pd.NaT, expected)\n tm.assert_numpy_array_equal(pd.NaT > lhs, expected)\n\n def test_dti_cmp_nat_behaves_like_float_cmp_nan(self):\n fidx1 = pd.Index([1.0, np.nan, 3.0, np.nan, 5.0, 7.0])\n fidx2 = pd.Index([2.0, 3.0, np.nan, np.nan, 6.0, 7.0])\n\n didx1 = pd.DatetimeIndex(['2014-01-01', pd.NaT, '2014-03-01', pd.NaT,\n '2014-05-01', '2014-07-01'])\n didx2 = pd.DatetimeIndex(['2014-02-01', '2014-03-01', pd.NaT, pd.NaT,\n '2014-06-01', '2014-07-01'])\n darr = np.array([np_datetime64_compat('2014-02-01 00:00Z'),\n np_datetime64_compat('2014-03-01 00:00Z'),\n np_datetime64_compat('nat'), np.datetime64('nat'),\n np_datetime64_compat('2014-06-01 00:00Z'),\n np_datetime64_compat('2014-07-01 00:00Z')])\n\n cases = [(fidx1, fidx2), (didx1, didx2), (didx1, darr)]\n\n # Check pd.NaT is handles as the same as np.nan\n with tm.assert_produces_warning(None):\n for idx1, idx2 in cases:\n\n result = idx1 < idx2\n expected = np.array([True, False, False, False, True, False])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx2 > idx1\n expected = np.array([True, False, False, False, True, False])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 <= idx2\n expected = np.array([True, False, False, False, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx2 >= idx1\n expected = np.array([True, False, False, False, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 == idx2\n expected = np.array([False, False, False, False, False, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 != idx2\n expected = np.array([True, True, True, True, True, False])\n tm.assert_numpy_array_equal(result, expected)\n\n with tm.assert_produces_warning(None):\n for idx1, val in [(fidx1, np.nan), (didx1, pd.NaT)]:\n result = idx1 < val\n expected = np.array([False, False, False, False, False, False])\n tm.assert_numpy_array_equal(result, expected)\n result = idx1 > val\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 <= val\n tm.assert_numpy_array_equal(result, expected)\n result = idx1 >= val\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 == val\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 != val\n expected = np.array([True, True, True, True, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n # Check pd.NaT is handles as the same as np.nan\n with tm.assert_produces_warning(None):\n for idx1, val in [(fidx1, 3), (didx1, datetime(2014, 3, 1))]:\n result = idx1 < val\n expected = np.array([True, False, False, False, False, False])\n tm.assert_numpy_array_equal(result, expected)\n result = idx1 > val\n expected = np.array([False, False, False, False, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 <= val\n expected = np.array([True, False, True, False, False, False])\n tm.assert_numpy_array_equal(result, expected)\n result = idx1 >= val\n expected = np.array([False, False, True, False, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 == val\n expected = np.array([False, False, True, False, False, False])\n tm.assert_numpy_array_equal(result, expected)\n\n result = idx1 != val\n expected = np.array([True, True, False, True, True, True])\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize('op', [operator.eq, operator.ne,\n operator.gt, operator.ge,\n operator.lt, operator.le])\n def test_comparison_tzawareness_compat(self, op):\n # GH#18162\n dr = pd.date_range('2016-01-01', periods=6)\n dz = dr.tz_localize('US/Pacific')\n\n with pytest.raises(TypeError):\n op(dr, dz)\n with pytest.raises(TypeError):\n op(dr, list(dz))\n with pytest.raises(TypeError):\n op(dz, dr)\n with pytest.raises(TypeError):\n op(dz, list(dr))\n\n # Check that there isn't a problem aware-aware and naive-naive do not\n # raise\n assert (dr == dr).all()\n assert (dr == list(dr)).all()\n assert (dz == dz).all()\n assert (dz == list(dz)).all()\n\n # Check comparisons against scalar Timestamps\n ts = pd.Timestamp('2000-03-14 01:59')\n ts_tz = pd.Timestamp('2000-03-14 01:59', tz='Europe/Amsterdam')\n\n assert (dr > ts).all()\n with pytest.raises(TypeError):\n op(dr, ts_tz)\n\n assert (dz > ts_tz).all()\n with pytest.raises(TypeError):\n op(dz, ts)\n\n @pytest.mark.parametrize('op', [operator.eq, operator.ne,\n operator.gt, operator.ge,\n operator.lt, operator.le])\n def test_nat_comparison_tzawareness(self, op):\n # GH#19276\n # tzaware DatetimeIndex should not raise when compared to NaT\n dti = pd.DatetimeIndex(['2014-01-01', pd.NaT, '2014-03-01', pd.NaT,\n '2014-05-01', '2014-07-01'])\n expected = np.array([op == operator.ne] * len(dti))\n result = op(dti, pd.NaT)\n tm.assert_numpy_array_equal(result, expected)\n\n result = op(dti.tz_localize('US/Pacific'), pd.NaT)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_dti_cmp_int_raises(self):\n rng = date_range('1/1/2000', periods=10)\n\n # raise TypeError for now\n with pytest.raises(TypeError):\n rng < rng[3].value\n\n def test_dti_cmp_list(self):\n rng = date_range('1/1/2000', periods=10)\n\n result = rng == list(rng)\n expected = rng == rng\n tm.assert_numpy_array_equal(result, expected)\n\n\nclass TestDatetimeIndexArithmetic(object):\n\n def test_dti_add_timestamp_raises(self):\n idx = DatetimeIndex(['2011-01-01', '2011-01-02'])\n msg = \"cannot add DatetimeIndex and Timestamp\"\n with tm.assert_raises_regex(TypeError, msg):\n idx + Timestamp('2011-01-01')\n\n def test_dti_radd_timestamp_raises(self):\n idx = DatetimeIndex(['2011-01-01', '2011-01-02'])\n msg = \"cannot add DatetimeIndex and Timestamp\"\n with tm.assert_raises_regex(TypeError, msg):\n Timestamp('2011-01-01') + idx\n\n # -------------------------------------------------------------\n # Binary operations DatetimeIndex and int\n\n def test_dti_add_int(self, tz, one):\n # Variants of `one` for #19012\n rng = pd.date_range('2000-01-01 09:00', freq='H',\n periods=10, tz=tz)\n result = rng + one\n expected = pd.date_range('2000-01-01 10:00', freq='H',\n periods=10, tz=tz)\n tm.assert_index_equal(result, expected)\n\n def test_dti_iadd_int(self, tz, one):\n rng = pd.date_range('2000-01-01 09:00', freq='H',\n periods=10, tz=tz)\n expected = pd.date_range('2000-01-01 10:00', freq='H',\n periods=10, tz=tz)\n rng += one\n tm.assert_index_equal(rng, expected)\n\n def test_dti_sub_int(self, tz, one):\n rng = pd.date_range('2000-01-01 09:00', freq='H',\n periods=10, tz=tz)\n result = rng - one\n expected = pd.date_range('2000-01-01 08:00', freq='H',\n periods=10, tz=tz)\n tm.assert_index_equal(result, expected)\n\n def test_dti_isub_int(self, tz, one):\n rng = pd.date_range('2000-01-01 09:00', freq='H',\n periods=10, tz=tz)\n expected = pd.date_range('2000-01-01 08:00', freq='H',\n periods=10, tz=tz)\n rng -= one\n tm.assert_index_equal(rng, expected)\n\n # -------------------------------------------------------------\n # DatetimeIndex.shift is used in integer addition\n\n def test_dti_shift_tzaware(self, tz):\n # GH#9903\n idx = pd.DatetimeIndex([], name='xxx', tz=tz)\n tm.assert_index_equal(idx.shift(0, freq='H'), idx)\n tm.assert_index_equal(idx.shift(3, freq='H'), idx)\n\n idx = pd.DatetimeIndex(['2011-01-01 10:00', '2011-01-01 11:00'\n '2011-01-01 12:00'], name='xxx', tz=tz)\n tm.assert_index_equal(idx.shift(0, freq='H'), idx)\n exp = pd.DatetimeIndex(['2011-01-01 13:00', '2011-01-01 14:00'\n '2011-01-01 15:00'], name='xxx', tz=tz)\n tm.assert_index_equal(idx.shift(3, freq='H'), exp)\n exp = pd.DatetimeIndex(['2011-01-01 07:00', '2011-01-01 08:00'\n '2011-01-01 09:00'], name='xxx', tz=tz)\n tm.assert_index_equal(idx.shift(-3, freq='H'), exp)\n\n def test_dti_shift_freqs(self):\n # test shift for DatetimeIndex and non DatetimeIndex\n # GH#8083\n drange = pd.date_range('20130101', periods=5)\n result = drange.shift(1)\n expected = pd.DatetimeIndex(['2013-01-02', '2013-01-03', '2013-01-04',\n '2013-01-05',\n '2013-01-06'], freq='D')\n tm.assert_index_equal(result, expected)\n\n result = drange.shift(-1)\n expected = pd.DatetimeIndex(['2012-12-31', '2013-01-01', '2013-01-02',\n '2013-01-03', '2013-01-04'],\n freq='D')\n tm.assert_index_equal(result, expected)\n\n result = drange.shift(3, freq='2D')\n expected = pd.DatetimeIndex(['2013-01-07', '2013-01-08', '2013-01-09',\n '2013-01-10',\n '2013-01-11'], freq='D')\n tm.assert_index_equal(result, expected)\n\n def test_dti_shift_int(self):\n rng = date_range('1/1/2000', periods=20)\n\n result = rng + 5\n expected = rng.shift(5)\n tm.assert_index_equal(result, expected)\n\n result = rng - 5\n expected = rng.shift(-5)\n tm.assert_index_equal(result, expected)\n\n def test_dti_shift_no_freq(self):\n # GH#19147\n dti = pd.DatetimeIndex(['2011-01-01 10:00', '2011-01-01'], freq=None)\n with pytest.raises(NullFrequencyError):\n dti.shift(2)\n\n @pytest.mark.parametrize('tzstr', ['US/Eastern', 'dateutil/US/Eastern'])\n def test_dti_shift_localized(self, tzstr):\n dr = date_range('2011/1/1', '2012/1/1', freq='W-FRI')\n dr_tz = dr.tz_localize(tzstr)\n\n result = dr_tz.shift(1, '10T')\n assert result.tz == dr_tz.tz\n\n # -------------------------------------------------------------\n # Binary operations DatetimeIndex and timedelta-like\n\n def test_dti_add_timedeltalike(self, tz, delta):\n rng = pd.date_range('2000-01-01', '2000-02-01', tz=tz)\n result = rng + delta\n expected = pd.date_range('2000-01-01 02:00',\n '2000-02-01 02:00', tz=tz)\n tm.assert_index_equal(result, expected)\n\n def test_dti_iadd_timedeltalike(self, tz, delta):\n rng = pd.date_range('2000-01-01', '2000-02-01', tz=tz)\n expected = pd.date_range('2000-01-01 02:00',\n '2000-02-01 02:00', tz=tz)\n rng += delta\n tm.assert_index_equal(rng, expected)\n\n def test_dti_sub_timedeltalike(self, tz, delta):\n rng = pd.date_range('2000-01-01', '2000-02-01', tz=tz)\n expected = pd.date_range('1999-12-31 22:00',\n '2000-01-31 22:00', tz=tz)\n result = rng - delta\n tm.assert_index_equal(result, expected)\n\n def test_dti_isub_timedeltalike(self, tz, delta):\n rng = pd.date_range('2000-01-01', '2000-02-01', tz=tz)\n expected = pd.date_range('1999-12-31 22:00',\n '2000-01-31 22:00', tz=tz)\n rng -= delta\n tm.assert_index_equal(rng, expected)\n\n # -------------------------------------------------------------\n # Binary operations DatetimeIndex and TimedeltaIndex/array\n def test_dti_add_tdi(self, tz):\n # GH 17558\n dti = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)\n tdi = pd.timedelta_range('0 days', periods=10)\n expected = pd.date_range('2017-01-01', periods=10, tz=tz)\n\n # add with TimdeltaIndex\n result = dti + tdi\n tm.assert_index_equal(result, expected)\n\n result = tdi + dti\n tm.assert_index_equal(result, expected)\n\n # add with timedelta64 array\n result = dti + tdi.values\n tm.assert_index_equal(result, expected)\n\n result = tdi.values + dti\n tm.assert_index_equal(result, expected)\n\n def test_dti_iadd_tdi(self, tz):\n # GH 17558\n dti = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)\n tdi = pd.timedelta_range('0 days', periods=10)\n expected = pd.date_range('2017-01-01', periods=10, tz=tz)\n\n # iadd with TimdeltaIndex\n result = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)\n result += tdi\n tm.assert_index_equal(result, expected)\n\n result = pd.timedelta_range('0 days', periods=10)\n result += dti\n tm.assert_index_equal(result, expected)\n\n # iadd with timedelta64 array\n result = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)\n result += tdi.values\n tm.assert_index_equal(result, expected)\n\n result = pd.timedelta_range('0 days', periods=10)\n result += dti\n tm.assert_index_equal(result, expected)\n\n def test_dti_sub_tdi(self, tz):\n # GH 17558\n dti = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)\n tdi = pd.timedelta_range('0 days', periods=10)\n expected = pd.date_range('2017-01-01', periods=10, tz=tz, freq='-1D')\n\n # sub with TimedeltaIndex\n result = dti - tdi\n tm.assert_index_equal(result, expected)\n\n msg = 'cannot subtract TimedeltaIndex and DatetimeIndex'\n with tm.assert_raises_regex(TypeError, msg):\n tdi - dti\n\n # sub with timedelta64 array\n result = dti - tdi.values\n tm.assert_index_equal(result, expected)\n\n msg = 'cannot perform __neg__ with this index type:'\n with tm.assert_raises_regex(TypeError, msg):\n tdi.values - dti\n\n def test_dti_isub_tdi(self, tz):\n # GH 17558\n dti = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)\n tdi = pd.timedelta_range('0 days', periods=10)\n expected = pd.date_range('2017-01-01', periods=10, tz=tz, freq='-1D')\n\n # isub with TimedeltaIndex\n result = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)\n result -= tdi\n tm.assert_index_equal(result, expected)\n\n msg = 'cannot subtract TimedeltaIndex and DatetimeIndex'\n with tm.assert_raises_regex(TypeError, msg):\n tdi -= dti\n\n # isub with timedelta64 array\n result = DatetimeIndex([Timestamp('2017-01-01', tz=tz)] * 10)\n result -= tdi.values\n tm.assert_index_equal(result, expected)\n\n msg = '|'.join(['cannot perform __neg__ with this index type:',\n 'ufunc subtract cannot use operands with types'])\n with tm.assert_raises_regex(TypeError, msg):\n tdi.values -= dti\n\n # -------------------------------------------------------------\n # Binary Operations DatetimeIndex and datetime-like\n # TODO: A couple other tests belong in this section. Move them in\n # A PR where there isn't already a giant diff.\n\n def test_add_datetimelike_and_dti(self, addend):\n # GH#9631\n dti = DatetimeIndex(['2011-01-01', '2011-01-02'])\n msg = 'cannot add DatetimeIndex and {0}'.format(\n type(addend).__name__)\n with tm.assert_raises_regex(TypeError, msg):\n dti + addend\n with tm.assert_raises_regex(TypeError, msg):\n addend + dti\n\n def test_add_datetimelike_and_dti_tz(self, addend):\n # GH#9631\n dti_tz = DatetimeIndex(['2011-01-01',\n '2011-01-02']).tz_localize('US/Eastern')\n msg = 'cannot add DatetimeIndex and {0}'.format(\n type(addend).__name__)\n with tm.assert_raises_regex(TypeError, msg):\n dti_tz + addend\n with tm.assert_raises_regex(TypeError, msg):\n addend + dti_tz\n\n # -------------------------------------------------------------\n\n def test_sub_dti_dti(self):\n # previously performed setop (deprecated in 0.16.0), now changed to\n # return subtraction -> TimeDeltaIndex (GH ...)\n\n dti = date_range('20130101', periods=3)\n dti_tz = date_range('20130101', periods=3).tz_localize('US/Eastern')\n dti_tz2 = date_range('20130101', periods=3).tz_localize('UTC')\n expected = TimedeltaIndex([0, 0, 0])\n\n result = dti - dti\n tm.assert_index_equal(result, expected)\n\n result = dti_tz - dti_tz\n tm.assert_index_equal(result, expected)\n\n with pytest.raises(TypeError):\n dti_tz - dti\n\n with pytest.raises(TypeError):\n dti - dti_tz\n\n with pytest.raises(TypeError):\n dti_tz - dti_tz2\n\n # isub\n dti -= dti\n tm.assert_index_equal(dti, expected)\n\n # different length raises ValueError\n dti1 = date_range('20130101', periods=3)\n dti2 = date_range('20130101', periods=4)\n with pytest.raises(ValueError):\n dti1 - dti2\n\n # NaN propagation\n dti1 = DatetimeIndex(['2012-01-01', np.nan, '2012-01-03'])\n dti2 = DatetimeIndex(['2012-01-02', '2012-01-03', np.nan])\n expected = TimedeltaIndex(['1 days', np.nan, np.nan])\n result = dti2 - dti1\n tm.assert_index_equal(result, expected)\n\n @pytest.mark.parametrize('freq', [None, 'D'])\n def test_sub_period(self, freq):\n # GH#13078\n # not supported, check TypeError\n p = pd.Period('2011-01-01', freq='D')\n\n idx = pd.DatetimeIndex(['2011-01-01', '2011-01-02'], freq=freq)\n\n with pytest.raises(TypeError):\n idx - p\n\n with pytest.raises(TypeError):\n p - idx\n\n def test_ufunc_coercions(self):\n idx = date_range('2011-01-01', periods=3, freq='2D', name='x')\n\n delta = np.timedelta64(1, 'D')\n for result in [idx + delta, np.add(idx, delta)]:\n assert isinstance(result, DatetimeIndex)\n exp = date_range('2011-01-02', periods=3, freq='2D', name='x')\n tm.assert_index_equal(result, exp)\n assert result.freq == '2D'\n\n for result in [idx - delta, np.subtract(idx, delta)]:\n assert isinstance(result, DatetimeIndex)\n exp = date_range('2010-12-31', periods=3, freq='2D', name='x')\n tm.assert_index_equal(result, exp)\n assert result.freq == '2D'\n\n delta = np.array([np.timedelta64(1, 'D'), np.timedelta64(2, 'D'),\n np.timedelta64(3, 'D')])\n for result in [idx + delta, np.add(idx, delta)]:\n assert isinstance(result, DatetimeIndex)\n exp = DatetimeIndex(['2011-01-02', '2011-01-05', '2011-01-08'],\n freq='3D', name='x')\n tm.assert_index_equal(result, exp)\n assert result.freq == '3D'\n\n for result in [idx - delta, np.subtract(idx, delta)]:\n assert isinstance(result, DatetimeIndex)\n exp = DatetimeIndex(['2010-12-31', '2011-01-01', '2011-01-02'],\n freq='D', name='x')\n tm.assert_index_equal(result, exp)\n assert result.freq == 'D'\n\n def test_datetimeindex_sub_timestamp_overflow(self):\n dtimax = pd.to_datetime(['now', pd.Timestamp.max])\n dtimin = pd.to_datetime(['now', pd.Timestamp.min])\n\n tsneg = Timestamp('1950-01-01')\n ts_neg_variants = [tsneg,\n tsneg.to_pydatetime(),\n tsneg.to_datetime64().astype('datetime64[ns]'),\n tsneg.to_datetime64().astype('datetime64[D]')]\n\n tspos = Timestamp('1980-01-01')\n ts_pos_variants = [tspos,\n tspos.to_pydatetime(),\n tspos.to_datetime64().astype('datetime64[ns]'),\n tspos.to_datetime64().astype('datetime64[D]')]\n\n for variant in ts_neg_variants:\n with pytest.raises(OverflowError):\n dtimax - variant\n\n expected = pd.Timestamp.max.value - tspos.value\n for variant in ts_pos_variants:\n res = dtimax - variant\n assert res[1].value == expected\n\n expected = pd.Timestamp.min.value - tsneg.value\n for variant in ts_neg_variants:\n res = dtimin - variant\n assert res[1].value == expected\n\n for variant in ts_pos_variants:\n with pytest.raises(OverflowError):\n dtimin - variant\n\n @pytest.mark.parametrize('names', [('foo', None, None),\n ('baz', 'bar', None),\n ('bar', 'bar', 'bar')])\n @pytest.mark.parametrize('tz', [None, 'America/Chicago'])\n def test_dti_add_series(self, tz, names):\n # GH#13905\n index = DatetimeIndex(['2016-06-28 05:30', '2016-06-28 05:31'],\n tz=tz, name=names[0])\n ser = Series([Timedelta(seconds=5)] * 2,\n index=index, name=names[1])\n expected = Series(index + Timedelta(seconds=5),\n index=index, name=names[2])\n\n # passing name arg isn't enough when names[2] is None\n expected.name = names[2]\n assert expected.dtype == index.dtype\n result = ser + index\n tm.assert_series_equal(result, expected)\n result2 = index + ser\n tm.assert_series_equal(result2, expected)\n\n expected = index + Timedelta(seconds=5)\n result3 = ser.values + index\n tm.assert_index_equal(result3, expected)\n result4 = index + ser.values\n tm.assert_index_equal(result4, expected)\n\n def test_dti_add_offset_array(self, tz):\n # GH#18849\n dti = pd.date_range('2017-01-01', periods=2, tz=tz)\n other = np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])\n\n with tm.assert_produces_warning(PerformanceWarning):\n res = dti + other\n expected = DatetimeIndex([dti[n] + other[n] for n in range(len(dti))],\n name=dti.name, freq='infer')\n tm.assert_index_equal(res, expected)\n\n with tm.assert_produces_warning(PerformanceWarning):\n res2 = other + dti\n tm.assert_index_equal(res2, expected)\n\n @pytest.mark.parametrize('names', [(None, None, None),\n ('foo', 'bar', None),\n ('foo', 'foo', 'foo')])\n def test_dti_add_offset_index(self, tz, names):\n # GH#18849, GH#19744\n dti = pd.date_range('2017-01-01', periods=2, tz=tz, name=names[0])\n other = pd.Index([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)],\n name=names[1])\n\n with tm.assert_produces_warning(PerformanceWarning):\n res = dti + other\n expected = DatetimeIndex([dti[n] + other[n] for n in range(len(dti))],\n name=names[2], freq='infer')\n tm.assert_index_equal(res, expected)\n\n with tm.assert_produces_warning(PerformanceWarning):\n res2 = other + dti\n tm.assert_index_equal(res2, expected)\n\n def test_dti_sub_offset_array(self, tz):\n # GH#18824\n dti = pd.date_range('2017-01-01', periods=2, tz=tz)\n other = np.array([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)])\n\n with tm.assert_produces_warning(PerformanceWarning):\n res = dti - other\n expected = DatetimeIndex([dti[n] - other[n] for n in range(len(dti))],\n name=dti.name, freq='infer')\n tm.assert_index_equal(res, expected)\n\n @pytest.mark.parametrize('names', [(None, None, None),\n ('foo', 'bar', None),\n ('foo', 'foo', 'foo')])\n def test_dti_sub_offset_index(self, tz, names):\n # GH#18824, GH#19744\n dti = pd.date_range('2017-01-01', periods=2, tz=tz, name=names[0])\n other = pd.Index([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)],\n name=names[1])\n\n with tm.assert_produces_warning(PerformanceWarning):\n res = dti - other\n expected = DatetimeIndex([dti[n] - other[n] for n in range(len(dti))],\n name=names[2], freq='infer')\n tm.assert_index_equal(res, expected)\n\n @pytest.mark.parametrize('names', [(None, None, None),\n ('foo', 'bar', None),\n ('foo', 'foo', 'foo')])\n def test_dti_with_offset_series(self, tz, names):\n # GH#18849\n dti = pd.date_range('2017-01-01', periods=2, tz=tz, name=names[0])\n other = Series([pd.offsets.MonthEnd(), pd.offsets.Day(n=2)],\n name=names[1])\n\n expected_add = Series([dti[n] + other[n] for n in range(len(dti))],\n name=names[2])\n\n with tm.assert_produces_warning(PerformanceWarning):\n res = dti + other\n tm.assert_series_equal(res, expected_add)\n\n with tm.assert_produces_warning(PerformanceWarning):\n res2 = other + dti\n tm.assert_series_equal(res2, expected_add)\n\n expected_sub = Series([dti[n] - other[n] for n in range(len(dti))],\n name=names[2])\n\n with tm.assert_produces_warning(PerformanceWarning):\n res3 = dti - other\n tm.assert_series_equal(res3, expected_sub)\n\n def test_dti_add_offset_tzaware(self):\n dates = date_range('2012-11-01', periods=3, tz='US/Pacific')\n offset = dates + pd.offsets.Hour(5)\n assert dates[0] + pd.offsets.Hour(5) == offset[0]\n\n # GH#6818\n for tz in ['UTC', 'US/Pacific', 'Asia/Tokyo']:\n dates = date_range('2010-11-01 00:00', periods=3, tz=tz, freq='H')\n expected = DatetimeIndex(['2010-11-01 05:00', '2010-11-01 06:00',\n '2010-11-01 07:00'], freq='H', tz=tz)\n\n offset = dates + pd.offsets.Hour(5)\n tm.assert_index_equal(offset, expected)\n offset = dates + np.timedelta64(5, 'h')\n tm.assert_index_equal(offset, expected)\n offset = dates + timedelta(hours=5)\n tm.assert_index_equal(offset, expected)\n\n\[email protected]('klass,assert_func', [\n (Series, tm.assert_series_equal),\n (DatetimeIndex, tm.assert_index_equal)])\ndef test_dt64_with_offset_array(klass, assert_func):\n # GH#10699\n # array of offsets\n box = Series if klass is Series else pd.Index\n with tm.assert_produces_warning(PerformanceWarning):\n s = klass([Timestamp('2000-1-1'), Timestamp('2000-2-1')])\n result = s + box([pd.offsets.DateOffset(years=1),\n pd.offsets.MonthEnd()])\n exp = klass([Timestamp('2001-1-1'), Timestamp('2000-2-29')])\n assert_func(result, exp)\n\n # same offset\n result = s + box([pd.offsets.DateOffset(years=1),\n pd.offsets.DateOffset(years=1)])\n exp = klass([Timestamp('2001-1-1'), Timestamp('2001-2-1')])\n assert_func(result, exp)\n\n\[email protected]('klass,assert_func', [\n (Series, tm.assert_series_equal),\n (DatetimeIndex, tm.assert_index_equal)])\ndef test_dt64_with_DateOffsets_relativedelta(klass, assert_func):\n # GH#10699\n vec = klass([Timestamp('2000-01-05 00:15:00'),\n Timestamp('2000-01-31 00:23:00'),\n Timestamp('2000-01-01'),\n Timestamp('2000-03-31'),\n Timestamp('2000-02-29'),\n Timestamp('2000-12-31'),\n Timestamp('2000-05-15'),\n Timestamp('2001-06-15')])\n\n # DateOffset relativedelta fastpath\n relative_kwargs = [('years', 2), ('months', 5), ('days', 3),\n ('hours', 5), ('minutes', 10), ('seconds', 2),\n ('microseconds', 5)]\n for i, kwd in enumerate(relative_kwargs):\n op = pd.DateOffset(**dict([kwd]))\n assert_func(klass([x + op for x in vec]), vec + op)\n assert_func(klass([x - op for x in vec]), vec - op)\n op = pd.DateOffset(**dict(relative_kwargs[:i + 1]))\n assert_func(klass([x + op for x in vec]), vec + op)\n assert_func(klass([x - op for x in vec]), vec - op)\n\n\[email protected]('cls_and_kwargs', [\n 'YearBegin', ('YearBegin', {'month': 5}),\n 'YearEnd', ('YearEnd', {'month': 5}),\n 'MonthBegin', 'MonthEnd',\n 'SemiMonthEnd', 'SemiMonthBegin',\n 'Week', ('Week', {'weekday': 3}),\n 'BusinessDay', 'BDay', 'QuarterEnd', 'QuarterBegin',\n 'CustomBusinessDay', 'CDay', 'CBMonthEnd',\n 'CBMonthBegin', 'BMonthBegin', 'BMonthEnd',\n 'BusinessHour', 'BYearBegin', 'BYearEnd',\n 'BQuarterBegin', ('LastWeekOfMonth', {'weekday': 2}),\n ('FY5253Quarter', {'qtr_with_extra_week': 1,\n 'startingMonth': 1,\n 'weekday': 2,\n 'variation': 'nearest'}),\n ('FY5253', {'weekday': 0, 'startingMonth': 2, 'variation': 'nearest'}),\n ('WeekOfMonth', {'weekday': 2, 'week': 2}),\n 'Easter', ('DateOffset', {'day': 4}),\n ('DateOffset', {'month': 5})])\[email protected]('normalize', [True, False])\[email protected]('klass,assert_func', [\n (Series, tm.assert_series_equal),\n (DatetimeIndex, tm.assert_index_equal)])\ndef test_dt64_with_DateOffsets(klass, assert_func, normalize, cls_and_kwargs):\n # GH#10699\n # assert these are equal on a piecewise basis\n vec = klass([Timestamp('2000-01-05 00:15:00'),\n Timestamp('2000-01-31 00:23:00'),\n Timestamp('2000-01-01'),\n Timestamp('2000-03-31'),\n Timestamp('2000-02-29'),\n Timestamp('2000-12-31'),\n Timestamp('2000-05-15'),\n Timestamp('2001-06-15')])\n\n if isinstance(cls_and_kwargs, tuple):\n # If cls_name param is a tuple, then 2nd entry is kwargs for\n # the offset constructor\n cls_name, kwargs = cls_and_kwargs\n else:\n cls_name = cls_and_kwargs\n kwargs = {}\n\n offset_cls = getattr(pd.offsets, cls_name)\n\n with warnings.catch_warnings(record=True):\n for n in [0, 5]:\n if (cls_name in ['WeekOfMonth', 'LastWeekOfMonth',\n 'FY5253Quarter', 'FY5253'] and n == 0):\n # passing n = 0 is invalid for these offset classes\n continue\n\n offset = offset_cls(n, normalize=normalize, **kwargs)\n assert_func(klass([x + offset for x in vec]), vec + offset)\n assert_func(klass([x - offset for x in vec]), vec - offset)\n assert_func(klass([offset + x for x in vec]), offset + vec)\n\n\n# GH 10699\[email protected]('klass,assert_func', zip([Series, DatetimeIndex],\n [tm.assert_series_equal,\n tm.assert_index_equal]))\ndef test_datetime64_with_DateOffset(klass, assert_func):\n s = klass(date_range('2000-01-01', '2000-01-31'), name='a')\n result = s + pd.DateOffset(years=1)\n result2 = pd.DateOffset(years=1) + s\n exp = klass(date_range('2001-01-01', '2001-01-31'), name='a')\n assert_func(result, exp)\n assert_func(result2, exp)\n\n result = s - pd.DateOffset(years=1)\n exp = klass(date_range('1999-01-01', '1999-01-31'), name='a')\n assert_func(result, exp)\n\n s = klass([Timestamp('2000-01-15 00:15:00', tz='US/Central'),\n pd.Timestamp('2000-02-15', tz='US/Central')], name='a')\n result = s + pd.offsets.Day()\n result2 = pd.offsets.Day() + s\n exp = klass([Timestamp('2000-01-16 00:15:00', tz='US/Central'),\n Timestamp('2000-02-16', tz='US/Central')], name='a')\n assert_func(result, exp)\n assert_func(result2, exp)\n\n s = klass([Timestamp('2000-01-15 00:15:00', tz='US/Central'),\n pd.Timestamp('2000-02-15', tz='US/Central')], name='a')\n result = s + pd.offsets.MonthEnd()\n result2 = pd.offsets.MonthEnd() + s\n exp = klass([Timestamp('2000-01-31 00:15:00', tz='US/Central'),\n Timestamp('2000-02-29', tz='US/Central')], name='a')\n assert_func(result, exp)\n assert_func(result2, exp)\n\n\[email protected]('years', [-1, 0, 1])\[email protected]('months', [-2, 0, 2])\ndef test_shift_months(years, months):\n s = DatetimeIndex([Timestamp('2000-01-05 00:15:00'),\n Timestamp('2000-01-31 00:23:00'),\n Timestamp('2000-01-01'),\n Timestamp('2000-02-29'),\n Timestamp('2000-12-31')])\n actual = DatetimeIndex(shift_months(s.asi8, years * 12 + months))\n\n raw = [x + pd.offsets.DateOffset(years=years, months=months)\n for x in s]\n expected = DatetimeIndex(raw)\n tm.assert_index_equal(actual, expected)\n" ]
[ [ "pandas.to_datetime", "pandas.offsets.Day", "pandas.util.testing.assert_produces_warning", "pandas.offsets.DateOffset", "pandas.util.testing.assert_index_equal", "pandas.util.testing.assert_numpy_array_equal", "pandas.offsets.Hour", "numpy.subtract", "pandas.Index", "pandas.DatetimeIndex", "pandas.util.testing.assert_series_equal", "pandas.offsets.MonthEnd", "pandas._libs.tslibs.offsets.shift_months", "pandas.compat.numpy.np_datetime64_compat", "pandas.Timedelta", "numpy.timedelta64", "pandas.date_range", "numpy.array", "pandas.timedelta_range", "pandas.DateOffset", "pandas.TimedeltaIndex", "pandas.util.testing.assert_raises_regex", "numpy.datetime64", "pandas.Period", "numpy.add", "pandas.Timestamp", "pandas._libs.tslib._localize_pydatetime" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zhangzhenhu/zzh
[ "ebacd9c0c46a0a537d014550bd2bff0a85452a6e" ]
[ "zzh/mllib/model/_deep_fm.py" ]
[ "\"\"\"\nTensorflow implementation of DeepFM\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow.compat.v1 as tf1\nfrom sklearn.base import BaseEstimator, TransformerMixin\nfrom sklearn.metrics import roc_auc_score\nfrom time import time\nfrom tensorflow.contrib.layers.python.layers import batch_norm as batch_norm\nfrom sklearn import metrics\n# from yellowfin import YFOptimizer\nimport os\nimport sys\nimport json\n\n\"\"\"\n关于 X_i 和 X_v\n\n为什么要把训练数据分成两个矩阵?\nFM模型需要为每个特征训练一个embedding vector,\n在模型计算过程中使用 embedding_lookup + index matrix 可以方便计算。\n\n\n\n首先把特征分成两种,一种是不需要one hot(数值类),一种是需要one hot(枚举类)。\n然后定义,one hot 之前的特征称为 field,one hot 之后的特征为 feature。\n\n- X_i 表示 feat_index\n- X_v 表示 feat_value\n\n**feat_index**\n\nfeat_index 存储的是样本的 field 的\"feature索引\",shape=(N,field_size)。\nfeat_index[i,j]表示的是第i个样本第j个field的 feature_index。\n如果当前 field 不需要 one hot,此 field 就只会映射成一个 feature;\n如果当前 field 需要 one hot,此 field 就会被映射成多个 feature ,\n每个枚举值是一个 feature,其实就是进行 one hot 编码。\n\n比如 feat_index[i,j]=c,表示 第i个样本第j个 field 的对应着第c个feature,\nc是 feature_index。\n当然如果 field_j 是数值 field,所有样本的j列都是一样的值,因为 field_j 不需要onehot。\n如果 field_j 需要one hot,c的值就是其原来的枚举值onehot后映射对应的 feature_index。\nfeat_index 是给 embedding_lookup是用的。\n\n**feat_value**\n\nfeat_value 存储的是样本field的\"值\",shape=(N,field_size)。\nfeat_value[i,j]表示的是第i个样本第j个field的值。\n如果当前field 不需要 one hot,feat_value[i,j]就是原始数据值;\n如果当前field 需要 one hot,feat_value[i,j]就是常量1;\n\n\n注意:这里有一个前提条件,就是 one_hot 的 field 变量只能取一个值,一个变量可以有多个取值的情况是不支持的。\n\n\"\"\"\n\n\nclass DeepFM(BaseEstimator, TransformerMixin):\n\n def __init__(self, feature_size, field_size,\n embedding_size=8, dropout_fm=[1.0, 1.0],\n deep_layers=[32, 32], dropout_deep=[0.5, 0.5, 0.5],\n deep_layers_activation=tf.nn.relu,\n epoch=10, batch_size=256,\n learning_rate=0.001, optimizer_type=\"adam\",\n batch_norm=0, batch_norm_decay=0.995,\n verbose=False, random_seed=2016,\n use_fm=True, use_deep=True,\n loss_type=\"logloss\", eval_metric=roc_auc_score,\n l2_reg=0.0, greater_is_better=True, threshold=0.5\n ):\n assert (use_fm or use_deep)\n assert loss_type in [\"logloss\", \"mse\"], \\\n \"loss_type can be either 'logloss' for classification task or 'mse' for regression task\"\n\n self.feature_size = feature_size # 259 denote as M, size of the feature dictionary\n self.field_size = field_size # 39 denote as F, size of the feature fields\n self.embedding_size = embedding_size # 8 denote as K, size of the feature embedding\n\n self.dropout_fm = dropout_fm\n self.deep_layers = deep_layers\n self.dropout_deep = dropout_deep\n self.deep_layers_activation = deep_layers_activation\n self.use_fm = use_fm\n self.use_deep = use_deep\n self.l2_reg = l2_reg\n\n self.epoch = epoch\n self.batch_size = batch_size\n self.learning_rate = learning_rate\n self.optimizer_type = optimizer_type\n\n self.batch_norm = batch_norm\n self.batch_norm_decay = batch_norm_decay\n\n self.verbose = verbose # 是否打印参数总量\n self.random_seed = random_seed\n self.loss_type = loss_type\n self.eval_metric = eval_metric\n self.greater_is_better = greater_is_better # 是否值越大越好\n self.train_result, self.valid_result = [], []\n self.sess = None\n self.graph = None\n self._config = None\n self.threshold = threshold\n\n def _make_config_pack(self):\n self._config = {\n\n \"feature_size\": self.feature_size, # 259 denote as M, size of the feature dictionary\n \"field_size \": self.field_size, # 39 denote as F, size of the feature fields\n \"embedding_size \": self.embedding_size, # 8 denote as K, size of the feature embedding\n\n \"dropout_fm \": self.dropout_fm,\n \"deep_layers \": self.deep_layers,\n \"dropout_deep \": self.dropout_deep,\n \"deep_layers_activation \": self.deep_layers_activation,\n \"use_fm \": self.use_fm,\n \"use_deep \": self.use_deep,\n \"l2_reg \": self.l2_reg,\n\n \"epoch \": self.epoch,\n \"batch_size \": self.batch_size,\n \"learning_rate \": self.learning_rate,\n \"optimizer_type \": self.optimizer_type,\n\n \"batch_norm \": self.batch_norm,\n \"batch_norm_decay \": self.batch_norm_decay,\n\n \"verbose \": self.verbose, # 是否打印参数总量\n \"random_seed \": self.random_seed,\n \"loss_type\": self.loss_type,\n \"eval_metric \": self.eval_metric,\n \"greater_is_better \": self.greater_is_better, # 是否值越大越好\n }\n\n # self.model_path = '%s/deepfm' % (save_path)\n\n # self._init_graph()\n\n def init_graph(self):\n if self.sess is not None:\n return\n self.graph = tf.Graph()\n with self.graph.as_default():\n\n tf1.set_random_seed(self.random_seed)\n\n self.feat_index = tf1.placeholder(tf.int32, shape=[None, None],\n name=\"feat_index\") # None * F\n self.feat_value = tf1.placeholder(tf.float32, shape=[None, None],\n name=\"feat_value\") # None * F\n self.label = tf1.placeholder(tf.float32, shape=[None, 1], name=\"label\") # None * 1\n self.dropout_keep_fm = tf1.placeholder(tf.float32, shape=[None], name=\"dropout_keep_fm\")\n self.dropout_keep_deep = tf1.placeholder(tf.float32, shape=[None], name=\"dropout_keep_deep\")\n self.train_phase = tf1.placeholder(tf.bool, name=\"train_phase\")\n\n self.weights = self._initialize_weights()\n\n # 每一个feature 有一个 embedding\n # feature_embeddings.shape=(self.feature_size, self.embedding_size)\n\n # feat_index[i,j] 存储的是 第i条样本第j个field 对应的 feature_index\n # 1. 如果 field_j 是非 one hot 特征,则 field_j 不需要拆成多个 feature,\n # feat_index[:,j] 所有样本行都是同一个值,对应同一个 feature_index。\n # 2. 如果 field_j 是 one hot 特征,则 field_j 需要拆成多个 feature,每个枚举值独立成一个 feature,\n # 此时 feat_index[:,j] 不同行是不同值,其值表示 枚举值Value(field_j) 对应的 feature_index.\n # 比如,第i=3行样本,第j=5个field表示颜色,其值是红色,红色被 onehot成 feature_index=13.则 feat_index[3,5]=13\n\n # shape=(N样本数量 * field_size * K)\n # N 表示样本的数量\n # K 是嵌入向量的长度,\n # 取出所有样本,每个 feature 的嵌入向量\n # 对于one_hot 的 field,相当于只取出来枚举值对应的 feature_index 的嵌入向量,\n # 相当于每个 field 取一个,最终每条样本嵌入向量的数量还是 field 。\n self.embeddings = tf.nn.embedding_lookup(\n self.weights[\"feature_embeddings\"], # shape=(self.feature_size, self.embedding_size)\n self.feat_index # N * field_size\n )\n # shape=(None * F * 1)\n #\n feat_value = tf.reshape(self.feat_value, shape=[-1, self.field_size, 1]) # None * F * 1\n\n # FM部分的公式是 (x_i * x_j)(v_i*v_j)=(x_i*v_i)(x_j*v_j)\n # 这里先把每个特征的向量乘上其特征值。\n self.embeddings = tf.multiply(self.embeddings, feat_value) # None * F * K\n\n # ---------- first order term ----------\n # 对于k维,tf.reduce_sum(x,axis=k-1)的结果是对最里面一维所有元素进行求和\n self.y_first_order = tf.nn.embedding_lookup(self.weights[\"feature_bias\"], self.feat_index) # None * F * 1\n self.y_first_order = tf.reduce_sum(tf.multiply(self.y_first_order, feat_value), 2) # None * F\n self.y_first_order = tf.nn.dropout(self.y_first_order, rate=1 - self.dropout_keep_fm[0]) # None * F\n\n # ---------- second order term ---------------\n # sum_square part\n self.summed_features_emb = tf.reduce_sum(self.embeddings, 1) # None * K\n self.summed_features_emb_square = tf.square(self.summed_features_emb) # None * K\n\n # square_sum part\n self.squared_features_emb = tf.square(self.embeddings)\n self.squared_sum_features_emb = tf.reduce_sum(self.squared_features_emb, 1) # None * K\n\n # second order\n self.y_second_order = 0.5 * tf.subtract(self.summed_features_emb_square,\n self.squared_sum_features_emb) # None * K\n self.y_second_order = tf.nn.dropout(self.y_second_order, rate=1 - self.dropout_keep_fm[1]) # None * K\n\n # ---------- Deep component ----------\n self.y_deep = tf.reshape(self.embeddings, shape=[-1, self.field_size * self.embedding_size]) # None * (F*K)\n self.y_deep = tf.nn.dropout(self.y_deep, rate=1 - self.dropout_keep_deep[0])\n for i in range(0, len(self.deep_layers)):\n self.y_deep = tf.add(tf.matmul(self.y_deep, self.weights[\"layer_%d\" % i]),\n self.weights[\"bias_%d\" % i]) # None * layer[i] * 1\n if self.batch_norm:\n self.y_deep = self.batch_norm_layer(self.y_deep, train_phase=self.train_phase,\n scope_bn=\"bn_%d\" % i) # None * layer[i] * 1\n self.y_deep = self.deep_layers_activation(self.y_deep)\n self.y_deep = tf.nn.dropout(self.y_deep,\n rate=1 - self.dropout_keep_deep[1 + i]) # dropout at each Deep layer\n\n # ---------- DeepFM ----------\n if self.use_fm and self.use_deep:\n concat_input = tf.concat([self.y_first_order, self.y_second_order, self.y_deep], axis=1)\n elif self.use_fm:\n concat_input = tf.concat([self.y_first_order, self.y_second_order], axis=1)\n elif self.use_deep:\n concat_input = self.y_deep\n self.out = tf.add(tf.matmul(concat_input, self.weights[\"concat_projection\"]), self.weights[\"concat_bias\"])\n\n # loss\n if self.loss_type == \"logloss\":\n self.out = tf.nn.sigmoid(self.out, name='out')\n self.loss = tf1.losses.log_loss(self.label, self.out)\n elif self.loss_type == \"mse\":\n self.loss = tf.nn.l2_loss(tf.subtract(self.label, self.out))\n # l2 regularization on weights 正则\n if self.l2_reg > 0:\n self.loss += tf.contrib.layers.l2_regularizer(\n self.l2_reg)(self.weights[\"concat_projection\"])\n if self.use_deep:\n for i in range(len(self.deep_layers)):\n self.loss += tf.contrib.layers.l2_regularizer(\n self.l2_reg)(self.weights[\"layer_%d\" % i])\n\n # optimizer\n # 这里可以使用现成的ftrl优化损失\n # optimizer = tf.train.FtrlOptimizer(lr) # lr: learningRate\n # gradients = optimizer.compute_gradients(loss) # cost\n # train_op = optimizer.apply_gradients(gradients, global_step=global_step)\n\n if self.optimizer_type == \"adam\":\n self.optimizer = tf1.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=0.9, beta2=0.999,\n epsilon=1e-8).minimize(self.loss)\n elif self.optimizer_type == \"adagrad\":\n self.optimizer = tf1.train.AdagradOptimizer(learning_rate=self.learning_rate,\n initial_accumulator_value=1e-8).minimize(self.loss)\n elif self.optimizer_type == \"gd\":\n self.optimizer = tf1.train.GradientDescentOptimizer(learning_rate=self.learning_rate).minimize(\n self.loss)\n elif self.optimizer_type == \"momentum\":\n self.optimizer = tf1.train.MomentumOptimizer(learning_rate=self.learning_rate, momentum=0.95).minimize(\n self.loss)\n # elif self.optimizer_type == \"yellowfin\":\n # self.optimizer = YFOptimizer(learning_rate=self.learning_rate, momentum=0.0).minimize(\n # self.loss)\n\n # init\n self.saver = tf1.train.Saver()\n init = tf1.global_variables_initializer()\n self.sess = self._init_session()\n self.sess.run(init)\n\n # number of params\n total_parameters = 0\n for variable in self.weights.values():\n shape = variable.get_shape()\n variable_parameters = 1\n for dim in shape:\n variable_parameters *= dim.value\n total_parameters += variable_parameters\n if self.verbose > 0:\n print(\"#params: %d\" % total_parameters)\n\n def _init_session(self):\n config = tf1.ConfigProto(device_count={\"gpu\": 0})\n config.gpu_options.allow_growth = True # 根据运行情况分配GPU内存\n return tf1.Session(config=config)\n\n def _initialize_weights(self):\n weights = dict() # 定义参数字典\n\n # embeddings\n weights[\"feature_embeddings\"] = tf.Variable(\n tf.random.normal([self.feature_size, self.embedding_size], 0.0, 0.01),\n # tf.random_normal([self.feature_size, self.embedding_size], 0.0, 0.01),\n name=\"feature_embeddings\") # feature_size * K\n weights[\"feature_bias\"] = tf.Variable(\n # tf.random_uniform([self.feature_size, 1], 0.0, 1.0), name=\"feature_bias\") # feature_size * 1\n tf.random.uniform([self.feature_size, 1], 0.0, 1.0), name=\"feature_bias\") # feature_size * 1\n\n # deep layers\n num_layer = len(self.deep_layers) # 层数\n input_size = self.field_size * self.embedding_size\n glorot = np.sqrt(2.0 / (input_size + self.deep_layers[0])) # 正态分布的标准差\n weights[\"layer_0\"] = tf.Variable(\n np.random.normal(loc=0, scale=glorot, size=(input_size, self.deep_layers[0])), dtype=np.float32)\n weights[\"bias_0\"] = tf.Variable(np.random.normal(loc=0, scale=glorot, size=(1, self.deep_layers[0])),\n dtype=np.float32) # 1 * layers[0]\n for i in range(1, num_layer):\n glorot = np.sqrt(2.0 / (self.deep_layers[i - 1] + self.deep_layers[i]))\n weights[\"layer_%d\" % i] = tf.Variable(\n np.random.normal(loc=0, scale=glorot, size=(self.deep_layers[i - 1], self.deep_layers[i])),\n dtype=np.float32) # layers[i-1] * layers[i]\n weights[\"bias_%d\" % i] = tf.Variable(\n np.random.normal(loc=0, scale=glorot, size=(1, self.deep_layers[i])),\n dtype=np.float32) # 1 * layer[i]\n\n # final concat projection layer\n if self.use_fm and self.use_deep:\n input_size = self.field_size + self.embedding_size + self.deep_layers[-1]\n elif self.use_fm:\n input_size = self.field_size + self.embedding_size\n elif self.use_deep:\n input_size = self.deep_layers[-1]\n glorot = np.sqrt(2.0 / (input_size + 1))\n weights[\"concat_projection\"] = tf.Variable(\n np.random.normal(loc=0, scale=glorot, size=(input_size, 1)),\n dtype=np.float32) # layers[i-1]*layers[i]\n weights[\"concat_bias\"] = tf.Variable(tf.constant(0.01), dtype=np.float32)\n\n return weights\n\n def batch_norm_layer(self, x, train_phase, scope_bn):\n bn_train = batch_norm(x, decay=self.batch_norm_decay, center=True, scale=True, updates_collections=None,\n is_training=True, reuse=None, trainable=True, scope=scope_bn)\n bn_inference = batch_norm(x, decay=self.batch_norm_decay, center=True, scale=True, updates_collections=None,\n is_training=False, reuse=True, trainable=True, scope=scope_bn)\n z = tf.cond(train_phase, lambda: bn_train, lambda: bn_inference)\n return z\n\n def get_batch(self, Xi, Xv, y, batch_size, index):\n start = index * batch_size\n end = (index + 1) * batch_size\n end = end if end < len(y) else len(y)\n return Xi[start:end], Xv[start:end], [[y_] for y_ in y[start:end]]\n\n # shuffle three lists simutaneously\n def shuffle_in_unison_scary(self, a, b, c):\n rng_state = np.random.get_state()\n np.random.shuffle(a)\n np.random.set_state(rng_state)\n np.random.shuffle(b)\n np.random.set_state(rng_state)\n np.random.shuffle(c)\n\n def fit_on_batch(self, Xi, Xv, y):\n feed_dict = {self.feat_index: Xi,\n self.feat_value: Xv,\n self.label: y,\n self.dropout_keep_fm: self.dropout_fm,\n self.dropout_keep_deep: self.dropout_deep,\n self.train_phase: True}\n out, loss, opt = self.sess.run((self.out, self.loss, self.optimizer), feed_dict=feed_dict)\n return out, loss\n\n def fit(self, Xi_train, Xv_train, y_train,\n Xi_valid=None, Xv_valid=None, y_valid=None,\n early_stopping=False, refit=False):\n \"\"\"\n :param Xi_train: [[ind1_1, ind1_2, ...], [ind2_1, ind2_2, ...], ..., [indi_1, indi_2, ..., indi_j, ...], ...]\n indi_j is the feature index of feature field j of sample i in the training set\n :param Xv_train: [[val1_1, val1_2, ...], [val2_1, val2_2, ...], ..., [vali_1, vali_2, ..., vali_j, ...], ...]\n vali_j is the feature value of feature field j of sample i in the training set\n vali_j can be either binary (1/0, for binary/categorical features) or float (e.g., 10.24, for numerical features)\n :param y_train: label of each sample in the training set\n :param Xi_valid: list of list of feature indices of each sample in the validation set\n :param Xv_valid: list of list of feature values of each sample in the validation set\n :param y_valid: label of each sample in the validation set\n :param early_stopping: perform early stopping or not\n :param refit: refit the model on the train+valid dataset or not\n :return: None\n \"\"\"\n has_valid = Xv_valid is not None\n Xi_train = Xi_train.copy()\n Xv_train = Xv_train.copy()\n y_train = y_train.copy()\n\n for epoch in range(self.epoch):\n t1 = time()\n self.shuffle_in_unison_scary(Xi_train, Xv_train, y_train)\n total_batch = int(len(y_train) / self.batch_size)\n for i in range(total_batch):\n Xi_batch, Xv_batch, y_batch = self.get_batch(Xi_train, Xv_train, y_train, self.batch_size, i)\n trian_out, train_loss = self.fit_on_batch(Xi_batch, Xv_batch, y_batch)\n # print(trian_out, file=sys.stderr)\n if i % 1000 == 0:\n # print(trian_out, file=sys.stderr)\n print(\"epoch:%d batch:%d train_loss=%.4f\" % (epoch, i, train_loss), file=sys.stderr)\n\n # evaluate training and validation datasets\n train_me = self.evaluate(Xi_train, Xv_train, y_train)\n self.train_result.append(train_me)\n if has_valid:\n valid_me = self.evaluate(Xi_valid, Xv_valid, y_valid)\n self.valid_result.append(valid_me)\n\n if self.verbose > 0 and epoch % self.verbose == 0:\n print(\"[%d] [train] auc=%.4f acc=%.4f mse=%.4f precision_1=%.4f recall_1=%.4f [%.1f s]\"\n % (epoch + 1,\n train_me['auc'],\n train_me['acc'],\n train_me['mse'],\n train_me['precision_1'],\n train_me['recall_1'],\n time() - t1))\n\n if has_valid:\n print(\n \"[%d] [valid] auc=%.4f acc=%.4f mse=%.4f precision_1=%.4f recall_1=%.4f [%.1f s]\"\n % (epoch + 1,\n valid_me['auc'],\n valid_me['acc'],\n valid_me['mse'],\n valid_me['precision_1'],\n valid_me['recall_1'],\n time() - t1))\n if has_valid and early_stopping and self.training_termination(self.valid_result):\n break\n\n # fit a few more epoch on train+valid until result reaches the best_train_score\n if has_valid and refit:\n if self.greater_is_better:\n best_valid_score = max(self.valid_result)\n else:\n best_valid_score = min(self.valid_result)\n best_epoch = self.valid_result.index(best_valid_score)\n best_train_score = self.train_result[best_epoch]\n Xi_train = Xi_train + Xi_valid\n Xv_train = Xv_train + Xv_valid\n y_train = y_train + y_valid\n for epoch in range(100):\n self.shuffle_in_unison_scary(Xi_train, Xv_train, y_train)\n total_batch = int(len(y_train) / self.batch_size)\n for i in range(total_batch):\n Xi_batch, Xv_batch, y_batch = self.get_batch(Xi_train, Xv_train, y_train,\n self.batch_size, i)\n self.fit_on_batch(Xi_batch, Xv_batch, y_batch)\n # check\n train_result = self.evaluate(Xi_train, Xv_train, y_train)\n if abs(train_result - best_train_score) < 0.001 or \\\n (self.greater_is_better and train_result > best_train_score) or \\\n ((not self.greater_is_better) and train_result < best_train_score):\n break\n\n def training_termination(self, valid_result):\n if len(valid_result) > 5:\n if self.greater_is_better:\n if valid_result[-1] < valid_result[-2] and \\\n valid_result[-2] < valid_result[-3] and \\\n valid_result[-3] < valid_result[-4] and \\\n valid_result[-4] < valid_result[-5]:\n return True\n else:\n if valid_result[-1] > valid_result[-2] \\\n and valid_result[-2] > valid_result[-3] \\\n and valid_result[-3] > valid_result[-4] \\\n and valid_result[-4] > valid_result[-5]:\n return True\n return False\n\n def predict(self, Xi, Xv):\n \"\"\"\n :param Xi: list of list of feature indices of each sample in the dataset\n :param Xv: list of list of feature values of each sample in the dataset\n :return: predicted probability of each sample\n \"\"\"\n dummy_y = [1] * len(Xi)\n batch_index = 0\n Xi_batch, Xv_batch, y_batch = self.get_batch(Xi, Xv, dummy_y, self.batch_size, batch_index)\n\n y_pred = None\n while len(Xi_batch) > 0:\n num_batch = len(y_batch)\n feed_dict = {self.feat_index: Xi_batch,\n self.feat_value: Xv_batch,\n # self.label: y_batch,\n self.dropout_keep_fm: [1.0] * len(self.dropout_fm),\n self.dropout_keep_deep: [1.0] * len(self.dropout_deep),\n self.train_phase: False}\n batch_out = self.sess.run(self.out, feed_dict=feed_dict)\n\n if batch_index == 0:\n y_pred = np.reshape(batch_out, (num_batch,))\n else:\n y_pred = np.concatenate((y_pred, np.reshape(batch_out, (num_batch,))))\n\n batch_index += 1\n Xi_batch, Xv_batch, y_batch = self.get_batch(Xi, Xv, dummy_y, self.batch_size, batch_index)\n\n return y_pred\n\n def evaluate(self, Xi, Xv, y_true):\n \"\"\"\n :param Xi: list of list of feature indices of each sample in the dataset\n :param Xv: list of list of feature values of each sample in the dataset\n :param y: label of each sample in the dataset\n :return: metric of the evaluation\n \"\"\"\n size = y_true.shape[0]\n y_pred = self.predict(Xi, Xv)\n error = y_true - y_pred\n mse = (error * error).sum() / size\n y_pred_m = y_pred.copy()\n\n y_pred_m[y_pred_m >= self.threshold] = 1\n y_pred_m[y_pred_m < self.threshold] = 0\n\n # accuracy = metrics.accuracy_score(y_true, y_pred_m)\n cm = metrics.confusion_matrix(y_true, y_pred_m, labels=[1, 0])\n # 实际正样本数量\n real_1_count = cm[0, :].sum()\n # 预测为正样本数量\n predict_1_count = cm[:, 0].sum()\n # 正样本 预测正确的数量\n right_1_count = cm[0, 0]\n if predict_1_count == 0:\n precision_1 = 0\n else:\n # 正样本精确率\n precision_1 = right_1_count / predict_1_count\n if real_1_count == 0:\n recall_1 = 0\n else:\n # 正样本召回率\n recall_1 = right_1_count / real_1_count\n\n return {\n \"size\": size,\n \"acc\": (cm[0, 0] + cm[1, 1]) / size,\n # \"实际退费人次\": cm[0, :].sum(),\n # \"预测退费人次\": cm[:, 0].sum(),\n # \"预测正确人次\": cm[0, 0],\n # \"预测错误人次\": cm[1, 0],\n \"precision_1\": precision_1,\n \"recall_1\": recall_1,\n \"auc\": self.eval_metric(y_true, y_pred),\n \"mse\": mse\n }\n\n def save(self, save_path):\n model_prefix = os.path.join(save_path, 'deepfm')\n print(\"Save model...\", save_path, file=sys.stderr)\n self.saver.save(self.sess, model_prefix)\n if self._config is not None:\n config_path = os.path.join(save_path, \"config.json\")\n with open(config_path, 'w') as fp:\n json.dump(fp)\n\n print(\"Save model done.\", save_path, file=sys.stderr)\n\n def load(self, model_path):\n\n if self.sess is not None:\n self.sess.close()\n if self.graph is not None:\n self.graph = None\n model_prefix = os.path.join(model_path, 'deepfm')\n # self.sess = tf.Session()\n # with tf.Session() as sess:\n # print('load model', file=sys.stderr)\n # t1 = time()\n print(\"Load model...\", model_path, file=sys.stderr)\n self.sess = tf1.Session()\n saver = tf1.train.import_meta_graph(model_prefix + '.meta', clear_devices=True)\n saver.restore(self.sess, model_prefix)\n self.feat_index = tf1.get_default_graph().get_tensor_by_name('feat_index:0')\n self.feat_value = tf1.get_default_graph().get_tensor_by_name('feat_value:0')\n self.dropout_keep_fm = tf1.get_default_graph().get_tensor_by_name('dropout_keep_fm:0')\n self.dropout_keep_deep = tf1.get_default_graph().get_tensor_by_name('dropout_keep_deep:0')\n self.train_phase = tf1.get_default_graph().get_tensor_by_name('train_phase:0')\n\n self.out = tf1.get_default_graph().get_tensor_by_name('out:0')\n\n config_path = os.path.join(model_path, \"config.json\")\n if os.path.exists(config_path):\n with open(config_path) as fp:\n self._config = json.load(fp)\n else:\n self._config = None\n\n print(\"Load model done\", model_path, file=sys.stderr)\n" ]
[ [ "tensorflow.cond", "tensorflow.compat.v1.train.import_meta_graph", "tensorflow.concat", "numpy.sqrt", "tensorflow.reduce_sum", "sklearn.metrics.confusion_matrix", "tensorflow.compat.v1.train.Saver", "tensorflow.Graph", "tensorflow.compat.v1.train.AdamOptimizer", "numpy.reshape", "tensorflow.subtract", "numpy.random.set_state", "tensorflow.square", "tensorflow.compat.v1.set_random_seed", "tensorflow.compat.v1.losses.log_loss", "tensorflow.compat.v1.train.GradientDescentOptimizer", "tensorflow.nn.dropout", "tensorflow.matmul", "tensorflow.nn.sigmoid", "tensorflow.random.uniform", "tensorflow.nn.embedding_lookup", "numpy.random.get_state", "tensorflow.compat.v1.get_default_graph", "tensorflow.compat.v1.ConfigProto", "tensorflow.multiply", "tensorflow.constant", "tensorflow.compat.v1.train.AdagradOptimizer", "tensorflow.reshape", "numpy.random.shuffle", "tensorflow.compat.v1.global_variables_initializer", "tensorflow.compat.v1.Session", "tensorflow.contrib.layers.python.layers.batch_norm", "tensorflow.compat.v1.placeholder", "numpy.random.normal", "tensorflow.compat.v1.train.MomentumOptimizer", "tensorflow.contrib.layers.l2_regularizer", "tensorflow.random.normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wenguanwang/ContrastiveSeg
[ "9a381b9799c16d81e18d8f9f25ab509b93fb56de" ]
[ "lib/loss/loss_contrast.py" ]
[ "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom abc import ABC\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom lib.loss.loss_helper import FSAuxCELoss, FSAuxRMILoss\nfrom lib.utils.tools.logger import Logger as Log\n\n\nclass PixelContrastLoss(nn.Module, ABC):\n def __init__(self, configer):\n super(PixelContrastLoss, self).__init__()\n\n self.configer = configer\n self.temperature = self.configer.get('contrast', 'temperature')\n self.base_temperature = self.configer.get('contrast', 'base_temperature')\n\n self.ignore_label = -1\n if self.configer.exists('loss', 'params') and 'ce_ignore_index' in self.configer.get('loss', 'params'):\n self.ignore_label = self.configer.get('loss', 'params')['ce_ignore_index']\n\n self.max_samples = self.configer.get('contrast', 'max_samples')\n self.max_views = self.configer.get('contrast', 'max_views')\n\n def _hard_anchor_sampling(self, X, y_hat, y):\n batch_size, feat_dim = X.shape[0], X.shape[-1]\n\n classes = []\n total_classes = 0\n for ii in range(batch_size):\n this_y = y_hat[ii]\n this_classes = torch.unique(this_y)\n this_classes = [x for x in this_classes if x > 0 and x != self.ignore_label]\n this_classes = [x for x in this_classes if (this_y == x).nonzero().shape[0] > self.max_views]\n\n classes.append(this_classes)\n total_classes += len(this_classes)\n\n if total_classes == 0:\n return None, None\n\n n_view = self.max_samples // total_classes\n n_view = min(n_view, self.max_views)\n\n X_ = torch.zeros((total_classes, n_view, feat_dim), dtype=torch.float).cuda()\n y_ = torch.zeros(total_classes, dtype=torch.float).cuda()\n\n X_ptr = 0\n for ii in range(batch_size):\n this_y_hat = y_hat[ii]\n this_y = y[ii]\n this_classes = classes[ii]\n\n for cls_id in this_classes:\n hard_indices = ((this_y_hat == cls_id) & (this_y != cls_id)).nonzero()\n easy_indices = ((this_y_hat == cls_id) & (this_y == cls_id)).nonzero()\n\n num_hard = hard_indices.shape[0]\n num_easy = easy_indices.shape[0]\n\n if num_hard >= n_view / 2 and num_easy >= n_view / 2:\n num_hard_keep = n_view // 2\n num_easy_keep = n_view - num_hard_keep\n elif num_hard >= n_view / 2:\n num_easy_keep = num_easy\n num_hard_keep = n_view - num_easy_keep\n elif num_easy >= n_view / 2:\n num_hard_keep = num_hard\n num_easy_keep = n_view - num_hard_keep\n else:\n Log.info('this shoud be never touched! {} {} {}'.format(num_hard, num_easy, n_view))\n raise Exception\n\n perm = torch.randperm(num_hard)\n hard_indices = hard_indices[perm[:num_hard_keep]]\n perm = torch.randperm(num_easy)\n easy_indices = easy_indices[perm[:num_easy_keep]]\n indices = torch.cat((hard_indices, easy_indices), dim=0)\n\n X_[X_ptr, :, :] = X[ii, indices, :].squeeze(1)\n y_[X_ptr] = cls_id\n X_ptr += 1\n\n return X_, y_\n\n def _contrastive(self, feats_, labels_):\n anchor_num, n_view = feats_.shape[0], feats_.shape[1]\n\n labels_ = labels_.contiguous().view(-1, 1)\n mask = torch.eq(labels_, torch.transpose(labels_, 0, 1)).float().cuda()\n\n contrast_count = n_view\n contrast_feature = torch.cat(torch.unbind(feats_, dim=1), dim=0)\n\n anchor_feature = contrast_feature\n anchor_count = contrast_count\n\n anchor_dot_contrast = torch.div(torch.matmul(anchor_feature, torch.transpose(contrast_feature, 0, 1)),\n self.temperature)\n logits_max, _ = torch.max(anchor_dot_contrast, dim=1, keepdim=True)\n logits = anchor_dot_contrast - logits_max.detach()\n\n mask = mask.repeat(anchor_count, contrast_count)\n neg_mask = 1 - mask\n\n logits_mask = torch.ones_like(mask).scatter_(1,\n torch.arange(anchor_num * anchor_count).view(-1, 1).cuda(),\n 0)\n mask = mask * logits_mask\n\n neg_logits = torch.exp(logits) * neg_mask\n neg_logits = neg_logits.sum(1, keepdim=True)\n\n exp_logits = torch.exp(logits)\n\n log_prob = logits - torch.log(exp_logits + neg_logits)\n\n mean_log_prob_pos = (mask * log_prob).sum(1) / mask.sum(1)\n\n loss = - (self.temperature / self.base_temperature) * mean_log_prob_pos\n loss = loss.mean()\n\n return loss\n\n def forward(self, feats, labels=None, predict=None):\n labels = labels.unsqueeze(1).float().clone()\n labels = torch.nn.functional.interpolate(labels,\n (feats.shape[2], feats.shape[3]), mode='nearest')\n labels = labels.squeeze(1).long()\n assert labels.shape[-1] == feats.shape[-1], '{} {}'.format(labels.shape, feats.shape)\n\n batch_size = feats.shape[0]\n\n labels = labels.contiguous().view(batch_size, -1)\n predict = predict.contiguous().view(batch_size, -1)\n feats = feats.permute(0, 2, 3, 1)\n feats = feats.contiguous().view(feats.shape[0], -1, feats.shape[-1])\n\n feats_, labels_ = self._hard_anchor_sampling(feats, labels, predict)\n\n loss = self._contrastive(feats_, labels_)\n\n return loss\n\n\nclass ContrastAuxCELoss(nn.Module, ABC):\n def __init__(self, configer=None):\n super(ContrastAuxCELoss, self).__init__()\n\n self.configer = configer\n\n ignore_index = -1\n if self.configer.exists('loss', 'params') and 'ce_ignore_index' in self.configer.get('loss', 'params'):\n ignore_index = self.configer.get('loss', 'params')['ce_ignore_index']\n Log.info('ignore_index: {}'.format(ignore_index))\n\n self.loss_weight = self.configer.get('contrast', 'loss_weight')\n self.use_rmi = self.configer.get('contrast', 'use_rmi')\n\n if self.use_rmi:\n self.seg_criterion = FSAuxRMILoss(configer=configer)\n else:\n self.seg_criterion = FSAuxCELoss(configer=configer)\n\n self.contrast_criterion = PixelContrastLoss(configer=configer)\n\n def forward(self, preds, target):\n h, w = target.size(1), target.size(2)\n\n assert \"seg\" in preds\n assert \"seg_aux\" in preds\n\n seg = preds['seg']\n seg_aux = preds['seg_aux']\n\n embedding = preds['embedding'] if 'embedding' in preds else None\n\n pred = F.interpolate(input=seg, size=(h, w), mode='bilinear', align_corners=True)\n pred_aux = F.interpolate(input=seg_aux, size=(h, w), mode='bilinear', align_corners=True)\n loss = self.seg_criterion([pred_aux, pred], target)\n\n if embedding is not None:\n _, predict = torch.max(seg, 1)\n\n loss_contrast = self.contrast_criterion(embedding, target, predict)\n return loss + self.loss_weight * loss_contrast\n\n return loss\n" ]
[ [ "torch.transpose", "torch.max", "torch.zeros", "torch.randperm", "torch.cat", "torch.arange", "torch.exp", "torch.unique", "torch.log", "torch.nn.functional.interpolate", "torch.unbind", "torch.ones_like" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jskinn/arvet
[ "742cf3e7ee8848c4efebfaa887fc9c0fd90a06e9", "742cf3e7ee8848c4efebfaa887fc9c0fd90a06e9" ]
[ "arvet/batch_analysis/tests/test_task.py", "arvet/database/tests/mock_image_manager.py" ]
[ "# Copyright (c) 2017, John Skinner\nimport unittest\nimport numpy as np\nimport arvet.database.tests.database_connection as dbconn\nfrom arvet.config.path_manager import PathManager\nimport arvet.batch_analysis.task as task\n\n\nclass MockTask(task.Task):\n def run_task(self, path_manager: PathManager):\n pass\n\n def get_unique_name(self) -> str:\n return \"mock_task_{0}\".format(self.pk)\n\n\nclass TestTaskDatabase(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n dbconn.connect_to_test_db()\n\n def setUp(self):\n # Remove the collection as the start of the test, so that we're sure it's empty\n task.Task._mongometa.collection.drop()\n\n @classmethod\n def tearDownClass(cls):\n # Clean up after ourselves by dropping the collection for this model\n task.Task._mongometa.collection.drop()\n\n def test_stores_and_loads_simple(self):\n obj = MockTask(state=task.JobState.UNSTARTED)\n obj.save()\n\n # Load all the entities\n all_entities = list(task.Task.objects.all())\n self.assertGreaterEqual(len(all_entities), 1)\n self.assertEqual(all_entities[0], obj)\n all_entities[0].delete()\n\n def test_stores_and_loads_all_params(self):\n obj = MockTask(\n state=task.JobState.RUNNING,\n node_id='test-hpc',\n job_id=15,\n num_cpus=3,\n num_gpus=150,\n memory_requirements='4KB',\n expected_duration='100:00:00'\n )\n obj.save()\n\n # Load all the entities\n all_entities = list(task.Task.objects.all())\n self.assertGreaterEqual(len(all_entities), 1)\n self.assertEqual(all_entities[0], obj)\n all_entities[0].delete()\n\n def test_stores_and_loads_after_change_state(self):\n obj = MockTask(\n state=task.JobState.RUNNING,\n node_id='test-hpc',\n job_id=15,\n num_cpus=3,\n num_gpus=150,\n memory_requirements='4KB',\n expected_duration='100:00:00'\n )\n obj.save()\n\n all_entities = list(task.Task.objects.all())\n self.assertGreaterEqual(len(all_entities), 1)\n self.assertEqual(all_entities[0], obj)\n\n obj.mark_job_failed()\n obj.save()\n\n all_entities = list(task.Task.objects.all())\n self.assertGreaterEqual(len(all_entities), 1)\n self.assertEqual(all_entities[0], obj)\n\n obj.mark_job_started('test_node', 143)\n obj.save()\n\n all_entities = list(task.Task.objects.all())\n self.assertGreaterEqual(len(all_entities), 1)\n self.assertEqual(all_entities[0], obj)\n\n obj.mark_job_complete()\n obj.save()\n\n all_entities = list(task.Task.objects.all())\n self.assertGreaterEqual(len(all_entities), 1)\n self.assertEqual(all_entities[0], obj)\n\n\nclass TestTask(unittest.TestCase):\n\n def test_mark_job_started_changes_unstarted_to_running(self):\n subject = MockTask(state=task.JobState.UNSTARTED)\n self.assertTrue(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n subject.mark_job_started('test', 12)\n self.assertFalse(subject.is_unstarted)\n self.assertTrue(subject.is_running)\n\n def test_mark_job_started_doesnt_affect_already_running_jobs(self):\n subject = MockTask(state=task.JobState.RUNNING, node_id='external', job_id=3)\n self.assertFalse(subject.is_unstarted)\n self.assertTrue(subject.is_running)\n self.assertFalse(subject.is_finished)\n subject.mark_job_started('test', 12)\n self.assertFalse(subject.is_unstarted)\n self.assertTrue(subject.is_running)\n self.assertFalse(subject.is_finished)\n self.assertEqual('external', subject.node_id)\n self.assertEqual(3, subject.job_id)\n\n def test_mark_job_started_doesnt_affect_finished_jobs(self):\n subject = MockTask(state=task.JobState.DONE)\n self.assertFalse(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n self.assertTrue(subject.is_finished)\n subject.mark_job_started('test', 12)\n self.assertFalse(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n self.assertTrue(subject.is_finished)\n self.assertIsNone(subject.node_id)\n self.assertIsNone(subject.job_id)\n\n def test_mark_job_failed_changes_running_to_unstarted(self):\n subject = MockTask(state=task.JobState.RUNNING, node_id='test', job_id=5)\n self.assertFalse(subject.is_unstarted)\n self.assertTrue(subject.is_running)\n subject.mark_job_failed()\n self.assertTrue(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n self.assertIsNone(subject.node_id)\n self.assertIsNone(subject.job_id)\n\n def test_mark_job_failed_increases_failed_count(self):\n subject = MockTask(state=task.JobState.RUNNING, node_id='test', job_id=5, failure_count=4)\n self.assertFalse(subject.is_unstarted)\n self.assertTrue(subject.is_running)\n subject.mark_job_failed()\n self.assertTrue(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n self.assertEqual(5, subject.failure_count)\n\n def test_mark_job_failed_doesnt_affect_unstarted_jobs(self):\n subject = MockTask(state=task.JobState.UNSTARTED)\n self.assertTrue(subject.is_unstarted)\n self.assertFalse(subject.is_finished)\n subject.mark_job_failed()\n self.assertTrue(subject.is_unstarted)\n self.assertFalse(subject.is_finished)\n self.assertEqual(0, subject.failure_count)\n\n def test_mark_job_failed_doesnt_affect_finished_jobs(self):\n subject = MockTask(state=task.JobState.DONE)\n self.assertFalse(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n self.assertTrue(subject.is_finished)\n subject.mark_job_failed()\n self.assertFalse(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n self.assertTrue(subject.is_finished)\n self.assertIsNone(subject.node_id)\n self.assertIsNone(subject.job_id)\n\n def test_mark_job_complete_changes_running_to_finished(self):\n subject = MockTask(state=task.JobState.RUNNING, node_id='test', job_id=5)\n self.assertFalse(subject.is_unstarted)\n self.assertTrue(subject.is_running)\n subject.mark_job_complete()\n self.assertFalse(subject.is_running)\n self.assertTrue(subject.is_finished)\n self.assertIsNone(subject.node_id)\n self.assertIsNone(subject.job_id)\n\n def test_mark_job_complete_doesnt_affect_unstarted_jobs(self):\n subject = MockTask(state=task.JobState.UNSTARTED)\n self.assertTrue(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n self.assertFalse(subject.is_finished)\n subject.mark_job_complete()\n self.assertTrue(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n self.assertFalse(subject.is_finished)\n\n def test_mark_job_complete_doesnt_affect_finished_jobs(self):\n subject = MockTask(state=task.JobState.DONE)\n self.assertFalse(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n self.assertTrue(subject.is_finished)\n subject.mark_job_complete()\n self.assertFalse(subject.is_unstarted)\n self.assertFalse(subject.is_running)\n self.assertTrue(subject.is_finished)\n self.assertIsNone(subject.node_id)\n self.assertIsNone(subject.job_id)\n\n def test_change_job_id_doesnt_affect_state(self):\n subject = MockTask(state=task.JobState.RUNNING)\n self.assertFalse(subject.is_unstarted)\n self.assertTrue(subject.is_running)\n self.assertFalse(subject.is_finished)\n subject.change_job_id('test', 12)\n self.assertFalse(subject.is_unstarted)\n self.assertTrue(subject.is_running)\n self.assertFalse(subject.is_finished)\n\n def test_change_job_id_changes_job_info(self):\n subject = MockTask(state=task.JobState.RUNNING, node_id='external', job_id=3)\n self.assertEqual('external', subject.node_id)\n self.assertEqual(3, subject.job_id)\n subject.change_job_id('test', 12)\n self.assertEqual('test', subject.node_id)\n self.assertEqual(12, subject.job_id)\n\n def test_change_job_id_doesnt_affect_unstarted_jobs(self):\n subject = MockTask(state=task.JobState.UNSTARTED)\n self.assertTrue(subject.is_unstarted)\n subject.change_job_id('test', 12)\n self.assertTrue(subject.is_unstarted)\n self.assertIsNone(subject.node_id)\n self.assertIsNone(subject.job_id)\n\n def test_change_job_id_doesnt_affect_finished_jobs(self):\n subject = MockTask(state=task.JobState.DONE, node_id='external', job_id=3)\n self.assertTrue(subject.is_finished)\n self.assertEqual('external', subject.node_id)\n self.assertEqual(3, subject.job_id)\n subject.change_job_id('test', 12)\n self.assertTrue(subject.is_finished)\n self.assertEqual('external', subject.node_id)\n self.assertEqual(3, subject.job_id)\n\n def test_state_remains_consistent(self):\n random = np.random.RandomState(144135)\n subject = MockTask(state=task.JobState.UNSTARTED)\n for idx in range(50):\n change = random.randint(0, 4 if idx > 30 else 3)\n if idx > 30 and change == 3:\n subject.mark_job_complete()\n elif change == 2:\n subject.change_job_id('external', random.randint(0, 1000))\n elif change == 1:\n subject.mark_job_started('test', random.randint(0, 1000))\n else:\n subject.mark_job_failed()\n # Make sure that the node id and job id match the state\n if subject.is_unstarted or subject.is_finished:\n self.assertIsNone(subject.node_id)\n self.assertIsNone(subject.job_id)\n else:\n self.assertIsNotNone(subject.node_id)\n self.assertIsNotNone(subject.job_id)\n", "import numpy as np\nimport xxhash\nimport arvet.database.image_manager as im_manager\n\n\nclass MockImageGroup(im_manager.ImageGroup):\n\n def __init__(self, allow_write=True):\n self._storage = dict()\n self._allow_write = bool(allow_write)\n\n @property\n def can_write(self) -> bool:\n return self._allow_write\n\n def get_image(self, path: str) -> np.ndarray:\n return self._storage[path]\n\n def is_valid_path(self, path: str) -> bool:\n return path in self._storage\n\n def store_image(self, data: np.ndarray) -> str:\n # Try different seeds until we find one that doesn't collide,\n # or we find that this image is already stored.\n # Since the iteration is in the same order every time, and we check equality,\n # will always resolve collisions if it is possible to do so.\n for seed in range(2 ** 32):\n path = self.find_path_for_image(data, seed)\n if path not in self._storage:\n if self._allow_write:\n # Hash value is available, store the data there\n self._storage[path] = data\n return path\n # We reached the point we'd write to the file, but we are not configured to do so. Fail.\n raise RuntimeError(\"ImageManager not configured for writing\")\n else:\n existing_data = self._storage[path]\n if np.array_equal(data, existing_data):\n # This image is already stored, return the path\n return path\n raise RuntimeError(\"Could not find a seed that allows this image to be stored in the database\")\n\n def remove_image(self, path: str) -> bool:\n \"\"\"\n Remove an image from the store\n :param path:\n :return:\n \"\"\"\n if path in self._storage:\n del self._storage[path]\n return True\n return False\n\n @staticmethod\n def find_path_for_image(data, seed=0):\n \"\"\"\n Find a valid path to store this image, based on a hash of the\n :param data:\n :param seed: A seed passed to the hash, for collision handling.\n :return:\n \"\"\"\n digest = xxhash.xxh64(data, seed=seed).hexdigest()\n return digest\n\n\nclass MockImageManager(im_manager.ImageManager):\n \"\"\"\n A fake image manager that does not persist images, but holds them in memory.\n Use for tests.\n \"\"\"\n\n def __init__(self):\n self.open_groups = dict()\n\n def get_group(self, group_name: str, allow_write: bool = False) -> im_manager.ImageGroup:\n \"\"\"\n\n :param group_name:\n :param allow_write:\n :return:\n \"\"\"\n if group_name not in self.open_groups:\n self.open_groups[group_name] = MockImageGroup(allow_write=allow_write)\n group = self.open_groups[group_name]\n if allow_write and not group.can_write:\n raise IOError(f\"Cannot write to group {group_name}, it is already open read-only\")\n return group\n" ]
[ [ "numpy.random.RandomState" ], [ "numpy.array_equal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Wenhao-Yang/DeepSpeaker-pytorch
[ "99eb8de3357c85e2b7576da2a742be2ffd773ead", "99eb8de3357c85e2b7576da2a742be2ffd773ead", "99eb8de3357c85e2b7576da2a742be2ffd773ead", "99eb8de3357c85e2b7576da2a742be2ffd773ead", "99eb8de3357c85e2b7576da2a742be2ffd773ead", "99eb8de3357c85e2b7576da2a742be2ffd773ead" ]
[ "Score/Cosine_Score.py", "TrainAndTest/Spectrogram/train_domres_egs.py", "TrainAndTest/train_egs.py", "TrainAndTest/Fbank/TDNNs/train_etdnn_kaldi.py", "Process_Data/validate_data.py", "TrainAndTest/deprecated/test_accuracy_kaldi.py" ]
[ "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@Author: yangwenhao\n@Contact: [email protected]\n@Software: PyCharm\n@File: Cosine.py\n@Time: 19-6-26 下午9:43\n@Overview: Implement Cosine Score for speaker identification!\nEnrollment set files will be in the 'Data/enroll_set.npy' and the classes-to-index file is 'Data/enroll_classes.npy'\nTest set files are in the 'Data/test_set.npy' and the utterances-to-index file is 'Data/test_classes.npy'\n\"\"\"\nimport numpy as np\nimport torch.nn as nn\n\nENROLL_FILE = \"Data/xvector/enroll/extract_adagrad-lr0.1-wd0.0-embed512-alpha10.npy\"\nENROLL_CLASS = \"Data/enroll_classes.npy\"\nTEST_FILE = \"Data/xvector/test/extract_adagrad-lr0.1-wd0.0-embed512-alpha10.npy\"\nTEST_CLASS = \"Data/test_classes.npy\"\n\n# test_vec = np.array([1,2,3,4])\n# refe_vec = np.array([8,3,3,4])\n\ndef normalize(narray, order=2, axis=1):\n norm = np.linalg.norm(narray, ord=order, axis=axis, keepdims=True)\n return(narray/norm + np.finfo(np.float32).eps)\n\ndef cos_dis(test_vec, refe_vec):\n vec1 = normalize(test_vec, axis=0)\n vec2 = normalize(refe_vec, axis=0)\n dis = np.matmul(vec1, vec2.T)\n return(dis)\n\nenroll_features = np.load(ENROLL_FILE, allow_pickle=True)\nenroll_classes = np.load(ENROLL_CLASS, allow_pickle=True).item()\ntest_features = np.load(TEST_FILE, allow_pickle=True)\ntest_classes = np.load(TEST_CLASS, allow_pickle=True)\nenroll_dict = dict()\nfor item in enroll_classes:\n num=0\n feat = np.zeros([512], dtype=float)\n for (label, feature) in enroll_features:\n if label==enroll_classes[item]:\n feat += feature.detach().numpy()\n num += 1\n enroll_dict[item] = feat/num\n\nsimilarity = {}\nfor (label, feature) in test_features:\n utt = {}\n for item in enroll_dict:\n utt[item] = np.linalg.norm(feature.detach().numpy()-enroll_dict[item])\n\n for utterance in test_classes:\n if int(utterance[1])==label.item():\n test_id = utterance[0]\n similarity[test_id]=utt\nprint(similarity)\n\n# cos_dis(test_vec, refe_vec)\n\n", "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@Author: yangwenhao\n@Contact: [email protected]\n@Software: PyCharm\n@File: train_lores10_kaldi.py\n@Time: 2020/4/4 11:14 AM\n@Overview:\n\"\"\"\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport os.path as osp\nimport sys\nimport time\n# Version conflict\nimport warnings\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nfrom kaldi_io import read_mat, read_vec_flt\nfrom tensorboardX import SummaryWriter\nfrom torch.autograd import Variable\nfrom torch.optim.lr_scheduler import MultiStepLR, ExponentialLR\nfrom tqdm import tqdm\n\nfrom Define_Model.LossFunction import CenterLoss\nfrom Define_Model.SoftmaxLoss import AngleSoftmaxLoss, AngleLinear, AdditiveMarginLinear, AMSoftmaxLoss\nfrom Define_Model.model import PairwiseDistance\nfrom Process_Data import constants as c\nfrom Process_Data.KaldiDataset import ScriptTestDataset, KaldiExtractDataset, \\\n ScriptVerifyDataset\nfrom Process_Data.LmdbDataset import EgsDataset\nfrom Process_Data.audio_processing import concateinputfromMFB, to2tensor, varLengthFeat, ConcateVarInput\nfrom Process_Data.audio_processing import toMFB, totensor, truncatedinput, read_audio\nfrom TrainAndTest.common_func import create_optimizer, create_model, verification_test, verification_extract\nfrom eval_metrics import evaluate_kaldi_eer, evaluate_kaldi_mindcf\nfrom logger import NewLogger\n\nwarnings.filterwarnings(\"ignore\")\n\nimport torch._utils\n\ntry:\n torch._utils._rebuild_tensor_v2\nexcept AttributeError:\n def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):\n tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)\n tensor.requires_grad = requires_grad\n tensor._backward_hooks = backward_hooks\n return tensor\n\n\n torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch Speaker Recognition')\n# Data options\nparser.add_argument('--train-dir', type=str, help='path to dataset')\nparser.add_argument('--valid-dir', type=str, help='path to dataset')\nparser.add_argument('--test-dir', type=str, help='path to voxceleb1 test dataset')\nparser.add_argument('--trials', type=str, default='trials', help='trials filename')\nparser.add_argument('--domain', action='store_true', default=False, help='set domain in dataset')\n\nparser.add_argument('--nj', default=12, type=int, metavar='NJOB', help='num of job')\nparser.add_argument('--feat-format', type=str, default='kaldi', choices=['kaldi', 'npy'],\n help='number of jobs to make feats (default: 10)')\n\nparser.add_argument('--check-path', default='Data/checkpoint/LoResNet10/spect/soft',\n help='folder to output model checkpoints')\nparser.add_argument('--save-init', action='store_true', default=True, help='need to make mfb file')\nparser.add_argument('--resume',\n default='Data/checkpoint/LoResNet10/spect/soft/checkpoint_10.pth', type=str,\n metavar='PATH',\n help='path to latest checkpoint (default: none)')\n\nparser.add_argument('--start-epoch', default=1, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('--epochs', type=int, default=20, metavar='E',\n help='number of epochs to train (default: 10)')\nparser.add_argument('--scheduler', default='multi', type=str,\n metavar='SCH', help='The optimizer to use (default: Adagrad)')\nparser.add_argument('--gamma', default=0.75, type=float,\n metavar='GAMMA', help='The optimizer to use (default: Adagrad)')\nparser.add_argument('--milestones', default='10,15', type=str,\n metavar='MIL', help='The optimizer to use (default: Adagrad)')\nparser.add_argument('--min-softmax-epoch', type=int, default=40, metavar='MINEPOCH',\n help='minimum epoch for initial parameter using softmax (default: 2')\nparser.add_argument('--veri-pairs', type=int, default=12800, metavar='VP',\n help='number of epochs to train (default: 10)')\n\n# Training options\n# Model options\nparser.add_argument('--model', type=str, help='path to voxceleb1 test dataset')\nparser.add_argument('--resnet-size', default=8, type=int,\n metavar='RES', help='The channels of convs layers)')\nparser.add_argument('--inst-norm', action='store_true', default=False,\n help='replace batchnorm with instance norm')\nparser.add_argument('--channels', default='64,128,256', type=str,\n metavar='CHA', help='The channels of convs layers)')\nparser.add_argument('--feat-dim', default=161, type=int, metavar='FEAT',\n help='acoustic feature dimension')\nparser.add_argument('--remove-vad', action='store_true', default=False,\n help='using Cosine similarity')\n\nparser.add_argument('--alpha', default=12, type=float, metavar='FEAT',\n help='acoustic feature dimension')\nparser.add_argument('--kernel-size', default='5,5', type=str, metavar='KE',\n help='kernel size of conv filters')\nparser.add_argument('--cos-sim', action='store_true', default=True,\n help='using Cosine similarity')\nparser.add_argument('--avg-size', type=int, default=4, metavar='ES',\n help='Dimensionality of the embedding')\n\nparser.add_argument('--embedding-size-a', type=int, default=128, metavar='ES',\n help='Dimensionality of the embedding')\nparser.add_argument('--embedding-size-b', type=int, default=64, metavar='ES',\n help='Dimensionality of the embedding')\nparser.add_argument('--embedding-size-o', type=int, default=32, metavar='ES',\n help='Dimensionality of the embedding')\n\nparser.add_argument('--batch-size', type=int, default=128, metavar='BS',\n help='input batch size for training (default: 128)')\nparser.add_argument('--input-per-spks', type=int, default=224, metavar='IPFT',\n help='input sample per file for testing (default: 8)')\nparser.add_argument('--num-valid', type=int, default=5, metavar='IPFT',\n help='input sample per file for testing (default: 8)')\nparser.add_argument('--test-input-per-file', type=int, default=4, metavar='IPFT',\n help='input sample per file for testing (default: 8)')\nparser.add_argument('--test-batch-size', type=int, default=1, metavar='BST',\n help='input batch size for testing (default: 64)')\nparser.add_argument('--dropout-p', type=float, default=0., metavar='BST',\n help='input batch size for testing (default: 64)')\n\n# loss configure\nparser.add_argument('--loss-type', type=str, default='soft', choices=['soft', 'asoft', 'center', 'amsoft'],\n help='path to voxceleb1 test dataset')\nparser.add_argument('--finetune', action='store_true', default=False,\n help='using Cosine similarity')\nparser.add_argument('--loss-ratio', type=float, default=0.1, metavar='LOSSRATIO',\n help='the ratio softmax loss - triplet loss (default: 2.0')\nparser.add_argument('--dom-ratio', type=float, default=0.1, metavar='DOMAINLOSSRATIO',\n help='the ratio softmax loss - triplet loss (default: 2.0')\nparser.add_argument('--sim-ratio', type=float, default=0.1, metavar='DOMAINLOSSRATIO',\n help='the ratio softmax loss - triplet loss (default: 2.0')\n# args for additive margin-softmax\nparser.add_argument('--margin', type=float, default=0.3, metavar='MARGIN',\n help='the margin value for the angualr softmax loss function (default: 3.0')\nparser.add_argument('--s', type=float, default=15, metavar='S',\n help='the margin value for the angualr softmax loss function (default: 3.0')\n\n# args for a-softmax\nparser.add_argument('--m', type=int, default=3, metavar='M',\n help='the margin value for the angualr softmax loss function (default: 3.0')\nparser.add_argument('--lambda-min', type=int, default=5, metavar='S',\n help='random seed (default: 0)')\nparser.add_argument('--lambda-max', type=float, default=1000, metavar='S',\n help='random seed (default: 0)')\n\nparser.add_argument('--lr', type=float, default=0.1, metavar='LR', help='learning rate (default: 0.125)')\nparser.add_argument('--lr-decay', default=0, type=float, metavar='LRD',\n help='learning rate decay ratio (default: 1e-4')\nparser.add_argument('--weight-decay', default=5e-4, type=float,\n metavar='WEI', help='weight decay (default: 0.0)')\nparser.add_argument('--momentum', default=0.9, type=float,\n metavar='MOM', help='momentum for sgd (default: 0.9)')\nparser.add_argument('--dampening', default=0, type=float,\n metavar='DAM', help='dampening for sgd (default: 0.0)')\nparser.add_argument('--optimizer', default='sgd', type=str,\n metavar='OPT', help='The optimizer to use (default: Adagrad)')\n\n# Device options\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='enables CUDA training')\nparser.add_argument('--gpu-id', default='1', type=str,\n help='id(s) for CUDA_VISIBLE_DEVICES')\nparser.add_argument('--seed', type=int, default=123456, metavar='S',\n help='random seed (default: 0)')\nparser.add_argument('--log-interval', type=int, default=1, metavar='LI',\n help='how many batches to wait before logging training status')\n\nparser.add_argument('--acoustic-feature', choices=['fbank', 'spectrogram', 'mfcc'], default='fbank',\n help='choose the acoustic features type.')\nparser.add_argument('--makemfb', action='store_true', default=False,\n help='need to make mfb file')\nparser.add_argument('--makespec', action='store_true', default=False,\n help='need to make spectrograms file')\n\nargs = parser.parse_args()\n\n# Set the device to use by setting CUDA_VISIBLE_DEVICES env variable in\n# order to prevent any memory allocation on unused GPUs\nos.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id\n\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\n# torch.multiprocessing.set_sharing_strategy('file_system')\n\nif args.cuda:\n torch.cuda.manual_seed_all(args.seed)\n cudnn.benchmark = True\n\n# create logger Define visulaize SummaryWriter instance\nwriter = SummaryWriter(logdir=args.check_path, filename_suffix='_first')\n\nsys.stdout = NewLogger(osp.join(args.check_path, 'log.txt'))\n\nkwargs = {'num_workers': args.nj, 'pin_memory': False} if args.cuda else {}\nif not os.path.exists(args.check_path):\n os.makedirs(args.check_path)\n\nopt_kwargs = {'lr': args.lr,\n 'lr_decay': args.lr_decay,\n 'weight_decay': args.weight_decay,\n 'dampening': args.dampening,\n 'momentum': args.momentum}\n\nl2_dist = nn.CosineSimilarity(dim=1, eps=1e-6) if args.cos_sim else PairwiseDistance(2)\n\nif args.acoustic_feature == 'fbank':\n transform = transforms.Compose([\n concateinputfromMFB(num_frames=c.NUM_FRAMES_SPECT, remove_vad=args.remove_vad),\n # varLengthFeat(),\n to2tensor()\n ])\n transform_T = transforms.Compose([\n ConcateVarInput(num_frames=c.NUM_FRAMES_SPECT, remove_vad=args.remove_vad),\n # to2tensor()\n ])\n transform_V = transforms.Compose([\n varLengthFeat(remove_vad=args.remove_vad),\n to2tensor()\n ])\n\nelse:\n transform = transforms.Compose([\n truncatedinput(),\n toMFB(),\n totensor(),\n # tonormal()\n ])\n file_loader = read_audio\n\n# pdb.set_trace()\ntorch.multiprocessing.set_sharing_strategy('file_system')\n\nif args.feat_format == 'kaldi':\n file_loader = read_mat\nelif args.feat_format == 'npy':\n file_loader = np.load\n\ntrain_dir = EgsDataset(dir=args.train_dir, feat_dim=args.feat_dim, loader=file_loader, transform=transform,\n domain=args.domain)\ntest_dir = ScriptTestDataset(dir=args.test_dir, loader=np.load, transform=transform_T)\n\nif len(test_dir) < args.veri_pairs:\n args.veri_pairs = len(test_dir)\n print('There are %d verification pairs.' % len(test_dir))\nelse:\n test_dir.partition(args.veri_pairs)\n\nvalid_dir = EgsDataset(dir=args.valid_dir, feat_dim=args.feat_dim, loader=file_loader, transform=transform,\n domain=args.domain)\n\n\ndef main():\n # Views the training images and displays the distance on anchor-negative and anchor-positive\n # test_display_triplet_distance = False\n # print the experiment configuration\n print('\\nCurrent time is \\33[91m{}\\33[0m.'.format(str(time.asctime())))\n print('Parsed options: {}'.format(vars(args)))\n print('Number of Speakers: {}.\\n'.format(train_dir.num_spks))\n\n # instantiate model and initialize weights\n kernel_size = args.kernel_size.split(',')\n kernel_size = [int(x) for x in kernel_size]\n padding = [int((x - 1) / 2) for x in kernel_size]\n\n kernel_size = tuple(kernel_size)\n padding = tuple(padding)\n\n channels = args.channels.split(',')\n channels = [int(x) for x in channels]\n\n model_kwargs = {'embedding_size_a': args.embedding_size_a,\n 'embedding_size_b': args.embedding_size_b,\n 'embedding_size_o': args.embedding_size_o,\n 'inst_norm': args.inst_norm,\n 'resnet_size': args.resnet_size,\n 'num_classes_a': train_dir.num_spks,\n 'num_classes_b': train_dir.num_doms,\n 'channels': channels,\n 'avg_size': args.avg_size,\n 'alpha': args.alpha,\n 'kernel_size': kernel_size,\n 'padding': padding,\n 'dropout_p': args.dropout_p}\n\n print('Model options: {}'.format(model_kwargs))\n model = create_model(args.model, **model_kwargs)\n\n start_epoch = 0\n if args.save_init and not args.finetune:\n check_path = '{}/checkpoint_{}.pth'.format(args.check_path, start_epoch)\n torch.save(model, check_path)\n\n if args.resume:\n if os.path.isfile(args.resume):\n print('=> loading checkpoint {}'.format(args.resume))\n checkpoint = torch.load(args.resume)\n start_epoch = checkpoint['epoch']\n\n filtered = {k: v for k, v in checkpoint['state_dict'].items() if 'num_batches_tracked' not in k}\n model_dict = model.state_dict()\n model_dict.update(filtered)\n model.load_state_dict(model_dict)\n #\n # model.dropout.p = args.dropout_p\n else:\n print('=> no checkpoint found at {}'.format(args.resume))\n\n ce_criterion = nn.CrossEntropyLoss()\n if args.loss_type == 'soft':\n xe_criterion = None\n elif args.loss_type == 'asoft':\n ce_criterion = None\n model.classifier_spk = AngleLinear(in_features=args.embedding_size, out_features=train_dir.num_spks, m=args.m)\n xe_criterion = AngleSoftmaxLoss(lambda_min=args.lambda_min, lambda_max=args.lambda_max)\n elif args.loss_type == 'center':\n xe_criterion = CenterLoss(num_classes=train_dir.num_spks, feat_dim=args.embedding_size)\n elif args.loss_type == 'amsoft':\n ce_criterion = None\n model.classifier_spk = AdditiveMarginLinear(feat_dim=args.embedding_size, n_classes=train_dir.num_spks)\n xe_criterion = AMSoftmaxLoss(margin=args.margin, s=args.s)\n\n optimizer = create_optimizer(model.parameters(), args.optimizer, **opt_kwargs)\n if args.loss_type == 'center':\n optimizer = torch.optim.SGD([{'params': xe_criterion.parameters(), 'lr': args.lr * 5},\n {'params': model.parameters()}],\n lr=args.lr, weight_decay=args.weight_decay,\n momentum=args.momentum)\n if args.finetune:\n if args.loss_type == 'asoft' or args.loss_type == 'amsoft':\n classifier_params = list(map(id, model.classifier.parameters()))\n rest_params = filter(lambda p: id(p) not in classifier_params, model.parameters())\n optimizer = torch.optim.SGD([{'params': model.classifier.parameters(), 'lr': args.lr * 5},\n {'params': rest_params}],\n lr=args.lr, weight_decay=args.weight_decay,\n momentum=args.momentum)\n\n if args.scheduler == 'exp':\n scheduler = ExponentialLR(optimizer, gamma=args.gamma)\n else:\n milestones = args.milestones.split(',')\n milestones = [int(x) for x in milestones]\n milestones.sort()\n scheduler = MultiStepLR(optimizer, milestones=milestones, gamma=0.1)\n\n ce = [ce_criterion, xe_criterion]\n\n start = args.start_epoch + start_epoch\n print('Start epoch is : ' + str(start))\n # start = 0\n end = start + args.epochs\n\n train_loader = torch.utils.data.DataLoader(train_dir, batch_size=args.batch_size, shuffle=False, **kwargs)\n valid_loader = torch.utils.data.DataLoader(valid_dir, batch_size=int(args.batch_size / 2), shuffle=False, **kwargs)\n test_loader = torch.utils.data.DataLoader(test_dir, batch_size=args.test_batch_size, shuffle=False, **kwargs)\n # sitw_test_loader = torch.utils.data.DataLoader(sitw_test_dir, batch_size=args.test_batch_size,\n # shuffle=False, **kwargs)\n # sitw_dev_loader = torch.utils.data.DataLoader(sitw_dev_part, batch_size=args.test_batch_size, shuffle=False,\n # **kwargs)\n\n if args.cuda:\n model = model.cuda()\n for i in range(len(ce)):\n if ce[i] != None:\n ce[i] = ce[i].cuda()\n print('Dropout is {}.'.format(model.dropout_p))\n\n for epoch in range(start, end):\n # pdb.set_trace()\n print('\\n\\33[1;34m Current \\'{}\\' learning rate is '.format(args.optimizer), end='')\n for param_group in optimizer.param_groups:\n print('{:.5f} '.format(param_group['lr']), end='')\n print(' \\33[0m')\n if epoch % 2 == 1 and epoch != (end - 1):\n test(test_loader, valid_loader, model, epoch)\n\n train(train_loader, model, ce, optimizer, epoch)\n if epoch % 4 == 1 or epoch == (end - 1):\n check_path = '{}/checkpoint_{}.pth'.format(args.check_path, epoch)\n torch.save({'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'criterion': ce},\n check_path)\n\n scheduler.step()\n\n # exit(1)\n\n extract_dir = KaldiExtractDataset(dir=args.test_dir, transform=transform_V, filer_loader=np.load)\n extract_loader = torch.utils.data.DataLoader(extract_dir, batch_size=1, shuffle=False, **kwargs)\n xvector_dir = args.check_path\n xvector_dir = xvector_dir.replace('checkpoint', 'xvector')\n verification_extract(extract_loader, model, xvector_dir)\n\n verify_dir = ScriptVerifyDataset(dir=args.test_dir, trials_file=args.trials, xvectors_dir=xvector_dir,\n loader=read_vec_flt)\n verify_loader = torch.utils.data.DataLoader(verify_dir, batch_size=64, shuffle=False, **kwargs)\n verification_test(test_loader=verify_loader, dist_type=('cos' if args.cos_sim else 'l2'),\n log_interval=args.log_interval)\n\n writer.close()\n\n\ndef train(train_loader, model, ce, optimizer, epoch):\n # switch to evaluate mode\n model.train()\n lambda_ = 2. / (1 + np.exp(-10. * epoch / args.epochs)) - 1.\n model.grl.set_lambda(lambda_)\n\n correct_a = 0.\n correct_b = 0.\n\n total_datasize = 0.\n total_loss_a = 0.\n total_loss_b = 0.\n total_loss_c = 0.\n\n total_loss = 0.\n # for param_group in optimizer.param_groups:\n # print('\\33[1;34m Optimizer \\'{}\\' learning rate is {}.\\33[0m'.format(args.optimizer, param_group['lr']))\n ce_criterion, xe_criterion = ce\n pbar = tqdm(enumerate(train_loader))\n output_softmax = nn.Softmax(dim=1)\n\n for batch_idx, (data, label_a, label_b) in pbar:\n\n if args.cuda:\n data = data.cuda()\n\n data, label_a = Variable(data), Variable(label_a)\n label_b = Variable(label_b)\n\n logits_spk, feat_spk, logits_dom, feat_dom = model(data)\n\n true_labels_a = label_a.cuda()\n true_labels_b = label_b.cuda()\n\n # pdb.set_trace()\n # cos_theta, phi_theta = classfier\n spk_label = logits_spk\n dom_lable = logits_dom\n\n if args.loss_type == 'soft':\n spk_loss = ce_criterion(logits_spk, true_labels_a)\n\n elif args.loss_type == 'asoft':\n spk_label, _ = spk_label\n spk_loss = xe_criterion(logits_spk, true_labels_a)\n elif args.loss_type == 'center':\n loss_cent = ce_criterion(logits_spk, true_labels_a)\n loss_xent = xe_criterion(feat_spk, true_labels_a)\n spk_loss = args.loss_ratio * loss_xent + loss_cent\n elif args.loss_type == 'amsoft':\n spk_loss = xe_criterion(logits_spk, true_labels_a)\n\n dom_loss = (args.dom_ratio * ce_criterion(dom_lable, true_labels_b))\n loss = spk_loss + dom_loss\n\n if args.sim_ratio:\n spk_dom_sim_loss = torch.cosine_similarity(feat_spk, feat_dom, dim=1).pow(2).mean()\n spk_dom_sim_loss = args.sim_ratio * spk_dom_sim_loss\n loss += spk_dom_sim_loss\n\n predicted_labels_a = output_softmax(spk_label)\n\n predicted_one_labels_a = torch.max(predicted_labels_a, dim=1)[1]\n minibatch_correct_a = float((predicted_one_labels_a.cuda() == true_labels_a.cuda()).sum().item())\n minibatch_acc_a = minibatch_correct_a / len(predicted_one_labels_a)\n correct_a += minibatch_correct_a\n\n predicted_labels_b = output_softmax(dom_lable)\n predicted_one_labels_b = torch.max(predicted_labels_b, dim=1)[1]\n minibatch_correct_b = float((predicted_one_labels_b.cuda() == true_labels_b.cuda()).sum().item())\n minibatch_acc_b = minibatch_correct_b / len(predicted_one_labels_b)\n correct_b += minibatch_correct_b\n\n total_datasize += len(predicted_one_labels_a)\n total_loss_a += float(spk_loss.item())\n total_loss_b += float(dom_loss.item())\n total_loss_c += float(spk_dom_sim_loss.item()) if args.sim_ratio else 0.\n total_loss += float(loss.item())\n\n # compute gradient and update weights\n optimizer.zero_grad()\n loss.backward()\n\n if args.loss_type == 'center' and args.loss_ratio != 0:\n for param in xe_criterion.parameters():\n param.grad.data *= (1. / args.loss_ratio)\n\n optimizer.step()\n\n if batch_idx % args.log_interval == 0:\n pbar.set_description(\n 'Train Epoch {:2d}: [{:4d}/{:4d}({:3.0f}%)] AvgLoss: {:.4f} SpkLoss: {:.4f} DomLoss: {:.4f} ' \\\n 'SimLoss: {:.4f} Batch Accuracy: Spk: {:.4f}%, Dom: {:.4f}%'.format(\n epoch,\n batch_idx,\n len(train_loader),\n 100. * batch_idx / len(train_loader),\n total_loss / (batch_idx + 1),\n total_loss_a / (batch_idx + 1),\n total_loss_b / (batch_idx + 1),\n total_loss_c / (batch_idx + 1),\n 100. * minibatch_acc_a,\n 100. * minibatch_acc_b))\n\n print('\\n\\33[91mTrain Epoch {}: Avg loss: {:.4f} Spk Loss: {:.4f} Dom Loss: {:.4f} .'.format(epoch,\n total_loss / len(\n train_loader),\n total_loss_a / len(\n train_loader),\n total_loss_b / len(\n train_loader)))\n\n print('Spk Accuracy:{:.4f}%, Dom Accuracy:{:.4f}%.\\33[0m'.format(100 * correct_a / total_datasize,\n 100 * correct_b / total_datasize, ))\n\n writer.add_scalar('Train/Spk_Accuracy', correct_a / total_datasize, epoch)\n writer.add_scalar('Train/Dom_Accuracy', correct_b / total_datasize, epoch)\n writer.add_scalar('Train/Loss', total_loss / len(train_loader), epoch)\n\n torch.cuda.empty_cache()\n\n\ndef test(test_loader, valid_loader, model, epoch):\n # switch to evaluate mode\n model.eval()\n\n valid_pbar = tqdm(enumerate(valid_loader))\n softmax = nn.Softmax(dim=1)\n\n correct_a = 0.\n correct_b = 0.\n\n total_datasize = 0.\n\n for batch_idx, (data, label_a, label_b) in valid_pbar:\n data = Variable(data.cuda())\n\n # compute output\n out_a, _, out_b, _ = model(data)\n if args.loss_type == 'asoft':\n predicted_labels_a, _ = out_a\n\n else:\n predicted_labels_a = out_a\n predicted_labels_b = out_b\n\n true_labels_a = Variable(label_a.cuda())\n true_labels_b = Variable(label_b.cuda())\n\n # pdb.set_trace()\n predicted_one_labels_a = softmax(predicted_labels_a)\n predicted_one_labels_a = torch.max(predicted_one_labels_a, dim=1)[1]\n\n batch_correct_a = (predicted_one_labels_a.cuda() == true_labels_a.cuda()).sum().item()\n minibatch_acc_a = float(batch_correct_a / len(predicted_one_labels_a))\n correct_a += batch_correct_a\n\n predicted_one_labels_b = softmax(predicted_labels_b)\n predicted_one_labels_b = torch.max(predicted_one_labels_b, dim=1)[1]\n batch_correct_b = (predicted_one_labels_b.cuda() == true_labels_b.cuda()).sum().item()\n minibatch_acc_b = float(batch_correct_b / len(predicted_one_labels_b))\n correct_b += batch_correct_b\n\n total_datasize += len(predicted_one_labels_a)\n\n if batch_idx % args.log_interval == 0:\n valid_pbar.set_description(\n 'Valid Epoch: {:2d} [{:8d}/{:8d} ({:3.0f}%)] Batch Spk Accuracy: {:.4f}% Dom Accuracy: {:.4f}%'.format(\n epoch,\n batch_idx * len(data),\n len(valid_loader.dataset),\n 100. * batch_idx / len(valid_loader),\n 100. * minibatch_acc_a,\n 100. * minibatch_acc_b\n ))\n\n spk_valid_accuracy = 100. * correct_a / total_datasize\n dom_valid_accuracy = 100. * correct_b / total_datasize\n\n writer.add_scalar('Test/Spk_Valid_Accuracy', spk_valid_accuracy, epoch)\n writer.add_scalar('Test/Dom_Valid_Accuracy', dom_valid_accuracy, epoch)\n\n torch.cuda.empty_cache()\n\n labels, distances = [], []\n pbar = tqdm(enumerate(test_loader))\n for batch_idx, (data_a, data_p, label) in pbar:\n\n vec_a_shape = data_a.shape\n vec_p_shape = data_p.shape\n # pdb.set_trace()\n data_a = data_a.reshape(vec_a_shape[0] * vec_a_shape[1], 1, vec_a_shape[2], vec_a_shape[3])\n data_p = data_p.reshape(vec_p_shape[0] * vec_p_shape[1], 1, vec_p_shape[2], vec_p_shape[3])\n\n if args.cuda:\n data_a, data_p = data_a.cuda(), data_p.cuda()\n data_a, data_p, label = Variable(data_a), Variable(data_p), Variable(label)\n\n # compute output\n _, out_a_, _, _ = model(data_a)\n _, out_p_, _, _ = model(data_p)\n # out_a = out_a_\n # out_p = out_p_\n\n out_a = out_a_.reshape(vec_a_shape[0], vec_a_shape[1], args.embedding_size_a).mean(dim=1)\n out_p = out_p_.reshape(vec_p_shape[0], vec_p_shape[1], args.embedding_size_a).mean(dim=1)\n\n\n dists = l2_dist.forward(out_a, out_p) # torch.sqrt(torch.sum((out_a - out_p) ** 2, 1)) # euclidean distance\n # dists = dists.reshape(vec_shape[0], vec_shape[1]).mean(dim=1)\n dists = dists.data.cpu().numpy()\n\n distances.append(dists)\n labels.append(label.data.cpu().numpy())\n\n if batch_idx % args.log_interval == 0:\n pbar.set_description('Test Epoch: {} [{}/{} ({:.0f}%)]'.format(\n epoch, batch_idx * len(data_a), len(test_loader.dataset), 100. * batch_idx / len(test_loader)))\n\n labels = np.array([sublabel for label in labels for sublabel in label])\n distances = np.array([subdist for dist in distances for subdist in dist])\n\n eer, eer_threshold, accuracy = evaluate_kaldi_eer(distances, labels, cos=args.cos_sim, re_thre=True)\n writer.add_scalar('Test/EER', 100. * eer, epoch)\n writer.add_scalar('Test/Threshold', eer_threshold, epoch)\n\n mindcf_01, mindcf_001 = evaluate_kaldi_mindcf(distances, labels)\n writer.add_scalar('Test/mindcf-0.01', mindcf_01, epoch)\n writer.add_scalar('Test/mindcf-0.001', mindcf_001, epoch)\n\n dist_type = 'cos' if args.cos_sim else 'l2'\n print('\\nFor %s_distance, ' % dist_type)\n print(' \\33[91mTest Spk ERR is {:.4f}%, Threshold is {}'.format(100. * eer, eer_threshold))\n print(' mindcf-0.01 {:.4f}, mindcf-0.001 {:.4f},'.format(mindcf_01, mindcf_001))\n print(' Valid Spk Accuracy is %.4f %%, Dom Accuracy is %.4f %% .\\33[0m' % (spk_valid_accuracy, dom_valid_accuracy))\n\n torch.cuda.empty_cache()\n\n\nif __name__ == '__main__':\n main()\n", "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@Author: yangwenhao\n@Contact: [email protected]\n@Software: PyCharm\n@File: train_egs.py\n@Time: 2020/8/21 20:30\n@Overview:\n\"\"\"\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport os.path as osp\nimport shutil\nimport sys\nimport time\n# Version conflict\nimport warnings\nfrom collections import OrderedDict\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nfrom kaldi_io import read_mat, read_vec_flt\nfrom kaldiio import load_mat\nfrom tensorboardX import SummaryWriter\nfrom torch.autograd import Variable\nfrom torch.nn.parallel import DistributedDataParallel\nfrom torch.optim import lr_scheduler\nfrom tqdm import tqdm\n\nfrom Define_Model.Loss.LossFunction import CenterLoss, Wasserstein_Loss, MultiCenterLoss, CenterCosLoss, RingLoss, \\\n VarianceLoss\nfrom Define_Model.Loss.SoftmaxLoss import AngleSoftmaxLoss, AngleLinear, AdditiveMarginLinear, AMSoftmaxLoss, \\\n ArcSoftmaxLoss, \\\n GaussianLoss\nfrom Process_Data.Datasets.KaldiDataset import KaldiExtractDataset, \\\n ScriptVerifyDataset\nfrom Process_Data.Datasets.LmdbDataset import EgsDataset\nfrom Process_Data.audio_processing import ConcateVarInput, tolog, ConcateOrgInput, PadCollate\nfrom Process_Data.audio_processing import toMFB, totensor, truncatedinput\nfrom TrainAndTest.common_func import create_optimizer, create_model, verification_test, verification_extract\nfrom logger import NewLogger\n\nwarnings.filterwarnings(\"ignore\")\n\nimport torch._utils\n\ntry:\n torch._utils._rebuild_tensor_v2\nexcept AttributeError:\n def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):\n tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)\n tensor.requires_grad = requires_grad\n tensor._backward_hooks = backward_hooks\n return tensor\n\n\n torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch Speaker Recognition: Classification')\n\n# Data options\nparser.add_argument('--train-dir', type=str, required=True, help='path to dataset')\nparser.add_argument('--train-test-dir', type=str, required=True, help='path to dataset')\nparser.add_argument('--valid-dir', type=str, required=True, help='path to dataset')\nparser.add_argument('--test-dir', type=str, required=True, help='path to voxceleb1 test dataset')\nparser.add_argument('--log-scale', action='store_true', default=False, help='log power spectogram')\nparser.add_argument('--exp', action='store_true', default=False, help='exp power spectogram')\n\nparser.add_argument('--trials', type=str, default='trials', help='path to voxceleb1 test dataset')\nparser.add_argument('--train-trials', type=str, default='trials', help='path to voxceleb1 test dataset')\n\nparser.add_argument('--sitw-dir', type=str, help='path to voxceleb1 test dataset')\nparser.add_argument('--var-input', action='store_true', default=True, help='need to make mfb file')\nparser.add_argument('--test-input', type=str, default='fix', choices=['var', 'fix'],\n help='batchnorm with instance norm')\nparser.add_argument('--random-chunk', nargs='+', type=int, default=[], metavar='MINCHUNK')\nparser.add_argument('--chunk-size', type=int, default=300, metavar='CHUNK')\n\nparser.add_argument('--remove-vad', action='store_true', default=False, help='using Cosine similarity')\nparser.add_argument('--extract', action='store_true', default=True, help='need to make mfb file')\nparser.add_argument('--shuffle', action='store_false', default=True, help='need to shuffle egs')\n\nparser.add_argument('--nj', default=10, type=int, metavar='NJOB', help='num of job')\nparser.add_argument('--feat-format', type=str, default='kaldi', choices=['kaldi', 'npy', 'wav'],\n help='number of jobs to make feats (default: 10)')\n\nparser.add_argument('--check-path', default='Data/checkpoint/GradResNet8/vox1/spect_egs/soft_dp25',\n help='folder to output model checkpoints')\nparser.add_argument('--save-init', action='store_true', default=True, help='need to make mfb file')\nparser.add_argument('--resume',\n default='Data/checkpoint/GradResNet8/vox1/spect_egs/soft_dp25/checkpoint_10.pth', type=str,\n metavar='PATH',\n help='path to latest checkpoint (default: none)')\n\nparser.add_argument('--start-epoch', default=1, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('--epochs', type=int, default=20, metavar='E',\n help='number of epochs to train (default: 10)')\nparser.add_argument('--scheduler', default='multi', type=str,\n metavar='SCH', help='The optimizer to use (default: Adagrad)')\nparser.add_argument('--patience', default=3, type=int,\n metavar='PAT', help='patience for scheduler (default: 4)')\nparser.add_argument('--gamma', default=0.75, type=float,\n metavar='GAMMA', help='The optimizer to use (default: Adagrad)')\nparser.add_argument('--milestones', default='10,15', type=str,\n metavar='MIL', help='The optimizer to use (default: Adagrad)')\nparser.add_argument('--min-softmax-epoch', type=int, default=40, metavar='MINEPOCH',\n help='minimum epoch for initial parameter using softmax (default: 2')\nparser.add_argument('--veri-pairs', type=int, default=20000, metavar='VP',\n help='number of epochs to train (default: 10)')\n\n# Training options\n# Model options\nparser.add_argument('--model', type=str, help='path to voxceleb1 test dataset')\nparser.add_argument('--resnet-size', default=8, type=int,\n metavar='RES', help='The channels of convs layers)')\nparser.add_argument('--filter', type=str, default='None', help='replace batchnorm with instance norm')\nparser.add_argument('--filter-fix', action='store_true', default=False, help='replace batchnorm with instance norm')\n\nparser.add_argument('--input-norm', type=str, default='Mean', help='batchnorm with instance norm')\n\nparser.add_argument('--mask-layer', type=str, default='None', help='time or freq masking layers')\nparser.add_argument('--mask-len', type=int, default=20, help='maximum length of time or freq masking layers')\nparser.add_argument('--block-type', type=str, default='basic', help='replace batchnorm with instance norm')\nparser.add_argument('--relu-type', type=str, default='relu', help='replace batchnorm with instance norm')\nparser.add_argument('--transform', type=str, default=\"None\", help='add a transform layer after embedding layer')\n\nparser.add_argument('--vad', action='store_true', default=False, help='vad layers')\nparser.add_argument('--inception', action='store_true', default=False, help='multi size conv layer')\nparser.add_argument('--inst-norm', action='store_true', default=False, help='batchnorm with instance norm')\n\nparser.add_argument('--encoder-type', type=str, default='None', help='path to voxceleb1 test dataset')\nparser.add_argument('--channels', default='64,128,256', type=str, metavar='CHA', help='The channels of convs layers)')\nparser.add_argument('--first-2d', action='store_true', default=False,\n help='replace first tdnn layer with conv2d layers')\nparser.add_argument('--dilation', default='1,1,1,1', type=str, metavar='CHA', help='The dilation of convs layers)')\nparser.add_argument('--feat-dim', default=64, type=int, metavar='N', help='acoustic feature dimension')\nparser.add_argument('--input-dim', default=257, type=int, metavar='N', help='acoustic feature dimension')\nparser.add_argument('--accu-steps', default=1, type=int, metavar='N', help='manual epoch number (useful on restarts)')\n\nparser.add_argument('--alpha', default=12, type=float, metavar='FEAT', help='acoustic feature dimension')\nparser.add_argument('--ring', default=12, type=float, metavar='RING', help='acoustic feature dimension')\n\nparser.add_argument('--kernel-size', default='5,5', type=str, metavar='KE', help='kernel size of conv filters')\nparser.add_argument('--context', default='5,3,3,5', type=str, metavar='KE', help='kernel size of conv filters')\n\nparser.add_argument('--padding', default='', type=str, metavar='KE', help='padding size of conv filters')\nparser.add_argument('--stride', default='1', type=str, metavar='ST', help='stride size of conv filters')\nparser.add_argument('--fast', type=str, default='None', help='max pooling for fast')\n\nparser.add_argument('--cos-sim', action='store_true', default=False, help='using Cosine similarity')\nparser.add_argument('--avg-size', type=int, default=4, metavar='ES', help='Dimensionality of the embedding')\nparser.add_argument('--time-dim', default=1, type=int, metavar='FEAT', help='acoustic feature dimension')\nparser.add_argument('--embedding-size', type=int, default=128, metavar='ES',\n help='Dimensionality of the embedding')\nparser.add_argument('--batch-size', type=int, default=128, metavar='BS',\n help='input batch size for training (default: 128)')\nparser.add_argument('--input-per-spks', type=int, default=224, metavar='IPFT',\n help='input sample per file for testing (default: 8)')\nparser.add_argument('--num-valid', type=int, default=5, metavar='IPFT',\n help='input sample per file for testing (default: 8)')\nparser.add_argument('--test-input-per-file', type=int, default=4, metavar='IPFT',\n help='input sample per file for testing (default: 8)')\nparser.add_argument('--test-batch-size', type=int, default=4, metavar='BST',\n help='input batch size for testing (default: 64)')\nparser.add_argument('--dropout-p', type=float, default=0.0, metavar='BST',\n help='input batch size for testing (default: 64)')\n\n# loss configure\nparser.add_argument('--loss-type', type=str, default='soft',\n help='path to voxceleb1 test dataset')\nparser.add_argument('--num-center', type=int, default=2, help='the num of source classes')\nparser.add_argument('--source-cls', type=int, default=1951,\n help='the num of source classes')\nparser.add_argument('--finetune', action='store_true', default=False,\n help='using Cosine similarity')\nparser.add_argument('--lr-ratio', type=float, default=0.0, metavar='LOSSRATIO',\n help='the ratio softmax loss - triplet loss (default: 2.0')\nparser.add_argument('--loss-ratio', type=float, default=0.1, metavar='LOSSRATIO',\n help='the ratio softmax loss - triplet loss (default: 2.0')\n\n# args for additive margin-softmax\nparser.add_argument('--margin', type=float, default=0.3, metavar='MARGIN',\n help='the margin value for the angualr softmax loss function (default: 3.0')\nparser.add_argument('--s', type=float, default=15, metavar='S',\n help='the margin value for the angualr softmax loss function (default: 3.0')\n\n# args for a-softmax\nparser.add_argument('--all-iteraion', type=int, default=0, metavar='M',\n help='the margin value for the angualr softmax loss function (default: 3.0')\nparser.add_argument('--m', type=int, default=3, metavar='M',\n help='the margin value for the angualr softmax loss function (default: 3.0')\nparser.add_argument('--lambda-min', type=int, default=5, metavar='S',\n help='random seed (default: 0)')\nparser.add_argument('--lambda-max', type=float, default=1000, metavar='S',\n help='random seed (default: 0)')\n\nparser.add_argument('--lr', type=float, default=0.1, metavar='LR', help='learning rate (default: 0.125)')\nparser.add_argument('--lr-decay', default=0, type=float, metavar='LRD',\n help='learning rate decay ratio (default: 1e-4')\nparser.add_argument('--weight-decay', default=5e-4, type=float,\n metavar='WEI', help='weight decay (default: 0.0)')\nparser.add_argument('--second-wd', default=0, type=float,\n metavar='SWEI', help='weight decay (default: 0.0)')\nparser.add_argument('--filter-wd', default=0, type=float,\n metavar='FWEI', help='weight decay (default: 0.0)')\nparser.add_argument('--momentum', default=0.9, type=float,\n metavar='MOM', help='momentum for sgd (default: 0.9)')\nparser.add_argument('--dampening', default=0, type=float,\n metavar='DAM', help='dampening for sgd (default: 0.0)')\nparser.add_argument('--optimizer', default='sgd', type=str,\n metavar='OPT', help='The optimizer to use (default: Adagrad)')\nparser.add_argument('--grad-clip', default=0., type=float,\n help='gradient clip threshold (default: 0)')\n# Device options\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='enables CUDA training')\nparser.add_argument('--gpu-id', default='0', type=str,\n help='id(s) for CUDA_VISIBLE_DEVICES')\nparser.add_argument('--seed', type=int, default=123456, metavar='S',\n help='random seed (default: 0)')\nparser.add_argument('--log-interval', type=int, default=10, metavar='LI',\n help='how many batches to wait before logging training status')\n\nparser.add_argument('--acoustic-feature', choices=['fbank', 'spectrogram', 'mfcc'], default='fbank',\n help='choose the acoustic features type.')\nparser.add_argument('--makemfb', action='store_true', default=False,\n help='need to make mfb file')\nparser.add_argument('--makespec', action='store_true', default=False,\n help='need to make spectrograms file')\n\nargs = parser.parse_args()\n\n# Set the device to use by setting CUDA_VISIBLE_DEVICES env variable in\n# order to prevent any memory allocation on unused GPUs\nos.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id\n# os.environ['MASTER_ADDR'] = '127.0.0.1'\n# os.environ['MASTER_PORT'] = '29555'\n\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\n# torch.multiprocessing.set_sharing_strategy('file_system')\n\nif args.cuda:\n torch.cuda.manual_seed_all(args.seed)\n cudnn.benchmark = True\n\n# create logger\n# Define visulaize SummaryWriter instance\nwriter = SummaryWriter(logdir=args.check_path, filename_suffix='_first')\n\nsys.stdout = NewLogger(osp.join(args.check_path, 'log.%s.txt' % time.strftime(\"%Y.%m.%d\", time.localtime())))\n\nkwargs = {'num_workers': args.nj, 'pin_memory': False} if args.cuda else {}\nextract_kwargs = {'num_workers': args.nj, 'pin_memory': False} if args.cuda else {}\n\nif not os.path.exists(args.check_path):\n os.makedirs(args.check_path)\n\nopt_kwargs = {'lr': args.lr, 'lr_decay': args.lr_decay, 'weight_decay': args.weight_decay, 'dampening': args.dampening,\n 'momentum': args.momentum}\n\nl2_dist = nn.CosineSimilarity(dim=1, eps=1e-12) if args.cos_sim else nn.PairwiseDistance(p=2)\n\nif args.acoustic_feature == 'fbank':\n transform = transforms.Compose([\n totensor()\n ])\nelse:\n transform = transforms.Compose([\n truncatedinput(),\n toMFB(),\n totensor(),\n # tonormal()\n ])\n\nif args.test_input == 'var':\n transform_V = transforms.Compose([\n ConcateOrgInput(remove_vad=args.remove_vad, feat_type=args.feat_format),\n ])\nelif args.test_input == 'fix':\n transform_V = transforms.Compose([\n ConcateVarInput(remove_vad=args.remove_vad, num_frames=args.chunk_size, frame_shift=args.chunk_size,\n feat_type=args.feat_format),\n ])\n\nif args.log_scale:\n transform.transforms.append(tolog())\n transform_V.transforms.append(tolog())\n\n# pdb.set_trace()\nif args.feat_format == 'kaldi':\n file_loader = read_mat\nelif args.feat_format == 'npy':\n file_loader = np.load\nelif args.feat_format == 'wav':\n file_loader = load_mat\n\ntorch.multiprocessing.set_sharing_strategy('file_system')\n\ntrain_dir = EgsDataset(dir=args.train_dir, feat_dim=args.input_dim, loader=file_loader, transform=transform,\n batch_size=args.batch_size, random_chunk=args.random_chunk)\n\ntrain_extract_dir = KaldiExtractDataset(dir=args.train_test_dir,\n transform=transform_V,\n filer_loader=file_loader,\n trials_file=args.train_trials)\n\nextract_dir = KaldiExtractDataset(dir=args.test_dir, transform=transform_V,\n trials_file=args.trials, filer_loader=file_loader)\n\n# train_test_dir = ScriptTestDataset(dir=args.train_test_dir, loader=file_loader, transform=transform_T)\n# test_dir = ScriptTestDataset(dir=args.test_dir, loader=file_loader, transform=transform_T)\nvalid_dir = EgsDataset(dir=args.valid_dir, feat_dim=args.input_dim, loader=file_loader, transform=transform)\n\n\ndef train(train_loader, model, ce, optimizer, epoch, scheduler):\n # switch to evaluate mode\n model.train()\n\n correct = 0.\n total_datasize = 0.\n total_loss = 0.\n orth_err = 0\n\n ce_criterion, xe_criterion = ce\n pbar = tqdm(enumerate(train_loader))\n output_softmax = nn.Softmax(dim=1)\n # start_time = time.time()\n # pdb.set_trace()\n for batch_idx, (data, label) in pbar:\n if args.cuda:\n # label = label.cuda(non_blocking=True)\n # data = data.cuda(non_blocking=True)\n label = label.cuda()\n data = data.cuda()\n\n data, label = Variable(data), Variable(label)\n\n classfier, feats = model(data)\n # cos_theta, phi_theta = classfier\n classfier_label = classfier\n # print('max logit is ', classfier_label.max())\n\n if args.loss_type == 'soft':\n loss = ce_criterion(classfier, label)\n elif args.loss_type == 'asoft':\n classfier_label, _ = classfier\n loss = xe_criterion(classfier, label)\n elif args.loss_type in ['center', 'mulcenter', 'gaussian', 'coscenter', 'variance']:\n loss_cent = ce_criterion(classfier, label)\n loss_xent = xe_criterion(feats, label)\n\n loss = args.loss_ratio * loss_xent + loss_cent\n elif args.loss_type == 'ring':\n loss_cent = ce_criterion(classfier, label)\n loss_xent = xe_criterion(feats)\n loss = args.loss_ratio * loss_xent + loss_cent\n elif args.loss_type in ['amsoft', 'arcsoft']:\n loss = xe_criterion(classfier, label)\n\n predicted_labels = output_softmax(classfier_label)\n predicted_one_labels = torch.max(predicted_labels, dim=1)[1]\n minibatch_correct = float((predicted_one_labels.cpu() == label.cpu()).sum().item())\n minibatch_acc = minibatch_correct / len(predicted_one_labels)\n correct += minibatch_correct\n\n total_datasize += len(predicted_one_labels)\n total_loss += float(loss.item())\n\n if np.isnan(loss.item()):\n raise ValueError('Loss value is NaN!')\n\n # compute gradient and update weights\n loss.backward()\n\n if ((batch_idx + 1) % args.accu_steps) == 0:\n # optimizer the net\n optimizer.step() # update parameters of net\n optimizer.zero_grad() # reset gradient\n\n if args.model == 'FTDNN':\n if isinstance(model, DistributedDataParallel):\n model.module.step_ftdnn_layers() # The key method to constrain the first two convolutions, perform after every SGD step\n orth_err += model.module.get_orth_errors()\n else:\n model.step_ftdnn_layers() # The key method to constrain the first two convolutions, perform after every SGD step\n orth_err += model.get_orth_errors()\n\n # optimizer.zero_grad()\n # loss.backward()\n\n if args.loss_ratio != 0:\n if args.loss_type in ['center', 'mulcenter', 'gaussian', 'coscenter']:\n for param in xe_criterion.parameters():\n param.grad.data *= (1. / args.loss_ratio)\n\n if args.grad_clip > 0:\n this_lr = args.lr\n for param_group in optimizer.param_groups:\n this_lr = min(param_group['lr'], this_lr)\n torch.nn.utils.clip_grad_norm_(model.parameters(), this_lr * args.grad_clip)\n\n # optimizer.step()\n if args.scheduler == 'cyclic':\n scheduler.step()\n\n if (batch_idx + 1) % args.log_interval == 0:\n epoch_str = 'Train Epoch {}: [{:8d}/{:8d} ({:3.0f}%)]'.format(epoch, batch_idx * len(data),\n len(train_loader.dataset),\n 100. * batch_idx / len(train_loader))\n\n if len(args.random_chunk) == 2 and args.random_chunk[0] < args.random_chunk[1]:\n epoch_str += ' Batch Len: {:>3d}'.format(data.shape[-2])\n\n if orth_err > 0:\n epoch_str += ' Orth_err: {:>5d}'.format(int(orth_err))\n\n if args.loss_type in ['center', 'variance', 'mulcenter', 'gaussian', 'coscenter']:\n epoch_str += ' Center Loss: {:.4f}'.format(loss_xent.float())\n epoch_str += ' Avg Loss: {:.4f} Batch Accuracy: {:.4f}%'.format(total_loss / (batch_idx + 1),\n 100. * minibatch_acc)\n pbar.set_description(epoch_str)\n\n print('\\nEpoch {:>2d}: \\33[91mTrain Accuracy: {:.6f}%, Avg loss: {:6f}.\\33[0m'.format(epoch, 100 * float(\n correct) / total_datasize, total_loss / len(train_loader)))\n writer.add_scalar('Train/Accuracy', correct / total_datasize, epoch)\n writer.add_scalar('Train/Loss', total_loss / len(train_loader), epoch)\n\n torch.cuda.empty_cache()\n\n\ndef valid_class(valid_loader, model, ce, epoch):\n # switch to evaluate mode\n model.eval()\n\n total_loss = 0.\n ce_criterion, xe_criterion = ce\n softmax = nn.Softmax(dim=1)\n\n correct = 0.\n total_datasize = 0.\n\n with torch.no_grad():\n for batch_idx, (data, label) in enumerate(valid_loader):\n data = data.cuda()\n label = label.cuda()\n\n # compute output\n out, feats = model(data)\n if args.loss_type == 'asoft':\n predicted_labels, _ = out\n else:\n predicted_labels = out\n\n classfier = predicted_labels\n if args.loss_type == 'soft':\n loss = ce_criterion(classfier, label)\n elif args.loss_type == 'asoft':\n classfier_label, _ = classfier\n loss = xe_criterion(classfier, label)\n elif args.loss_type in ['variance', 'center', 'mulcenter', 'gaussian', 'coscenter']:\n loss_cent = ce_criterion(classfier, label)\n loss_xent = xe_criterion(feats, label)\n\n loss = args.loss_ratio * loss_xent + loss_cent\n elif args.loss_type == 'amsoft' or args.loss_type == 'arcsoft':\n loss = xe_criterion(classfier, label)\n\n total_loss += float(loss.item())\n # pdb.set_trace()\n predicted_one_labels = softmax(predicted_labels)\n predicted_one_labels = torch.max(predicted_one_labels, dim=1)[1]\n\n batch_correct = (predicted_one_labels.cuda() == label).sum().item()\n correct += batch_correct\n total_datasize += len(predicted_one_labels)\n\n valid_loss = total_loss / len(valid_loader)\n valid_accuracy = 100. * correct / total_datasize\n writer.add_scalar('Train/Valid_Loss', valid_loss, epoch)\n writer.add_scalar('Train/Valid_Accuracy', valid_accuracy, epoch)\n torch.cuda.empty_cache()\n print(' \\33[91mValid Accuracy: {:.6f}%, Avg loss: {:.6f}.\\33[0m'.format(valid_accuracy,\n valid_loss))\n\n return valid_loss\n\n\ndef valid_test(train_extract_loader, model, epoch, xvector_dir):\n # switch to evaluate mode\n model.eval()\n\n this_xvector_dir = \"%s/train/epoch_%s\" % (xvector_dir, epoch)\n verification_extract(train_extract_loader, model, this_xvector_dir, epoch, test_input=args.test_input)\n\n verify_dir = ScriptVerifyDataset(dir=args.train_test_dir, trials_file=args.train_trials,\n xvectors_dir=this_xvector_dir,\n loader=read_vec_flt)\n verify_loader = torch.utils.data.DataLoader(verify_dir, batch_size=128, shuffle=False, **kwargs)\n eer, eer_threshold, mindcf_01, mindcf_001 = verification_test(test_loader=verify_loader,\n dist_type=('cos' if args.cos_sim else 'l2'),\n log_interval=args.log_interval,\n xvector_dir=this_xvector_dir,\n epoch=epoch)\n\n print(' \\33[91mTrain EER: {:.4f}%, Threshold: {:.4f}, ' \\\n 'mindcf-0.01: {:.4f}, mindcf-0.001: {:.4f}. \\33[0m'.format(100. * eer,\n eer_threshold,\n mindcf_01,\n mindcf_001))\n\n writer.add_scalar('Train/EER', 100. * eer, epoch)\n writer.add_scalar('Train/Threshold', eer_threshold, epoch)\n writer.add_scalar('Train/mindcf-0.01', mindcf_01, epoch)\n writer.add_scalar('Train/mindcf-0.001', mindcf_001, epoch)\n\n torch.cuda.empty_cache()\n\n\ndef test(model, epoch, writer, xvector_dir):\n this_xvector_dir = \"%s/test/epoch_%s\" % (xvector_dir, epoch)\n\n extract_loader = torch.utils.data.DataLoader(extract_dir, batch_size=1, shuffle=False, **extract_kwargs)\n verification_extract(extract_loader, model, this_xvector_dir, epoch, test_input=args.test_input)\n\n verify_dir = ScriptVerifyDataset(dir=args.test_dir, trials_file=args.trials, xvectors_dir=this_xvector_dir,\n loader=read_vec_flt)\n verify_loader = torch.utils.data.DataLoader(verify_dir, batch_size=128, shuffle=False, **kwargs)\n eer, eer_threshold, mindcf_01, mindcf_001 = verification_test(test_loader=verify_loader,\n dist_type=('cos' if args.cos_sim else 'l2'),\n log_interval=args.log_interval,\n xvector_dir=this_xvector_dir,\n epoch=epoch)\n print(\n ' \\33[91mTest ERR: {:.4f}%, Threshold: {:.4f}, mindcf-0.01: {:.4f}, mindcf-0.001: {:.4f}.\\33[0m\\n'.format(\n 100. * eer, eer_threshold, mindcf_01, mindcf_001))\n\n writer.add_scalar('Test/EER', 100. * eer, epoch)\n writer.add_scalar('Test/Threshold', eer_threshold, epoch)\n writer.add_scalar('Test/mindcf-0.01', mindcf_01, epoch)\n writer.add_scalar('Test/mindcf-0.001', mindcf_001, epoch)\n\n\ndef main():\n # Views the training images and displays the distance on anchor-negative and anchor-positive\n # test_display_triplet_distance = False\n # print the experiment configuration\n print('\\nCurrent time is \\33[91m{}\\33[0m.'.format(str(time.asctime())))\n opts = vars(args)\n keys = list(opts.keys())\n keys.sort()\n\n options = []\n for k in keys:\n options.append(\"\\'%s\\': \\'%s\\'\" % (str(k), str(opts[k])))\n\n print('Parsed options: \\n{ %s }' % (', '.join(options)))\n print('Number of Speakers: {}.\\n'.format(train_dir.num_spks))\n\n # instantiate model and initialize weights\n kernel_size = args.kernel_size.split(',')\n kernel_size = [int(x) for x in kernel_size]\n\n context = args.context.split(',')\n context = [int(x) for x in context]\n if args.padding == '':\n padding = [int((x - 1) / 2) for x in kernel_size]\n else:\n padding = args.padding.split(',')\n padding = [int(x) for x in padding]\n\n kernel_size = tuple(kernel_size)\n padding = tuple(padding)\n stride = args.stride.split(',')\n stride = [int(x) for x in stride]\n\n channels = args.channels.split(',')\n channels = [int(x) for x in channels]\n\n dilation = args.dilation.split(',')\n dilation = [int(x) for x in dilation]\n model_kwargs = {'input_dim': args.input_dim, 'feat_dim': args.feat_dim, 'kernel_size': kernel_size,\n 'context': context, 'filter_fix': args.filter_fix, 'dilation': dilation,\n 'first_2d': args.first_2d,\n 'mask': args.mask_layer, 'mask_len': args.mask_len, 'block_type': args.block_type,\n 'filter': args.filter, 'exp': args.exp, 'inst_norm': args.inst_norm, 'input_norm': args.input_norm,\n 'stride': stride, 'fast': args.fast, 'avg_size': args.avg_size, 'time_dim': args.time_dim,\n 'padding': padding, 'encoder_type': args.encoder_type, 'vad': args.vad,\n 'transform': args.transform, 'embedding_size': args.embedding_size, 'ince': args.inception,\n 'resnet_size': args.resnet_size, 'num_classes': train_dir.num_spks,\n 'num_classes_b': train_dir.num_doms,\n 'channels': channels, 'alpha': args.alpha, 'dropout_p': args.dropout_p,\n 'loss_type': args.loss_type, 'm': args.m, 'margin': args.margin, 's': args.s,\n 'iteraion': 0, 'all_iteraion': args.all_iteraion}\n\n print('Model options: {}'.format(model_kwargs))\n dist_type = 'cos' if args.cos_sim else 'l2'\n print('Testing with %s distance, ' % dist_type)\n\n model = create_model(args.model, **model_kwargs)\n\n start_epoch = 0\n if args.save_init and not args.finetune:\n check_path = '{}/checkpoint_{}.pth'.format(args.check_path, start_epoch)\n torch.save(model, check_path)\n\n iteration = 0 # if args.resume else 0\n if args.finetune and args.resume:\n if os.path.isfile(args.resume):\n print('=> loading checkpoint {}'.format(args.resume))\n checkpoint = torch.load(args.resume)\n start_epoch = checkpoint['epoch']\n\n checkpoint_state_dict = checkpoint['state_dict']\n if isinstance(checkpoint_state_dict, tuple):\n checkpoint_state_dict = checkpoint_state_dict[0]\n filtered = {k: v for k, v in checkpoint_state_dict.items() if 'num_batches_tracked' not in k}\n if list(filtered.keys())[0].startswith('module'):\n new_state_dict = OrderedDict()\n for k, v in filtered.items():\n name = k[7:] # remove `module.`,表面从第7个key值字符取到最后一个字符,去掉module.\n new_state_dict[name] = v # 新字典的key值对应的value为一一对应的值。\n\n model.load_state_dict(new_state_dict)\n else:\n model_dict = model.state_dict()\n model_dict.update(filtered)\n model.load_state_dict(model_dict)\n # model.dropout.p = args.dropout_p\n else:\n print('=> no checkpoint found at {}'.format(args.resume))\n\n ce_criterion = nn.CrossEntropyLoss()\n if args.loss_type == 'soft':\n xe_criterion = None\n elif args.loss_type == 'asoft':\n ce_criterion = None\n xe_criterion = AngleSoftmaxLoss(lambda_min=args.lambda_min, lambda_max=args.lambda_max)\n elif args.loss_type == 'center':\n xe_criterion = CenterLoss(num_classes=train_dir.num_spks, feat_dim=args.embedding_size)\n elif args.loss_type == 'variance':\n xe_criterion = VarianceLoss(num_classes=train_dir.num_spks, feat_dim=args.embedding_size)\n elif args.loss_type == 'gaussian':\n xe_criterion = GaussianLoss(num_classes=train_dir.num_spks, feat_dim=args.embedding_size)\n elif args.loss_type == 'coscenter':\n xe_criterion = CenterCosLoss(num_classes=train_dir.num_spks, feat_dim=args.embedding_size)\n elif args.loss_type == 'mulcenter':\n xe_criterion = MultiCenterLoss(num_classes=train_dir.num_spks, feat_dim=args.embedding_size,\n num_center=args.num_center)\n elif args.loss_type == 'amsoft':\n ce_criterion = None\n xe_criterion = AMSoftmaxLoss(margin=args.margin, s=args.s)\n elif args.loss_type == 'arcsoft':\n ce_criterion = None\n xe_criterion = ArcSoftmaxLoss(margin=args.margin, s=args.s, iteraion=iteration, all_iteraion=args.all_iteraion)\n elif args.loss_type == 'wasse':\n xe_criterion = Wasserstein_Loss(source_cls=args.source_cls)\n elif args.loss_type == 'ring':\n xe_criterion = RingLoss(ring=args.ring)\n args.alpha = 0.0\n\n model_para = [{'params': model.parameters()}]\n if args.loss_type in ['center', 'variance', 'mulcenter', 'gaussian', 'coscenter', 'ring']:\n assert args.lr_ratio > 0\n model_para.append({'params': xe_criterion.parameters(), 'lr': args.lr * args.lr_ratio})\n\n if args.finetune or args.second_wd > 0:\n # if args.loss_type in ['asoft', 'amsoft']:\n classifier_params = list(map(id, model.classifier.parameters()))\n rest_params = filter(lambda p: id(p) not in classifier_params, model.parameters())\n init_lr = args.lr * args.lr_ratio if args.lr_ratio > 0 else args.lr\n init_wd = args.second_wd if args.second_wd > 0 else args.weight_decay\n print('Set the lr and weight_decay of classifier to %f and %f' % (init_lr, init_wd))\n model_para = [{'params': rest_params},\n {'params': model.classifier.parameters(), 'lr': init_lr, 'weight_decay': init_wd}]\n\n if args.filter in ['fDLR', 'fBLayer', 'fLLayer', 'fBPLayer']:\n filter_params = list(map(id, model.filter_layer.parameters()))\n rest_params = filter(lambda p: id(p) not in filter_params, model_para[0]['params'])\n init_wd = args.filter_wd if args.filter_wd > 0 else args.weight_decay\n init_lr = args.lr * args.lr_ratio if args.lr_ratio > 0 else args.lr\n print('Set the lr and weight_decay of filter layer to %f and %f' % (init_lr, init_wd))\n model_para[0]['params'] = rest_params\n model_para.append({'params': model.filter_layer.parameters(), 'lr': init_lr,\n 'weight_decay': init_wd})\n\n optimizer = create_optimizer(model_para, args.optimizer, **opt_kwargs)\n\n if not args.finetune and args.resume:\n if os.path.isfile(args.resume):\n print('=> loading checkpoint {}'.format(args.resume))\n checkpoint = torch.load(args.resume)\n start_epoch = checkpoint['epoch']\n\n checkpoint_state_dict = checkpoint['state_dict']\n if isinstance(checkpoint_state_dict, tuple):\n checkpoint_state_dict = checkpoint_state_dict[0]\n filtered = {k: v for k, v in checkpoint_state_dict.items() if 'num_batches_tracked' not in k}\n\n # filtered = {k: v for k, v in checkpoint['state_dict'].items() if 'num_batches_tracked' not in k}\n if list(filtered.keys())[0].startswith('module'):\n new_state_dict = OrderedDict()\n for k, v in filtered.items():\n name = k[7:] # remove `module.`,表面从第7个key值字符取到最后一个字符,去掉module.\n new_state_dict[name] = v # 新字典的key值对应的value为一一对应的值。\n\n model.load_state_dict(new_state_dict)\n else:\n model_dict = model.state_dict()\n model_dict.update(filtered)\n model.load_state_dict(model_dict)\n # model.dropout.p = args.dropout_p\n else:\n print('=> no checkpoint found at {}'.format(args.resume))\n\n # Save model config txt\n with open(osp.join(args.check_path, 'model.%s.conf' % time.strftime(\"%Y.%m.%d\", time.localtime())), 'w') as f:\n f.write('model: ' + str(model) + '\\n')\n f.write('CrossEntropy: ' + str(ce_criterion) + '\\n')\n f.write('Other Loss: ' + str(xe_criterion) + '\\n')\n f.write('Optimizer: ' + str(optimizer) + '\\n')\n\n milestones = args.milestones.split(',')\n milestones = [int(x) for x in milestones]\n milestones.sort()\n if args.scheduler == 'exp':\n scheduler = lr_scheduler.ExponentialLR(optimizer, gamma=args.gamma)\n elif args.scheduler == 'rop':\n scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, patience=args.patience, min_lr=1e-5)\n elif args.scheduler == 'cyclic':\n cycle_momentum = False if args.optimizer == 'adam' else True\n scheduler = lr_scheduler.CyclicLR(optimizer, base_lr=1e-8, max_lr=args.lr, step_size_up=13000,\n cycle_momentum=cycle_momentum)\n else:\n scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=milestones, gamma=0.1)\n\n ce = [ce_criterion, xe_criterion]\n\n start = args.start_epoch + start_epoch\n print('Start epoch is : ' + str(start))\n # start = 0\n end = start + args.epochs\n\n if len(args.random_chunk) == 2 and args.random_chunk[0] < args.random_chunk[1]:\n min_chunk_size = int(args.random_chunk[0])\n max_chunk_size = int(args.random_chunk[1])\n pad_dim = 2 if args.feat_format == 'kaldi' else 3\n\n train_loader = torch.utils.data.DataLoader(train_dir, batch_size=args.batch_size,\n collate_fn=PadCollate(dim=pad_dim,\n num_batch=int(\n np.ceil(len(train_dir) / args.batch_size)),\n min_chunk_size=min_chunk_size,\n max_chunk_size=max_chunk_size),\n shuffle=args.shuffle, **kwargs)\n valid_loader = torch.utils.data.DataLoader(valid_dir, batch_size=int(args.batch_size / 2),\n collate_fn=PadCollate(dim=pad_dim, fix_len=True,\n min_chunk_size=args.chunk_size,\n max_chunk_size=args.chunk_size + 1),\n shuffle=False, **kwargs)\n else:\n train_loader = torch.utils.data.DataLoader(train_dir, batch_size=args.batch_size, shuffle=args.shuffle,\n **kwargs)\n valid_loader = torch.utils.data.DataLoader(valid_dir, batch_size=int(args.batch_size / 2), shuffle=False,\n **kwargs)\n train_extract_loader = torch.utils.data.DataLoader(train_extract_dir, batch_size=1, shuffle=False, **extract_kwargs)\n\n if args.cuda:\n if len(args.gpu_id) > 1:\n print(\"Continue with gpu: %s ...\" % str(args.gpu_id))\n torch.distributed.init_process_group(backend=\"nccl\",\n # init_method='tcp://localhost:23456',\n init_method='file:///home/ssd2020/yangwenhao/lstm_speaker_verification/data/sharedfile',\n rank=0,\n world_size=1)\n # if args.gain\n # model = DistributedDataParallel(model.cuda(), find_unused_parameters=True)\n model = DistributedDataParallel(model.cuda())\n\n\n else:\n model = model.cuda()\n\n for i in range(len(ce)):\n if ce[i] != None:\n ce[i] = ce[i].cuda()\n try:\n print('Dropout is {}.'.format(model.dropout_p))\n except:\n pass\n\n xvector_dir = args.check_path\n xvector_dir = xvector_dir.replace('checkpoint', 'xvector')\n start_time = time.time()\n\n try:\n for epoch in range(start, end):\n # pdb.set_trace()\n lr_string = '\\n\\33[1;34m Current \\'{}\\' learning rate is '.format(args.optimizer)\n for param_group in optimizer.param_groups:\n lr_string += '{:.10f} '.format(param_group['lr'])\n print('%s \\33[0m' % lr_string)\n\n train(train_loader, model, ce, optimizer, epoch, scheduler)\n valid_loss = valid_class(valid_loader, model, ce, epoch)\n\n if (epoch == 1 or epoch != (end - 2)) and (epoch % 4 == 1 or epoch in milestones or epoch == (end - 1)):\n model.eval()\n check_path = '{}/checkpoint_{}.pth'.format(args.check_path, epoch)\n model_state_dict = model.module.state_dict() \\\n if isinstance(model, DistributedDataParallel) else model.state_dict()\n torch.save({'epoch': epoch,\n 'state_dict': model_state_dict,\n 'criterion': ce},\n check_path)\n\n valid_test(train_extract_loader, model, epoch, xvector_dir)\n test(model, epoch, writer, xvector_dir)\n if epoch != (end - 1):\n try:\n shutil.rmtree(\"%s/train/epoch_%s\" % (xvector_dir, epoch))\n shutil.rmtree(\"%s/test/epoch_%s\" % (xvector_dir, epoch))\n except Exception as e:\n print('rm dir xvectors error:', e)\n\n if args.scheduler == 'rop':\n scheduler.step(valid_loss)\n elif args.scheduler == 'cyclic':\n continue\n else:\n scheduler.step()\n\n except KeyboardInterrupt:\n end = epoch\n\n writer.close()\n stop_time = time.time()\n t = float(stop_time - start_time)\n print(\"Running %.4f minutes for each epoch.\\n\" % (t / 60 / (max(end - start, 1))))\n exit(0)\n\n\nif __name__ == '__main__':\n main()", "#!/usr/bin/env python -u\n# encoding: utf-8\n\n\"\"\"\n@Author: yangwenhao\n@Contact: [email protected]\n@Software: PyCharm\n@File: test_accuracy.py\n@Time: 19-8-6 下午1:29\n@Overview: Train the resnet 34 with asoftmax.\n\"\"\"\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport os.path as osp\nimport sys\nimport time\n# Version conflict\nimport warnings\n\nimport numpy as np\nimport torch\nimport torch.backends.cudnn as cudnn\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nfrom kaldi_io import read_mat\nfrom tensorboardX import SummaryWriter\nfrom torch.autograd import Variable\nfrom torch.optim.lr_scheduler import MultiStepLR, ExponentialLR\nfrom tqdm import tqdm\n\nfrom Define_Model.LossFunction import CenterLoss\nfrom Define_Model.SoftmaxLoss import AngleSoftmaxLoss, AngleLinear, AdditiveMarginLinear, AMSoftmaxLoss\nfrom Define_Model.TDNN import ETDNN\nfrom Define_Model.model import PairwiseDistance\nfrom Process_Data import constants as c\nfrom Process_Data.KaldiDataset import ScriptTrainDataset, ScriptTestDataset, ScriptValidDataset\nfrom Process_Data.audio_processing import concateinputfromMFB, to2tensor\nfrom Process_Data.audio_processing import toMFB, totensor, truncatedinput, read_audio\nfrom TrainAndTest.common_func import create_optimizer\nfrom eval_metrics import evaluate_kaldi_eer, evaluate_kaldi_mindcf\nfrom logger import NewLogger\n\nwarnings.filterwarnings(\"ignore\")\n\nimport torch._utils\n\ntry:\n torch._utils._rebuild_tensor_v2\nexcept AttributeError:\n def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):\n tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)\n tensor.requires_grad = requires_grad\n tensor._backward_hooks = backward_hooks\n return tensor\n\n\n torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch Speaker Recognition')\n# Data options\nparser.add_argument('--train-dir', type=str,\n default='/home/yangwenhao/local/project/lstm_speaker_verification/data/Vox1_pyfb80/dev_kaldi',\n help='path to dataset')\nparser.add_argument('--test-dir', type=str,\n default='/home/yangwenhao/local/project/lstm_speaker_verification/data/Vox1_pyfb80/test_kaldi',\n help='path to voxceleb1 test dataset')\nparser.add_argument('--sitw-dir', type=str,\n default='/home/yangwenhao/local/project/lstm_speaker_verification/data/sitw',\n help='path to voxceleb1 test dataset')\nparser.add_argument('--nj', default=12, type=int, metavar='NJOB', help='num of job')\n\nparser.add_argument('--check-path', default='Data/checkpoint/ASTDNN/fbank24/soft',\n help='folder to output model checkpoints')\nparser.add_argument('--save-init', action='store_true', default=True, help='need to make mfb file')\nparser.add_argument('--resume',\n default='Data/checkpoint/ASTDNN/fbank24/soft/checkpoint_10.pth', type=str,\n metavar='PATH',\n help='path to latest checkpoint (default: none)')\n\nparser.add_argument('--start-epoch', default=1, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('--epochs', type=int, default=20, metavar='E',\n help='number of epochs to train (default: 10)')\nparser.add_argument('--scheduler', default='multi', type=str,\n metavar='SCH', help='The optimizer to use (default: Adagrad)')\nparser.add_argument('--gamma', default=0.75, type=float,\n metavar='GAMMA', help='The optimizer to use (default: Adagrad)')\nparser.add_argument('--milestones', default='10,15', type=str,\n metavar='MIL', help='The optimizer to use (default: Adagrad)')\nparser.add_argument('--min-softmax-epoch', type=int, default=40, metavar='MINEPOCH',\n help='minimum epoch for initial parameter using softmax (default: 2')\nparser.add_argument('--veri-pairs', type=int, default=12800, metavar='VP',\n help='number of epochs to train (default: 10)')\n\n# Training options\n# Model options\nparser.add_argument('--feat-dim', default=80, type=int, metavar='FEAT',\n help='acoustic feature dimension')\nparser.add_argument('--cos-sim', action='store_true', default=True,\n help='using Cosine similarity')\nparser.add_argument('--embedding-size', type=int, default=256, metavar='ES',\n help='Dimensionality of the embedding')\nparser.add_argument('--batch-size', type=int, default=128, metavar='BS',\n help='input batch size for training (default: 128)')\nparser.add_argument('--input-per-spks', type=int, default=224, metavar='IPFT',\n help='input sample per file for testing (default: 8)')\nparser.add_argument('--num-valid', type=int, default=2, metavar='IPFT',\n help='input sample per file for testing (default: 8)')\nparser.add_argument('--test-input-per-file', type=int, default=4, metavar='IPFT',\n help='input sample per file for testing (default: 8)')\nparser.add_argument('--test-batch-size', type=int, default=4, metavar='BST',\n help='input batch size for testing (default: 64)')\nparser.add_argument('--dropout-p', type=float, default=0., metavar='BST',\n help='input batch size for testing (default: 64)')\n\n# loss configure\nparser.add_argument('--loss-type', type=str, default='soft', choices=['soft', 'asoft', 'center', 'amsoft'],\n help='path to voxceleb1 test dataset')\nparser.add_argument('--loss-ratio', type=float, default=0.1, metavar='LOSSRATIO',\n help='the ratio softmax loss - triplet loss (default: 2.0')\n\n# args for additive margin-softmax\nparser.add_argument('--margin', type=float, default=0.3, metavar='MARGIN',\n help='the margin value for the angualr softmax loss function (default: 3.0')\nparser.add_argument('--s', type=float, default=15, metavar='S',\n help='the margin value for the angualr softmax loss function (default: 3.0')\n\n# args for a-softmax\nparser.add_argument('--m', type=int, default=3, metavar='M',\n help='the margin value for the angualr softmax loss function (default: 3.0')\nparser.add_argument('--lambda-min', type=int, default=5, metavar='S',\n help='random seed (default: 0)')\nparser.add_argument('--lambda-max', type=float, default=0.05, metavar='S',\n help='random seed (default: 0)')\n\nparser.add_argument('--lr', type=float, default=0.01, metavar='LR', help='learning rate (default: 0.125)')\nparser.add_argument('--lr-decay', default=0, type=float, metavar='LRD',\n help='learning rate decay ratio (default: 1e-4')\nparser.add_argument('--weight-decay', default=5e-4, type=float,\n metavar='WEI', help='weight decay (default: 0.0)')\nparser.add_argument('--momentum', default=0.9, type=float,\n metavar='MOM', help='momentum for sgd (default: 0.9)')\nparser.add_argument('--dampening', default=0, type=float,\n metavar='DAM', help='dampening for sgd (default: 0.0)')\nparser.add_argument('--optimizer', default='sgd', type=str,\n metavar='OPT', help='The optimizer to use (default: Adagrad)')\n\n# Device options\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='enables CUDA training')\nparser.add_argument('--gpu-id', default='1', type=str,\n help='id(s) for CUDA_VISIBLE_DEVICES')\nparser.add_argument('--seed', type=int, default=123456, metavar='S',\n help='random seed (default: 0)')\nparser.add_argument('--log-interval', type=int, default=12, metavar='LI',\n help='how many batches to wait before logging training status')\n\nparser.add_argument('--acoustic-feature', choices=['fbank', 'spectrogram', 'mfcc'], default='fbank',\n help='choose the acoustic features type.')\nparser.add_argument('--makemfb', action='store_true', default=False,\n help='need to make mfb file')\nparser.add_argument('--makespec', action='store_true', default=False,\n help='need to make spectrograms file')\n\nargs = parser.parse_args()\n\n# Set the device to use by setting CUDA_VISIBLE_DEVICES env variable in\n# order to prevent any memory allocation on unused GPUs\nos.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id\n\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\ntorch.multiprocessing.set_sharing_strategy('file_system')\n\nif args.cuda:\n torch.cuda.manual_seed_all(args.seed)\n cudnn.benchmark = True\n\n# create logger\n# Define visulaize SummaryWriter instance\nwriter = SummaryWriter(logdir=args.check_path, filename_suffix='_first')\n\nsys.stdout = NewLogger(osp.join(args.check_path, 'log.txt'))\n\nkwargs = {'num_workers': args.nj, 'pin_memory': True} if args.cuda else {}\nif not os.path.exists(args.check_path):\n os.makedirs(args.check_path)\n\nopt_kwargs = {'lr': args.lr,\n 'lr_decay': args.lr_decay,\n 'weight_decay': args.weight_decay,\n 'dampening': args.dampening,\n 'momentum': args.momentum}\n\nl2_dist = nn.CosineSimilarity(dim=1, eps=1e-6) if args.cos_sim else PairwiseDistance(2)\n\nif args.acoustic_feature == 'fbank':\n transform = transforms.Compose([\n concateinputfromMFB(num_frames=c.NUM_FRAMES_SPECT, remove_vad=True),\n # varLengthFeat(),\n to2tensor()\n ])\n transform_T = transforms.Compose([\n concateinputfromMFB(num_frames=c.NUM_FRAMES_SPECT, input_per_file=args.test_input_per_file, remove_vad=True),\n # varLengthFeat(),\n to2tensor()\n ])\n\nelse:\n transform = transforms.Compose([\n truncatedinput(),\n toMFB(),\n totensor(),\n # tonormal()\n ])\n file_loader = read_audio\n\n# pdb.set_trace()\nfile_loader = read_mat\ntrain_dir = ScriptTrainDataset(dir=args.train_dir, samples_per_speaker=args.input_per_spks, loader=file_loader,\n transform=transform, num_valid=args.num_valid)\ntest_dir = ScriptTestDataset(dir=args.test_dir, loader=file_loader, transform=transform_T)\n\nif len(test_dir) < args.veri_pairs:\n args.veri_pairs = len(test_dir)\n print('There are %d verification pairs.' % len(test_dir))\nelse:\n test_dir.partition(args.veri_pairs)\n\n# indices = list(range(len(test_dir)))\n# random.shuffle(indices)\n# indices = indices[:args.veri_pairs]\n# test_part = torch.utils.data.Subset(test_dir, indices)\n\n# sitw_test_dir = SitwTestDataset(sitw_dir=args.sitw_dir, sitw_set='eval', transform=transform_T, set_suffix='')\n# if len(sitw_test_dir) < args.veri_pairs:\n# args.veri_pairs = len(sitw_test_dir)\n# print('There are %d verification pairs in sitw eval.' % len(sitw_test_dir))\n# else:\n# sitw_test_dir.partition(args.veri_pairs)\n\nvalid_dir = ScriptValidDataset(valid_set=train_dir.valid_set, loader=file_loader, spk_to_idx=train_dir.spk_to_idx,\n valid_uid2feat=train_dir.valid_uid2feat, valid_utt2spk_dict=train_dir.valid_utt2spk_dict,\n transform=transform)\n\n\ndef main():\n # Views the training images and displays the distance on anchor-negative and anchor-positive\n # test_display_triplet_distance = False\n # print the experiment configuration\n print('\\nCurrent time is \\33[91m{}\\33[0m.'.format(str(time.asctime())))\n print('Parsed options: {}'.format(vars(args)))\n print('Number of Speakers: {}.\\n'.format(train_dir.num_spks))\n\n model = ETDNN(num_spk=train_dir.num_spks, embedding_size=args.embedding_size,\n input_dim=args.feat_dim, dropout_p=args.dropout_p)\n\n start_epoch = 0\n if args.save_init:\n check_path = '{}/checkpoint_{}.pth'.format(args.check_path, start_epoch)\n torch.save(model, check_path)\n\n if args.resume:\n if os.path.isfile(args.resume):\n print('=> loading checkpoint {}'.format(args.resume))\n checkpoint = torch.load(args.resume)\n start_epoch = checkpoint['epoch']\n\n filtered = {k: v for k, v in checkpoint['state_dict'].items() if 'num_batches_tracked' not in k}\n model_dict = model.state_dict()\n model_dict.update(filtered)\n\n model.load_state_dict(model_dict)\n #\n model.dropout.p = args.dropout_p\n else:\n print('=> no checkpoint found at {}'.format(args.resume))\n\n ce_criterion = nn.CrossEntropyLoss()\n if args.loss_type == 'soft':\n xe_criterion = None\n elif args.loss_type == 'asoft':\n ce_criterion = None\n model.classifier = AngleLinear(in_features=args.embedding_size, out_features=train_dir.num_spks, m=args.m)\n all_iteration = train_dir.num_spks * args.input_per_spks / args.batch_size * args.epochs\n lambda_max = int(all_iteration * args.lambda_max / 2) // 50 * 50\n xe_criterion = AngleSoftmaxLoss(lambda_min=args.lambda_min, lambda_max=lambda_max)\n elif args.loss_type == 'center':\n xe_criterion = CenterLoss(num_classes=train_dir.num_spks, feat_dim=args.embedding_size)\n elif args.loss_type == 'amsoft':\n ce_criterion = None\n model.classifier = AdditiveMarginLinear(feat_dim=args.embedding_size, n_classes=train_dir.num_spks)\n xe_criterion = AMSoftmaxLoss(margin=args.margin, s=args.s)\n\n optimizer = create_optimizer(model.parameters(), args.optimizer, **opt_kwargs)\n if args.loss_type == 'center':\n optimizer = torch.optim.SGD([{'params': xe_criterion.parameters(), 'lr': args.lr * 5},\n {'params': model.parameters()}],\n lr=args.lr, weight_decay=args.weight_decay,\n momentum=args.momentum)\n\n if args.scheduler == 'exp':\n scheduler = ExponentialLR(optimizer, gamma=args.gamma)\n else:\n milestones = args.milestones.split(',')\n milestones = [int(x) for x in milestones]\n milestones.sort()\n scheduler = MultiStepLR(optimizer, milestones=milestones, gamma=0.1)\n\n ce = [ce_criterion, xe_criterion]\n\n start = args.start_epoch + start_epoch\n print('Start epoch is : ' + str(start))\n # start = 0\n end = start + args.epochs\n\n train_loader = torch.utils.data.DataLoader(train_dir, batch_size=args.batch_size, shuffle=True, **kwargs)\n valid_loader = torch.utils.data.DataLoader(valid_dir, batch_size=int(args.batch_size / 2), shuffle=False, **kwargs)\n test_loader = torch.utils.data.DataLoader(test_dir, batch_size=args.test_batch_size, shuffle=False, **kwargs)\n # sitw_test_loader = torch.utils.data.DataLoader(sitw_test_dir, batch_size=args.test_batch_size,\n # shuffle=False, **kwargs)\n # sitw_dev_loader = torch.utils.data.DataLoader(sitw_dev_part, batch_size=args.test_batch_size, shuffle=False,\n # **kwargs)\n\n if args.cuda:\n model = model.cuda()\n for i in range(len(ce)):\n if ce[i] != None:\n ce[i] = ce[i].cuda()\n\n for epoch in range(start, end):\n # pdb.set_trace()\n print('\\n\\33[1;34m Current \\'{}\\' learning rate is '.format(args.optimizer), end='')\n for param_group in optimizer.param_groups:\n print('{:.5f} '.format(param_group['lr']), end='')\n print(' \\33[0m')\n\n train(train_loader, model, ce, optimizer, scheduler, epoch)\n test(test_loader, valid_loader, model, epoch)\n # sitw_test(sitw_test_loader, model, epoch)\n # sitw_test(sitw_dev_loader, model, epoch)\n scheduler.step()\n # exit(1)\n\n writer.close()\n\n\ndef train(train_loader, model, ce, optimizer, scheduler, epoch):\n # switch to evaluate mode\n model.train()\n\n correct = 0.\n total_datasize = 0.\n total_loss = 0.\n # for param_group in optimizer.param_groups:\n # print('\\33[1;34m Optimizer \\'{}\\' learning rate is {}.\\33[0m'.format(args.optimizer, param_group['lr']))\n ce_criterion, xe_criterion = ce\n pbar = tqdm(enumerate(train_loader))\n output_softmax = nn.Softmax(dim=1)\n\n for batch_idx, (data, label) in pbar:\n if args.cuda:\n data = data.float().cuda()\n data, label = Variable(data), Variable(label)\n\n # pdb.set_trace()\n classfier, feats = model(data)\n true_labels = label.cuda()\n # cos_theta, phi_theta = classfier\n classfier_label = classfier\n\n if args.loss_type == 'soft':\n loss = ce_criterion(classfier, true_labels)\n elif args.loss_type == 'asoft':\n classfier_label, _ = classfier\n loss = xe_criterion(classfier, true_labels)\n elif args.loss_type == 'center':\n loss_cent = ce_criterion(classfier, true_labels)\n loss_xent = xe_criterion(feats, true_labels)\n loss = args.loss_ratio * loss_xent + loss_cent\n elif args.loss_type == 'amsoft':\n loss = xe_criterion(classfier, true_labels)\n\n predicted_labels = output_softmax(classfier_label)\n predicted_one_labels = torch.max(predicted_labels, dim=1)[1]\n minibatch_acc = float((predicted_one_labels.cuda() == true_labels.cuda()).sum().item()) / len(\n predicted_one_labels)\n correct += float((predicted_one_labels.cuda() == true_labels.cuda()).sum().item())\n total_datasize += len(predicted_one_labels)\n total_loss += loss.item()\n\n # compute gradient and update weights\n optimizer.zero_grad()\n loss.backward()\n\n if args.loss_type == 'center' and args.loss_ratio != 0:\n for param in xe_criterion.parameters():\n param.grad.data *= (1. / args.loss_ratio)\n\n optimizer.step()\n\n if batch_idx % args.log_interval == 0:\n pbar.set_description(\n 'Train Epoch {:2d}: [{:8d}/{:8d} ({:3.0f}%)] Avg Loss: {:.4f} Batch Accuracy: {:.4f}%'.format(\n epoch,\n batch_idx * len(data),\n len(train_loader.dataset),\n 100. * batch_idx / len(train_loader),\n total_loss / (batch_idx + 1),\n 100. * minibatch_acc))\n\n check_path = '{}/checkpoint_{}.pth'.format(args.check_path, epoch)\n torch.save({'epoch': epoch,\n 'state_dict': model.state_dict(),\n 'criterion': ce},\n check_path)\n\n print('\\n\\33[91mTrain Epoch {}: Train Accuracy:{:.6f}%, Avg loss: {}.\\33[0m'.format(epoch, 100 * float(\n correct) / total_datasize, total_loss / len(train_loader)))\n writer.add_scalar('Train/Accuracy', correct / total_datasize, epoch)\n writer.add_scalar('Train/Loss', total_loss / len(train_loader), epoch)\n\n torch.cuda.empty_cache()\n\n\ndef test(test_loader, valid_loader, model, epoch):\n # switch to evaluate mode\n model.eval()\n\n valid_pbar = tqdm(enumerate(valid_loader))\n softmax = nn.Softmax(dim=1)\n\n correct = 0.\n total_datasize = 0.\n\n for batch_idx, (data, label) in valid_pbar:\n data = Variable(data.cuda())\n\n # compute output\n out, _ = model(data)\n if args.loss_type == 'asoft':\n predicted_labels, _ = out\n else:\n predicted_labels = out\n\n true_labels = Variable(label.cuda())\n\n # pdb.set_trace()\n predicted_one_labels = softmax(predicted_labels)\n predicted_one_labels = torch.max(predicted_one_labels, dim=1)[1]\n\n batch_correct = (predicted_one_labels.cuda() == true_labels.cuda()).sum().item()\n minibatch_acc = float(batch_correct / len(predicted_one_labels))\n correct += batch_correct\n total_datasize += len(predicted_one_labels)\n\n if batch_idx % args.log_interval == 0:\n valid_pbar.set_description('Valid Epoch: {:2d} [{:8d}/{:8d} ({:3.0f}%)] Batch Accuracy: {:.4f}%'.format(\n epoch,\n batch_idx * len(data),\n len(valid_loader.dataset),\n 100. * batch_idx / len(valid_loader),\n 100. * minibatch_acc\n ))\n\n valid_accuracy = 100. * correct / total_datasize\n writer.add_scalar('Test/Valid_Accuracy', valid_accuracy, epoch)\n torch.cuda.empty_cache()\n\n labels, distances = [], []\n pbar = tqdm(enumerate(test_loader))\n for batch_idx, (data_a, data_p, label) in pbar:\n\n vec_shape = data_a.shape\n # pdb.set_trace()\n if vec_shape[1] != 1:\n data_a = data_a.reshape(vec_shape[0] * vec_shape[1], 1, vec_shape[2], vec_shape[3])\n data_p = data_p.reshape(vec_shape[0] * vec_shape[1], 1, vec_shape[2], vec_shape[3])\n\n if args.cuda:\n data_a, data_p = data_a.cuda(), data_p.cuda()\n data_a, data_p, label = Variable(data_a), Variable(data_p), Variable(label)\n\n # compute output\n _, out_a_ = model(data_a)\n _, out_p_ = model(data_p)\n out_a = out_a_\n out_p = out_p_\n\n dists = l2_dist.forward(out_a, out_p) # torch.sqrt(torch.sum((out_a - out_p) ** 2, 1)) # euclidean distance\n dists = dists.reshape(vec_shape[0], vec_shape[1]).mean(axis=1)\n dists = dists.data.cpu().numpy()\n\n distances.append(dists)\n labels.append(label.data.cpu().numpy())\n\n if batch_idx % args.log_interval == 0:\n pbar.set_description('Test Epoch: {} [{}/{} ({:.0f}%)]'.format(\n epoch, batch_idx * len(data_a), len(test_loader.dataset), 100. * batch_idx / len(test_loader)))\n\n labels = np.array([sublabel for label in labels for sublabel in label])\n distances = np.array([subdist for dist in distances for subdist in dist])\n\n eer, eer_threshold, accuracy = evaluate_kaldi_eer(distances, labels, cos=args.cos_sim, re_thre=True)\n writer.add_scalar('Test/EER', 100. * eer, epoch)\n writer.add_scalar('Test/Threshold', eer_threshold, epoch)\n\n mindcf_01, mindcf_001 = evaluate_kaldi_mindcf(distances, labels)\n writer.add_scalar('Test/mindcf-0.01', mindcf_01, epoch)\n writer.add_scalar('Test/mindcf-0.001', mindcf_001, epoch)\n\n dist_type = 'cos' if args.cos_sim else 'l2'\n print('\\nFor %s_distance, ' % dist_type)\n print(' \\33[91mTest ERR is {:.4f}%, Threshold is {}'.format(100. * eer, eer_threshold))\n print(' mindcf-0.01 {:.4f}, mindcf-0.001 {:.4f},'.format(mindcf_01, mindcf_001))\n print(' Valid Accuracy is %.4f %%.\\33[0m' % valid_accuracy)\n\n torch.cuda.empty_cache()\n\n\ndef sitw_test(sitw_test_loader, model, epoch):\n # switch to evaluate mode\n model.eval()\n\n labels, distances = [], []\n pbar = tqdm(enumerate(sitw_test_loader))\n for batch_idx, (data_a, data_p, label) in pbar:\n\n vec_shape = data_a.shape\n # pdb.set_trace()\n if vec_shape[1] != 1:\n data_a = data_a.reshape(vec_shape[0] * vec_shape[1], 1, vec_shape[2], vec_shape[3])\n data_p = data_p.reshape(vec_shape[0] * vec_shape[1], 1, vec_shape[2], vec_shape[3])\n\n if args.cuda:\n data_a, data_p = data_a.cuda(), data_p.cuda()\n data_a, data_p, label = Variable(data_a), Variable(data_p), Variable(label)\n\n # compute output\n _, out_a_ = model(data_a)\n _, out_p_ = model(data_p)\n out_a = out_a_\n out_p = out_p_\n\n dists = l2_dist.forward(out_a, out_p) # torch.sqrt(torch.sum((out_a - out_p) ** 2, 1)) # euclidean distance\n if vec_shape[1] != 1:\n dists = dists.reshape(vec_shape[0], vec_shape[1]).mean(axis=1)\n dists = dists.data.cpu().numpy()\n\n distances.append(dists)\n labels.append(label.data.cpu().numpy())\n\n if batch_idx % args.log_interval == 0:\n pbar.set_description('Test Epoch: {} [{}/{} ({:.0f}%)]'.format(\n epoch, batch_idx * vec_shape[0], len(sitw_test_loader.dataset),\n 100. * batch_idx / len(sitw_test_loader)))\n\n labels = np.array([sublabel for label in labels for sublabel in label])\n distances = np.array([subdist for dist in distances for subdist in dist])\n\n eer_t, eer_threshold_t, accuracy = evaluate_kaldi_eer(distances, labels, cos=args.cos_sim, re_thre=True)\n torch.cuda.empty_cache()\n\n writer.add_scalars('Test/EER', {'sitw_test': 100. * eer_t}, epoch)\n writer.add_scalars('Test/Threshold', {'sitw_test': eer_threshold_t}, epoch)\n\n print('\\33[91mFor Sitw Test ERR: {:.4f}%, Threshold: {}.\\n\\33[0m'.format(100. * eer_t, eer_threshold_t))\n\n\n# python TrainAndTest/Spectrogram/train_surescnn10_kaldi.py > Log/SuResCNN10/spect_161/\n\nif __name__ == '__main__':\n main()\n", "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@Author: yangwenhao\n@Contact: [email protected]\n@Software: PyCharm\n@File: validate_data.py\n@Time: 2019/9/26 上午10:51\n@Overview:\n\nLoad /home/cca01/work2019/yangwenhao/mydataset/voxceleb2/fbank64/dev/aac/id02912/88v-sPZl5-w/00010.wav error!\nLoad /home/cca01/work2019/yangwenhao/mydataset/voxceleb2/fbank24/dev/aac/id00518/7PRhib9U-DQ/00007.wav error!\n\"\"\"\nfrom __future__ import print_function\n\n# import os\n# import pathlib\nimport pdb\nfrom multiprocessing import Queue, Process\nimport multiprocessing\n\nimport numpy as np\nfrom Process_Data.Datasets.voxceleb2_wav_reader import voxceleb2_list_reader\nfrom Process_Data.Datasets.voxceleb_wav_reader import wav_list_reader\n\ndataroot = '/home/cca01/work2019/yangwenhao/mydataset/voxceleb1/Fbank64_Norm'\n\nnum_pro = 0.\nskip_wav = 0.\n\n\ndef check_from_queue(queue, error_queue, spk_utt_duration, cpid, share_lock):\n # return np.load('/home/cca01/work2019/yangwenhao/mydataset/voxceleb2/fbank64/dev/aac/id02912/88v-sPZl5-w/00010.npy')\n while not queue.empty():\n vox2 = queue.get()\n\n write_path = dataroot + '/' + vox2['filename'].decode('utf-8') + '.npy'\n spk = vox2['speaker_id'].decode('utf-8')\n #print(dict(spk_utt_duration))\n\n # pdb.set_trace()\n try:\n item = np.load(write_path)\n #print('feat length: ' + str(len(item)))\n share_lock.acquire()\n if spk not in spk_utt_duration.keys():\n spk_utt_duration[spk] = []\n this_spk = spk_utt_duration[spk]\n this_spk.append(len(item))\n spk_utt_duration[spk] = this_spk\n share_lock.release()\n # print('')\n except Exception:\n error_queue.put(vox2)\n #share_lock.release()\n print('\\rProcess {}: There are {:6d} features left.'.format(cpid, queue.qsize()), end='\\r')\n pass\n\ndef add_duration_vox(queue, error_queue, vox_duration, cpid, share_lock):\n while not queue.empty():\n vox2 = queue.get()\n\n write_path = dataroot + '/' + vox2['filename'].decode('utf-8') + '.npy'\n\n # pdb.set_trace()\n try:\n item = np.load(write_path)\n #print('feat length: ' + str(len(item)))\n share_lock.acquire()\n vox2['duration'] = len(item)\n vox_duration.append(vox2)\n\n share_lock.release()\n # print('')\n except Exception:\n error_queue.put(vox2)\n #share_lock.release()\n print('\\rProcess {}: There are {:6d} features left.'.format(cpid, queue.qsize()), end='\\r')\n pass\n\nif __name__ == '__main__':\n queue = Queue()\n que_queue = Queue()\n # voxceleb2, voxceleb2_dev = voxceleb2_list_reader(dataroot)\n vox1, vox1_dev = wav_list_reader(dataroot)\n vox_duration = multiprocessing.Manager().list()\n # spk_utt_duration = multiprocessing.Manager().dict()\n\n share_lock = multiprocessing.Manager().Lock()\n\n for i in range(len(vox1)):\n queue.put(vox1[i])\n\n #check_from_queue(queue, que_queue, 1)\n\n process_list = []\n for i in range(15):\n # pro = Process(target=check_from_queue, args=(queue, que_queue, spk_utt_duration, i, share_lock))\n pro = Process(target=add_duration_vox, args=(queue, que_queue, vox_duration, i, share_lock))\n process_list.append(pro)\n\n for process in process_list:\n process.start()\n for process in process_list:\n process.join()\n\n # print(dict(spk_utt_duration))\n # np.save(dataroot+'/spk_utt_duration.npy', dict(spk_utt_duration))\n np.save(dataroot + '/vox_duration.npy', list(vox_duration))\n if que_queue.empty():\n print('\\nChecking Fbank features success without error!.')\n else:\n print('Error Fbank features are :')\n while not que_queue.empty():\n ti = que_queue.get()\n print(ti)\n\n exit(1)\n\n", "#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\n@Author: yangwenhao\n@Contact: [email protected]\n@Software: PyCharm\n@File: test_accuracy.py\n@Time: 19-6-19 下午5:17\n@Overview:\n\"\"\"\n# from __future__ import print_function\nimport argparse\nimport pdb\nimport random\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision.transforms as transforms\nfrom tensorboardX import SummaryWriter\nfrom torch.autograd import Variable\nimport torch.backends.cudnn as cudnn\nimport os\n\nimport numpy as np\nfrom tqdm import tqdm\nfrom Define_Model.ResNet import SimpleResNet, ResNet\nfrom Define_Model.TDNN import Time_Delay\nfrom Define_Model.model import ResSpeakerModel\nfrom Process_Data.KaldiDataset import KaldiTestDataset\nfrom eval_metrics import evaluate_kaldi_eer\n# from DeepSpeakerDataset_static import DeepSpeakerDataset\nfrom Process_Data.DeepSpeakerDataset_dynamic import DeepSpeakerDataset, ClassificationDataset\nfrom Process_Data.VoxcelebTestset import VoxcelebTestset\nfrom Process_Data.voxceleb_wav_reader import wav_list_reader\n\nfrom Define_Model.model import PairwiseDistance, ResCNNSpeaker, SuperficialResCNN\nfrom Process_Data.audio_processing import toMFB, totensor, truncatedinput, truncatedinputfromMFB, read_MFB, read_audio, \\\n mk_MFB, concateinputfromMFB, varLengthFeat\n# Version conflict\n\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\nimport torch._utils\n\ntry:\n torch._utils._rebuild_tensor_v2\nexcept AttributeError:\n def _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks):\n tensor = torch._utils._rebuild_tensor(storage, storage_offset, size, stride)\n tensor.requires_grad = requires_grad\n tensor._backward_hooks = backward_hooks\n return tensor\n\n\n torch._utils._rebuild_tensor_v2 = _rebuild_tensor_v2\n\n# Training settings\nparser = argparse.ArgumentParser(description='PyTorch Speaker Recognition')\n# Model options\nparser.add_argument('--test-dir', type=str,\n default='/home/cca01/work2019/yangwenhao/NewAdded/kaldi/egs/voxceleb/v4/data/voxceleb1_test_no_sil',\n help='path to voxceleb1 test dataset')\n\nparser.add_argument('--test-pairs-path', type=str, default='Data/dataset/voxceleb1/test_trials/ver_list.txt',\n help='path to pairs file')\n\nparser.add_argument('--resume', default='Data/checkpoint/SiResNet34/soft/kaldi/checkpoint_{}.pth', type=str,\n metavar='PATH',\n help='path to latest checkpoint (default: none)')\n\n# Training options\nparser.add_argument('--cos-sim', action='store_true', default=True,\n help='using Cosine similarity')\nparser.add_argument('--embedding-size', type=int, default=1024, metavar='ES',\n help='Dimensionality of the embedding')\nparser.add_argument('--resnet-size', type=int, default=10, metavar='E',\n help='depth of resnet to train (default: 34)')\nparser.add_argument('--batch-size', type=int, default=512, metavar='BS',\n help='input batch size for training (default: 128)')\nparser.add_argument('--test-batch-size', type=int, default=1, metavar='BST',\n help='input batch size for testing (default: 64)')\nparser.add_argument('--test-input-per-file', type=int, default=1, metavar='IPFT',\n help='input sample per file for testing (default: 8)')\n\n# Device options\nparser.add_argument('--no-cuda', action='store_true', default=False,\n help='enables CUDA training')\nparser.add_argument('--gpu-id', default='3', type=str,\n help='id(s) for CUDA_VISIBLE_DEVICES')\nparser.add_argument('--seed', type=int, default=3, metavar='S',\n help='random seed (default: 0)')\nparser.add_argument('--log-interval', type=int, default=1, metavar='LI',\n help='how many batches to wait before logging training status')\n\nparser.add_argument('--acoustic-feature', choices=['fbank', 'spectrogram', 'mfcc'], default='fbank',\n help='choose the acoustic features type.')\n\nargs = parser.parse_args()\n\n# set the device to use by setting CUDA_VISIBLE_DEVICES env variable in\n# order to prevent any memory allocation on unused GPUs\nos.environ['CUDA_VISIBLE_DEVICES'] = args.gpu_id\n\nargs.cuda = not args.no_cuda and torch.cuda.is_available()\nnp.random.seed(args.seed)\n\nif args.cuda:\n cudnn.benchmark = True\n\nkwargs = {'num_workers': 2, 'pin_memory': True} if args.cuda else {}\n\nl2_dist = nn.CosineSimilarity(dim=1, eps=1e-6) if args.cos_sim else PairwiseDistance(2)\n\n# voxceleb, voxceleb_dev = wav_list_reader(args.dataroot)\n\ntransform = transforms.Compose([\n varLengthFeat(),\n totensor()\n])\n\ntest_dir = KaldiTestDataset(dir=args.test_dir, transform=transform)\nindices = list(range(len(test_dir)))\nrandom.shuffle(indices)\nindices = indices[:4800]\ntest_part = torch.utils.data.Subset(test_dir, indices)\n\nwriter = SummaryWriter('Data/checkpoint/SiResNet34/soft/kaldi/', filename_suffix='eer')\n\n\ndef main():\n # print the experiment configuration\n print('Parsed options:\\n{}\\n'.format(vars(args)))\n model = SimpleResNet(layers=[3, 4, 6, 3], num_classes=1211)\n\n if args.cuda:\n model.cuda()\n\n test_loader = torch.utils.data.DataLoader(test_part, batch_size=args.test_batch_size, shuffle=False, **kwargs)\n\n epochs = np.arange(1, 29)\n\n for epoch in epochs:\n # Load model from Checkpoint file\n if os.path.isfile(args.resume.format(epoch)):\n print('=> loading checkpoint {}'.format(args.resume.format(epoch)))\n checkpoint = torch.load(args.resume.format(epoch))\n args.start_epoch = checkpoint['epoch']\n filtered = {k: v for k, v in checkpoint['state_dict'].items() if 'num_batches_tracked' not in k}\n model.load_state_dict(filtered)\n # optimizer.load_state_dict(checkpoint['optimizer'])\n else:\n print('=> no checkpoint found at {}'.format(args.resume))\n break\n # train_test(train_loader, model, epoch)\n test(test_loader, model, epoch)\n\n writer.close()\n\n\ndef train_test(test_loader, model, epoch):\n # switch to evaluate mode\n model.eval()\n\n labels, distances = [], []\n x_vectors = []\n\n pbar = tqdm(enumerate(test_loader))\n for batch_idx, (data_a, label) in pbar:\n\n if args.cuda:\n data_a = data_a.cuda()\n\n data_a = Variable(data_a)\n\n labels.append(label.data.numpy())\n\n if batch_idx % args.log_interval == 0:\n pbar.set_description('Test Epoch: {} [{}/{} ({:.0f}%)]'.format(\n epoch, batch_idx * len(data_a), len(test_loader.dataset),\n 100. * batch_idx / len(test_loader)))\n\n try:\n x_vectors = np.array(x_vectors)\n labels = np.array(labels)\n # labels.append(label.numpy())\n except Exception:\n pdb.set_trace()\n\n # err, accuracy= evaluate_eer(distances,labels)\n # eer, accuracy = evaluate_kaldi_eer(distances, labels, cos=args.cos_sim)\n try:\n # np.save('Data/xvector/train/x_vectors.npy', x_vectors)\n np.save('Data/xvector/train/label.npy', labels)\n print('Extracted {} x_vectors from train set.'.format(len(x_vectors)))\n except:\n pdb.set_trace()\n\n # tpr, fpr, accuracy, val, far = evaluate(distances, labels)\n\n # logger.log_value('Test Accuracy', np.mean(accuracy))\n\n\ndef test(test_loader, model, epoch):\n # switch to evaluate mode\n model.eval()\n\n labels, distances = [], []\n pbar = tqdm(enumerate(test_loader))\n for batch_idx, (data_a, data_p, label) in pbar:\n\n if args.cuda:\n data_a, data_p = data_a.cuda(), data_p.cuda()\n\n data_a, data_p, label = Variable(data_a), \\\n Variable(data_p), Variable(label)\n\n # SiResNet34\n out_a = model.pre_forward_norm(data_a)\n out_p = model.pre_forward_norm(data_p)\n\n dists = l2_dist.forward(out_a, out_p)\n dists = dists.data.cpu().numpy()\n distances.append(dists)\n labels.append(label.data.cpu().numpy())\n\n if batch_idx % args.log_interval == 0:\n pbar.set_description('Test Epoch: {} [{}/{} ({:.0f}%)]'.format(\n epoch, batch_idx * len(data_a), len(test_loader.dataset),\n 100. * batch_idx / len(test_loader)))\n\n labels = np.array([sublabel for label in labels for sublabel in label])\n distances = np.array([subdist for dist in distances for subdist in dist])\n\n eer, eer_threshold, accuracy = evaluate_kaldi_eer(distances, labels, cos=args.cos_sim, re_thre=True)\n writer.add_scalar('Test/EER', eer, epoch - 1)\n writer.add_scalar('Test/Threshold', eer_threshold, epoch - 1)\n\n print('\\33[91mFor {}_distance, Test ERR: {:.8f}, Threshold: {:.8f}.\\n\\33[0m'.format('cos' if args.cos_sim else 'l2',\n 100. * eer, eer_threshold))\n\n\nif __name__ == '__main__':\n main()\n" ]
[ [ "numpy.matmul", "numpy.linalg.norm", "numpy.finfo", "numpy.load", "numpy.zeros" ], [ "torch.nn.Softmax", "torch.max", "torch.load", "torch.utils.data.DataLoader", "torch.cuda.is_available", "torch.cuda.manual_seed_all", "numpy.exp", "torch.autograd.Variable", "torch.optim.lr_scheduler.MultiStepLR", "torch.save", "torch.nn.CrossEntropyLoss", "torch.nn.CosineSimilarity", "torch.cuda.empty_cache", "numpy.array", "numpy.random.seed", "torch.manual_seed", "torch.cosine_similarity", "torch.optim.lr_scheduler.ExponentialLR", "torch._utils._rebuild_tensor", "torch.multiprocessing.set_sharing_strategy" ], [ "torch.nn.Softmax", "torch.max", "torch.load", "torch.utils.data.DataLoader", "torch.no_grad", "torch.cuda.is_available", "torch.cuda.manual_seed_all", "torch.nn.PairwiseDistance", "torch.autograd.Variable", "torch.save", "torch.optim.lr_scheduler.MultiStepLR", "torch.nn.CrossEntropyLoss", "torch.optim.lr_scheduler.ReduceLROnPlateau", "torch.distributed.init_process_group", "torch.nn.CosineSimilarity", "torch.optim.lr_scheduler.CyclicLR", "torch.cuda.empty_cache", "numpy.random.seed", "torch.manual_seed", "torch.optim.lr_scheduler.ExponentialLR", "torch._utils._rebuild_tensor", "torch.multiprocessing.set_sharing_strategy" ], [ "torch.optim.lr_scheduler.MultiStepLR", "torch.nn.Softmax", "torch.nn.CrossEntropyLoss", "torch.max", "numpy.random.seed", "torch.load", "torch.manual_seed", "torch.utils.data.DataLoader", "torch.cuda.empty_cache", "torch.nn.CosineSimilarity", "torch.optim.lr_scheduler.ExponentialLR", "torch.autograd.Variable", "torch._utils._rebuild_tensor", "torch.cuda.is_available", "torch.cuda.manual_seed_all", "numpy.array", "torch.multiprocessing.set_sharing_strategy", "torch.save" ], [ "numpy.load" ], [ "numpy.random.seed", "numpy.arange", "torch.utils.data.DataLoader", "torch.nn.CosineSimilarity", "numpy.save", "torch._utils._rebuild_tensor", "torch.cuda.is_available", "torch.utils.data.Subset", "numpy.array", "torch.autograd.Variable" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
mmicromegas/ransX
[ "2faaa786e00cfd14dce0e18f0793cd0252428d2a", "2faaa786e00cfd14dce0e18f0793cd0252428d2a" ]
[ "EQUATIONS/InternalEnergyEquation.py", "CANUTO1997/LuminosityEquation.py" ]
[ "import numpy as np\nimport matplotlib.pyplot as plt\nfrom UTILS.Calculus import Calculus\nfrom UTILS.SetAxisLimit import SetAxisLimit\nfrom UTILS.Tools import Tools\nfrom UTILS.Errors import Errors\nimport sys\n\n\n# Theoretical background https://arxiv.org/abs/1401.5176\n\n# Mocak, Meakin, Viallet, Arnett, 2014, Compressible Hydrodynamic Mean-Field #\n# Equations in Spherical Geometry and their Application to Turbulent Stellar #\n# Convection Data #\n\nclass InternalEnergyEquation(Calculus, SetAxisLimit, Tools, Errors, object):\n\n def __init__(self, filename, ig, fext, intc, tke_diss, data_prefix):\n super(InternalEnergyEquation, self).__init__(ig)\n\n # load data to structured array\n eht = self.customLoad(filename)\n\n # load grid\n xzn0 = self.getRAdata(eht, 'xzn0')\n nx = self.getRAdata(eht, 'nx')\n\n # pick equation-specific Reynolds-averaged mean fields according to:\n # https://github.com/mmicromegas/ransX/blob/master/DOCS/ransXimplementationGuide.pdf\t\n\n dd = self.getRAdata(eht, 'dd')[intc]\n ux = self.getRAdata(eht, 'ux')[intc]\n pp = self.getRAdata(eht, 'pp')[intc]\n\n ddux = self.getRAdata(eht, 'ddux')[intc]\n ddei = self.getRAdata(eht, 'ddei')[intc]\n ddeiux = self.getRAdata(eht, 'ddeiux')[intc]\n\n divu = self.getRAdata(eht, 'divu')[intc]\n ppdivu = self.getRAdata(eht, 'ppdivu')[intc]\n\n ddenuc1 = self.getRAdata(eht, 'ddenuc1')[intc]\n ddenuc2 = self.getRAdata(eht, 'ddenuc2')[intc]\n\n # store time series for time derivatives\n t_timec = self.getRAdata(eht, 'timec')\n t_dd = self.getRAdata(eht, 'dd')\n t_ddei = self.getRAdata(eht, 'ddei')\n t_fht_ei = t_ddei / t_dd\n\n # construct equation-specific mean fields\t\t\n fht_ux = ddux / dd\n fht_ei = ddei / dd\n fei = ddeiux - ddux * ddei / dd\n\n ##########################\n # INTERNAL ENERGY EQUATION \n ##########################\n\n # LHS -dq/dt \t\t\n self.minus_dt_dd_fht_ei = -self.dt(t_dd * t_fht_ei, xzn0, t_timec, intc)\n\n # LHS -div dd fht_ux fht_ei\t\t\n self.minus_div_dd_fht_ux_fht_ei = -self.Div(dd * fht_ux * fht_ei, xzn0)\n\n # RHS -div fei\n self.minus_div_fei = -self.Div(fei, xzn0)\n\n # RHS -div ftt (not included) heat flux\n self.minus_div_ftt = -np.zeros(nx)\n\n # RHS -P d = - pp Div ux\n self.minus_pp_div_ux = -pp * self.Div(ux, xzn0)\n\n # RHS -Wp = -eht_ppf_df\n self.minus_eht_ppf_df = -(ppdivu - pp * divu)\n\n # RHS source + dd enuc\n self.plus_dd_fht_enuc = ddenuc1 + ddenuc2\n\n # RHS dissipated turbulent kinetic energy\n self.plus_disstke = +tke_diss\n\n # -res\n self.minus_resEiEquation = -(self.minus_dt_dd_fht_ei + self.minus_div_dd_fht_ux_fht_ei +\n self.minus_div_fei + self.minus_div_ftt + self.minus_pp_div_ux + self.minus_eht_ppf_df +\n self.plus_dd_fht_enuc + self.plus_disstke)\n\n ##############################\n # END INTERNAL ENERGY EQUATION \n ##############################\n\n # assign global data to be shared across whole class\n self.data_prefix = data_prefix\n self.xzn0 = xzn0\n self.fht_ei = fht_ei\n self.fext = fext\n\n def plot_ei(self, LAXIS, bconv, tconv, xbl, xbr, ybu, ybd, ilg):\n \"\"\"Plot mean Favrian internal energy stratification in the model\"\"\"\n\n if self.ig != 1 and self.ig != 2:\n print(\"ERROR(InternalEnergyEquation.py):\" + self.errorGeometry(self.ig))\n sys.exit()\n\n # load x GRID\n grd1 = self.xzn0\n\n # load DATA to plot\n plt1 = self.fht_ei\n\n # create FIGURE\n plt.figure(figsize=(7, 6))\n\n # format AXIS, make sure it is exponential\n plt.gca().yaxis.get_major_formatter().set_powerlimits((0, 0))\n\n # set plot boundaries \n to_plot = [plt1]\n self.set_plt_axis(LAXIS, xbl, xbr, ybu, ybd, to_plot)\n\n # plot DATA \n plt.title(r'internal energy')\n plt.plot(grd1, plt1, color='brown', label=r'$\\widetilde{\\varepsilon}_I$')\n\n # convective boundary markers\n plt.axvline(bconv, linestyle='--', linewidth=0.7, color='k')\n plt.axvline(tconv, linestyle='--', linewidth=0.7, color='k')\n\n # define and show x/y LABELS\n if self.ig == 1:\n setxlabel = r\"x (cm)\"\n setylabel = r\"$\\widetilde{\\varepsilon}_I$ (erg g$^{-1}$)\"\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n elif self.ig == 2:\n setxlabel = r\"r (cm)\"\n setylabel = r\"$\\widetilde{\\varepsilon}_I$ (erg g$^{-1}$)\"\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n\n # show LEGEND\n plt.legend(loc=ilg, prop={'size': 18})\n\n # display PLOT\n plt.show(block=False)\n\n # save PLOT\n if self.fext == 'png':\n plt.savefig('RESULTS/' + self.data_prefix + 'mean_ei.png')\n elif self.fext == 'eps':\n plt.savefig('RESULTS/' + self.data_prefix + 'mean_ei.eps')\n\n def plot_ei_equation(self, LAXIS, bconv, tconv, xbl, xbr, ybu, ybd, ilg):\n \"\"\"Plot internal energy equation in the model\"\"\"\n\n if self.ig != 1 and self.ig != 2:\n print(\"ERROR(InternalEnergyEquation.py):\" + self.errorGeometry(self.ig))\n sys.exit()\n\n # load x GRID\n grd1 = self.xzn0\n\n lhs0 = self.minus_dt_dd_fht_ei\n lhs1 = self.minus_div_dd_fht_ux_fht_ei\n\n rhs0 = self.minus_div_fei\n rhs1 = self.minus_div_ftt\n rhs2 = self.minus_pp_div_ux\n rhs3 = self.minus_eht_ppf_df\n rhs4 = self.plus_dd_fht_enuc\n rhs5 = self.plus_disstke\n\n res = self.minus_resEiEquation\n\n # create FIGURE\n plt.figure(figsize=(7, 6))\n\n # format AXIS, make sure it is exponential\n plt.gca().yaxis.get_major_formatter().set_powerlimits((0, 0))\n\n # set plot boundaries \n to_plot = [lhs0, lhs1, rhs0, rhs1, rhs2, rhs3, rhs4, rhs5, res]\n self.set_plt_axis(LAXIS, xbl, xbr, ybu, ybd, to_plot)\n\n # plot DATA \n plt.title('internal energy equation')\n if self.ig == 1:\n plt.plot(grd1, lhs0, color='#FF6EB4', label=r\"$-\\partial_t (\\overline{\\rho} \\widetilde{\\epsilon}_I )$\")\n plt.plot(grd1, lhs1, color='k', label=r\"$-\\nabla_x (\\overline{\\rho}\\widetilde{u}_x \\widetilde{\\epsilon}_I$)\")\n\n plt.plot(grd1, rhs0, color='#FF8C00', label=r\"$-\\nabla_x f_I $\")\n plt.plot(grd1, rhs1, color='c', label=r\"$-\\nabla_x f_T$ (not incl.)\")\n plt.plot(grd1, rhs2, color='#802A2A', label=r\"$-\\bar{P} \\bar{d}$\")\n plt.plot(grd1, rhs3, color='r', label=r\"$-W_P$\")\n plt.plot(grd1, rhs4, color='b', label=r\"$+\\overline{\\rho}\\widetilde{\\epsilon}_{nuc}$\")\n plt.plot(grd1, rhs5, color='m', label=r\"$+\\varepsilon_k$\")\n\n plt.plot(grd1, res, color='k', linestyle='--', label=r\"res $\\sim N_\\epsilon$\")\n elif self.ig == 2:\n plt.plot(grd1, lhs0, color='#FF6EB4', label=r\"$-\\partial_t (\\overline{\\rho} \\widetilde{\\epsilon}_I )$\")\n plt.plot(grd1, lhs1, color='k', label=r\"$-\\nabla_r (\\overline{\\rho}\\widetilde{u}_r \\widetilde{\\epsilon}_I$)\")\n\n plt.plot(grd1, rhs0, color='#FF8C00', label=r\"$-\\nabla_r f_I $\")\n plt.plot(grd1, rhs1, color='c', label=r\"$-\\nabla_r f_T$ (not incl.)\")\n plt.plot(grd1, rhs2, color='#802A2A', label=r\"$-\\bar{P} \\bar{d}$\")\n plt.plot(grd1, rhs3, color='r', label=r\"$-W_P$\")\n plt.plot(grd1, rhs4, color='b', label=r\"$+\\overline{\\rho}\\widetilde{\\epsilon}_{nuc}$\")\n plt.plot(grd1, rhs5, color='m', label=r\"$+\\varepsilon_k$\")\n\n plt.plot(grd1, res, color='k', linestyle='--', label=r\"res $\\sim N_\\epsilon$\")\n\n # convective boundary markers\n plt.axvline(bconv, linestyle='--', linewidth=0.7, color='k')\n plt.axvline(tconv, linestyle='--', linewidth=0.7, color='k')\n\n # define and show x/y LABELS\n if self.ig == 1:\n setxlabel = r\"x (cm)\"\n setylabel = r\"erg cm$^{-3}$ s$^{-1}$\"\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n elif self.ig == 2:\n setxlabel = r\"r (cm)\"\n setylabel = r\"erg cm$^{-3}$ s$^{-1}$\"\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n\n # show LEGEND\n plt.legend(loc=ilg, prop={'size': 10}, ncol=2)\n\n # display PLOT\n plt.show(block=False)\n\n # save PLOT\n if self.fext == 'png':\n plt.savefig('RESULTS/' + self.data_prefix + 'ei_eq.png')\n elif self.fext == 'eps':\n plt.savefig('RESULTS/' + self.data_prefix + 'ei_eq.eps')", "import numpy as np\nimport matplotlib.pyplot as plt\nfrom UTILS.Calculus import Calculus\nfrom UTILS.SetAxisLimit import SetAxisLimit\nfrom UTILS.Tools import Tools\nfrom UTILS.Errors import Errors\nimport sys\n\n\n# Theoretical background https://arxiv.org/abs/1401.5176\n\n# Mocak, Meakin, Viallet, Arnett, 2014, Compressible Hydrodynamic Mean-Field #\n# Equations in Spherical Geometry and their Application to Turbulent Stellar #\n# Convection Data #\n\nclass LuminosityEquation(Calculus, SetAxisLimit, Tools, Errors, object):\n\n def __init__(self, filename, ig, ieos, fext, intc, tke_diss, bconv, tconv, data_prefix):\n super(LuminosityEquation, self).__init__(ig)\n\n # load data to structured array\n eht = self.customLoad(filename)\n\n # load grid\n xzn0 = self.getRAdata(eht, 'xzn0')\n yzn0 = self.getRAdata(eht, 'yzn0')\n zzn0 = self.getRAdata(eht, 'zzn0')\n nx = self.getRAdata(eht, 'nx')\n\n # pick equation-specific Reynolds-averaged mean fields according to:\n # https://github.com/mmicromegas/ransX/blob/master/DOCS/ransXimplementationGuide.pdf\t\n\n dd = self.getRAdata(eht, 'dd')[intc]\n ux = self.getRAdata(eht, 'ux')[intc]\n pp = self.getRAdata(eht, 'pp')[intc]\n tt = self.getRAdata(eht, 'tt')[intc]\n cp = self.getRAdata(eht, 'cp')[intc]\n gg = self.getRAdata(eht, 'gg')[intc]\n abar = self.getRAdata(eht, 'abar')[intc]\n\n ddux = self.getRAdata(eht, 'ddux')[intc]\n dduy = self.getRAdata(eht, 'dduy')[intc]\n dduz = self.getRAdata(eht, 'dduz')[intc]\n\n ddttux = self.getRAdata(eht, 'ddttux')[intc]\n dduxttx = self.getRAdata(eht, 'dduxttx')[intc]\n dduytty = self.getRAdata(eht, 'dduytty')[intc]\n dduzttz = self.getRAdata(eht, 'dduzttz')[intc]\n\n eiuxddx = self.getRAdata(eht, 'eiuxddx')[intc]\n eiuyddy = self.getRAdata(eht, 'eiuyddy')[intc]\n eiuzddz = self.getRAdata(eht, 'eiuzddz')[intc]\n\n dduxux = self.getRAdata(eht, 'dduxux')[intc]\n dduyuy = self.getRAdata(eht, 'dduyuy')[intc]\n dduzuz = self.getRAdata(eht, 'dduzuz')[intc]\n dduxuy = self.getRAdata(eht, 'dduxuy')[intc]\n dduxuz = self.getRAdata(eht, 'dduxuz')[intc]\n\n ddekux = self.getRAdata(eht, 'ddekux')[intc]\n ddek = self.getRAdata(eht, 'ddek')[intc]\n\n ddei = self.getRAdata(eht, 'ddei')[intc]\n ddeiux = self.getRAdata(eht, 'ddeiux')[intc]\n eiux = self.getRAdata(eht, 'eiux')[intc]\n\n ddetux = self.getRAdata(eht, 'ddetux')[intc]\n\n divu = self.getRAdata(eht, 'divu')[intc]\n ppdivu = self.getRAdata(eht, 'ppdivu')[intc]\n dddivu = self.getRAdata(eht, 'dddivu')[intc]\n uxdivu = self.getRAdata(eht, 'uxdivu')[intc]\n ppux = self.getRAdata(eht, 'ppux')[intc]\n\n ddenuc1 = self.getRAdata(eht, 'ddenuc1')[intc]\n ddenuc2 = self.getRAdata(eht, 'ddenuc2')[intc]\n\n chim = self.getRAdata(eht, 'chim')[intc]\n chit = self.getRAdata(eht, 'chit')[intc]\n chid = self.getRAdata(eht, 'chid')[intc]\n\n gamma1 = self.getRAdata(eht, 'gamma1')[intc]\n\n gascon = 8.3144629e7 # gas constant in cgs\n\n # override gamma for ideal gas eos (need to be fixed in PROMPI later)\n if ieos == 1:\n cp = self.getRAdata(eht, 'cp')[intc]\n cv = self.getRAdata(eht, 'cv')[intc]\n gamma1 = cp / cv # gamma1,gamma2,gamma3 = gamma = cp/cv Cox & Giuli 2nd Ed. page 230, Eq.9.110\n\n # print(gamma1)\n # print(\"-----------\")\n # print((gamma1/(gamma1-1.))*gascon/abar)\n # print(\"-----------\")\n # print(cp)\n\n\n ##########################\n # HSSE LUMINOSITY EQUATION \n ##########################\n\n # store time series for time derivatives\n t_timec = self.getRAdata(eht, 'timec')\n t_dd = self.getRAdata(eht, 'dd')\n t_tt = self.getRAdata(eht, 'tt')\n t_pp = self.getRAdata(eht, 'pp')\n\n t_ddei = self.getRAdata(eht, 'ddei')\n t_ddss = self.getRAdata(eht, 'ddss')\n t_ddtt = self.getRAdata(eht, 'ddtt')\n\n t_ddux = self.getRAdata(eht, 'ddux')\n t_dduy = self.getRAdata(eht, 'dduy')\n t_dduz = self.getRAdata(eht, 'dduz')\n\n t_dduxux = self.getRAdata(eht, 'dduxux')\n t_dduyuy = self.getRAdata(eht, 'dduyuy')\n t_dduzuz = self.getRAdata(eht, 'dduzuz')\n\n t_uxux = self.getRAdata(eht, 'uxux')\n t_uyuy = self.getRAdata(eht, 'uyuy')\n t_uzuz = self.getRAdata(eht, 'uzuz')\n\n t_fht_ek = 0.5 * (t_dduxux + t_dduyuy + t_dduzuz) / t_dd\n t_fht_ei = t_ddei / t_dd\n t_fht_et = t_fht_ek + t_fht_ei\n t_fht_ss = t_ddss / t_dd\n\n t_fht_ux = t_ddux / t_dd\n t_fht_uy = t_dduy / t_dd\n t_fht_uz = t_dduz / t_dd\n\n t_fht_ui_fht_ui = t_fht_ux * t_fht_ux + t_fht_uy * t_fht_uy + t_fht_uz * t_fht_uz\n\n t_fht_tt = t_ddtt/t_dd\n\n # t_mm = self.getRAdata(eht,'mm'))\n # minus_dt_mm = -self.dt(t_mm,xzn0,t_timec,intc)\n # fht_ux = minus_dt_mm/(4.*np.pi*(xzn0**2.)*dd)\n\n # construct equation-specific mean fields\t\t\t\n # fht_ek = 0.5*(dduxux + dduyuy + dduzuz)/dd\n fht_ek = ddek / dd\n fht_ux = ddux / dd\n fht_uy = dduy / dd\n fht_uz = dduz / dd\n fht_ei = ddei / dd\n fht_et = fht_ek + fht_ei\n fht_enuc = (ddenuc1 + ddenuc2) / dd\n fht_eiux = ddeiux/dd\n\n fei = ddeiux - ddux * ddei / dd\n fekx = ddekux - fht_ux * fht_ek\n fpx = ppux - pp * ux\n fekx = ddekux - fht_ux * fht_ek\n\n fht_ui_fht_ui = fht_ux * fht_ux + fht_uy * fht_uy + fht_uz * fht_uz\n\n if self.ig == 1: # Kippenhahn and Weigert, page 38\n alpha = 1.\n delta = 1.\n phi = 1.\n elif self.ig == 2:\n alpha = 1. / chid\n delta = -chit / chid\n phi = chid / chim\n\n fht_rxx = dduxux - ddux * ddux / dd\n fdil = (uxdivu - ux * divu)\n\n gg = -gg\n\n if self.ig == 1:\n surface = (yzn0[-1] - yzn0[0]) * (zzn0[-1] - zzn0[0])\n elif self.ig == 2:\n # sphere surface\n surface = +4. * np.pi * (xzn0 ** 2.)\n else:\n print(\"ERROR(Properties.py): \" + self.errorGeometry(self.ig))\n sys.exit()\n\n ####################################\n # STANDARD LUMINOSITY EQUATION EXACT\n ####################################\n\n self.minus_cp_rho_dTdt = -cp*(self.dt(t_ddtt, xzn0, t_timec, intc) + self.Div(ddttux,xzn0) - (dduxttx + dduytty + dduzttz))\n\n self.plus_delta_dPdt = +delta * self.dt(t_pp, xzn0, t_timec, intc)\n\n self.minus_dd_div_eiui = -(self.Div(ddeiux, xzn0) - (eiuxddx + eiuyddy + eiuzddz))\n #self.minus_dd_div_eiui = -(self.Div(ddeiux, xzn0))\n\n self.plus_tke_diss = +tke_diss\n\n self.minus_resLumExactEquation = -(self.minus_cp_rho_dTdt+self.plus_delta_dPdt+self.minus_dd_div_eiui+self.plus_tke_diss)\n\n ########################################\n # END STANDARD LUMINOSITY EQUATION EXACT \n ######################################## \n\n # assign global data to be shared across whole class\n self.data_prefix = data_prefix\n self.xzn0 = xzn0\n self.fht_et = fht_ei + fht_ek\n self.nx = nx\n self.bconv = bconv\n self.tconv = tconv\n self.fext = fext\n\n def plot_et(self, LAXIS, xbl, xbr, ybu, ybd, ilg):\n \"\"\"Plot mean total energy stratification in the model\"\"\"\n\n # load x GRID\n grd1 = self.xzn0\n\n # load DATA to plot\n plt1 = self.fht_et\n\n # create FIGURE\n plt.figure(figsize=(7, 6))\n\n # format AXIS, make sure it is exponential\n plt.gca().yaxis.get_major_formatter().set_powerlimits((0, 0))\n\n # set plot boundaries \n to_plot = [plt1]\n self.set_plt_axis(LAXIS, xbl, xbr, ybu, ybd, to_plot)\n\n # plot DATA \n plt.title(r'total energy')\n plt.plot(grd1, plt1, color='brown', label=r'$\\widetilde{\\varepsilon}_t$')\n\n # define and show x/y LABELS\n if self.ig == 1:\n setxlabel = r\"x (cm)\"\n setylabel = r\"$\\widetilde{\\varepsilon}_t$ (erg g$^{-1}$)\"\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n elif self.ig == 2:\n setxlabel = r\"r (cm)\"\n setylabel = r\"$\\widetilde{\\varepsilon}_t$ (erg g$^{-1}$)\"\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n\n # show LEGEND\n plt.legend(loc=ilg, prop={'size': 18})\n\n # display PLOT\n plt.show(block=False)\n\n # save PLOT\n if self.fext == 'png':\n plt.savefig('RESULTS/' + self.data_prefix + 'mean_et.png')\n elif self.fext == 'eps':\n plt.savefig('RESULTS/' + self.data_prefix + 'mean_et.eps')\n\n\n def plot_luminosity_equation_exact(self, LAXIS, xbl, xbr, ybu, ybd, ilg):\n \"\"\"Plot luminosity equation in the model\"\"\"\n\n # load x GRID\n grd1 = self.xzn0\n\n rhs0 = self.minus_cp_rho_dTdt\n rhs1 = self.plus_delta_dPdt\n rhs2 = self.minus_dd_div_eiui\n rhs3 = self.plus_tke_diss\n\n res = self.minus_resLumExactEquation\n\n # create FIGURE\n plt.figure(figsize=(7, 6))\n\n # format AXIS, make sure it is exponential\n plt.gca().yaxis.get_major_formatter().set_powerlimits((0, 0))\n\n # set plot boundaries \n to_plot = [rhs0, rhs1, res]\n self.set_plt_axis(LAXIS, xbl, xbr, ybu, ybd, to_plot)\n\n self.bconv = 4.e8\n self.tconv = 1.2e9\n\n xlimitrange = np.where((grd1 > self.bconv) & (grd1 < self.tconv))\n xlimitbottom = np.where(grd1 < self.bconv)\n xlimittop = np.where(grd1 > self.tconv)\n\n # plot DATA \n plt.title(\"standard luminosity equation exact\")\n if self.ig == 1:\n plt.plot(grd1[xlimitrange], rhs0[xlimitrange], color='#FF8C00', label=r\"$-c_P \\overline{\\rho \\partial_t T}$\")\n plt.plot(grd1[xlimitrange], rhs1[xlimitrange], color='y',label = r\"$+\\delta \\overline{\\partial_t P}$\")\n plt.plot(grd1[xlimitrange], rhs2[xlimitrange], color='r',label = r\"$-\\overline{\\rho \\nabla \\cdot \\epsilon_I {\\bf u}}$\")\n plt.plot(grd1[xlimitrange], rhs3[xlimitrange], color='g',label = r\"$+\\varepsilon_K$\")\n plt.plot(grd1, res, color='k', linestyle='--', label=r\"res $\\sim N$\")\n\n zeros = np.zeros(self.nx)\n plt.plot(grd1, zeros, color='k', linewidth=0.6, label=\"zero\")\n elif self.ig == 2:\n plt.plot(grd1[xlimitrange], rhs0[xlimitrange], color='#FF8C00', label=r\"$-c_P \\rho dT/dt$\")\n plt.plot(grd1[xlimitrange], rhs1[xlimitrange], color='y',label = r\"$+\\delta dP/dt$\")\n plt.plot(grd1, res, color='k', linestyle='--', label=r\"res $\\sim N$\")\n\n zeros = np.zeros(self.nx)\n plt.plot(grd1, zeros, color='k', linewidth=0.6, label=\"zero\")\n\n # convective boundary markers\n plt.axvline(self.bconv, linestyle='--', linewidth=0.7, color='k')\n plt.axvline(self.tconv, linestyle='--', linewidth=0.7, color='k')\n\n if self.ig == 1:\n setxlabel = r\"x (cm)\"\n setylabel = r\"erg g$^{-1}$ s$^{-1}$\"\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n elif self.ig == 2:\n setxlabel = r\"r (cm)\"\n setylabel = r\"erg g$^{-1}$ s$^{-1}$\"\n plt.xlabel(setxlabel)\n plt.ylabel(setylabel)\n\n # show LEGEND\n plt.legend(loc=ilg, prop={'size': 10}, ncol = 2)\n\n # display PLOT\n plt.show(block=False)\n\n # save PLOT\n if self.fext == 'png':\n plt.savefig('RESULTS/' + self.data_prefix + 'standard_luminosity_exact_eq.png')\n elif self.fext == 'eps':\n plt.savefig('RESULTS/' + self.data_prefix + 'standard_luminosity_exact_eq.eps')\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.gca", "matplotlib.pyplot.axvline", "matplotlib.pyplot.title", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.figure" ], [ "matplotlib.pyplot.legend", "matplotlib.pyplot.gca", "matplotlib.pyplot.axvline", "matplotlib.pyplot.title", "matplotlib.pyplot.savefig", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.show", "numpy.where", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cwaitt/zse
[ "4330397ddf84dafaa0af7bddd25756e008cb3ff5" ]
[ "cif_tools.py" ]
[ "__all__ = ['read_cif','cif_site_labels']\n\nfrom ase.io import read\nfrom ase.spacegroup import spacegroup\nimport sys\nimport os\nimport logging\nfrom math import *\nimport numpy as np\nimport pkg_resources\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\npath = '.temp_files/'\nfilepath = pkg_resources.resource_filename(__name__,path)\n\n'''\nNOTE ABOUT CIF FILE FORMATS:\nCIFs must include '_symmetry_Int_Taables_number' to be read by ASE.\nIf this is not included please edit your CIF file to include this information.\n'''\n\ndef get_atom_lines(alllines):\n order = []\n for i,line in enumerate(alllines):\n if '_atom' in line:\n order.append(line)\n start = i+1\n end = None\n for i,line in enumerate(alllines[start:]):\n\n if len(line.split()) == 0:\n end = start+i-1\n break\n if not end:\n end = len(alllines)-1\n\n new_order = []\n for i,o in enumerate(order):\n if 'site_label' in o:\n new_order.append(i)\n if 'site_type_symbol' in o:\n new_order.append(i)\n if 'fract_x' in o:\n new_order.append(i)\n if 'fract_y' in o:\n new_order.append(i)\n if 'fract_z' in o:\n new_order.append(i)\n\n return start,end,new_order\n\ndef fix_cif(cif):\n f = open(cif,\"r\")\n alllines = f.readlines()\n f.close()\n\n for i, line in enumerate(alllines):\n if 'IT_coordinate_system_code' in line:\n fields = line.split()\n alllines[i] = '_symmetry_space_group_setting {0} \\n'.format(fields[-1])\n\n if '_atom_site_type_symbol' in line and '_atom_site_label' in alllines[i+1]:\n alllines[i],alllines[i+1] = alllines[i+1],alllines[i]\n\n file_name = cif.rstrip('.cif')\n temp_file = '{0}/{1}_temp.cif'.format(filepath,file_name.split('/')[-1])\n f = open(temp_file,\"w\")\n f.writelines(alllines)\n f.close()\n atoms = read(temp_file);\n os.remove(temp_file)\n return atoms, alllines\n\ndef get_tsites(cif):\n from ase.geometry import get_distances\n tsites = []\n tpos = []\n z,alllines = fix_cif(cif)\n si = [atom.index for atom in z if atom.symbol!='O']\n start,end,order = get_atom_lines(alllines)\n for line in alllines[start:end+1]:\n if 'Si' in line or 'T' in line:\n line = line.split()\n temp_label = line[order[0]]\n if not any(str.isdigit(c) for c in temp_label):\n temp_label = line[order[1]]\n if 'Si' in temp_label:\n temp_label = temp_label.replace('Si','T')\n tsites.append(temp_label)\n pos = [float(line[order[2]]),float(line[order[3]]),float(line[order[4]])]\n tpos.append([round(num,2) for num in pos])\n\n tpos = np.array(tpos)\n pos = z[si].get_scaled_positions()\n tinds = []\n tmults = []\n t_class = []\n for tp in tpos:\n for i,p in enumerate(pos):\n p = [round(num,2) for num in p]\n diff = abs(tp-p)\n if sum(diff) <= 0.03:\n tinds.append(si[i])\n\n for i in range(1,len(tsites)):\n tmults.append(tinds[i]-tinds[i-1])\n tmults.append(si[-1]-tinds[-1]+1)\n\n #\n # si = [atom.index for atom in z if atom.symbol=='Si']\n # o = [atom.index for atom in z if atom.symbol=='O']\n # si_pos = z[si].positions\n # cell = z.cell\n # distances = get_distances(si_pos,si_pos,cell=cell,pbc=[1,1,1])[1]\n #\n # for i in tinds:\n # orig_ind = si.index(i)\n # dists = sorted(distances[orig_ind])\n # t_class.append([round(num,2) for num in dists])\n #\n #\n # for i,d in enumerate(t_class):\n # for j,t in enumerate(distances):\n # dist = [round(num,2) for num in sorted(t)]\n # if np.array_equal(dist,d):\n # dist = [round(num,2) for num in sorted(t)]\n # d = np.array(d)\n # dist = np.array(dist)\n # diff = abs(d - dist)\n # if sum(diff) <= 0.1:\n # tmults[i]+=1\n\n n = len(si)\n sn = sum(tmults)\n if n != sn:\n print('Something Went Wrong With T Sites')\n return tsites, tmults, tinds\n\ndef get_osites(cif):\n from ase.geometry import get_distances\n osites = []\n opos = []\n z,alllines = fix_cif(cif)\n start,end,order = get_atom_lines(alllines)\n for line in alllines[start:end+1]:\n if 'O' in line:\n line = line.split()\n temp_label = line[order[0]]\n if not any(str.isdigit(c) for c in temp_label):\n temp_label = line[order[1]]\n osites.append(temp_label)\n pos = [float(line[order[2]]),float(line[order[3]]),float(line[order[4]])]\n opos.append([round(num,2) for num in pos])\n opos = np.array(opos)\n pos = z.get_scaled_positions()\n oinds = []\n omults = []\n o_class = []\n\n si = [atom.index for atom in z if atom.symbol=='Si']\n o = [atom.index for atom in z if atom.symbol=='O']\n o_pos = z[o].get_scaled_positions()\n for op in opos:\n for i,p in enumerate(o_pos):\n p = np.array([round(num,2) for num in p])\n diff = abs(op-p)\n if sum(diff) <= 0.02:\n oinds.append(o[i])\n\n for i in range(1,len(osites)):\n omults.append(oinds[i]-oinds[i-1])\n omults.append(o[-1]-oinds[-1]+1)\n\n # all_pos = z.positions\n # o_pos = z[o].positions\n # si_pos = z[si].positions\n # cell = z.cell\n # distances = get_distances(o_pos,all_pos,cell=cell,pbc=[1,1,1])[1]\n #\n # for i in oinds:\n # orig_ind = o.index(i)\n # dists = sorted(distances[orig_ind])\n # o_class.append([round(num,2) for num in dists])\n #\n # for i,d in enumerate(o_class):\n # for j,t in enumerate(distances):\n # dist = [round(num,2) for num in sorted(t)]\n # d = np.array(d)\n # dist = np.array(dist)\n # diff = abs(d - dist)\n # if sum(diff) <= 0.05:\n # omults[i]+=1\n\n n = len(o)\n sn = sum(omults)\n if n != sn:\n print('Something Went Wrong With O Sites')\n return osites, omults, oinds\n\ndef read_cif(cif):\n atoms, alllines = fix_cif(cif)\n ts,tm,tinds = get_tsites(cif)\n os,om,oinds = get_osites(cif)\n return atoms,ts,tm,tinds,os,om,oinds\n\ndef cif_site_labels(cif):\n atoms,ts,tm,tinds,os,om,oinds = read_cif(cif)\n labels = {}\n for i,t in enumerate(ts):\n for j in range(tm[i]):\n labels[tinds[i]+j] = t\n\n for i,o in enumerate(os):\n for j in range(om[i]):\n labels[oinds[i]+j] = o\n\n return labels\n\n''' DEPRECRATED FUNCTIONS'''\n\ndef float_with_error(x):\n \"\"\"\n some value in cif accompanies error like \"1.234(5)\n \"\"\"\n if \"?\" in x:\n return 0\n pos = x.find(\"(\")\n if pos >= 0:\n x = x[:pos]\n return float(x)\n\ndef get_mults(cif):\n\n # read the cif file\n\n F = open(cif,\"r\")\n alllines = F.readlines()\n F.close()\n\n # Parse out data from the cif file\n\n for i,line in enumerate(alllines):\n if '_cell_length_a' in line:\n fields = line.split()\n field = fields[-1]\n field = float_with_error(field)\n La = field\n if '_cell_length_b' in line:\n fields = line.split()\n field = fields[-1]\n field = float_with_error(field)\n Lb = field\n if '_cell_length_c' in line:\n fields = line.split()\n field = fields[-1]\n field = float_with_error(field)\n Lc = field\n if '_cell_angle_alpha' in line:\n fields = line.split()\n field = fields[-1]\n field = float_with_error(field)\n alpha = field\n if '_cell_angle_beta' in line:\n fields = line.split()\n field = fields[-1]\n field = float_with_error(field)\n beta = field\n if '_cell_angle_gamma' in line:\n fields = line.split()\n field = fields[-1]\n field = float_with_error(field)\n gamma = field\n if '_space_group_symop' in line or '_symmetry_equiv_pos' in line or '_space_group' in line:\n n = i\n\n lastline = len(alllines)\n\n loops = []\n for i,line in enumerate(alllines):\n if 'loop' in line:\n loops.append(i)\n\n ops = []\n for i in range(n+1,loops[1]):\n n+=1\n line = alllines[i]\n if 'x' in line or 'X' in line:\n ops.append(line.replace(\"'\",''))\n\n for i in range(len(ops)):\n ops[i] = ops[i].replace(\"0/\", \"0./\") # also for e.g. 10/9\n ops[i] = ops[i].replace(\"1/\", \"1./\")\n ops[i] = ops[i].replace(\"2/\", \"2./\")\n ops[i] = ops[i].replace(\"3/\", \"3./\")\n ops[i] = ops[i].replace(\"4/\", \"4./\")\n ops[i] = ops[i].replace(\"5/\", \"5./\")\n ops[i] = ops[i].replace(\"6/\", \"6./\")\n ops[i] = ops[i].replace(\"7/\", \"7./\")\n ops[i] = ops[i].replace(\"8/\", \"8./\")\n ops[i] = ops[i].replace(\"9/\", \"9./\")\n\n osites = []\n tsites = []\n atoms = []\n for j in range(n,lastline):\n line = alllines[j]\n if '_' not in line:\n fields = line.split()\n if len(fields) >3:\n tmp = (fields[0],float(fields[2]),float(fields[3]),float(fields[4]))\n if 'O' in fields[0]:\n osites.append(fields[0])\n if 'T' in fields[0]:\n tsites.append(fields[0])\n atoms.append(tmp)\n for i in range(len(atoms)):\n (name,xn,yn,zn) = atoms[i]\n xn = (xn + 10.0) % 1.0\n yn = (yn + 10.0) % 1.0\n zn = (zn + 10.0) % 1.0\n atoms[i] = (name,xn,yn,zn)\n\n # perfrom symmetry operations\n\n label_list = []\n symbols = []\n positions = []\n\n for i in atoms:\n label_list.append(i[0])\n eps = 0.01\n imax = len(atoms)\n i=0\n while (i<imax):\n label,x,y,z=atoms[i]\n for op in ops:\n op = op.replace(\"'\",'')\n op = op.lower()\n xn,yn,zn = eval(op)\n\n xn = (xn + 10.0) % 1.0\n yn = (yn + 10.0) % 1.0\n zn = (zn + 10.0) % 1.0\n\n new_atom = True\n for at in atoms:\n if (abs(at[1]-xn) < eps and abs(at[2]-yn) < eps and abs(at[3]-zn) < eps):\n new_atom = False\n if new_atom:\n p1 = np.array([at[1],at[2],at[3]])\n p2 = np.array([xn,yn,zn])\n diff = abs(p1-p2)\n diff = np.round(diff,2)\n count = np.count_nonzero(diff)\n if count ==1 and 1 in diff:\n new_atom = False\n if new_atom:\n\n atoms.append( (label,xn,yn,zn) )\n label_list.append(label)\n i += 1\n imax =len(atoms)\n #atoms2 = Atoms(symbols,scaled_positions=positions,cell = [La,Lb,Lc,alpha,beta,gamma])\n # count up the osits\n label_list = sorted(label_list)\n omults = []\n for o in osites:\n count = label_list.count(o)\n omults.append(count)\n tmults = []\n for t in tsites:\n count = label_list.count(t)\n tmults.append(count)\n return tsites, tmults, osites, omults\n\ndef get_indices(cif):\n '''\n This is a tool that will read a CIF file and return the unique T-sites,\n their multiplicities, and an example atom index.\n\n It also does the same for the unique O-sites in the framework.\n\n This tool only works on CIFs that are formatted the same way as the IZA\n Structure Database CIFs.\n '''\n\n tsites, tmults, osites, omults = get_mults(cif)\n f = open(cif,\"r\")\n alllines = f.read()\n f.close()\n\n for i, line in enumerate(alllines):\n if 'IT_coordinate_system_code' in line:\n fields = line.split()\n alllines[i] = '_symmetry_space_group_setting {0}'.format(fields[-1])\n\n\n atoms = read(cif)\n\n oinds = [atom.index for atom in atoms if atom.symbol=='O']\n index = 0\n first_os = []\n for i,m in enumerate(omults):\n first_os.append(oinds[index])\n index+=m\n\n tinds = [atom.index for atom in atoms if atom.symbol !='O']\n index = 0\n first_ts = []\n for i,m, in enumerate(tmults):\n first_ts.append(tinds[index])\n index+=m\n return tsites,tmults,first_ts, osites, omults, first_os\n" ]
[ [ "numpy.round", "numpy.array", "numpy.count_nonzero" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
VirgiAgl/V_savigp
[ "310f31f789db34737313bf057ff1474e314d68fd", "310f31f789db34737313bf057ff1474e314d68fd" ]
[ "GP/data_transformation.py", "GP/model_learn.py" ]
[ "import numpy as np\nfrom sklearn import preprocessing\n\n\nclass DataTransformation:\n \"\"\"\n A generic class for the transformation of data\n \"\"\"\n\n def __init__(self):\n pass\n\n def transform_X(self, X):\n \"\"\"\n transforms X\n\n :param\n X: Input X\n :return\n transformed X\n \"\"\"\n raise NotImplementedError()\n\n def transform_Y(self, Y):\n \"\"\"\n transforms Y\n\n :param\n Y: Input Y\n :return\n transformed Y\n \"\"\"\n raise NotImplementedError()\n\n def untransform_X(self, X):\n \"\"\"\n Untransforms X to its original values\n\n :param\n X: transformed X\n :return\n untransformed X\n \"\"\"\n raise NotImplementedError()\n\n def untransform_Y(self, Y):\n \"\"\"\n Untransforms Y\n :param\n Y: transformed Y\n :return\n untransfomred Y\n \"\"\"\n raise NotImplementedError()\n\n def untransform_Y_var(self, Yvar):\n raise NotImplementedError()\n\n def untransform_NLPD(self, NLPD):\n \"\"\"\n Untransfomrs NLPD to the original Y space\n\n :param\n NLPD: transfomred NLPD\n :return\n untransformed NLPD\n \"\"\"\n raise NotImplementedError()\n\n\nclass IdentityTransformation:\n \"\"\"\n Identity transformation. No transformation will be applied to data.\n \"\"\"\n\n def __init__(self):\n pass\n\n def transform_X(self, X):\n return X\n\n def transform_Y(self, Y):\n return Y\n\n def untransform_X(self, X):\n return X\n\n def untransform_Y(self, Y):\n return Y\n\n def untransform_Y_var(self, Yvar):\n return Yvar\n\n @staticmethod\n def get_transformation(Y, X):\n return IdentityTransformation()\n\n def untransform_NLPD(self, NLPD):\n return NLPD\n\n\nclass MeanTransformation(object, DataTransformation):\n \"\"\"\n Only transforms Y as follows:\n transformed Y = untransformed Y - mean(Y)\n \"\"\"\n\n def __init__(self, mean):\n super(MeanTransformation, self).__init__()\n self.mean = mean\n\n def transform_X(self, X):\n return X\n\n def transform_Y(self, Y):\n return Y - self.mean\n\n def untransform_X(self, X):\n return X\n\n def untransform_Y(self, Y):\n return Y + self.mean\n\n def untransform_Y_var(self, Yvar):\n return Yvar\n\n def untransform_NLPD(self, NLPD):\n return NLPD\n\n @staticmethod\n def get_transformation(Y, X):\n return MeanTransformation(Y.mean(axis=0))\n\n\nclass MeanStdYTransformation(object, DataTransformation):\n \"\"\"\n Transforms only Y in a way that the transformed Y has mean = 0 and std =1\n \"\"\"\n\n def __init__(self, scalar):\n super(MeanStdYTransformation, self).__init__()\n self.scalar = scalar\n\n def transform_X(self, X):\n return X\n\n def transform_Y(self, Y):\n return self.scalar.transform(Y)\n\n def untransform_X(self, X):\n return X\n\n def untransform_Y(self, Y):\n return self.scalar.inverse_transform(Y)\n\n def untransform_Y_var(self, Yvar):\n return Yvar\n\n def untransform_NLPD(self, NLPD):\n return NLPD + np.hstack((np.array([np.log(self.scalar.std_).sum()]), np.log(self.scalar.std_)))\n\n @staticmethod\n def get_transformation(Y, X):\n return MeanStdYTransformation(preprocessing.StandardScaler().fit(Y))\n\n\nclass MinTransformation(object, DataTransformation):\n \"\"\"\n Transforms only Y.\n transformed Y = (Y - min(Y)) / (max(Y) - min(Y)) - 0.5\n \"\"\"\n\n def __init__(self, min, max, offset):\n super(MinTransformation, self).__init__()\n self.min = min\n self.max = max\n self.offset = offset\n\n def transform_X(self, X):\n return X\n\n def transform_Y(self, Y):\n return (Y-self.min).astype('float')/(self.max-self.min) - self.offset\n\n def untransform_X(self, X):\n return X\n\n def untransform_Y(self, Y):\n return (Y+self.offset)*(self.max-self.min) + self.min\n\n def untransform_Y_var(self, Yvar):\n return Yvar * (self.max-self.min) ** 2\n\n def untransform_NLPD(self, NLPD):\n return NLPD + np.log(self.max - self.min)\n\n @staticmethod\n def get_transformation(Y, X):\n return MinTransformation(Y.min(), Y.max(), 0.5)\n", "import logging\nimport pickle\nimport csv\n\nimport GPy\nimport numpy as np\n\nfrom savigp import SAVIGP\nfrom savigp_diag import SAVIGP_Diag\nfrom savigp_single_comp import SAVIGP_SingleComponent\nfrom optimizer import Optimizer\nfrom util import id_generator, check_dir_exists, get_git\n\n\nclass ModelLearn:\n \"\"\"\n Provides facility for fitting models to data, making predictions and exporting results to csv files.\n \"\"\"\n\n def __init__(self):\n pass\n\n @staticmethod\n def get_output_path():\n \"\"\"\n Returns\n -------\n path : string\n the path in which results of the experiment will be saved\n \"\"\"\n return '../results/'\n\n @staticmethod\n def get_logger_path():\n \"\"\"\n Returns\n -------\n path : string\n the path in which log files will be created\n \"\"\"\n return '../logs/'\n\n @staticmethod\n def get_logger(path, name, level):\n \"\"\"\n Creates loggers\n\n Parameters\n ----------\n path : string\n path for save the log file in\n\n name : string\n name of the log file\n\n level : string\n level of debugging\n\n Returns\n -------\n logger : logger\n created loggers\n \"\"\"\n\n logger = logging.getLogger(name)\n logger.setLevel(level)\n check_dir_exists(path)\n fh = logging.FileHandler(path + '/'+ name + '.log')\n fh.setLevel(logging.DEBUG)\n ch = logging.StreamHandler()\n ch.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n fh.setFormatter(formatter)\n ch.setFormatter(formatter)\n logger.addHandler(fh)\n logger.addHandler(ch)\n return logger\n\n @staticmethod\n def export_train(name, Xtrain, Ytrain, export_X=True): #V_changed for the mining to true\n \"\"\"\n Exports training data into a csv file\n\n Parameters\n ----------\n name : string\n name of file\n\n Xtrain : ndarray\n X of training data\n\n Ytrain : ndarray\n Y of training data\n\n export_X : boolean\n whether to export 'X'. If False, only ``Ytrain`` will be exported\n\n :return:\n None\n \"\"\"\n path = ModelLearn.get_output_path() + name + '/'\n check_dir_exists(path)\n file_name = 'train_'\n header = ['Y%d,' % (j) for j in range(Ytrain.shape[1])] #V_give the number of tasks P\n data = None\n if export_X:\n data = np.hstack((Ytrain, Xtrain))\n header += ['X%d,' % (j) for j in range(Xtrain.shape[1])] #V_giving the dimension D of the X\n else:\n data = Ytrain\n np.savetxt(path + file_name + '.csv', data, header=''.join(header), delimiter=',', comments='') #V_quindi il file sara Y1 Y2 YP X1 X2 XD. Matrice N P D\n\n\n @staticmethod\n def export_track(name, track):\n \"\"\"\n exports trajectory of the objective function\n\n Parameters\n ----------\n name : string\n name of the file to which track will be exported\n\n track : list\n trajectory of the objective function\n\n \"\"\"\n path = ModelLearn.get_output_path() + name + '/'\n check_dir_exists(path)\n file_name = 'obj_track_'\n np.savetxt(path + file_name + '.csv', np.array([track]).T, #V_penso che dia una serie di valori per f\n header='objective'\n , delimiter=',', comments='')\n\n @staticmethod\n def export_model(model, name):\n \"\"\"\n exports Model into a csv file\n\n Parameters\n ----------\n model : model\n the model to be exported\n\n name : string\n name of the csv file\n \"\"\"\n\n path = ModelLearn.get_output_path() + name + '/'\n check_dir_exists(path)\n file_name = 'model_'\n if model is not None:\n with open(path + file_name + '.csv', 'w') as fp:\n f = csv.writer(fp, delimiter=',')\n f.writerow(['#model', model.__class__])\n params = model.get_all_params()\n param_names = model.get_all_param_names()\n for j in range(len(params)):\n f.writerow([param_names[j], params[j]])\n\n\n @staticmethod\n def export_test(name, Xtest, Ytrue, Ypred, Yvar_pred, nlpd, pred_names=[''], export_X=True): #V_changed to true for the mining dataset\n \"\"\"\n Exports test data and the predictions into a csv file\n\n Parameters\n ----------\n name : string\n name of the file\n\n X : ndarray\n X test for which prediction have been made\n\n Ytrue : ndarray\n The true values of 'Y'\n\n Ypred : ndarray\n Predictions at the test points\n\n Yvar_pred : ndarray\n Variance of the prediction\n\n nlpd : ndarray #V_negative log predicted density\n NLPD of the predictions\n\n pred_names : list\n not necessary. It should be ['']\n\n export_X : boolean\n Whether to export 'X' to the csv file. If False, 'X' will not be exported into the csv file\n (useful in large datasets).\n \"\"\"\n\n path = ModelLearn.get_output_path() + name + '/'\n check_dir_exists(path)\n file_name = 'test_'\n out = []\n out.append(Ytrue)\n out += Ypred\n out += Yvar_pred\n out += [nlpd]\n header = ['Ytrue%d,' % (j) for j in range(Ytrue.shape[1])] + \\\n ['Ypred_%s_%d,' % (m, j) for m in pred_names for j in range(Ypred[0].shape[1])] + \\\n ['Yvar_pred_%s_%d,' % (m, j) for m in pred_names for j in range(Yvar_pred[0].shape[1])] + \\\n ['nlpd,'] + ['NLPD_%d,' % (j) for j in range(nlpd.shape[1] - 1)]\n #V_thus the previous function take one 1 row for Ypred e Yvar_pred, so prediction for one point?\n\n if export_X: \n out.append(Xtest) #V_this part is changed from X to X_test\n header += ['X%d,' % (j) for j in range(Xtest.shape[1])] #V_this part is changed from X to X_test\n\n header = ''.join(header)\n out = np.hstack(out)\n np.savetxt(path + file_name + '.csv', out\n , header=header\n , delimiter=',', comments='')\n\n\n @staticmethod\n def export_configuration(name, config):\n \"\"\"\n Exports configuration of the model as well as optimisation parameters to a csv file\n\n Parameters\n ----------\n name : string\n Name of the file\n\n config : dictionary\n Configuration to be exported\n \"\"\"\n\n path = ModelLearn.get_output_path() + name + '/'\n check_dir_exists(path)\n file_name = path + 'config_' + '.csv'\n with open(file_name, 'wb') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=config.keys())\n writer.writeheader()\n writer.writerow(config)\n\n @staticmethod\n def get_ID():\n \"\"\"\n :return: A random ID\n \"\"\"\n return id_generator(size=6)\n\n\n @staticmethod\n def opt_callback(name):\n \"\"\"\n A callback function which will be called by the optimiser to save the model\n\n Parameters\n ----------\n name : string\n name of the folder to save the model in.\n \"\"\"\n\n def callback(model, current_iter, total_evals, delta_m, delta_s, obj_track):\n path = ModelLearn.get_output_path() + name + '/'\n check_dir_exists(path)\n pickle.dump(model.image(), open(path + 'model.dump', 'w'))\n pickle.dump({\n 'current_iter': current_iter,\n 'total_evals': total_evals,\n 'delta_m': delta_m,\n 'delta_s': delta_s,\n 'obj_track': obj_track,\n 'obj_fun': model.objective_function()\n },\n open(path + 'opt.dump', 'w'))\n\n return callback\n\n\n @staticmethod\n def run_model(Xtest, Xtrain, Ytest, Ytrain, cond_ll, kernel, method, name, run_id, num_inducing, num_samples,\n sparsify_factor, to_optimize, trans_class, random_Z, logging_level, export_X,\n latent_noise=0.001, opt_per_iter=None, max_iter=200, n_threads=1, model_image_file=None,\n xtol=1e-3, ftol=1e-5, partition_size=3000):\n \"\"\"\n Fits a model to the data (Xtrain, Ytrain) using the method provided by 'method', and makes predictions on\n 'Xtest' and 'Ytest', and exports the result to csv files.\n\n Parameters\n ----------\n Xtest : ndarray\n X of test points\n\n Xtrain : ndarray\n X of training points\n\n Ytest : ndarray\n Y of test points\n\n Ytrain : ndarray\n Y of traiing points\n\n cond_ll : subclass of likelihood/Likelihood\n Conditional log likelihood function used to build the model.\n\n kernel : list\n The kernel that the model uses. It should be an array, and size of the array should be same as the\n number of latent processes. Each element should provide interface similar to ``ExtRBF`` class\n\n method : string\n The method to use to learns the model. It can be 'full', 'mix1', and 'mix2'\n\n name : string\n The name that will be used for logger file names, and results files names\n\n run_id : object\n ID of the experiment, which can be anything, and it will be included in the configuration file. It can provdie\n for example a number referring to a particular test and train partition.\n\n num_inducing : integer\n Number of inducing points\n\n num_samples : integer\n Number of samples for estimating objective function and gradients\n\n sparsify_factor : float\n Can be any number and will be included in the configuration file. It will not determine\n the number of inducing points\n\n to_optimize : list\n The set of parameters to optimize. It should be a list, and it can include 'll', 'mog', 'hyp', 'inducing' e.g.,\n it can be ['ll', 'mog'] in which case posterior and ll will be optimised.\n\n trans_class : subclass of DataTransformation\n The class which will be used to transform data.\n\n random_Z : boolean\n Whether to initialise inducing points randomly on the training data. If False, inducing points\n will be placed using k-means (or mini-batch k-mean) clustering. If True, inducing points will be placed randomly\n on the training data.\n\n logging_level : string\n The logging level to use.\n\n export_X : boolean\n Whether to export X to csv files.\n\n latent_noise : integer\n The amount of latent noise to add to the kernel. A white noise of amount latent_noise will be\n added to the kernel.\n\n opt_per_iter: integer\n Number of update of each subset of parameters in each iteration, e.g., {'mog': 15000, 'hyp': 25, 'll': 25}\n\n max_iter: integer\n Maximum of global iterations used on optimization.\n\n n_threads: integer\n Maximum number of threads used.\n\n model_image_file: string\n The image file from the which the model will be initialized.\n\n xtol: float\n Tolerance of 'X' below which the optimization is determined as converged.\n\n ftol: float\n Tolerance of 'f' below which the optimization is determined as converged.\n\n partition_size: integer\n The size which is used to partition training data (This is not the partition used for SGD).\n Training data will be split to the partitions of size ``partition_size`` and calculations will be done on each\n partition separately. This aim of this partitioning of data is to make algorithm memory efficient.\n\n Returns\n -------\n folder : string\n the name of the folder in which results are stored\n\n model : model\n the fitted model itself.\n \"\"\"\n\n if opt_per_iter is None:\n opt_per_iter = {'mog': 40, 'hyp': 40, 'll': 40}\n folder_name = name + '_' + ModelLearn.get_ID()\n transformer = trans_class.get_transformation(Ytrain, Xtrain)\n Ytrain = transformer.transform_Y(Ytrain)\n Ytest = transformer.transform_Y(Ytest)\n Xtrain = transformer.transform_X(Xtrain)\n Xtest = transformer.transform_X(Xtest)\n\n opt_max_fun_evals = None\n total_time = None\n timer_per_iter = None\n tracker = None\n export_model = False\n git_hash, git_branch = get_git()\n\n properties = {'method': method,\n 'sparsify_factor': sparsify_factor,\n 'sample_num': num_samples,\n 'll': cond_ll.__class__.__name__,\n 'opt_max_evals': opt_max_fun_evals,\n 'opt_per_iter': opt_per_iter,\n 'xtol': xtol, #V_to determine the convergence of the algorithm\n 'ftol': ftol,\n 'run_id': run_id,\n 'experiment': name,\n 'max_iter': max_iter,\n 'git_hash': git_hash,\n 'git_branch': git_branch,\n 'random_Z': random_Z,\n 'latent_noise:': latent_noise,\n 'model_init': model_image_file\n }\n\n logger = ModelLearn.get_logger(ModelLearn.get_output_path() + folder_name, folder_name, logging_level)\n logger.info('experiment started for:' + str(properties))\n\n model_image = None\n current_iter = None\n if model_image_file is not None:\n model_image = pickle.load(open(model_image_file + 'model.dump'))\n opt_params = pickle.load(open(model_image_file + 'opt.dump'))\n current_iter = opt_params['current_iter']\n\n if model_image:\n logger.info('loaded model - iteration started from: ' + str(opt_params['current_iter']) +\n ' Obj fun: ' + str(opt_params['obj_fun']) + ' fun evals: ' + str(opt_params['total_evals']))\n if method == 'full':\n m = SAVIGP_SingleComponent(Xtrain, Ytrain, num_inducing, cond_ll,\n kernel, num_samples, None, latent_noise, False, random_Z, n_threads=n_threads,\n image=model_image, partition_size=partition_size)\n _, timer_per_iter, total_time, tracker, total_evals = \\\n Optimizer.optimize_model(m, opt_max_fun_evals, logger, to_optimize, xtol, opt_per_iter, max_iter, ftol,\n ModelLearn.opt_callback(folder_name), current_iter)\n if method == 'mix1':\n m = SAVIGP_Diag(Xtrain, Ytrain, num_inducing, 1, cond_ll,\n kernel, num_samples, None, latent_noise, False, random_Z, n_threads=n_threads,\n image=model_image, partition_size=partition_size)\n _, timer_per_iter, total_time, tracker, total_evals = \\\n Optimizer.optimize_model(m, opt_max_fun_evals, logger, to_optimize, xtol, opt_per_iter, max_iter, ftol,\n ModelLearn.opt_callback(folder_name), current_iter)\n if method == 'mix2':\n m = SAVIGP_Diag(Xtrain, Ytrain, num_inducing, 2, cond_ll,\n kernel, num_samples, None, latent_noise, False, random_Z, n_threads=n_threads,\n image=model_image, partition_size=partition_size)\n _, timer_per_iter, total_time, tracker, total_evals = \\\n Optimizer.optimize_model(m, opt_max_fun_evals, logger, to_optimize, xtol, opt_per_iter, max_iter, ftol,\n ModelLearn.opt_callback(folder_name), current_iter)\n if method == 'gp':\n m = GPy.models.GPRegression(Xtrain, Ytrain, kernel[0])\n if 'll' in to_optimize and 'hyp' in to_optimize:\n m.optimize('bfgs')\n\n logger.debug(\"prediction started...\")\n y_pred, var_pred, nlpd = m.predict(Xtest, Ytest)\n logger.debug(\"prediction finished\")\n if not (tracker is None):\n ModelLearn.export_track(folder_name, tracker)\n ModelLearn.export_train(folder_name, transformer.untransform_X(Xtrain), transformer.untransform_Y(Ytrain),\n export_X)\n ModelLearn.export_test(folder_name,\n transformer.untransform_X(Xtest),\n transformer.untransform_Y(Ytest),\n [transformer.untransform_Y(y_pred)],\n [transformer.untransform_Y_var(var_pred)],\n transformer.untransform_NLPD(nlpd),\n [''], export_X)\n\n if export_model and isinstance(m, SAVIGP):\n ModelLearn.export_model(m, folder_name)\n\n properties['total_time'] = total_time\n properties['time_per_iter'] = timer_per_iter\n properties['total_evals'] = total_evals\n ModelLearn.export_configuration(folder_name, properties)\n return folder_name, m\n\n" ]
[ [ "sklearn.preprocessing.StandardScaler", "numpy.log" ], [ "numpy.savetxt", "numpy.hstack", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jscarlson/stylegan2-pytorch
[ "b460a7378ff3e80ff56190b3225c65e42e37ad6e" ]
[ "blend.py" ]
[ "import os\nimport copy\nimport numpy as np\nimport click\nfrom typing import List, Optional\nimport torch\nimport pickle\n\ndef extract_conv_names(model):\n model_names = list(name for name in model.keys())\n\n return model_names\n\ndef blend_models(low, high, model_res, level):\n\n levels = [x for x in range(level)]\n \n low_names = extract_conv_names(low)\n high_names = extract_conv_names(high)\n\n assert all((x == y for x, y in zip(low_names, high_names)))\n\n #start with lower model and add weights above\n model_out = copy.deepcopy(low)\n\n for name in high.keys():\n\n if any(f'convs.{lvl}' in name for lvl in levels):\n continue\n if any(f'to_rgbs.{lvl // 2}' in name for lvl in levels):\n continue\n if any(f'noises.noise_{lvl}' in name for lvl in levels):\n continue\n if ('style' in name):\n continue\n if ('conv1' in name):\n continue\n if ('to_rgb1' in name):\n continue\n if ('input.input' in name):\n continue\n \n # print(name)\n model_out[name] = high[name].clone()\n \n return model_out\n\n#----------------------------------------------------------------------------\n\[email protected]()\[email protected]_context\[email protected]('--lower_res_pkl', help='Network pickle filename for lower resolutions', required=True)\[email protected]('--higher_res_pkl', help='Network pickle filename for higher resolutions', required=True)\[email protected]('--output_path','out', help='Network pickle filepath for output', default='./blended.pt')\[email protected]('--model_res', type=int, help='Output resolution of model (likely 1024, 512, or 256)', default=64, show_default=True)\[email protected]('--split_lvl', type=int, help='Resolution to split model weights', default=4, show_default=True)\n\ndef create_blended_model(\n ctx: click.Context,\n lower_res_pkl: str,\n higher_res_pkl: str,\n model_res: Optional[int],\n split_lvl: Optional[int],\n out: Optional[str],\n):\n\n lo_G_ema = torch.load(lower_res_pkl, map_location=torch.device('cpu'))['g_ema']\n hi = torch.load(higher_res_pkl, map_location=torch.device('cpu'))['g_ema']\n model_out = blend_models(lo_G_ema, hi, model_res, split_lvl)\n torch.save(model_out, out)\n\n#----------------------------------------------------------------------------\n\nif __name__ == \"__main__\":\n create_blended_model() # pylint: disable=no-value-for-parameter\n\n#----------------------------------------------------------------------------" ]
[ [ "torch.device", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
traffic-analysis/gandalf
[ "7015cdde2765fadd0cb653adea1e2b5dc2a6145e" ]
[ "wfi/cw/wfi-cw5.py" ]
[ "import tensorflow as tf\nimport tensorflow.contrib.distributions as tfd\nimport numpy as np\nimport os.path as opth\nimport tqdm\nimport os\nfrom sklearn.utils import shuffle\nimport argparse\nHOME = os.path.expanduser('~')\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"2\";\nlayers = tf.keras.layers\nparser = argparse.ArgumentParser()\n\n\ndef define_generator():\n\n def conv1d_block(filters, upsample=True, activation=tf.nn.relu, index=0):\n if upsample:\n model.add(layers.UpSampling1D(name=\"UpSampling\" + str(index), size=2))\n model.add(layers.Conv1D(filters=filters, kernel_size=5, padding='same', name=\"Conv1D\" + str(index),\n activation=activation))\n model.add(layers.BatchNormalization())\n\n model = tf.keras.models.Sequential(name=\"Generator\")\n model.add(layers.Dense(int(316), activation=tf.nn.relu, name=\"NoiseToSpatial\")) #50\n model.add(layers.BatchNormalization())\n model.add(layers.Reshape((int(316),1)))\n\n conv1d_block(filters=512, upsample=True, index=0)\n conv1d_block(filters=512, upsample=True, index=1)\n conv1d_block(filters=256, upsample=True, index=2)\n conv1d_block(filters=256, upsample=True, index=3)\n conv1d_block(filters=128, upsample=False, index=4)\n conv1d_block(filters=128, upsample=False, index=5)\n conv1d_block(filters=64, upsample=False, index=6)\n conv1d_block(filters=64, upsample=False, index=7)\n conv1d_block(filters=1, upsample=False, activation=tf.nn.tanh, index=8)\n return model\n\n\nclass Discriminator:\n\n def __init__(self):\n self.tail = self._define_tail()\n self.head = self._define_head()\n\n def _define_tail(self, name=\"Discriminator\"):\n feature_model = tf.keras.models.Sequential(name=name)\n\n def conv1d_dropout(filters, strides, index=0):\n suffix = str(index)\n feature_model.add(layers.Conv1D(filters=filters, strides=strides, name=\"Conv{}\".format(suffix), padding='same',\n kernel_size=5, activation=tf.nn.leaky_relu))\n feature_model.add(layers.Dropout(name=\"Dropout{}\".format(suffix), rate=0.3))\n\n conv1d_dropout(filters=32, strides=2, index=5)\n conv1d_dropout(filters=32, strides=2, index=6)\n conv1d_dropout(filters=64, strides=2, index=0)\n conv1d_dropout(filters=64, strides=2, index=1)\n conv1d_dropout(filters=128, strides=2, index=2)\n conv1d_dropout(filters=128, strides=2, index=3)\n conv1d_dropout(filters=256, strides=1, index=4) #64\n conv1d_dropout(filters=256, strides=1, index=7)\n\n feature_model.add(layers.Flatten(name=\"Flatten\")) # This is feature layer for FM loss !!\n return feature_model\n\n def _define_head(self):\n head_model = tf.keras.models.Sequential(name=\"DiscriminatorHead\")\n\n head_model.add(layers.Dense(units=2048, activation='relu'))\n head_model.add(layers.Dropout(rate=0.5))\n head_model.add(layers.Dense(units=2048, activation='relu'))\n head_model.add(layers.Dropout(rate=0.5))\n head_model.add(layers.Dense(units=1024, activation='relu'))\n head_model.add(layers.Dropout(rate=0.5))\n head_model.add(layers.Dense(units=512, activation='relu'))\n head_model.add(layers.Dropout(rate=0.5))\n\n head_model.add(layers.Dense(units=args.num_classes, activation=None, name=\"Logits\"))\n return head_model\n\n @property\n def trainable_variables(self):\n return self.tail.trainable_variables + self.head.trainable_variables\n\n def __call__(self, x, *args, **kwargs):\n features = self.tail(x, *args, **kwargs)\n print(features.shape)\n return self.head(features, *args, **kwargs), features\n\n\ndef accuracy(logits, labels):\n preds = tf.argmax(logits, axis=1)\n return tf.reduce_mean(tf.to_float(tf.equal(preds, labels)))\n\n\ndef main(args):\n global best_acc\n best_acc = 0\n with tf.Graph().as_default():\n print(\"Input data preprocessing...\")\n with tf.name_scope(\"DataPreprocess\"):\n r_train = 500.0 / 6.0\n r_test = 100.0 / 6.0\n nClass = 100 # 95 # 100\n mon_instance = 2498.0 # 1000.0 # 300.0\n unClass = 0 # 40000 # 30000\n unmon_instance = unClass\n dim = 5000\n with tf.device('/cpu:0'):\n (train_x, train_y, test_x_data, test_y_data) = split_awf_closed(r_train, r_test, nClass, mon_instance,\n unmon_instance, dim)\n\n def reshape_and_scale(x, img_shape=(-1, dim, 1)):\n return x.reshape(img_shape).astype(np.float32)\n\n train_x = reshape_and_scale(train_x)\n test_x_data = reshape_and_scale(test_x_data)\n\n # Use AWF2 for unlabled set\n awf_data2 = np.load (HOME+'/datasets/awf2.npz', allow_pickle=True)\n\n train_x_unlabeled = awf_data2['data']\n train_y_unlabeled = awf_data2['labels']\n\n\n\n train_x_unlabeled = reshape_and_scale(train_x_unlabeled)\n\n X, y = shuffle(train_x, train_y)\n print(X.shape)\n print(y.shape)\n print(\"Setup the input pipeline...\")\n with tf.name_scope(\"InputPipeline\"):\n train_x_labeled, train_y_labeled = [], []\n for i in range(args.num_classes):\n print(i)\n train_x_labeled.append(X[y == i][:args.num_labeled_examples])\n train_y_labeled.append(y[y == i][:args.num_labeled_examples])\n train_x_labeled_data = np.concatenate(train_x_labeled)\n train_y_labeled_data = np.concatenate(train_y_labeled)\n train_x_unlabeled_data = train_x_unlabeled#np.concatenate(train_x_unlabeled)\n train_y_unlabeled_data = train_y_unlabeled#np.concatenate(train_y_unlabeled)\n\n train_x_unlabeled2, train_y_unlabeled2 = shuffle(train_x_unlabeled, train_y_unlabeled)\n train_x_unlabeled2_data = train_x_unlabeled2#np.concatenate(train_x_unlabeled2)\n train_y_unlabeled2_data = train_y_unlabeled2#np.concatenate(train_y_unlabeled2)\n\n labeled_X = tf.placeholder(tf.float32, shape=[None, dim, 1])\n labeled_y = tf.placeholder(tf.int64, shape=[None])\n\n unlabeled_X = tf.placeholder(tf.float32, shape=[None, dim, 1])\n unlabeled_y = tf.placeholder(tf.int64, shape=[None])\n\n unlabeled_X2 = tf.placeholder(tf.float32, shape=[None, dim, 1])\n unlabeled_y2 = tf.placeholder(tf.int64, shape=[None])\n\n test_X = tf.placeholder(tf.float32, shape=[None, dim, 1])\n test_y = tf.placeholder(tf.int64, shape=[None])\n\n train_labeled_dataset = tf.data.Dataset.from_tensor_slices((labeled_X, labeled_y)) \\\n .shuffle(buffer_size=len(train_x_labeled_data)) \\\n .repeat()\n train_labeled_dataset = train_labeled_dataset.batch(args.batch_size)\n iterator_labeled = train_labeled_dataset.make_initializable_iterator()\n traces_lab, labels_lab = iterator_labeled.get_next()\n\n train_unlabeled_dataset = tf.data.Dataset.from_tensor_slices(\n (unlabeled_X, unlabeled_y, unlabeled_X2, unlabeled_y2)) \\\n .shuffle(buffer_size=len(train_x_labeled_data)) \\\n .repeat()\n train_unlabeled_dataset = train_unlabeled_dataset.batch(args.batch_size)\n iterator_unlabeled = train_unlabeled_dataset.make_initializable_iterator()\n traces_unl, labels_unl, traces_unl2, labels_unl2 = iterator_unlabeled.get_next()\n\n test_dataset = tf.data.Dataset.from_tensor_slices((test_X, test_y)) \\\n .repeat()\n test_dataset = test_dataset.batch(args.batch_size)\n iterator_test = test_dataset.make_initializable_iterator()\n traces_test, labels_test = iterator_test.get_next()\n\n with tf.name_scope(\"BatchSize\"):\n batch_size_tensor = tf.shape(traces_lab)[0]\n\n z, z_perturbed = define_noise(batch_size_tensor,args)\n\n with tf.name_scope(\"Generator\"):\n g_model = define_generator()\n traces_fake = g_model(z)\n traces_fake_perturbed = g_model(z_perturbed)\n\n with tf.name_scope(\"Discriminator\") as discriminator_scope:\n d_model = Discriminator()\n logits_fake, features_fake = d_model(traces_fake, training=True)\n logits_fake_perturbed, _ = d_model(traces_fake_perturbed, training=True)\n logits_real_unl, features_real_unl = d_model(traces_unl, training=True)\n logits_real_lab, features_real_lab = d_model(traces_lab, training=True) # 1) For supervised loss\n logits_train, _ = d_model(traces_lab, training=False)\n\n with tf.name_scope(\"DiscriminatorLoss\"):\n loss_supervised = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n labels=labels_lab, logits=logits_real_lab))\n\n logits_sum_real = tf.reduce_logsumexp(logits_real_unl, axis=1)\n logits_sum_fake = tf.reduce_logsumexp(logits_fake, axis=1)\n loss_unsupervised = 0.5 * (\n tf.negative(tf.reduce_mean(logits_sum_real)) +\n tf.reduce_mean(tf.nn.softplus(logits_sum_real)) +\n tf.reduce_mean(tf.nn.softplus(logits_sum_fake)))\n loss_d = loss_supervised + loss_unsupervised\n if args.man_reg:\n loss_d += 1e-3 * tf.nn.l2_loss(logits_fake - logits_fake_perturbed) \\\n / tf.to_float(batch_size_tensor)\n\n with tf.name_scope(\"Train\") as train_scope:\n optimizer = tf.train.AdamOptimizer(args.lr * 0.25)\n optimize_d = optimizer.minimize(loss_d, var_list=d_model.trainable_variables)\n train_accuracy_op = accuracy(logits_train, labels_lab)\n\n with tf.name_scope(discriminator_scope):\n with tf.control_dependencies([optimize_d]):\n logits_fake, features_fake = d_model(traces_fake, training=True)\n logits_real_unl, features_real_unl = d_model(traces_unl2, training=True)\n\n with tf.name_scope(\"GeneratorLoss\"):\n feature_mean_real = tf.reduce_mean(features_real_unl, axis=0)\n feature_mean_fake = tf.reduce_mean(features_fake, axis=0)\n # L1 distance of features is the loss for the generator\n loss_g = tf.reduce_mean(tf.abs(feature_mean_real - feature_mean_fake))\n\n with tf.name_scope(train_scope):\n optimizer = tf.train.AdamOptimizer(args.lr, beta1=0.5)\n train_op = optimizer.minimize(loss_g, var_list=g_model.trainable_variables)\n\n with tf.name_scope(discriminator_scope):\n with tf.name_scope(\"Test\"):\n logits_test, _ = d_model(traces_test, training=False)\n test_accuracy_op = accuracy(logits_test, labels_test)\n\n with tf.name_scope(\"Summaries\"):\n summary_op = tf.summary.merge([\n tf.summary.scalar(\"LossDiscriminator\", loss_d),\n tf.summary.scalar(\"LossGenerator\", loss_g),\n tf.summary.scalar(\"ClassificationAccuracyTrain\", train_accuracy_op),\n tf.summary.scalar(\"ClassificationAccuracyTest\", test_accuracy_op)])\n writer = tf.summary.FileWriter(_next_logdir(\"tensorboard/wfi5_cw\"))\n\n print(\"Run training...\")\n steps_per_epoch = (len(train_x_labeled_data) + len(\n train_x_unlabeled_data)) // args.batch_size\n steps_per_test = test_x_data.shape[0] // args.batch_size\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n step = 0\n for epoch in range(args.train_epochs):\n losses_d, losses_g, accuracies = [], [], []\n print(\"Epoch {}\".format(epoch))\n pbar = tqdm.trange(steps_per_epoch)\n\n sess.run(iterator_labeled.initializer,\n feed_dict={labeled_X: train_x_labeled_data, labeled_y: train_y_labeled_data})\n\n sess.run(iterator_unlabeled.initializer,\n feed_dict={unlabeled_X: train_x_unlabeled_data, unlabeled_y: train_y_unlabeled_data,\n unlabeled_X2: train_x_unlabeled2_data, unlabeled_y2: train_y_unlabeled2_data})\n\n sess.run(iterator_test.initializer, feed_dict={test_X: test_x_data, test_y: test_y_data})\n\n for _ in pbar:\n if step % 1000 == 0:\n _, loss_g_batch, loss_d_batch, summ, accuracy_batch = sess.run(\n [train_op, loss_g, loss_d, summary_op, train_accuracy_op])\n writer.add_summary(summ, global_step=step)\n else:\n _, loss_g_batch, loss_d_batch, accuracy_batch = sess.run(\n [train_op, loss_g, loss_d, train_accuracy_op])\n pbar.set_description(\"Discriminator loss {0:.3f}, Generator loss {1:.3f}\"\n .format(loss_d_batch, loss_g_batch))\n losses_d.append(loss_d_batch)\n losses_g.append(loss_g_batch)\n accuracies.append(accuracy_batch)\n step += 1\n\n print(\"Discriminator loss: {0:.4f}, Generator loss: {1:.4f}, \"\n \"Train accuracy: {2:.4f}\"\n .format(np.mean(losses_d), np.mean(losses_g), np.mean(accuracies)))\n\n accuracies = [sess.run(test_accuracy_op) for _ in range(steps_per_test)]\n if np.mean (accuracies) > best_acc:\n best_acc = np.mean (accuracies)\n\n if epoch == (int(args.train_epochs)-1):\n print (\"Test accuracy: {0:.4f}\".format (np.mean (accuracies)))\n print (\"Best accuracy: {0:.4f}\".format (best_acc))\n\n\ndef define_noise(batch_size_tensor, args):\n with tf.name_scope(\"LatentNoiseVector\"):\n z = tfd.Normal(loc=0.0, scale=args.stddev).sample(\n sample_shape=(batch_size_tensor, args.z_dim_size))\n z_perturbed = z + tfd.Normal(loc=0.0, scale=args.stddev).sample(\n sample_shape=(batch_size_tensor, args.z_dim_size)) * 1e-5\n return z, z_perturbed\n\n\ndef split_awf_closed(r_train, r_test, nClass, mon_instance, unmon_instance, dim):\n mon_data = np.load(HOME+'/datasets/awf1.npz', allow_pickle=True)\n mon_x = mon_data['feature']\n\n ## We need to uniformly random selection over each monitored class\n print('mon_instance',mon_instance)\n print('unmon_instance',unmon_instance)\n num_mtrain_instance = mon_instance * (r_train / (r_train + r_test)) ## number of monitored training instances for each class\n mon_random = np.array(range(int(mon_instance)))\n np.random.shuffle(mon_random)\n\n mon_train_ins = mon_random[:int(num_mtrain_instance)] #1666\n mon_test_ins = mon_random[int(num_mtrain_instance):]\n print('mon_test_ins', len(mon_test_ins))\n\n\n # Due to the memory error, initialize np arrays here first\n train_feature = np.zeros((nClass*len(mon_train_ins), dim), dtype=int)\n test_feature = np.zeros((nClass*len(mon_test_ins),dim), dtype=int)\n print('test_feature', len(test_feature))\n train_label = np.zeros((nClass*len(mon_train_ins),), dtype=int)\n test_label = np.zeros((nClass*len(mon_test_ins),), dtype=int)\n\n print(len(mon_train_ins))\n print(len(mon_test_ins))\n i = 0\n mon_instance = int(mon_instance)\n print('Monitored training set partitioning...')\n print(nClass)\n print(len(mon_train_ins))\n for c in range(nClass):\n c=int(c)\n print(c)\n for instance in mon_train_ins:\n train_label[i] = c\n train_feature[i] = mon_x[(c*mon_instance)+instance][:dim]\n i += 1\n print(i)\n print('Monitored testing set partitioning...')\n j = 0\n for c in range(nClass):\n c = int(c)\n for instance in mon_test_ins:\n test_label[j]=c\n test_feature[j]=mon_x[(c*mon_instance)+instance][:dim]\n j += 1\n print(j)\n\n print(j)\n print('train_feature: ', len(train_feature))\n print('train_label: ', len(train_label))\n print('test_feature: ', len(test_feature))\n print('test_label: ', len(test_label))\n print('train_dim: ', len(train_feature[0]))\n print('test_dim: ', len(test_feature[0]))\n\n\n return train_feature, train_label, test_feature, test_label\n\n\ndef _next_logdir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n subdirs = [d for d in os.listdir(path) if opth.isdir(opth.join(path, d))]\n logdir = opth.join(path, \"run\" + str(len(subdirs)).zfill(4))\n if not os.path.exists(logdir):\n os.makedirs(logdir)\n return logdir\n\n\nif __name__ == \"__main__\":\n parser.add_argument ('--batch_size', required=False, default=32)\n parser.add_argument ('--train_epochs', required=False, default=12)\n parser.add_argument ('--lr', required=False, default=2e-4)\n parser.add_argument ('--stddev', required=False, default=1e-2)\n parser.add_argument ('--num_classes', required=False, default=100)\n parser.add_argument ('--z_dim_size', required=False, default=100)\n parser.add_argument ('--num_labeled_examples', required=False, default=5)\n parser.add_argument ('--man_reg', required=False, default=True)\n args = parser.parse_args ()\n for i in range(5):\n main(args)\n" ]
[ [ "tensorflow.device", "tensorflow.control_dependencies", "tensorflow.equal", "numpy.concatenate", "tensorflow.nn.l2_loss", "numpy.mean", "tensorflow.train.AdamOptimizer", "tensorflow.summary.scalar", "tensorflow.reduce_logsumexp", "tensorflow.Graph", "tensorflow.contrib.distributions.Normal", "tensorflow.name_scope", "tensorflow.Session", "tensorflow.to_float", "numpy.load", "tensorflow.argmax", "tensorflow.nn.softplus", "tensorflow.keras.models.Sequential", "tensorflow.shape", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.nn.sparse_softmax_cross_entropy_with_logits", "tensorflow.reduce_mean", "sklearn.utils.shuffle", "tensorflow.data.Dataset.from_tensor_slices", "numpy.random.shuffle", "tensorflow.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] } ]
bi3mer/Word2Vec
[ "55297c4f10c5dbfdcaf93b01282808efdd275956" ]
[ "Word2Vec/NearestNeighbor.py" ]
[ "from heapq import heappush, nsmallest\nimport numpy as np\n\nclass NearestNeighbor():\n def __init__(self, embeddings, encodings, config):\n self.embeddings = embeddings\n self.encodings = encodings\n self.config = config\n\n def euclidian_distance(self, e1, e2):\n '''\n https://stackoverflow.com/questions/1401712/how-can-the-euclidean-distance-be-calculated-with-numpy\n '''\n return np.linalg.norm(e1 - e2)\n\n def get_embedding(self, word):\n if self.encodings.word_in_vocab(word):\n return self.embeddings[word]\n\n return self.embeddings[config.unknown_word]\n\n def nearest_neighbors(self, word, count=1):\n embedding = self.get_embedding(word)\n heap = []\n\n # TODO: is it faster to not have the the string comparision and instead always\n # remove the first element of the array which will have a distance of 0\n # TODO: implement faster solution than the heap where it only keeps track of K\n # values which should vastly reduce the number of operations required.\n for w in self.embeddings:\n if w == word:\n continue\n\n dist = self.euclidian_distance(embedding, self.embeddings[w])\n heappush(heap, (dist, w))\n\n return nsmallest(count, heap)\n" ]
[ [ "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
jlazzaridean/mScarlet_lifetime_reports_pH
[ "13b022b1dc1fff8ebd0a881248011923e378889b", "13b022b1dc1fff8ebd0a881248011923e378889b" ]
[ "figures/fig3_baf_time_series/baf_TS_plot_lyso_hist.py", "figures/figS13_baf_time_series_other_ex/01_baf_TS_plot_lyso_hist.py" ]
[ "from pathlib import Path\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import Divider, Size\nimport pandas as pd\n\n# This script plots histograms of pHlys by lysosome from two particular\n# recordings (DMSO 10/29 01, pos 5; Baf 10/29 01 pos 9) for use in main\n# text figure 3.\n\ncurrent_dir = Path.cwd()\nman_dir = current_dir.parents[1]\ndata_path = man_dir / 'source_data' / 'bafilomycin_time_series' / 'baf_time_series_individ_lyso_results.csv'\nresults = pd.read_csv(data_path)\n\n# basic plot setup\nplt.style.use(man_dir / 'figures' / 'default.mplstyle')\ncycle = plt.rcParams['axes.prop_cycle'].by_key()['color']\n\n# locate the particular recording and position\ntemp = results.loc[results['date'] == 20211029]\ntemp1 = temp.loc[temp['recording'] == 1]\nbaf = temp1.loc[temp1['position'] == 9]\ndmso = temp1.loc[temp1['position'] == 5]\nassert np.max(dmso['mean_tau_ns'].values) < 5\nassert np.max(baf['mean_tau_ns'].values) < 5\nassert np.min(dmso['mean_tau_ns'].values) > 1\nassert np.min(baf['mean_tau_ns'].values) > 1\nbin_list = np.linspace(1, 5, num=40)\nfor x in range(12):\n # figure setup\n fig1 = plt.figure(figsize=(3,3), dpi=300)\n h = [Size.Fixed(1.0), Size.Fixed(1)]\n v = [Size.Fixed(0.7), Size.Fixed(1)]\n divider = Divider(fig1, (0, 0, 1, 1), h, v, aspect=False)\n axs1 = fig1.add_axes(divider.get_position(),\n axes_locator=divider.new_locator(nx=1, ny=1))\n # find and plot the correct data\n this_frame_dmso = dmso.loc[dmso['frame_ID'] == x+1]\n axs1.hist(this_frame_dmso['mean_tau_ns'].values, bins=bin_list, alpha=0.5,\n label='DMSO')\n this_frame_baf = baf.loc[baf['frame_ID'] == x+1]\n axs1.hist(this_frame_baf['mean_tau_ns'].values, bins=bin_list, alpha=0.5,\n label='BafA')\n # formatting\n axs1.set_ylabel('# Lysosomes')\n axs1.set_xlabel('Lifetime (ns)')\n axs1.set_xlim(1, 5)\n axs1.set_ylim(0, 60)\n axs1.set_title('%d min' % (x * 5 - 8)) # time 0 = when baf was added\n axs1.legend()\n out_path = current_dir / 'one_fov' / ('baf_dmso_hist_oneFOV_t%d.pdf'%x)\n fig1.savefig(out_path, bbox_inches='tight',\n transparent=True)\n\nplt.show()\n\n", "from pathlib import Path\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import Divider, Size\nimport pandas as pd\n\n# This script plots histograms of pHlys by lysosome from two particular\n# recordings (DMSO 10/29 01, pos 5; Baf 10/29 01 pos 9) for use in main\n# text figure 3.\n\ncurrent_dir = Path.cwd()\nman_dir = current_dir.parents[1]\ndata_path = man_dir / 'source_data' / 'bafilomycin_time_series' / 'baf_time_series_individ_lyso_results.csv'\nresults = pd.read_csv(data_path)\n\n# basic plot setup\nplt.style.use(man_dir / 'figures' / 'default.mplstyle')\ncycle = plt.rcParams['axes.prop_cycle'].by_key()['color']\n\n# locate the particular recording and position\ndf1029 = results.loc[results['date'] == 20211029]\ndf1215 = results.loc[results['date'] == 20211215]\ndmso1 = df1029.loc[df1029['position'] == 2]\ndmso2 = df1215.loc[df1215['position'] == 3]\nbaf1 = df1029.loc[df1029['position'] == 8]\nbaf2 = df1215.loc[df1215['position'] == 7]\n# check that my histogram bins are OK\nassert np.max(dmso1['mean_tau_ns'].values) < 5.5\nassert np.max(baf1['mean_tau_ns'].values) < 5.5\nassert np.max(dmso2['mean_tau_ns'].values) < 5.5\nassert np.max(baf2['mean_tau_ns'].values) < 5.5\nassert np.min(dmso1['mean_tau_ns'].values) > 1\nassert np.min(baf1['mean_tau_ns'].values) > 1\nassert np.min(dmso2['mean_tau_ns'].values) > 1\nassert np.min(baf2['mean_tau_ns'].values) > 1\nbin_list = np.linspace(1, 5.5, num=45)\nfor x in range(12):\n # figure setup\n fig1 = plt.figure(figsize=(3,3), dpi=300)\n h = [Size.Fixed(1.0), Size.Fixed(1)]\n v = [Size.Fixed(0.7), Size.Fixed(1)]\n divider = Divider(fig1, (0, 0, 1, 1), h, v, aspect=False)\n axs1 = fig1.add_axes(divider.get_position(),\n axes_locator=divider.new_locator(nx=1, ny=1))\n # find and plot the correct data\n this_frame_dmso1 = dmso1.loc[dmso1['frame_ID'] == x+1]\n axs1.hist(this_frame_dmso1['mean_tau_ns'].values, bins=bin_list, alpha=0.7,\n label='DMSO_1', color='#56B4E9')\n this_frame_dmso2 = dmso2.loc[dmso2['frame_ID'] == x+1]\n axs1.hist(this_frame_dmso2['mean_tau_ns'].values, bins=bin_list, alpha=0.7,\n label='DMSO_2', color='#009E73')\n this_frame_baf1 = baf1.loc[baf1['frame_ID'] == x+1]\n axs1.hist(this_frame_baf1['mean_tau_ns'].values, bins=bin_list, alpha=0.7,\n label='BafA_1', histtype=u'step', linewidth=0.75, color='#D55E00')\n this_frame_baf2 = baf2.loc[baf2['frame_ID'] == x+1]\n axs1.hist(this_frame_baf2['mean_tau_ns'].values, bins=bin_list, alpha=0.7,\n label='BafA_2', histtype=u'step', linewidth=0.75, color='#E69F00')\n # formatting\n axs1.set_ylabel('# Lysosomes')\n axs1.set_xlabel('Lifetime (ns)')\n axs1.set_xlim(1, 5.5)\n axs1.set_ylim(0, 100)\n axs1.set_title('%d min' % (x * 5 - 8)) # time 0 = when baf was added\n axs1.legend()\n out_path = current_dir / ('combined_hist_t%d.pdf'%x)\n fig1.savefig(out_path, bbox_inches='tight',\n transparent=True)\n\nplt.show()\n\n" ]
[ [ "pandas.read_csv", "numpy.linspace", "numpy.min", "numpy.max", "matplotlib.pyplot.show", "matplotlib.pyplot.style.use", "matplotlib.pyplot.figure" ], [ "pandas.read_csv", "numpy.linspace", "numpy.min", "numpy.max", "matplotlib.pyplot.show", "matplotlib.pyplot.style.use", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
wangna11BD/Paddle
[ "bc379ca3d5895eadbc1748bc5b71606011563ee1" ]
[ "python/paddle/nn/functional/extension.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\n# TODO: define the extention functions\n\nimport numpy as np\nfrom ...fluid.data_feeder import check_dtype\nfrom ...fluid.layer_helper import LayerHelper\nfrom ...fluid.framework import Variable, in_dygraph_mode\nfrom ...fluid.layers.tensor import assign\nfrom ...fluid import core, dygraph_utils\nfrom ...fluid.layers.layer_function_generator import templatedoc\nfrom ...fluid.layers.sequence_lod import sequence_mask\n\n\ndef diag_embed(input, offset=0, dim1=-2, dim2=-1):\n \"\"\"\n This OP creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2) \n are filled by ``input``. By default, a 2D plane formed by the last two dimensions \n of the returned tensor will be selected.\n\n The argument ``offset`` determines which diagonal is generated:\n\n - If offset = 0, it is the main diagonal.\n - If offset > 0, it is above the main diagonal.\n - If offset < 0, it is below the main diagonal.\n\n Args:\n input(Tensor|numpy.ndarray): The input tensor. Must be at least 1-dimensional. The input data type should be float32, float64, int32, int64.\n offset(int, optional): Which diagonal to consider. Default: 0 (main diagonal).\n dim1(int, optional): The first dimension with respect to which to take diagonal. Default: -2.\n dim2(int, optional): The second dimension with respect to which to take diagonal. Default: -1.\n \n Returns:\n Tensor, the output data type is the same as input data type.\n \n Examples:\n .. code-block:: python\n\n import paddle.nn.functional as F\n import numpy as np\n \n diag_embed = np.random.randn(2, 3).astype('float32')\n # [[ 0.7545889 , -0.25074545, 0.5929117 ],\n # [-0.6097662 , -0.01753256, 0.619769 ]]\n\n data1 = F.diag_embed(diag_embed)\n data1.numpy()\n # [[[ 0.7545889 , 0. , 0. ],\n # [ 0. , -0.25074545, 0. ],\n # [ 0. , 0. , 0.5929117 ]],\n\n # [[-0.6097662 , 0. , 0. ],\n # [ 0. , -0.01753256, 0. ],\n # [ 0. , 0. , 0.619769 ]]]\n\n data2 = F.diag_embed(diag_embed, offset=-1, dim1=0, dim2=2)\n data2.numpy()\n # [[[ 0. , 0. , 0. , 0. ],\n # [ 0.7545889 , 0. , 0. , 0. ],\n # [ 0. , -0.25074545, 0. , 0. ],\n # [ 0. , 0. , 0.5929117 , 0. ]],\n #\n # [[ 0. , 0. , 0. , 0. ],\n # [-0.6097662 , 0. , 0. , 0. ],\n # [ 0. , -0.01753256, 0. , 0. ],\n # [ 0. , 0. , 0.619769 , 0. ]]]\n\n data3 = F.diag_embed(diag_embed, offset=1, dim1=0, dim2=2)\n data3.numpy()\n # [[[ 0. , 0.7545889 , 0. , 0. ],\n # [ 0. , -0.6097662 , 0. , 0. ]],\n #\n # [[ 0. , 0. , -0.25074545, 0. ],\n # [ 0. , 0. , -0.01753256, 0. ]],\n #\n # [[ 0. , 0. , 0. , 0.5929117 ],\n # [ 0. , 0. , 0. , 0.619769 ]],\n #\n # [[ 0. , 0. , 0. , 0. ],\n # [ 0. , 0. , 0. , 0. ]]]\n \"\"\"\n inputs = {'Input': [input]}\n attrs = {'offset': offset, 'dim1': dim1, 'dim2': dim2}\n\n if not isinstance(input, Variable):\n input = assign(input)\n\n def __check_input(input, offset, dim1, dim2):\n check_dtype(input.dtype, 'Input',\n ['int32', 'int64', 'float16', 'float32', 'float64'],\n 'diag_embed')\n\n input_shape = list(input.shape)\n assert len(input_shape) >= 1, \\\n \"Input must be at least 1-dimensional, \" \\\n \"But received Input's dimensional: %s.\\n\" % \\\n len(input_shape)\n\n assert np.abs(dim1) <= len(input_shape), \\\n \"Dim1 is out of range (expected to be in range of [%d, %d], but got %d).\\n\" \\\n % (-(len(input_shape) + 1), len(input_shape), dim1)\n\n assert np.abs(dim2) <= len(input_shape), \\\n \"Dim2 is out of range (expected to be in range of [%d, %d], but got %d).\\n\" \\\n % (-(len(input_shape) + 1), len(input_shape), dim2)\n\n dim1_ = dim1 if dim1 >= 0 else len(input_shape) + dim1 + 1\n dim2_ = dim2 if dim2 >= 0 else len(input_shape) + dim2 + 1\n assert dim1_ != dim2_, \\\n \"dim1 and dim2 cannot be the same dimension.\" \\\n \"But received dim1 = %d, dim2 = %d\\n\"%(dim1, dim2)\n\n if not in_dygraph_mode():\n __check_input(input, offset, dim1, dim2)\n helper = LayerHelper(\"diag_embed\", **locals())\n\n out = helper.create_variable_for_type_inference(dtype=input.dtype)\n\n helper.append_op(\n type='diag_embed',\n inputs={'Input': [input]},\n attrs={'offset': offset,\n 'dim1': dim1,\n 'dim2': dim2},\n outputs={'Out': [out]})\n out.stop_gradient = True\n return out\n" ]
[ [ "numpy.abs" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ysBach/astropy
[ "3dc84b260e5bced65ebc2c45c40c8fa65f9b5aa9" ]
[ "astropy/coordinates/spectral_coordinate.py" ]
[ "import warnings\nfrom textwrap import indent\n\nimport astropy.units as u\nimport numpy as np\nfrom astropy.constants import c\nfrom astropy.coordinates import (ICRS,\n CartesianDifferential,\n CartesianRepresentation, SkyCoord)\nfrom astropy.coordinates.spectral_quantity import SpectralQuantity\nfrom astropy.coordinates.baseframe import (BaseCoordinateFrame,\n frame_transform_graph)\nfrom astropy.utils.exceptions import AstropyUserWarning\n\n__all__ = ['SpectralCoord']\n\n\nclass NoVelocityWarning(AstropyUserWarning):\n pass\n\n\nclass NoDistanceWarning(AstropyUserWarning):\n pass\n\n\nKMS = u.km / u.s\nC_KMS = c.to(KMS)\nZERO_VELOCITIES = CartesianDifferential([0, 0, 0] * KMS)\n\n# Default distance to use for target when none is provided\nDEFAULT_DISTANCE = 1e6 * u.kpc\n\n# We don't want to run doctests in the docstrings we inherit from Quantity\n__doctest_skip__ = ['SpectralCoord.*']\n\n\ndef _velocity_to_redshift(velocity):\n \"\"\"\n Convert a velocity to a relativistic redshift.\n \"\"\"\n beta = velocity / C_KMS\n return np.sqrt((1 + beta) / (1 - beta)) - 1\n\n\ndef _redshift_to_velocity(redshift):\n \"\"\"\n Convert a relativistic redshift to a velocity.\n \"\"\"\n zponesq = (1 + redshift) ** 2\n return (C_KMS * (zponesq - 1) / (zponesq + 1))\n\n\ndef _apply_relativistic_doppler_shift(scoord, velocity):\n \"\"\"\n Given a `SpectralQuantity` and a velocity, return a new `SpectralQuantity`\n that is Doppler shifted by this amount.\n\n Note that the Doppler shift applied is the full relativistic one, so\n `SpectralQuantity` currently expressed in velocity and not using the\n relativistic convention will temporarily be converted to use the\n relativistic convention while the shift is applied.\n\n Positive velocities are assumed to redshift the spectral quantity,\n while negative velocities blueshift the spectral quantity.\n \"\"\"\n\n # NOTE: we deliberately don't keep sub-classes of SpectralQuantity intact\n # since we can't guarantee that their metadata would be correct/consistent.\n squantity = scoord.view(SpectralQuantity)\n\n beta = velocity / c\n doppler_factor = np.sqrt((1 + beta) / (1 - beta))\n\n if squantity.unit.is_equivalent(u.m): # wavelength\n return squantity * doppler_factor\n elif (squantity.unit.is_equivalent(u.Hz) or\n squantity.unit.is_equivalent(u.eV) or\n squantity.unit.is_equivalent(1 / u.m)):\n return squantity / doppler_factor\n elif squantity.unit.is_equivalent(KMS): # velocity\n return (squantity.to(u.Hz) / doppler_factor).to(squantity.unit)\n else: # pragma: no cover\n raise RuntimeError(f\"Unexpected units in velocity shift: {squantity.unit}. \"\n \"This should not happen, so please report this in the \"\n \"astropy issue tracker!\")\n\n\ndef update_differentials_to_match(original, velocity_reference, preserve_observer_frame=False):\n \"\"\"\n Given an original coordinate object, update the differentials so that\n the final coordinate is at the same location as the original coordinate\n but co-moving with the velocity reference object.\n\n If preserve_original_frame is set to True, the resulting object will be in\n the frame of the original coordinate, otherwise it will be in the frame of\n the velocity reference.\n \"\"\"\n\n if not velocity_reference.data.differentials:\n raise ValueError(\"Reference frame has no velocities\")\n\n # If the reference has an obstime already defined, we should ignore\n # it and stick with the original observer obstime.\n if 'obstime' in velocity_reference.frame_attributes and hasattr(original, 'obstime'):\n velocity_reference = velocity_reference.replicate(obstime=original.obstime)\n\n # We transform both coordinates to ICRS for simplicity and because we know\n # it's a simple frame that is not time-dependent (it could be that both\n # the original and velocity_reference frame are time-dependent)\n\n original_icrs = original.transform_to(ICRS())\n velocity_reference_icrs = velocity_reference.transform_to(ICRS())\n\n differentials = velocity_reference_icrs.data.represent_as(CartesianRepresentation,\n CartesianDifferential).differentials\n\n data_with_differentials = (original_icrs.data.represent_as(CartesianRepresentation)\n .with_differentials(differentials))\n\n final_icrs = original_icrs.realize_frame(data_with_differentials)\n\n if preserve_observer_frame:\n final = final_icrs.transform_to(original)\n else:\n final = final_icrs.transform_to(velocity_reference)\n\n return final.replicate(representation_type=CartesianRepresentation,\n differential_type=CartesianDifferential)\n\n\ndef attach_zero_velocities(coord):\n \"\"\"\n Set the differentials to be stationary on a coordinate object.\n \"\"\"\n new_data = coord.cartesian.with_differentials(ZERO_VELOCITIES)\n return coord.realize_frame(new_data)\n\n\ndef _get_velocities(coord):\n if 's' in coord.data.differentials:\n return coord.velocity\n else:\n return ZERO_VELOCITIES\n\n\nclass SpectralCoord(SpectralQuantity):\n \"\"\"\n A spectral coordinate with its corresponding unit.\n\n .. note:: The |SpectralCoord| class is new in Astropy v4.1 and should be\n considered experimental at this time. Note that we do not fully\n support cases where the observer and target are moving\n relativistically relative to each other, so care should be taken\n in those cases. It is possible that there will be API changes in\n future versions of Astropy based on user feedback. If you have\n specific ideas for how it might be improved, please let us know\n on the `astropy-dev mailing list`_ or at\n http://feedback.astropy.org.\n\n Parameters\n ----------\n value : ndarray or `~astropy.units.Quantity` or `SpectralCoord`\n Spectral values, which should be either wavelength, frequency,\n energy, wavenumber, or velocity values.\n unit : str or `~astropy.units.Unit`\n Unit for the given spectral values.\n observer : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`, optional\n The coordinate (position and velocity) of observer. If no velocities\n are present on this object, the observer is assumed to be stationary\n relative to the frame origin.\n target : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`, optional\n The coordinate (position and velocity) of target. If no velocities\n are present on this object, the target is assumed to be stationary\n relative to the frame origin.\n radial_velocity : `~astropy.units.Quantity`, optional\n The radial velocity of the target with respect to the observer. This\n can only be specified if ``redshift`` is not specified.\n redshift : float, optional\n The relativistic redshift of the target with respect to the observer.\n This can only be specified if ``radial_velocity`` cannot be specified.\n doppler_rest : `~astropy.units.Quantity`, optional\n The rest value to use when expressing the spectral value as a velocity.\n doppler_convention : str, optional\n The Doppler convention to use when expressing the spectral value as a velocity.\n \"\"\"\n\n @u.quantity_input(radial_velocity=u.km/u.s)\n def __new__(cls, value, unit=None,\n observer=None, target=None,\n radial_velocity=None, redshift=None,\n **kwargs):\n\n obj = super().__new__(cls, value, unit=unit, **kwargs)\n\n # There are two main modes of operation in this class. Either the\n # observer and target are both defined, in which case the radial\n # velocity and redshift are automatically computed from these, or\n # only one of the observer and target are specified, along with a\n # manually specified radial velocity or redshift. So if a target and\n # observer are both specified, we can't also accept a radial velocity\n # or redshift.\n if target is not None and observer is not None:\n if radial_velocity is not None or redshift is not None:\n raise ValueError(\"Cannot specify radial velocity or redshift if both \"\n \"target and observer are specified\")\n\n # We only deal with redshifts here and in the redshift property.\n # Otherwise internally we always deal with velocities.\n if redshift is not None:\n if radial_velocity is not None:\n raise ValueError(\"Cannot set both a radial velocity and redshift\")\n redshift = u.Quantity(redshift)\n # For now, we can't specify redshift=u.one in quantity_input above\n # and have it work with plain floats, but if that is fixed, for\n # example as in https://github.com/astropy/astropy/pull/10232, we\n # can remove the check here and add redshift=u.one to the decorator\n if not redshift.unit.is_equivalent(u.one):\n raise u.UnitsError('redshift should be dimensionless')\n radial_velocity = _redshift_to_velocity(redshift)\n\n # If we're initializing from an existing SpectralCoord, keep any\n # parameters that aren't being overridden\n if observer is None:\n observer = getattr(value, 'observer', None)\n if target is None:\n target = getattr(value, 'target', None)\n\n # As mentioned above, we should only specify the radial velocity\n # manually if either or both the observer and target are not\n # specified.\n if observer is None or target is None:\n if radial_velocity is None:\n radial_velocity = getattr(value, 'radial_velocity', None)\n\n obj._radial_velocity = radial_velocity\n obj._observer = cls._validate_coordinate(observer, label='observer')\n obj._target = cls._validate_coordinate(target, label='target')\n\n return obj\n\n def __array_finalize__(self, obj):\n super().__array_finalize__(obj)\n self._radial_velocity = getattr(obj, '_radial_velocity', None)\n self._observer = getattr(obj, '_observer', None)\n self._target = getattr(obj, '_target', None)\n\n @staticmethod\n def _validate_coordinate(coord, label=''):\n \"\"\"\n Checks the type of the frame and whether a velocity differential and a\n distance has been defined on the frame object.\n\n If no distance is defined, the target is assumed to be \"really far\n away\", and the observer is assumed to be \"in the solar system\".\n\n Parameters\n ----------\n coord : `~astropy.coordinates.BaseCoordinateFrame`\n The new frame to be used for target or observer.\n label : str, optional\n The name of the object being validated (e.g. 'target' or 'observer'),\n which is then used in error messages.\n \"\"\"\n\n if coord is None:\n return\n\n if not issubclass(coord.__class__, BaseCoordinateFrame):\n if isinstance(coord, SkyCoord):\n coord = coord.frame\n else:\n raise TypeError(f\"{label} must be a SkyCoord or coordinate frame instance\")\n\n # If the distance is not well-defined, ensure that it works properly\n # for generating differentials\n # TODO: change this to not set the distance and yield a warning once\n # there's a good way to address this in astropy.coordinates\n # https://github.com/astropy/astropy/issues/10247\n with np.errstate(all='ignore'):\n distance = getattr(coord, 'distance', None)\n if distance is not None and distance.unit.physical_type == 'dimensionless':\n coord = SkyCoord(coord, distance=DEFAULT_DISTANCE)\n warnings.warn(\n \"Distance on coordinate object is dimensionless, an \"\n f\"abritrary distance value of {DEFAULT_DISTANCE} will be set instead.\",\n NoDistanceWarning)\n\n # If the observer frame does not contain information about the\n # velocity of the system, assume that the velocity is zero in the\n # system.\n if 's' not in coord.data.differentials:\n warnings.warn(\n \"No velocity defined on frame, assuming {}.\".format(\n ZERO_VELOCITIES),\n NoVelocityWarning)\n\n coord = attach_zero_velocities(coord)\n\n return coord\n\n def replicate(self, value=None, unit=None,\n observer=None, target=None,\n radial_velocity=None, redshift=None,\n doppler_convention=None, doppler_rest=None,\n copy=False):\n \"\"\"\n Return a replica of the `SpectralCoord`, optionally changing the\n values or attributes.\n\n Note that no conversion is carried out by this method - this keeps\n all the values and attributes the same, except for the ones explicitly\n passed to this method which are changed.\n\n If ``copy`` is set to `True` then a full copy of the internal arrays\n will be made. By default the replica will use a reference to the\n original arrays when possible to save memory.\n\n Parameters\n ----------\n value : ndarray or `~astropy.units.Quantity` or `SpectralCoord`, optional\n Spectral values, which should be either wavelength, frequency,\n energy, wavenumber, or velocity values.\n unit : str or `~astropy.units.Unit`\n Unit for the given spectral values.\n observer : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`, optional\n The coordinate (position and velocity) of observer.\n target : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`, optional\n The coordinate (position and velocity) of target.\n radial_velocity : `~astropy.units.Quantity`, optional\n The radial velocity of the target with respect to the observer.\n redshift : float, optional\n The relativistic redshift of the target with respect to the observer.\n doppler_rest : `~astropy.units.Quantity`, optional\n The rest value to use when expressing the spectral value as a velocity.\n doppler_convention : str, optional\n The Doppler convention to use when expressing the spectral value as a velocity.\n copy : bool, optional\n If `True`, and ``value`` is not specified, the values are copied to\n the new `SkyCoord` - otherwise a reference to the same values is used.\n\n Returns\n -------\n sc : `SpectralCoord` object\n Replica of this object\n \"\"\"\n\n if isinstance(value, u.Quantity):\n if unit is not None:\n raise ValueError(\"Cannot specify value as a Quantity and also specify unit\")\n else:\n value, unit = value.value, value.unit\n\n value = value if value is not None else self.value\n unit = unit or self.unit\n observer = self._validate_coordinate(observer) or self.observer\n target = self._validate_coordinate(target) or self.target\n doppler_convention = doppler_convention or self.doppler_convention\n doppler_rest = doppler_rest or self.doppler_rest\n\n # If value is being taken from self and copy is Tru\n if copy:\n value = value.copy()\n\n # Only include radial_velocity if it is not auto-computed from the\n # observer and target.\n if (self.observer is None or self.target is None) and radial_velocity is None and redshift is None:\n radial_velocity = self.radial_velocity\n\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', NoVelocityWarning)\n return self.__class__(value=value, unit=unit,\n observer=observer, target=target,\n radial_velocity=radial_velocity, redshift=redshift,\n doppler_convention=doppler_convention, doppler_rest=doppler_rest, copy=False)\n\n @property\n def quantity(self):\n \"\"\"\n Convert the ``SpectralCoord`` to a `~astropy.units.Quantity`.\n Equivalent to ``self.view(u.Quantity)``.\n\n Returns\n -------\n `~astropy.units.Quantity`\n This object viewed as a `~astropy.units.Quantity`.\n\n \"\"\"\n return self.view(u.Quantity)\n\n @property\n def observer(self):\n \"\"\"\n The coordinates of the observer.\n\n If set, and a target is set as well, this will override any explicit\n radial velocity passed in.\n\n Returns\n -------\n `~astropy.coordinates.BaseCoordinateFrame`\n The astropy coordinate frame representing the observation.\n \"\"\"\n return self._observer\n\n @observer.setter\n def observer(self, value):\n\n if self.observer is not None:\n raise ValueError(\"observer has already been set\")\n\n self._observer = self._validate_coordinate(value, label='observer')\n\n # Switch to auto-computing radial velocity\n if self._target is not None:\n self._radial_velocity = None\n\n @property\n def target(self):\n \"\"\"\n The coordinates of the target being observed.\n\n If set, and an observer is set as well, this will override any explicit\n radial velocity passed in.\n\n Returns\n -------\n `~astropy.coordinates.BaseCoordinateFrame`\n The astropy coordinate frame representing the target.\n \"\"\"\n return self._target\n\n @target.setter\n def target(self, value):\n\n if self.target is not None:\n raise ValueError(\"target has already been set\")\n\n self._target = self._validate_coordinate(value, label='target')\n\n # Switch to auto-computing radial velocity\n if self._observer is not None:\n self._radial_velocity = None\n\n @property\n def radial_velocity(self):\n \"\"\"\n Radial velocity of target relative to the observer.\n\n Returns\n -------\n `~astropy.units.Quantity`\n Radial velocity of target.\n\n Notes\n -----\n This is different from the ``.radial_velocity`` property of a\n coordinate frame in that this calculates the radial velocity with\n respect to the *observer*, not the origin of the frame.\n \"\"\"\n if self._observer is None or self._target is None:\n if self._radial_velocity is None:\n return 0 * KMS\n else:\n return self._radial_velocity\n else:\n return self._calculate_radial_velocity(self._observer, self._target,\n as_scalar=True)\n\n @property\n def redshift(self):\n \"\"\"\n Redshift of target relative to observer. Calculated from the radial\n velocity.\n\n Returns\n -------\n float\n Redshift of target.\n \"\"\"\n return _velocity_to_redshift(self.radial_velocity)\n\n @staticmethod\n def _calculate_radial_velocity(observer, target, as_scalar=False):\n \"\"\"\n Compute the line-of-sight velocity from the observer to the target.\n\n Parameters\n ----------\n observer : `~astropy.coordinates.BaseCoordinateFrame`\n The frame of the observer.\n target : `~astropy.coordinates.BaseCoordinateFrame`\n The frame of the target.\n as_scalar : bool\n If `True`, the magnitude of the velocity vector will be returned,\n otherwise the full vector will be returned.\n\n Returns\n -------\n `~astropy.units.Quantity`\n The radial velocity of the target with respect to the observer.\n \"\"\"\n\n # Convert observer and target to ICRS to avoid finite differencing\n # calculations that lack numerical precision.\n observer_icrs = observer.transform_to(ICRS())\n target_icrs = target.transform_to(ICRS())\n\n pos_hat = SpectralCoord._normalized_position_vector(observer_icrs, target_icrs)\n\n d_vel = target_icrs.velocity - observer_icrs.velocity\n\n vel_mag = pos_hat.dot(d_vel)\n\n if as_scalar:\n return vel_mag\n else:\n return vel_mag * pos_hat\n\n @staticmethod\n def _normalized_position_vector(observer, target):\n \"\"\"\n Calculate the normalized position vector between two frames.\n\n Parameters\n ----------\n observer : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`\n The observation frame or coordinate.\n target : `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`\n The target frame or coordinate.\n\n Returns\n -------\n pos_hat : `BaseRepresentation`\n Position representation.\n \"\"\"\n d_pos = (target.cartesian.without_differentials() -\n observer.cartesian.without_differentials())\n\n dp_norm = d_pos.norm()\n\n # Reset any that are 0 to 1 to avoid nans from 0/0\n dp_norm[dp_norm == 0] = 1 * dp_norm.unit\n\n pos_hat = d_pos / dp_norm\n\n return pos_hat\n\n @u.quantity_input(velocity=u.km/u.s)\n def with_observer_stationary_relative_to(self, frame, velocity=None, preserve_observer_frame=False):\n \"\"\"\n A new `SpectralCoord` with the velocity of the observer altered,\n but not the position.\n\n If a coordinate frame is specified, the observer velocities will be\n modified to be stationary in the specified frame. If a coordinate\n instance is specified, optionally with non-zero velocities, the\n observer velocities will be updated so that the observer is co-moving\n with the specified coordinates.\n\n Parameters\n ----------\n frame : str, `~astropy.coordinates.BaseCoordinateFrame` or `~astropy.coordinates.SkyCoord`\n The observation frame in which the observer will be stationary. This\n can be the name of a frame (e.g. 'icrs'), a frame class, frame instance\n with no data, or instance with data. This can optionally include\n velocities.\n velocity : `~astropy.units.Quantity` or `~astropy.coordinates.CartesianDifferential`, optional\n If ``frame`` does not contain velocities, these can be specified as\n a 3-element `~astropy.units.Quantity`. In the case where this is\n also not specified, the velocities default to zero.\n preserve_observer_frame : bool\n If `True`, the final observer frame class will be the same as the\n original one, and if `False` it will be the frame of the velocity\n reference class.\n\n Returns\n -------\n new_coord : `SpectralCoord`\n The new coordinate object representing the spectral data\n transformed based on the observer's new velocity frame.\n \"\"\"\n\n if self.observer is None or self.target is None:\n raise ValueError(\"This method can only be used if both observer \"\n \"and target are defined on the SpectralCoord.\")\n\n # Start off by extracting frame if a SkyCoord was passed in\n if isinstance(frame, SkyCoord):\n frame = frame.frame\n\n if isinstance(frame, BaseCoordinateFrame):\n\n if not frame.has_data:\n frame = frame.realize_frame(CartesianRepresentation(0 * u.km, 0 * u.km, 0 * u.km))\n\n if frame.data.differentials:\n if velocity is not None:\n raise ValueError('frame already has differentials, cannot also specify velocity')\n # otherwise frame is ready to go\n else:\n if velocity is None:\n differentials = ZERO_VELOCITIES\n else:\n differentials = CartesianDifferential(velocity)\n frame = frame.realize_frame(frame.data.with_differentials(differentials))\n\n if isinstance(frame, (type, str)):\n if isinstance(frame, type):\n frame_cls = frame\n elif isinstance(frame, str):\n frame_cls = frame_transform_graph.lookup_name(frame)\n if velocity is None:\n velocity = 0 * u.m / u.s, 0 * u.m / u.s, 0 * u.m / u.s\n elif velocity.shape != (3,):\n raise ValueError('velocity should be a Quantity vector with 3 elements')\n frame = frame_cls(0 * u.m, 0 * u.m, 0 * u.m,\n *velocity,\n representation_type='cartesian',\n differential_type='cartesian')\n\n observer = update_differentials_to_match(self.observer, frame,\n preserve_observer_frame=preserve_observer_frame)\n\n # Calculate the initial and final los velocity\n init_obs_vel = self._calculate_radial_velocity(self.observer, self.target, as_scalar=True)\n fin_obs_vel = self._calculate_radial_velocity(observer, self.target, as_scalar=True)\n\n # Apply transformation to data\n new_data = _apply_relativistic_doppler_shift(self, fin_obs_vel - init_obs_vel)\n\n new_coord = self.replicate(value=new_data, observer=observer)\n\n return new_coord\n\n def with_radial_velocity_shift(self, target_shift=None, observer_shift=None):\n \"\"\"\n Apply a velocity shift to this spectral coordinate.\n\n The shift can be provided as a redshift (float value) or radial\n velocity (`~astropy.units.Quantity` with physical type of 'speed').\n\n Parameters\n ----------\n target_shift : float or `~astropy.units.Quantity`\n Shift value to apply to current target.\n observer_shift : float or `~astropy.units.Quantity`\n Shift value to apply to current observer.\n\n Returns\n -------\n `SpectralCoord`\n New spectral coordinate with the target/observer velocity changed\n to incorporate the shift. This is always a new object even if\n ``target_shift`` and ``observer_shift`` are both `None`.\n \"\"\"\n\n if observer_shift is not None and (self.target is None or\n self.observer is None):\n raise ValueError(\"Both an observer and target must be defined \"\n \"before applying a velocity shift.\")\n\n for arg in [x for x in [target_shift, observer_shift] if x is not None]:\n if isinstance(arg, u.Quantity) and not arg.unit.is_equivalent((u.one, KMS)):\n raise u.UnitsError(\"Argument must have unit physical type \"\n \"'speed' for radial velocty or \"\n \"'dimensionless' for redshift.\")\n\n # The target or observer value is defined but is not a quantity object,\n # assume it's a redshift float value and convert to velocity\n\n if target_shift is None:\n if self._observer is None or self._target is None:\n return self.replicate()\n target_shift = 0 * KMS\n else:\n target_shift = u.Quantity(target_shift)\n if target_shift.unit.physical_type == 'dimensionless':\n target_shift = _redshift_to_velocity(target_shift)\n if self._observer is None or self._target is None:\n return self.replicate(value=_apply_relativistic_doppler_shift(self, target_shift),\n radial_velocity=self.radial_velocity + target_shift)\n\n if observer_shift is None:\n observer_shift = 0 * KMS\n else:\n observer_shift = u.Quantity(observer_shift)\n if observer_shift.unit.physical_type == 'dimensionless':\n observer_shift = _redshift_to_velocity(observer_shift)\n\n target_icrs = self._target.transform_to(ICRS())\n observer_icrs = self._observer.transform_to(ICRS())\n\n pos_hat = SpectralCoord._normalized_position_vector(observer_icrs, target_icrs)\n\n target_velocity = _get_velocities(target_icrs) + target_shift * pos_hat\n observer_velocity = _get_velocities(observer_icrs) + observer_shift * pos_hat\n\n target_velocity = CartesianDifferential(target_velocity.xyz)\n observer_velocity = CartesianDifferential(observer_velocity.xyz)\n\n new_target = (target_icrs\n .realize_frame(target_icrs.cartesian.with_differentials(target_velocity))\n .transform_to(self._target))\n\n new_observer = (observer_icrs\n .realize_frame(observer_icrs.cartesian.with_differentials(observer_velocity))\n .transform_to(self._observer))\n\n init_obs_vel = self._calculate_radial_velocity(observer_icrs, target_icrs, as_scalar=True)\n fin_obs_vel = self._calculate_radial_velocity(new_observer, new_target, as_scalar=True)\n\n new_data = _apply_relativistic_doppler_shift(self, fin_obs_vel - init_obs_vel)\n\n return self.replicate(value=new_data,\n observer=new_observer,\n target=new_target)\n\n def to_rest(self):\n \"\"\"\n Transforms the spectral axis to the rest frame.\n \"\"\"\n\n if self.observer is not None and self.target is not None:\n return self.with_observer_stationary_relative_to(self.target)\n\n result = _apply_relativistic_doppler_shift(self, -self.radial_velocity)\n\n return self.replicate(value=result, radial_velocity=0. * KMS, redshift=None)\n\n def __repr__(self):\n\n prefixstr = '<' + self.__class__.__name__ + ' '\n\n try:\n radial_velocity = self.radial_velocity\n redshift = self.redshift\n except ValueError:\n radial_velocity = redshift = 'Undefined'\n\n repr_items = [f'{prefixstr}']\n\n if self.observer is not None:\n observer_repr = indent(repr(self.observer), 14 * ' ').lstrip()\n repr_items.append(f' observer: {observer_repr}')\n\n if self.target is not None:\n target_repr = indent(repr(self.target), 12 * ' ').lstrip()\n repr_items.append(f' target: {target_repr}')\n\n if (self._observer is not None and self._target is not None) or self._radial_velocity is not None:\n if self.observer is not None and self.target is not None:\n repr_items.append(' observer to target (computed from above):')\n else:\n repr_items.append(' observer to target:')\n repr_items.append(f' radial_velocity={radial_velocity}')\n repr_items.append(f' redshift={redshift}')\n\n if self.doppler_rest is not None or self.doppler_convention is not None:\n repr_items.append(f' doppler_rest={self.doppler_rest}')\n repr_items.append(f' doppler_convention={self.doppler_convention}')\n\n arrstr = np.array2string(self.view(np.ndarray), separator=', ',\n prefix=' ')\n\n if len(repr_items) == 1:\n repr_items[0] += f'{arrstr}{self._unitstr:s}'\n else:\n repr_items[1] = ' (' + repr_items[1].lstrip()\n repr_items[-1] += ')'\n repr_items.append(f' {arrstr}{self._unitstr:s}')\n\n return '\\n'.join(repr_items) + '>'\n" ]
[ [ "numpy.errstate", "numpy.sqrt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
565353780/pointcloud-manage
[ "77f16671ec0b88f53cd9fde2538143721f9d3ab6" ]
[ "PointCloudClass/renderer.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport cv2\nimport numpy as np\nfrom math import cos, sin, pi\nfrom tqdm import tqdm\nimport open3d as o3d\n\ndef render(pointcloud_file_path, estimate_normals_radius, estimate_normals_max_nn):\n pointcloud = o3d.io.read_point_cloud(pointcloud_file_path, print_progress=True)\n pointcloud.estimate_normals(\n search_param=o3d.geometry.KDTreeSearchParamHybrid(\n radius=estimate_normals_radius,\n max_nn=estimate_normals_max_nn))\n o3d.visualization.draw_geometries([pointcloud])\n return True\n\nclass Renderer(object):\n def __init__(self):\n self.vis = o3d.visualization.Visualizer()\n self.render_center = None\n self.euler_angle = [0, 0, 0]\n return\n\n def getRotationMatrixFromEulerAngle(self, euler_angle):\n R_x = np.array([\n [1, 0, 0],\n [0, cos(euler_angle[0]), -sin(euler_angle[0])],\n [0, sin(euler_angle[0]), cos(euler_angle[0])]\n ])\n\n R_y = np.array([\n [cos(euler_angle[1]), 0, sin(euler_angle[1])],\n [0, 1, 0],\n [-sin(euler_angle[1]), 0, cos(euler_angle[1])]\n ])\n\n R_z = np.array([\n [cos(euler_angle[2]), -sin(euler_angle[2]), 0],\n [sin(euler_angle[2]), cos(euler_angle[2]), 0],\n [0, 0, 1]\n ])\n\n rotation_matrix = np.dot(R_z, np.dot(R_y, R_x))\n return rotation_matrix\n\n def getRotateDirection(self, direction_vector, euler_angle):\n np_direction_vector = np.array(direction_vector)\n direction_vector_norm = np.linalg.norm(np_direction_vector)\n if direction_vector_norm == 0:\n print(\"[ERROR][Renderer::getRotateDirection]\")\n print(\"\\t direction_vector_norm is 0!\")\n return None\n\n np_unit_direction_vector = np_direction_vector / direction_vector_norm\n\n rotation_matrix = self.getRotationMatrixFromEulerAngle(euler_angle)\n\n rotate_direction = np.dot(rotation_matrix, np_unit_direction_vector)\n return rotate_direction.tolist()\n\n def rotateVis(self, delta_rotate_angle):\n self.euler_angle[0] = 0\n self.euler_angle[1] = -10 * pi / 180.0\n self.euler_angle[2] += delta_rotate_angle * pi / 180.0\n\n ctr = self.vis.get_view_control()\n\n front_direction = self.getRotateDirection(\n [1, 0, 0], self.euler_angle)\n ctr.set_front(front_direction)\n\n up_direction = self.getRotateDirection(\n [0, 0, 1], self.euler_angle)\n ctr.set_up(up_direction)\n\n ctr.set_lookat(self.render_center)\n # ctr.set_zoom(0.5)\n return True\n\n def render(self, show_labels, scene_pointcloud_file_path=None):\n delta_rotate_angle = 0.5\n\n if scene_pointcloud_file_path is not None:\n print(\"start reading floor and wall...\")\n self.splitLabeledPoints(scene_pointcloud_file_path)\n\n rendered_pointcloud = o3d.geometry.PointCloud()\n\n render_points = []\n render_colors = []\n print(\"start create rendered pointcloud...\")\n for i in tqdm(range(len(self.pointcloud_list))):\n points = np.asarray(self.pointcloud_list[i].points).tolist()\n if len(points) == 0:\n continue\n for point in points:\n render_points.append(point)\n render_colors.append(self.d3_40_colors_rgb[i % len(self.d3_40_colors_rgb)] / 255.0)\n\n if scene_pointcloud_file_path is not None:\n print(\"start create rendered floor...\")\n for wall_point in tqdm(self.labeled_point_cluster_list[0]):\n if abs(wall_point[2]) > 0.01:\n continue\n render_points.append(wall_point)\n render_colors.append(np.array([132, 133, 135], dtype=np.uint8) / 255.0)\n\n rendered_pointcloud.points = o3d.utility.Vector3dVector(np.array(render_points))\n rendered_pointcloud.colors = o3d.utility.Vector3dVector(np.array(render_colors))\n\n rendered_pointcloud.estimate_normals(\n search_param=o3d.geometry.KDTreeSearchParamHybrid(radius=0.1, max_nn=30))\n\n self.render_center = rendered_pointcloud.get_axis_aligned_bounding_box().get_center()\n\n self.vis.create_window(window_name=\"Open3D RenderObject\")\n render_option = self.vis.get_render_option()\n render_option.background_color = np.array([1, 1, 1])\n render_option.point_size = 1\n\n self.vis.add_geometry(rendered_pointcloud)\n while True:\n self.rotateVis(delta_rotate_angle)\n # self.vis.update_geometry()\n self.vis.poll_events()\n self.vis.update_renderer()\n\n if ord('q') == cv2.waitKey(1):\n break\n self.vis.destroy_window()\n return True\n\n def saveRender(self, output_video_file_path):\n fps = 30\n video_width = 1920\n video_height = 1080\n delta_rotate_angle = 0.5\n\n if scene_pointcloud_file_path is not None:\n print(\"start reading floor and wall...\")\n self.splitLabeledPoints(scene_pointcloud_file_path)\n\n rendered_pointcloud = o3d.geometry.PointCloud()\n\n render_points = []\n render_colors = []\n print(\"start create rendered pointcloud...\")\n for i in tqdm(range(len(self.pointcloud_list))):\n points = np.asarray(self.pointcloud_list[i].points).tolist()\n if len(points) == 0:\n continue\n for point in points:\n render_points.append(point)\n render_colors.append(self.d3_40_colors_rgb[i % len(self.d3_40_colors_rgb)] / 255.0)\n\n if scene_pointcloud_file_path is not None:\n print(\"start create rendered floor...\")\n for wall_point in tqdm(self.labeled_point_cluster_list[0]):\n if abs(wall_point[2]) > 0.01:\n continue\n render_points.append(wall_point)\n render_colors.append(np.array([132, 133, 135], dtype=np.uint8) / 255.0)\n\n rendered_pointcloud.points = o3d.utility.Vector3dVector(np.array(render_points))\n rendered_pointcloud.colors = o3d.utility.Vector3dVector(np.array(render_colors))\n\n self.render_center = rendered_pointcloud.get_axis_aligned_bounding_box().get_center()\n\n self.vis.create_window(window_name=\"Open3D RenderObject\")\n render_option = self.vis.get_render_option()\n render_option.background_color = np.array([1, 1, 1])\n render_option.point_size = 1\n\n self.vis.add_geometry(rendered_pointcloud)\n\n fourcc = cv2.VideoWriter_fourcc(*'MP4V')\n out = cv2.VideoWriter(output_video_file_path, fourcc, fps, (video_width, video_height))\n for i in range(int(360 / delta_rotate_angle)):\n self.rotateVis(0.5)\n # self.vis.update_geometry()\n self.vis.poll_events()\n self.vis.update_renderer()\n\n open3d_image = np.asarray(self.vis.capture_screen_float_buffer()) * 255.0\n cv_image = cv2.cvtColor(open3d_image, cv2.COLOR_RGB2BGR).astype(np.uint8)\n\n out.write(cv_image)\n\n self.vis.destroy_window()\n out.release()\n return True\n\n" ]
[ [ "numpy.asarray", "numpy.dot", "numpy.array", "numpy.linalg.norm" ] ]
[ { "matplotlib": [], "numpy": [ "1.10", "1.12", "1.11", "1.19", "1.24", "1.13", "1.16", "1.9", "1.18", "1.23", "1.21", "1.22", "1.20", "1.7", "1.15", "1.14", "1.17", "1.8" ], "pandas": [], "scipy": [], "tensorflow": [] } ]
unkper/PedestrainSimulationModule
[ "039ed0903a0861130566d8d1d862594064b8e0db" ]
[ "rl/env/multiagent_particle_envs/multiagent/multi_discrete.py" ]
[ "# An old version of OpenAI Gym's multi_discrete.py. (Was getting affected by Gym updates)\n# (https://github.com/openai/gym/blob/1fb81d4e3fb780ccf77fec731287ba07da35eb84/gym/spaces/multi_discrete.py)\n\nimport numpy as np\n\nimport gym\n\nclass MultiDiscrete(gym.Space):\n \"\"\"\n - The multi-discrete action space consists of a series of discrete action spaces with different parameters\n - It can be adapted to both a Discrete action space or a continuous (Box) action space\n - It is useful to represent game controllers or keyboards where each key can be represented as a discrete action space\n - It is parametrized by passing an array of arrays containing [min, max] for each discrete action space\n where the discrete action space can take any integers from `min` to `max` (both inclusive)\n Note: A value of 0 always need to represent the NOOP action.\n e.g. Nintendo Game Controller\n - Can be conceptualized as 3 discrete action spaces:\n 1) Arrow Keys: Discrete 5 - NOOP[0], UP[1], RIGHT[2], DOWN[3], LEFT[4] - params: min: 0, max: 4\n 2) Button A: Discrete 2 - NOOP[0], Pressed[1] - params: min: 0, max: 1\n 3) Button B: Discrete 2 - NOOP[0], Pressed[1] - params: min: 0, max: 1\n - Can be initialized as\n MultiDiscrete([ [0,4], [0,1], [0,1] ])\n \"\"\"\n def __init__(self, array_of_param_array):\n self.low = np.array([x[0] for x in array_of_param_array])\n self.high = np.array([x[1] for x in array_of_param_array])\n self.num_discrete_space = self.low.shape[0]\n\n def sample(self):\n \"\"\" Returns a array with one sample from each discrete action space \"\"\"\n # For each row: round(random .* (max - min) + min, 0)\n np_random = np.random.RandomState()\n random_array = np_random.rand(self.num_discrete_space)\n return [int(x) for x in np.floor(np.multiply((self.high - self.low + 1.), random_array) + self.low)]\n def contains(self, x):\n return len(x) == self.num_discrete_space and (np.array(x) >= self.low).all() and (np.array(x) <= self.high).all()\n\n @property\n def shape(self):\n return self.num_discrete_space\n def __repr__(self):\n return \"MultiDiscrete\" + str(self.num_discrete_space)\n def __eq__(self, other):\n return np.array_equal(self.low, other.low) and np.array_equal(self.high, other.high)" ]
[ [ "numpy.multiply", "numpy.array_equal", "numpy.array", "numpy.random.RandomState" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
tonthatnam/japanese_ocr
[ "c78ed95d940fd979bbec1f33bca085e9977cafa4" ]
[ "tess/utilities/image_process.py" ]
[ "from PIL import Image\nimport tempfile\nimport cv2\nimport imutils\nimport numpy as np\n\ndef set_image_dpi_ppi(file_path):\n im = Image.open(file_path)\n length_x, width_y = im.size\n factor = float(length_x/width_y)\n size = int(600), int(600/factor)\n im_resized = im.resize(size, Image.ANTIALIAS)\n temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')\n temp_filename = temp_file.name\n im_resized.save(temp_filename, dpi=(800, 800))\n return temp_filename\n\ndef set_text_region(file_path):\n img = cv2.imread(file_path)\n height = img.shape[0]\n width = img.shape[1]\n\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n sobel = cv2.Sobel(gray, cv2.CV_8U, 1, 0, ksize=3)\n ret, binary = cv2.threshold(sobel, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY)\n\n element1 = cv2.getStructuringElement(cv2.MORPH_RECT, (int(width/2), 5))\n element2 = cv2.getStructuringElement(cv2.MORPH_RECT, (int(width/3), 2))\n dilation = cv2.dilate(binary, element2, iterations=1)\n erosion = cv2.erode(dilation, element1, iterations=1)\n dilation2 = cv2.dilate(erosion, element2, iterations=2)\n\n region = []\n contours, hierarchy = cv2.findContours(dilation2, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n for i in range(len(contours)):\n cnt = contours[i]\n area = cv2.contourArea(cnt)\n if (area < height*width/6):\n continue\n rect = cv2.minAreaRect(cnt)\n box = cv2.boxPoints(rect)\n box = np.int0(box)\n height = abs(box[0][1] - box[2][1])\n width = abs(box[0][0] - box[2][0])\n if (height > width * 1.3):\n continue\n region.append(box)\n return img, region\n\ndef set_sign_board_region(file_path):\n image = cv2.imread(file_path)\n height = image.shape[0]\n width = image.shape[1]\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n blurred = cv2.bilateralFilter(gray, 25, 15, 15)\n thresh = cv2.threshold(blurred, 90, 255, cv2.THRESH_BINARY)[1]\n output = image.copy()\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n region = []\n for c in cnts:\n epsilon = 0.02 * cv2.arcLength(c, True)\n c = cv2.approxPolyDP(c, epsilon, True)\n area = cv2.contourArea(c)\n if area < int(height*width/3):\n continue\n x,y,w,h = cv2.boundingRect(c)\n cv2.rectangle(output,(x,y),(x+w,y+h),(0,255,0),2)\n region.append((x,y,x+w,y+h))\n return output, region\n\ndef add_margin(file_path, top, right, bottom, left, color):\n image = Image.open(file_path)\n width, height = image.size\n new_width = width + right + left\n new_height = height + top + bottom\n result = Image.new(image.mode, (new_width, new_height), color)\n result.paste(image, (left, top))\n temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')\n temp_filename = temp_file.name\n result.save(temp_filename, dpi=(800, 800))\n return temp_filename\n\ndef process_text(file_path):\n image = cv2.imread(file_path)\n height = image.shape[0]\n width = image.shape[1]\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n blurred = cv2.bilateralFilter(gray, 25, 15, 15)\n thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]\n temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.png')\n temp_filename = temp_file.name\n cv2.imwrite(temp_filename, thresh)\n return temp_filename\n" ]
[ [ "numpy.int0" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
opendilab/DI-hpc
[ "8f001382cd1c0119013e1d0d0e98ff41c751d8a2" ]
[ "tests/test_iqn_nstep_td_error.py" ]
[ "import time\nimport torch\nfrom hpc_rll.origin.td import iqn_nstep_td_error, iqn_nstep_td_data\nfrom hpc_rll.rl_utils.td import IQNNStepTDError\nfrom testbase import mean_relative_error, times\n\nassert torch.cuda.is_available()\nuse_cuda = True\n\ntau = 33\ntauPrime = 34\nT = 10\nB = 64\nN = 8\ngamma = 0.95\nkappa = 0.9\n\ndef iqn_val():\n ori_q = torch.randn(tau, B, N)\n ori_next_n_q = torch.randn(tauPrime, B, N)\n ori_action = torch.randint(0, N, size=(B, ))\n ori_next_n_action = torch.randint(0, N, size=(B, ))\n ori_reward = torch.randn(T, B)\n ori_done = torch.randn(B)\n ori_r_q = torch.randn(tau, B)\n ori_weight = torch.randn(B)\n ori_value_gamma = torch.randn(B)\n \n hpc_q = ori_q.clone().detach()\n hpc_next_n_q = ori_next_n_q.clone().detach()\n hpc_action = ori_action.clone().detach()\n hpc_next_n_action = ori_next_n_action.clone().detach()\n hpc_reward = ori_reward.clone().detach()\n hpc_done = ori_done.clone().detach()\n hpc_r_q = ori_r_q.clone().detach()\n hpc_weight = ori_weight.clone().detach()\n hpc_value_gamma = ori_value_gamma.clone().detach()\n hpc_iqn = IQNNStepTDError(tau, tauPrime, T, B, N)\n\n if use_cuda:\n ori_q = ori_q.cuda()\n ori_next_n_q = ori_next_n_q.cuda()\n ori_action = ori_action.cuda()\n ori_next_n_action = ori_next_n_action.cuda()\n ori_reward = ori_reward.cuda()\n ori_done = ori_done.cuda()\n ori_r_q = ori_r_q.cuda()\n ori_weight = ori_weight.cuda()\n ori_value_gamma = ori_value_gamma.cuda()\n\n hpc_q = hpc_q.cuda()\n hpc_next_n_q = hpc_next_n_q.cuda()\n hpc_action = hpc_action.cuda()\n hpc_next_n_action = hpc_next_n_action.cuda()\n hpc_reward = hpc_reward.cuda()\n hpc_done = hpc_done.cuda()\n hpc_r_q = hpc_r_q.cuda()\n hpc_weight = hpc_weight.cuda()\n hpc_value_gamma = hpc_value_gamma.cuda()\n hpc_iqn = hpc_iqn.cuda()\n\n ori_q.requires_grad_(True)\n ori_loss, ori_ = iqn_nstep_td_error(iqn_nstep_td_data(ori_q, ori_next_n_q, ori_action, ori_next_n_action, ori_reward, ori_done, ori_r_q, ori_weight), gamma, T, kappa, ori_value_gamma)\n ori_loss = ori_loss.mean()\n ori_loss.backward()\n if use_cuda:\n torch.cuda.synchronize()\n\n torch.cuda.cudart().cudaProfilerStart()\n hpc_q.requires_grad_(True)\n hpc_loss, hpc_ = hpc_iqn(hpc_q, hpc_next_n_q, hpc_action, hpc_next_n_action, hpc_reward, hpc_done, hpc_r_q, gamma, kappa, hpc_weight, hpc_value_gamma)\n hpc_loss = hpc_loss.mean()\n hpc_loss.backward()\n if use_cuda:\n torch.cuda.synchronize()\n torch.cuda.cudart().cudaProfilerStop()\n\n mre = mean_relative_error(torch.flatten(ori_loss).cpu().detach().numpy(), torch.flatten(hpc_loss).cpu().detach().numpy())\n print(\"iqn fp mean_relative_error: \" + str(mre))\n mre = mean_relative_error(torch.flatten(ori_q.grad).cpu().detach().numpy(), torch.flatten(hpc_q.grad).cpu().detach().numpy())\n print(\"iqn bp mean_relative_error: \" + str(mre))\n\ndef iqn_perf():\n ori_q = torch.randn(tau, B, N)\n ori_next_n_q = torch.randn(tauPrime, B, N)\n ori_action = torch.randint(0, N, size=(B, ))\n ori_next_n_action = torch.randint(0, N, size=(B, ))\n ori_reward = torch.randn(T, B)\n ori_done = torch.randn(B)\n ori_r_q = torch.randn(tau, B)\n ori_weight = torch.randn(B)\n ori_value_gamma = torch.randn(B)\n \n hpc_q = ori_q.clone().detach()\n hpc_next_n_q = ori_next_n_q.clone().detach()\n hpc_action = ori_action.clone().detach()\n hpc_next_n_action = ori_next_n_action.clone().detach()\n hpc_reward = ori_reward.clone().detach()\n hpc_done = ori_done.clone().detach()\n hpc_r_q = ori_r_q.clone().detach()\n hpc_weight = ori_weight.clone().detach()\n hpc_value_gamma = ori_value_gamma.clone().detach()\n hpc_iqn = IQNNStepTDError(tau, tauPrime, T, B, N)\n\n if use_cuda:\n ori_q = ori_q.cuda()\n ori_next_n_q = ori_next_n_q.cuda()\n ori_action = ori_action.cuda()\n ori_next_n_action = ori_next_n_action.cuda()\n ori_reward = ori_reward.cuda()\n ori_done = ori_done.cuda()\n ori_r_q = ori_r_q.cuda()\n ori_weight = ori_weight.cuda()\n ori_value_gamma = ori_value_gamma.cuda()\n\n hpc_q = hpc_q.cuda()\n hpc_next_n_q = hpc_next_n_q.cuda()\n hpc_action = hpc_action.cuda()\n hpc_next_n_action = hpc_next_n_action.cuda()\n hpc_reward = hpc_reward.cuda()\n hpc_done = hpc_done.cuda()\n hpc_r_q = hpc_r_q.cuda()\n hpc_weight = hpc_weight.cuda()\n hpc_iqn = hpc_iqn.cuda()\n hpc_value_gamma = hpc_value_gamma.cuda()\n\n ori_q.requires_grad_(True)\n for i in range(times):\n t = time.time()\n ori_loss, ori_ = iqn_nstep_td_error(iqn_nstep_td_data(ori_q, ori_next_n_q, ori_action, ori_next_n_action, ori_reward, ori_done, ori_r_q, ori_weight), gamma, T, kappa, ori_value_gamma)\n ori_loss = ori_loss.mean()\n ori_loss.backward()\n if use_cuda:\n torch.cuda.synchronize()\n print('epoch: {}, original iqn cost time: {}'.format(i, time.time() - t))\n\n #torch.cuda.cudart().cudaProfilerStart()\n hpc_q.requires_grad_(True)\n for i in range(times):\n t = time.time()\n hpc_loss, hpc_ = hpc_iqn(hpc_q, hpc_next_n_q, hpc_action, hpc_next_n_action, hpc_reward, hpc_done, hpc_r_q, gamma, kappa, hpc_weight, hpc_value_gamma)\n hpc_loss = hpc_loss.mean()\n hpc_loss.backward()\n if use_cuda:\n torch.cuda.synchronize()\n print('epoch: {}, hpc iqn cost time: {}'.format(i, time.time() - t))\n #torch.cuda.cudart().cudaProfilerStop()\n\n mre = mean_relative_error(torch.flatten(ori_loss).cpu().detach().numpy(), torch.flatten(hpc_loss).cpu().detach().numpy())\n print(\"iqn fp mean_relative_error: \" + str(mre))\n mre = mean_relative_error(torch.flatten(ori_q.grad).cpu().detach().numpy(), torch.flatten(hpc_q.grad).cpu().detach().numpy())\n print(\"iqn bp mean_relative_error: \" + str(mre))\n\nif __name__ == '__main__':\n print(\"target problem: tau = {}, tauPrime = {}, T = {}, B = {}, N = {}, gamma = {}, kappa = {}\".format(tau, tauPrime, T, B, N, gamma, kappa))\n print(\"================run iqn validation test================\")\n iqn_val()\n print(\"================run iqn performance test================\")\n iqn_perf()\n" ]
[ [ "torch.cuda.synchronize", "torch.randint", "torch.randn", "torch.cuda.is_available", "torch.flatten", "torch.cuda.cudart" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
leonsor/scikit-learn-mooc
[ "b58f051efb591a38859a4242369c9494ccac6a17", "27c5caf7b0d2f0cc734baee59ad65efc263704cd" ]
[ "python_scripts/03_categorical_pipeline_sol_01.py", "python_scripts/ensemble_sol_01.py" ]
[ "# ---\n# jupyter:\n# jupytext:\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.6.0\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown]\n# # 📃 Solution for Exercise M1.04\n#\n# The goal of this exercise is to evaluate the impact of using an arbitrary\n# integer encoding for categorical variables along with a linear\n# classification model such as Logistic Regression.\n#\n# To do so, let's try to use `OrdinalEncoder` to preprocess the categorical\n# variables. This preprocessor is assembled in a pipeline with\n# `LogisticRegression`. The generalization performance of the pipeline can be\n# evaluated by cross-validation and then compared to the score obtained when\n# using `OneHotEncoder` or to some other baseline score.\n#\n# First, we load the dataset.\n\n# %%\nimport pandas as pd\n\nadult_census = pd.read_csv(\"../datasets/adult-census.csv\")\n\n# %%\ntarget_name = \"class\"\ntarget = adult_census[target_name]\ndata = adult_census.drop(columns=[target_name, \"education-num\"])\n\n# %% [markdown]\n# In the previous notebook, we used `sklearn.compose.make_column_selector` to\n# automatically select columns with a specific data type (also called `dtype`).\n# Here, we will use this selector to get only the columns containing strings\n# (column with `object` dtype) that correspond to categorical features in our\n# dataset.\n\n# %%\nfrom sklearn.compose import make_column_selector as selector\n\ncategorical_columns_selector = selector(dtype_include=object)\ncategorical_columns = categorical_columns_selector(data)\ndata_categorical = data[categorical_columns]\n\n# %% [markdown]\n# Define a scikit-learn pipeline composed of an `OrdinalEncoder` and a\n# `LogisticRegression` classifier.\n#\n# Because `OrdinalEncoder` can raise errors if it sees an unknown category at\n# prediction time, you can set the `handle_unknown=\"use_encoded_value\"` and\n# `unknown_value` parameters. You can refer to the\n# [scikit-learn documentation](https://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OrdinalEncoder.html)\n# for more details regarding these parameters.\n\n# %%\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import OrdinalEncoder\nfrom sklearn.linear_model import LogisticRegression\n\n# solution\nmodel = make_pipeline(\n OrdinalEncoder(handle_unknown=\"use_encoded_value\", unknown_value=-1),\n LogisticRegression(max_iter=500))\n\n# %% [markdown]\n# Your model is now defined. Evaluate it using a cross-validation using\n# `sklearn.model_selection.cross_validate`.\n#\n# ```{note}\n# Be aware that if an error happened during the cross-validation,\n# `cross_validate` will raise a warning and return NaN (Not a Number)\n# as scores. To make it raise a standard Python exception with a traceback,\n# you can pass the `error_score=\"raise\"` argument in the call to\n# `cross_validate`. An exception will be raised instead of a warning at the first\n# encountered problem and `cross_validate` will stop right away instead of\n# returning NaN values. This is particularly handy when developing\n# complex machine learning pipelines.\n# ```\n\n# %%\nfrom sklearn.model_selection import cross_validate\n\n# solution\ncv_results = cross_validate(model, data_categorical, target)\n\nscores = cv_results[\"test_score\"]\nprint(\"The mean cross-validation accuracy is: \"\n f\"{scores.mean():.3f} +/- {scores.std():.3f}\")\n\n# %% [markdown] tags=[\"solution\"]\n# Using an arbitrary mapping from string labels to integers as done here causes\n# the linear model to make bad assumptions on the relative ordering of\n# categories.\n#\n# This prevents the model from learning anything predictive enough and the\n# cross-validated score is even lower than the baseline we obtained by ignoring\n# the input data and just constantly predicting the most frequent class:\n\n# %% tags=[\"solution\"]\nfrom sklearn.dummy import DummyClassifier\n\ncv_results = cross_validate(DummyClassifier(strategy=\"most_frequent\"),\n data_categorical, target)\nscores = cv_results[\"test_score\"]\nprint(\"The mean cross-validation accuracy is: \"\n f\"{scores.mean():.3f} +/- {scores.std():.3f}\")\n\n# %% [markdown]\n# Now, we would like to compare the generalization performance of our previous\n# model with a new model where instead of using an `OrdinalEncoder`, we will\n# use a `OneHotEncoder`. Repeat the model evaluation using cross-validation.\n# Compare the score of both models and conclude on the impact of choosing a\n# specific encoding strategy when using a linear model.\n\n# %%\nfrom sklearn.preprocessing import OneHotEncoder\n\n# solution\nmodel = make_pipeline(\n OneHotEncoder(handle_unknown=\"ignore\"),\n LogisticRegression(max_iter=500))\ncv_results = cross_validate(model, data_categorical, target)\nscores = cv_results[\"test_score\"]\nprint(\"The mean cross-validation accuracy is: \"\n f\"{scores.mean():.3f} +/- {scores.std():.3f}\")\n\n# %% [markdown] tags=[\"solution\"]\n# With the linear classifier chosen, using an encoding that does not assume\n# any ordering lead to much better result.\n#\n# The important message here is: linear model and `OrdinalEncoder` are used\n# together only for ordinal categorical features, i.e. features that have a\n# specific ordering. Otherwise, your model will perform poorly.\n", "# %% [markdown]\n# # 📃 Solution for Exercise M6.01\n#\n# The aim of this notebook is to investigate if we can tune the hyperparameters\n# of a bagging regressor and evaluate the gain obtained.\n#\n# We will load the California housing dataset and split it into a training and\n# a testing set.\n\n# %%\nfrom sklearn.datasets import fetch_california_housing\nfrom sklearn.model_selection import train_test_split\n\ndata, target = fetch_california_housing(as_frame=True, return_X_y=True)\ntarget *= 100 # rescale the target in k$\ndata_train, data_test, target_train, target_test = train_test_split(\n data, target, random_state=0, test_size=0.5)\n\n# %% [markdown]\n# ```{note}\n# If you want a deeper overview regarding this dataset, you can refer to the\n# Appendix - Datasets description section at the end of this MOOC.\n# ```\n\n# %% [markdown]\n# Create a `BaggingRegressor` and provide a `DecisionTreeRegressor`\n# to its parameter `base_estimator`. Train the regressor and evaluate its\n# generalization performance on the testing set using the mean absolute error.\n\n# %%\n# solution\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.tree import DecisionTreeRegressor\nfrom sklearn.ensemble import BaggingRegressor\n\ntree = DecisionTreeRegressor()\nbagging = BaggingRegressor(base_estimator=tree, n_jobs=2)\nbagging.fit(data_train, target_train)\ntarget_predicted = bagging.predict(data_test)\nprint(f\"Basic mean absolute error of the bagging regressor:\\n\"\n f\"{mean_absolute_error(target_test, target_predicted):.2f} k$\")\n\n# %% [markdown]\n# Now, create a `RandomizedSearchCV` instance using the previous model and\n# tune the important parameters of the bagging regressor. Find the best\n# parameters and check if you are able to find a set of parameters that\n# improve the default regressor still using the mean absolute error as a\n# metric.\n\n# ```{tip}\n# You can list the bagging regressor's parameters using the `get_params`\n# method.\n# ```\n\n# %%\n# solution\nfor param in bagging.get_params().keys():\n print(param)\n\n# %% tags=[\"solution\"]\nfrom scipy.stats import randint\nfrom sklearn.model_selection import RandomizedSearchCV\n\nparam_grid = {\n \"n_estimators\": randint(10, 30),\n \"max_samples\": [0.5, 0.8, 1.0],\n \"max_features\": [0.5, 0.8, 1.0],\n \"base_estimator__max_depth\": randint(3, 10),\n}\nsearch = RandomizedSearchCV(\n bagging, param_grid, n_iter=20, scoring=\"neg_mean_absolute_error\"\n)\n_ = search.fit(data_train, target_train)\n\n# %% tags=[\"solution\"]\nimport pandas as pd\n\ncolumns = [f\"param_{name}\" for name in param_grid.keys()]\ncolumns += [\"mean_test_error\", \"std_test_error\"]\ncv_results = pd.DataFrame(search.cv_results_)\ncv_results[\"mean_test_error\"] = -cv_results[\"mean_test_score\"]\ncv_results[\"std_test_error\"] = cv_results[\"std_test_score\"]\ncv_results[columns].sort_values(by=\"mean_test_error\")\n\n# %% tags=[\"solution\"]\ntarget_predicted = search.predict(data_test)\nprint(f\"Mean absolute error after tuning of the bagging regressor:\\n\"\n f\"{mean_absolute_error(target_test, target_predicted):.2f} k$\")\n\n# %% [markdown]\n# We see that the predictor provided by the bagging regressor does not need\n# much hyperparameter tuning compared to a single decision tree.\n" ]
[ [ "pandas.read_csv", "sklearn.linear_model.LogisticRegression", "sklearn.dummy.DummyClassifier", "sklearn.preprocessing.OneHotEncoder", "sklearn.compose.make_column_selector", "sklearn.preprocessing.OrdinalEncoder", "sklearn.model_selection.cross_validate" ], [ "sklearn.tree.DecisionTreeRegressor", "sklearn.model_selection.RandomizedSearchCV", "sklearn.ensemble.BaggingRegressor", "sklearn.metrics.mean_absolute_error", "sklearn.model_selection.train_test_split", "pandas.DataFrame", "sklearn.datasets.fetch_california_housing", "scipy.stats.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
aarora8/icefall
[ "8cb7f712e413fffbcdfdd865be73d6ff43f0ce7a", "8cb7f712e413fffbcdfdd865be73d6ff43f0ce7a", "8cb7f712e413fffbcdfdd865be73d6ff43f0ce7a" ]
[ "egs/librispeech/ASR/conformer_mmi/decode.py", "egs/librispeech/ASR/tdnn_lstm_ctc/train.py", "egs/librispeech/ASR/conformer_ctc/export.py" ]
[ "#!/usr/bin/env python3\n# Copyright 2021 Xiaomi Corporation (Author: Liyong Guo, Fangjun Kuang)\n#\n# See ../../../../LICENSE for clarification regarding multiple authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport argparse\nimport logging\nfrom collections import defaultdict\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Tuple\n\nimport k2\nimport sentencepiece as spm\nimport torch\nimport torch.nn as nn\nfrom asr_datamodule import LibriSpeechAsrDataModule\nfrom conformer import Conformer\n\nfrom icefall.bpe_graph_compiler import BpeCtcTrainingGraphCompiler\nfrom icefall.checkpoint import average_checkpoints, load_checkpoint\nfrom icefall.decode import (\n get_lattice,\n nbest_decoding,\n nbest_oracle,\n one_best_decoding,\n rescore_with_attention_decoder,\n rescore_with_n_best_list,\n rescore_with_whole_lattice,\n)\nfrom icefall.lexicon import Lexicon\nfrom icefall.utils import (\n AttributeDict,\n get_texts,\n setup_logger,\n store_transcripts,\n str2bool,\n write_error_stats,\n)\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n\n parser.add_argument(\n \"--epoch\",\n type=int,\n default=34,\n help=\"It specifies the checkpoint to use for decoding.\"\n \"Note: Epoch counts from 0.\",\n )\n parser.add_argument(\n \"--avg\",\n type=int,\n default=20,\n help=\"Number of checkpoints to average. Automatically select \"\n \"consecutive checkpoints before the checkpoint specified by \"\n \"'--epoch'. \",\n )\n\n parser.add_argument(\n \"--method\",\n type=str,\n default=\"attention-decoder\",\n help=\"\"\"Decoding method.\n Supported values are:\n - (0) ctc-decoding. Use CTC decoding. It uses a sentence piece\n model, i.e., lang_dir/bpe.model, to convert word pieces to words.\n It needs neither a lexicon nor an n-gram LM.\n - (1) 1best. Extract the best path from the decoding lattice as the\n decoding result.\n - (2) nbest. Extract n paths from the decoding lattice; the path\n with the highest score is the decoding result.\n - (3) nbest-rescoring. Extract n paths from the decoding lattice,\n rescore them with an n-gram LM (e.g., a 4-gram LM), the path with\n the highest score is the decoding result.\n - (4) whole-lattice-rescoring. Rescore the decoding lattice with an\n n-gram LM (e.g., a 4-gram LM), the best path of rescored lattice\n is the decoding result.\n - (5) attention-decoder. Extract n paths from the LM rescored\n lattice, the path with the highest score is the decoding result.\n - (6) nbest-oracle. Its WER is the lower bound of any n-best\n rescoring method can achieve. Useful for debugging n-best\n rescoring method.\n \"\"\",\n )\n\n parser.add_argument(\n \"--num-paths\",\n type=int,\n default=100,\n help=\"\"\"Number of paths for n-best based decoding method.\n Used only when \"method\" is one of the following values:\n nbest, nbest-rescoring, attention-decoder, and nbest-oracle\n \"\"\",\n )\n\n parser.add_argument(\n \"--nbest-scale\",\n type=float,\n default=0.5,\n help=\"\"\"The scale to be applied to `lattice.scores`.\n It's needed if you use any kinds of n-best based rescoring.\n Used only when \"method\" is one of the following values:\n nbest, nbest-rescoring, attention-decoder, and nbest-oracle\n A smaller value results in more unique paths.\n \"\"\",\n )\n\n parser.add_argument(\n \"--export\",\n type=str2bool,\n default=False,\n help=\"\"\"When enabled, the averaged model is saved to\n conformer_ctc/exp/pretrained.pt. Note: only model.state_dict() is saved.\n pretrained.pt contains a dict {\"model\": model.state_dict()},\n which can be loaded by `icefall.checkpoint.load_checkpoint()`.\n \"\"\",\n )\n\n parser.add_argument(\n \"--exp-dir\",\n type=str,\n default=\"conformer_mmi/exp_500\",\n help=\"The experiment dir\",\n )\n\n parser.add_argument(\n \"--lang-dir\",\n type=str,\n default=\"data/lang_bpe_500\",\n help=\"The lang dir\",\n )\n\n parser.add_argument(\n \"--num-decoder-layers\",\n type=int,\n default=6,\n help=\"Number of attention decoder layers\",\n )\n\n return parser\n\n\ndef get_params() -> AttributeDict:\n params = AttributeDict(\n {\n \"lm_dir\": Path(\"data/lm\"),\n # parameters for conformer\n \"subsampling_factor\": 4,\n \"vgg_frontend\": False,\n \"use_feat_batchnorm\": True,\n \"feature_dim\": 80,\n \"nhead\": 8,\n \"attention_dim\": 512,\n # parameters for decoding\n \"search_beam\": 20,\n \"output_beam\": 8,\n \"min_active_states\": 30,\n \"max_active_states\": 10000,\n \"use_double_scores\": True,\n }\n )\n return params\n\n\ndef decode_one_batch(\n params: AttributeDict,\n model: nn.Module,\n HLG: Optional[k2.Fsa],\n H: Optional[k2.Fsa],\n bpe_model: Optional[spm.SentencePieceProcessor],\n batch: dict,\n word_table: k2.SymbolTable,\n sos_id: int,\n eos_id: int,\n G: Optional[k2.Fsa] = None,\n) -> Dict[str, List[List[str]]]:\n \"\"\"Decode one batch and return the result in a dict. The dict has the\n following format:\n\n - key: It indicates the setting used for decoding. For example,\n if no rescoring is used, the key is the string `no_rescore`.\n If LM rescoring is used, the key is the string `lm_scale_xxx`,\n where `xxx` is the value of `lm_scale`. An example key is\n `lm_scale_0.7`\n - value: It contains the decoding result. `len(value)` equals to\n batch size. `value[i]` is the decoding result for the i-th\n utterance in the given batch.\n Args:\n params:\n It's the return value of :func:`get_params`.\n\n - params.method is \"1best\", it uses 1best decoding without LM rescoring.\n - params.method is \"nbest\", it uses nbest decoding without LM rescoring.\n - params.method is \"nbest-rescoring\", it uses nbest LM rescoring.\n - params.method is \"whole-lattice-rescoring\", it uses whole lattice LM\n rescoring.\n\n model:\n The neural model.\n HLG:\n The decoding graph. Used only when params.method is NOT ctc-decoding.\n H:\n The ctc topo. Used only when params.method is ctc-decoding.\n bpe_model:\n The BPE model. Used only when params.method is ctc-decoding.\n batch:\n It is the return value from iterating\n `lhotse.dataset.K2SpeechRecognitionDataset`. See its documentation\n for the format of the `batch`.\n word_table:\n The word symbol table.\n sos_id:\n The token ID of the SOS.\n eos_id:\n The token ID of the EOS.\n G:\n An LM. It is not None when params.method is \"nbest-rescoring\"\n or \"whole-lattice-rescoring\". In general, the G in HLG\n is a 3-gram LM, while this G is a 4-gram LM.\n Returns:\n Return the decoding result. See above description for the format of\n the returned dict.\n \"\"\"\n if HLG is not None:\n device = HLG.device\n else:\n device = H.device\n feature = batch[\"inputs\"]\n assert feature.ndim == 3\n feature = feature.to(device)\n # at entry, feature is (N, T, C)\n\n supervisions = batch[\"supervisions\"]\n\n nnet_output, memory, memory_key_padding_mask = model(feature, supervisions)\n # nnet_output is (N, T, C)\n\n supervision_segments = torch.stack(\n (\n supervisions[\"sequence_idx\"],\n supervisions[\"start_frame\"] // params.subsampling_factor,\n supervisions[\"num_frames\"] // params.subsampling_factor,\n ),\n 1,\n ).to(torch.int32)\n\n if H is None:\n assert HLG is not None\n decoding_graph = HLG\n else:\n assert HLG is None\n assert bpe_model is not None\n decoding_graph = H\n\n lattice = get_lattice(\n nnet_output=nnet_output,\n decoding_graph=decoding_graph,\n supervision_segments=supervision_segments,\n search_beam=params.search_beam,\n output_beam=params.output_beam,\n min_active_states=params.min_active_states,\n max_active_states=params.max_active_states,\n subsampling_factor=params.subsampling_factor,\n )\n\n if params.method == \"ctc-decoding\":\n best_path = one_best_decoding(\n lattice=lattice, use_double_scores=params.use_double_scores\n )\n # Note: `best_path.aux_labels` contains token IDs, not word IDs\n # since we are using H, not HLG here.\n #\n # token_ids is a lit-of-list of IDs\n token_ids = get_texts(best_path)\n\n # hyps is a list of str, e.g., ['xxx yyy zzz', ...]\n hyps = bpe_model.decode(token_ids)\n\n # hyps is a list of list of str, e.g., [['xxx', 'yyy', 'zzz'], ... ]\n hyps = [s.split() for s in hyps]\n key = \"ctc-decoding\"\n return {key: hyps}\n\n if params.method == \"nbest-oracle\":\n # Note: You can also pass rescored lattices to it.\n # We choose the HLG decoded lattice for speed reasons\n # as HLG decoding is faster and the oracle WER\n # is only slightly worse than that of rescored lattices.\n best_path = nbest_oracle(\n lattice=lattice,\n num_paths=params.num_paths,\n ref_texts=supervisions[\"text\"],\n word_table=word_table,\n nbest_scale=params.nbest_scale,\n oov=\"<UNK>\",\n )\n hyps = get_texts(best_path)\n hyps = [[word_table[i] for i in ids] for ids in hyps]\n key = f\"oracle_{params.num_paths}_nbest_scale_{params.nbest_scale}\" # noqa\n return {key: hyps}\n\n if params.method in [\"1best\", \"nbest\"]:\n if params.method == \"1best\":\n best_path = one_best_decoding(\n lattice=lattice, use_double_scores=params.use_double_scores\n )\n key = \"no_rescore\"\n else:\n best_path = nbest_decoding(\n lattice=lattice,\n num_paths=params.num_paths,\n use_double_scores=params.use_double_scores,\n nbest_scale=params.nbest_scale,\n )\n key = f\"no_rescore-nbest-scale-{params.nbest_scale}-{params.num_paths}\" # noqa\n\n hyps = get_texts(best_path)\n hyps = [[word_table[i] for i in ids] for ids in hyps]\n return {key: hyps}\n\n assert params.method in [\n \"nbest-rescoring\",\n \"whole-lattice-rescoring\",\n \"attention-decoder\",\n ]\n\n lm_scale_list = [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]\n lm_scale_list += [0.8, 0.9, 1.0, 1.1, 1.2, 1.3]\n lm_scale_list += [1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]\n\n if params.method == \"nbest-rescoring\":\n best_path_dict = rescore_with_n_best_list(\n lattice=lattice,\n G=G,\n num_paths=params.num_paths,\n lm_scale_list=lm_scale_list,\n nbest_scale=params.nbest_scale,\n )\n elif params.method == \"whole-lattice-rescoring\":\n best_path_dict = rescore_with_whole_lattice(\n lattice=lattice,\n G_with_epsilon_loops=G,\n lm_scale_list=lm_scale_list,\n )\n elif params.method == \"attention-decoder\":\n # lattice uses a 3-gram Lm. We rescore it with a 4-gram LM.\n rescored_lattice = rescore_with_whole_lattice(\n lattice=lattice,\n G_with_epsilon_loops=G,\n lm_scale_list=None,\n )\n # TODO: pass `lattice` instead of `rescored_lattice` to\n # `rescore_with_attention_decoder`\n\n best_path_dict = rescore_with_attention_decoder(\n lattice=rescored_lattice,\n num_paths=params.num_paths,\n model=model,\n memory=memory,\n memory_key_padding_mask=memory_key_padding_mask,\n sos_id=sos_id,\n eos_id=eos_id,\n nbest_scale=params.nbest_scale,\n )\n else:\n assert False, f\"Unsupported decoding method: {params.method}\"\n\n ans = dict()\n if best_path_dict is not None:\n for lm_scale_str, best_path in best_path_dict.items():\n hyps = get_texts(best_path)\n hyps = [[word_table[i] for i in ids] for ids in hyps]\n ans[lm_scale_str] = hyps\n else:\n for lm_scale in lm_scale_list:\n ans[\"empty\"] = [[] * lattice.shape[0]]\n return ans\n\n\ndef decode_dataset(\n dl: torch.utils.data.DataLoader,\n params: AttributeDict,\n model: nn.Module,\n HLG: Optional[k2.Fsa],\n H: Optional[k2.Fsa],\n bpe_model: Optional[spm.SentencePieceProcessor],\n word_table: k2.SymbolTable,\n sos_id: int,\n eos_id: int,\n G: Optional[k2.Fsa] = None,\n) -> Dict[str, List[Tuple[List[str], List[str]]]]:\n \"\"\"Decode dataset.\n\n Args:\n dl:\n PyTorch's dataloader containing the dataset to decode.\n params:\n It is returned by :func:`get_params`.\n model:\n The neural model.\n HLG:\n The decoding graph. Used only when params.method is NOT ctc-decoding.\n H:\n The ctc topo. Used only when params.method is ctc-decoding.\n bpe_model:\n The BPE model. Used only when params.method is ctc-decoding.\n word_table:\n It is the word symbol table.\n sos_id:\n The token ID for SOS.\n eos_id:\n The token ID for EOS.\n G:\n An LM. It is not None when params.method is \"nbest-rescoring\"\n or \"whole-lattice-rescoring\". In general, the G in HLG\n is a 3-gram LM, while this G is a 4-gram LM.\n Returns:\n Return a dict, whose key may be \"no-rescore\" if no LM rescoring\n is used, or it may be \"lm_scale_0.7\" if LM rescoring is used.\n Its value is a list of tuples. Each tuple contains two elements:\n The first is the reference transcript, and the second is the\n predicted result.\n \"\"\"\n results = []\n\n num_cuts = 0\n\n try:\n num_batches = len(dl)\n except TypeError:\n num_batches = \"?\"\n\n results = defaultdict(list)\n for batch_idx, batch in enumerate(dl):\n texts = batch[\"supervisions\"][\"text\"]\n\n hyps_dict = decode_one_batch(\n params=params,\n model=model,\n HLG=HLG,\n H=H,\n bpe_model=bpe_model,\n batch=batch,\n word_table=word_table,\n G=G,\n sos_id=sos_id,\n eos_id=eos_id,\n )\n\n for lm_scale, hyps in hyps_dict.items():\n this_batch = []\n assert len(hyps) == len(texts)\n for hyp_words, ref_text in zip(hyps, texts):\n ref_words = ref_text.split()\n this_batch.append((ref_words, hyp_words))\n\n results[lm_scale].extend(this_batch)\n\n num_cuts += len(batch[\"supervisions\"][\"text\"])\n\n if batch_idx % 100 == 0:\n batch_str = f\"{batch_idx}/{num_batches}\"\n\n logging.info(\n f\"batch {batch_str}, cuts processed until now is {num_cuts}\"\n )\n return results\n\n\ndef save_results(\n params: AttributeDict,\n test_set_name: str,\n results_dict: Dict[str, List[Tuple[List[int], List[int]]]],\n):\n if params.method == \"attention-decoder\":\n # Set it to False since there are too many logs.\n enable_log = False\n else:\n enable_log = True\n test_set_wers = dict()\n for key, results in results_dict.items():\n recog_path = params.exp_dir / f\"recogs-{test_set_name}-{key}.txt\"\n store_transcripts(filename=recog_path, texts=results)\n if enable_log:\n logging.info(f\"The transcripts are stored in {recog_path}\")\n\n # The following prints out WERs, per-word error statistics and aligned\n # ref/hyp pairs.\n errs_filename = params.exp_dir / f\"errs-{test_set_name}-{key}.txt\"\n with open(errs_filename, \"w\") as f:\n wer = write_error_stats(\n f, f\"{test_set_name}-{key}\", results, enable_log=enable_log\n )\n test_set_wers[key] = wer\n\n if enable_log:\n logging.info(\n \"Wrote detailed error stats to {}\".format(errs_filename)\n )\n\n test_set_wers = sorted(test_set_wers.items(), key=lambda x: x[1])\n errs_info = params.exp_dir / f\"wer-summary-{test_set_name}.txt\"\n with open(errs_info, \"w\") as f:\n print(\"settings\\tWER\", file=f)\n for key, val in test_set_wers:\n print(\"{}\\t{}\".format(key, val), file=f)\n\n s = \"\\nFor {}, WER of different settings are:\\n\".format(test_set_name)\n note = \"\\tbest for {}\".format(test_set_name)\n for key, val in test_set_wers:\n s += \"{}\\t{}{}\\n\".format(key, val, note)\n note = \"\"\n logging.info(s)\n\n\[email protected]_grad()\ndef main():\n parser = get_parser()\n LibriSpeechAsrDataModule.add_arguments(parser)\n args = parser.parse_args()\n args.exp_dir = Path(args.exp_dir)\n args.lang_dir = Path(args.lang_dir)\n\n params = get_params()\n params.update(vars(args))\n\n setup_logger(f\"{params.exp_dir}/log-{params.method}/log-decode\")\n logging.info(\"Decoding started\")\n logging.info(params)\n\n lexicon = Lexicon(params.lang_dir)\n max_token_id = max(lexicon.tokens)\n num_classes = max_token_id + 1 # +1 for the blank\n\n device = torch.device(\"cpu\")\n if torch.cuda.is_available():\n device = torch.device(\"cuda\", 0)\n\n logging.info(f\"device: {device}\")\n\n graph_compiler = BpeCtcTrainingGraphCompiler(\n params.lang_dir,\n device=device,\n sos_token=\"<sos/eos>\",\n eos_token=\"<sos/eos>\",\n )\n sos_id = graph_compiler.sos_id\n eos_id = graph_compiler.eos_id\n\n if params.method == \"ctc-decoding\":\n HLG = None\n H = k2.ctc_topo(\n max_token=max_token_id,\n modified=False,\n device=device,\n )\n bpe_model = spm.SentencePieceProcessor()\n bpe_model.load(str(params.lang_dir / \"bpe.model\"))\n else:\n H = None\n bpe_model = None\n HLG = k2.Fsa.from_dict(\n torch.load(f\"{params.lang_dir}/HLG.pt\", map_location=\"cpu\")\n )\n HLG = HLG.to(device)\n assert HLG.requires_grad is False\n\n if not hasattr(HLG, \"lm_scores\"):\n HLG.lm_scores = HLG.scores.clone()\n\n if params.method in (\n \"nbest-rescoring\",\n \"whole-lattice-rescoring\",\n \"attention-decoder\",\n ):\n if not (params.lm_dir / \"G_4_gram.pt\").is_file():\n logging.info(\"Loading G_4_gram.fst.txt\")\n logging.warning(\"It may take 8 minutes.\")\n with open(params.lm_dir / \"G_4_gram.fst.txt\") as f:\n first_word_disambig_id = lexicon.word_table[\"#0\"]\n\n G = k2.Fsa.from_openfst(f.read(), acceptor=False)\n # G.aux_labels is not needed in later computations, so\n # remove it here.\n del G.aux_labels\n # CAUTION: The following line is crucial.\n # Arcs entering the back-off state have label equal to #0.\n # We have to change it to 0 here.\n G.labels[G.labels >= first_word_disambig_id] = 0\n G = k2.Fsa.from_fsas([G]).to(device)\n G = k2.arc_sort(G)\n torch.save(G.as_dict(), params.lm_dir / \"G_4_gram.pt\")\n else:\n logging.info(\"Loading pre-compiled G_4_gram.pt\")\n d = torch.load(params.lm_dir / \"G_4_gram.pt\", map_location=\"cpu\")\n G = k2.Fsa.from_dict(d).to(device)\n\n if params.method in [\"whole-lattice-rescoring\", \"attention-decoder\"]:\n # Add epsilon self-loops to G as we will compose\n # it with the whole lattice later\n G = k2.add_epsilon_self_loops(G)\n G = k2.arc_sort(G)\n G = G.to(device)\n\n # G.lm_scores is used to replace HLG.lm_scores during\n # LM rescoring.\n G.lm_scores = G.scores.clone()\n else:\n G = None\n\n model = Conformer(\n num_features=params.feature_dim,\n nhead=params.nhead,\n d_model=params.attention_dim,\n num_classes=num_classes,\n subsampling_factor=params.subsampling_factor,\n num_decoder_layers=params.num_decoder_layers,\n vgg_frontend=params.vgg_frontend,\n use_feat_batchnorm=params.use_feat_batchnorm,\n )\n\n if params.avg == 1:\n load_checkpoint(f\"{params.exp_dir}/epoch-{params.epoch}.pt\", model)\n else:\n start = params.epoch - params.avg + 1\n filenames = []\n for i in range(start, params.epoch + 1):\n if start >= 0:\n filenames.append(f\"{params.exp_dir}/epoch-{i}.pt\")\n logging.info(f\"averaging {filenames}\")\n model.load_state_dict(average_checkpoints(filenames))\n\n if params.export:\n logging.info(f\"Export averaged model to {params.exp_dir}/pretrained.pt\")\n torch.save(\n {\"model\": model.state_dict()}, f\"{params.exp_dir}/pretrained.pt\"\n )\n return\n\n model.to(device)\n model.eval()\n num_param = sum([p.numel() for p in model.parameters()])\n logging.info(f\"Number of model parameters: {num_param}\")\n\n librispeech = LibriSpeechAsrDataModule(args)\n # CAUTION: `test_sets` is for displaying only.\n # If you want to skip test-clean, you have to skip\n # it inside the for loop. That is, use\n #\n # if test_set == 'test-clean': continue\n #\n test_sets = [\"test-clean\", \"test-other\"]\n for test_set, test_dl in zip(test_sets, librispeech.test_dataloaders()):\n results_dict = decode_dataset(\n dl=test_dl,\n params=params,\n model=model,\n HLG=HLG,\n H=H,\n bpe_model=bpe_model,\n word_table=lexicon.word_table,\n G=G,\n sos_id=sos_id,\n eos_id=eos_id,\n )\n\n save_results(\n params=params, test_set_name=test_set, results_dict=results_dict\n )\n\n logging.info(\"Done!\")\n\n\ntorch.set_num_threads(1)\ntorch.set_num_interop_threads(1)\n\nif __name__ == \"__main__\":\n main()\n", "#!/usr/bin/env python3\n# Copyright 2021 Xiaomi Corp. (authors: Fangjun Kuang\n# Mingshuang Luo)\n#\n# See ../../../../LICENSE for clarification regarding multiple authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nimport argparse\nimport logging\nfrom pathlib import Path\nfrom shutil import copyfile\nfrom typing import Optional, Tuple\n\nimport k2\nimport torch\nimport torch.multiprocessing as mp\nimport torch.nn as nn\nimport torch.optim as optim\nfrom asr_datamodule import LibriSpeechAsrDataModule\nfrom lhotse.utils import fix_random_seed\nfrom model import TdnnLstm\nfrom torch import Tensor\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.nn.utils import clip_grad_norm_\nfrom torch.optim.lr_scheduler import StepLR\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom icefall.checkpoint import load_checkpoint\nfrom icefall.checkpoint import save_checkpoint as save_checkpoint_impl\nfrom icefall.dist import cleanup_dist, setup_dist\nfrom icefall.graph_compiler import CtcTrainingGraphCompiler\nfrom icefall.lexicon import Lexicon\nfrom icefall.utils import (\n AttributeDict,\n MetricsTracker,\n encode_supervisions,\n get_env_info,\n setup_logger,\n str2bool,\n)\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n\n parser.add_argument(\n \"--world-size\",\n type=int,\n default=1,\n help=\"Number of GPUs for DDP training.\",\n )\n\n parser.add_argument(\n \"--master-port\",\n type=int,\n default=12354,\n help=\"Master port to use for DDP training.\",\n )\n\n parser.add_argument(\n \"--tensorboard\",\n type=str2bool,\n default=True,\n help=\"Should various information be logged in tensorboard.\",\n )\n\n parser.add_argument(\n \"--num-epochs\",\n type=int,\n default=20,\n help=\"Number of epochs to train.\",\n )\n\n parser.add_argument(\n \"--start-epoch\",\n type=int,\n default=0,\n help=\"\"\"Resume training from from this epoch.\n If it is positive, it will load checkpoint from\n tdnn_lstm_ctc/exp/epoch-{start_epoch-1}.pt\n \"\"\",\n )\n\n return parser\n\n\ndef get_params() -> AttributeDict:\n \"\"\"Return a dict containing training parameters.\n\n All training related parameters that are not passed from the commandline\n is saved in the variable `params`.\n\n Commandline options are merged into `params` after they are parsed, so\n you can also access them via `params`.\n\n Explanation of options saved in `params`:\n\n - exp_dir: It specifies the directory where all training related\n files, e.g., checkpoints, log, etc, are saved\n\n - lang_dir: It contains language related input files such as\n \"lexicon.txt\"\n\n - lr: It specifies the initial learning rate\n\n - feature_dim: The model input dim. It has to match the one used\n in computing features.\n\n - weight_decay: The weight_decay for the optimizer.\n\n - subsampling_factor: The subsampling factor for the model.\n\n - best_train_loss: Best training loss so far. It is used to select\n the model that has the lowest training loss. It is\n updated during the training.\n\n - best_valid_loss: Best validation loss so far. It is used to select\n the model that has the lowest validation loss. It is\n updated during the training.\n\n - best_train_epoch: It is the epoch that has the best training loss.\n\n - best_valid_epoch: It is the epoch that has the best validation loss.\n\n - batch_idx_train: Used to writing statistics to tensorboard. It\n contains number of batches trained so far across\n epochs.\n\n - log_interval: Print training loss if batch_idx % log_interval` is 0\n\n - reset_interval: Reset statistics if batch_idx % reset_interval is 0\n\n - valid_interval: Run validation if batch_idx % valid_interval` is 0\n\n - beam_size: It is used in k2.ctc_loss\n\n - reduction: It is used in k2.ctc_loss\n\n - use_double_scores: It is used in k2.ctc_loss\n \"\"\"\n params = AttributeDict(\n {\n \"exp_dir\": Path(\"tdnn_lstm_ctc/exp\"),\n \"lang_dir\": Path(\"data/lang_phone\"),\n \"lr\": 1e-3,\n \"feature_dim\": 80,\n \"weight_decay\": 5e-4,\n \"subsampling_factor\": 3,\n \"best_train_loss\": float(\"inf\"),\n \"best_valid_loss\": float(\"inf\"),\n \"best_train_epoch\": -1,\n \"best_valid_epoch\": -1,\n \"batch_idx_train\": 0,\n \"log_interval\": 10,\n \"reset_interval\": 200,\n \"valid_interval\": 1000,\n \"beam_size\": 10,\n \"reduction\": \"sum\",\n \"use_double_scores\": True,\n \"env_info\": get_env_info(),\n }\n )\n\n return params\n\n\ndef load_checkpoint_if_available(\n params: AttributeDict,\n model: nn.Module,\n optimizer: Optional[torch.optim.Optimizer] = None,\n scheduler: Optional[torch.optim.lr_scheduler._LRScheduler] = None,\n) -> None:\n \"\"\"Load checkpoint from file.\n\n If params.start_epoch is positive, it will load the checkpoint from\n `params.start_epoch - 1`. Otherwise, this function does nothing.\n\n Apart from loading state dict for `model`, `optimizer` and `scheduler`,\n it also updates `best_train_epoch`, `best_train_loss`, `best_valid_epoch`,\n and `best_valid_loss` in `params`.\n\n Args:\n params:\n The return value of :func:`get_params`.\n model:\n The training model.\n optimizer:\n The optimizer that we are using.\n scheduler:\n The learning rate scheduler we are using.\n Returns:\n Return None.\n \"\"\"\n if params.start_epoch <= 0:\n return\n\n filename = params.exp_dir / f\"epoch-{params.start_epoch-1}.pt\"\n saved_params = load_checkpoint(\n filename,\n model=model,\n optimizer=optimizer,\n scheduler=scheduler,\n )\n\n keys = [\n \"best_train_epoch\",\n \"best_valid_epoch\",\n \"batch_idx_train\",\n \"best_train_loss\",\n \"best_valid_loss\",\n ]\n for k in keys:\n params[k] = saved_params[k]\n\n return saved_params\n\n\ndef save_checkpoint(\n params: AttributeDict,\n model: nn.Module,\n optimizer: torch.optim.Optimizer,\n scheduler: torch.optim.lr_scheduler._LRScheduler,\n rank: int = 0,\n) -> None:\n \"\"\"Save model, optimizer, scheduler and training stats to file.\n\n Args:\n params:\n It is returned by :func:`get_params`.\n model:\n The training model.\n \"\"\"\n if rank != 0:\n return\n filename = params.exp_dir / f\"epoch-{params.cur_epoch}.pt\"\n save_checkpoint_impl(\n filename=filename,\n model=model,\n params=params,\n optimizer=optimizer,\n scheduler=scheduler,\n rank=rank,\n )\n\n if params.best_train_epoch == params.cur_epoch:\n best_train_filename = params.exp_dir / \"best-train-loss.pt\"\n copyfile(src=filename, dst=best_train_filename)\n\n if params.best_valid_epoch == params.cur_epoch:\n best_valid_filename = params.exp_dir / \"best-valid-loss.pt\"\n copyfile(src=filename, dst=best_valid_filename)\n\n\ndef compute_loss(\n params: AttributeDict,\n model: nn.Module,\n batch: dict,\n graph_compiler: CtcTrainingGraphCompiler,\n is_training: bool,\n) -> Tuple[Tensor, MetricsTracker]:\n \"\"\"\n Compute CTC loss given the model and its inputs.\n\n Args:\n params:\n Parameters for training. See :func:`get_params`.\n model:\n The model for training. It is an instance of TdnnLstm in our case.\n batch:\n A batch of data. See `lhotse.dataset.K2SpeechRecognitionDataset()`\n for the content in it.\n graph_compiler:\n It is used to build a decoding graph from a ctc topo and training\n transcript. The training transcript is contained in the given `batch`,\n while the ctc topo is built when this compiler is instantiated.\n is_training:\n True for training. False for validation. When it is True, this\n function enables autograd during computation; when it is False, it\n disables autograd.\n \"\"\"\n device = graph_compiler.device\n feature = batch[\"inputs\"]\n # at entry, feature is (N, T, C)\n feature = feature.permute(0, 2, 1) # now feature is (N, C, T)\n assert feature.ndim == 3\n feature = feature.to(device)\n\n with torch.set_grad_enabled(is_training):\n nnet_output = model(feature)\n # nnet_output is (N, T, C)\n\n # NOTE: We need `encode_supervisions` to sort sequences with\n # different duration in decreasing order, required by\n # `k2.intersect_dense` called in `k2.ctc_loss`\n supervisions = batch[\"supervisions\"]\n supervision_segments, texts = encode_supervisions(\n supervisions, subsampling_factor=params.subsampling_factor\n )\n decoding_graph = graph_compiler.compile(texts)\n\n dense_fsa_vec = k2.DenseFsaVec(\n nnet_output,\n supervision_segments,\n allow_truncate=params.subsampling_factor - 1,\n )\n\n loss = k2.ctc_loss(\n decoding_graph=decoding_graph,\n dense_fsa_vec=dense_fsa_vec,\n output_beam=params.beam_size,\n reduction=params.reduction,\n use_double_scores=params.use_double_scores,\n )\n\n assert loss.requires_grad == is_training\n\n info = MetricsTracker()\n info[\"frames\"] = supervision_segments[:, 2].sum().item()\n info[\"loss\"] = loss.detach().cpu().item()\n\n return loss, info\n\n\ndef compute_validation_loss(\n params: AttributeDict,\n model: nn.Module,\n graph_compiler: CtcTrainingGraphCompiler,\n valid_dl: torch.utils.data.DataLoader,\n world_size: int = 1,\n) -> MetricsTracker:\n \"\"\"Run the validation process. The validation loss\n is saved in `params.valid_loss`.\n \"\"\"\n model.eval()\n\n tot_loss = MetricsTracker()\n\n for batch_idx, batch in enumerate(valid_dl):\n loss, loss_info = compute_loss(\n params=params,\n model=model,\n batch=batch,\n graph_compiler=graph_compiler,\n is_training=False,\n )\n assert loss.requires_grad is False\n\n tot_loss = tot_loss + loss_info\n\n if world_size > 1:\n tot_loss.reduce(loss.device)\n\n loss_value = tot_loss[\"loss\"] / tot_loss[\"frames\"]\n\n if loss_value < params.best_valid_loss:\n params.best_valid_epoch = params.cur_epoch\n params.best_valid_loss = loss_value\n\n return tot_loss\n\n\ndef train_one_epoch(\n params: AttributeDict,\n model: nn.Module,\n optimizer: torch.optim.Optimizer,\n graph_compiler: CtcTrainingGraphCompiler,\n train_dl: torch.utils.data.DataLoader,\n valid_dl: torch.utils.data.DataLoader,\n tb_writer: Optional[SummaryWriter] = None,\n world_size: int = 1,\n) -> None:\n \"\"\"Train the model for one epoch.\n\n The training loss from the mean of all frames is saved in\n `params.train_loss`. It runs the validation process every\n `params.valid_interval` batches.\n\n Args:\n params:\n It is returned by :func:`get_params`.\n model:\n The model for training.\n optimizer:\n The optimizer we are using.\n graph_compiler:\n It is used to convert transcripts to FSAs.\n train_dl:\n Dataloader for the training dataset.\n valid_dl:\n Dataloader for the validation dataset.\n tb_writer:\n Writer to write log messages to tensorboard.\n world_size:\n Number of nodes in DDP training. If it is 1, DDP is disabled.\n \"\"\"\n model.train()\n\n tot_loss = MetricsTracker()\n\n for batch_idx, batch in enumerate(train_dl):\n params.batch_idx_train += 1\n batch_size = len(batch[\"supervisions\"][\"text\"])\n\n loss, loss_info = compute_loss(\n params=params,\n model=model,\n batch=batch,\n graph_compiler=graph_compiler,\n is_training=True,\n )\n # summary stats.\n tot_loss = (tot_loss * (1 - 1 / params.reset_interval)) + loss_info\n\n optimizer.zero_grad()\n loss.backward()\n clip_grad_norm_(model.parameters(), 5.0, 2.0)\n optimizer.step()\n\n if batch_idx % params.log_interval == 0:\n logging.info(\n f\"Epoch {params.cur_epoch}, \"\n f\"batch {batch_idx}, loss[{loss_info}], \"\n f\"tot_loss[{tot_loss}], batch size: {batch_size}\"\n )\n if batch_idx % params.log_interval == 0:\n\n if tb_writer is not None:\n loss_info.write_summary(\n tb_writer, \"train/current_\", params.batch_idx_train\n )\n tot_loss.write_summary(\n tb_writer, \"train/tot_\", params.batch_idx_train\n )\n\n if batch_idx > 0 and batch_idx % params.valid_interval == 0:\n valid_info = compute_validation_loss(\n params=params,\n model=model,\n graph_compiler=graph_compiler,\n valid_dl=valid_dl,\n world_size=world_size,\n )\n model.train()\n logging.info(f\"Epoch {params.cur_epoch}, validation {valid_info}\")\n if tb_writer is not None:\n valid_info.write_summary(\n tb_writer,\n \"train/valid_\",\n params.batch_idx_train,\n )\n\n loss_value = tot_loss[\"loss\"] / tot_loss[\"frames\"]\n params.train_loss = loss_value\n\n if params.train_loss < params.best_train_loss:\n params.best_train_epoch = params.cur_epoch\n params.best_train_loss = params.train_loss\n\n\ndef run(rank, world_size, args):\n \"\"\"\n Args:\n rank:\n It is a value between 0 and `world_size-1`, which is\n passed automatically by `mp.spawn()` in :func:`main`.\n The node with rank 0 is responsible for saving checkpoint.\n world_size:\n Number of GPUs for DDP training.\n args:\n The return value of get_parser().parse_args()\n \"\"\"\n params = get_params()\n params.update(vars(args))\n\n fix_random_seed(42)\n if world_size > 1:\n setup_dist(rank, world_size, params.master_port)\n\n setup_logger(f\"{params.exp_dir}/log/log-train\")\n logging.info(\"Training started\")\n logging.info(params)\n\n if args.tensorboard and rank == 0:\n tb_writer = SummaryWriter(log_dir=f\"{params.exp_dir}/tensorboard\")\n else:\n tb_writer = None\n\n lexicon = Lexicon(params.lang_dir)\n max_phone_id = max(lexicon.tokens)\n\n device = torch.device(\"cpu\")\n if torch.cuda.is_available():\n device = torch.device(\"cuda\", rank)\n\n graph_compiler = CtcTrainingGraphCompiler(lexicon=lexicon, device=device)\n\n model = TdnnLstm(\n num_features=params.feature_dim,\n num_classes=max_phone_id + 1, # +1 for the blank symbol\n subsampling_factor=params.subsampling_factor,\n )\n\n checkpoints = load_checkpoint_if_available(params=params, model=model)\n\n model.to(device)\n if world_size > 1:\n model = DDP(model, device_ids=[rank])\n\n optimizer = optim.AdamW(\n model.parameters(),\n lr=params.lr,\n weight_decay=params.weight_decay,\n )\n scheduler = StepLR(optimizer, step_size=8, gamma=0.1)\n\n if checkpoints:\n optimizer.load_state_dict(checkpoints[\"optimizer\"])\n scheduler.load_state_dict(checkpoints[\"scheduler\"])\n\n librispeech = LibriSpeechAsrDataModule(args)\n train_dl = librispeech.train_dataloaders()\n valid_dl = librispeech.valid_dataloaders()\n\n for epoch in range(params.start_epoch, params.num_epochs):\n train_dl.sampler.set_epoch(epoch)\n\n if epoch > params.start_epoch:\n logging.info(f\"epoch {epoch}, lr: {scheduler.get_last_lr()[0]}\")\n\n if tb_writer is not None:\n tb_writer.add_scalar(\n \"train/lr\",\n scheduler.get_last_lr()[0],\n params.batch_idx_train,\n )\n tb_writer.add_scalar(\"train/epoch\", epoch, params.batch_idx_train)\n\n params.cur_epoch = epoch\n\n train_one_epoch(\n params=params,\n model=model,\n optimizer=optimizer,\n graph_compiler=graph_compiler,\n train_dl=train_dl,\n valid_dl=valid_dl,\n tb_writer=tb_writer,\n world_size=world_size,\n )\n\n scheduler.step()\n\n save_checkpoint(\n params=params,\n model=model,\n optimizer=optimizer,\n scheduler=scheduler,\n rank=rank,\n )\n\n logging.info(\"Done!\")\n if world_size > 1:\n torch.distributed.barrier()\n cleanup_dist()\n\n\ndef main():\n parser = get_parser()\n LibriSpeechAsrDataModule.add_arguments(parser)\n args = parser.parse_args()\n\n world_size = args.world_size\n assert world_size >= 1\n if world_size > 1:\n mp.spawn(run, args=(world_size, args), nprocs=world_size, join=True)\n else:\n run(rank=0, world_size=1, args=args)\n\n\nif __name__ == \"__main__\":\n main()\n", "#!/usr/bin/env python3\n#\n# Copyright 2021 Xiaomi Corporation (Author: Fangjun Kuang)\n#\n# See ../../../../LICENSE for clarification regarding multiple authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script converts several saved checkpoints\n# to a single one using model averaging.\n\nimport argparse\nimport logging\nfrom pathlib import Path\n\nimport torch\nfrom conformer import Conformer\n\nfrom icefall.checkpoint import average_checkpoints, load_checkpoint\nfrom icefall.lexicon import Lexicon\nfrom icefall.utils import AttributeDict, str2bool\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n\n parser.add_argument(\n \"--epoch\",\n type=int,\n default=34,\n help=\"It specifies the checkpoint to use for decoding.\"\n \"Note: Epoch counts from 0.\",\n )\n\n parser.add_argument(\n \"--avg\",\n type=int,\n default=20,\n help=\"Number of checkpoints to average. Automatically select \"\n \"consecutive checkpoints before the checkpoint specified by \"\n \"'--epoch'. \",\n )\n\n parser.add_argument(\n \"--exp-dir\",\n type=str,\n default=\"conformer_ctc/exp\",\n help=\"\"\"It specifies the directory where all training related\n files, e.g., checkpoints, log, etc, are saved\n \"\"\",\n )\n\n parser.add_argument(\n \"--lang-dir\",\n type=str,\n default=\"data/lang_bpe_5000\",\n help=\"\"\"It contains language related input files such as \"lexicon.txt\"\n \"\"\",\n )\n\n parser.add_argument(\n \"--jit\",\n type=str2bool,\n default=True,\n help=\"\"\"True to save a model after applying torch.jit.script.\n \"\"\",\n )\n\n return parser\n\n\ndef get_params() -> AttributeDict:\n params = AttributeDict(\n {\n \"feature_dim\": 80,\n \"subsampling_factor\": 4,\n \"use_feat_batchnorm\": True,\n \"attention_dim\": 512,\n \"nhead\": 8,\n \"num_decoder_layers\": 6,\n }\n )\n return params\n\n\ndef main():\n args = get_parser().parse_args()\n args.exp_dir = Path(args.exp_dir)\n args.lang_dir = Path(args.lang_dir)\n\n params = get_params()\n params.update(vars(args))\n\n logging.info(params)\n\n lexicon = Lexicon(params.lang_dir)\n max_token_id = max(lexicon.tokens)\n num_classes = max_token_id + 1 # +1 for the blank\n\n device = torch.device(\"cpu\")\n if torch.cuda.is_available():\n device = torch.device(\"cuda\", 0)\n\n logging.info(f\"device: {device}\")\n\n model = Conformer(\n num_features=params.feature_dim,\n nhead=params.nhead,\n d_model=params.attention_dim,\n num_classes=num_classes,\n subsampling_factor=params.subsampling_factor,\n num_decoder_layers=params.num_decoder_layers,\n vgg_frontend=False,\n use_feat_batchnorm=params.use_feat_batchnorm,\n )\n model.to(device)\n\n if params.avg == 1:\n load_checkpoint(f\"{params.exp_dir}/epoch-{params.epoch}.pt\", model)\n else:\n start = params.epoch - params.avg + 1\n filenames = []\n for i in range(start, params.epoch + 1):\n if start >= 0:\n filenames.append(f\"{params.exp_dir}/epoch-{i}.pt\")\n logging.info(f\"averaging {filenames}\")\n model.load_state_dict(average_checkpoints(filenames))\n\n model.to(\"cpu\")\n model.eval()\n\n if params.jit:\n logging.info(\"Using torch.jit.script\")\n model = torch.jit.script(model)\n filename = params.exp_dir / \"cpu_jit.pt\"\n model.save(str(filename))\n logging.info(f\"Saved to {filename}\")\n else:\n logging.info(\"Not using torch.jit.script\")\n # Save it using a format so that it can be loaded\n # by :func:`load_checkpoint`\n filename = params.exp_dir / \"pretrained.pt\"\n torch.save({\"model\": model.state_dict()}, str(filename))\n logging.info(f\"Saved to {filename}\")\n\n\nif __name__ == \"__main__\":\n formatter = (\n \"%(asctime)s %(levelname)s [%(filename)s:%(lineno)d] %(message)s\"\n )\n\n logging.basicConfig(format=formatter, level=logging.INFO)\n main()\n" ]
[ [ "torch.set_num_interop_threads", "torch.load", "torch.set_num_threads", "torch.no_grad", "torch.cuda.is_available", "torch.device", "torch.stack" ], [ "torch.multiprocessing.spawn", "torch.distributed.barrier", "torch.set_grad_enabled", "torch.utils.tensorboard.SummaryWriter", "torch.cuda.is_available", "torch.device", "torch.nn.parallel.DistributedDataParallel", "torch.optim.lr_scheduler.StepLR" ], [ "torch.device", "torch.jit.script", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DevilCarp/Paddle
[ "04325d2cbefb029a4478bdc069d3279cd566ac6a", "04325d2cbefb029a4478bdc069d3279cd566ac6a", "04325d2cbefb029a4478bdc069d3279cd566ac6a", "04325d2cbefb029a4478bdc069d3279cd566ac6a", "04325d2cbefb029a4478bdc069d3279cd566ac6a", "04325d2cbefb029a4478bdc069d3279cd566ac6a", "04325d2cbefb029a4478bdc069d3279cd566ac6a" ]
[ "python/paddle/tensor/linalg.py", "python/paddle/tensor/manipulation.py", "python/paddle/fluid/tests/unittests/ipu/test_one_hot_v2_op_ipu.py", "python/paddle/fluid/tests/unittests/test_inner.py", "python/paddle/fluid/tests/unittests/auto_parallel_autoconvert.py", "python/paddle/fluid/tests/unittests/test_ctc_align.py", "python/paddle/fluid/tests/unittests/xpu/test_cast_op_xpu.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\nfrom ..fluid.layer_helper import LayerHelper\nfrom ..framework import _varbase_creator, _dygraph_tracer\nfrom ..fluid.data_feeder import check_variable_and_dtype, check_type, check_dtype\nfrom ..static import Variable\nfrom ..fluid.framework import _in_legacy_dygraph, in_dygraph_mode\nfrom ..fluid.layers import transpose, cast # noqa: F401\nfrom ..fluid import layers\nimport paddle\nfrom paddle.common_ops_import import core\nfrom paddle.common_ops_import import VarDesc\nfrom paddle import _C_ops\n\n__all__ = []\n\n\ndef matmul(x, y, transpose_x=False, transpose_y=False, name=None):\n \"\"\"\n Applies matrix multiplication to two tensors. `matmul` follows\n the complete broadcast rules,\n and its behavior is consistent with `np.matmul`.\n\n Currently, the input tensors' number of dimensions can be any, `matmul` can be used to\n achieve the `dot`, `matmul` and `batchmatmul`.\n\n The actual behavior depends on the shapes of :math:`x`, :math:`y` and the\n flag values of :attr:`transpose_x`, :attr:`transpose_y`. Specifically:\n\n - If a transpose flag is specified, the last two dimensions of the tensor\n are transposed. If the tensor is ndim-1 of shape, the transpose is invalid. If the tensor\n is ndim-1 of shape :math:`[D]`, then for :math:`x` it is treated as :math:`[1, D]`, whereas\n for :math:`y` it is the opposite: It is treated as :math:`[D, 1]`.\n\n The multiplication behavior depends on the dimensions of `x` and `y`. Specifically:\n\n - If both tensors are 1-dimensional, the dot product result is obtained.\n\n - If both tensors are 2-dimensional, the matrix-matrix product is obtained.\n\n - If the `x` is 1-dimensional and the `y` is 2-dimensional,\n a `1` is prepended to its dimension in order to conduct the matrix multiply.\n After the matrix multiply, the prepended dimension is removed.\n\n - If the `x` is 2-dimensional and `y` is 1-dimensional,\n the matrix-vector product is obtained.\n\n - If both arguments are at least 1-dimensional and at least one argument\n is N-dimensional (where N > 2), then a batched matrix multiply is obtained.\n If the first argument is 1-dimensional, a 1 is prepended to its dimension\n in order to conduct the batched matrix multiply and removed after.\n If the second argument is 1-dimensional, a 1 is appended to its\n dimension for the purpose of the batched matrix multiple and removed after.\n The non-matrix (exclude the last two dimensions) dimensions are\n broadcasted according the broadcast rule.\n For example, if input is a (j, 1, n, m) tensor and the other is a (k, m, p) tensor,\n out will be a (j, k, n, p) tensor.\n\n Args:\n x (Tensor): The input tensor which is a Tensor.\n y (Tensor): The input tensor which is a Tensor.\n transpose_x (bool): Whether to transpose :math:`x` before multiplication.\n transpose_y (bool): Whether to transpose :math:`y` before multiplication.\n name(str|None): A name for this layer(optional). If set None, the layer\n will be named automatically.\n\n Returns:\n Tensor: The output Tensor.\n\n Examples:\n\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n # vector * vector\n x_data = np.random.random([10]).astype(np.float32)\n y_data = np.random.random([10]).astype(np.float32)\n x = paddle.to_tensor(x_data)\n y = paddle.to_tensor(y_data)\n z = paddle.matmul(x, y)\n print(z.numpy().shape)\n # [1]\n\n # matrix * vector\n x_data = np.random.random([10, 5]).astype(np.float32)\n y_data = np.random.random([5]).astype(np.float32)\n x = paddle.to_tensor(x_data)\n y = paddle.to_tensor(y_data)\n z = paddle.matmul(x, y)\n print(z.numpy().shape)\n # [10]\n\n # batched matrix * broadcasted vector\n x_data = np.random.random([10, 5, 2]).astype(np.float32)\n y_data = np.random.random([2]).astype(np.float32)\n x = paddle.to_tensor(x_data)\n y = paddle.to_tensor(y_data)\n z = paddle.matmul(x, y)\n print(z.numpy().shape)\n # [10, 5]\n\n # batched matrix * batched matrix\n x_data = np.random.random([10, 5, 2]).astype(np.float32)\n y_data = np.random.random([10, 2, 5]).astype(np.float32)\n x = paddle.to_tensor(x_data)\n y = paddle.to_tensor(y_data)\n z = paddle.matmul(x, y)\n print(z.numpy().shape)\n # [10, 5, 5]\n\n # batched matrix * broadcasted matrix\n x_data = np.random.random([10, 1, 5, 2]).astype(np.float32)\n y_data = np.random.random([1, 3, 2, 5]).astype(np.float32)\n x = paddle.to_tensor(x_data)\n y = paddle.to_tensor(y_data)\n z = paddle.matmul(x, y)\n print(z.numpy().shape)\n # [10, 3, 5, 5]\n\n \"\"\"\n if in_dygraph_mode():\n return _C_ops.final_state_matmul(x, y, transpose_x, transpose_y)\n\n if _in_legacy_dygraph():\n op_type = 'matmul_v2'\n op = getattr(_C_ops, op_type)\n return op(x, y, 'trans_x', transpose_x, 'trans_y', transpose_y)\n\n attrs = {\n 'trans_x': transpose_x,\n 'trans_y': transpose_y,\n }\n\n def __check_input(x, y):\n var_names = {'x': x, 'y': y}\n for name, val in var_names.items():\n check_variable_and_dtype(\n val, name,\n ['float16', 'float32', 'float64', 'complex64', 'complex128'],\n 'matmul')\n\n __check_input(x, y)\n\n helper = LayerHelper('matmul_v2', **locals())\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n helper.append_op(\n type='matmul_v2',\n inputs={'X': x,\n 'Y': y},\n outputs={'Out': out},\n attrs=attrs)\n return out\n\n\ndef norm(x, p='fro', axis=None, keepdim=False, name=None):\n \"\"\"\n\n Returns the matrix norm (Frobenius) or vector norm (the 1-norm, the Euclidean\n or 2-norm, and in general the p-norm for p > 0) of a given tensor.\n\n .. note::\n This norm API is different from `numpy.linalg.norm`.\n This api supports high-order input tensors (rank >= 3), and certain axis need to be pointed out to calculate the norm.\n But `numpy.linalg.norm` only supports 1-D vector or 2-D matrix as input tensor.\n For p-order matrix norm, this api actually treats matrix as a flattened vector to calculate the vector norm, NOT REAL MATRIX NORM.\n\n Args:\n x (Tensor): The input tensor could be N-D tensor, and the input data\n type could be float32 or float64.\n p (float|string, optional): Order of the norm. Supported values are `fro`, `0`, `1`, `2`,\n `inf`, `-inf` and any positive real number yielding the corresponding p-norm. Not supported: ord < 0 and nuclear norm.\n Default value is `fro`.\n axis (int|list|tuple, optional): The axis on which to apply norm operation. If axis is int\n or list(int)/tuple(int) with only one element, the vector norm is computed over the axis.\n If `axis < 0`, the dimension to norm operation is rank(input) + axis.\n If axis is a list(int)/tuple(int) with two elements, the matrix norm is computed over the axis.\n Defalut value is `None`.\n keepdim (bool, optional): Whether to reserve the reduced dimension in the\n output Tensor. The result tensor will have fewer dimension\n than the :attr:`input` unless :attr:`keepdim` is true, default\n value is False.\n name (str, optional): The default value is None. Normally there is no need for\n user to set this property. For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: results of norm operation on the specified axis of input tensor,\n it's data type is the same as input's Tensor.\n\n Examples:\n .. code-block:: python\n\n import paddle\n import numpy as np\n shape=[2, 3, 4]\n np_input = np.arange(24).astype('float32') - 12\n np_input = np_input.reshape(shape)\n x = paddle.to_tensor(np_input)\n #[[[-12. -11. -10. -9.] [ -8. -7. -6. -5.] [ -4. -3. -2. -1.]]\n # [[ 0. 1. 2. 3.] [ 4. 5. 6. 7.] [ 8. 9. 10. 11.]]]\n\n # compute frobenius norm along last two dimensions.\n out_fro = paddle.linalg.norm(x, p='fro', axis=[0,1])\n # out_fro.numpy() [17.435596 16.911535 16.7332 16.911535]\n\n # compute 2-order vector norm along last dimension.\n out_pnorm = paddle.linalg.norm(x, p=2, axis=-1)\n #out_pnorm.numpy(): [[21.118711 13.190906 5.477226]\n # [ 3.7416575 11.224972 19.131126]]\n\n # compute 2-order norm along [0,1] dimension.\n out_pnorm = paddle.linalg.norm(x, p=2, axis=[0,1])\n #out_pnorm.numpy(): [17.435596 16.911535 16.7332 16.911535]\n\n # compute inf-order norm\n out_pnorm = paddle.linalg.norm(x, p=np.inf)\n #out_pnorm.numpy() = [12.]\n out_pnorm = paddle.linalg.norm(x, p=np.inf, axis=0)\n #out_pnorm.numpy(): [[12. 11. 10. 9.] [8. 7. 6. 7.] [8. 9. 10. 11.]]\n\n # compute -inf-order norm\n out_pnorm = paddle.linalg.norm(x, p=-np.inf)\n #out_pnorm.numpy(): [0.]\n out_pnorm = paddle.linalg.norm(x, p=-np.inf, axis=0)\n #out_pnorm.numpy(): [[0. 1. 2. 3.] [4. 5. 6. 5.] [4. 3. 2. 1.]]\n \"\"\"\n\n def frobenius_norm(input, dim=None, keepdim=False, name=None):\n \"\"\"\n The frobenius norm OP is to calculate the frobenius norm of certain two dimensions of Tensor `input`.\n Args:\n input (Variable): Tensor, data type float32, float64.\n dim (list, optional): None for last two dimensions.\n keepdim (bool, optional): Whether keep the dimensions as the `input`, Default False.\n \"\"\"\n if dim is not None and not (isinstance(dim, list) and len(dim) == 2):\n raise ValueError(\n \"The dim of frobenius norm op should be None or two elements list!\"\n )\n if paddle.in_dynamic_mode():\n if dim is None:\n return _C_ops.frobenius_norm(input, 'keep_dim', keepdim,\n 'reduce_all', True)\n return _C_ops.frobenius_norm(input, 'dim', dim, 'keep_dim', keepdim,\n 'reduce_all', False)\n attrs = {'dim': dim, 'keep_dim': keepdim, 'reduce_all': False}\n if dim is None:\n attrs['reduce_all'] = True\n check_variable_and_dtype(input, 'input', ['float32', 'float64'],\n 'frobenius_norm')\n\n helper = LayerHelper('frobenius_norm', **locals())\n out = helper.create_variable_for_type_inference(\n dtype=helper.input_dtype())\n\n helper.append_op(\n type='frobenius_norm',\n inputs={'X': input},\n outputs={'Out': out},\n attrs=attrs)\n return out\n\n def vector_norm(input,\n porder=None,\n axis=None,\n keepdim=False,\n asvector=False,\n name=None):\n \"\"\"\n Calculate the p-order vector norm for certain dimension of Tensor `input`.\n Args:\n input (Variable): Tensor, data type float32, float64.\n porder (float, optional): None for porder=2.0.\n axis (int, optional): None for last dimension.\n keepdim (bool, optional): Whether keep the dimensions as the `input`, Default False.\n \"\"\"\n if paddle.in_dynamic_mode():\n if axis is None: axis = -1\n return _C_ops.p_norm(input, 'porder', porder, 'axis', axis,\n 'keepdim', keepdim, 'asvector', asvector)\n if porder is not None:\n check_type(porder, 'porder', (float, int), 'p_norm')\n if axis is not None:\n check_type(axis, 'axis', (int), 'p_norm')\n check_variable_and_dtype(input, 'input', ['float32', 'float64'],\n 'p_norm')\n\n attrs = {\n 'axis': axis if axis is not None else -1,\n 'porder': float(porder) if porder is not None else 2.0,\n 'keepdim': keepdim,\n 'asvector': asvector,\n 'epsilon': 1e-12,\n }\n helper = LayerHelper('p_norm', **locals())\n out = helper.create_variable_for_type_inference(\n dtype=helper.input_dtype())\n\n helper.append_op(\n type='p_norm',\n inputs={'X': input},\n outputs={'Out': out},\n attrs=attrs)\n return out\n\n def inf_norm(input,\n porder=None,\n axis=axis,\n keepdim=False,\n asvector=False,\n name=None):\n helper = LayerHelper('frobenius_norm', **locals())\n out = helper.create_variable_for_type_inference(\n dtype=helper.input_dtype())\n helper.append_op(type='abs', inputs={'X': input}, outputs={'Out': out})\n reduce_out = helper.create_variable_for_type_inference(\n dtype=helper.input_dtype())\n\n reduce_all = True if axis == None or axis == [] or asvector == True else False\n axis = axis if axis != None and axis != [] else [0]\n\n reduce_type = 'reduce_max' if porder == np.float(\n 'inf') else 'reduce_min'\n helper.append_op(\n type=reduce_type,\n inputs={'X': out},\n outputs={'Out': reduce_out},\n attrs={'dim': axis,\n 'keep_dim': keepdim,\n 'reduce_all': reduce_all})\n\n return reduce_out\n\n def p_matrix_norm(input, porder=1., axis=axis, keepdim=False, name=None):\n \"\"\"\n NOTE:\n This function actually treats the matrix as flattened vector to calculate vector norm instead of matrix norm.\n \"\"\"\n block = LayerHelper('norm', **locals())\n out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n abs_out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n block.append_op(\n type='abs', inputs={'X': input}, outputs={'Out': abs_out})\n pow_out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n\n block.append_op(\n type='pow',\n inputs={'X': abs_out},\n outputs={'Out': pow_out},\n attrs={'factor': porder})\n sum_out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n block.append_op(\n type='reduce_sum',\n inputs={'X': pow_out},\n outputs={'Out': sum_out},\n attrs={\n 'dim': axis,\n 'keep_dim': keepdim,\n 'reduce_all': True if axis is None else False\n })\n porder\n block.append_op(\n type='pow',\n inputs={'X': sum_out},\n outputs={'Out': out},\n attrs={'factor': float(1. / porder)})\n return out\n\n if axis is None and p is not None:\n if isinstance(p, str):\n if p == \"fro\":\n return frobenius_norm(x, dim=axis, keepdim=keepdim, name=name)\n else:\n raise ValueError(\n \"only valid string values are 'fro', found {}\".format(p))\n elif isinstance(p, (int, float)):\n return vector_norm(\n x,\n porder=p,\n axis=axis,\n keepdim=keepdim,\n asvector=True,\n name=name)\n else:\n raise ValueError(\"only valid p type is string or float, found {}\".\n format(type(p)))\n\n if isinstance(axis, tuple):\n axis = list(axis)\n if isinstance(axis, list) and len(axis) == 1:\n axis = axis[0]\n\n #calculate vector norm, where axis is int or list with only one integer\n if isinstance(axis, int):\n if isinstance(p, str):\n if p == \"fro\":\n return vector_norm(\n x,\n porder=2,\n axis=axis,\n keepdim=keepdim,\n asvector=False,\n name=name)\n\n else:\n raise ValueError(\n \"only valid string values are 'fro', found {}\".format(p))\n elif isinstance(p, (int, float)):\n return vector_norm(\n x,\n axis=axis,\n porder=p,\n keepdim=keepdim,\n asvector=False,\n name=name)\n else:\n raise ValueError(\n \"unspport p for p-order vector norm. except float, found {}\".\n format(p))\n #calculate matrix norm, where axis is list with two integers\n elif isinstance(axis, list) and len(axis) == 2:\n if p == \"fro\":\n return frobenius_norm(x, dim=axis, keepdim=keepdim, name=name)\n elif p == np.inf or p == -np.inf:\n return inf_norm(x, porder=p, axis=axis, keepdim=keepdim, name=name)\n elif p == 0:\n raise ValueError(\n \"just suport axis type int or list (length of list <=1) if p = 0, found {}\".\n format(axis))\n else:\n return p_matrix_norm(\n x, porder=p, axis=axis, keepdim=keepdim, name=name)\n else:\n raise ValueError(\n \"except axis type int or list (length of list <=2), found {}\".\n format(axis))\n\n\ndef dist(x, y, p=2, name=None):\n r\"\"\"\n\n This OP returns the p-norm of (x - y). It is not a norm in a strict sense, only as a measure\n of distance. The shapes of x and y must be broadcastable. The definition is as follows, for\n details, please refer to the `numpy's broadcasting <https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>`_:\n\n - Each input has at least one dimension.\n - Match the two input dimensions from back to front, the dimension sizes must either be equal, one of them is 1, or one of them does not exist.\n\n Where, z = x - y, the shapes of x and y are broadcastable, then the shape of z can be\n obtained as follows:\n\n 1. If the number of dimensions of x and y are not equal, prepend 1 to the dimensions of the\n tensor with fewer dimensions.\n\n For example, The shape of x is [8, 1, 6, 1], the shape of y is [7, 1, 5], prepend 1 to the\n dimension of y.\n\n x (4-D Tensor): 8 x 1 x 6 x 1\n\n y (4-D Tensor): 1 x 7 x 1 x 5\n\n 2. Determine the size of each dimension of the output z: choose the maximum value from the\n two input dimensions.\n\n z (4-D Tensor): 8 x 7 x 6 x 5\n\n If the number of dimensions of the two inputs are the same, the size of the output can be\n directly determined in step 2. When p takes different values, the norm formula is as follows:\n\n When p = 0, defining $0^0=0$, the zero-norm of z is simply the number of non-zero elements of z.\n\n .. math::\n\n ||z||_{0}=\\lim_{p \\\\rightarrow 0}\\sum_{i=1}^{m}|z_i|^{p}\n\n When p = inf, the inf-norm of z is the maximum element of z.\n\n .. math::\n\n ||z||_\\infty=\\max_i |z_i|\n\n When p = -inf, the negative-inf-norm of z is the minimum element of z.\n\n .. math::\n\n ||z||_{-\\infty}=\\min_i |z_i|\n\n Otherwise, the p-norm of z follows the formula,\n\n .. math::\n\n ||z||_{p}=(\\sum_{i=1}^{m}|z_i|^p)^{\\\\frac{1}{p}}\n\n Args:\n x (Tensor): 1-D to 6-D Tensor, its data type is float32 or float64.\n y (Tensor): 1-D to 6-D Tensor, its data type is float32 or float64.\n p (float, optional): The norm to be computed, its data type is float32 or float64. Default: 2.\n\n Returns:\n Tensor: Tensor that is the p-norm of (x - y).\n\n Examples:\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n x = paddle.to_tensor(np.array([[3, 3],[3, 3]]), \"float32\")\n y = paddle.to_tensor(np.array([[3, 3],[3, 1]]), \"float32\")\n out = paddle.dist(x, y, 0)\n print(out) # out = [1.]\n\n out = paddle.dist(x, y, 2)\n print(out) # out = [2.]\n\n out = paddle.dist(x, y, float(\"inf\"))\n print(out) # out = [2.]\n\n out = paddle.dist(x, y, float(\"-inf\"))\n print(out) # out = [0.]\n \"\"\"\n check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'dist')\n check_variable_and_dtype(y, 'dtype', ['float32', 'float64'], 'dist')\n check_type(p, 'p', (float, int), 'dist')\n helper = LayerHelper(\"dist\", **locals())\n out = helper.create_variable_for_type_inference(x.dtype)\n\n inputs = {\"X\": [x], \"Y\": [y]}\n outputs = {'Out': [out]}\n attrs = {\"p\": float(p)}\n helper.append_op(\n type='dist', inputs=inputs, outputs={'Out': out}, attrs=attrs)\n return out\n\n\ndef cond(x, p=None, name=None):\n \"\"\"\n\n Computes the condition number of a matrix or batches of matrices with respect to a matrix norm ``p``.\n\n Args:\n x (Tensor): The input tensor could be tensor of shape ``(*, m, n)`` where ``*`` is zero or more batch dimensions\n for ``p`` in ``(2, -2)``, or of shape ``(*, n, n)`` where every matrix is invertible for any supported ``p``.\n And the input data type could be ``float32`` or ``float64``.\n p (float|string, optional): Order of the norm. Supported values are `fro`, `nuc`, `1`, `-1`, `2`, `-2`,\n `inf`, `-inf`. Default value is `None`, meaning that the order of the norm is `2`.\n name (str, optional): The default value is `None`. Normally there is no need for\n user to set this property. For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: computing results of condition number, its data type is the same as input Tensor ``x``.\n\n Examples:\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n x = paddle.to_tensor([[1., 0, -1], [0, 1, 0], [1, 0, 1]])\n\n # compute conditional number when p is None\n out = paddle.linalg.cond(x)\n # out.numpy() [1.4142135]\n\n # compute conditional number when order of the norm is 'fro'\n out_fro = paddle.linalg.cond(x, p='fro')\n # out_fro.numpy() [3.1622777]\n\n # compute conditional number when order of the norm is 'nuc'\n out_nuc = paddle.linalg.cond(x, p='nuc')\n # out_nuc.numpy() [9.2426405]\n\n # compute conditional number when order of the norm is 1\n out_1 = paddle.linalg.cond(x, p=1)\n # out_1.numpy() [2.]\n\n # compute conditional number when order of the norm is -1\n out_minus_1 = paddle.linalg.cond(x, p=-1)\n # out_minus_1.numpy() [1.]\n\n # compute conditional number when order of the norm is 2\n out_2 = paddle.linalg.cond(x, p=2)\n # out_2.numpy() [1.4142135]\n\n # compute conditional number when order of the norm is -1\n out_minus_2 = paddle.linalg.cond(x, p=-2)\n # out_minus_2.numpy() [0.70710677]\n\n # compute conditional number when order of the norm is inf\n out_inf = paddle.linalg.cond(x, p=np.inf)\n # out_inf.numpy() [2.]\n\n # compute conditional number when order of the norm is -inf\n out_minus_inf = paddle.linalg.cond(x, p=-np.inf)\n # out_minus_inf.numpy() [1.]\n\n a = paddle.to_tensor(np.random.randn(2, 4, 4).astype('float32'))\n # a.numpy()\n # [[[ 0.14063153 -0.996288 0.7996131 -0.02571543]\n # [-0.16303636 1.5534962 -0.49919784 -0.04402903]\n # [-1.1341571 -0.6022629 0.5445269 0.29154757]\n # [-0.16816919 -0.30972657 1.7521842 -0.5402487 ]]\n # [[-0.58081484 0.12402827 0.7229862 -0.55046535]\n # [-0.15178485 -1.1604939 0.75810957 0.30971205]\n # [-0.9669573 1.0940945 -0.27363303 -0.35416734]\n # [-1.216529 2.0018666 -0.7773689 -0.17556527]]]\n a_cond_fro = paddle.linalg.cond(a, p='fro')\n # a_cond_fro.numpy() [31.572273 28.120834]\n\n b = paddle.to_tensor(np.random.randn(2, 3, 4).astype('float64'))\n # b.numpy()\n # [[[ 1.61707487 0.46829144 0.38130416 0.82546736]\n # [-1.72710298 0.08866375 -0.62518804 0.16128892]\n # [-0.02822879 -1.67764516 0.11141444 0.3220113 ]]\n # [[ 0.22524372 0.62474921 -0.85503233 -1.03960523]\n # [-0.76620689 0.56673047 0.85064753 -0.45158196]\n # [ 1.47595418 2.23646462 1.5701758 0.10497519]]]\n b_cond_2 = paddle.linalg.cond(b, p=2)\n # b_cond_2.numpy() [3.30064451 2.51976252]\n\n \"\"\"\n\n def mat_norm(input, porder=1., axis=None):\n \"\"\"\n NOTE:\n Calculate the matrix norm of a square matrix or batches of square matrices,\n when porder is in (1, -1, inf, -inf)\n \"\"\"\n reduce_all = True if axis is None or axis == [] else False\n axis = axis if axis != None and axis != [] else [0]\n keepdim = False\n\n if paddle.in_dynamic_mode():\n abs_out = _C_ops.abs(input)\n sum_out = _C_ops.reduce_sum(abs_out, 'dim', axis, 'keepdim',\n keepdim, 'reduce_all', reduce_all)\n if porder == 1 or porder == np.inf:\n return _C_ops.reduce_max(sum_out, 'dim', [-1], 'keepdim',\n keepdim, 'reduce_all', reduce_all)\n if porder == -1 or porder == -np.inf:\n return _C_ops.reduce_min(sum_out, 'dim', [-1], 'keepdim',\n keepdim, 'reduce_all', reduce_all)\n\n block = LayerHelper('norm', **locals())\n abs_out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n sum_out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n block.append_op(\n type='abs', inputs={'X': input}, outputs={'Out': abs_out})\n block.append_op(\n type='reduce_sum',\n inputs={'X': abs_out},\n outputs={'Out': sum_out},\n attrs={'dim': axis,\n 'keep_dim': keepdim,\n 'reduce_all': reduce_all})\n if porder == 1 or porder == np.inf:\n block.append_op(\n type='reduce_max',\n inputs={'X': sum_out},\n outputs={'Out': out},\n attrs={\n 'dim': [-1],\n 'keep_dim': keepdim,\n 'reduce_all': reduce_all\n })\n if porder == -1 or porder == -np.inf:\n block.append_op(\n type='reduce_min',\n inputs={'X': sum_out},\n outputs={'Out': out},\n attrs={\n 'dim': [-1],\n 'keep_dim': keepdim,\n 'reduce_all': reduce_all\n })\n return out\n\n def fro_norm(input, porder=2, axis=[-1]):\n \"\"\"\n NOTE:\n Calculate the frobenius norm of a square matrix or batches of square matrices.\n \"\"\"\n reduce_all = True if axis is None or axis == [] else False\n keepdim = False\n\n if paddle.in_dynamic_mode():\n pow_out = _C_ops.pow(input, 'factor', porder)\n sum_out_1 = _C_ops.reduce_sum(pow_out, 'dim', axis, 'keepdim',\n keepdim, 'reduce_all', reduce_all)\n sum_out_2 = _C_ops.reduce_sum(sum_out_1, 'dim', axis, 'keepdim',\n keepdim, 'reduce_all', reduce_all)\n return _C_ops.pow(sum_out_2, 'factor', float(1. / porder))\n\n block = LayerHelper('norm', **locals())\n pow_out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n sum_out_1 = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n sum_out_2 = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n block.append_op(\n type='pow',\n inputs={'X': input},\n outputs={'Out': pow_out},\n attrs={'factor': porder})\n block.append_op(\n type='reduce_sum',\n inputs={'X': pow_out},\n outputs={'Out': sum_out_1},\n attrs={'dim': axis,\n 'keep_dim': keepdim,\n 'reduce_all': reduce_all})\n block.append_op(\n type='reduce_sum',\n inputs={'X': sum_out_1},\n outputs={'Out': sum_out_2},\n attrs={'dim': axis,\n 'keep_dim': keepdim,\n 'reduce_all': reduce_all})\n block.append_op(\n type='pow',\n inputs={'X': sum_out_2},\n outputs={'Out': out},\n attrs={'factor': float(1. / porder)})\n return out\n\n def svd_norm(input, porder, axis=[-1]):\n \"\"\"\n NOTE:\n Calculate the matrix norm, which is related to singular values, of a matrix\n or batches of matrices, including nuclear norm, 2-norm and (-2)-norm.\n \"\"\"\n reduce_all = True if axis is None or axis == [] else False\n keepdim = False\n\n u, s, vh = svd(input, full_matrices=False)\n\n if paddle.in_dynamic_mode():\n if porder == \"nuc\":\n return _C_ops.reduce_sum(s, 'dim', axis, 'keepdim', keepdim,\n 'reduce_all', reduce_all)\n max_out = _C_ops.reduce_max(s, 'dim', axis, 'keepdim', keepdim,\n 'reduce_all', reduce_all)\n min_out = _C_ops.reduce_min(s, 'dim', axis, 'keepdim', keepdim,\n 'reduce_all', reduce_all)\n if porder == 2:\n return _C_ops.elementwise_div(max_out, min_out, 'aixs', axis,\n 'use_mkldnn', False)\n if porder == -2:\n return _C_ops.elementwise_div(min_out, max_out, 'aixs', axis,\n 'use_mkldnn', False)\n\n block = LayerHelper('norm', **locals())\n out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n if porder == \"nuc\":\n block.append_op(\n type='reduce_sum',\n inputs={'X': s},\n outputs={'Out': out},\n attrs={\n 'dim': axis,\n 'keep_dim': keepdim,\n 'reduce_all': reduce_all\n })\n return out\n max_out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n min_out = block.create_variable_for_type_inference(\n dtype=block.input_dtype())\n block.append_op(\n type='reduce_max',\n inputs={'X': s},\n outputs={'Out': max_out},\n attrs={'dim': axis,\n 'keep_dim': keepdim,\n 'reduce_all': reduce_all})\n block.append_op(\n type='reduce_min',\n inputs={'X': s},\n outputs={'Out': min_out},\n attrs={'dim': axis,\n 'keep_dim': keepdim,\n 'reduce_all': reduce_all})\n if porder == 2:\n block.append_op(\n type='elementwise_div',\n inputs={'X': max_out,\n 'Y': min_out},\n outputs={'Out': out},\n attrs={'aixs': axis,\n 'use_mkldnn': False})\n return out\n if porder == -2:\n block.append_op(\n type='elementwise_div',\n inputs={'X': min_out,\n 'Y': max_out},\n outputs={'Out': out},\n attrs={'aixs': axis,\n 'use_mkldnn': False})\n return out\n\n def empty_tensor(input, shape):\n if paddle.in_dynamic_mode():\n return input.reshape(shape)\n raise ValueError(\"only support x is nonempty tensor in static mode\")\n\n x_shape = list(x.shape)\n if not len(x_shape) >= 2:\n raise ValueError(\"input should be a matrix or batches of matrices, \" +\n \"but the dimention of received input is {}\".format(\n len(x_shape)))\n if p == None:\n p = 2\n x_size = 0 if (0 in x_shape) else 1\n if p in (\"fro\", \"nuc\", 1, -1, np.inf, -np.inf):\n if x_shape[len(x_shape) - 1] == x_shape[len(x_shape) - 2]:\n if x_size == 0:\n return empty_tensor(x, x_shape[:-2])\n x_inv = x.inverse()\n if p == \"fro\":\n return fro_norm(x) * fro_norm(x_inv)\n if p == \"nuc\":\n return svd_norm(x, p) * svd_norm(x_inv, p)\n if p in (1, -1):\n return mat_norm(\n x, porder=p, axis=[-2]) * mat_norm(\n x_inv, porder=p, axis=[-2])\n if p in (np.inf, -np.inf):\n return mat_norm(\n x, porder=p, axis=[-1]) * mat_norm(\n x_inv, porder=p, axis=[-1])\n else:\n raise ValueError(\"only support p is {} when input is a \".format(p) +\n \"square matrix or batches of square matrices\")\n elif p in (2, -2):\n if x_size == 0:\n return empty_tensor(x, x_shape[:-2])\n return svd_norm(x, porder=p)\n else:\n raise ValueError(\n \"unsupported {} for p, only supporting ('fro', 'nuc', \".format(\n p) + \"1, -1, 2, -2, inf, -inf) or none\")\n\n\ndef dot(x, y, name=None):\n \"\"\"\n This operator calculates inner product for vectors.\n\n .. note::\n Support 1-d and 2-d Tensor. When it is 2d, the first dimension of this matrix\n is the batch dimension, which means that the vectors of multiple batches are dotted.\n\n Parameters:\n x(Tensor): 1-D or 2-D ``Tensor``. Its dtype should be ``float32``, ``float64``, ``int32``, ``int64``\n y(Tensor): 1-D or 2-D ``Tensor``. Its dtype soulde be ``float32``, ``float64``, ``int32``, ``int64``\n name(str, optional): Name of the output. Default is None. It's used to print debug info for developers. Details: :ref:`api_guide_Name`\n\n Returns:\n Tensor: the calculated result Tensor.\n\n Examples:\n\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n x_data = np.random.uniform(0.1, 1, [10]).astype(np.float32)\n y_data = np.random.uniform(1, 3, [10]).astype(np.float32)\n x = paddle.to_tensor(x_data)\n y = paddle.to_tensor(y_data)\n z = paddle.dot(x, y)\n print(z)\n\n \"\"\"\n op_type = 'dot'\n # skip var type check in dygraph mode to improve efficiency\n if paddle.in_dynamic_mode():\n op = getattr(_C_ops, op_type)\n return op(x, y)\n\n assert x is not None, 'x cannot be None in {}'.format(op_type)\n assert y is not None, 'y cannot be None in {}'.format(op_type)\n\n check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'],\n op_type)\n check_variable_and_dtype(y, 'y', ['float32', 'float64', 'int32', 'int64'],\n op_type)\n\n helper = LayerHelper(op_type, **locals())\n if name is None:\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n else:\n out = helper.create_variable(\n name=name, dtype=x.dtype, persistable=False)\n helper.append_op(\n type=\"dot\", inputs={'X': x,\n 'Y': y}, attrs={}, outputs={\"Out\": out})\n return out\n\n\ndef cov(x, rowvar=True, ddof=True, fweights=None, aweights=None, name=None):\n \"\"\"\n Estimate the covariance matrix of the input variables, given data and weights.\n\n A covariance matrix is a square matrix, indicate the covariance of each pair variables in the input matrix.\n For example, for an N-dimensional samples X=[x1,x2,…xN]T, then the covariance matrix \n element Cij is the covariance of xi and xj. The element Cii is the variance of xi itself.\n\n Parameters:\n x(Tensor): A N-D(N<=2) Tensor containing multiple variables and observations. By default, each row of x represents a variable. Also see rowvar below.\n rowvar(Bool, optional): If rowvar is True (default), then each row represents a variable, with observations in the columns. Default: True\n ddof(Bool, optional): If ddof=True will return the unbiased estimate, and ddof=False will return the simple average. Default: True\n fweights(Tensor, optional): 1-D Tensor of integer frequency weights; The number of times each observation vector should be repeated. Default: None\n aweights(Tensor, optional): 1-D Tensor of observation vector weights. How important of the observation vector, larger data means this element is more important. Default: None\n name(str, optional): Name of the output. Default is None. It's used to print debug info for developers. Details: :ref:`api_guide_Name`\n\n Returns:\n Tensor: The covariance matrix Tensor of the variables.\n\n Examples:\n\n .. code-block:: python\n\n import paddle\n\n xt = paddle.rand((3,4))\n paddle.linalg.cov(xt)\n\n '''\n Tensor(shape=[3, 3], dtype=float64, place=CUDAPlace(0), stop_gradient=True,\n [[0.07918842, 0.06127326, 0.01493049],\n [0.06127326, 0.06166256, 0.00302668],\n [0.01493049, 0.00302668, 0.01632146]])\n '''\n \"\"\"\n op_type = 'cov'\n if len(x.shape) > 2 or len(x.shape) < 1:\n raise ValueError(\n \"Input(x) only support N-D (1<=N<=2) tensor in cov, but received \"\n \"length of Input(input) is %s.\" % len(x.shape))\n check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'cov')\n nx = x\n if len(x.shape) == 1:\n nx = x.reshape((1, -1))\n if not rowvar and nx.shape[0] != 1:\n nx = nx.t()\n w = None\n observation_num = nx.shape[1]\n if fweights is not None:\n w = fweights.astype(nx.dtype)\n if len(w.shape) > 1:\n raise ValueError(\n \"Input(fweights) only support N-D (N<=1) tensor in cov, but received \"\n \"shape of Input(input) is %s.\" % len(fweights.shape))\n if fweights.shape[0] != observation_num:\n raise ValueError(\n \"The number of Input(fweights) should equal to x's dim[1]: {}, but received \"\n \"size of Input(fweights) is {}.\".format(observation_num,\n fweights.shape[0]))\n if fweights.min() < 0:\n raise ValueError(\n \"The value of Input(fweights) cannot be negtive, but received \"\n \"min of Input(fweights) is {}.\".format(fweights.min()))\n if not paddle.all(fweights == paddle.round(fweights.astype('float64'))):\n raise ValueError(\"Input(fweights) must be integer \")\n\n if aweights is not None:\n aw = aweights.astype(nx.dtype)\n if len(aw.shape) > 1:\n raise ValueError(\n \"Input(aweights) only support N-D (N<=1) tensor in cov, but received \"\n \"length of Input(input) is %s.\" % len(aweights.shape))\n check_variable_and_dtype(aweights, 'dtype', ['float32', 'float64'],\n 'cov')\n if aweights.shape[0] != observation_num:\n raise ValueError(\n \"The number of Input(aweights) should equal to x's dim[1]: {}, but received \"\n \"size of Input(aweights) is {}.\".format(observation_num,\n aweights.shape[0]))\n if aweights.min() < 0:\n raise ValueError(\n \"The value of Input(aweights) cannot be negtive, but received \"\n \"min of Input(aweights) is {}.\".format(aweights.min()))\n if w is not None:\n w = w * aw\n else:\n w = aw\n\n w_sum = paddle.to_tensor(observation_num, dtype=nx.dtype)\n if fweights is not None or aweights is not None:\n w_sum = w.sum()\n if w_sum.item() == 0:\n raise ValueError(\"The sum of weights is zero, can't be normalized.\")\n\n if w is not None:\n nx_w = nx * w\n avg = (nx_w).sum(axis=1) / w_sum\n else:\n avg = nx.sum(axis=1) / w_sum\n nx_w = nx\n\n if w is not None and aweights is not None and ddof == True:\n norm_factor = w_sum - (w * aweights).sum() / w_sum\n else:\n norm_factor = w_sum - ddof\n if norm_factor <= 0:\n norm_factor = paddle.to_tensor(0, dtype=nx.dtype)\n nx = nx - avg.unsqueeze(1)\n xxt = paddle.mm(nx, nx_w.t().conj())\n cov = paddle.divide(xxt, norm_factor).squeeze()\n return cov\n\n\ndef t(input, name=None):\n \"\"\"\n Transpose <=2-D tensor.\n 0-D and 1-D tensors are returned as it is and 2-D tensor is equal to\n the paddle.transpose function which perm dimensions set 0 and 1.\n\n Args:\n input (Tensor): The input Tensor. It is a N-D (N<=2) Tensor of data types float16, float32, float64, int32.\n name(str, optional): The default value is None. Normally there is no need for\n user to set this property. For more information, please refer to :ref:`api_guide_Name`\n Returns:\n Tensor: A transposed n-D Tensor, with data type being float16, float32, float64, int32, int64.\n\n For Example:\n\n .. code-block:: text\n\n # Example 1 (0-D tensor)\n x = tensor([0.79])\n paddle.t(x) = tensor([0.79])\n\n # Example 2 (1-D tensor)\n x = tensor([0.79, 0.84, 0.32])\n paddle.t(x) = tensor([0.79, 0.84, 0.32])\n\n # Example 3 (2-D tensor)\n x = tensor([0.79, 0.84, 0.32],\n [0.64, 0.14, 0.57])\n paddle.t(x) = tensor([0.79, 0.64],\n [0.84, 0.14],\n [0.32, 0.57])\n\n Examples:\n\n .. code-block:: python\n\n import paddle\n x = paddle.ones(shape=[2, 3], dtype='int32')\n x_transposed = paddle.t(x)\n print(x_transposed.shape)\n # [3, 2]\n \"\"\"\n if len(input.shape) > 2:\n raise ValueError(\n \"Input(input) only support N-D (N<=2) tensor, but received \"\n \"length of Input(input) is %s. Perhaps you can use paddle.\"\n \"tensor.transpose() instead.\" % len(input.shape))\n if paddle.in_dynamic_mode():\n if len(input.shape) == 1:\n return input\n # 2-D tensor\n perm = [1, 0]\n out, _ = _C_ops.transpose2(input, 'axis', perm)\n return out\n\n check_variable_and_dtype(\n input, 'input', ['float16', 'float32', 'float64', 'int32',\n 'int64'], 'transpose')\n\n helper = LayerHelper('t', **locals())\n out = helper.create_variable_for_type_inference(input.dtype)\n input_shape = helper.create_variable_for_type_inference(input.dtype)\n if len(input.shape) == 1:\n out = input\n else:\n helper.append_op(\n type='transpose2',\n inputs={'X': [input]},\n outputs={'Out': [out],\n 'XShape': [input_shape]},\n attrs={'axis': [1, 0]})\n return out\n\n\ndef cross(x, y, axis=None, name=None):\n \"\"\"\n Computes the cross product between two tensors along an axis.\n\n Inputs must have the same shape, and the length of their axes should be equal to 3.\n If `axis` is not given, it defaults to the first axis found with the length 3.\n\n Args:\n x (Tensor): The first input tensor.\n y (Tensor): The second input tensor.\n axis (int, optional): The axis along which to compute the cross product. It defaults to the first axis found with the length 3.\n name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor. A Tensor with same data type as `x`.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.to_tensor([[1.0, 1.0, 1.0],\n [2.0, 2.0, 2.0],\n [3.0, 3.0, 3.0]])\n y = paddle.to_tensor([[1.0, 1.0, 1.0],\n [1.0, 1.0, 1.0],\n [1.0, 1.0, 1.0]])\n\n z1 = paddle.cross(x, y)\n # [[-1. -1. -1.]\n # [ 2. 2. 2.]\n # [-1. -1. -1.]]\n\n z2 = paddle.cross(x, y, axis=1)\n # [[0. 0. 0.]\n # [0. 0. 0.]\n # [0. 0. 0.]]\n \"\"\"\n if in_dygraph_mode():\n return _C_ops.final_state_cross(x, y, axis)\n else:\n if _in_legacy_dygraph():\n if axis is not None:\n return _C_ops.cross(x, y, 'dim', axis)\n else:\n return _C_ops.cross(x, y)\n else:\n helper = LayerHelper(\"cross\", **locals())\n out = helper.create_variable_for_type_inference(x.dtype)\n attrs = dict()\n attrs['dim'] = axis\n\n helper.append_op(\n type='cross',\n inputs={'X': x,\n 'Y': y},\n outputs={'Out': out},\n attrs=attrs)\n return out\n\n\ndef cholesky(x, upper=False, name=None):\n r\"\"\"\n Computes the Cholesky decomposition of one symmetric positive-definite\n matrix or batches of symmetric positive-definite matrice.\n\n If `upper` is `True`, the decomposition has the form :math:`A = U^{T}U` ,\n and the returned matrix :math:`U` is upper-triangular. Otherwise, the\n decomposition has the form :math:`A = LL^{T}` , and the returned matrix\n :math:`L` is lower-triangular.\n\n Args:\n x (Tensor): The input tensor. Its shape should be `[*, M, M]`,\n where * is zero or more batch dimensions, and matrices on the\n inner-most 2 dimensions all should be symmetric positive-definite.\n Its data type should be float32 or float64.\n upper (bool): The flag indicating whether to return upper or lower\n triangular matrices. Default: False.\n\n Returns:\n Tensor: A Tensor with same shape and data type as `x`. It represents \\\n triangular matrices generated by Cholesky decomposition.\n\n Examples:\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n a = np.random.rand(3, 3)\n a_t = np.transpose(a, [1, 0])\n x_data = np.matmul(a, a_t) + 1e-03\n x = paddle.to_tensor(x_data)\n out = paddle.linalg.cholesky(x, upper=False)\n print(out)\n # [[1.190523 0. 0. ]\n # [0.9906703 0.27676893 0. ]\n # [1.25450498 0.05600871 0.06400121]]\n\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.cholesky(x, \"upper\", upper)\n check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'cholesky')\n check_type(upper, 'upper', bool, 'cholesky')\n helper = LayerHelper('cholesky', **locals())\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n helper.append_op(\n type='cholesky',\n inputs={'X': [x]},\n outputs={'Out': out},\n attrs={'upper': upper})\n return out\n\n\ndef matrix_rank(x, tol=None, hermitian=False, name=None):\n r\"\"\"\n Computes the rank of a matrix.\n\n The rank of a matrix is the number of singular values that are greater than the specified `tol` threshold when hermitian=False,\n or the number of eigenvalues in absolute value that are greater than the specified `tol` threshold when hermitian=True.\n\n Args:\n x (Tensor): The input tensor. Its shape should be `[..., m, n]`, where `...` is zero or more batch dimensions. If `x` is a batch\n of matrices then the output has the same batch dimensions. The data type of `x` should be float32 or float64.\n tol (float,Tensor,optional): the tolerance value. Default: None. If `tol` is not specified, and `sigma` is the largest\n singular value (or eigenvalues in absolute value), and `eps` is the epsilon value for the dtype of `x`, then `tol` is computed\n with formula `tol=sigma * max(m,n) * eps`. Note that if `x` is a batch of matrices, `tol` is computed this way for every batch.\n hermitian (bool,optional): indicates whether `x` is Hermitian. Default: False. When hermitian=True, `x` is assumed to be Hermitian,\n enabling a more efficient method for finding eigenvalues, but `x` is not checked inside the function. Instead, We just use\n the lower triangular of the matrix to compute.\n name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: Rank of tensor x.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n a = paddle.eye(10)\n b = paddle.linalg.matrix_rank(a)\n print(b)\n # b = [10]\n\n c = paddle.ones(shape=[3, 4, 5, 5])\n d = paddle.linalg.matrix_rank(c, tol=0.01, hermitian=True)\n print(d)\n # d = [[1, 1, 1, 1],\n # [1, 1, 1, 1],\n # [1, 1, 1, 1]]\n\n \"\"\"\n\n if paddle.in_dynamic_mode():\n if tol is None:\n tol_tensor = None\n tol_attr = 0.0\n use_default_tol = True\n elif isinstance(tol, Variable):\n if tol.dtype != x.dtype:\n tol_tensor = cast(tol, x.dtype)\n else:\n tol_tensor = tol\n tol_attr = 0.0\n use_default_tol = False\n else:\n tol_tensor = None\n tol_attr = float(tol)\n use_default_tol = False\n return _C_ops.matrix_rank(x, tol_tensor, \"tol\", tol_attr, 'hermitian',\n hermitian, 'use_default_tol', use_default_tol)\n\n inputs = {}\n attrs = {}\n check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'matrix_rank')\n inputs['X'] = x\n if tol is None:\n attrs['use_default_tol'] = True\n elif isinstance(tol, Variable):\n check_variable_and_dtype(tol, 'tol', ['float32'], 'matrix_rank')\n attrs['use_default_tol'] = False\n if tol.dtype != x.dtype:\n inputs['TolTensor'] = cast(tol, x.dtype)\n else:\n inputs['TolTensor'] = tol\n else:\n check_type(tol, 'tol', float, 'matrix_rank')\n attrs['use_default_tol'] = False\n attrs['tol'] = tol\n check_type(hermitian, 'hermitian', bool, 'matrix_rank')\n attrs['hermitian'] = hermitian\n\n helper = LayerHelper('matrix_rank', **locals())\n out = helper.create_variable_for_type_inference(dtype='int32')\n helper.append_op(\n type='matrix_rank', inputs=inputs, outputs={'Out': out}, attrs=attrs)\n return out\n\n\ndef bmm(x, y, name=None):\n \"\"\"\n Applies batched matrix multiplication to two tensors.\n\n Both of the two input tensors must be three-dementional and share the same batch size.\n\n if x is a (b, m, k) tensor, y is a (b, k, n) tensor, the output will be a (b, m, n) tensor.\n\n Args:\n x (Tensor): The input Tensor.\n y (Tensor): The input Tensor.\n name(str|None): A name for this layer(optional). If set None, the layer\n will be named automatically.\n\n Returns:\n Tensor: The product Tensor.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n # In imperative mode:\n # size x: (2, 2, 3) and y: (2, 3, 2)\n x = paddle.to_tensor([[[1.0, 1.0, 1.0],\n [2.0, 2.0, 2.0]],\n [[3.0, 3.0, 3.0],\n [4.0, 4.0, 4.0]]])\n y = paddle.to_tensor([[[1.0, 1.0],[2.0, 2.0],[3.0, 3.0]],\n [[4.0, 4.0],[5.0, 5.0],[6.0, 6.0]]])\n out = paddle.bmm(x, y)\n #output size: (2, 2, 2)\n #output value:\n #[[[6.0, 6.0],[12.0, 12.0]],[[45.0, 45.0],[60.0, 60.0]]]\n out_np = out.numpy()\n\n \"\"\"\n x_shape = x.shape\n y_shape = y.shape\n if not len(x_shape) == len(y_shape) == 3:\n raise ValueError(\n \"x and y should be 3-dimensional. But received x's dimention: {}, y's dimention: {}\".\n format(x_shape, y_shape))\n if x_shape[2] != y_shape[1]:\n raise ValueError(\n \"x's width must be equal with y's height. But received x's shape: {}, y's shape: {}\".\n format(x_shape, y_shape))\n if x_shape[0] != y_shape[0]:\n raise ValueError(\n \"x's batch (shape[0]) must be equal with y's batch (shape[0]). But received x's shape: {}, y's shape: {}\".\n format(x_shape, y_shape))\n\n if paddle.in_dynamic_mode():\n return _C_ops.bmm(x, y)\n\n helper = LayerHelper('bmm', **locals())\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n helper.append_op(type='bmm', inputs={'X': x, 'Y': y}, outputs={'Out': out})\n return out\n\n\ndef histogram(input, bins=100, min=0, max=0, name=None):\n \"\"\"\n Computes the histogram of a tensor. The elements are sorted into equal width bins between min and max.\n If min and max are both zero, the minimum and maximum values of the data are used.\n\n Args:\n input (Tensor): A Tensor(or LoDTensor) with shape :math:`[N_1, N_2,..., N_k]` . The data type of the input Tensor\n should be float32, float64, int32, int64.\n bins (int): number of histogram bins\n min (int): lower end of the range (inclusive)\n max (int): upper end of the range (inclusive)\n\n Returns:\n Tensor: data type is int64, shape is (nbins,).\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n inputs = paddle.to_tensor([1, 2, 1])\n result = paddle.histogram(inputs, bins=4, min=0, max=3)\n print(result) # [0, 2, 1, 0]\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.histogram(input, \"bins\", bins, \"min\", min, \"max\", max)\n\n helper = LayerHelper('histogram', **locals())\n check_variable_and_dtype(\n input, 'X', ['int32', 'int64', 'float32', 'float64'], 'histogram')\n out = helper.create_variable_for_type_inference(VarDesc.VarType.INT64)\n helper.append_op(\n type='histogram',\n inputs={'X': input},\n outputs={'Out': out},\n attrs={'bins': bins,\n 'min': min,\n 'max': max})\n return out\n\n\ndef bincount(x, weights=None, minlength=0, name=None):\n \"\"\"\n Computes frequency of each value in the input tensor. \n\n Args:\n x (Tensor): A Tensor with non-negative integer. Should be 1-D tensor.\n weights (Tensor, optional): Weight for each value in the input tensor. Should have the same shape as input. Default is None.\n minlength (int, optional): Minimum number of bins. Should be non-negative integer. Default is 0.\n name(str, optional): The default value is None. Normally there is no need for user to set this\n property. For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: The tensor of frequency.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.to_tensor([1, 2, 1, 4, 5])\n result1 = paddle.bincount(x)\n print(result1) # [0, 2, 1, 0, 1, 1]\n\n w = paddle.to_tensor([2.1, 0.4, 0.1, 0.5, 0.5])\n result2 = paddle.bincount(x, weights=w)\n print(result2) # [0., 2.19999981, 0.40000001, 0., 0.50000000, 0.50000000]\n \"\"\"\n if x.dtype not in [paddle.int32, paddle.int64]:\n raise TypeError(\"Elements in Input(x) should all be integers\")\n\n if paddle.in_dynamic_mode():\n return _C_ops.bincount(x, weights, \"minlength\", minlength)\n\n helper = LayerHelper('bincount', **locals())\n\n check_variable_and_dtype(x, 'X', ['int32', 'int64'], 'bincount')\n\n if weights is not None:\n check_variable_and_dtype(weights, 'Weights',\n ['int32', 'int64', 'float32', 'float64'],\n 'bincount')\n out = helper.create_variable_for_type_inference(dtype=weights.dtype)\n else:\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n helper.append_op(\n type='bincount',\n inputs={'X': x,\n 'Weights': weights},\n outputs={'Out': out},\n attrs={'minlength': minlength})\n return out\n\n\ndef mv(x, vec, name=None):\n \"\"\"\n Performs a matrix-vector product of the matrix x and the vector vec.\n\n Args:\n x (Tensor): A tensor with shape :math:`[M, N]` , The data type of the input Tensor x\n should be one of float32, float64.\n vec (Tensor): A tensor with shape :math:`[N]` , The data type of the input Tensor x\n should be one of float32, float64.\n name(str, optional): The default value is None. Normally there is no need for user to set this\n property. For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: The tensor which is producted by x and vec.\n\n Examples:\n .. code-block:: python\n\n # x: [M, N], vec: [N]\n # paddle.mv(x, vec) # out: [M]\n\n import numpy as np\n import paddle\n\n x_data = np.array([[2, 1, 3], [3, 0, 1]]).astype(\"float64\")\n x = paddle.to_tensor(x_data)\n vec_data = np.array([3, 5, 1])\n vec = paddle.to_tensor(vec_data).astype(\"float64\")\n out = paddle.mv(x, vec)\n \"\"\"\n if in_dygraph_mode():\n return _C_ops.final_state_mv(x, vec)\n else:\n if _in_legacy_dygraph():\n out = _C_ops.mv(x, vec)\n return out\n else:\n\n def __check_input(x, vec):\n var_names = {'x': x, 'vec': vec}\n for name, val in var_names.items():\n check_variable_and_dtype(val, name, ['float32', 'float64'],\n 'mv')\n x_shape = list(x.shape)\n vec_shape = list(vec.shape)\n if len(x_shape) != 2:\n raise ValueError(\n \"x should be 2-dimensional. But received x's dimention: {}\".\n format(x_shape))\n if len(vec_shape) != 1:\n raise ValueError(\n \"vec should be 1-dimensional. But received vec's dimention: {}\".\n format(vec_shape))\n\n __check_input(x, vec)\n\n helper = LayerHelper('mv', **locals())\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n helper.append_op(\n type='mv', inputs={'X': x,\n 'Vec': vec}, outputs={'Out': out})\n return out\n\n\ndef det(x, name=None):\n \"\"\"\n Calculates determinant value of a square matrix or batches of square matrices.\n Args:\n x (Tensor): input (Tensor): the input matrix of size `(n, n)` or the batch of matrices of size\n `(*, n, n)` where `*` is one or more batch dimensions.\n Returns:\n y (Tensor):the determinant value of a square matrix or batches of square matrices.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.randn([3,3,3])\n\n A = paddle.linalg.det(x)\n\n print(A)\n\n # [ 0.02547996, 2.52317095, -6.15900707])\n\n\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.determinant(x)\n\n check_dtype(x.dtype, 'Input', ['float32', 'float64'], 'det')\n\n input_shape = list(x.shape)\n assert len(input_shape) >= 2, \\\n \"The x must be at least 2-dimensional, \" \\\n \"but received Input x's dimensional: %s.\\n\" % \\\n len(input_shape)\n\n assert (input_shape[-1] == input_shape[-2]), \\\n \"Expect squared input,\" \\\n \"but received %s by %s matrix.\\n\" \\\n %(input_shape[-2], input_shape[-1]) \\\n\n helper = LayerHelper('determinant', **locals())\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n helper.append_op(\n type='determinant', inputs={'Input': [x]}, outputs={'Out': [out]})\n return out\n\n\ndef slogdet(x, name=None):\n \"\"\"\n Calculates the sign and natural logarithm of the absolute value of a square matrix's or batches square matrices' determinant.\n The determinant can be computed with ``sign * exp(logabsdet)\n\n Supports input of float, double\n\n Note that for matrices that have zero determinant, this returns ``(0, -inf)``\n Args:\n x (Tensor): the batch of matrices of size :math:`(*, n, n)`\n where math:`*` is one or more batch dimensions.\n\n Returns:\n y (Tensor): A tensor containing the sign of the determinant and the natural logarithm\n of the absolute value of determinant, respectively.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.randn([3,3,3])\n\n A = paddle.linalg.slogdet(x)\n\n print(A)\n\n # [[ 1. , 1. , -1. ],\n # [-0.98610914, -0.43010661, -0.10872950]])\n\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.slogdeterminant(x)\n\n check_dtype(x.dtype, 'Input', ['float32', 'float64'], 'slogdet')\n\n input_shape = list(x.shape)\n assert len(input_shape) >= 2, \\\n \"The x must be at least 2-dimensional, \" \\\n \"but received Input x's dimensional: %s.\\n\" % \\\n len(input_shape)\n\n assert (input_shape[-1] == input_shape[-2]), \\\n \"Expect squared input,\" \\\n \"but received %s by %s matrix.\\n\" \\\n %(input_shape[-2], input_shape[-1]) \\\n\n helper = LayerHelper('slogdeterminant', **locals())\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n helper.append_op(\n type='slogdeterminant', inputs={'Input': [x]}, outputs={'Out': [out]})\n return out\n\n\ndef svd(x, full_matrices=False, name=None):\n r\"\"\"\n Computes the singular value decomposition of one matrix or a batch of regular matrices.\n\n Let :math:`X` be the input matrix or a batch of input matrices, the output should satisfies:\n\n .. math::\n X = U * diag(S) * VT\n\n Args:\n x (Tensor): The input tensor. Its shape should be `[..., N, M]`,\n where `...` is zero or more batch dimensions. N and M can be arbitraty\n positive number. Note that if x is sigular matrices, the grad is numerical\n instable. The data type of x should be float32 or float64.\n full_matrices (bool): A flag to control the behavor of svd.\n If full_matrices = True, svd op will compute full U and V matrics,\n which means shape of U is `[..., N, N]`, shape of V is `[..., M, M]`. K = min(M, N).\n If full_matrices = False, svd op will use a economic method to store U and V.\n which means shape of U is `[..., N, K]`, shape of V is `[..., M, K]`. K = min(M, N).\n name (str, optional): Name for the operation (optional, default is None).\n For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tuple of 3 tensors: (U, S, VH). VH is the conjugate transpose of V. S is the singlar value vectors of matrics with shape `[..., K]`\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.to_tensor([[1.0, 2.0], [1.0, 3.0], [4.0, 6.0]]).astype('float64')\n x = x.reshape([3, 2])\n u, s, vh = paddle.linalg.svd(x)\n print (u)\n #U = [[ 0.27364809, -0.21695147 ],\n # [ 0.37892198, -0.87112408 ],\n # [ 0.8840446 , 0.44053933 ]]\n\n print (s)\n #S = [8.14753743, 0.78589688]\n print (vh)\n #VT= [[ 0.51411221, 0.85772294],\n # [ 0.85772294, -0.51411221]]\n\n # one can verify : U * S * VT == X\n # U * UH == I\n # V * VH == I\n \"\"\"\n\n if paddle.in_dynamic_mode():\n return _C_ops.svd(x, 'full_matrices', full_matrices)\n check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'svd')\n check_type(full_matrices, 'full_matrices', bool, 'svd')\n helper = LayerHelper('svd', **locals())\n u = helper.create_variable_for_type_inference(dtype=x.dtype)\n vh = helper.create_variable_for_type_inference(dtype=x.dtype)\n s = helper.create_variable_for_type_inference(dtype=x.dtype)\n attrs = dict()\n attrs['full_matrices'] = full_matrices\n helper.append_op(\n type='svd',\n inputs={'X': [x]},\n outputs={'U': u,\n 'VH': vh,\n 'S': s},\n attrs=attrs, )\n return u, s, vh\n\n\ndef matrix_power(x, n, name=None):\n r\"\"\"\n Computes the n-th power of a square matrix or a batch of square matrices.\n\n Let :math:`X` be a sqaure matrix or a batch of square matrices, :math:`n` be\n an exponent, the equation should be:\n\n .. math::\n Out = X ^ {n}\n\n Specifically,\n\n - If `n > 0`, it returns the matrix or a batch of matrices raised to the power\n of `n`.\n\n - If `n = 0`, it returns the identity matrix or a batch of identity matrices.\n\n - If `n < 0`, it returns the inverse of each matrix (if invertible) raised to\n the power of `abs(n)`.\n\n Args:\n x (Tensor): A square matrix or a batch of square matrices to be raised\n to power `n`. Its shape should be `[*, M, M]`, where `*` is zero or\n more batch dimensions. Its data type should be float32 or float64.\n n (int): The exponent. It can be any positive, negative integer or zero.\n name (str, optional): Name for the operation (optional, default is None).\n For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: The n-th power of the matrix (or the batch of matrices) `x`. Its\n data type should be the same as that of `x`.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.to_tensor([[1, 2, 3],\n [1, 4, 9],\n [1, 8, 27]], dtype='float64')\n print(paddle.linalg.matrix_power(x, 2))\n # [[6. , 34. , 102.],\n # [14. , 90. , 282.],\n # [36. , 250., 804.]]\n\n print(paddle.linalg.matrix_power(x, 0))\n # [[1., 0., 0.],\n # [0., 1., 0.],\n # [0., 0., 1.]]\n\n print(paddle.linalg.matrix_power(x, -2))\n # [[ 12.91666667, -12.75000000, 2.83333333 ],\n # [-7.66666667 , 8. , -1.83333333 ],\n # [ 1.80555556 , -1.91666667 , 0.44444444 ]]\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.matrix_power(x, \"n\", n)\n\n check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'matrix_power')\n check_type(n, 'n', int, 'matrix_power')\n helper = LayerHelper('matrix_power', **locals())\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n helper.append_op(\n type='matrix_power',\n inputs={'X': x},\n outputs={'Out': out},\n attrs={'n': n})\n return out\n\n\ndef qr(x, mode=\"reduced\", name=None):\n r\"\"\"\n Computes the QR decomposition of one matrix or batches of matrice (backward is unsupported now).\n\n Args:\n x (Tensor): The input tensor. Its shape should be `[..., M, N]`,\n where ... is zero or more batch dimensions. M and N can be arbitrary\n positive number. The data type of x should be float32 or float64. \n mode (str, optional): A flag to control the behavior of qr, the default is \"reduced\". \n Suppose x's shape is `[..., M, N]` and denoting `K = min(M, N)`:\n If mode = \"reduced\", qr op will return reduced Q and R matrices, \n which means Q's shape is `[..., M, K]` and R's shape is `[..., K, N]`.\n If mode = \"complete\", qr op will return complete Q and R matrices, \n which means Q's shape is `[..., M, M]` and R's shape is `[..., M, N]`.\n If mode = \"r\", qr op will only return reduced R matrix, which means\n R's shape is `[..., K, N]`.\n name (str, optional): Name for the operation (optional, default is None).\n For more information, please refer to :ref:`api_guide_Name`.\n \n Returns:\n If mode = \"reduced\" or mode = \"complete\", qr will return a two tensor-tuple, which represents Q and R. \n If mode = \"r\", qr will return a tensor which represents R.\n \n Examples: \n .. code-block:: python\n\n import paddle \n\n x = paddle.to_tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]).astype('float64')\n q, r = paddle.linalg.qr(x)\n print (q)\n print (r)\n\n # Q = [[-0.16903085, 0.89708523],\n # [-0.50709255, 0.27602622],\n # [-0.84515425, -0.34503278]])\n\n # R = [[-5.91607978, -7.43735744],\n # [ 0. , 0.82807867]])\n \n # one can verify : X = Q * R ; \n \"\"\"\n if paddle.in_dynamic_mode():\n q, r = _C_ops.qr(x, 'mode', mode)\n if mode == \"r\":\n return r\n else:\n return q, r\n check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'qr')\n check_type(mode, 'mode', str, 'qr')\n helper = LayerHelper('qr', **locals())\n q = helper.create_variable_for_type_inference(dtype=x.dtype)\n r = helper.create_variable_for_type_inference(dtype=x.dtype)\n attrs = dict()\n attrs['mode'] = mode\n helper.append_op(\n type='qr', inputs={'X': [x]}, outputs={'Q': q,\n 'R': r}, attrs=attrs)\n if mode == \"r\":\n return r\n else:\n return q, r\n\n\ndef lu(x, pivot=True, get_infos=False, name=None):\n r\"\"\"\n Computes the LU factorization of an N-D(N>=2) matrix x. \n\n Returns the LU factorization(inplace x) and Pivots. low triangular matrix L and \n upper triangular matrix U are combined to a single LU matrix.\n\n Pivoting is done if pivot is set to True.\n P mat can be get by pivots:\n # ones = eye(rows) #eye matrix of rank rows\n # for i in range(cols):\n # swap(ones[i], ones[pivots[i]])\n # return ones\n\n Args:\n\n X (Tensor): the tensor to factor of N-dimensions(N>=2).\n\n pivot (bool, optional): controls whether pivoting is done. Default: True.\n\n get_infos (bool, optional): if set to True, returns an info IntTensor. Default: False.\n\n name (str, optional): Name for the operation (optional, default is None).\n For more information, please refer to :ref:`api_guide_Name`.\n \n Returns:\n factorization (Tensor): LU matrix, the factorization of input X.\n\n pivots (IntTensor): the pivots of size(∗(N-2), min(m,n)). `pivots` stores all the \n intermediate transpositions of rows. The final permutation `perm` could be \n reconstructed by this, details refer to upper example.\n\n infos (IntTensor, optional): if `get_infos` is `True`, this is a tensor of size (∗(N-2)) \n where non-zero values indicate whether factorization for the matrix or each minibatch \n has succeeded or failed.\n\n \n Examples: \n .. code-block:: python\n\n import paddle \n\n x = paddle.to_tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]).astype('float64')\n lu,p,info = paddle.linalg.lu(x, get_infos=True)\n\n # >>> lu:\n # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True,\n # [[5. , 6. ],\n # [0.20000000, 0.80000000],\n # [0.60000000, 0.50000000]])\n # >>> p\n # Tensor(shape=[2], dtype=int32, place=CUDAPlace(0), stop_gradient=True,\n # [3, 3])\n # >>> info\n # Tensor(shape=[], dtype=int32, place=CUDAPlace(0), stop_gradient=True,\n # 0)\n \n P,L,U = paddle.linalg.lu_unpack(lu,p)\n\n # >>> P\n # (Tensor(shape=[3, 3], dtype=float64, place=CUDAPlace(0), stop_gradient=True,\n # [[0., 1., 0.],\n # [0., 0., 1.],\n # [1., 0., 0.]]), \n # >>> L\n # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True,\n # [[1. , 0. ],\n # [0.20000000, 1. ],\n # [0.60000000, 0.50000000]]), \n # >>> U\n # Tensor(shape=[2, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True,\n # [[5. , 6. ],\n # [0. , 0.80000000]]))\n \n\n # one can verify : X = P @ L @ U ; \n \"\"\"\n if paddle.in_dynamic_mode():\n LU, Piv, Info = _C_ops.lu(x, 'pivots', pivot)\n if get_infos:\n return LU, Piv, Info\n else:\n return LU, Piv\n check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'lu')\n helper = LayerHelper('lu', **locals())\n lu = helper.create_variable_for_type_inference(dtype=x.dtype)\n p = helper.create_variable_for_type_inference(dtype='int')\n info = helper.create_variable_for_type_inference(dtype='int')\n attrs = dict()\n attrs['pivots'] = pivot\n helper.append_op(\n type='lu',\n inputs={'X': x},\n outputs={'Out': lu,\n 'Pivots': p,\n 'Infos': info},\n attrs=attrs)\n if get_infos:\n return lu, p, info\n else:\n return lu, p\n\n\ndef lu_unpack(x, y, unpack_ludata=True, unpack_pivots=True, name=None):\n r\"\"\"\n Unpack L U and P to single matrix tensor . \n unpack L and U matrix from LU, unpack permutation matrix P from Pivtos .\n\n P mat can be get by pivots:\n # ones = eye(rows) #eye matrix of rank rows\n # for i in range(cols):\n # swap(ones[i], ones[pivots[i]])\n\n\n Args:\n x (Tensor): The LU tensor get from paddle.linalg.lu, which is combined by L and U.\n\n y (Tensor): Pivots get from paddle.linalg.lu.\n\n unpack_ludata (bool,optional): whether to unpack L and U from x. Default: True.\n\n unpack_pivots (bool, optional): whether to unpack permutation matrix P from Pivtos. Default: True.\n\n name (str, optional): Name for the operation (optional, default is None).\n For more information, please refer to :ref:`api_guide_Name`.\n \n Returns:\n P (Tensor): Permutation matrix P of lu factorization.\n\n L (Tensor): The lower triangular matrix tensor of lu factorization.\n\n U (Tensor): The upper triangular matrix tensor of lu factorization.\n\n \n Examples: \n .. code-block:: python\n\n import paddle \n\n x = paddle.to_tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]).astype('float64')\n lu,p,info = paddle.linalg.lu(x, get_infos=True)\n\n # >>> lu:\n # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True,\n # [[5. , 6. ],\n # [0.20000000, 0.80000000],\n # [0.60000000, 0.50000000]])\n # >>> p\n # Tensor(shape=[2], dtype=int32, place=CUDAPlace(0), stop_gradient=True,\n # [3, 3])\n # >>> info\n # Tensor(shape=[], dtype=int32, place=CUDAPlace(0), stop_gradient=True,\n # 0)\n \n P,L,U = paddle.linalg.lu_unpack(lu,p)\n\n # >>> P\n # (Tensor(shape=[3, 3], dtype=float64, place=CUDAPlace(0), stop_gradient=True,\n # [[0., 1., 0.],\n # [0., 0., 1.],\n # [1., 0., 0.]]), \n # >>> L\n # Tensor(shape=[3, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True,\n # [[1. , 0. ],\n # [0.20000000, 1. ],\n # [0.60000000, 0.50000000]]), \n # >>> U\n # Tensor(shape=[2, 2], dtype=float64, place=CUDAPlace(0), stop_gradient=True,\n # [[5. , 6. ],\n # [0. , 0.80000000]]))\n\n # one can verify : X = P @ L @ U ; \n \"\"\"\n\n if paddle.in_dynamic_mode():\n P, L, U = _C_ops.lu_unpack(x, y, 'unpack_ludata', unpack_ludata,\n 'unpack_pivots', unpack_pivots)\n return P, L, U\n\n check_variable_and_dtype(x, 'dtype', ['float32', 'float64'], 'lu_unpack')\n helper = LayerHelper('lu_unpack', **locals())\n p = helper.create_variable_for_type_inference(dtype=x.dtype)\n l = helper.create_variable_for_type_inference(dtype=x.dtype)\n u = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n attrs = dict()\n attrs['unpack_ludata'] = unpack_ludata\n attrs['unpack_pivots'] = unpack_pivots\n helper.append_op(\n type='lu_unpack',\n inputs={'X': x,\n 'Pivots': y},\n outputs={'Pmat': p,\n 'L': l,\n 'U': u},\n attrs=attrs)\n return p, l, u\n\n\ndef eig(x, name=None):\n \"\"\"\n This API performs the eigenvalue decomposition of a square matrix or a batch of square matrices.\n\n .. note::\n If the matrix is a Hermitian or a real symmetric matrix, please use :ref:`paddle.linalg.eigh` instead, which is much faster.\n If only eigenvalues is needed, please use :ref:`paddle.linalg.eigvals` instead.\n If the matrix is of any shape, please use :ref:`paddle.linalg.svd`.\n This API is only supported on CPU device.\n The output datatype is always complex for both real and complex input.\n\n Args:\n x (Tensor): A tensor with shape math:`[*, N, N]`, The data type of the x should be one of ``float32``,\n ``float64``, ``compplex64`` or ``complex128``.\n name (str, optional): The default value is `None`. Normally there is no need for user to set \n this property. For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Eigenvalues(Tensors): A tensor with shape math:`[*, N]` refers to the eigen values.\n Eigenvectors(Tensors): A tensor with shape math:`[*, N, N]` refers to the eigen vectors.\n\n Examples:\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n paddle.device.set_device(\"cpu\")\n\n x_data = np.array([[1.6707249, 7.2249975, 6.5045543],\n [9.956216, 8.749598, 6.066444 ],\n [4.4251957, 1.7983172, 0.370647 ]]).astype(\"float32\")\n x = paddle.to_tensor(x_data)\n w, v = paddle.linalg.eig(x)\n print(w)\n # Tensor(shape=[3, 3], dtype=complex128, place=CPUPlace, stop_gradient=False,\n # [[(-0.5061363550800655+0j) , (-0.7971760990842826+0j) ,\n # (0.18518077798279986+0j)],\n # [(-0.8308237755993192+0j) , (0.3463813401919749+0j) ,\n # (-0.6837005269141947+0j) ],\n # [(-0.23142567697893396+0j), (0.4944999840400175+0j) ,\n # (0.7058765252952796+0j) ]])\n\n print(v)\n # Tensor(shape=[3], dtype=complex128, place=CPUPlace, stop_gradient=False,\n # [ (16.50471283351188+0j) , (-5.5034820550763515+0j) ,\n # (-0.21026087843552282+0j)])\n \"\"\"\n if paddle.in_dynamic_mode():\n w, v = _C_ops.eig(x)\n return w, v\n\n check_variable_and_dtype(\n x, 'X', ['float32', 'float64', 'complex64', 'complex128'], 'eig')\n helper = LayerHelper('eig', **locals())\n\n w = helper.create_variable_for_type_inference(x.dtype)\n v = helper.create_variable_for_type_inference(x.dtype)\n\n inputs = {'X': x}\n outputs = {'Eigenvalues': w, 'Eigenvectors': v}\n helper.append_op(type='eig', inputs=inputs, outputs=outputs)\n\n return w, v\n\n\ndef eigvals(x, name=None):\n \"\"\"\n Compute the eigenvalues of one or more general matrices.\n\n Warning:\n The gradient kernel of this operator does not yet developed.\n If you need back propagation through this operator, please replace it with paddle.linalg.eig.\n\n Args:\n x (Tensor): A square matrix or a batch of square matrices whose eigenvalues will be computed.\n Its shape should be `[*, M, M]`, where `*` is zero or more batch dimensions.\n Its data type should be float32, float64, complex64, or complex128.\n name (str, optional): Name for the operation (optional, default is None).\n For more information, please refer to :ref:`api_guide_Name`.\n \n Returns:\n Tensor: A tensor containing the unsorted eigenvalues which has the same batch dimensions with `x`.\n The eigenvalues are complex-valued even when `x` is real.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n paddle.set_device(\"cpu\")\n paddle.seed(1234)\n\n x = paddle.rand(shape=[3, 3], dtype='float64')\n # [[0.02773777, 0.93004224, 0.06911496],\n # [0.24831591, 0.45733623, 0.07717843],\n # [0.48016702, 0.14235102, 0.42620817]])\n\n print(paddle.linalg.eigvals(x))\n # [(-0.27078833542132674+0j), (0.29962280156230725+0j), (0.8824477020120244+0j)] #complex128\n \"\"\"\n\n check_variable_and_dtype(x, 'dtype',\n ['float32', 'float64', 'complex64',\n 'complex128'], 'eigvals')\n\n x_shape = list(x.shape)\n if len(x_shape) < 2:\n raise ValueError(\n \"The dimension of Input(x) should be at least 2, but received x's dimention = {}, x's shape = {}\".\n format(len(x_shape), x_shape))\n\n if x_shape[-1] != x_shape[-2]:\n raise ValueError(\n \"The last two dimensions of Input(x) should be equal, but received x's shape = {}\".\n format(x_shape))\n\n if paddle.in_dynamic_mode():\n return _C_ops.eigvals(x)\n\n helper = LayerHelper('eigvals', **locals())\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n helper.append_op(type='eigvals', inputs={'X': x}, outputs={'Out': out})\n return out\n\n\ndef multi_dot(x, name=None):\n \"\"\"\n Multi_dot is an operator that calculates multiple matrix multiplications.\n\n Supports inputs of float16(only GPU support), float32 and float64 dtypes. This function does not\n support batched inputs.\n\n The input tensor in [x] must be 2-D except for the first and last can be 1-D.\n If the first tensor is a 1-D vector of shape(n, ) it is treated as row vector\n of shape(1, n), similarly if the last tensor is a 1D vector of shape(n, ), it\n is treated as a column vector of shape(n, 1).\n\n If the first and last tensor are 2-D matrix, then the output is also 2-D matrix,\n otherwise the output is a 1-D vector.\n\n Multi_dot will select the lowest cost multiplication order for calculation. The\n cost of multiplying two matrices with shapes (a, b) and (b, c) is a * b * c.\n Given matrices A, B, C with shapes (20, 5), (5, 100), (100, 10) respectively,\n we can calculate the cost of different multiplication orders as follows:\n - Cost((AB)C) = 20x5x100 + 20x100x10 = 30000\n - Cost(A(BC)) = 5x100x10 + 20x5x10 = 6000\n\n In this case, multiplying B and C first, then multiply A, which is 5 times faster\n than sequential calculation.\n\n Args:\n x ([Tensor]): The input tensors which is a list Tensor.\n name(str|None): A name for this layer(optional). If set None, the layer\n will be named automatically.\n\n Returns:\n Tensor: The output Tensor.\n\n\n Examples:\n\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n # A * B\n A_data = np.random.random([3, 4]).astype(np.float32)\n B_data = np.random.random([4, 5]).astype(np.float32)\n A = paddle.to_tensor(A_data)\n B = paddle.to_tensor(B_data)\n out = paddle.linalg.multi_dot([A, B])\n print(out.numpy().shape)\n # [3, 5]\n\n # A * B * C\n A_data = np.random.random([10, 5]).astype(np.float32)\n B_data = np.random.random([5, 8]).astype(np.float32)\n C_data = np.random.random([8, 7]).astype(np.float32)\n A = paddle.to_tensor(A_data)\n B = paddle.to_tensor(B_data)\n C = paddle.to_tensor(C_data)\n out = paddle.linalg.multi_dot([A, B, C])\n print(out.numpy().shape)\n # [10, 7]\n\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.multi_dot(x)\n\n check_type(x, 'x', (list, tuple), 'multi_dot')\n for id, item in enumerate(x):\n check_variable_and_dtype(item, 'x[' + str(id) + ']',\n ['float16', 'float32', 'float64'], 'multi_dot')\n if item.dtype != x[0].dtype:\n raise TypeError(\n \"All the Tensors in the input must have the same data type.\")\n\n helper = LayerHelper('multi_dot', **locals())\n dtype = helper.input_dtype(input_param_name='x')\n out = helper.create_variable_for_type_inference(dtype)\n helper.append_op(type='multi_dot', inputs={\"X\": x}, outputs={\"Out\": out})\n return out\n\n\ndef eigh(x, UPLO='L', name=None):\n \"\"\"\n Compute the eigenvalues and eigenvectors of a\n complex Hermitian (conjugate symmetric) or a real symmetric matrix.\n\n Args:\n x (Tensor): A tensor with shape :math:`[*, N, N]` , The data type of the input Tensor x\n should be one of float32, float64, complex64, complex128.\n UPLO(str, optional): (string, default 'L'), 'L' represents the lower triangular matrix,\n \"'U' represents the upper triangular matrix.\".\n name(str, optional): The default value is None. Normally there is no need for user to set this\n property. For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n\n out_value(Tensor): A Tensor with shape [*, N] and data type of float32 and float64. The eigenvalues of eigh op.\n out_vector(Tensor): A Tensor with shape [*, N, N] and data type of float32,float64,complex64 and complex128. The eigenvectors of eigh op.\n\n Examples:\n .. code-block:: python\n\n import numpy as np\n import paddle\n\n x_data = np.array([[1, -2j], [2j, 5]])\n x = paddle.to_tensor(x_data)\n out_value, out_vector = paddle.linalg.eigh(x, UPLO='L')\n print(out_value)\n #[0.17157288, 5.82842712]\n print(out_vector)\n #[(-0.9238795325112867+0j), (-0.3826834323650898+0j)],\n #[ 0.3826834323650898j , -0.9238795325112867j ]]\n\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.eigh(x, 'UPLO', UPLO)\n\n def __check_input(x, UPLO):\n x_shape = list(x.shape)\n if len(x.shape) < 2:\n raise ValueError(\n \"Input(input) only support >=2 tensor, but received \"\n \"length of Input(input) is %s.\" % len(x.shape))\n if x_shape[-1] != x_shape[-2]:\n raise ValueError(\n \"The input matrix must be batches of square matrices. But received x's dimention: {}\".\n format(x_shape))\n if UPLO != 'L' and UPLO != 'U':\n raise ValueError(\n \"UPLO must be L or U. But received UPLO is: {}\".format(UPLO))\n\n __check_input(x, UPLO)\n\n helper = LayerHelper('eigh', **locals())\n check_variable_and_dtype(\n x, 'dtype', ['float32', 'float64', 'complex64', 'complex128'], 'eigh')\n\n out_value = helper.create_variable_for_type_inference(dtype=x.dtype)\n out_vector = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n helper.append_op(\n type='eigh',\n inputs={'X': x},\n outputs={'Eigenvalues': out_value,\n 'Eigenvectors': out_vector},\n attrs={'UPLO': UPLO})\n return out_value, out_vector\n\n\ndef pinv(x, rcond=1e-15, hermitian=False, name=None):\n r\"\"\"\n Calculate pseudo inverse via SVD(singular value decomposition)\n of one matrix or batches of regular matrix.\n\n .. math::\n\n if hermitian == False:\n x = u * s * vt (SVD)\n out = v * 1/s * ut\n else:\n x = u * s * ut (eigh)\n out = u * 1/s * u.conj().transpose(-2,-1)\n\n If x is hermitian or symmetric matrix, svd will be replaced with eigh.\n\n Args:\n x(Tensor): The input tensor. Its shape should be (*, m, n)\n where * is zero or more batch dimensions. m and n can be\n arbitraty positive number. The data type of x should be\n float32 or float64 or complex64 or complex128. When data\n type is complex64 or cpmplex128, hermitian should be set\n True.\n\n rcond(Tensor, optional): the tolerance value to determine\n when is a singular value zero. Defalut:1e-15.\n\n hermitian(bool, optional): indicates whether x is Hermitian\n if complex or symmetric if real. Default: False.\n\n name(str|None): A name for this layer(optional). If set None,\n the layer will be named automatically.\n\n Returns:\n Tensor: The tensor with same data type with x. it represents\n pseudo inverse of x. Its shape should be (*, n, m).\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.arange(15).reshape((3, 5)).astype('float64')\n input = paddle.to_tensor(x)\n out = paddle.linalg.pinv(input)\n print(input)\n print(out)\n\n # input:\n # [[0. , 1. , 2. , 3. , 4. ],\n # [5. , 6. , 7. , 8. , 9. ],\n # [10., 11., 12., 13., 14.]]\n\n # out:\n # [[-0.22666667, -0.06666667, 0.09333333],\n # [-0.12333333, -0.03333333, 0.05666667],\n # [-0.02000000, 0.00000000, 0.02000000],\n # [ 0.08333333, 0.03333333, -0.01666667],\n # [ 0.18666667, 0.06666667, -0.05333333]]\n\n # one can verify : x * out * x = x ;\n # or out * x * out = x ;\n \"\"\"\n\n if paddle.in_dynamic_mode():\n if not hermitian:\n # combine svd and matmul op\n u, s, vt = _C_ops.svd(x, 'full_matrices', False)\n max_singular_val = _C_ops.reduce_max(s, 'dim', [-1], 'keep_dim', True, \\\n 'reduce_all', False)\n rcond = paddle.to_tensor(rcond, dtype=x.dtype)\n cutoff = rcond * max_singular_val\n y = float('inf')\n y = paddle.to_tensor(y, dtype=x.dtype)\n\n condition = s > cutoff\n cond_int = layers.cast(condition, s.dtype)\n cond_not_int = layers.cast(layers.logical_not(condition), s.dtype)\n out1 = layers.elementwise_mul(1 / s, cond_int)\n out2 = layers.elementwise_mul(1 / y, cond_not_int)\n singular = layers.elementwise_add(out1, out2)\n st, _ = _C_ops.unsqueeze2(singular, 'axes', [-2])\n\n dims = list(range(len(vt.shape)))\n perm = dims[:-2] + [dims[-1]] + [dims[-2]]\n v, _ = _C_ops.transpose2(vt, 'axis', perm)\n\n out_1 = v * st\n out_2 = _C_ops.matmul_v2(out_1, u, 'trans_x', False, 'trans_y',\n True)\n return out_2\n else:\n # combine eigh and matmul op\n s, u = _C_ops.eigh(x, 'UPLO', 'L')\n s_abs = paddle.abs(s)\n max_singular_val = _C_ops.reduce_max(s_abs, 'dim', [-1], 'keep_dim', True, \\\n 'reduce_all', False)\n rcond = paddle.to_tensor(rcond, dtype=s.dtype)\n cutoff = rcond * max_singular_val\n y = float('inf')\n y = paddle.to_tensor(y, dtype=s.dtype)\n\n condition = s_abs > cutoff\n cond_int = layers.cast(condition, s.dtype)\n cond_not_int = layers.cast(layers.logical_not(condition), s.dtype)\n out1 = layers.elementwise_mul(1 / s, cond_int)\n out2 = layers.elementwise_mul(1 / y, cond_not_int)\n singular = layers.elementwise_add(out1, out2)\n st, _ = _C_ops.unsqueeze2(singular, 'axes', [-2])\n\n out_1 = u * st\n u_conj = _C_ops.conj(u)\n out_2 = _C_ops.matmul_v2(out_1, u_conj, 'trans_x', False, 'trans_y',\n True)\n return out_2\n else:\n if not hermitian:\n helper = LayerHelper('pinv', **locals())\n dtype = x.dtype\n check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'pinv')\n\n u = helper.create_variable_for_type_inference(dtype)\n s = helper.create_variable_for_type_inference(dtype)\n vt = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='svd',\n inputs={'X': [x]},\n outputs={'U': u,\n 'VH': vt,\n 'S': s},\n attrs={'full_matrices': False}, )\n\n max_singular_val = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='reduce_max',\n inputs={'X': s},\n outputs={'Out': max_singular_val},\n attrs={'dim': [-1],\n 'keep_dim': True,\n 'reduce_all': False})\n\n rcond = layers.fill_constant(shape=[1], value=rcond, dtype=dtype)\n cutoff = rcond * max_singular_val\n y = float('inf')\n y = layers.fill_constant(shape=[1], value=y, dtype=dtype)\n\n condition = s > cutoff\n cond_int = layers.cast(condition, dtype)\n cond_not_int = layers.cast(layers.logical_not(condition), dtype)\n out1 = layers.elementwise_mul(1 / s, cond_int)\n out2 = layers.elementwise_mul(1 / y, cond_not_int)\n singular = layers.elementwise_add(out1, out2)\n\n st = helper.create_variable_for_type_inference(dtype=dtype)\n st_shape = helper.create_variable_for_type_inference(dtype=dtype)\n helper.append_op(\n type='unsqueeze2',\n inputs={'X': singular},\n attrs={'axes': [-2]},\n outputs={'Out': st,\n 'XShape': st_shape})\n\n dims = list(range(len(vt.shape)))\n perm = dims[:-2] + [dims[-1]] + [dims[-2]]\n v = helper.create_variable_for_type_inference(dtype)\n v_shape = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='transpose2',\n inputs={'X': [vt]},\n outputs={'Out': [v],\n 'XShape': [v_shape]},\n attrs={'axis': perm})\n\n out_1 = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='elementwise_mul',\n inputs={'X': v,\n 'Y': st},\n outputs={'Out': out_1},\n attrs={'axis': -1,\n 'use_mkldnn': False})\n out_1 = helper.append_activation(out_1)\n\n out_2 = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='matmul_v2',\n inputs={'X': out_1,\n 'Y': u},\n outputs={'Out': out_2},\n attrs={'trans_x': False,\n 'trans_y': True}, )\n return out_2\n else:\n helper = LayerHelper('pinv', **locals())\n dtype = x.dtype\n check_variable_and_dtype(\n x, 'dtype', ['float32', 'float64', 'complex64',\n 'complex128'], 'pinv')\n\n if dtype == paddle.complex128:\n s_type = 'float64'\n elif dtype == paddle.complex64:\n s_type = 'float32'\n else:\n s_type = dtype\n\n u = helper.create_variable_for_type_inference(dtype)\n s = helper.create_variable_for_type_inference(s_type)\n helper.append_op(\n type='eigh',\n inputs={'X': x},\n outputs={'Eigenvalues': s,\n 'Eigenvectors': u},\n attrs={'UPLO': 'L'})\n s_abs = helper.create_variable_for_type_inference(s_type)\n helper.append_op(\n type='abs', inputs={'X': s}, outputs={'Out': s_abs})\n max_singular_val = helper.create_variable_for_type_inference(s_type)\n helper.append_op(\n type='reduce_max',\n inputs={'X': s_abs},\n outputs={'Out': max_singular_val},\n attrs={'dim': [-1],\n 'keep_dim': True,\n 'reduce_all': False})\n\n rcond = layers.fill_constant(shape=[1], value=rcond, dtype=s_type)\n cutoff = rcond * max_singular_val\n y = float('inf')\n y = layers.fill_constant(shape=[1], value=y, dtype=s_type)\n\n condition = s_abs > cutoff\n cond_int = layers.cast(condition, s_type)\n cond_not_int = layers.cast(layers.logical_not(condition), s_type)\n out1 = layers.elementwise_mul(1 / s, cond_int)\n out2 = layers.elementwise_mul(1 / y, cond_not_int)\n singular = layers.elementwise_add(out1, out2)\n\n st = helper.create_variable_for_type_inference(dtype=s_type)\n st_shape = helper.create_variable_for_type_inference(dtype=s_type)\n helper.append_op(\n type='unsqueeze2',\n inputs={'X': singular},\n attrs={'axes': [-2]},\n outputs={'Out': st,\n 'XShape': st_shape})\n\n out_1 = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='elementwise_mul',\n inputs={'X': u,\n 'Y': st},\n outputs={'Out': out_1},\n attrs={'axis': -1,\n 'use_mkldnn': False})\n out_1 = helper.append_activation(out_1)\n\n u_conj = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='conj', inputs={'X': u}, outputs={'Out': [u_conj]})\n\n out_2 = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='matmul_v2',\n inputs={'X': out_1,\n 'Y': u_conj},\n outputs={'Out': out_2},\n attrs={'trans_x': False,\n 'trans_y': True}, )\n return out_2\n\n\ndef solve(x, y, name=None):\n r\"\"\"\n Computes the solution of a square system of linear equations with a unique solution for input 'X' and 'Y'.\n Let :math: `X` be a sqaure matrix or a batch of square matrices, :math:`Y` be\n a vector/matrix or a batch of vectors/matrices, the equation should be:\n\n .. math::\n Out = X^-1 * Y\n Specifically,\n - This system of linear equations has one solution if and only if input 'X' is invertible.\n\n Args:\n x (Tensor): A square matrix or a batch of square matrices. Its shape should be `[*, M, M]`, where `*` is zero or\n more batch dimensions. Its data type should be float32 or float64.\n y (Tensor): A vector/matrix or a batch of vectors/matrices. Its shape should be `[*, M, K]`, where `*` is zero or\n more batch dimensions. Its data type should be float32 or float64.\n name(str, optional): Name for the operation (optional, default is None).\n For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: The solution of a square system of linear equations with a unique solution for input 'x' and 'y'.\n Its data type should be the same as that of `x`.\n\n Examples:\n .. code-block:: python\n\n # a square system of linear equations:\n # 2*X0 + X1 = 9\n # X0 + 2*X1 = 8\n\n import paddle\n import numpy as np\n\n np_x = np.array([[3, 1],[1, 2]])\n np_y = np.array([9, 8])\n x = paddle.to_tensor(np_x, dtype=\"float64\")\n y = paddle.to_tensor(np_y, dtype=\"float64\")\n out = paddle.linalg.solve(x, y)\n\n print(out)\n # [2., 3.])\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.solve(x, y)\n\n inputs = {\"X\": [x], \"Y\": [y]}\n helper = LayerHelper(\"solve\", **locals())\n check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'solve')\n check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'solve')\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n helper.append_op(\n type=\"solve\", inputs={\"X\": x,\n \"Y\": y}, outputs={\"Out\": out})\n return out\n\n\ndef triangular_solve(x,\n y,\n upper=True,\n transpose=False,\n unitriangular=False,\n name=None):\n r\"\"\"\n Computes the solution of a system of equations with a triangular coefficient matrix `x` and\n multiple right-hand sides `y` .\n\n Input `x` and `y` is 2D matrices or batches of 2D matrices. If the inputs are batches, the outputs\n is also batches.\n\n Args:\n x (Tensor): The input triangular coefficient matrix. Its shape should be `[*, M, M]`, where `*` is zero or\n more batch dimensions. Its data type should be float32 or float64.\n y (Tensor): Multiple right-hand sides of system of equations. Its shape should be `[*, M, K]`, where `*` is \n zero or more batch dimensions. Its data type should be float32 or float64.\n upper (bool, optional): Whether to solve the upper-triangular system of equations (default) or the lower-triangular \n system of equations. Default: True.\n transpose (bool, optional): whether `x` should be transposed before calculation. Default: False.\n unitriangular (bool, optional): whether `x` is unit triangular. If True, the diagonal elements of `x` are assumed \n to be 1 and not referenced from `x` . Default: False.\n name(str, optional): Name for the operation (optional, default is None).\n For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: The solution of the system of equations. Its data type should be the same as that of `x`.\n\n Examples:\n .. code-block:: python\n\n # a square system of linear equations:\n # x1 + x2 + x3 = 0\n # 2*x2 + x3 = -9\n # -x3 = 5\n\n import paddle\n import numpy as np\n\n x = paddle.to_tensor([[1, 1, 1], \n [0, 2, 1],\n [0, 0,-1]], dtype=\"float64\")\n y = paddle.to_tensor([[0], [-9], [5]], dtype=\"float64\")\n out = paddle.linalg.triangular_solve(x, y, upper=True)\n\n print(out)\n # [7, -2, -5]\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.triangular_solve(x, y, 'upper', upper, 'transpose',\n transpose, 'unitriangular',\n unitriangular)\n\n inputs = {\"X\": [x], \"Y\": [y]}\n helper = LayerHelper(\"triangular_solve\", **locals())\n check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'triangular_solve')\n check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'triangular_solve')\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n helper.append_op(\n type='triangular_solve',\n inputs={'X': x,\n 'Y': y},\n outputs={'Out': out},\n attrs={\n 'upper': upper,\n 'transpose': transpose,\n 'unitriangular': unitriangular\n })\n return out\n\n\ndef cholesky_solve(x, y, upper=False, name=None):\n r\"\"\"\n Solves a linear system of equations A @ X = B, given A's Cholesky factor matrix u and matrix B.\n\n Input `x` and `y` is 2D matrices or batches of 2D matrices. If the inputs are batches, the outputs\n is also batches.\n\n Args:\n x (Tensor): The input matrix which is upper or lower triangular Cholesky factor of square matrix A. Its shape should be `[*, M, M]`, where `*` is zero or\n more batch dimensions. Its data type should be float32 or float64.\n y (Tensor): Multiple right-hand sides of system of equations. Its shape should be `[*, M, K]`, where `*` is \n zero or more batch dimensions. Its data type should be float32 or float64.\n upper (bool, optional): whether to consider the Cholesky factor as a lower or upper triangular matrix. Default: False.\n name(str, optional): Name for the operation (optional, default is None).\n For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: The solution of the system of equations. Its data type is the same as that of `x`.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n u = paddle.to_tensor([[1, 1, 1], \n [0, 2, 1],\n [0, 0,-1]], dtype=\"float64\")\n b = paddle.to_tensor([[0], [-9], [5]], dtype=\"float64\")\n out = paddle.linalg.cholesky_solve(b, u, upper=True)\n\n print(out)\n # [-2.5, -7, 9.5]\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.cholesky_solve(x, y, 'upper', upper)\n\n helper = LayerHelper(\"cholesky_solve\", **locals())\n check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'cholesky_solve')\n check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'cholesky_solve')\n out = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n helper.append_op(\n type='cholesky_solve',\n inputs={'X': x,\n 'Y': y},\n outputs={'Out': out},\n attrs={'upper': upper})\n return out\n\n\ndef eigvalsh(x, UPLO='L', name=None):\n \"\"\"\n Computes the eigenvalues of a \n complex Hermitian (conjugate symmetric) or a real symmetric matrix.\n\n Args:\n x (Tensor): A tensor with shape :math:`[_, M, M]` , The data type of the input Tensor x\n should be one of float32, float64, complex64, complex128.\n UPLO(str, optional): Lower triangular part of a (‘L’, default) or the upper triangular part (‘U’).\n name(str, optional): The default value is None. Normally there is no need for user to set this\n property. For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: The tensor eigenvalues in ascending order.\n\n Examples:\n .. code-block:: python\n\n import numpy as np\n import paddle\n\n x_data = np.array([[1, -2j], [2j, 5]])\n x = paddle.to_tensor(x_data)\n out_value = paddle.eigvalsh(x, UPLO='L')\n print(out_value)\n #[0.17157288, 5.82842712]\n \"\"\"\n if paddle.in_dynamic_mode():\n is_test = x.stop_gradient\n values, _ = _C_ops.eigvalsh(x, 'UPLO', UPLO, 'is_test', is_test)\n return values\n\n def __check_input(x, UPLO):\n x_shape = list(x.shape)\n if len(x.shape) < 2:\n raise ValueError(\n \"Input(input) only support >=2 tensor, but received \"\n \"length of Input(input) is %s.\" % len(x.shape))\n if x_shape[-1] != x_shape[-2]:\n raise ValueError(\n \"The input matrix must be batches of square matrices. But received x's dimention: {}\".\n format(x_shape))\n if UPLO != 'L' and UPLO != 'U':\n raise ValueError(\n \"UPLO must be L or U. But received UPLO is: {}\".format(UPLO))\n\n __check_input(x, UPLO)\n\n helper = LayerHelper('eigvalsh', **locals())\n check_variable_and_dtype(x, 'dtype',\n ['float32', 'float64', 'complex64', 'complex128'],\n 'eigvalsh')\n\n out_value = helper.create_variable_for_type_inference(dtype=x.dtype)\n out_vector = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n is_test = x.stop_gradient\n helper.append_op(\n type='eigvalsh',\n inputs={'X': x},\n outputs={'Eigenvalues': out_value,\n 'Eigenvectors': out_vector},\n attrs={'UPLO': UPLO,\n 'is_test': is_test})\n return out_value\n\n\ndef lstsq(x, y, rcond=None, driver=None, name=None):\n \"\"\"\n Computes a solution to\n the least squares problem of a system of linear equations.\n\n Args:\n x (Tensor): A tensor with shape ``(*, M, N)`` , the data type of the input Tensor ``x``\n should be one of float32, float64.\n y (Tensor): A tensor with shape ``(*, M, K)`` , the data type of the input Tensor ``y`` \n should be one of float32, float64.\n rcond(float, optional): The default value is None. A float pointing number used to determine \n the effective rank of ``x``. If ``rcond`` is None, it will be set to max(M, N) times the \n machine precision of x_dtype.\n driver(str, optional): The default value is None. The name of LAPACK method to be used. For \n CPU inputs the valid values are ‘gels’, ‘gelsy’, ‘gelsd, ‘gelss’. For CUDA input, the only \n valid driver is ‘gels’. If ``driver`` is None, ‘gelsy’ is used for CPU inputs and ‘gels’ \n for CUDA inputs.\n name(str, optional): The default value is None. Normally there is no need for user to set \n this property. For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tuple: A tuple of 4 Tensors which is (``solution``, ``residuals``, ``rank``, ``singular_values``). \n ``solution`` is a tensor with shape ``(*, N, K)``, meaning the least squares solution. ``residuals`` \n is a tensor with shape ``(*, K)``, meaning the squared residuals of the solutions, which is computed \n when M > N and every matrix in ``x`` is full-rank, otherwise return an empty tensor. ``rank`` is a tensor \n with shape ``(*)``, meaning the ranks of the matrices in ``x``, which is computed when ``driver`` in \n (‘gelsy’, ‘gelsd’, ‘gelss’), otherwise return an empty tensor. ``singular_values`` is a tensor with \n shape ``(*, min(M, N))``, meaning singular values of the matrices in ``x``, which is computed when \n ``driver`` in (‘gelsd’, ‘gelss’), otherwise return an empty tensor.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n paddle.set_device(\"cpu\")\n x = paddle.to_tensor([[1, 3], [3, 2], [5, 6.]])\n y = paddle.to_tensor([[3, 4, 6], [5, 3, 4], [1, 2, 1.]])\n results = paddle.linalg.lstsq(x, y, driver=\"gelsd\")\n print(results[0])\n # [[ 0.78350395, -0.22165027, -0.62371236],\n # [-0.11340097, 0.78866047, 1.14948535]]\n print(results[1])\n # [19.81443405, 10.43814468, 30.56185532])\n print(results[2])\n # 2\n print(results[3])\n # [9.03455734, 1.54167950]\n\n x = paddle.to_tensor([[10, 2, 3], [3, 10, 5], [5, 6, 12.]])\n y = paddle.to_tensor([[4, 2, 9], [2, 0, 3], [2, 5, 3.]])\n results = paddle.linalg.lstsq(x, y, driver=\"gels\")\n print(results[0])\n # [[ 0.39386186, 0.10230173, 0.93606132],\n # [ 0.10741687, -0.29028133, 0.11892585],\n # [-0.05115091, 0.51918161, -0.19948854]]\n print(results[1])\n # []\n \"\"\"\n device = paddle.get_device()\n if device == \"cpu\":\n if driver not in (None, \"gels\", \"gelss\", \"gelsd\", \"gelsy\"):\n raise ValueError(\n \"Only support valid driver is 'gels', 'gelss', 'gelsd', 'gelsy' or None for CPU inputs. But got {}\".\n format(driver))\n driver = \"gelsy\" if driver is None else driver\n elif \"gpu\" in device:\n if driver not in (None, \"gels\"):\n raise ValueError(\n \"Only support valid driver is 'gels' or None for CUDA inputs. But got {}\".\n format(driver))\n driver = \"gels\" if driver is None else driver\n else:\n raise RuntimeError(\"Only support lstsq api for CPU or CUDA device.\")\n\n if x.dtype == y.dtype and x.dtype in (paddle.float32, paddle.float64):\n pass\n else:\n raise ValueError(\n \"Only support x and y have the same dtype such as 'float32' and 'float64'.\"\n )\n\n if rcond is None:\n if x.dtype == paddle.float32:\n rcond = 1e-7 * max(x.shape[-2], x.shape[-1])\n elif x.dtype == paddle.float64:\n rcond = 1e-15 * max(x.shape[-2], x.shape[-1])\n\n if paddle.in_dynamic_mode():\n solution, rank, singular_values = _C_ops.lstsq(x, y, \"rcond\", rcond,\n \"driver\", driver)\n if x.shape[-2] > x.shape[-1]:\n matmul_out = _varbase_creator(dtype=x.dtype)\n _C_ops.matmul(x, solution, matmul_out, 'trans_x', False, 'trans_y',\n False)\n minus_out = _C_ops.elementwise_sub(matmul_out, y)\n pow_out = _C_ops.pow(minus_out, 'factor', 2)\n residuals = _C_ops.reduce_sum(pow_out, 'dim', [-2], 'keepdim',\n False, 'reduce_all', False)\n else:\n residuals = paddle.empty(shape=[0], dtype=x.dtype)\n\n if driver == \"gels\":\n rank = paddle.empty(shape=[0], dtype=paddle.int32)\n singular_values = paddle.empty(shape=[0], dtype=x.dtype)\n elif driver == \"gelsy\":\n singular_values = paddle.empty(shape=[0], dtype=x.dtype)\n\n return solution, residuals, rank, singular_values\n\n helper = LayerHelper('lstsq', **locals())\n check_variable_and_dtype(\n x, 'dtype', ['float32', 'float64', 'complex64', 'complex128'], 'lstsq')\n check_variable_and_dtype(\n y, 'dtype', ['float32', 'float64', 'complex64', 'complex128'], 'lstsq')\n\n solution = helper.create_variable_for_type_inference(dtype=x.dtype)\n residuals = helper.create_variable_for_type_inference(dtype=x.dtype)\n rank = helper.create_variable_for_type_inference(dtype=paddle.int32)\n singular_values = helper.create_variable_for_type_inference(dtype=x.dtype)\n\n helper.append_op(\n type='lstsq',\n inputs={'X': x,\n 'Y': y},\n outputs={\n 'Solution': solution,\n 'Rank': rank,\n 'SingularValues': singular_values\n },\n attrs={'rcond': rcond,\n 'driver': driver})\n\n matmul_out = helper.create_variable_for_type_inference(dtype=x.dtype)\n minus_out = helper.create_variable_for_type_inference(dtype=x.dtype)\n pow_out = helper.create_variable_for_type_inference(dtype=x.dtype)\n helper.append_op(\n type='matmul_v2',\n inputs={'X': x,\n 'Y': solution},\n outputs={'Out': matmul_out},\n attrs={\n 'trans_x': False,\n 'trans_y': False,\n })\n\n helper.append_op(\n type='elementwise_sub',\n inputs={'X': matmul_out,\n 'Y': y},\n outputs={'Out': minus_out})\n\n helper.append_op(\n type='pow',\n inputs={'X': minus_out},\n outputs={'Out': pow_out},\n attrs={'factor': 2})\n\n helper.append_op(\n type='reduce_sum',\n inputs={'X': pow_out},\n outputs={'Out': residuals},\n attrs={'dim': [-2],\n 'keep_dim': False,\n 'reduce_all': False})\n\n if driver == \"gels\":\n rank = paddle.static.data(name='rank', shape=[0])\n singular_values = paddle.static.data(name='singular_values', shape=[0])\n elif driver == \"gelsy\":\n singular_values = paddle.static.data(name='singular_values', shape=[0])\n\n return solution, residuals, rank, singular_values\n", "# 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\nfrom __future__ import print_function\nfrom collections import Counter\n\nfrom ..static import Variable, device_guard\nfrom ..framework import core\nfrom ..fluid.framework import _in_legacy_dygraph, in_dygraph_mode, _in_eager_without_dygraph_check\nfrom ..fluid.layer_helper import LayerHelper\nfrom ..framework import OpProtoHolder, convert_np_dtype_to_dtype_, dygraph_only\nfrom ..fluid.data_feeder import convert_dtype, check_variable_and_dtype, check_type, check_dtype\nfrom ..fluid.layers import utils\nimport numpy as np\n# TODO: define functions to manipulate a tensor \nfrom ..fluid.layers import cast # noqa: F401\nfrom ..fluid.layers import slice # noqa: F401\nfrom ..fluid.layers import transpose # noqa: F401\nfrom ..fluid.layers import unstack # noqa: F401\n\nfrom ..fluid.layers import scatter_nd # noqa: F401\nfrom ..fluid.layers import shard_index # noqa: F401\nfrom ..fluid.layers import crop_tensor as crop # noqa: F401\nfrom ..fluid.layers.nn import _elementwise_op_in_dygraph\nfrom ..fluid import layers\nfrom ..fluid.dygraph.inplace_utils import inplace_apis_in_dygraph_only\nimport paddle\nfrom paddle import _C_ops\nfrom paddle.tensor.attribute import _complex_to_real_dtype, _real_to_complex_dtype\n\n__all__ = []\n\n\n@dygraph_only\ndef fill_(x, value):\n \"\"\"\n **Notes**:\n **This API is ONLY available in Dygraph mode**\n\n This function fill the Tensor with value inplace.\n\n Args:\n x(Tensor): ``x`` is the Tensor we want to filled data inplace\n value(Scale): ``value`` is the value to be filled in x\n\n Returns:\n x(Tensor): Tensor x filled with value inplace\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n tensor = paddle.to_tensor([0, 1, 2, 3, 4])\n\n tensor.fill_(0)\n print(tensor.tolist()) #[0, 0, 0, 0, 0]\n\n \"\"\"\n if not isinstance(value, (float, int)):\n raise TypeError(\n \"The type of 'value' must be int or float, but received %s.\" %\n (type(value)))\n return _C_ops.fill_any_(x, \"value_float\",\n float(value), \"value_int\", int(value))\n\n\nsetattr(core.VarBase, 'fill_', fill_)\n\n\n@dygraph_only\ndef zero_(x):\n \"\"\"\n **Notes**:\n **This API is ONLY available in Dygraph mode**\n\n This function fill the Tensor with zero inplace.\n\n Args:\n x(Tensor): ``x`` is the Tensor we want to filled with zero inplace\n\n Returns:\n x(Tensor): Tensor x filled with zero inplace\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n tensor = paddle.to_tensor([0, 1, 2, 3, 4])\n\n tensor.zero_()\n print(tensor.tolist()) #[0, 0, 0, 0, 0]\n\n \"\"\"\n return _C_ops.fill_any_(x, \"value_float\", 0., \"value_int\", int(0))\n\n\nsetattr(core.VarBase, 'zero_', zero_)\n\n\n@dygraph_only\ndef fill_diagonal_(x, value, offset=0, wrap=False, name=None):\n \"\"\"\n **Notes**:\n **This API is ONLY available in Dygraph mode**\n This function fill the value into the x Tensor's diagonal inplace.\n Args:\n x(Tensor): ``x`` is the original Tensor\n value(Scale): ``value`` is the value to filled in x\n offset(int,optional): the offset to the main diagonal. Default: 0 (main diagonal).\n wrap(bool,optional): the diagonal 'wrapped' after N columns for tall matrices.\n name(str,optional): Name for the operation (optional, default is None)\n Returns:\n Tensor: Tensor with diagonal filled with value.\n Returns type:\n dtype is same as x Tensor\n Examples:\n .. code-block:: python\n import paddle\n x = paddle.ones((4, 3)) * 2\n x.fill_diagonal_(1.0)\n print(x.tolist()) #[[1.0, 2.0, 2.0], [2.0, 1.0, 2.0], [2.0, 2.0, 1.0], [2.0, 2.0, 2.0]]\n \"\"\"\n helper = LayerHelper(\"fill_diagonal_\", **locals())\n check_type(x, 'X', (Variable), 'fill_diagonal_')\n dtype = helper.input_dtype('x')\n check_dtype(dtype, 'X',\n ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'],\n 'fill_diagonal_')\n check_type(value, 'value', (bool, int, float), 'fill_diagonal_')\n check_type(wrap, 'wrap', (bool), 'fill_diagonal_')\n\n inshape = x.shape\n inshapeset = set(inshape)\n assert len(inshape) >= 2, ('Tensor dims should >= 2 in fill_diagonal_ API')\n if len(inshape) > 2:\n assert len(inshapeset) == 1, (\n 'Tensor dims should be equal while input dims > 2 in fill_diagonal_ API'\n )\n if len(inshape) == 2:\n return _C_ops.fill_diagonal_(x, 'value', value, 'offset', offset,\n 'wrap', wrap)\n return _C_ops.fill_diagonal_(x, 'value', value, 'offset', offset, 'wrap',\n True)\n\n\nsetattr(core.VarBase, 'fill_diagonal_', fill_diagonal_)\n\n\ndef _fill_diagonal_tensor_impl(x, y, offset=0, dim1=0, dim2=1, inplace=False):\n inshape = x.shape\n assert dim1 < len(inshape) and dim1 >= -len(inshape), (\n 'dim1 should between [-rank,rank) in fill_diagonal_tensor_')\n assert dim2 < len(inshape) and dim2 >= -len(inshape), (\n 'dim2 should between [-rank,rank) in fill_diagonal_tensor_')\n assert len(inshape) >= 2, (\n 'Tensor dims should >= 2 in fill_diagonal_tensor_')\n dim1 %= len(inshape)\n dim2 %= len(inshape)\n\n predshape = []\n for i in range(len(inshape)):\n if i != dim1 and i != dim2:\n predshape.append(inshape[i])\n diaglen = min(\n min(inshape[dim1], inshape[dim1] + offset),\n min(inshape[dim2], inshape[dim2] - offset))\n predshape.append(diaglen)\n assert tuple(predshape) == tuple(y.shape), (\n \"the y shape should be {}\".format(predshape))\n if len(y.shape) == 1:\n y = y.reshape([1, -1])\n\n if inplace:\n return _C_ops.fill_diagonal_tensor_(x, y, 'dim1', dim1, 'dim2', dim2,\n 'offset', offset)\n return _C_ops.fill_diagonal_tensor(x, y, 'dim1', dim1, 'dim2', dim2,\n 'offset', offset)\n\n\ndef fill_diagonal_tensor_(x, y, offset=0, dim1=0, dim2=1, name=None):\n \"\"\"\n **Notes**:\n **This API is ONLY available in Dygraph mode**\n\n This function fill the source Tensor y into the x Tensor's diagonal inplace.\n\n Args:\n x(Tensor): ``x`` is the original Tensor\n y(Tensor): ``y`` is the Tensor to filled in x\n dim1(int,optional): first dimension with respect to which to fill diagonal. Default: 0.\n dim2(int,optional): second dimension with respect to which to fill diagonal. Default: 1.\n offset(int,optional): the offset to the main diagonal. Default: 0 (main diagonal).\n name(str,optional): Name for the operation (optional, default is None)\n\n Returns:\n Tensor: Tensor with diagonal filled with y.\n\n Returns type:\n list: dtype is same as x Tensor\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.ones((4, 3)) * 2\n y = paddle.ones((3,))\n x.fill_diagonal_tensor_(y)\n print(x.tolist()) #[[1.0, 2.0, 2.0], [2.0, 1.0, 2.0], [2.0, 2.0, 1.0], [2.0, 2.0, 2.0]]\n\n \"\"\"\n return _fill_diagonal_tensor_impl(\n x, y, offset=offset, dim1=dim1, dim2=dim2, inplace=True)\n\n\nsetattr(core.VarBase, 'fill_diagonal_tensor_', fill_diagonal_tensor_)\n\n\ndef fill_diagonal_tensor(x, y, offset=0, dim1=0, dim2=1, name=None):\n \"\"\"\n This function fill the source Tensor y into the x Tensor's diagonal.\n\n Args:\n x(Tensor): ``x`` is the original Tensor\n y(Tensor): ``y`` is the Tensor to filled in x\n dim1(int,optional): first dimension with respect to which to fill diagonal. Default: 0.\n dim2(int,optional): second dimension with respect to which to fill diagonal. Default: 1.\n offset(int,optional): the offset to the main diagonal. Default: 0 (main diagonal).\n name(str,optional): Name for the operation (optional, default is None)\n\n Returns:\n Tensor: Tensor with diagonal filled with y.\n\n Returns type:\n list: dtype is same as x Tensor\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.ones((4, 3)) * 2\n y = paddle.ones((3,))\n nx = x.fill_diagonal_tensor(y)\n print(nx.tolist()) #[[1.0, 2.0, 2.0], [2.0, 1.0, 2.0], [2.0, 2.0, 1.0], [2.0, 2.0, 2.0]]\n\n \"\"\"\n return _fill_diagonal_tensor_impl(\n x, y, offset=offset, dim1=dim1, dim2=dim2, inplace=False)\n\n\nsetattr(core.VarBase, 'fill_diagonal_tensor', fill_diagonal_tensor)\n\nif _in_eager_without_dygraph_check():\n setattr(core.eager.Tensor, 'fill_diagonal_tensor', fill_diagonal_tensor)\n\n\n@dygraph_only\ndef tolist(x):\n \"\"\"\n **Notes**:\n **This API is ONLY available in Dygraph mode**\n\n This function translate the paddle.Tensor to python list.\n\n Args:\n x(Tensor): ``x`` is the Tensor we want to translate to list\n\n Returns:\n list: A list that contain the same value of current Tensor.\n\n Returns type:\n list: dtype is same as current Tensor\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n t = paddle.to_tensor([0,1,2,3,4])\n expectlist = t.tolist()\n print(expectlist) #[0, 1, 2, 3, 4]\n\n expectlist = paddle.tolist(t)\n print(expectlist) #[0, 1, 2, 3, 4]\n\n \"\"\"\n return x.numpy().tolist()\n\n\nsetattr(core.VarBase, 'tolist', tolist)\n\n\ndef concat(x, axis=0, name=None):\n \"\"\"\n\n This OP concatenates the input along the axis.\n\n Args:\n x(list|tuple): ``x`` is a Tensor list or Tensor tuple which is with data type bool, float16,\n float32, float64, int32, int64, uint8. All the Tensors in ``x`` must have same data type.\n axis(int|Tensor, optional): Specify the axis to operate on the input Tensors.\n It's a scalar with data type int or a Tensor with shape [1] and data type int32 \n or int64. The effective range is [-R, R), where R is Rank(x). When ``axis < 0``,\n it works the same way as ``axis+R``. Default is 0.\n name (str, optional): The default value is None. Normally there is no\n need for user to set this property. For more information, please\n refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: A Tensor with the same data type as ``x``.\n\n Examples:\n .. code-block:: python\n \n import paddle\n \n x1 = paddle.to_tensor([[1, 2, 3],\n [4, 5, 6]])\n x2 = paddle.to_tensor([[11, 12, 13],\n [14, 15, 16]])\n x3 = paddle.to_tensor([[21, 22],\n [23, 24]])\n zero = paddle.full(shape=[1], dtype='int32', fill_value=0)\n # When the axis is negative, the real axis is (axis + Rank(x))\n # As follow, axis is -1, Rank(x) is 2, the real axis is 1\n out1 = paddle.concat(x=[x1, x2, x3], axis=-1)\n out2 = paddle.concat(x=[x1, x2], axis=0)\n out3 = paddle.concat(x=[x1, x2], axis=zero)\n # out1\n # [[ 1 2 3 11 12 13 21 22]\n # [ 4 5 6 14 15 16 23 24]]\n # out2 out3\n # [[ 1 2 3]\n # [ 4 5 6]\n # [11 12 13]\n # [14 15 16]]\n \"\"\"\n return paddle.fluid.layers.concat(input=x, axis=axis, name=name)\n\n\ndef broadcast_tensors(input, name=None):\n \"\"\"\n This OP broadcast a list of tensors following broadcast semantics\n\n .. note::\n If you want know more about broadcasting, please refer to :ref:`user_guide_broadcasting`.\n\n Args:\n input(list|tuple): ``input`` is a Tensor list or Tensor tuple which is with data type bool,\n float16, float32, float64, int32, int64. All the Tensors in ``input`` must have same data type.\n Currently we only support tensors with rank no greater than 5.\n\n name (str, optional): The default value is None. Normally there is no need for user to set this property. \n For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n list(Tensor): The list of broadcasted tensors following the same order as ``input``.\n\n Examples:\n .. code-block:: python\n\n import paddle\n x1 = paddle.rand([1, 2, 3, 4]).astype('float32')\n x2 = paddle.rand([1, 2, 1, 4]).astype('float32')\n x3 = paddle.rand([1, 1, 3, 1]).astype('float32')\n out1, out2, out3 = paddle.broadcast_tensors(input=[x1, x2, x3])\n # out1, out2, out3: tensors broadcasted from x1, x2, x3 with shape [1,2,3,4]\n \"\"\"\n\n num_inputs = len(input)\n if paddle.in_dynamic_mode():\n return _C_ops.broadcast_tensors(input, num_inputs)\n\n check_type(input, 'input', (list, tuple), 'broadcast_tensors')\n if num_inputs < 1:\n raise TypeError(\n \"At least 1 tensor is needed to perform broadcast_tensors\")\n\n # Check input types\n for id, x in enumerate(input):\n check_variable_and_dtype(\n x, 'input[' + str(id) + ']',\n ['bool', 'float32', 'float64', 'int32', 'int64'],\n 'broadcast_tensors')\n if x.dtype != input[0].dtype:\n raise TypeError(\n \"All the Tensors in the input must have the same data type.\")\n\n # Check bcast semantics\n output_shape_r_last_tensor_index = []\n output_shape_r = []\n\n # Use while loop due to weird behaviour of \"range()\"\n j = 0\n while j < len(input):\n tensor = input[j]\n shape = list(reversed(tensor.shape))\n\n i = 0\n while i < len(shape):\n if len(output_shape_r) <= i:\n output_shape_r.append(shape[i])\n output_shape_r_last_tensor_index.append(j)\n else:\n invalid = (output_shape_r[i] != shape[i] and\n output_shape_r[i] != 1 and shape[i] != 1)\n if invalid:\n last_index = output_shape_r_last_tensor_index[i]\n raise TypeError(\n \"Input tensors to broadcast_tensors does not follow bcast semantics\"\n \"Tensor {last_index} conflicts with Tensor {j} in reversed dimension {i}\"\n )\n if output_shape_r[i] <= shape[i]:\n output_shape_r[i] = shape[i]\n output_shape_r_last_tensor_index[i] = j\n i += 1 # while i < len(shape)\n j += 1 # while j < len(input)\n\n helper = LayerHelper('broadcast_tensors', **locals())\n i = 0\n out = []\n while i < num_inputs:\n out.append(\n helper.create_variable_for_type_inference(dtype=helper.input_dtype(\n )))\n i += 1\n\n inputs = {'X': input}\n helper.append_op(\n type='broadcast_tensors', inputs=inputs, outputs={'Out': out},\n attrs={})\n\n return out\n\n\ndef flip(x, axis, name=None):\n \"\"\"\n Reverse the order of a n-D tensor along given axis in axis.\n\n Args:\n x (Tensor): A Tensor(or LoDTensor) with shape :math:`[N_1, N_2,..., N_k]` . The data type of the input Tensor x\n should be float32, float64, int32, int64, bool.\n axis (list|tuple|int): The axis(axes) to flip on. Negative indices for indexing from the end are accepted.\n name (str, optional): The default value is None. Normally there is no need for user to set this property.\n For more information, please refer to :ref:`api_guide_Name` .\n\n Returns:\n Tensor: Tensor or LoDTensor calculated by flip layer. The data type is same with input x.\n\n Examples:\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n image_shape=(3, 2, 2)\n x = np.arange(image_shape[0] * image_shape[1] * image_shape[2]).reshape(image_shape)\n x = x.astype('float32')\n img = paddle.to_tensor(x)\n tmp = paddle.flip(img, [0,1])\n print(tmp) # [[[10,11],[8, 9]], [[6, 7],[4, 5]], [[2, 3],[0, 1]]]\n\n out = paddle.flip(tmp,-1)\n print(out) # [[[11,10],[9, 8]], [[7, 6],[5, 4]], [[3, 2],[1, 0]]]\n \"\"\"\n if isinstance(axis, int):\n axis = [axis]\n if paddle.in_dynamic_mode():\n return _C_ops.flip(x, \"axis\", axis)\n\n helper = LayerHelper(\"flip\", **locals())\n check_type(x, 'X', (Variable), 'flip')\n dtype = helper.input_dtype('x')\n check_dtype(dtype, 'X',\n ['float16', 'float32', 'float64', 'int32', 'int64', 'bool'],\n 'flip')\n check_type(axis, 'axis', (list, tuple), 'flip')\n if name is None:\n out = helper.create_variable_for_type_inference(dtype)\n else:\n out = helper.create_variable(name=name, dtype=dtype, persistable=False)\n\n helper.append_op(\n type=\"flip\",\n inputs={\"X\": x},\n outputs={\"Out\": out},\n attrs={\"axis\": axis})\n return out\n\n\ndef rot90(x, k=1, axes=[0, 1], name=None):\n \"\"\"\n Rotate a n-D tensor by 90 degrees. The rotation direction and times are specified by axes. Rotation direction is from axes[0] towards axes[1] if k > 0, and from axes[1] towards axes[0] for k < 0.\n\n Args:\n x (Tensor): The input Tensor(or LoDTensor). The data type of the input Tensor x\n should be float16, float32, float64, int32, int64, bool. float16 is only supported on gpu.\n k (int, optional): Direction and number of times to rotate, default value: 1.\n axes (list|tuple, optional): Axes to rotate, dimension must be 2. default value: [0, 1].\n name (str, optional): The default value is None. Normally there is no need for user to set this property.\n For more information, please refer to :ref:`api_guide_Name` .\n\n Returns:\n Tensor: Tensor or LoDTensor calculated by rot90 layer. The data type is same with input x.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n data = paddle.arange(4)\n data = paddle.reshape(data, (2, 2))\n print(data) \n #[[0, 1],\n # [2, 3]]\n\n y = paddle.rot90(data, 1, [0, 1])\n print(y) \n #[[1, 3],\n # [0, 2]]\n\n y= paddle.rot90(data, -1, [0, 1])\n print(y) \n #[[2, 0],\n # [3, 1]]\n\n data2 = paddle.arange(8)\n data2 = paddle.reshape(data2, (2,2,2))\n print(data2) \n #[[[0, 1],\n # [2, 3]],\n # [[4, 5],\n # [6, 7]]]\n\n y = paddle.rot90(data2, 1, [1, 2])\n print(y)\n #[[[1, 3],\n # [0, 2]],\n # [[5, 7],\n # [4, 6]]]\n \"\"\"\n\n helper = LayerHelper(\"rot90\", **locals())\n check_type(x, 'X', (Variable), 'rot90')\n dtype = helper.input_dtype('x')\n check_dtype(dtype, 'X',\n ['float16', 'float32', 'float64', 'int32', 'int64', 'bool'],\n 'rot90')\n check_type(axes, 'axes', (list, tuple), 'rot90')\n\n input_total_dims = len(x.shape)\n total_rot_dims = len(axes)\n if total_rot_dims != 2:\n raise ValueError(\"expected total rotation axes == 2, but got axes = {}\".\n format(total_rot_dims))\n if input_total_dims < 2:\n raise ValueError(\"expected total dims >= 2, but got total dims = {}\".\n format(input_total_dims))\n\n if not (axes[0] != axes[1] and abs(axes[0] - axes[1]) != input_total_dims):\n raise ValueError(\n \"expected rotation axes to be different, but got axis0 = {}, and axis1 = {}\".\n format(axes[0], axes[1]))\n\n if not (axes[0] < input_total_dims and axes[0] >= -input_total_dims):\n raise ValueError(\"Rotation axis0 out of range, axis0 = {}\".format(axes[\n 0]))\n if not (axes[1] < input_total_dims and axes[1] >= -input_total_dims):\n raise ValueError(\"Rotation axis1 out of range, axis1 = {}\".format(axes[\n 1]))\n\n k %= 4\n if k == 0:\n return x\n if k == 2:\n return flip(flip(x, axes[0]), axes[1])\n\n axes_list = list(range(0, input_total_dims))\n (axes_list[axes[0]], axes_list[axes[1]]) = (axes_list[axes[1]],\n axes_list[axes[0]])\n if k == 1:\n return transpose(flip(x, axes[1]), axes_list)\n else:\n # k == 3\n return flip(transpose(x, axes_list), axes[1])\n\n\ndef flatten(x, start_axis=0, stop_axis=-1, name=None):\n r\"\"\"\n **Flatten op**\n\n Flattens a contiguous range of axes in a tensor according to start_axis and stop_axis.\n\n Note that the output Tensor will share data with origin Tensor and doesn't have a \n Tensor copy in ``dygraph`` mode. If you want to use the Tensor copy version, please \n use `Tensor.clone` like ``flatten_clone_x = x.flatten().clone()``.\n\n For Example:\n\n .. code-block:: text\n\n Case 1:\n\n Given\n X.shape = (3, 100, 100, 4)\n\n and\n start_axis = 1\n end_axis = 2\n\n We get:\n Out.shape = (3, 1000 * 100, 2)\n\n Case 2:\n\n Given\n X.shape = (3, 100, 100, 4)\n\n and\n start_axis = 0\n stop_axis = -1\n\n We get:\n Out.shape = (3 * 100 * 100 * 4)\n\n Args:\n x (Tensor): A tensor of number of dimentions >= axis. A tensor with data type float32,\n float64, int8, int32, int64, uint8.\n start_axis (int): the start axis to flatten\n stop_axis (int): the stop axis to flatten\n name(str, Optional): For details, please refer to :ref:`api_guide_Name`.\n Generally, no setting is required. Default: None.\n\n Returns:\n Tensor: A tensor with the contents of the input tensor, with input \\\n axes flattened by indicated start axis and end axis. \\\n A Tensor with data type same as input x.\n\n Raises:\n ValueError: If x is not a Tensor.\n ValueError: If start_axis or stop_axis is illegal.\n\n Examples:\n\n .. code-block:: python\n\n import paddle\n\n image_shape=(2, 3, 4, 4)\n\n x = paddle.arange(end=image_shape[0] * image_shape[1] * image_shape[2] * image_shape[3])\n img = paddle.reshape(x, image_shape)\n\n out = paddle.flatten(img, start_axis=1, stop_axis=2)\n # out shape is [2, 12, 4]\n\n # out shares data with img in dygraph mode\n img[0, 0, 0, 0] = -1\n print(out[0, 0, 0]) # [-1]\n \"\"\"\n if not (isinstance(x, Variable)):\n raise ValueError(\"The input x should be a Tensor\")\n\n if not paddle.in_dynamic_mode():\n check_variable_and_dtype(\n x, 'x',\n ['float32', 'float64', 'int8', 'int16', 'int32', 'int64', 'uint8'],\n 'flatten')\n\n x_dim = len(x.shape)\n if not (isinstance(start_axis, int)) or (\n start_axis > x_dim - 1) or start_axis < -x_dim:\n raise ValueError(\n \"The start_axis should be a int, and in range [-rank(x), rank(x))\")\n if not (isinstance(stop_axis, int)) or (\n stop_axis > x_dim - 1) or stop_axis < -x_dim:\n raise ValueError(\n \"The stop_axis should be a int, and in range [-rank(x), rank(x))\")\n if start_axis < 0:\n start_axis = start_axis + x_dim\n if stop_axis < 0:\n stop_axis = stop_axis + x_dim\n if start_axis > stop_axis:\n raise ValueError(\"The stop_axis should be larger than stat_axis\")\n\n if paddle.in_dynamic_mode():\n dy_out, _ = _C_ops.flatten_contiguous_range(x, 'start_axis', start_axis,\n 'stop_axis', stop_axis)\n return dy_out\n\n helper = LayerHelper('flatten', **locals())\n out = helper.create_variable_for_type_inference(x.dtype)\n x_shape = helper.create_variable_for_type_inference(x.dtype)\n helper.append_op(\n type='flatten_contiguous_range',\n inputs={\"X\": x},\n outputs={'Out': out,\n 'XShape': x_shape},\n attrs={\"start_axis\": start_axis,\n \"stop_axis\": stop_axis})\n return out\n\n\n@inplace_apis_in_dygraph_only\ndef flatten_(x, start_axis=0, stop_axis=-1, name=None):\n \"\"\"\n Inplace version of ``flatten`` API, the output Tensor will be inplaced with input ``x``.\n Please refer to :ref:`api_tensor_flatten`.\n \"\"\"\n if not (isinstance(x, Variable)):\n raise ValueError(\"The input x should be a Tensor\")\n\n x_dim = len(x.shape)\n if not (isinstance(start_axis, int)) or (\n start_axis > x_dim - 1) or start_axis < -x_dim:\n raise ValueError(\n \"The start_axis should be a int, and in range [-rank(x), rank(x))\")\n if not (isinstance(stop_axis, int)) or (\n stop_axis > x_dim - 1) or stop_axis < -x_dim:\n raise ValueError(\n \"The stop_axis should be a int, and in range [-rank(x), rank(x))\")\n if start_axis < 0:\n start_axis = start_axis + x_dim\n if stop_axis < 0:\n stop_axis = stop_axis + x_dim\n if start_axis > stop_axis:\n raise ValueError(\"The stop_axis should be larger than stat_axis\")\n\n dy_out, _ = _C_ops.flatten_contiguous_range_(x, 'start_axis', start_axis,\n 'stop_axis', stop_axis)\n return dy_out\n\n\ndef roll(x, shifts, axis=None, name=None):\n \"\"\"\n Roll the `x` tensor along the given axis(axes). With specific 'shifts', Elements that \n roll beyond the last position are re-introduced at the first according to 'shifts'. \n If a axis is not specified, \n the tensor will be flattened before rolling and then restored to the original shape.\n\n Args:\n x (Tensor): The x tensor as input.\n shifts (int|list|tuple): The number of places by which the elements\n of the `x` tensor are shifted.\n axis (int|list|tuple|None): axis(axes) along which to roll.\n\n Returns:\n Tensor: A Tensor with same data type as `x`.\n\n Examples:\n .. code-block:: python\n \n import paddle\n\n x = paddle.to_tensor([[1.0, 2.0, 3.0],\n [4.0, 5.0, 6.0],\n [7.0, 8.0, 9.0]])\n out_z1 = paddle.roll(x, shifts=1)\n print(out_z1)\n #[[9. 1. 2.]\n # [3. 4. 5.]\n # [6. 7. 8.]]\n out_z2 = paddle.roll(x, shifts=1, axis=0)\n print(out_z2)\n #[[7. 8. 9.]\n # [1. 2. 3.]\n # [4. 5. 6.]]\n \"\"\"\n origin_shape = x.shape\n if type(shifts) == int:\n shifts = [shifts]\n if type(axis) == int:\n axis = [axis]\n\n len_origin_shape = len(origin_shape)\n if axis is not None:\n for i in range(len(axis)):\n if axis[i] >= len_origin_shape or axis[i] < -len_origin_shape:\n raise ValueError(\n \"axis is out of range, it should be in range [{}, {}), but received {}\".\n format(-len_origin_shape, len_origin_shape, axis))\n else:\n axis = []\n\n if paddle.in_dynamic_mode():\n return _C_ops.roll(x, 'axis', axis, 'shifts', shifts)\n\n helper = LayerHelper(\"roll\", **locals())\n check_type(axis, 'axis', (list, tuple), 'roll')\n\n out = helper.create_variable_for_type_inference(x.dtype)\n\n if isinstance(shifts, Variable):\n helper.append_op(\n type='roll',\n inputs={'X': x,\n \"ShiftsTensor\": shifts},\n outputs={'Out': out},\n attrs={'axis': axis})\n else:\n check_type(shifts, 'shifts', (list, tuple), 'roll')\n helper.append_op(\n type='roll',\n inputs={'X': x},\n outputs={'Out': out},\n attrs={'axis': axis,\n 'shifts': shifts})\n return out\n\n\ndef stack(x, axis=0, name=None):\n \"\"\"\n This OP stacks all the input tensors ``x`` along ``axis`` dimemsion. \n All tensors must be of the same shape and same dtype.\n \n For example, given N tensors of shape [A, B], if ``axis == 0``, the shape of stacked \n tensor is [N, A, B]; if ``axis == 1``, the shape of stacked \n tensor is [A, N, B], etc.\n \n\n .. code-block:: text\n\n Case 1:\n\n Input:\n x[0].shape = [1, 2]\n x[0].data = [ [1.0 , 2.0 ] ]\n x[1].shape = [1, 2]\n x[1].data = [ [3.0 , 4.0 ] ]\n x[2].shape = [1, 2]\n x[2].data = [ [5.0 , 6.0 ] ]\n\n Attrs:\n axis = 0\n\n Output:\n Out.dims = [3, 1, 2]\n Out.data =[ [ [1.0, 2.0] ],\n [ [3.0, 4.0] ],\n [ [5.0, 6.0] ] ]\n\n\n Case 2:\n\n Input:\n x[0].shape = [1, 2]\n x[0].data = [ [1.0 , 2.0 ] ]\n x[1].shape = [1, 2]\n x[1].data = [ [3.0 , 4.0 ] ]\n x[2].shape = [1, 2]\n x[2].data = [ [5.0 , 6.0 ] ]\n\n\n Attrs:\n axis = 1 or axis = -2 # If axis = -2, axis = axis+ndim(x[0])+1 = -2+2+1 = 1.\n\n Output:\n Out.shape = [1, 3, 2]\n Out.data =[ [ [1.0, 2.0]\n [3.0, 4.0]\n [5.0, 6.0] ] ]\n\n Args:\n x (list[Tensor]|tuple[Tensor]): Input ``x`` can be a ``list`` or ``tuple`` of tensors, the Tensors in ``x``\n must be of the same shape and dtype. Supported data types: float32, float64, int32, int64.\n axis (int, optional): The axis along which all inputs are stacked. ``axis`` range is ``[-(R+1), R+1)``,\n where ``R`` is the number of dimensions of the first input tensor ``x[0]``. \n If ``axis < 0``, ``axis = axis+R+1``. The default value of axis is 0.\n name (str, optional): Please refer to :ref:`api_guide_Name`, Default None.\n \n Returns:\n Tensor: The stacked tensor with same data type as input.\n\n Example: \n .. code-block:: python\n\n import paddle\n \n x1 = paddle.to_tensor([[1.0, 2.0]])\n x2 = paddle.to_tensor([[3.0, 4.0]])\n x3 = paddle.to_tensor([[5.0, 6.0]])\n\t \n out = paddle.stack([x1, x2, x3], axis=0)\n print(out.shape) # [3, 1, 2]\n print(out)\n # [[[1., 2.]],\n # [[3., 4.]],\n # [[5., 6.]]]\n\t \n\t out = paddle.stack([x1, x2, x3], axis=-2)\n\t print(out.shape) # [1, 3, 2]\n\t print(out)\n\t # [[[1., 2.],\n\t # [3., 4.],\n\t # [5., 6.]]]\n \"\"\"\n return layers.stack(x, axis, name)\n\n\ndef split(x, num_or_sections, axis=0, name=None):\n \"\"\"\n Split the input tensor into multiple sub-Tensors.\n \n Args:\n x (Tensor): A N-D Tensor. The data type is bool, float16, float32, float64, int32 or int64.\n num_or_sections (int|list|tuple): If ``num_or_sections`` is an int, then ``num_or_sections`` \n indicates the number of equal sized sub-Tensors that the ``x`` will be divided into.\n If ``num_or_sections`` is a list or tuple, the length of it indicates the number of\n sub-Tensors and the elements in it indicate the sizes of sub-Tensors' dimension orderly.\n The length of the list must not be larger than the ``x`` 's size of specified ``axis``.\n axis (int|Tensor, optional): The axis along which to split, it can be a scalar with type \n ``int`` or a ``Tensor`` with shape [1] and data type ``int32`` or ``int64``.\n If :math::`axis < 0`, the axis to split along is :math:`rank(x) + axis`. Default is 0.\n name (str, optional): The default value is None. Normally there is no need for user to set this property.\n For more information, please refer to :ref:`api_guide_Name` .\n Returns:\n list(Tensor): The list of segmented Tensors.\n \n Example:\n .. code-block:: python\n \n import paddle\n \n # x is a Tensor of shape [3, 9, 5]\n x = paddle.rand([3, 9, 5])\n\n out0, out1, out2 = paddle.split(x, num_or_sections=3, axis=1)\n print(out0.shape) # [3, 3, 5]\n print(out1.shape) # [3, 3, 5]\n print(out2.shape) # [3, 3, 5]\n\n out0, out1, out2 = paddle.split(x, num_or_sections=[2, 3, 4], axis=1)\n print(out0.shape) # [3, 2, 5]\n print(out1.shape) # [3, 3, 5]\n print(out2.shape) # [3, 4, 5]\n\n out0, out1, out2 = paddle.split(x, num_or_sections=[2, 3, -1], axis=1)\n print(out0.shape) # [3, 2, 5]\n print(out1.shape) # [3, 3, 5]\n print(out2.shape) # [3, 4, 5]\n \n # axis is negative, the real axis is (rank(x) + axis)=1\n out0, out1, out2 = paddle.split(x, num_or_sections=3, axis=-2)\n print(out0.shape) # [3, 3, 5]\n print(out1.shape) # [3, 3, 5]\n print(out2.shape) # [3, 3, 5]\n \"\"\"\n return paddle.fluid.layers.split(\n input=x, num_or_sections=num_or_sections, dim=axis, name=name)\n\n\ndef squeeze(x, axis=None, name=None):\n \"\"\"\n This OP will squeeze the dimension(s) of size 1 of input tensor x's shape. \n \n Note that the output Tensor will share data with origin Tensor and doesn't have a \n Tensor copy in ``dygraph`` mode. If you want to use the Tensor copy version, \n please use `Tensor.clone` like ``squeeze_clone_x = x.squeeze().clone()``.\n\n If axis is provided, it will remove the dimension(s) by given axis that of size 1. \n If the dimension of given axis is not of size 1, the dimension remain unchanged. \n If axis is not provided, all dims equal of size 1 will be removed.\n\n .. code-block:: text\n\n Case1:\n\n Input:\n x.shape = [1, 3, 1, 5] # If axis is not provided, all dims equal of size 1 will be removed.\n axis = None\n Output:\n out.shape = [3, 5]\n\n Case2:\n\n Input:\n x.shape = [1, 3, 1, 5] # If axis is provided, it will remove the dimension(s) by given axis that of size 1.\n axis = 0\n Output:\n out.shape = [3, 1, 5]\n \n Case4:\n\n Input:\n x.shape = [1, 3, 1, 5] # If the dimension of one given axis (3) is not of size 1, the dimension remain unchanged. \n axis = [0, 2, 3]\n Output:\n out.shape = [3, 5]\n\n Case4:\n\n Input:\n x.shape = [1, 3, 1, 5] # If axis is negative, axis = axis + ndim (number of dimensions in x). \n axis = [-2]\n Output:\n out.shape = [1, 3, 5]\n\n Args:\n x (Tensor): The input Tensor. Supported data type: float32, float64, bool, int8, int32, int64.\n axis (int|list|tuple, optional): An integer or list/tuple of integers, indicating the dimensions to be squeezed. Default is None.\n The range of axis is :math:`[-ndim(x), ndim(x))`.\n If axis is negative, :math:`axis = axis + ndim(x)`.\n If axis is None, all the dimensions of x of size 1 will be removed.\n name (str, optional): Please refer to :ref:`api_guide_Name`, Default None.\n\n Returns:\n Tensor: Squeezed Tensor with the same data type as input Tensor.\n\n Examples:\n .. code-block:: python\n\n import paddle\n \n x = paddle.rand([5, 1, 10])\n output = paddle.squeeze(x, axis=1)\n\n print(x.shape) # [5, 1, 10]\n print(output.shape) # [5, 10]\n\n # output shares data with x in dygraph mode\n x[0, 0, 0] = 10.\n print(output[0, 0]) # [10.]\n\n \"\"\"\n if axis is None:\n axis = []\n elif isinstance(axis, int):\n axis = [axis]\n elif isinstance(axis, tuple):\n axis = list(axis)\n\n return layers.squeeze(x, axis, name)\n\n\n@inplace_apis_in_dygraph_only\ndef squeeze_(x, axis=None, name=None):\n \"\"\"\n Inplace version of ``squeeze`` API, the output Tensor will be inplaced with input ``x``.\n Please refer to :ref:`api_paddle_tensor_squeeze`.\n \"\"\"\n if axis is None:\n axis = []\n elif isinstance(axis, int):\n axis = [axis]\n elif isinstance(axis, tuple):\n axis = list(axis)\n\n out, _ = _C_ops.squeeze2_(x, 'axes', axis)\n return out\n\n\ndef unique_consecutive(x,\n return_inverse=False,\n return_counts=False,\n axis=None,\n dtype=\"int64\",\n name=None):\n r\"\"\"\n Eliminates all but the first element from every consecutive group of equivalent elements.\n\n .. note:: This function is different from :func:`paddle.unique` in the sense that this function\n only eliminates consecutive duplicate values. This semantics is similar to `std::unique` in C++.\n\n Args:\n x(Tensor): the input tensor, it's data type should be float32, float64, int32, int64.\n return_inverse(bool, optional): If True, also return the indices for where elements in\n the original input ended up in the returned unique consecutive tensor. Default is False.\n return_counts(bool, optional): If True, also return the counts for each unique consecutive element.\n Default is False.\n axis(int, optional): The axis to apply unique consecutive. If None, the input will be flattened.\n Default is None.\n dtype(np.dtype|str, optional): The data type `inverse` tensor: int32 or int64.\n Default: int64.\n name(str, optional): Name for the operation. For more information, please refer to\n :ref:`api_guide_Name`. Default is None.\n\n Returns:\n tuple: (out, inverse, counts). `out` is the unique consecutive tensor for `x`. `inverse` is provided only if `return_inverse` is True. `counts` is provided only if `return_counts` is True.\n\n Example:\n .. code-block:: python\n\n import paddle \n\n x = paddle.to_tensor([1, 1, 2, 2, 3, 1, 1, 2])\n output = paddle.unique_consecutive(x) # \n np_output = output.numpy() # [1 2 3 1 2]\n _, inverse, counts = paddle.unique_consecutive(x, return_inverse=True, return_counts=True)\n np_inverse = inverse.numpy() # [0 0 1 1 2 3 3 4]\n np_counts = inverse.numpy() # [2 2 1 2 1]\n\n x = paddle.to_tensor([[2, 1, 3], [3, 0, 1], [2, 1, 3], [2, 1, 3]])\n output = paddle.unique_consecutive(x, axis=0) # \n np_output = output.numpy() # [2 1 3 0 1 2 1 3 2 1 3]\n\n x = paddle.to_tensor([[2, 1, 3], [3, 0, 1], [2, 1, 3], [2, 1, 3]])\n output = paddle.unique_consecutive(x, axis=0) # \n np_output = output.numpy()\n # [[2 1 3]\n # [3 0 1]\n # [2 1 3]]\n \"\"\"\n\n if axis is None:\n axis = []\n else:\n axis = [axis]\n attr_dtype = convert_np_dtype_to_dtype_(dtype)\n if paddle.in_dynamic_mode():\n out, inverse, counts = _C_ops.unique_consecutive(\n x, 'dtype', attr_dtype, 'return_inverse', return_inverse,\n 'return_counts', return_counts, 'axis', axis)\n outs = [out]\n if return_inverse:\n outs.append(inverse)\n if return_counts:\n outs.append(counts)\n if len(outs) == 1:\n return outs[0]\n return tuple(outs)\n check_variable_and_dtype(x, \"input\",\n ['float32', 'float64', 'int32', 'int64'],\n 'unique_consecutive')\n check_type(return_inverse, 'return_inverse', bool, 'unique_consecutive')\n check_type(return_counts, 'return_counts', bool, 'unique_consecutive')\n check_dtype(dtype, 'dtype', ['int32', 'int64'], 'unique_consecutive')\n if len(axis) != 0:\n check_type(axis[0], 'axis', int, 'unique_consecutive')\n helper = LayerHelper('unique_consecutive', **locals())\n attrs = {\n 'dtype': attr_dtype,\n \"return_inverse\": return_inverse,\n \"return_counts\": return_counts,\n \"axis\": axis,\n }\n out = helper.create_variable_for_type_inference(\n dtype=x.dtype, stop_gradient=True)\n inverse = helper.create_variable_for_type_inference(\n dtype=attr_dtype, stop_gradient=True)\n counts = helper.create_variable_for_type_inference(\n dtype=attr_dtype, stop_gradient=True)\n outputs = {\"Out\": out, \"Index\": inverse, \"Counts\": counts}\n outs = [out]\n if return_inverse:\n outs.append(inverse)\n if return_counts:\n outs.append(counts)\n helper.append_op(\n type=\"unique_consecutive\",\n inputs={\"X\": x},\n attrs=attrs,\n outputs=outputs)\n if len(outs) == 1:\n return outs[0]\n return tuple(outs)\n\n\ndef unique(x,\n return_index=False,\n return_inverse=False,\n return_counts=False,\n axis=None,\n dtype=\"int64\",\n name=None):\n r\"\"\"\n Returns the unique elements of `x` in ascending order.\n\n Args:\n x(Tensor): The input tensor, it's data type should be float32, float64, int32, int64.\n return_index(bool, optional): If True, also return the indices of the input tensor that\n result in the unique Tensor.\n return_inverse(bool, optional): If True, also return the indices for where elements in\n the original input ended up in the returned unique tensor.\n return_counts(bool, optional): If True, also return the counts for each unique element.\n axis(int, optional): The axis to apply unique. If None, the input will be flattened.\n Default: None.\n dtype(np.dtype|str, optional): The date type of `indices` or `inverse` tensor: int32 or int64.\n Default: int64.\n name(str, optional): Name for the operation. For more information, please refer to\n :ref:`api_guide_Name`. Default: None.\n\n Returns: \n tuple: (out, indices, inverse, counts). `out` is the unique tensor for `x`. `indices` is \\\n provided only if `return_index` is True. `inverse` is provided only if `return_inverse` \\\n is True. `counts` is provided only if `return_counts` is True.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.to_tensor([2, 3, 3, 1, 5, 3])\n unique = paddle.unique(x)\n np_unique = unique.numpy() # [1 2 3 5]\n _, indices, inverse, counts = paddle.unique(x, return_index=True, return_inverse=True, return_counts=True)\n np_indices = indices.numpy() # [3 0 1 4]\n np_inverse = inverse.numpy() # [1 2 2 0 3 2]\n np_counts = counts.numpy() # [1 1 3 1]\n\n x = paddle.to_tensor([[2, 1, 3], [3, 0, 1], [2, 1, 3]])\n unique = paddle.unique(x)\n np_unique = unique.numpy() # [0 1 2 3]\n\n unique = paddle.unique(x, axis=0)\n np_unique = unique.numpy() \n # [[2 1 3]\n # [3 0 1]]\n \"\"\"\n if axis is None:\n axis = []\n else:\n axis = [axis]\n attr_dtype = convert_np_dtype_to_dtype_(dtype)\n if paddle.in_dynamic_mode():\n out, inverse, indices, counts = _C_ops.unique(\n x, 'dtype', attr_dtype, 'return_index', return_index,\n 'return_inverse', return_inverse, 'return_counts', return_counts,\n 'axis', axis, \"is_sorted\", True)\n outs = [out]\n if return_index:\n outs.append(indices)\n if return_inverse:\n outs.append(inverse)\n if return_counts:\n outs.append(counts)\n\n if len(outs) == 1:\n return outs[0]\n\n return tuple(outs)\n\n check_variable_and_dtype(x, \"input\",\n ['float32', 'float64', 'int32', 'int64'], 'unique')\n check_type(return_index, 'return_index', bool, 'unique')\n check_type(return_inverse, 'return_inverse', bool, 'unique')\n check_type(return_counts, 'return_counts', bool, 'unique')\n check_dtype(dtype, 'dtype', ['int32', 'int64'], 'unique')\n if len(axis) != 0:\n check_type(axis[0], 'axis', int, 'unique')\n\n helper = LayerHelper('unique', **locals())\n attrs = {\n 'dtype': attr_dtype,\n \"return_index\": return_index,\n \"return_inverse\": return_inverse,\n \"return_counts\": return_counts,\n \"axis\": axis,\n \"is_sorted\": True\n }\n out = helper.create_variable_for_type_inference(\n dtype=x.dtype, stop_gradient=True)\n indices = helper.create_variable_for_type_inference(\n dtype=attr_dtype, stop_gradient=True)\n inverse = helper.create_variable_for_type_inference(\n dtype=attr_dtype, stop_gradient=True)\n counts = helper.create_variable_for_type_inference(\n dtype=attr_dtype, stop_gradient=True)\n outputs = {\n \"Out\": out,\n \"Indices\": indices,\n \"Index\": inverse,\n \"Counts\": counts\n }\n outs = [out]\n if return_index:\n outs.append(indices)\n if return_inverse:\n outs.append(inverse)\n if return_counts:\n outs.append(counts)\n\n helper.append_op(\n type=\"unique\", inputs={\"X\": x}, attrs=attrs, outputs=outputs)\n\n if len(outs) == 1:\n return outs[0]\n\n return tuple(outs)\n\n\ndef unsqueeze(x, axis, name=None):\n \"\"\"\n Insert single-dimensional entries to the shape of input Tensor ``x``. Takes one\n required argument axis, a dimension or list of dimensions that will be inserted.\n Dimension indices in axis are as seen in the output tensor.\n\n Note that the output Tensor will share data with origin Tensor and doesn't have a \n Tensor copy in ``dygraph`` mode. If you want to use the Tensor copy version, \n please use `Tensor.clone` like ``unsqueeze_clone_x = x.unsqueeze(-1).clone()``.\n\n Args:\n x (Tensor): The input Tensor to be unsqueezed. Supported data type: float32, float64, bool, int8, int32, int64.\n axis (int|list|tuple|Tensor): Indicates the dimensions to be inserted. The data type is ``int32`` . \n If ``axis`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. \n If ``axis`` is a Tensor, it should be an 1-D Tensor .\n If ``axis`` is negative, ``axis = axis + ndim(x) + 1``.\n name (str|None): Name for this layer. Please refer to :ref:`api_guide_Name`, Default None.\n\n Returns:\n Tensor: Unsqueezed Tensor with the same data type as input Tensor.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.rand([5, 10])\n print(x.shape) # [5, 10]\n \n out1 = paddle.unsqueeze(x, axis=0)\n print(out1.shape) # [1, 5, 10]\n \n out2 = paddle.unsqueeze(x, axis=[0, 2]) \n print(out2.shape) # [1, 5, 1, 10]\n\n axis = paddle.to_tensor([0, 1, 2])\n out3 = paddle.unsqueeze(x, axis=axis) \n print(out3.shape) # [1, 1, 1, 5, 10]\n\n # out1, out2, out3 share data with x in dygraph mode\n x[0, 0] = 10.\n print(out1[0, 0, 0]) # [10.]\n print(out2[0, 0, 0, 0]) # [10.]\n print(out3[0, 0, 0, 0, 0]) # [10.]\n \n \"\"\"\n\n return layers.unsqueeze(x, axis, name)\n\n\n@inplace_apis_in_dygraph_only\ndef unsqueeze_(x, axis, name=None):\n \"\"\"\n Inplace version of ``unsqueeze`` API, the output Tensor will be inplaced with input ``x``.\n Please refer to :ref:`api_paddle_tensor_unsqueeze`.\n \"\"\"\n if isinstance(axis, int):\n axis = [axis]\n elif isinstance(axis, Variable):\n axis = axis.numpy().tolist()\n elif isinstance(axis, (list, tuple)):\n axis = [\n item.numpy().item(0) if isinstance(item, Variable) else item\n for item in axis\n ]\n out, _ = _C_ops.unsqueeze2_(x, 'axes', axis)\n return out\n\n\ndef gather(x, index, axis=None, name=None):\n \"\"\"\n Output is obtained by gathering entries of ``axis``\n of ``x`` indexed by ``index`` and concatenate them together.\n\n .. code-block:: text\n\n\n Given:\n\n x = [[1, 2],\n [3, 4],\n [5, 6]]\n\n index = [1, 2]\n axis=[0]\n\n Then:\n\n out = [[3, 4],\n [5, 6]] \n\n Args:\n x (Tensor): The source input tensor with rank>=1. Supported data type is\n int32, int64, float32, float64 and uint8 (only for CPU),\n float16 (only for GPU).\n index (Tensor): The index input tensor with rank=1. Data type is int32 or int64.\n axis (Tensor|int, optional): The axis of input to be gathered, it's can be int or a Tensor with data type is int32 or int64. The default value is None, if None, the ``axis`` is 0.\n name (str, optional): The default value is None. Normally there is no need for user to set this property.\n For more information, please refer to :ref:`api_guide_Name` .\n\n Returns:\n output (Tensor): The output is a tensor with the same rank as ``x``.\n \n Examples:\n\n .. code-block:: python\n\n import paddle\n\n input = paddle.to_tensor([[1,2],[3,4],[5,6]])\n index = paddle.to_tensor([0,1])\n output = paddle.gather(input, index, axis=0)\n # expected output: [[1,2],[3,4]]\n \"\"\"\n if axis is None:\n axis = 0\n\n if paddle.in_dynamic_mode():\n axis = axis.item() if isinstance(axis, paddle.Tensor) else axis\n return _C_ops.gather(x, index, None, \"axis\", axis, \"overwrite\", False)\n\n check_variable_and_dtype(\n x, 'x',\n ['float16', 'float32', 'float64', 'int16', 'int32', 'int64', 'uint8'],\n 'gather')\n check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'gather')\n\n if isinstance(axis, Variable):\n check_variable_and_dtype(axis, 'axis', ['int32', 'int64'], 'gather')\n\n helper = LayerHelper('gather', **locals())\n dtype = helper.input_dtype('x')\n out = helper.create_variable_for_type_inference(dtype)\n if not isinstance(axis, Variable):\n helper.append_op(\n type=\"gather\",\n inputs={\"X\": x,\n \"Index\": index},\n attrs={'axis': axis,\n 'overwrite': False},\n outputs={\"Out\": out})\n else:\n helper.append_op(\n type=\"gather\",\n inputs={\"X\": x,\n \"Index\": index,\n \"Axis\": axis},\n attrs={\"overwrite\": False},\n outputs={\"Out\": out})\n\n return out\n\n\ndef unbind(input, axis=0):\n \"\"\"\n\n Removes a tensor dimension, then split the input tensor into multiple sub-Tensors.\n\n Args:\n input (Tensor): The input variable which is an N-D Tensor, data type being float32, float64, int32 or int64.\n axis (int32|int64, optional): A scalar with type ``int32|int64`` shape [1]. The dimension along which to unbind. \n If :math:`axis < 0`, the dimension to unbind along is :math:`rank(input) + axis`. Default is 0.\n Returns:\n list(Tensor): The list of segmented Tensor variables.\n\n Example:\n .. code-block:: python\n\n import paddle\n import numpy as np\n # input is a variable which shape is [3, 4, 5]\n np_input = np.random.rand(3, 4, 5).astype('float32')\n input = paddle.to_tensor(np_input)\n [x0, x1, x2] = paddle.unbind(input, axis=0)\n # x0.shape [4, 5]\n # x1.shape [4, 5]\n # x2.shape [4, 5]\n [x0, x1, x2, x3] = paddle.unbind(input, axis=1)\n # x0.shape [3, 5]\n # x1.shape [3, 5]\n # x2.shape [3, 5]\n # x3.shape [3, 5]\n\n \"\"\"\n if not isinstance(axis, (int)):\n raise TypeError(\"The type of 'axis' must be int, but received %s.\" %\n (type(axis)))\n if isinstance(axis, np.generic):\n axis = np.asscalar(axis)\n input_shape = input.shape\n axis_ = axis if axis >= 0 else len(input_shape) + axis\n num = input_shape[axis_]\n if paddle.in_dynamic_mode():\n return _C_ops.unbind(input, num, 'axis', axis)\n\n helper = LayerHelper(\"unbind\", **locals())\n check_type(input, 'input', (Variable), 'unbind')\n dtype = helper.input_dtype()\n check_dtype(dtype, 'unbind', ['float32', 'float64', 'int32', 'int64'],\n 'unbind')\n outs = [\n helper.create_variable_for_type_inference(dtype=helper.input_dtype())\n for i in range(num)\n ]\n helper.append_op(\n type=\"unbind\",\n inputs={\"X\": input},\n outputs={\"Out\": outs},\n attrs={\"axis\": axis})\n return outs\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\n **NOTICE**: The order in which updates are applied is nondeterministic, \n so the output will be nondeterministic if index contains duplicates.\n\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 \n If True, use the overwrite mode to update the output of the same index,\n\t if False, use the accumulate mode to update the output of the same index.Default value is True.\n \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\n Examples:\n .. code-block:: python\n \n import paddle\n\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\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 _C_ops.final_state_scatter(x, index, updates, overwrite)\n else:\n if _in_legacy_dygraph():\n return _C_ops.scatter(x, index, updates, 'overwrite', overwrite)\n else:\n check_variable_and_dtype(\n x, 'dtype',\n ['float32', 'float64', 'float16', 'int32', 'int64'], '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\n@inplace_apis_in_dygraph_only\ndef scatter_(x, index, updates, overwrite=True, name=None):\n \"\"\"\n Inplace version of ``scatter`` API, the output Tensor will be inplaced with input ``x``.\n Please refer to :ref:`api_paddle_tensor_scatter`.\n \"\"\"\n return _C_ops.scatter_(x, index, updates, 'overwrite', overwrite)\n\n\ndef scatter_nd_add(x, index, updates, name=None):\n r\"\"\"\n **Scatter_nd_add Layer**\n\n Output is obtained by applying sparse addition to a single value\n or slice in a Tensor.\n\n :attr:`x` is a Tensor with ndim :math:`R`\n and :attr:`index` is a Tensor with ndim :math:`K` . Thus, :attr:`index`\n has shape :math:`[i_0, i_1, ..., i_{K-2}, Q]` where :math:`Q \\leq R` . :attr:`updates`\n is a Tensor with ndim :math:`K - 1 + R - Q` and its\n shape is :math:`index.shape[:-1] + x.shape[index.shape[-1]:]` .\n\n According to the :math:`[i_0, i_1, ..., i_{K-2}]` of :attr:`index` ,\n add the corresponding :attr:`updates` slice to the :attr:`x` slice\n which is obtained by the last one dimension of :attr:`index` .\n\n .. code-block:: text\n\n Given:\n\n * Case 1:\n x = [0, 1, 2, 3, 4, 5]\n index = [[1], [2], [3], [1]]\n updates = [9, 10, 11, 12]\n\n we get:\n\n output = [0, 22, 12, 14, 4, 5]\n\n * Case 2:\n x = [[65, 17], [-14, -25]]\n index = [[], []]\n updates = [[[-1, -2], [1, 2]],\n [[3, 4], [-3, -4]]]\n x.shape = (2, 2)\n index.shape = (2, 0)\n updates.shape = (2, 2, 2)\n\n we get:\n\n output = [[67, 19], [-16, -27]]\n\n Args:\n x (Tensor): The x input. Its dtype should be int32, int64, float32, float64.\n index (Tensor): The index input with ndim > 1 and index.shape[-1] <= x.ndim.\n Its dtype should be int32 or int64 as it is used as indexes.\n updates (Tensor): The updated value of scatter_nd_add op, and it must have the same dtype\n as x. It must have the shape index.shape[:-1] + x.shape[index.shape[-1]:].\n name (str|None): The output tensor name. If set None, the layer will be named automatically.\n\n Returns:\n output (Tensor): The output is a tensor with the same shape and dtype as x.\n\n Examples:\n\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n x = paddle.rand(shape=[3, 5, 9, 10], dtype='float32')\n updates = paddle.rand(shape=[3, 9, 10], dtype='float32')\n index_data = np.array([[1, 1],\n [0, 1],\n [1, 3]]).astype(np.int64)\n index = paddle.to_tensor(index_data)\n output = paddle.scatter_nd_add(x, index, updates)\n \"\"\"\n return layers.scatter_nd_add(x, index, updates, name=None)\n\n\ndef chunk(x, chunks, axis=0, name=None):\n \"\"\"\n Split the input tensor into multiple sub-Tensors.\n \n Args:\n x (Tensor): A N-D Tensor. The data type is bool, float16, float32, float64, int32 or int64.\n chunks(int): The number of tensor to be split along the certain axis.\n axis (int|Tensor, optional): The axis along which to split, it can be a scalar with type \n ``int`` or a ``Tensor`` with shape [1] and data type ``int32`` or ``int64``.\n If :math::`axis < 0`, the axis to split along is :math:`rank(x) + axis`. Default is 0.\n name (str, optional): The default value is None. Normally there is no need for user to set this property.\n For more information, please refer to :ref:`api_guide_Name` .\n Returns:\n list(Tensor): The list of segmented Tensors.\n \n Example:\n .. code-block:: python\n \n import numpy as np\n import paddle\n \n # x is a Tensor which shape is [3, 9, 5]\n x_np = np.random.random([3, 9, 5]).astype(\"int32\")\n x = paddle.to_tensor(x_np)\n\n out0, out1, out2 = paddle.chunk(x, chunks=3, axis=1)\n # out0.shape [3, 3, 5]\n # out1.shape [3, 3, 5]\n # out2.shape [3, 3, 5]\n\n \n # axis is negative, the real axis is (rank(x) + axis) which real\n # value is 1.\n out0, out1, out2 = paddle.chunk(x, chunks=3, axis=-2)\n # out0.shape [3, 3, 5]\n # out1.shape [3, 3, 5]\n # out2.shape [3, 3, 5]\n \"\"\"\n check_type(chunks, 'chunks', (int), 'chunk')\n return paddle.fluid.layers.split(\n input=x, num_or_sections=chunks, dim=axis, name=name)\n\n\ndef tile(x, repeat_times, name=None):\n \"\"\"\n\n Construct a new Tensor by repeating ``x`` the number of times given by ``repeat_times``.\n After tiling, the value of the i'th dimension of the output is equal to ``x.shape[i]*repeat_times[i]``.\n\n Both the number of dimensions of ``x`` and the number of elements in ``repeat_times`` should be less than or equal to 6.\n\n Args:\n x (Tensor): The input tensor, its data type should be bool, float32, float64, int32 or int64.\n repeat_times (list|tuple|Tensor): The number of repeating times. If repeat_times is a list or tuple, all its elements\n should be integers or 1-D Tensors with the data type int32. If repeat_times is a Tensor, it should be an 1-D Tensor with the data type int32.\n name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n N-D Tensor. The data type is the same as ``x``. The size of the i-th dimension is equal to ``x[i] * repeat_times[i]``.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n data = paddle.to_tensor([1, 2, 3], dtype='int32')\n out = paddle.tile(data, repeat_times=[2, 1])\n np_out = out.numpy()\n # [[1, 2, 3]\n # [1, 2, 3]]\n\n out = paddle.tile(data, repeat_times=(2, 2))\n np_out = out.numpy()\n # [[1, 2, 3, 1, 2, 3]\n # [1, 2, 3, 1, 2, 3]]\n\n repeat_times = paddle.to_tensor([1, 2], dtype='int32')\n out = paddle.tile(data, repeat_times=repeat_times)\n np_out = out.numpy()\n # [[1, 2, 3, 1, 2, 3]]\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.tile(x, 'repeat_times', repeat_times)\n check_type(repeat_times, 'repeat_times', (list, tuple, Variable), 'tile')\n if isinstance(repeat_times, Variable):\n assert len(repeat_times.shape) == 1, (\n 'repeat_times must be an 1-D Tensor.')\n else:\n for elem in repeat_times:\n if isinstance(elem, Variable):\n assert len(elem.shape) == 1, (\n 'Elements in repeat_times must be 1-D Tensors or integers.')\n else:\n type_tuple = (int, np.int32, np.int64)\n assert isinstance(elem, type_tuple), (\n 'Elements in repeat_times must be 1-D Tensors or integers.')\n\n check_variable_and_dtype(\n x, 'x', ['bool', 'float32', 'float64', 'int32', 'int64'], 'tile')\n if convert_dtype(x.dtype) == 'bool' and x.stop_gradient == False:\n raise ValueError(\n \"When the date type is bool for the input 'x' of tile op, you \"\n \"must set its stop_gradient to be True by \"\n \"some_var.stop_gradient == True supporting some_var is the input.\")\n\n helper = LayerHelper('tile', **locals())\n\n inputs = {\"X\": [x]}\n attrs = {}\n\n def get_attr_repeat_times(list_repeat_times):\n attrs_repeat_times = []\n for idx, times in enumerate(list_repeat_times):\n if isinstance(times, Variable):\n attrs_repeat_times.append(-1)\n else:\n attrs_repeat_times.append(times)\n assert times > 0, (\n \"All elements in repeat_times must be positive for tile.\")\n return attrs_repeat_times\n\n if isinstance(repeat_times, Variable):\n repeat_times.stop_gradient = True\n inputs['RepeatTimes'] = repeat_times\n attrs['repeat_times'] = [-1]\n elif isinstance(repeat_times, (list, tuple)):\n attrs['repeat_times'] = get_attr_repeat_times(repeat_times)\n if utils._contain_var(repeat_times):\n inputs['repeat_times_tensor'] = utils._convert_to_tensor_list(\n repeat_times)\n\n dtype = helper.input_dtype(input_param_name='x')\n out = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='tile', inputs=inputs, outputs={'Out': out}, attrs=attrs)\n return out\n\n\ndef expand_as(x, y, name=None):\n \"\"\"\n\n Expand the input tensor ``x`` to the same shape as the input tensor ``y``.\n\n Both the number of dimensions of ``x`` and ``y`` must be less than or equal to 6, and the number of dimensions of ``y`` must be greather than or equal to that of ``x``. The dimension to expand must have a value of 1.\n\n Args:\n x (Tensor): The input tensor, its data type is bool, float32, float64, int32 or int64.\n y (Tensor): The input tensor that gives the shape to expand to.\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 N-D Tensor: A Tensor with the same shape as ``y``. The data type is the same as ``x``.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n data_x = paddle.to_tensor([1, 2, 3], 'int32')\n data_y = paddle.to_tensor([[1, 2, 3], [4, 5, 6]], 'int32')\n out = paddle.expand_as(data_x, data_y)\n np_out = out.numpy()\n # [[1, 2, 3], [1, 2, 3]]\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.expand_as_v2(x, 'target_shape', y.shape)\n\n check_variable_and_dtype(\n x, 'x', ['bool', 'float32', 'float64', 'int32', 'int64'], 'expand_as')\n check_type(y, 'y', Variable, 'expand_as')\n\n if convert_dtype(x.dtype) == 'bool' and x.stop_gradient == False:\n raise ValueError(\n \"When the data type of input 'x' for expand_as is bool, \"\n \"you must set its stop_gradient to be False by \"\n \"some_var.stop_gradient = True, supporting \"\n \"some_var as the input 'x'.\")\n inputs = {\"X\": [x], \"Y\": [y]}\n\n helper = LayerHelper('expand_as', **locals())\n dtype = helper.input_dtype(input_param_name='x')\n out = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='expand_as_v2',\n inputs=inputs,\n attrs={'target_shape': y.shape},\n outputs={'Out': out})\n return out\n\n\ndef broadcast_to(x, shape, name=None):\n \"\"\"\n\n Broadcast the input tensor to a given shape.\n\n Both the number of dimensions of ``x`` and the number of elements in ``shape`` should be less than or equal to 6. The dimension to broadcast to must have a value 1.\n\n\n Args:\n x (Tensor): The input tensor, its data type is bool, float32, float64, int32 or int64.\n shape (list|tuple|Tensor): The result shape after broadcasting. The data type is int32. If shape is a list or tuple, all its elements\n should be integers or 1-D Tensors with the data type int32. If shape is a Tensor, it should be an 1-D Tensor with the data type int32. \n The value -1 in shape means keeping the corresponding dimension unchanged.\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 N-D Tensor: A Tensor with the given shape. The data type is the same as ``x``.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n data = paddle.to_tensor([1, 2, 3], dtype='int32')\n out = paddle.broadcast_to(data, shape=[2, 3])\n print(out)\n # [[1, 2, 3], [1, 2, 3]]\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.expand_v2(x, 'shape', shape)\n\n if isinstance(shape, Variable):\n assert len(shape.shape) == 1, ('shape must be an 1-D Tensor.')\n else:\n for elem in shape:\n if isinstance(elem, Variable):\n assert len(elem.shape) == 1, (\n 'Elements in shape must be 1-D Tensors or integers.')\n else:\n type_tuple = (int, np.int32, np.int64)\n assert isinstance(elem, type_tuple), (\n 'Elements in shape must be 1-D Tensors or integers.')\n\n check_variable_and_dtype(x, 'x',\n ['bool', 'float32', 'float64', 'int32', 'int64'],\n 'broadcast_to')\n check_type(shape, 'shape', (list, tuple, Variable), 'broadcast_to')\n if convert_dtype(x.dtype) == 'bool' and x.stop_gradient == False:\n raise ValueError(\n \"When the data type of input 'x' for broadcast_to is bool, \"\n \"you must set its stop_gradient to be False by \"\n \"some_var.stop_gradient = True, supporting \"\n \"some_var as the input.\")\n\n inputs = {\"X\": [x]}\n attrs = {}\n\n helper = LayerHelper('expand', **locals())\n\n def get_attr_expand_shape(list_expand_shape):\n attrs_expand_shape = []\n for idx, shape in enumerate(list_expand_shape):\n if isinstance(shape, Variable):\n attrs_expand_shape.append(-1)\n else:\n attrs_expand_shape.append(shape)\n assert shape > 0 or shape == -1, (\n \"All elements in shape of broadcast_to must be positive or -1.\"\n )\n return attrs_expand_shape\n\n if isinstance(shape, Variable):\n shape.stop_gradient = True\n inputs['Shape'] = shape\n elif isinstance(shape, (list, tuple)):\n attrs['shape'] = get_attr_expand_shape(shape)\n if utils._contain_var(shape):\n inputs['expand_shapes_tensor'] = utils._convert_to_tensor_list(\n shape)\n\n dtype = helper.input_dtype(input_param_name='x')\n out = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='expand_v2', inputs=inputs, outputs={'Out': out}, attrs=attrs)\n return out\n\n\ndef expand(x, shape, name=None):\n \"\"\"\n\n Expand the input tensor to a given shape.\n\n Both the number of dimensions of ``x`` and the number of elements in ``shape`` should be less than or equal to 6. The dimension to expand must have a value 1.\n\n\n Args:\n x (Tensor): The input tensor, its data type is bool, float32, float64, int32 or int64.\n shape (list|tuple|Tensor): The result shape after expanding. The data type is int32. If shape is a list or tuple, all its elements\n should be integers or 1-D Tensors with the data type int32. If shape is a Tensor, it should be an 1-D Tensor with the data type int32. \n The value -1 in shape means keeping the corresponding dimension unchanged.\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 N-D Tensor: A Tensor with the given shape. The data type is the same as ``x``.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n data = paddle.to_tensor([1, 2, 3], dtype='int32')\n out = paddle.expand(data, shape=[2, 3])\n print(out)\n # [[1, 2, 3], [1, 2, 3]]\n \"\"\"\n if paddle.in_dynamic_mode():\n return _C_ops.expand_v2(x, 'shape', shape)\n\n if isinstance(shape, Variable):\n assert len(shape.shape) == 1, ('shape must be an 1-D Tensor.')\n else:\n for elem in shape:\n if isinstance(elem, Variable):\n assert len(elem.shape) == 1, (\n 'Elements in shape must be 1-D Tensors or integers.')\n else:\n type_tuple = (int, np.int32, np.int64)\n assert isinstance(elem, type_tuple), (\n 'Elements in shape must be 1-D Tensors or integers.')\n\n check_variable_and_dtype(\n x, 'x', ['bool', 'float16', 'float32', 'float64', 'int32', 'int64'],\n 'expand')\n check_type(shape, 'shape', (list, tuple, Variable), 'expand')\n if convert_dtype(x.dtype) == 'bool' and x.stop_gradient == False:\n raise ValueError(\"When the data type of input 'x' for expand is bool, \"\n \"you must set its stop_gradient to be False by \"\n \"some_var.stop_gradient = True, supporting \"\n \"some_var as the input.\")\n\n inputs = {\"X\": [x]}\n attrs = {}\n\n helper = LayerHelper('expand', **locals())\n\n def get_attr_expand_shape(list_expand_shape):\n attrs_expand_shape = []\n for idx, shape in enumerate(list_expand_shape):\n if isinstance(shape, Variable):\n attrs_expand_shape.append(-2)\n else:\n attrs_expand_shape.append(shape)\n assert shape > 0 or shape == -1, (\n \"All elements in shape of expand must be positive or -1.\")\n return attrs_expand_shape\n\n if isinstance(shape, Variable):\n shape.stop_gradient = True\n inputs['Shape'] = shape\n elif isinstance(shape, (list, tuple)):\n attrs['shape'] = get_attr_expand_shape(shape)\n if utils._contain_var(shape):\n inputs['expand_shapes_tensor'] = utils._convert_to_tensor_list(\n shape)\n\n dtype = helper.input_dtype(input_param_name='x')\n out = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type='expand_v2', inputs=inputs, outputs={'Out': out}, attrs=attrs)\n return out\n\n\ndef reshape(x, shape, name=None):\n \"\"\"\n This operator changes the shape of ``x`` without changing its data.\n\n Note that the output Tensor will share data with origin Tensor and doesn't\n have a Tensor copy in ``dygraph`` mode. \n If you want to use the Tensor copy version, please use `Tensor.clone` like \n ``reshape_clone_x = x.reshape([-1]).clone()``.\n\n Some tricks exist when specifying the target shape.\n\n 1. -1 means the value of this dimension is inferred from the total element\n number of x and remaining dimensions. Thus one and only one dimension can\n be set -1.\n\n 2. 0 means the actual dimension value is going to be copied from the\n corresponding dimension of x. The index of 0s in shape can not exceed\n the dimension of x.\n\n Here are some examples to explain it.\n\n 1. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape\n is [6, 8], the reshape operator will transform x into a 2-D tensor with\n shape [6, 8] and leaving x's data unchanged.\n\n 2. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape\n specified is [2, 3, -1, 2], the reshape operator will transform x into a\n 4-D tensor with shape [2, 3, 4, 2] and leaving x's data unchanged. In this\n case, one dimension of the target shape is set to -1, the value of this\n dimension is inferred from the total element number of x and remaining\n dimensions.\n\n 3. Given a 3-D tensor x with a shape [2, 4, 6], and the target shape\n is [-1, 0, 3, 2], the reshape operator will transform x into a 4-D tensor\n with shape [2, 4, 3, 2] and leaving x's data unchanged. In this case,\n besides -1, 0 means the actual dimension value is going to be copied from\n the corresponding dimension of x.\n\n Args:\n x(Tensor): An N-D Tensor. The data type is ``float32``, ``float64``, ``int32``, ``int64`` or ``bool``\n shape(list|tuple|Tensor): Define the target shape. At most one dimension of the target shape can be -1.\n The data type is ``int32`` . If ``shape`` is a list or tuple, the elements of it should be integers or Tensors with shape [1].\n If ``shape`` is an Tensor, it should be an 1-D Tensor .\n name(str, optional): The default value is None. Normally there is no need for user to set this property.\n For more information, please refer to :ref:`api_guide_Name` .\n\n Returns:\n Tensor: A reshaped Tensor with the same data type as ``x``.\n\n Examples:\n .. code-block:: python\n\n import numpy as np\n import paddle\n\n x = paddle.rand([2, 4, 6], dtype=\"float32\")\n positive_four = paddle.full([1], 4, \"int32\")\n\n out = paddle.reshape(x, [-1, 0, 3, 2])\n print(out)\n # the shape is [2,4,3,2].\n\n out = paddle.reshape(x, shape=[positive_four, 12])\n print(out)\n # the shape of out_2 is [4, 12].\n\n shape_tensor = paddle.to_tensor(np.array([8, 6]).astype(\"int32\"))\n out = paddle.reshape(x, shape=shape_tensor)\n print(out)\n # the shape is [8, 6].\n # out shares data with x in dygraph mode\n x[0, 0, 0] = 10.\n print(out[0, 0])\n # the value is [10.]\n\n \"\"\"\n return paddle.fluid.layers.reshape(x=x, shape=shape, name=name)\n\n\n@inplace_apis_in_dygraph_only\ndef reshape_(x, shape, name=None):\n \"\"\"\n Inplace version of ``reshape`` API, the output Tensor will be inplaced with input ``x``.\n Please refer to :ref:`api_paddle_tensor_reshape`.\n \"\"\"\n if isinstance(shape, (list, tuple)):\n shape = [\n item.numpy().item(0) if isinstance(item, Variable) else item\n for item in shape\n ]\n out, _ = _C_ops.reshape2_(x, None, 'shape', shape)\n return out\n elif isinstance(shape, Variable):\n shape.stop_gradient = True\n out, _ = _C_ops.reshape2_(x, shape)\n return out\n\n\ndef gather_nd(x, index, name=None):\n \"\"\"\n\n This function is actually a high-dimensional extension of :code:`gather`\n and supports for simultaneous indexing by multiple axes. :attr:`index` is a\n K-dimensional integer tensor, which is regarded as a (K-1)-dimensional\n tensor of :attr:`index` into :attr:`input`, where each element defines\n a slice of params:\n\n .. math::\n\n output[(i_0, ..., i_{K-2})] = input[index[(i_0, ..., i_{K-2})]]\n\n Obviously, :code:`index.shape[-1] <= input.rank` . And, the output tensor has\n shape :code:`index.shape[:-1] + input.shape[index.shape[-1]:]` .\n\n .. code-block:: text\n\n Given:\n x = [[[ 0, 1, 2, 3],\n [ 4, 5, 6, 7],\n [ 8, 9, 10, 11]],\n [[12, 13, 14, 15],\n [16, 17, 18, 19],\n [20, 21, 22, 23]]]\n x.shape = (2, 3, 4)\n\n * Case 1:\n index = [[1]]\n\n gather_nd(x, index)\n = [x[1, :, :]]\n = [[12, 13, 14, 15],\n [16, 17, 18, 19],\n [20, 21, 22, 23]]\n\n * Case 2:\n index = [[0,2]]\n\n gather_nd(x, index)\n = [x[0, 2, :]]\n = [8, 9, 10, 11]\n\n * Case 3:\n index = [[1, 2, 3]]\n\n gather_nd(x, index)\n = [x[1, 2, 3]]\n = [23]\n\n Args:\n x (Tensor): The input Tensor which it's data type should be bool, float32, float64, int32, int64.\n index (Tensor): The index input with rank > 1, index.shape[-1] <= input.rank.\n Its dtype should be int32, int64.\n name(str, optional): The default value is None. Normally there is no need for user to set this property.\n For more information, please refer to :ref:`api_guide_Name` .\n\n Returns:\n output (Tensor): A tensor with the shape index.shape[:-1] + input.shape[index.shape[-1]:]\n \n Examples:\n\n .. code-block:: python\n \n import paddle\n \n x = paddle.to_tensor([[[1, 2], [3, 4], [5, 6]],\n [[7, 8], [9, 10], [11, 12]]])\n index = paddle.to_tensor([[0, 1]])\n \n output = paddle.gather_nd(x, index) #[[3, 4]]\n\n \"\"\"\n\n return paddle.fluid.layers.gather_nd(input=x, index=index, name=name)\n\n\ndef strided_slice(x, axes, starts, ends, strides, name=None):\n \"\"\"\n This operator produces a slice of ``x`` along multiple axes. Similar to numpy:\n https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html\n Slice uses ``axes``, ``starts`` and ``ends`` attributes to specify the start and\n end dimension for each axis in the list of axes and Slice uses this information\n to slice the input data tensor. If a negative value is passed to\n ``starts`` or ``ends`` such as :math:`-i`, it represents the reverse position of the\n axis :math:`i-1` th(here 0 is the initial position). The ``strides`` represents steps of\n slicing and if the ``strides`` is negative, slice operation is in the opposite direction.\n If the value passed to ``starts`` or ``ends`` is greater than n\n (the number of elements in this dimension), it represents n.\n For slicing to the end of a dimension with unknown size, it is recommended\n to pass in INT_MAX. The size of ``axes`` must be equal to ``starts`` , ``ends`` and ``strides``.\n Following examples will explain how strided_slice works:\n\n .. code-block:: text\n\n Case1:\n Given:\n data = [ [1, 2, 3, 4], [5, 6, 7, 8], ]\n axes = [0, 1]\n starts = [1, 0]\n ends = [2, 3]\n strides = [1, 1]\n Then:\n result = [ [5, 6, 7], ]\n\n Case2:\n Given:\n data = [ [1, 2, 3, 4], [5, 6, 7, 8], ]\n axes = [0, 1]\n starts = [0, 1]\n ends = [2, 0]\n strides = [1, -1]\n Then:\n result = [ [8, 7, 6], ]\n Case3:\n Given:\n data = [ [1, 2, 3, 4], [5, 6, 7, 8], ]\n axes = [0, 1]\n starts = [0, 1]\n ends = [-1, 1000]\n strides = [1, 3]\n Then:\n result = [ [2], ]\n\n Args:\n x (Tensor): An N-D ``Tensor``. The data type is ``float32``, ``float64``, ``int32`` or ``int64``.\n axes (list|tuple): The data type is ``int32`` . Axes that `starts` and `ends` apply to.\n It's optional. If it is not provides, it will be treated as :math:`[0,1,...,len(starts)-1]`.\n starts (list|tuple|Tensor): The data type is ``int32`` . If ``starts`` is a list or tuple, the elements of it should be integers or Tensors with shape [1]. If ``starts`` is an Tensor, it should be an 1-D Tensor. It represents starting indices of corresponding axis in ``axes``.\n ends (list|tuple|Tensor): The data type is ``int32`` . If ``ends`` is a list or tuple, the elements of\n it should be integers or Tensors with shape [1]. If ``ends`` is an Tensor, it should be an 1-D Tensor . It represents ending indices of corresponding axis in ``axes``.\n strides (list|tuple|Tensor): The data type is ``int32`` . If ``strides`` is a list or tuple, the elements of\n it should be integers or Tensors with shape [1]. If ``strides`` is an Tensor, it should be an 1-D Tensor . It represents slice step of corresponding axis in ``axes``.\n name(str, optional): The default value is None. Normally there is no need for user to set this property.\n For more information, please refer to :ref:`api_guide_Name` .\n\n Returns:\n Tensor: A ``Tensor`` with the same dimension as ``x``. The data type is same as ``x``.\n\n Examples:\n .. code-block:: python\n\n import paddle\n x = paddle.zeros(shape=[3,4,5,6], dtype=\"float32\")\n # example 1:\n # attr starts is a list which doesn't contain Tensor.\n axes = [1, 2, 3]\n starts = [-3, 0, 2]\n ends = [3, 2, 4]\n strides_1 = [1, 1, 1]\n strides_2 = [1, 1, 2]\n sliced_1 = paddle.strided_slice(x, axes=axes, starts=starts, ends=ends, strides=strides_1)\n # sliced_1 is x[:, 1:3:1, 0:2:1, 2:4:1]. \n # example 2:\n # attr starts is a list which contain tensor Tensor.\n minus_3 = paddle.full(shape=[1], fill_value=-3, dtype='int32')\n sliced_2 = paddle.strided_slice(x, axes=axes, starts=[minus_3, 0, 2], ends=ends, strides=strides_2)\n # sliced_2 is x[:, 1:3:1, 0:2:1, 2:4:2].\n \"\"\"\n\n return paddle.fluid.layers.strided_slice(\n input=x, axes=axes, starts=starts, ends=ends, strides=strides)\n\n\ndef tensordot(x, y, axes=2, name=None):\n r\"\"\"\n This function computes a contraction, which sum the product of elements from two tensors along the given axes. \n\n Args:\n x (Tensor): The left tensor for contraction with data type ``float32`` or ``float64``.\n y (Tensor): The right tensor for contraction with the same data type as ``x``.\n axes (int|tuple|list|Tensor, optional): The axes to contract for ``x`` and ``y``, defaulted to integer ``2``.\n\n 1. It could be a non-negative integer ``n``, \n in which the function will sum over the last ``n`` axes of ``x`` and the first ``n`` axes of ``y`` in order.\n \n 2. It could be a 1-d tuple or list with data type ``int``, in which ``x`` and ``y`` will be contracted along the same given axes. \n For example, ``axes`` =[0, 1] applies contraction along the first two axes for ``x`` and the first two axes for ``y``.\n \n 3. It could be a tuple or list containing one or two 1-d tuple|list|Tensor with data type ``int``. \n When containing one tuple|list|Tensor, the data in tuple|list|Tensor specified the same axes for ``x`` and ``y`` to contract. \n When containing two tuple|list|Tensor, the first will be applied to ``x`` and the second to ``y``. \n When containing more than two tuple|list|Tensor, only the first two axis sequences will be used while the others will be ignored.\n \n 4. It could be a tensor, in which the ``axes`` tensor will be translated to a python list \n and applied the same rules described above to determine the contraction axes. \n Note that the ``axes`` with Tensor type is ONLY available in Dygraph mode.\n name(str, optional): The default value is None. Normally there is no need for user to set this property. \n For more information, please refer to :ref:`api_guide_Name` .\n\n Return: \n Output (Tensor): The contraction result with the same data type as ``x`` and ``y``. \n In general, :math:`output.ndim = x.ndim + y.ndim - 2 \\times n_{axes}`, where :math:`n_{axes}` denotes the number of axes to be contracted.\n \n NOTES:\n 1. This function supports tensor broadcast, \n the size in the corresponding dimensions of ``x`` and ``y`` should be equal, or applies to the broadcast rules.\n 2. This function also supports axes expansion, \n when the two given axis sequences for ``x`` and ``y`` are of different lengths, \n the shorter sequence will expand the same axes as the longer one at the end. \n For example, if ``axes`` =[[0, 1, 2, 3], [1, 0]], \n the axis sequence for ``x`` is [0, 1, 2, 3], \n while the corresponding axis sequences for ``y`` will be expanded from [1, 0] to [1, 0, 2, 3].\n \n Examples:\n .. code-block:: python\n\n import paddle\n\n data_type = 'float64'\n\n # For two 2-d tensor x and y, the case axes=0 is equivalent to outer product.\n # Note that tensordot supports empty axis sequence, so all the axes=0, axes=[], axes=[[]], and axes=[[],[]] are equivalent cases. \n x = paddle.arange(4, dtype=data_type).reshape([2, 2])\n y = paddle.arange(4, dtype=data_type).reshape([2, 2])\n z = paddle.tensordot(x, y, axes=0)\n # z = [[[[0., 0.],\n # [0., 0.]],\n #\n # [[0., 1.],\n # [2., 3.]]],\n #\n #\n # [[[0., 2.],\n # [4., 6.]],\n #\n # [[0., 3.],\n # [6., 9.]]]]\n\n\n # For two 1-d tensor x and y, the case axes=1 is equivalent to inner product.\n x = paddle.arange(10, dtype=data_type)\n y = paddle.arange(10, dtype=data_type)\n z1 = paddle.tensordot(x, y, axes=1)\n z2 = paddle.dot(x, y)\n # z1 = z2 = [285.]\n\n\n # For two 2-d tensor x and y, the case axes=1 is equivalent to matrix multiplication.\n x = paddle.arange(6, dtype=data_type).reshape([2, 3])\n y = paddle.arange(12, dtype=data_type).reshape([3, 4])\n z1 = paddle.tensordot(x, y, axes=1)\n z2 = paddle.matmul(x, y)\n # z1 = z2 = [[20., 23., 26., 29.],\n # [56., 68., 80., 92.]]\n\n\n # When axes is a 1-d int list, x and y will be contracted along the same given axes.\n # Note that axes=[1, 2] is equivalent to axes=[[1, 2]], axes=[[1, 2], []], axes=[[1, 2], [1]], and axes=[[1, 2], [1, 2]].\n x = paddle.arange(24, dtype=data_type).reshape([2, 3, 4])\n y = paddle.arange(36, dtype=data_type).reshape([3, 3, 4])\n z = paddle.tensordot(x, y, axes=[1, 2])\n # z = [[506. , 1298., 2090.],\n # [1298., 3818., 6338.]]\n\n\n # When axes is a list containing two 1-d int list, the first will be applied to x and the second to y.\n x = paddle.arange(60, dtype=data_type).reshape([3, 4, 5])\n y = paddle.arange(24, dtype=data_type).reshape([4, 3, 2])\n z = paddle.tensordot(x, y, axes=([1, 0], [0, 1]))\n # z = [[4400., 4730.],\n # [4532., 4874.],\n # [4664., 5018.],\n # [4796., 5162.],\n # [4928., 5306.]]\n\n\n # Thanks to the support of axes expansion, axes=[[0, 1, 3, 4], [1, 0, 3, 4]] can be abbreviated as axes= [[0, 1, 3, 4], [1, 0]].\n x = paddle.arange(720, dtype=data_type).reshape([2, 3, 4, 5, 6])\n y = paddle.arange(720, dtype=data_type).reshape([3, 2, 4, 5, 6])\n z = paddle.tensordot(x, y, axes=[[0, 1, 3, 4], [1, 0]])\n # z = [[23217330., 24915630., 26613930., 28312230.],\n # [24915630., 26775930., 28636230., 30496530.],\n # [26613930., 28636230., 30658530., 32680830.],\n # [28312230., 30496530., 32680830., 34865130.]] \n \"\"\"\n op_type = 'tensordot'\n input_dtype = ['float32', 'float64']\n\n check_variable_and_dtype(x, 'x', input_dtype, op_type)\n check_variable_and_dtype(y, 'y', input_dtype, op_type)\n check_type(axes, 'axes', (int, tuple, list, Variable), op_type)\n\n def _var_to_list(var):\n if paddle.in_dynamic_mode():\n return tolist(var)\n raise TypeError(\n \"The 'axes' with type 'Tensor' in \" + op_type +\n \" is not available in static graph mode, \"\n \"please convert its type to int|Tuple|List, or use dynamic graph mode.\"\n )\n\n axes_x = []\n axes_y = []\n if np.issubdtype(type(axes), np.integer):\n assert axes >= 0, (\n \"The 'axes' in \" + op_type +\n f\" should not be negative, but received axes={axes}.\")\n axes_x = range(x.ndim - axes, x.ndim)\n axes_y = range(axes)\n else:\n if isinstance(axes, Variable):\n axes = _var_to_list(axes)\n\n if not axes or np.issubdtype(type(axes[0]), np.integer):\n axes_x = axes\n else:\n axes_x = axes[0]\n if len(axes) > 1:\n axes_y = axes[1]\n\n if isinstance(axes_x, Variable):\n axes_x = _var_to_list(axes_x)\n if isinstance(axes_y, Variable):\n axes_y = _var_to_list(axes_y)\n\n axes_x, axes_y = list(axes_x), list(axes_y)\n len_axes_x, len_axes_y = len(axes_x), len(axes_y)\n if len_axes_x < len_axes_y:\n axes_x.extend(axes_y[len_axes_x:])\n elif len_axes_y < len_axes_x:\n axes_y.extend(axes_x[len_axes_y:])\n\n shape_x, shape_y = list(x.shape), list(y.shape)\n need_contracted_dim_x = np.zeros((x.ndim), dtype=bool)\n need_contracted_dim_y = np.zeros((y.ndim), dtype=bool)\n contraction_size = 1\n for i in range(len(axes_x)):\n dim_x, dim_y = axes_x[i], axes_y[i]\n sx, sy = shape_x[dim_x], shape_y[dim_y]\n if sx == 1:\n shape_y[dim_y] = 1\n y = y.sum(dim_y).reshape(shape_y)\n elif sy == 1:\n shape_x[dim_x] = 1\n x = x.sum(dim_x).reshape(shape_x)\n else:\n assert sx == sy, \"The dimensional size for 'x' and 'y' in \" + op_type + f\" should match each other, but 'x' has size {sx} in dim {dim_x} while 'y' has size {sy} in dim {dim_y}.\"\n\n need_contracted_dim_x[dim_x] = True\n need_contracted_dim_y[dim_y] = True\n contraction_size *= shape_x[dim_x]\n\n perm_x = []\n perm_y = []\n shape_out = []\n not_contraction_size_x = 1\n not_contraction_size_y = 1\n for i in range(x.ndim):\n if not need_contracted_dim_x[i]:\n perm_x.append(i)\n shape_out.append(shape_x[i])\n not_contraction_size_x *= shape_x[i]\n perm_x.extend(axes_x)\n perm_y.extend(axes_y)\n for i in range(y.ndim):\n if not need_contracted_dim_y[i]:\n perm_y.append(i)\n shape_out.append(shape_y[i])\n not_contraction_size_y *= shape_y[i]\n\n if not shape_out:\n shape_out = [1]\n\n x = x.transpose(perm=perm_x).reshape(\n [not_contraction_size_x, contraction_size])\n y = y.transpose(perm=perm_y).reshape(\n [contraction_size, not_contraction_size_y])\n out = x.matmul(y).reshape(shape_out)\n return out\n\n\ndef as_complex(x, name=None):\n \"\"\"Transform a real tensor to a complex tensor. \n \n The data type of the input tensor is 'float32' or 'float64', and the data\n type of the returned tensor is 'complex64' or 'complex128', respectively.\n\n The shape of the input tensor is ``(* ,2)``, (``*`` means arbitary shape), i.e. \n the size of the last axis shoule be 2, which represent the real and imag part\n of a complex number. The shape of the returned tensor is ``(*,)``.\n\n Args:\n x (Tensor): The input tensor. Data type is 'float32' or 'float64'.\n name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: The output. Data type is 'complex64' or 'complex128', with the same precision as the input.\n \n Examples:\n .. code-block:: python\n\n import paddle\n x = paddle.arange(12, dtype=paddle.float32).reshape([2, 3, 2])\n y = paddle.as_complex(x)\n print(y.numpy())\n\n # [[ 0. +1.j 2. +3.j 4. +5.j]\n # [ 6. +7.j 8. +9.j 10.+11.j]]\n \"\"\"\n if paddle.in_dynamic_mode():\n return paddle._C_ops.as_complex(x)\n\n check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'as_complex')\n op_type = \"as_complex\"\n helper = LayerHelper(op_type, **locals())\n inputs = {\"X\": x}\n out = helper.create_variable_for_type_inference(\n dtype=_real_to_complex_dtype(x.dtype))\n outputs = {\"Out\": out}\n attrs = {}\n helper.append_op(type=op_type, inputs=inputs, attrs=attrs, outputs=outputs)\n return out\n\n\ndef as_real(x, name=None):\n \"\"\"Transform a complex tensor to a real tensor. \n \n The data type of the input tensor is 'complex64' or 'complex128', and the data \n type of the returned tensor is 'float32' or 'float64', respectively.\n\n When the shape of the input tensor is ``(*, )``, (``*`` means arbitary shape),\n the shape of the output tensor is ``(*, 2)``, i.e. the shape of the output is\n the shape of the input appended by an extra ``2``.\n\n Args:\n x (Tensor): The input tensor. Data type is 'complex64' or 'complex128'.\n name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: The output. Data type is 'float32' or 'float64', with the same precision as the input.\n \n Examples:\n .. code-block:: python\n\n import paddle\n x = paddle.arange(12, dtype=paddle.float32).reshape([2, 3, 2])\n y = paddle.as_complex(x)\n z = paddle.as_real(y)\n print(z.numpy())\n\n # [[[ 0. 1.]\n # [ 2. 3.]\n # [ 4. 5.]]\n\n # [[ 6. 7.]\n # [ 8. 9.]\n # [10. 11.]]]\n \"\"\"\n if paddle.in_dynamic_mode():\n return paddle._C_ops.as_real(x)\n\n check_variable_and_dtype(x, 'x', ['complex64', 'complex128'], 'as_real')\n op_type = \"as_real\"\n helper = LayerHelper(op_type, **locals())\n inputs = {\"X\": x}\n out = helper.create_variable_for_type_inference(\n dtype=_complex_to_real_dtype(x.dtype))\n outputs = {\"Out\": out}\n helper.append_op(type=op_type, inputs=inputs, outputs=outputs)\n return out\n\n\ndef repeat_interleave(x, repeats, axis=None, name=None):\n \"\"\"\n\n Returns a new tensor which repeats the ``x`` tensor along dimension ``axis`` using\n the entries in ``repeats`` which is a int or a Tensor.\n\n Args:\n x (Tensor): The input Tensor to be operated. The data of ``x`` can be one of float32, float64, int32, int64.\n repeats (Tensor or int): The number of repetitions for each element. repeats is broadcasted to fit the shape of the given axis.\n axis (int, optional): The dimension in which we manipulate. Default: None, the output tensor is flatten.\n name(str, optional): The default value is None. Normally there is no\n need for user to set this property. For more information, please\n refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: A Tensor with same data type as ``x``.\n\n Examples:\n .. code-block:: python\n\n import paddle\n\n x = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])\n repeats = paddle.to_tensor([3, 2, 1], dtype='int32')\n\n paddle.repeat_interleave(x, repeats, 1)\n # [[1, 1, 1, 2, 2, 3],\n # [4, 4, 4, 5, 5, 6]]\n\n paddle.repeat_interleave(x, 2, 0)\n # [[1, 2, 3], [1, 2, 3], [4, 5, 6], [4, 5, 6]]\n\n paddle.repeat_interleave(x, 2, None)\n # [1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6]\n \"\"\"\n\n if axis is None:\n x = paddle.flatten(x)\n axis = 0\n\n if paddle.in_dynamic_mode():\n if isinstance(repeats, int):\n return _C_ops.repeat_interleave(x, None, 'Repeats', repeats, 'dim',\n axis)\n elif isinstance(repeats, Variable):\n return _C_ops.repeat_interleave(x, repeats, 'dim', axis)\n\n helper = LayerHelper(\"repeat_interleave\", **locals())\n check_variable_and_dtype(x, 'x', ['float32', 'float64', 'int32', 'int64'],\n 'paddle.tensor.manipulation.repeat_interleave')\n\n out = helper.create_variable_for_type_inference(x.dtype)\n\n helper.append_op(\n type='repeat_interleave',\n inputs={\n 'X': x,\n 'RepeatsTensor': repeats if isinstance(repeats, Variable) else None\n },\n outputs={'Out': out},\n attrs={\n 'dim': axis,\n 'Repeats': repeats if isinstance(repeats, int) else 0\n })\n return out\n\n\ndef moveaxis(x, source, destination, name=None):\n \"\"\"\n Move the axis of tensor from ``source`` position to ``destination`` position.\n\n Other axis that have not been moved remain their original order.\n\n Args:\n x (Tensor): The input Tensor. It is a N-D Tensor of data types bool, int32, int64, float32, float64, complex64, complex128.\n source(int|tuple|list): ``source`` position of axis that will be moved. Each element must be unique and integer.\n destination(int|tuple|list(int)): ``destination`` position of axis that has been moved. Each element must be unique and integer.\n name(str, optional): The default value is None. Normally there is no need for user to set this\n property. For more information, please refer to :ref:`api_guide_Name`.\n\n Returns:\n Tensor: A new tensor whose axis have been moved.\n\n Examples:\n .. code-block:: python\n \n import paddle\n\n x = paddle.ones([3, 2, 4])\n paddle.moveaxis(x, [0, 1], [1, 2]).shape\n # [4, 3, 2]\n\n x = paddle.ones([2, 3])\n paddle.moveaxis(x, 0, 1) # equivalent to paddle.t(x)\n # [3, 2] \n \"\"\"\n src = [source] if isinstance(source, int) else source\n dst = [destination] if isinstance(destination, int) else destination\n\n assert len(src) == len(\n dst), \"'source' must have the same number with 'destination'\"\n\n count = Counter(src).most_common(1)\n if count[0][1] > 1:\n raise ValueError(\"Each elemment of 'source' must be unique!\")\n count = Counter(dst).most_common(1)\n if count[0][1] > 1:\n raise ValueError(\"Each elemment of 'destination' must be unique!\")\n\n ndim = len(x.shape)\n\n # perm is the new order after move axis\n perm = list(range(ndim))\n src_dims = list(range(ndim))\n dst_dims = list(range(ndim))\n\n for i, axis in enumerate(zip(src, dst)):\n assert isinstance(axis[0],\n int), \"Each elemment of 'source' must be integer.\"\n if axis[0] < 0:\n assert axis[\n 0] >= -ndim, \"'source' must be in the range of [-{0}, {0})\".format(\n ndim)\n src[i] += ndim\n else:\n assert axis[\n 0] < ndim, \"'source' must be in the range of [-{0}, {0})\".format(\n ndim)\n\n assert isinstance(axis[1],\n int), \"Each elemment of 'source' must be integer.\"\n if axis[1] < 0:\n assert axis[\n 1] >= -ndim, \"'source' must be in the range of [-{0}, {0})\".format(\n ndim)\n dst[i] += ndim\n else:\n assert axis[\n 1] < ndim, \"'source' must be in the range of [-{0}, {0})\".format(\n ndim)\n perm[dst[i]] = src[i]\n src_dims.remove(src[i])\n dst_dims.remove(dst[i])\n\n for i in range(len(src_dims)):\n perm[dst_dims[i]] = src_dims[i]\n\n if paddle.in_dynamic_mode():\n out, _ = _C_ops.transpose2(x, 'axis', perm)\n return out\n\n check_variable_and_dtype(x, 'x', [\n 'bool', 'float16', 'float32', 'float64', 'int32', 'int64', 'complex64',\n 'complex128'\n ], 'moveaxis')\n\n helper = LayerHelper('moveaxis', **locals())\n out = helper.create_variable_for_type_inference(x.dtype)\n x_shape = helper.create_variable_for_type_inference(x.dtype)\n helper.append_op(\n type='transpose2',\n inputs={'X': [x]},\n outputs={'Out': [out],\n 'XShape': [x_shape]},\n attrs={'axis': perm})\n return out\n\n\ndef non_negative_axis(arr, axis):\n ndim = len(arr.shape)\n if axis >= 0:\n assert axis < ndim, \"'axis' must be in the range of [-{0}, {0})\".format(\n ndim)\n else:\n assert axis >= -ndim, \"'axis' must be in the range of [-{0}, {0})\".format(\n ndim)\n axis += ndim\n\n return axis\n\n\ndef infer_broadcast_shape(arr, indices, axis):\n # This function is used in take/put_along_axis \n broadcast_shape_list = list(arr.shape)\n broadcast_shape_list[axis] = list(indices.shape)[axis]\n broadcast_shape = tuple(broadcast_shape_list)\n for i in range(len(arr.shape)):\n if arr.shape[i] < indices.shape[i]:\n # if indices matrix has larger size than arr matrix, do not broadcast.\n return None\n return broadcast_shape\n\n\ndef take_along_axis(arr, indices, axis):\n \"\"\"\n Take values from the input array by given indices matrix along the designated axis.\n\n Args:\n arr (Tensor) : The input Tensor. Supported data types are float32 and float64.\n indices (Tensor) : Indices to take along each 1d slice of arr. This must match the dimension of arr,\n and need to broadcast against arr. Supported data type are int and int64.\n axis (int) : The axis to take 1d slices along. \n\n Returns: \n Tensor: The indexed element, same dtype with arr\n \n Examples:\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n x_np = np.array([[1, 2, 3], [4, 5, 6], [7,8,9]])\n index_np = np.array([[0]])\n x = paddle.to_tensor(x_np)\n index = paddle.to_tensor(index_np)\n axis = 0\n result = paddle.take_along_axis(x, index, axis)\n print(result)\n # [[1, 2, 3]]\n \"\"\"\n if (len(arr.shape) != len(indices.shape)):\n raise ValueError(\n \"`indices` and `arr` must have the same number of dimensions!\")\n axis = non_negative_axis(arr, axis)\n broadcast_shape = infer_broadcast_shape(arr, indices, axis)\n if not broadcast_shape:\n # if indices matrix have larger size than arr, arr should broadcast into indices shape.\n broadcast_shape = indices.shape\n if paddle.in_dynamic_mode():\n indices = paddle.broadcast_to(indices, broadcast_shape)\n broadcast_shape_list = list(broadcast_shape)\n broadcast_shape_list[axis] = list(arr.shape)[axis]\n broadcast_shape = tuple(broadcast_shape_list)\n arr = paddle.broadcast_to(arr, broadcast_shape)\n return _C_ops.take_along_axis(arr, indices, 'Axis', axis)\n check_variable_and_dtype(\n arr, 'x', ['float16', 'float32', 'float64', 'int32', 'int64', 'uint8'],\n 'take_along_axis')\n check_variable_and_dtype(indices, 'index', ['int32', 'int64'],\n 'take_along_axis')\n indices = paddle.broadcast_to(indices, broadcast_shape)\n broadcast_shape_list = list(broadcast_shape)\n broadcast_shape_list[axis] = list(arr.shape)[axis]\n broadcast_shape = tuple(broadcast_shape_list)\n arr = paddle.broadcast_to(arr, broadcast_shape)\n helper = LayerHelper('take_along_axis', **locals())\n dtype = helper.input_dtype()\n result = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type=\"take_along_axis\",\n inputs={\"Input\": arr,\n \"Index\": indices},\n attrs={\"Axis\": axis},\n outputs={\"Result\": result})\n return result\n\n\ndef put_along_axis(arr, indices, values, axis, reduce='assign'):\n \"\"\"\n Put values into the destination array by given indices matrix along the designated axis.\n\n Args:\n arr (Tensor) : The Destination Tensor. Supported data types are float32 and float64.\n indices (Tensor) : Indices to put along each 1d slice of arr. This must match the dimension of arr,\n and need to broadcast against arr. Supported data type are int and int64.\n axis (int) : The axis to put 1d slices along. \n reduce (string | optinal) : The reduce operation, default is 'assign', support 'add', 'assign', 'mul' and 'multiply'.\n Returns : \n Tensor: The indexed element, same dtype with arr\n \n Examples:\n .. code-block:: python\n\n import paddle\n import numpy as np\n\n x_np = np.array([[10, 30, 20], [60, 40, 50]])\n index_np = np.array([[0]])\n x = paddle.to_tensor(x_np)\n index = paddle.to_tensor(index_np)\n value = 99\n axis = 0\n result = paddle.put_along_axis(x, index, value, axis)\n print(result)\n # [[99, 99, 99],\n # [60, 40, 50]]\n\n \"\"\"\n if (len(arr.shape) != len(indices.shape)):\n raise ValueError(\n \"`indices` and `arr` must have the same number of dimensions!\")\n axis = non_negative_axis(arr, axis)\n broadcast_shape = infer_broadcast_shape(arr, indices, axis)\n if paddle.in_dynamic_mode():\n values = paddle.to_tensor(values) if not isinstance(\n values, paddle.Tensor) else values\n if broadcast_shape:\n indices = paddle.broadcast_to(indices, broadcast_shape)\n values = paddle.broadcast_to(values, indices.shape)\n return _C_ops.put_along_axis(arr, indices, values, \"Axis\", axis,\n \"Reduce\", reduce)\n\n check_variable_and_dtype(\n arr, 'x', ['float16', 'float32', 'float64', 'int32', 'int64', 'uint8'],\n 'put_along_axis')\n check_variable_and_dtype(indices, 'index', ['int32', 'int64'],\n 'put_along_axis')\n if broadcast_shape:\n indices = paddle.broadcast_to(indices, broadcast_shape)\n values = paddle.broadcast_to(values, indices.shape)\n helper = LayerHelper('put_along_axis', **locals())\n dtype = helper.input_dtype()\n result = helper.create_variable_for_type_inference(dtype)\n helper.append_op(\n type=\"put_along_axis\",\n inputs={\"Input\": arr,\n \"Index\": indices,\n \"Value\": values},\n attrs={\"Axis\": axis,\n \"Reduce\": reduce},\n outputs={\"Result\": result})\n return result\n\n\n@inplace_apis_in_dygraph_only\ndef put_along_axis_(arr, indices, values, axis, reduce='assign'):\n r\"\"\"\n Inplace version of ``put_along_axis`` API, the output Tensor will be inplaced with input ``arr``.\n Please refer to :ref:`api_tensor_put_along_axis`.\n \"\"\"\n if (len(arr.shape) != len(indices.shape)):\n raise ValueError(\n \"`indices` and `arr` must have the same number of dimensions!\")\n axis = non_negative_axis(arr, axis)\n broadcast_shape = infer_broadcast_shape(arr, indices, axis)\n values = paddle.to_tensor(values) if not isinstance(\n values, paddle.Tensor) else values\n if broadcast_shape:\n indices = paddle.broadcast_to(indices, broadcast_shape)\n values = paddle.broadcast_to(values, indices.shape)\n return _C_ops.put_along_axis_(arr, indices, values, \"Axis\", axis, \"Reduce\",\n reduce)\n", "# Copyright (c) 2022 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 unittest\n\nimport numpy as np\nimport paddle\nimport paddle.static\nfrom paddle.fluid.tests.unittests.ipu.op_test_ipu import IPUOpTest, ExecutionMode\n\n\[email protected](not paddle.is_compiled_with_ipu(),\n \"core is not compiled with IPU\")\nclass TestBase(IPUOpTest):\n def setUp(self):\n self.set_atol()\n self.set_training()\n self.set_data_feed()\n self.set_feed_attr()\n self.set_op_attrs()\n\n @property\n def fp16_enabled(self):\n return True\n\n def set_data_feed(self):\n data1 = np.array([[1], [1], [3], [0]])\n\n self.feed = {'x': data1.astype(np.int32)}\n\n def set_feed_attr(self):\n self.feed_shape = [x.shape for x in self.feed.values()]\n self.feed_list = list(self.feed.keys())\n\n def set_op_attrs(self):\n self.attrs = {\"depth\": 4, \"allow_out_of_range\": False}\n\n def _test_base(self, exec_mode):\n scope = paddle.static.Scope()\n main_prog = paddle.static.Program()\n startup_prog = paddle.static.Program()\n main_prog.random_seed = self.SEED\n startup_prog.random_seed = self.SEED\n\n with paddle.static.scope_guard(scope):\n with paddle.static.program_guard(main_prog, startup_prog):\n x = paddle.static.data(\n name=self.feed_list[0],\n shape=self.feed_shape[0],\n dtype='int32')\n\n out = paddle.fluid.input.one_hot(x, **self.attrs)\n\n fetch_list = [out.name]\n\n if exec_mode == ExecutionMode.CPU_FP32:\n place = paddle.CPUPlace()\n else:\n place = paddle.IPUPlace()\n\n exe = paddle.static.Executor(place)\n exe.run(startup_prog)\n\n if exec_mode != ExecutionMode.CPU_FP32:\n feed_list = self.feed_list\n ipu_strategy = paddle.static.IpuStrategy()\n ipu_strategy.set_graph_config(is_training=self.is_training)\n if exec_mode == ExecutionMode.IPU_POPART_FP16:\n ipu_strategy.set_precision_config(enable_fp16=True)\n program = paddle.static.IpuCompiledProgram(\n main_prog,\n ipu_strategy=ipu_strategy).compile(feed_list, fetch_list)\n else:\n program = main_prog\n\n feed = self.feed\n\n result = exe.run(program, feed=feed, fetch_list=fetch_list)\n\n return result[0]\n\n def test_base(self):\n output_dict = {}\n for mode in ExecutionMode:\n if (mode > ExecutionMode.IPU_FP32 and not self.fp16_enabled):\n break\n output_dict[mode] = self._test_base(mode).flatten()\n\n self.check(output_dict)\n\n\[email protected]('does not support allow_out_of_range=True')\nclass TestCase1(TestBase):\n def set_op_attrs(self):\n self.attrs = {\"depth\": 4, \"allow_out_of_range\": True}\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# 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\nfrom __future__ import print_function\nimport unittest\n\nimport numpy as np\n\nimport paddle\nfrom paddle.static import Program, program_guard\n\n\nclass TestMultiplyApi(unittest.TestCase):\n def _run_static_graph_case(self, x_data, y_data):\n with program_guard(Program(), Program()):\n paddle.enable_static()\n x = paddle.static.data(\n name='x', shape=x_data.shape, dtype=x_data.dtype)\n y = paddle.static.data(\n name='y', shape=y_data.shape, dtype=y_data.dtype)\n res = paddle.inner(x, y)\n\n place = paddle.CUDAPlace(0) if paddle.is_compiled_with_cuda(\n ) else paddle.CPUPlace()\n exe = paddle.static.Executor(place)\n outs = exe.run(paddle.static.default_main_program(),\n feed={'x': x_data,\n 'y': y_data},\n fetch_list=[res])\n res = outs[0]\n return res\n\n def _run_dynamic_graph_case(self, x_data, y_data):\n paddle.disable_static()\n x = paddle.to_tensor(x_data)\n y = paddle.to_tensor(y_data)\n res = paddle.inner(x, y)\n return res.numpy()\n\n def test_multiply(self):\n np.random.seed(7)\n\n # test static computation graph: 3-d array\n x_data = np.random.rand(2, 10, 10).astype(np.float64)\n y_data = np.random.rand(2, 5, 10).astype(np.float64)\n res = self._run_static_graph_case(x_data, y_data)\n self.assertTrue(np.allclose(res, np.inner(x_data, y_data)))\n\n # test static computation graph: 2-d array\n x_data = np.random.rand(200, 5).astype(np.float64)\n y_data = np.random.rand(50, 5).astype(np.float64)\n res = self._run_static_graph_case(x_data, y_data)\n self.assertTrue(np.allclose(res, np.inner(x_data, y_data)))\n\n # test static computation graph: 1-d array\n x_data = np.random.rand(50).astype(np.float64)\n y_data = np.random.rand(50).astype(np.float64)\n res = self._run_static_graph_case(x_data, y_data)\n self.assertTrue(np.allclose(res, np.inner(x_data, y_data)))\n\n # test dynamic computation graph: 3-d array\n x_data = np.random.rand(5, 10, 10).astype(np.float64)\n y_data = np.random.rand(2, 10).astype(np.float64)\n res = self._run_dynamic_graph_case(x_data, y_data)\n self.assertTrue(np.allclose(res, np.inner(x_data, y_data)))\n\n # test dynamic computation graph: 2-d array\n x_data = np.random.rand(20, 50).astype(np.float64)\n y_data = np.random.rand(50).astype(np.float64)\n res = self._run_dynamic_graph_case(x_data, y_data)\n self.assertTrue(np.allclose(res, np.inner(x_data, y_data)))\n\n # test dynamic computation graph: Scalar\n x_data = np.random.rand(20, 10).astype(np.float32)\n y_data = np.random.rand(1).astype(np.float32).item()\n res = self._run_dynamic_graph_case(x_data, y_data)\n self.assertTrue(np.allclose(res, np.inner(x_data, y_data)))\n\n # test dynamic computation graph: 2-d array Complex\n x_data = np.random.rand(20,\n 50).astype(np.float64) + 1J * np.random.rand(\n 20, 50).astype(np.float64)\n y_data = np.random.rand(50).astype(np.float64) + 1J * np.random.rand(\n 50).astype(np.float64)\n res = self._run_dynamic_graph_case(x_data, y_data)\n self.assertTrue(np.allclose(res, np.inner(x_data, y_data)))\n\n # test dynamic computation graph: 3-d array Complex\n x_data = np.random.rand(5, 10,\n 10).astype(np.float64) + 1J * np.random.rand(\n 5, 10, 10).astype(np.float64)\n y_data = np.random.rand(2, 10).astype(np.float64) + 1J * np.random.rand(\n 2, 10).astype(np.float64)\n res = self._run_dynamic_graph_case(x_data, y_data)\n self.assertTrue(np.allclose(res, np.inner(x_data, y_data)))\n\n\nclass TestMultiplyError(unittest.TestCase):\n def test_errors(self):\n # test static computation graph: dtype can not be int8\n paddle.enable_static()\n with program_guard(Program(), Program()):\n x = paddle.static.data(name='x', shape=[100], dtype=np.int8)\n y = paddle.static.data(name='y', shape=[100], dtype=np.int8)\n self.assertRaises(TypeError, paddle.inner, x, y)\n\n # test static computation graph: inputs must be broadcastable \n with program_guard(Program(), Program()):\n x = paddle.static.data(name='x', shape=[20, 50], dtype=np.float64)\n y = paddle.static.data(name='y', shape=[20], dtype=np.float64)\n self.assertRaises(ValueError, paddle.inner, x, y)\n\n np.random.seed(7)\n # test dynamic computation graph: dtype can not be int8\n paddle.disable_static()\n x_data = np.random.randn(200).astype(np.int8)\n y_data = np.random.randn(200).astype(np.int8)\n x = paddle.to_tensor(x_data)\n y = paddle.to_tensor(y_data)\n self.assertRaises(RuntimeError, paddle.inner, x, y)\n\n # test dynamic computation graph: inputs must be broadcastable\n x_data = np.random.rand(20, 5)\n y_data = np.random.rand(10, 2)\n x = paddle.to_tensor(x_data)\n y = paddle.to_tensor(y_data)\n self.assertRaises(ValueError, paddle.inner, x, y)\n\n # test dynamic computation graph: dtype must be same\t\n x_data = np.random.randn(200).astype(np.float32)\n y_data = np.random.randn(200).astype(np.float64)\n x = paddle.to_tensor(x_data)\n y = paddle.to_tensor(y_data)\n self.assertRaises(ValueError, paddle.inner, x, y)\n\n # test dynamic computation graph: dtype must be Tensor type\n x_data = np.random.randn(200).astype(np.float64)\n y_data = np.random.randn(200).astype(np.float64)\n y = paddle.to_tensor(y_data)\n self.assertRaises(ValueError, paddle.inner, x_data, y)\n\n # test dynamic computation graph: dtype must be Tensor type\n x_data = np.random.randn(200).astype(np.float64)\n y_data = np.random.randn(200).astype(np.float64)\n x = paddle.to_tensor(x_data)\n self.assertRaises(ValueError, paddle.inner, x, y_data)\n\n # test dynamic computation graph: dtype must be Tensor type\n x_data = np.random.randn(200).astype(np.float32)\n y_data = np.random.randn(200).astype(np.float32)\n self.assertRaises(ValueError, paddle.inner, x_data, y_data)\n\n\nif __name__ == '__main__':\n paddle.enable_static()\n unittest.main()\n", "# Copyright (c) 2021 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 __future__ import print_function\n\nimport unittest\nimport random\nimport numpy as np\nimport os\nimport shutil\n\nimport paddle\nimport paddle.nn as nn\nimport paddle.utils as utils\nimport paddle.static as static\nimport paddle.nn.functional as F\nimport paddle.distributed.auto_parallel as auto\n\nfrom paddle.distributed import fleet\nfrom paddle.fluid.initializer import NumpyArrayInitializer\nfrom paddle.distributed.auto_parallel.utils import save_distributed_checkpoint, load_distributed_checkpoint, load_checkpoint_into_program\nfrom paddle.distributed.auto_parallel.utils import get_dist_attr, merge_and_slice_parameter, load_parameter_into_program\nfrom paddle.distributed.auto_parallel.dist_context import set_default_distributed_context\n\npaddle.enable_static()\n_global_parallel_strategy = None\n_global_process_mesh = None\nPP_MESH_0 = None\nPP_MESH_1 = None\n\n\nclass MLPLayer(nn.Layer):\n def __init__(self,\n hidden_size=64,\n intermediate_size=4 * 64,\n initializer_range=0.02):\n super(MLPLayer, self).__init__()\n d_model = hidden_size\n dim_feedforward = intermediate_size\n np.random.seed(2021)\n arr0 = np.random.normal(0, 0.02, size=(d_model, dim_feedforward))\n arr1 = np.random.normal(0, 0.02, size=(d_model, dim_feedforward))\n weight_attr0 = paddle.ParamAttr(initializer=NumpyArrayInitializer(arr0))\n weight_attr1 = paddle.ParamAttr(initializer=NumpyArrayInitializer(arr1))\n bias_attr = None\n self.linear0 = nn.Linear(\n d_model, dim_feedforward, weight_attr0, bias_attr=bias_attr)\n self.linear1 = nn.Linear(\n dim_feedforward, d_model, weight_attr1, bias_attr=bias_attr)\n self.norm = nn.LayerNorm(d_model, epsilon=1e-5)\n\n def forward(self, input):\n if _global_parallel_strategy == \"pp\":\n auto.shard_tensor(\n self.linear0.weight,\n dist_attr={\n \"process_mesh\": PP_MESH_0,\n \"dims_mapping\": [-1, -1]\n })\n auto.shard_tensor(\n self.linear1.weight,\n dist_attr={\n \"process_mesh\": PP_MESH_1,\n \"dims_mapping\": [-1, -1]\n })\n elif _global_parallel_strategy == \"mp\":\n auto.shard_tensor(\n self.linear0.weight,\n dist_attr={\n \"process_mesh\": _global_process_mesh,\n \"dims_mapping\": [-1, 0]\n })\n auto.shard_tensor(\n self.linear1.weight,\n dist_attr={\n \"process_mesh\": _global_process_mesh,\n \"dims_mapping\": [0, -1]\n })\n elif _global_parallel_strategy == \"dp\":\n auto.shard_tensor(\n self.linear0.weight,\n dist_attr={\n \"process_mesh\": _global_process_mesh,\n \"dims_mapping\": [-1, -1]\n })\n auto.shard_tensor(\n self.linear1.weight,\n dist_attr={\n \"process_mesh\": _global_process_mesh,\n \"dims_mapping\": [-1, -1]\n })\n\n out = self.norm(input)\n out = self.linear0(out)\n out = F.gelu(out, approximate=True)\n out = self.linear1(out)\n return out\n\n\ndef mlp_forward(train_program, start_program):\n with static.program_guard(train_program,start_program), \\\n utils.unique_name.guard():\n batch_size = 4\n hidden_size = 64\n input = static.data(\n name=\"input\", shape=[batch_size, hidden_size], dtype='float32')\n label = static.data(\n name=\"label\", shape=[batch_size, 1], dtype='float32')\n\n if _global_parallel_strategy == \"pp\":\n auto.shard_tensor(\n input,\n dist_attr={\n \"process_mesh\": PP_MESH_0,\n \"dims_mapping\": [-1, -1]\n })\n auto.shard_tensor(\n label,\n dist_attr={\n \"process_mesh\": PP_MESH_1,\n \"dims_mapping\": [-1, -1]\n })\n elif _global_parallel_strategy == \"dp\":\n auto.shard_tensor(\n input,\n dist_attr={\n \"process_mesh\": _global_process_mesh,\n \"dims_mapping\": [0, -1]\n })\n elif _global_parallel_strategy == \"mp\":\n auto.shard_tensor(\n input,\n dist_attr={\n \"process_mesh\": _global_process_mesh,\n \"dims_mapping\": [-1, -1]\n })\n\n mlp = MLPLayer(\n hidden_size=hidden_size,\n intermediate_size=4 * hidden_size,\n initializer_range=0.02)\n predict = mlp(input)\n error_cost = paddle.nn.functional.square_error_cost(predict, label)\n loss = paddle.mean(error_cost)\n return loss, train_program, start_program\n\n\ndef get_distributed_program():\n train_program = static.Program()\n startup_program = static.Program()\n dist_strategy = fleet.DistributedStrategy()\n dist_strategy.semi_auto = True\n fleet.init(is_collective=True, strategy=dist_strategy)\n loss, train_program, startup_program = mlp_forward(train_program,\n startup_program)\n optimizer = paddle.fluid.optimizer.SGDOptimizer(learning_rate=0.01)\n optimizer = fleet.distributed_optimizer(optimizer)\n _, _, dist_startup_prog, dist_main_prog = optimizer.minimize(\n loss, startup_program)\n\n return dist_main_prog, dist_startup_prog, loss\n\n\nclass TestMLPAutoConvert(unittest.TestCase):\n def setUp(self):\n paddle.seed(2021)\n random.seed(2021)\n np.random.seed(2021)\n\n def tearDown(self):\n os.remove(\"./model_state_rank{}.pdmodel\".format(\n str(paddle.distributed.get_rank())))\n os.remove(\"./dist_attr_rank{}.pdattr\".format(\n str(paddle.distributed.get_rank())))\n\n def test_mlp_mp2pp(self):\n set_default_distributed_context(None)\n global _global_parallel_strategy\n _global_parallel_strategy = \"mp\"\n global _global_process_mesh\n _global_process_mesh = auto.ProcessMesh([0, 1])\n\n input = np.random.random(size=(80, 64)).astype('float32')\n label = np.random.random(size=(80, 1)).astype('float32')\n\n dist_main_prog, dist_start_prog, loss = get_distributed_program()\n place = paddle.set_device(\"gpu\")\n exe = paddle.static.Executor(place)\n exe.run(dist_start_prog)\n\n for step in range(20):\n if step == 10:\n save_distributed_checkpoint(\n dist_main_prog, \".\", dist_attr_path=\".\")\n\n res = exe.run(dist_main_prog,\n feed={\n \"input\": input[step * 4:(step + 1) * 4, :],\n \"label\": label[step * 4:(step + 1) * 4, :]\n },\n fetch_list=[loss])\n last_res = res[0]\n\n set_default_distributed_context(None)\n _global_parallel_strategy = \"pp\"\n _global_process_mesh = auto.ProcessMesh([0, 1])\n global PP_MESH_0\n PP_MESH_0 = auto.ProcessMesh(mesh=[0])\n global PP_MESH_1\n PP_MESH_1 = auto.ProcessMesh(mesh=[1])\n\n dist_main_prog_load, dist_start_prog_load, loss_load = get_distributed_program(\n )\n place = paddle.set_device(\"gpu\")\n exe = paddle.static.Executor(place)\n exe.run(dist_start_prog_load)\n\n ckpt_path = [\n \"./model_state_rank0.pdmodel\", \"./model_state_rank1.pdmodel\"\n ]\n dist_attr_path = [\n \"./dist_attr_rank0.pdattr\", \"./dist_attr_rank1.pdattr\"\n ]\n load_checkpoint_into_program(ckpt_path, dist_attr_path,\n dist_main_prog_load)\n for step in range(10, 20):\n if paddle.distributed.get_rank() in [0]:\n res = exe.run(dist_main_prog_load,\n feed={\n \"input\": input[step * 4:(step + 1) * 4, :],\n \"label\": label[step * 4:(step + 1) * 4, :]\n })\n else:\n res = exe.run(dist_main_prog_load,\n feed={\n \"input\": input[step * 4:(step + 1) * 4, :],\n \"label\": label[step * 4:(step + 1) * 4, :]\n },\n fetch_list=[loss_load])\n if paddle.distributed.get_rank() in [1]:\n self.assertEqual(last_res, res[0])\n\n\nclass TestMLPAutoConvert2(unittest.TestCase):\n def setUp(self):\n paddle.seed(2021)\n random.seed(2021)\n np.random.seed(2021)\n\n def tearDown(self):\n os.remove(\"./model_state_rank{}.pdmodel\".format(\n str(paddle.distributed.get_rank())))\n os.remove(\"./dist_attr_rank{}.pdattr\".format(\n str(paddle.distributed.get_rank())))\n\n def test_mlp_pp2mp(self):\n set_default_distributed_context(None)\n global _global_parallel_strategy\n _global_parallel_strategy = \"pp\"\n global _global_process_mesh\n _global_process_mesh = auto.ProcessMesh([0, 1])\n global PP_MESH_0\n PP_MESH_0 = auto.ProcessMesh(mesh=[0])\n global PP_MESH_1\n PP_MESH_1 = auto.ProcessMesh(mesh=[1])\n input = np.random.random(size=(80, 64)).astype('float32')\n label = np.random.random(size=(80, 1)).astype('float32')\n\n dist_main_prog, dist_start_prog, loss = get_distributed_program()\n place = paddle.set_device(\"gpu\")\n exe = paddle.static.Executor(place)\n exe.run(dist_start_prog)\n for step in range(20):\n if step == 10:\n add_info = {\"batch\": step, \"batch_size\": 4}\n save_distributed_checkpoint(dist_main_prog, \".\", \".\", add_info)\n\n if paddle.distributed.get_rank() in [0]:\n res = exe.run(dist_main_prog,\n feed={\n \"input\": input[step * 4:(step + 1) * 4, :],\n \"label\": label[step * 4:(step + 1) * 4, :]\n })\n else:\n res = exe.run(dist_main_prog,\n feed={\n \"input\": input[step * 4:(step + 1) * 4, :],\n \"label\": label[step * 4:(step + 1) * 4, :]\n },\n fetch_list=[loss])\n if paddle.distributed.get_rank() in [1]:\n last_res = res[0]\n\n set_default_distributed_context(None)\n _global_parallel_strategy = \"mp\"\n _global_process_mesh = auto.ProcessMesh([0, 1])\n\n dist_main_prog_load, dist_start_prog_load, loss_load = get_distributed_program(\n )\n place = paddle.set_device(\"gpu\")\n exe = paddle.static.Executor(place)\n exe.run(dist_start_prog_load)\n ckpt_path = [\n \"./model_state_rank0.pdmodel\", \"./model_state_rank1.pdmodel\"\n ]\n dist_attr_path = [\n \"./dist_attr_rank0.pdattr\", \"./dist_attr_rank1.pdattr\"\n ]\n param_dict, pre_dist_attr, add_info = load_distributed_checkpoint(\n ckpt_path, dist_attr_path)\n batch = add_info[\"batch\"]\n batch_size = add_info[\"batch_size\"]\n start_index = batch * batch_size\n input = input[start_index:, :]\n label = label[start_index:, :]\n cur_dist_attr = get_dist_attr(dist_main_prog_load)\n sliced_param_dict = merge_and_slice_parameter(param_dict, pre_dist_attr,\n cur_dist_attr)\n load_parameter_into_program(sliced_param_dict, dist_main_prog_load)\n for step in range(10):\n res = exe.run(dist_main_prog_load,\n feed={\n \"input\": input[step * 4:(step + 1) * 4, :],\n \"label\": label[step * 4:(step + 1) * 4, :]\n },\n fetch_list=[loss_load])\n if paddle.distributed.get_rank() in [1]:\n self.assertEqual(last_res, res[0])\n\n\nclass TestMLPAutoConvertInvalid(unittest.TestCase):\n def setUp(self):\n paddle.seed(2021)\n random.seed(2021)\n np.random.seed(2021)\n\n def test_input_invalid(self):\n set_default_distributed_context(None)\n global _global_parallel_strategy\n _global_parallel_strategy = \"mp\"\n global _global_process_mesh\n _global_process_mesh = auto.ProcessMesh([0, 1])\n dist_main_prog, _, _ = get_distributed_program()\n with self.assertRaises(TypeError):\n save_distributed_checkpoint(\n dist_main_prog, [\"\"], [\"\"], addition_info=[0])\n with self.assertRaises(ValueError):\n save_distributed_checkpoint(\n dist_main_prog, [\"\"], [\"\"], addition_info={\"step\": 0})\n with self.assertRaises(ValueError):\n save_distributed_checkpoint(\n dist_main_prog, [\"\"], [\"\"], addition_info={\"batch\": 0.0})\n with self.assertRaises(ValueError):\n load_checkpoint_into_program([\"./model_state_rank.pdmodel\"],\n [\"./dist_attr_rank.pdattr\"],\n dist_main_prog)\n with self.assertRaises(ValueError):\n load_distributed_checkpoint([\"./model_state_rank.pdmodel\"],\n [\"./dist_attr_rank.pdattr\"])\n with self.assertRaises(TypeError):\n load_distributed_checkpoint({\n \"0\": \"./model_state_rank.pdmodel\"\n }, {\"1\": \"./dist_attr_rank.pdattr\"})\n\n\nif __name__ == \"__main__\":\n unittest.main()\n", "# Copyright (c) 2018 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 __future__ import print_function\n\nimport sys\nimport unittest\nimport numpy as np\nfrom op_test import OpTest\nfrom test_softmax_op import stable_softmax\nimport paddle.fluid as fluid\nimport paddle\n\n\ndef CTCAlign(input, lod, blank, merge_repeated, padding=0, input_length=None):\n if input_length is None:\n lod0 = lod[0]\n result = []\n cur_offset = 0\n for i in range(len(lod0)):\n prev_token = -1\n for j in range(cur_offset, cur_offset + lod0[i]):\n token = input[j][0]\n if (token != blank) and not (merge_repeated and\n token == prev_token):\n result.append(token)\n prev_token = token\n cur_offset += lod0[i]\n result = np.array(result).reshape([len(result), 1]).astype(\"int32\")\n if len(result) == 0:\n result = np.array([-1])\n return result\n else:\n result = [[] for i in range(len(input))]\n output_length = []\n for i in range(len(input)):\n prev_token = -1\n for j in range(input_length[i][0]):\n token = input[i][j]\n if (token != blank) and not (merge_repeated and\n token == prev_token):\n result[i].append(token)\n prev_token = token\n start = len(result[i])\n output_length.append([start])\n for j in range(start, len(input[i])):\n result[i].append(padding)\n result = np.array(result).reshape(\n [len(input), len(input[0])]).astype(\"int32\")\n output_length = np.array(output_length).reshape(\n [len(input), 1]).astype(\"int32\")\n\n return result, output_length\n\n\nclass TestCTCAlignOp(OpTest):\n def config(self):\n self.op_type = \"ctc_align\"\n self.input_lod = [[11, 7]]\n self.blank = 0\n self.merge_repeated = False\n self.input = np.array(\n [0, 1, 2, 2, 0, 4, 0, 4, 5, 0, 6, 6, 0, 0, 7, 7, 7, 0]).reshape(\n [18, 1]).astype(\"int32\")\n\n def setUp(self):\n self.config()\n output = CTCAlign(self.input, self.input_lod, self.blank,\n self.merge_repeated)\n\n self.inputs = {\"Input\": (self.input, self.input_lod), }\n self.outputs = {\"Output\": output}\n self.attrs = {\n \"blank\": self.blank,\n \"merge_repeated\": self.merge_repeated\n }\n\n def test_check_output(self):\n self.check_output()\n pass\n\n\nclass TestCTCAlignOpCase1(TestCTCAlignOp):\n def config(self):\n self.op_type = \"ctc_align\"\n self.input_lod = [[11, 8]]\n self.blank = 0\n self.merge_repeated = True\n self.input = np.array(\n [0, 1, 2, 2, 0, 4, 0, 4, 5, 0, 6, 6, 0, 0, 7, 7, 7, 0, 0]).reshape(\n [19, 1]).astype(\"int32\")\n\n\nclass TestCTCAlignOpCase2(TestCTCAlignOp):\n def config(self):\n self.op_type = \"ctc_align\"\n self.input_lod = [[4]]\n self.blank = 0\n self.merge_repeated = True\n self.input = np.array([0, 0, 0, 0]).reshape([4, 1]).astype(\"int32\")\n\n\nclass TestCTCAlignPaddingOp(OpTest):\n def config(self):\n self.op_type = \"ctc_align\"\n self.input_lod = []\n self.blank = 0\n self.padding_value = 0\n self.merge_repeated = True\n self.input = np.array([[0, 2, 4, 4, 0, 6, 3, 6, 6, 0, 0],\n [1, 1, 3, 0, 0, 4, 5, 6, 0, 0, 0]]).reshape(\n [2, 11]).astype(\"int32\")\n self.input_length = np.array([[9], [8]]).reshape([2, 1]).astype(\"int32\")\n\n def setUp(self):\n self.config()\n output, output_length = CTCAlign(self.input, self.input_lod, self.blank,\n self.merge_repeated,\n self.padding_value, self.input_length)\n self.inputs = {\n \"Input\": (self.input, self.input_lod),\n \"InputLength\": self.input_length\n }\n self.outputs = {\"Output\": output, \"OutputLength\": output_length}\n self.attrs = {\n \"blank\": self.blank,\n \"merge_repeated\": self.merge_repeated,\n \"padding_value\": self.padding_value\n }\n\n def test_check_output(self):\n self.check_output()\n\n\nclass TestCTCAlignOpCase3(TestCTCAlignPaddingOp):\n def config(self):\n self.op_type = \"ctc_align\"\n self.blank = 0\n self.input_lod = []\n self.merge_repeated = True\n self.padding_value = 0\n self.input = np.array([[0, 1, 2, 2, 0, 4], [0, 4, 5, 0, 6, 0],\n [0, 7, 7, 7, 0, 0]]).reshape(\n [3, 6]).astype(\"int32\")\n self.input_length = np.array([[6], [5],\n [4]]).reshape([3, 1]).astype(\"int32\")\n\n\nclass TestCTCAlignOpCase4(TestCTCAlignPaddingOp):\n '''\n # test tensor input which has attr input padding_value\n '''\n\n def config(self):\n self.op_type = \"ctc_align\"\n self.blank = 0\n self.input_lod = []\n self.merge_repeated = False\n self.padding_value = 0\n self.input = np.array([[0, 1, 2, 2, 0, 4], [0, 4, 5, 0, 6, 0],\n [0, 7, 7, 7, 0, 0]]).reshape(\n [3, 6]).astype(\"int32\")\n self.input_length = np.array([[6], [5],\n [4]]).reshape([3, 1]).astype(\"int32\")\n\n\nclass TestCTCAlignOpCase5(TestCTCAlignPaddingOp):\n def config(self):\n self.op_type = \"ctc_align\"\n self.blank = 0\n self.input_lod = []\n self.merge_repeated = False\n self.padding_value = 1\n self.input = np.array([[0, 1, 2, 2, 0, 4], [0, 4, 5, 0, 6, 0],\n [0, 7, 1, 7, 0, 0]]).reshape(\n [3, 6]).astype(\"int32\")\n self.input_length = np.array([[6], [5],\n [4]]).reshape([3, 1]).astype(\"int32\")\n\n\nclass TestCTCAlignOpApi(unittest.TestCase):\n def test_api(self):\n x = fluid.layers.data('x', shape=[4], dtype='float32')\n y = fluid.layers.ctc_greedy_decoder(x, blank=0)\n\n x_pad = fluid.layers.data('x_pad', shape=[4, 4], dtype='float32')\n x_pad_len = fluid.layers.data('x_pad_len', shape=[1], dtype='int64')\n y_pad, y_pad_len = fluid.layers.ctc_greedy_decoder(\n x_pad, blank=0, input_length=x_pad_len)\n\n place = fluid.CPUPlace()\n x_tensor = fluid.create_lod_tensor(\n np.random.rand(8, 4).astype(\"float32\"), [[4, 4]], place)\n\n x_pad_tensor = np.random.rand(2, 4, 4).astype(\"float32\")\n x_pad_len_tensor = np.array([[4], [4]]).reshape([2, 1]).astype(\"int64\")\n\n exe = fluid.Executor(place)\n\n exe.run(fluid.default_startup_program())\n ret = exe.run(feed={\n 'x': x_tensor,\n 'x_pad': x_pad_tensor,\n 'x_pad_len': x_pad_len_tensor\n },\n fetch_list=[y, y_pad, y_pad_len],\n return_numpy=False)\n\n\nclass BadInputTestCTCAlignr(unittest.TestCase):\n def test_error(self):\n with fluid.program_guard(fluid.Program()):\n\n def test_bad_x():\n x = fluid.layers.data(name='x', shape=[8], dtype='int64')\n cost = fluid.layers.ctc_greedy_decoder(input=x, blank=0)\n\n self.assertRaises(TypeError, test_bad_x)\n\n\nif __name__ == \"__main__\":\n paddle.enable_static()\n unittest.main()\n", "# Copyright (c) 2018 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 __future__ import print_function\nimport sys\n\nsys.path.append(\"..\")\nimport unittest\nimport op_test\nimport numpy as np\nimport paddle\nimport paddle.fluid.core as core\nimport paddle.fluid as fluid\nfrom paddle.fluid import compiler, Program, program_guard\n\ntypeid_dict = {\n 'int32': int(core.VarDesc.VarType.INT32),\n 'int64': int(core.VarDesc.VarType.INT64),\n 'float32': int(core.VarDesc.VarType.FP32),\n 'float16': int(core.VarDesc.VarType.FP16),\n 'bool': int(core.VarDesc.VarType.BOOL),\n}\n\n\ndef create_test_class(in_typename, out_typename):\n class Cls(op_test.OpTest):\n def setUp(self):\n ipt = np.random.random(size=[10, 10])\n self.inputs = {'X': ipt.astype(in_typename)}\n self.outputs = {'Out': ipt.astype(in_typename).astype(out_typename)}\n self.attrs = {\n 'in_dtype': typeid_dict[in_typename],\n 'out_dtype': typeid_dict[out_typename],\n }\n self.op_type = 'cast'\n self.__class__.no_need_check_grad = True\n\n def test_check_output(self):\n if paddle.is_compiled_with_xpu():\n place = paddle.XPUPlace(0)\n self.check_output_with_place(place)\n\n cls_name = \"cast_{0}_{1}\".format(in_typename, out_typename)\n Cls.__name__ = cls_name\n globals()[cls_name] = Cls\n\n\nfor in_type in {'float16', 'float32', 'int32', 'int64', 'bool'}:\n for out_type in {'float16', 'float32', 'int32', 'int64'}:\n create_test_class(in_type, out_type)\n\n\nclass TestCastOpError(unittest.TestCase):\n def test_errors(self):\n with program_guard(Program(), Program()):\n # The input type of cast_op must be Variable.\n x1 = fluid.create_lod_tensor(\n np.array([[-1]]), [[1]], fluid.XPUPlace(0))\n self.assertRaises(TypeError, fluid.layers.cast, x1, 'int32')\n\n\nif __name__ == '__main__':\n paddle.enable_static()\n unittest.main()\n" ]
[ [ "numpy.float" ], [ "numpy.asscalar", "numpy.zeros" ], [ "numpy.array" ], [ "numpy.inner", "numpy.random.randn", "numpy.random.rand", "numpy.random.seed" ], [ "numpy.random.normal", "numpy.random.random", "numpy.random.seed" ], [ "numpy.array", "numpy.random.rand" ], [ "numpy.array", "numpy.random.random" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wilsongis/3DP_Experiments
[ "da9bd3b4ba1d82bac7dcfa27d86634add59db087" ]
[ "Samples/codes/matopt_review/add_objective.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCopyright (c) 2021 Showa Denko Materials co., Ltd. All rights reserved.\n\nThis software is for non-profit use only.\n\nTHIS SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\nINCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\nIN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THIS SOFTWARE OR THE USE OR OTHER DEALINGS IN THIS SOFTWARE.\n\"\"\"\n\nimport time\nimport numpy as np\nfrom GPyOpt.core.task.objective import Objective\n\nclass MultiObjective(Objective):\n \"\"\"\n Class to handle problems with multiple objective functions.\n\n param func: objective function.\n param n_obj: number of objective functions\n param num_cores: number of cores to use in the process of evaluating the objective (default, 1).\n param objective_name: name of the objective function.\n param batch_type: Type of batch used. Only 'synchronous' evaluations are possible at the moment.\n param space: Not in use.\n\n \"\"\"\n\n\n def __init__(self, func, n_obj, num_cores = 1, objective_name = 'no_name', batch_type = 'synchronous', space = None):\n self.func = func\n self.n_procs = num_cores\n self.num_evaluations = 0\n self.space = space\n self.objective_name = objective_name\n self.n_obj = n_obj\n\n\n def evaluate(self, x):\n \"\"\"\n Performs the evaluation of the objective at x.\n \"\"\"\n\n f_evals, cost_evals = self._eval_func(x)\n return f_evals, cost_evals\n\n\n def _eval_func(self, x):\n \"\"\"\n Performs sequential evaluations of the function at x (single location or batch). The computing time of each\n evaluation is also provided.\n \"\"\"\n cost_evals = []\n f_evals = np.empty(shape=[0, self.n_obj])\n\n for i in range(x.shape[0]):\n st_time = time.time()\n rlt = self.func(np.atleast_2d(x[i]))\n f_evals = np.vstack([f_evals,rlt])\n cost_evals += [time.time()-st_time]\n return f_evals, cost_evals\n" ]
[ [ "numpy.atleast_2d", "numpy.vstack", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JiwanChung/acav100m
[ "51cb948d5682da69334a8d05d2df631971b60215" ]
[ "subset_selection/code/measures/contrastive/contrastive.py" ]
[ "import csv\nfrom pathlib import Path\n\nimport torch\nimport pandas\nimport numpy as np\n\nfrom utils import peek, load_json, dump_json\nfrom .module import ContrastiveModule\nfrom mps import distributed as du\nfrom save import format_rows\n\n\ndef get_penultimates(keys):\n penultimates = {}\n for key in keys:\n view = key[:key.find('_')] # get dataset+model name\n layer_name = key[key.find('_') + 1:]\n if view not in penultimates:\n penultimates[view] = view + '_' + layer_name\n elif layer_name > penultimates[view]:\n penultimates[view] = view + '_' + layer_name\n keys = sorted(list(penultimates.keys()))\n return [penultimates[k] for k in keys]\n\n\ndef get_optimizer(params, lr=1e-3):\n optimizer = torch.optim.AdamW(\n params,\n lr=lr,\n betas=(0.9, 0.999),\n eps=1e-6,\n amsgrad=True,\n )\n return optimizer\n\n\ndef set_lr(optimizer, lr):\n for param in optimizer.param_groups:\n param['lr'] = lr\n return optimizer\n\n\ndef lr_func_linear(current_step, num_training_steps, num_warmup_steps=3):\n if current_step < num_warmup_steps:\n return float(current_step) / float(max(1, num_warmup_steps))\n return max(0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)))\n\n\ndef update_lr(optimizer, epoch, num_epochs, base_lr=1e-3, num_warmup_steps=3):\n lr = lr_func_linear(epoch + 1, num_epochs + 1, num_warmup_steps) * base_lr\n optimizer = set_lr(optimizer, lr)\n return optimizer, lr\n\n\nclass Contrastive:\n def __init__(self, num_epochs=1, device='cpu', base_lr=1e-4,\n num_warmup_steps=3, distributed=False):\n self.num_epochs = num_epochs\n self.device = device\n self.base_lr = base_lr\n self.num_warmup_steps = num_warmup_steps\n self.distributed = distributed\n self.epoch = 0\n\n # sizes = self.get_sizes(train)\n sizes = self.default_sizes\n self.model = ContrastiveModule(*sizes, use_global_batch=distributed)\n self.model = self.model.to(self.device)\n\n def init(self, clustering_combinations, candidates):\n pass\n\n @property\n def default_sizes(self):\n # video (slowfast) : 2304, audio (VGGish) : 128\n return [2304, 128]\n\n def get_sizes(self, train):\n class_data = peek(train)\n row = class_data[0]\n penultimates = get_penultimates(list(row['features'].keys()))\n return [row['features'][k].shape[-1] for k in penultimates]\n\n def get_feature_names(self, train):\n class_data = peek(train)\n row = peek(class_data)\n return sorted(list(row.keys()))\n\n def train_batch(self, batch, optimizer):\n moved = []\n for feature in batch:\n moved.append(feature.to(self.device))\n loss, acc = self.model(*moved)\n loss.backward()\n if self.distributed:\n self.model.average_gradient()\n optimizer.step()\n return loss.item(), acc.item()\n\n def _get_features(self, batch):\n unique_ids = pandas.Series(batch['idx']).drop_duplicates().index.tolist()\n filenames = [batch['filename'][idx] for idx in unique_ids]\n ids = [batch['idx'][idx] for idx in unique_ids]\n shard_names = [batch['shard_name'][idx] for idx in unique_ids]\n metas = [{'id': idx, 'filename': filename, 'shard_name': shard_name}\n for idx, filename, shard_name in zip(ids, filenames, shard_names)]\n\n video_features = batch['SLOWFAST_8x8_R50/kinetics-400']['layer_4']\n audio_features = batch['VGGish/YouTube-8M']['layer_4']\n unique_ids = torch.Tensor(unique_ids).long()\n video_features = video_features.index_select(dim=0, index=unique_ids)\n audio_features = audio_features.index_select(dim=0, index=unique_ids)\n return metas, [video_features, audio_features]\n\n def get_features(self, batch):\n metas, [video_features, audio_features] = self._get_features(batch)\n if self.distributed:\n i = du.get_rank()\n total = du.get_world_size()\n metas = metas[i::total]\n video_features = video_features[i::total]\n audio_features = audio_features[i::total]\n return metas, [video_features, audio_features]\n\n def train(self, args, path, dataloader, log_every=1, verbose=True):\n self.model.train()\n optimizer = get_optimizer(self.model.parameters(), self.base_lr)\n for epoch in range(self.epoch, self.num_epochs):\n optimizer, lr = update_lr(optimizer, epoch, self.num_epochs, self.base_lr,\n self.num_warmup_steps)\n epoch_loss = []\n epoch_acc = []\n pbar = dataloader\n for count, batch in enumerate(pbar):\n _, features = self.get_features(batch)\n loss, acc = self.train_batch(features, optimizer)\n epoch_loss.append(loss)\n epoch_acc.append(acc)\n if verbose and count % log_every == 0:\n print(\"(node {}) training epoch ({}/{}) iter ({}/{}) (lr: {:04f}, loss: {:04f}, acc: {:04f})\".format(\n du.get_rank(), epoch, self.num_epochs, count, len(dataloader), lr, loss, acc))\n epoch_loss = np.array(epoch_loss).mean()\n epoch_acc = np.array(epoch_acc).mean()\n if verbose:\n print(\"(node {}) epoch ({}/{}) done (lr: {:04f}, loss: {:04f}, acc: {:04f})\".format(\n du.get_rank(), epoch, self.num_epochs, lr, epoch_loss, epoch_acc))\n self.epoch = epoch\n self.save_cache(args, path, epoch, verbose)\n\n return\n\n def get_cache_path_run(self, args, epoch):\n cache_dir = args.data.output.path.parent / 'caches'\n cache_dir.mkdir(parents=True, exist_ok=True)\n pid = args.parent_pid\n rank = args.node_rank\n i = args.chunk_num\n name = \"contrastive_model_cache_epoch_{}_{}_{}_{}.pkl\".format(epoch, pid, rank, i)\n path = str(cache_dir / name)\n key_name = \"contrastive_model_cache_epoch_{}_{}_{}_{}.json\".format(epoch, pid, rank, i)\n key_path = str(cache_dir / key_name)\n return path, key_path\n\n def get_cache_path_load(self, args, path, epoch):\n cache_dir = args.data.output.path.parent / 'caches'\n cache_dir.mkdir(parents=True, exist_ok=True)\n keys = list(cache_dir.glob(\"contrastive_model_cache_epoch_{}_*.json\".format(epoch)))\n if len(keys) == 0:\n return None\n keys = {p.stem: set(load_json(p)) for p in keys}\n path = set([Path(p).stem for p in path])\n intersections = [(k, len(v & path)) for k, v in keys.items() if len(path - v) == 0]\n if len(intersections) == 0:\n return None\n key = max(intersections, key=lambda x: x[1])[0]\n path = cache_dir / key\n path = path.parent / (path.stem + '.pkl')\n return path\n\n def save_cache(self, args, chunks, epoch, verbose=True):\n path, key_path = self.get_cache_path_run(args, epoch)\n dt = {\n 'epoch': self.epoch,\n 'base_lr': self.base_lr,\n 'model': self.model.state_dict()\n }\n if verbose:\n print(\"saved cache file: {}\".format(Path(path).stem))\n torch.save(dt, path)\n keys = [Path(p).stem for p in chunks]\n dump_json(keys, key_path)\n\n def load_cache(self, args, path, epoch):\n path = self.get_cache_path_load(args, path, epoch)\n assert path is not None, 'no cache file'\n dt = torch.load(path)\n self.epoch = dt['epoch']\n self.base_lr = dt['base_lr']\n self.model.load_state_dict(dt['model'])\n\n def infer_batch(self, batch):\n moved = []\n for feature in batch:\n moved.append(feature.to(self.device))\n logits = self.model.infer(*moved)\n return logits.detach().cpu()\n\n def infer(self, args, dataloader, json_metas, subset_size, log_every=1, verbose=True):\n self.model.eval()\n with torch.no_grad():\n logits, filename_ids = self._infer(args, dataloader, json_metas, log_every, verbose)\n if subset_size > logits.shape[0]:\n subset_size = logits.shape[0]\n scores, ids = logits.topk(subset_size, sorted=True)\n return scores, ids, filename_ids\n\n def _infer(self, args, dataloader, json_metas, log_every=1, verbose=True):\n logits = []\n pbar = dataloader\n metas = []\n for count, batch in enumerate(pbar):\n batch_metas, features = self.get_features(batch)\n logit = self.infer_batch(features)\n logits.append(logit)\n metas.extend(batch_metas)\n if verbose and count % log_every == 0:\n print(\"inference iter ({}/{}) saving caches\".format(count, len(dataloader)))\n logits = torch.cat(logits, dim=0)\n self.save_inference(args, logits, metas, json_metas)\n logits = []\n metas = []\n if len(metas) > 0:\n logits = torch.cat(logits, dim=0)\n self.save_inference(args, logits, metas, json_metas)\n print(\"done: inference iter ({}/{}) saving caches\".format(count, len(dataloader)))\n return logits, metas\n\n def save_inference(self, args, logits, metas, json_metas):\n cache_dir = args.data.output.path.parent / 'caches'\n cache_dir.mkdir(parents=True, exist_ok=True)\n pid = args.parent_pid\n local_rank = du.get_rank()\n output_name = Path(args.data.output.path).stem\n name = \"{}_contrastive_inferred_cache_{}_{}.csv\".format(output_name, pid, local_rank)\n\n scores = logits.numpy().tolist()\n rows = [{'score': score, **v} for score, v in zip(scores, metas)]\n lines = format_rows(rows, json_metas, sharded_meta=True,\n headers=['score', 'shard_name', 'filename', 'id', 'segment'])\n\n print(\"saving cache to {}\".format(cache_dir / name))\n with open(cache_dir / name, 'a+') as f:\n writer = csv.writer(f)\n for line in lines:\n writer.writerow(line)\n" ]
[ [ "pandas.Series", "torch.Tensor", "torch.load", "torch.cat", "torch.optim.AdamW", "torch.no_grad", "numpy.array", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
Genevievekim/semantic-segmentation-1
[ "f28b026e44cff80fe3ca4cac94cea27e4073821b", "f28b026e44cff80fe3ca4cac94cea27e4073821b", "f28b026e44cff80fe3ca4cac94cea27e4073821b", "f28b026e44cff80fe3ca4cac94cea27e4073821b" ]
[ "semseg/models/bisenetv1.py", "semseg/datasets/ade20k.py", "semseg/datasets/helen.py", "scripts/onnx_infer.py" ]
[ "import torch \nimport math\nfrom torch import nn, Tensor\nfrom torch.nn import functional as F\nfrom semseg.models.backbones import *\nfrom semseg.models.modules.common import ConvModule\n\n\nclass SpatialPath(nn.Module):\n def __init__(self, c1, c2) -> None:\n super().__init__()\n ch = 64\n self.conv_7x7 = ConvModule(c1, ch, 7, 2, 3)\n self.conv_3x3_1 = ConvModule(ch, ch, 3, 2, 1)\n self.conv_3x3_2 = ConvModule(ch, ch, 3, 2, 1)\n self.conv_1x1 = ConvModule(ch, c2, 1, 1, 0)\n\n def forward(self, x): \n x = self.conv_7x7(x)\n x = self.conv_3x3_1(x)\n x = self.conv_3x3_2(x)\n return self.conv_1x1(x)\n\n\nclass ContextPath(nn.Module):\n def __init__(self, backbone: nn.Module) -> None:\n super().__init__()\n self.backbone = backbone\n c3, c4 = self.backbone.channels[-2:]\n\n self.arm16 = AttentionRefinmentModule(c3, 128)\n self.arm32 = AttentionRefinmentModule(c4, 128)\n\n self.global_context = nn.Sequential(\n nn.AdaptiveAvgPool2d(1),\n ConvModule(c4, 128, 1, 1, 0)\n )\n\n self.up16 = nn.Upsample(scale_factor=2.0, mode='bilinear', align_corners=True)\n self.up32 = nn.Upsample(scale_factor=2.0, mode='bilinear', align_corners=True)\n\n self.refine16 = ConvModule(128, 128, 3, 1, 1)\n self.refine32 = ConvModule(128, 128, 3, 1, 1)\n\n\n def forward(self, x):\n _, _, down16, down32 = self.backbone(x) # 4x256x64x128, 4x512x32x64\n\n arm_down16 = self.arm16(down16) # 4x128x64x128\n arm_down32 = self.arm32(down32) # 4x128x32x64\n\n global_down32 = self.global_context(down32) # 4x128x1x1\n global_down32 = F.interpolate(global_down32, size=down32.size()[2:], mode='bilinear', align_corners=True) # 4x128x32x64\n\n arm_down32 = arm_down32 + global_down32 # 4x128x32x64\n arm_down32 = self.up32(arm_down32) # 4x128x64x128\n arm_down32 = self.refine32(arm_down32) # 4x128x64x128\n\n arm_down16 = arm_down16 + arm_down32 # 4x128x64x128\n arm_down16 = self.up16(arm_down16) # 4x128x128x256\n arm_down16 = self.refine16(arm_down16) # 4x128x128x256 \n\n return arm_down16, arm_down32\n\n\nclass AttentionRefinmentModule(nn.Module):\n def __init__(self, c1, c2) -> None:\n super().__init__()\n self.conv_3x3 = ConvModule(c1, c2, 3, 1, 1)\n\n self.attention = nn.Sequential(\n nn.AdaptiveAvgPool2d(1),\n nn.Conv2d(c2, c2, 1, bias=False),\n nn.BatchNorm2d(c2),\n nn.Sigmoid()\n )\n\n def forward(self, x):\n fm = self.conv_3x3(x)\n fm_se = self.attention(fm)\n return fm * fm_se\n\n\nclass FeatureFusionModule(nn.Module):\n def __init__(self, c1, c2, reduction=1) -> None:\n super().__init__()\n self.conv_1x1 = ConvModule(c1, c2, 1, 1, 0)\n\n self.attention = nn.Sequential(\n nn.AdaptiveAvgPool2d(1),\n nn.Conv2d(c2, c2 // reduction, 1, bias=False),\n nn.ReLU(True),\n nn.Conv2d(c2 // reduction, c2, 1, bias=False),\n nn.Sigmoid()\n )\n\n def forward(self, x1, x2):\n fm = torch.cat([x1, x2], dim=1)\n fm = self.conv_1x1(fm)\n fm_se = self.attention(fm)\n return fm + fm * fm_se\n\n\nclass Head(nn.Module):\n def __init__(self, c1, n_classes, upscale_factor, is_aux=False) -> None:\n super().__init__()\n ch = 256 if is_aux else 64\n c2 = n_classes * upscale_factor * upscale_factor\n self.conv_3x3 = ConvModule(c1, ch, 3, 1, 1)\n self.conv_1x1 = nn.Conv2d(ch, c2, 1, 1, 0)\n self.upscale = nn.PixelShuffle(upscale_factor)\n\n def forward(self, x):\n x = self.conv_1x1(self.conv_3x3(x))\n return self.upscale(x)\n\n\nclass BiSeNetv1(nn.Module):\n def __init__(self, backbone: str = 'ResNet-18', num_classes: int = 19) -> None:\n super().__init__()\n backbone, variant = backbone.split('-')\n\n self.context_path = ContextPath(eval(backbone)(variant))\n self.spatial_path = SpatialPath(3, 128)\n self.ffm = FeatureFusionModule(256, 256)\n\n self.output_head = Head(256, num_classes, upscale_factor=8, is_aux=False)\n self.context16_head = Head(128, num_classes, upscale_factor=8, is_aux=True)\n self.context32_head = Head(128, num_classes, upscale_factor=16, is_aux=True)\n\n self.apply(self._init_weights)\n\n def _init_weights(self, m: nn.Module) -> None:\n if isinstance(m, nn.Conv2d):\n fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n fan_out // m.groups\n m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))\n if m.bias is not None:\n nn.init.zeros_(m.bias)\n elif isinstance(m, (nn.LayerNorm, nn.BatchNorm2d)):\n nn.init.ones_(m.weight)\n nn.init.zeros_(m.bias)\n\n def init_pretrained(self, pretrained: str = None) -> None:\n if pretrained:\n self.context_path.backbone.load_state_dict(torch.load(pretrained, map_location='cpu'), strict=False)\n\n def forward(self, x): # 4x3x1024x2048 \n spatial_out = self.spatial_path(x) # 4x128x128x256\n context16, context32 = self.context_path(x) # 4x128x128x256, 4x128x64x128\n\n fm_fuse = self.ffm(spatial_out, context16) # 4x256x128x256\n output = self.output_head(fm_fuse) # 4xn_classesx1024x2048\n\n if self.training:\n context_out16 = self.context16_head(context16) # 4xn_classesx1024x2048\n context_out32 = self.context32_head(context32) # 4xn_classesx1024x2048\n return output, context_out16, context_out32\n return output \n\n\nif __name__ == '__main__':\n model = BiSeNetv1('MobileNetV2-1.0', 19)\n # model.init_pretrained('checkpoints/backbones/resnet/resnet18.pth')\n model.eval()\n image = torch.randn(1, 3, 224, 224)\n output = model(image)\n print(output.shape)", "import torch \nfrom torch import Tensor\nfrom torch.utils.data import Dataset\nfrom torchvision import io\nfrom pathlib import Path\nfrom typing import Tuple\n\n\nclass ADE20K(Dataset):\n CLASSES = [\n 'wall', 'building', 'sky', 'floor', 'tree', 'ceiling', 'road', 'bed ', 'windowpane', 'grass', 'cabinet', 'sidewalk', 'person', 'earth',\n 'door', 'table', 'mountain', 'plant', 'curtain', 'chair', 'car', 'water', 'painting', 'sofa', 'shelf', 'house', 'sea', 'mirror', 'rug',\n 'field', 'armchair', 'seat', 'fence', 'desk', 'rock', 'wardrobe', 'lamp', 'bathtub', 'railing', 'cushion', 'base', 'box', 'column',\n 'signboard', 'chest of drawers', 'counter', 'sand', 'sink', 'skyscraper', 'fireplace', 'refrigerator', 'grandstand', 'path',\n 'stairs', 'runway', 'case', 'pool table', 'pillow', 'screen door', 'stairway', 'river', 'bridge', 'bookcase', 'blind', 'coffee table',\n 'toilet', 'flower', 'book', 'hill', 'bench', 'countertop', 'stove', 'palm', 'kitchen island', 'computer', 'swivel chair', 'boat', 'bar',\n 'arcade machine', 'hovel', 'bus', 'towel', 'light', 'truck', 'tower', 'chandelier', 'awning', 'streetlight', 'booth', 'television receiver',\n 'airplane', 'dirt track', 'apparel', 'pole', 'land', 'bannister', 'escalator', 'ottoman', 'bottle', 'buffet', 'poster', 'stage', 'van',\n 'ship', 'fountain', 'conveyer belt', 'canopy', 'washer', 'plaything', 'swimming pool', 'stool', 'barrel', 'basket', 'waterfall', 'tent',\n 'bag', 'minibike', 'cradle', 'oven', 'ball', 'food', 'step', 'tank', 'trade name', 'microwave', 'pot', 'animal', 'bicycle', 'lake',\n 'dishwasher', 'screen', 'blanket', 'sculpture', 'hood', 'sconce', 'vase', 'traffic light', 'tray', 'ashcan', 'fan', 'pier', 'crt screen',\n 'plate', 'monitor', 'bulletin board', 'shower', 'radiator', 'glass', 'clock', 'flag'\n ]\n\n PALETTE = torch.tensor([\n [120, 120, 120], [180, 120, 120], [6, 230, 230], [80, 50, 50], [4, 200, 3], [120, 120, 80], [140, 140, 140], [204, 5, 255],\n [230, 230, 230], [4, 250, 7], [224, 5, 255], [235, 255, 7], [150, 5, 61], [120, 120, 70], [8, 255, 51], [255, 6, 82],\n [143, 255, 140], [204, 255, 4], [255, 51, 7], [204, 70, 3], [0, 102, 200], [61, 230, 250], [255, 6, 51], [11, 102, 255],\n [255, 7, 71], [255, 9, 224], [9, 7, 230], [220, 220, 220], [255, 9, 92], [112, 9, 255], [8, 255, 214], [7, 255, 224],\n [255, 184, 6], [10, 255, 71], [255, 41, 10], [7, 255, 255], [224, 255, 8], [102, 8, 255], [255, 61, 6], [255, 194, 7],\n [255, 122, 8], [0, 255, 20], [255, 8, 41], [255, 5, 153], [6, 51, 255], [235, 12, 255], [160, 150, 20], [0, 163, 255],\n [140, 140, 140], [250, 10, 15], [20, 255, 0], [31, 255, 0], [255, 31, 0], [255, 224, 0], [153, 255, 0], [0, 0, 255],\n [255, 71, 0], [0, 235, 255], [0, 173, 255], [31, 0, 255], [11, 200, 200], [255, 82, 0], [0, 255, 245], [0, 61, 255],\n [0, 255, 112], [0, 255, 133], [255, 0, 0], [255, 163, 0], [255, 102, 0], [194, 255, 0], [0, 143, 255], [51, 255, 0],\n [0, 82, 255], [0, 255, 41], [0, 255, 173], [10, 0, 255], [173, 255, 0], [0, 255, 153], [255, 92, 0], [255, 0, 255],\n [255, 0, 245], [255, 0, 102], [255, 173, 0], [255, 0, 20], [255, 184, 184], [0, 31, 255], [0, 255, 61], [0, 71, 255],\n [255, 0, 204], [0, 255, 194], [0, 255, 82], [0, 10, 255], [0, 112, 255], [51, 0, 255], [0, 194, 255], [0, 122, 255],\n [0, 255, 163], [255, 153, 0], [0, 255, 10], [255, 112, 0], [143, 255, 0], [82, 0, 255], [163, 255, 0], [255, 235, 0],\n [8, 184, 170], [133, 0, 255], [0, 255, 92], [184, 0, 255], [255, 0, 31], [0, 184, 255], [0, 214, 255], [255, 0, 112],\n [92, 255, 0], [0, 224, 255], [112, 224, 255], [70, 184, 160], [163, 0, 255], [153, 0, 255], [71, 255, 0], [255, 0, 163],\n [255, 204, 0], [255, 0, 143], [0, 255, 235], [133, 255, 0], [255, 0, 235], [245, 0, 255], [255, 0, 122], [255, 245, 0],\n [10, 190, 212], [214, 255, 0], [0, 204, 255], [20, 0, 255], [255, 255, 0], [0, 153, 255], [0, 41, 255], [0, 255, 204],\n [41, 0, 255], [41, 255, 0], [173, 0, 255], [0, 245, 255], [71, 0, 255], [122, 0, 255], [0, 255, 184], [0, 92, 255],\n [184, 255, 0], [0, 133, 255], [255, 214, 0], [25, 194, 194], [102, 255, 0], [92, 0, 255]\n ])\n\n def __init__(self, root: str, split: str = 'train', transform = None) -> None:\n super().__init__()\n assert split in ['train', 'val']\n split = 'training' if split == 'train' else 'validation'\n self.transform = transform\n self.n_classes = len(self.CLASSES)\n self.ignore_label = -1\n\n img_path = Path(root) / 'images' / split \n self.files = list(img_path.glob('*.jpg'))\n \n if not self.files:\n raise Exception(f\"No images found in {img_path}\")\n print(f\"Found {len(self.files)} {split} images.\")\n\n def __len__(self) -> int:\n return len(self.files)\n\n def __getitem__(self, index: int) -> Tuple[Tensor, Tensor]:\n img_path = str(self.files[index])\n lbl_path = str(self.files[index]).replace('images', 'annotations').replace('.jpg', '.png')\n\n image = io.read_image(img_path)\n label = io.read_image(lbl_path)\n \n if self.transform:\n image, label = self.transform(image, label)\n return image, label.squeeze().long() - 1\n\n\nif __name__ == '__main__':\n from semseg.utils.visualize import visualize_dataset_sample\n visualize_dataset_sample(ADE20K, '/home/sithu/datasets/ADEChallenge/ADEChallengeData2016')", "import torch \nfrom torch import Tensor\nfrom torch.utils.data import Dataset\nfrom torchvision import io\nfrom pathlib import Path\nfrom typing import Tuple\n\n\nclass HELEN(Dataset):\n CLASSES = ['background', 'skin', 'l-brow', 'r-brow', 'l-eye', 'r-eye', 'nose', 'u-lip', 'i-mouth', 'l-lip', 'hair']\n PALETTE = torch.tensor([[0, 0 ,0], [127, 0, 0], [254, 0, 0], [0, 84, 0], [169, 0, 50], [254, 84, 0], [255, 0, 84], [0, 118, 220], [84, 84, 0], [0, 84, 84], [84, 50, 0]])\n\n def __init__(self, root: str, split: str = 'train', transform = None) -> None:\n super().__init__()\n assert split in ['train', 'val', 'test']\n self.transform = transform\n self.n_classes = len(self.CLASSES)\n self.ignore_label = 255\n\n self.files = self.get_files(root, split)\n if not self.files: raise Exception(f\"No images found in {root}\")\n print(f\"Found {len(self.files)} {split} images.\")\n\n def get_files(self, root: str, split: str):\n root = Path(root)\n if split == 'train':\n split = 'exemplars'\n elif split == 'val':\n split = 'tuning'\n else:\n split = 'testing'\n with open(root / f'{split}.txt') as f:\n lines = f.read().splitlines()\n \n split_names = [line.split(',')[-1].strip() for line in lines if line != '']\n files = (root / 'images').glob(\"*.jpg\")\n files = list(filter(lambda x: x.stem in split_names, files))\n return files\n\n def __len__(self) -> int:\n return len(self.files)\n\n def __getitem__(self, index: int) -> Tuple[Tensor, Tensor]:\n img_path = str(self.files[index])\n lbl_path = str(self.files[index]).split('.')[0].replace('images', 'labels')\n image = io.read_image(img_path)\n label = self.encode(lbl_path)\n\n if self.transform:\n image, label = self.transform(image, label)\n return image, label.squeeze().long()\n\n def encode(self, label_path: str) -> Tensor:\n mask_paths = sorted(list(Path(label_path).glob('*.png')))\n for i, mask_path in enumerate(mask_paths):\n mask = io.read_image(str(mask_path)).squeeze()\n if i == 0:\n label = torch.zeros(self.n_classes, *mask.shape)\n label[i, ...] = mask\n label = label.argmax(dim=0).unsqueeze(0)\n return label \n\n\nif __name__ == '__main__':\n from semseg.utils.visualize import visualize_dataset_sample\n visualize_dataset_sample(HELEN, '/home/sithu/datasets/SmithCVPR2013_dataset_resized')", "import argparse\nimport numpy as np\nimport onnxruntime\nfrom PIL import Image\nimport sys\nsys.path.insert(0, '.')\nfrom semseg.utils.visualize import generate_palette\nfrom semseg.utils.utils import timer\n\n\nclass Inference:\n def __init__(self, model: str) -> None:\n self.session = onnxruntime.InferenceSession(model)\n self.input_details = self.session.get_inputs()[0]\n self.palette = generate_palette(self.session.get_outputs()[0].shape[1], background=True)\n self.img_size = self.input_details.shape[-2:]\n self.mean = np.array([0.485, 0.456, 0.406]).reshape(-1, 1, 1)\n self.std = np.array([0.229, 0.224, 0.225]).reshape(-1, 1, 1)\n\n def preprocess(self, image: Image.Image) -> np.ndarray:\n image = image.resize(self.img_size)\n image = np.array(image, dtype=np.float32).transpose(2, 0, 1)\n image /= 255\n image -= self.mean\n image /= self.std\n image = image[np.newaxis, ...]\n return image\n\n def postprocess(self, seg_map: np.ndarray) -> np.ndarray:\n seg_map = np.argmax(seg_map, axis=1).astype(int)\n seg_map = self.palette[seg_map]\n return seg_map.squeeze()\n\n @timer\n def model_forward(self, img: np.ndarray) -> np.ndarray:\n return self.session.run(None, {self.input_details.name: img})[0]\n\n def predict(self, img_path: str) -> Image.Image:\n image = Image.open(img_path).convert('RGB')\n image = self.preprocess(image)\n seg_map = self.model_forward(image)\n seg_map = self.postprocess(seg_map)\n return seg_map.astype(np.uint8)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--model', type=str, default='output/DDRNet_23slim_HELEN_59_75.onnx')\n parser.add_argument('--img-path', type=str, default='assests/faces/27409477_1.jpg')\n args = parser.parse_args()\n\n session = Inference(args.model)\n seg_map = session.predict(args.img_path)\n seg_map = Image.fromarray(seg_map)\n seg_map.save(f\"{args.img_path.split('.')[0]}_out.png\")" ]
[ [ "torch.cat", "torch.nn.init.zeros_", "torch.randn", "torch.load", "torch.nn.Conv2d", "torch.nn.PixelShuffle", "torch.nn.Sigmoid", "torch.nn.init.ones_", "torch.nn.Upsample", "torch.nn.AdaptiveAvgPool2d", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ], [ "torch.tensor" ], [ "torch.zeros", "torch.tensor" ], [ "numpy.array", "numpy.argmax" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
aryaman4/tensorboard
[ "72a104edb0f8d83ef8889ebee7dd39be684461c1" ]
[ "tensorboard/plugins/hparams/backend_context_test.py" ]
[ "# Copyright 2019 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\"\"\"Tests for backend_context.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport operator\n\ntry:\n # python version >= 3.3\n from unittest import mock\nexcept ImportError:\n import mock # pylint: disable=unused-import\nimport tensorflow as tf\n\nfrom google.protobuf import text_format\nfrom tensorboard import context\nfrom tensorboard.backend.event_processing import data_provider\nfrom tensorboard.backend.event_processing import event_accumulator\nfrom tensorboard.backend.event_processing import plugin_event_multiplexer\nfrom tensorboard.compat.proto import summary_pb2\nfrom tensorboard.plugins import base_plugin\nfrom tensorboard.plugins.hparams import api_pb2\nfrom tensorboard.plugins.hparams import backend_context\nfrom tensorboard.plugins.hparams import metadata\nfrom tensorboard.plugins.hparams import plugin_data_pb2\nfrom tensorboard.plugins.scalar import metadata as scalars_metadata\n\nDATA_TYPE_EXPERIMENT = \"experiment\"\nDATA_TYPE_SESSION_START_INFO = \"session_start_info\"\nDATA_TYPE_SESSION_END_INFO = \"session_end_info\"\n\n\nclass BackendContextTest(tf.test.TestCase):\n # Make assertProtoEquals print all the diff.\n maxDiff = None # pylint: disable=invalid-name\n\n def setUp(self):\n self._mock_tb_context = base_plugin.TBContext()\n # TODO(#3425): Remove mocking or switch to mocking data provider\n # APIs directly.\n self._mock_multiplexer = mock.create_autospec(\n plugin_event_multiplexer.EventMultiplexer\n )\n self._mock_tb_context.multiplexer = self._mock_multiplexer\n self._mock_multiplexer.PluginRunToTagToContent.side_effect = (\n self._mock_plugin_run_to_tag_to_content\n )\n self._mock_multiplexer.AllSummaryMetadata.side_effect = (\n self._mock_all_summary_metadata\n )\n self._mock_multiplexer.SummaryMetadata.side_effect = (\n self._mock_summary_metadata\n )\n self._mock_tb_context.data_provider = data_provider.MultiplexerDataProvider(\n self._mock_multiplexer, \"/path/to/logs\"\n )\n self.session_1_start_info_ = \"\"\n self.session_2_start_info_ = \"\"\n self.session_3_start_info_ = \"\"\n\n def _mock_all_summary_metadata(self):\n result = {}\n hparams_content = {\n \"exp/session_1\": {\n metadata.SESSION_START_INFO_TAG: self._serialized_plugin_data(\n DATA_TYPE_SESSION_START_INFO, self.session_1_start_info_\n ),\n },\n \"exp/session_2\": {\n metadata.SESSION_START_INFO_TAG: self._serialized_plugin_data(\n DATA_TYPE_SESSION_START_INFO, self.session_2_start_info_\n ),\n },\n \"exp/session_3\": {\n metadata.SESSION_START_INFO_TAG: self._serialized_plugin_data(\n DATA_TYPE_SESSION_START_INFO, self.session_3_start_info_\n ),\n },\n }\n scalars_content = {\n \"exp/session_1\": {\"loss\": b\"\", \"accuracy\": b\"\"},\n \"exp/session_1/eval\": {\"loss\": b\"\",},\n \"exp/session_1/train\": {\"loss\": b\"\",},\n \"exp/session_2\": {\"loss\": b\"\", \"accuracy\": b\"\",},\n \"exp/session_2/eval\": {\"loss\": b\"\",},\n \"exp/session_2/train\": {\"loss\": b\"\",},\n \"exp/session_3\": {\"loss\": b\"\", \"accuracy\": b\"\",},\n \"exp/session_3/eval\": {\"loss\": b\"\",},\n \"exp/session_3xyz/\": {\"loss2\": b\"\",},\n }\n for (run, tag_to_content) in hparams_content.items():\n result.setdefault(run, {})\n for (tag, content) in tag_to_content.items():\n m = summary_pb2.SummaryMetadata()\n m.data_class = summary_pb2.DATA_CLASS_TENSOR\n m.plugin_data.plugin_name = metadata.PLUGIN_NAME\n m.plugin_data.content = content\n result[run][tag] = m\n for (run, tag_to_content) in scalars_content.items():\n result.setdefault(run, {})\n for (tag, content) in tag_to_content.items():\n m = summary_pb2.SummaryMetadata()\n m.data_class = summary_pb2.DATA_CLASS_SCALAR\n m.plugin_data.plugin_name = scalars_metadata.PLUGIN_NAME\n m.plugin_data.content = content\n result[run][tag] = m\n return result\n\n def _mock_plugin_run_to_tag_to_content(self, plugin_name):\n result = {}\n for (\n run,\n tag_to_metadata,\n ) in self._mock_multiplexer.AllSummaryMetadata().items():\n for (tag, metadata) in tag_to_metadata.items():\n if metadata.plugin_data.plugin_name != plugin_name:\n continue\n result.setdefault(run, {})\n result[run][tag] = metadata.plugin_data.content\n return result\n\n def _mock_summary_metadata(self, run, tag):\n return self._mock_multiplexer.AllSummaryMetadata()[run][tag]\n\n def test_experiment_with_experiment_tag(self):\n experiment = \"\"\"\n description: 'Test experiment'\n metric_infos: [\n { name: { tag: 'current_temp' } }\n ]\n \"\"\"\n run = \"exp\"\n tag = metadata.EXPERIMENT_TAG\n m = summary_pb2.SummaryMetadata()\n m.data_class = summary_pb2.DATA_CLASS_TENSOR\n m.plugin_data.plugin_name = metadata.PLUGIN_NAME\n m.plugin_data.content = self._serialized_plugin_data(\n DATA_TYPE_EXPERIMENT, experiment\n )\n self._mock_multiplexer.AllSummaryMetadata.side_effect = None\n self._mock_multiplexer.AllSummaryMetadata.return_value = {run: {tag: m}}\n ctxt = backend_context.Context(self._mock_tb_context)\n request_ctx = context.RequestContext()\n self.assertProtoEquals(\n experiment,\n ctxt.experiment_from_metadata(\n request_ctx, \"123\", ctxt.hparams_metadata(request_ctx, \"123\")\n ),\n )\n\n def test_experiment_without_experiment_tag(self):\n self.session_1_start_info_ = \"\"\"\n hparams: [\n {key: 'batch_size' value: {number_value: 100}},\n {key: 'lr' value: {number_value: 0.01}},\n {key: 'model_type' value: {string_value: 'CNN'}}\n ]\n \"\"\"\n self.session_2_start_info_ = \"\"\"\n hparams:[\n {key: 'batch_size' value: {number_value: 200}},\n {key: 'lr' value: {number_value: 0.02}},\n {key: 'model_type' value: {string_value: 'LATTICE'}}\n ]\n \"\"\"\n self.session_3_start_info_ = \"\"\"\n hparams:[\n {key: 'batch_size' value: {number_value: 300}},\n {key: 'lr' value: {number_value: 0.05}},\n {key: 'model_type' value: {string_value: 'CNN'}}\n ]\n \"\"\"\n expected_exp = \"\"\"\n hparam_infos: {\n name: 'batch_size'\n type: DATA_TYPE_FLOAT64\n },\n hparam_infos: {\n name: 'lr'\n type: DATA_TYPE_FLOAT64\n },\n hparam_infos: {\n name: 'model_type'\n type: DATA_TYPE_STRING\n domain_discrete: {\n values: [{string_value: 'CNN'},\n {string_value: 'LATTICE'}]\n }\n }\n metric_infos: {\n name: {group: '', tag: 'accuracy'}\n }\n metric_infos: {\n name: {group: '', tag: 'loss'}\n }\n metric_infos: {\n name: {group: 'eval', tag: 'loss'}\n }\n metric_infos: {\n name: {group: 'train', tag: 'loss'}\n }\n \"\"\"\n ctxt = backend_context.Context(self._mock_tb_context)\n request_ctx = context.RequestContext()\n actual_exp = ctxt.experiment_from_metadata(\n request_ctx, \"123\", ctxt.hparams_metadata(request_ctx, \"123\")\n )\n _canonicalize_experiment(actual_exp)\n self.assertProtoEquals(expected_exp, actual_exp)\n\n def test_experiment_without_experiment_tag_different_hparam_types(self):\n self.session_1_start_info_ = \"\"\"\n hparams:[\n {key: 'batch_size' value: {number_value: 100}},\n {key: 'lr' value: {string_value: '0.01'}}\n ]\n \"\"\"\n self.session_2_start_info_ = \"\"\"\n hparams:[\n {key: 'lr' value: {number_value: 0.02}},\n {key: 'model_type' value: {string_value: 'LATTICE'}}\n ]\n \"\"\"\n self.session_3_start_info_ = \"\"\"\n hparams:[\n {key: 'batch_size' value: {bool_value: true}},\n {key: 'model_type' value: {string_value: 'CNN'}}\n ]\n \"\"\"\n expected_exp = \"\"\"\n hparam_infos: {\n name: 'batch_size'\n type: DATA_TYPE_STRING\n domain_discrete: {\n values: [{string_value: '100.0'},\n {string_value: 'true'}]\n }\n }\n hparam_infos: {\n name: 'lr'\n type: DATA_TYPE_STRING\n domain_discrete: {\n values: [{string_value: '0.01'},\n {string_value: '0.02'}]\n }\n }\n hparam_infos: {\n name: 'model_type'\n type: DATA_TYPE_STRING\n domain_discrete: {\n values: [{string_value: 'CNN'},\n {string_value: 'LATTICE'}]\n }\n }\n metric_infos: {\n name: {group: '', tag: 'accuracy'}\n }\n metric_infos: {\n name: {group: '', tag: 'loss'}\n }\n metric_infos: {\n name: {group: 'eval', tag: 'loss'}\n }\n metric_infos: {\n name: {group: 'train', tag: 'loss'}\n }\n \"\"\"\n ctxt = backend_context.Context(self._mock_tb_context)\n request_ctx = context.RequestContext()\n actual_exp = ctxt.experiment_from_metadata(\n request_ctx, \"123\", ctxt.hparams_metadata(request_ctx, \"123\")\n )\n _canonicalize_experiment(actual_exp)\n self.assertProtoEquals(expected_exp, actual_exp)\n\n def test_experiment_without_experiment_tag_many_distinct_values(self):\n self.session_1_start_info_ = \"\"\"\n hparams:[\n {key: 'batch_size' value: {number_value: 100}},\n {key: 'lr' value: {string_value: '0.01'}}\n ]\n \"\"\"\n self.session_2_start_info_ = \"\"\"\n hparams:[\n {key: 'lr' value: {number_value: 0.02}},\n {key: 'model_type' value: {string_value: 'CNN'}}\n ]\n \"\"\"\n self.session_3_start_info_ = \"\"\"\n hparams:[\n {key: 'batch_size' value: {bool_value: true}},\n {key: 'model_type' value: {string_value: 'CNN'}}\n ]\n \"\"\"\n expected_exp = \"\"\"\n hparam_infos: {\n name: 'batch_size'\n type: DATA_TYPE_STRING\n }\n hparam_infos: {\n name: 'lr'\n type: DATA_TYPE_STRING\n }\n hparam_infos: {\n name: 'model_type'\n type: DATA_TYPE_STRING\n domain_discrete: {\n values: [{string_value: 'CNN'}]\n }\n }\n metric_infos: {\n name: {group: '', tag: 'accuracy'}\n }\n metric_infos: {\n name: {group: '', tag: 'loss'}\n }\n metric_infos: {\n name: {group: 'eval', tag: 'loss'}\n }\n metric_infos: {\n name: {group: 'train', tag: 'loss'}\n }\n \"\"\"\n ctxt = backend_context.Context(\n self._mock_tb_context, max_domain_discrete_len=1\n )\n request_ctx = context.RequestContext()\n actual_exp = ctxt.experiment_from_metadata(\n request_ctx, \"123\", ctxt.hparams_metadata(request_ctx, \"123\"),\n )\n _canonicalize_experiment(actual_exp)\n self.assertProtoEquals(expected_exp, actual_exp)\n\n def _serialized_plugin_data(self, data_oneof_field, text_protobuffer):\n oneof_type_dict = {\n DATA_TYPE_EXPERIMENT: api_pb2.Experiment,\n DATA_TYPE_SESSION_START_INFO: plugin_data_pb2.SessionStartInfo,\n DATA_TYPE_SESSION_END_INFO: plugin_data_pb2.SessionEndInfo,\n }\n protobuffer = text_format.Merge(\n text_protobuffer, oneof_type_dict[data_oneof_field]()\n )\n plugin_data = plugin_data_pb2.HParamsPluginData()\n getattr(plugin_data, data_oneof_field).CopyFrom(protobuffer)\n return metadata.create_summary_metadata(plugin_data).plugin_data.content\n\n\ndef _canonicalize_experiment(exp):\n \"\"\"Sorts the repeated fields of an Experiment message.\"\"\"\n exp.hparam_infos.sort(key=operator.attrgetter(\"name\"))\n exp.metric_infos.sort(key=operator.attrgetter(\"name.group\", \"name.tag\"))\n for hparam_info in exp.hparam_infos:\n if hparam_info.HasField(\"domain_discrete\"):\n hparam_info.domain_discrete.values.sort(\n key=operator.attrgetter(\"string_value\")\n )\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n" ]
[ [ "tensorflow.test.main" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
wqqpp007/geoist
[ "116b674eae3da4ee706902ce7f5feae1f61f43a5" ]
[ "geoist/cattools/MapTools.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n\nfrom mpl_toolkits.basemap import Basemap\nimport matplotlib.pyplot as plt\nimport matplotlib.cm as cm\nimport numpy as np\n\n#-----------------------------------------------------------------------------------------\n\nclass GeoMap:\n '''\n INFO:\n\n Map boundary edges order:\n [LeftLowerLon,LeftLowerLat,UpperRightLon,UpperRightLat]\n\n Background type:\n 'none'\n 'etopo'\n 'esri' --> background source\n\n Background sources available for 'esri':\n ESRI_Imagery_World_2D (MapServer)\n ESRI_StreetMap_World_2D (MapServer)\n I3_Imagery_Prime_World (GlobeServer)\n NASA_CloudCover_World (GlobeServer)\n NatGeo_World_Map (MapServer)\n NGS_Topo_US_2D (MapServer)\n Ocean_Basemap (MapServer)\n USA_Topo_Maps (MapServer)\n World_Imagery (MapServer)\n World_Physical_Map (MapServer)\n World_Shaded_Relief (MapServer)\n World_Street_Map (MapServer)\n World_Terrain_Base (MapServer)\n World_Topo_Map (MapServer)\n '''\n\n #---------------------------------------------------------------------------------------\n\n def __init__(self, Cfg=[]):\n\n # Defaults (example setting)\n if not Cfg:\n self._cfg = {'Bounds': [7., 36., 19., 48.],\n 'FigSize': [6., 6.],\n 'Background': ['esri','World_Terrain_Base',1500],\n 'Grid': [5., 5.]}\n else:\n self._cfg = Cfg\n\n self._zo = 1\n\n #---------------------------------------------------------------------------------------\n\n def BasePlot(self):\n\n plt.figure(figsize = (self._cfg['FigSize'][0],\n self._cfg['FigSize'][1]))\n\n # Basemap\n self._map = Basemap(self._cfg['Bounds'][0],\n self._cfg['Bounds'][1],\n self._cfg['Bounds'][2],\n self._cfg['Bounds'][3],\n resolution = 'l',\n projection = 'tmerc',\n epsg = 3857)\n\n # Background land\n if self._cfg['Background'][0] == 'color':\n self._map.drawlsmask(land_color = self._cfg['Background'][1],\n ocean_color = self._cfg['Background'][2],\n grid = 1.25,\n lakes = True)\n\n if self._cfg['Background'][0] == 'etopo':\n self._map.etopo(zorder = self._zo)\n\n if self._cfg['Background'][0] == 'esri':\n self._map.arcgisimage(service = self._cfg['Background'][1],\n xpixels = self._cfg['Background'][2],\n dpi = 300,\n zorder = self._zo)\n\n if self._cfg['Background'][0] == 'relief':\n self._map.shadedrelief()\n\n #---------------------------------------------------------------------------------------\n\n def DrawGrid(self):\n\n # Parallels and meridians\n parallels = np.arange(-90, 90, self._cfg['Grid'][1])\n meridians = np.arange(0, 360., self._cfg['Grid'][0])\n\n self._zo += 1\n self._map.drawparallels(parallels, labels = [1,0,0,0],\n fontsize = 14, weight = 'normal',\n linewidth = 0.5,\n zorder = self._zo)\n self._zo += 1\n self._map.drawmeridians(meridians, labels = [0,0,0,1],\n fontsize = 14, weight = 'normal',\n linewidth = 0.5,\n zorder = self._zo)\n\n #---------------------------------------------------------------------------------------\n\n def DrawBounds(self):\n\n # Boundaries and lines\n self._zo += 1\n self._map.drawcoastlines(linewidth = 0.8,\n zorder = self._zo)\n self._zo += 1\n self._map.drawstates(linewidth = 0.8,\n zorder = self._zo)\n self._zo += 1\n self._map.drawcountries(linewidth = 0.8,\n zorder = self._zo)\n self._zo += 1\n self._map.drawrivers(linewidth = 0.1,\n color = 'b',\n zorder = self._zo)\n \"\"\"\n self._zo += 1\n self._map.drawmapboundary(linewidth = 2,\n color = 'k',\n zorder = self._zo)\n \"\"\"\n\n #---------------------------------------------------------------------------------------\n\n def Title(self, string, Set=['bold','k',18]):\n\n plt.title(string, weight = Set[0],\n color = Set[1],\n fontsize = Set[2])\n\n #---------------------------------------------------------------------------------------\n\n def PointPlot(self, Lon, Lat, Label=[], Set=['o','y',5,1]):\n\n x, y = self._map(Lon, Lat)\n\n self._zo += 1\n self._map.plot(x, y, Set[0],\n color = Set[1],\n markersize = Set[2],\n markeredgewidth = Set[3],\n label = Label,\n zorder = self._zo)\n\n #---------------------------------------------------------------------------------------\n\n def LabelPlot(self, Lon, Lat, Label, Set=['normal','k',14]):\n\n x, y = self._map(Lon, Lat)\n\n # If only one label provided, convert to list\n if isinstance(Label, str):\n x = [x]\n y = [y]\n Label = [Label]\n\n self._zo += 1\n for i, string in enumerate(Label):\n plt.text(x[i], y[i], string, weight = Set[0],\n color = Set[1],\n fontsize = Set[2],\n zorder = self._zo)\n\n #---------------------------------------------------------------------------------------\n\n def AreaPlot(self, Lon, Lat, Set=['y',1,'k',1]):\n\n x, y = self._map(Lon, Lat)\n\n if Set[0]:\n self._zo += 1\n plt.fill(x, y, color = Set[0],\n alpha = Set[1],\n zorder = self._zo)\n if Set[2]:\n self._zo += 1\n plt.plot(x, y, Set[2],\n linewidth = Set[3],\n zorder = self._zo)\n\n #---------------------------------------------------------------------------------------\n\n def MeshPlot(self, Lon, Lat, Elev, Cmap=[], Clim=[], Mesh=True):\n\n from matplotlib.colors import BoundaryNorm\n from matplotlib.ticker import MaxNLocator\n\n x, y = self._map(Lon, Lat)\n z = Elev\n\n if not Cmap:\n Cmap = cm.jet\n # cmap.set_under('w', alpha=0.)\n\n if not Clim:\n Clim = [z.min(), z.max()]\n\n levels = MaxNLocator(nbins=16).tick_values(Clim[0], Clim[1])\n norm = BoundaryNorm(levels, ncolors = Cmap.N, clip=True)\n\n if not Mesh:\n self._zo += 1\n h = plt.scatter(x, y, c = z,\n s = 20,\n marker = 's',\n cmap = Cmap,\n vmin = Clim[0],\n vmax = Clim[1],\n lw = 0,\n alpha = 1.,\n zorder = self._zo)\n\n else:\n self._zo += 1\n z = z[:-1, :-1]\n h = plt.pcolormesh(x, y, z, cmap = Cmap,\n norm = norm,\n vmin = Clim[0],\n vmax = Clim[1],\n lw = 0,\n alpha = 1.,\n zorder = self._zo)\n\n clb = plt.gcf().colorbar(h, orientation = 'vertical')\n clb.outline.set_linewidth(1)\n clb.ax.tick_params(labelsize=14)\n clb.set_label('Spectral Acceleration ($g$)', size=12)\n\n #---------------------------------------------------------------------------------------\n\n def ShapeFile(self, ShpFile, Name, Color='k'):\n\n # NOTE: this doesn't always work with polygons,\n # better to use the function in crd_tool\n\n self._zo += 1\n self._map.readshapefile(ShpFile,\n Name,\n linewidth = 1.5,\n drawbounds = True,\n color = Color,\n zorder = self._zo)\n\n #---------------------------------------------------------------------------------------\n\n def Legend(self, Location=[]):\n\n self._zo += 1\n if Location:\n l = plt.legend(loc = Location, numpoints = 1)\n else:\n # Default outside\n l = plt.legend(bbox_to_anchor = (1.05, 1), \n loc = 2, borderaxespad = 0.,\n numpoints = 1)\n l.set_zorder(self._zo)\n\n #---------------------------------------------------------------------------------------\n\n def Show(self):\n \n plt.show(block = False)\n\n #---------------------------------------------------------------------------------------\n\n def Close(self):\n\n plt.close('all')\n\n #---------------------------------------------------------------------------------------\n\n def SaveFig(self, OutFile, Dpi=150):\n\n plt.savefig(OutFile, bbox_inches = 'tight', dpi = Dpi)\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.colors.BoundaryNorm", "matplotlib.pyplot.title", "matplotlib.pyplot.scatter", "numpy.arange", "matplotlib.pyplot.savefig", "matplotlib.pyplot.gcf", "matplotlib.pyplot.plot", "matplotlib.ticker.MaxNLocator", "matplotlib.pyplot.close", "matplotlib.pyplot.fill", "matplotlib.pyplot.pcolormesh", "matplotlib.pyplot.text", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cschlick/espaloma
[ "cae5664446d0c89025de5eb827f507d8af64e2d4", "cae5664446d0c89025de5eb827f507d8af64e2d4" ]
[ "espaloma/nn/readout/node_typing.py", "espaloma/mm/tests/test_openmm_consistency.py" ]
[ "# =============================================================================\n# IMPORTS\n# =============================================================================\nimport torch\n\nfrom espaloma.nn.readout.base_readout import BaseReadout\n\n\n# =============================================================================\n# MODULE CLASSES\n# =============================================================================\nclass NodeTyping(BaseReadout):\n \"\"\"Simple typing on homograph.\"\"\"\n\n def __init__(self, in_features, n_classes=100):\n super(NodeTyping, self).__init__()\n self.c = torch.nn.Linear(in_features, n_classes)\n\n def forward(self, g):\n g.apply_nodes(\n ntype=\"n1\",\n func=lambda node: {\"nn_typing\": self.c(node.data[\"h\"])},\n )\n return g\n", "import numpy as np\nimport numpy.testing as npt\nimport pytest\nimport torch\nfrom simtk import openmm\nfrom simtk import openmm as mm\nfrom simtk import unit\n\nfrom espaloma.utils.geometry import _sample_four_particle_torsion_scan\n\nomm_angle_unit = unit.radian\nomm_energy_unit = unit.kilojoule_per_mole\n\nfrom simtk.openmm import app\n\nimport espaloma as esp\n\ndecimal_threshold = 2\n\n\ndef _create_torsion_sim(\n periodicity: int = 2, phase=0 * omm_angle_unit, k=10.0 * omm_energy_unit\n) -> app.Simulation:\n \"\"\"Create a 4-particle OpenMM Simulation containing only a PeriodicTorsionForce\"\"\"\n system = mm.System()\n\n # add 4 particles of unit mass\n for _ in range(4):\n system.addParticle(1)\n\n # add torsion force to system\n force = mm.PeriodicTorsionForce()\n force.addTorsion(0, 1, 2, 3, periodicity, phase, k)\n system.addForce(force)\n\n # create openmm Simulation, which requires a Topology and Integrator\n topology = app.Topology()\n chain = topology.addChain()\n residue = topology.addResidue(\"torsion\", chain)\n for name in [\"a\", \"b\", \"c\", \"d\"]:\n topology.addAtom(name, \"C\", residue)\n integrator = mm.VerletIntegrator(1.0)\n sim = app.Simulation(topology, system, integrator)\n\n return sim\n\n\n# TODO: mark this properly: want to test periodicities 1..6, +ve, -ve k\n# @pytest.mark.parametrize(periodicity=[1,2,3,4,5,6], k=[-10 * omm_energy_unit, +10 * omm_energy_unit])\ndef test_periodic_torsion(\n periodicity=4, k=10 * omm_energy_unit, n_samples=100\n):\n \"\"\"Using simulated torsion scan, test if espaloma torsion energies and\n OpenMM torsion energies agree.\n\n \"\"\"\n phase = 0 * omm_angle_unit # all zero phases\n\n # create torsion simulation\n sim = _create_torsion_sim(periodicity=periodicity, phase=phase, k=k)\n\n # grab snapshots from torsion scan\n xyz_np = _sample_four_particle_torsion_scan(n_samples)\n\n # compute energies using OpenMM\n openmm_energies = np.zeros(n_samples)\n for i, pos in enumerate(xyz_np):\n sim.context.setPositions(pos)\n openmm_energies[i] = (\n sim.context.getState(getEnergy=True).getPotentialEnergy()\n / omm_energy_unit\n )\n\n # compute energies using espaloma\n xyz = torch.tensor(xyz_np)\n x0, x1, x2, x3 = xyz[:, 0, :], xyz[:, 1, :], xyz[:, 2, :], xyz[:, 3, :]\n theta = esp.mm.geometry.dihedral(x0, x1, x2, x3).reshape((n_samples, 1))\n ks = torch.zeros(n_samples, 6)\n ks[:, periodicity - 1] = k.value_in_unit(esp.units.ENERGY_UNIT)\n\n espaloma_energies = (\n esp.mm.functional.periodic(theta, ks).numpy().flatten()\n * esp.units.ENERGY_UNIT\n )\n espaloma_energies_in_omm_units = espaloma_energies.value_in_unit(\n omm_energy_unit\n )\n\n np.testing.assert_almost_equal(\n actual=espaloma_energies_in_omm_units,\n desired=openmm_energies,\n decimal=decimal_threshold,\n )\n\n\n# TODO: parameterize on the individual energy terms also\[email protected](\n \"g\",\n esp.data.esol(first=10),\n)\ndef test_energy_angle_and_bond(g):\n # make simulation\n from espaloma.data.md import MoleculeVacuumSimulation\n\n # get simulation\n esp_simulation = MoleculeVacuumSimulation(\n n_samples=1,\n n_steps_per_sample=1000,\n forcefield=\"gaff-1.81\",\n charge_method=\"gasteiger\",\n )\n\n simulation = esp_simulation.simulation_from_graph(g)\n system = simulation.system\n esp_simulation.run(g, in_place=True)\n\n # if MD blows up, forget about it\n if g.nodes[\"n1\"].data[\"xyz\"].abs().max() > 100:\n return True\n\n forces = list(system.getForces())\n\n energies = {}\n\n for idx, force in enumerate(forces):\n force.setForceGroup(idx)\n\n name = force.__class__.__name__\n\n if \"Nonbonded\" in name:\n force.setNonbondedMethod(openmm.NonbondedForce.NoCutoff)\n\n # epsilons = {}\n # sigmas = {}\n\n # for _idx in range(force.getNumParticles()):\n # q, sigma, epsilon = force.getParticleParameters(_idx)\n\n # # record parameters\n # epsilons[_idx] = epsilon\n # sigmas[_idx] = sigma\n\n # force.setParticleParameters(_idx, 0., sigma, epsilon)\n\n # def sigma_combining_rule(sig1, sig2):\n # return (sig1 + sig2) / 2\n\n # def eps_combining_rule(eps1, eps2):\n # return np.sqrt(np.abs(eps1 * eps2))\n\n # for _idx in range(force.getNumExceptions()):\n # idx0, idx1, q, sigma, epsilon = force.getExceptionParameters(\n # _idx)\n # force.setExceptionParameters(\n # _idx,\n # idx0,\n # idx1,\n # 0.0,\n # sigma_combining_rule(sigmas[idx0], sigmas[idx1]),\n # eps_combining_rule(epsilons[idx0], epsilons[idx1])\n # )\n\n # force.updateParametersInContext(_simulation.context)\n\n # create new simulation\n _simulation = openmm.app.Simulation(\n simulation.topology,\n system,\n openmm.VerletIntegrator(0.0),\n )\n\n _simulation.context.setPositions(\n g.nodes[\"n1\"].data[\"xyz\"][:, 0, :].detach().numpy() * unit.bohr\n )\n\n for idx, force in enumerate(forces):\n name = force.__class__.__name__\n\n state = _simulation.context.getState(\n getEnergy=True,\n getParameters=True,\n groups=2 ** idx,\n )\n\n energy = state.getPotentialEnergy().value_in_unit(\n esp.units.ENERGY_UNIT\n )\n\n energies[name] = energy\n\n # parametrize\n ff = esp.graphs.legacy_force_field.LegacyForceField(\"gaff-1.81\")\n g = ff.parametrize(g)\n\n # n2 : bond, n3: angle, n1: nonbonded?\n # n1 : sigma (k), epsilon (eq), and charge (not included yet)\n for term in [\"n2\", \"n3\"]:\n g.nodes[term].data[\"k\"] = g.nodes[term].data[\"k_ref\"]\n g.nodes[term].data[\"eq\"] = g.nodes[term].data[\"eq_ref\"]\n\n \"\"\"\n for term in [\"n1\"]:\n g.nodes[term].data[\"sigma\"] = g.nodes[term].data[\"sigma_ref\"]\n g.nodes[term].data[\"epsilon\"] = g.nodes[term].data[\"epsilon_ref\"]\n # g.nodes[term].data['q'] = g.nodes[term].data['q_ref']\n \"\"\"\n\n for term in [\"n4\"]:\n g.nodes[term].data[\"phases\"] = g.nodes[term].data[\"phases_ref\"]\n g.nodes[term].data[\"periodicity\"] = g.nodes[term].data[\n \"periodicity_ref\"\n ]\n g.nodes[term].data[\"k\"] = g.nodes[term].data[\"k_ref\"]\n\n # for each atom, store n_snapshots x 3\n # g.nodes[\"n1\"].data[\"xyz\"] = torch.tensor(\n # simulation.context.getState(getPositions=True)\n # .getPositions(asNumpy=True)\n # .value_in_unit(esp.units.DISTANCE_UNIT),\n # dtype=torch.float32,\n # )[None, :, :].permute(1, 0, 2)\n\n # print(g.nodes['n2'].data)\n esp.mm.geometry.geometry_in_graph(g.heterograph)\n esp.mm.energy.energy_in_graph(g.heterograph, terms=[\"n2\", \"n3\", \"n4\"])\n # writes into nodes\n # .data['u_nonbonded'], .data['u_onefour'], .data['u2'], .data['u3'],\n\n # TODO: consider more carefully how many decimals of precision are needed\n n_decimals = 3\n\n # test bonds\n npt.assert_almost_equal(\n g.nodes[\"g\"].data[\"u_n2\"].detach().numpy(),\n energies[\"HarmonicBondForce\"],\n decimal=n_decimals,\n )\n\n # test angles\n npt.assert_almost_equal(\n g.nodes[\"g\"].data[\"u_n3\"].detach().numpy(),\n energies[\"HarmonicAngleForce\"],\n decimal=n_decimals,\n )\n\n # propers = g.nodes[\"g\"].data[\"u_n4\"].detach().numpy()\n # impropers = g.nodes[\"g\"].data[\"u_n4_improper\"].detach().numpy()\n # all_torsions = propers + impropers\n # npt.assert_almost_equal(\n # all_torsions,\n # energies[\"PeriodicTorsionForce\"],\n # decimal=n_decimals,\n # )\n\n # print(all_torsions)\n # print(energies[\"PeriodicTorsionForce\"])\n\n # TODO:\n # This is not working now, matching OpenMM nonbonded.\n # test nonbonded\n # TODO: must set all charges to zero in _simulation for this to pass currently, since g doesn't have any charges\n # npt.assert_almost_equal(\n # g.nodes['g'].data['u_nonbonded'].numpy()\\\n # + g.nodes['g'].data['u_onefour'].numpy(),\n # energies['NonbondedForce'],\n # decimal=3,\n # )\n" ]
[ [ "torch.nn.Linear" ], [ "numpy.testing.assert_almost_equal", "torch.zeros", "numpy.zeros", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
KeAWang/emmental
[ "dae9f9fbba944f7c8404ab85aa9296545db1b82b" ]
[ "src/emmental/utils/seed.py" ]
[ "# Copyright (c) 2021 Sen Wu. All Rights Reserved.\n\n\n\"\"\"Helper function to set random seed for reproducibility of models.\"\"\"\n\nimport logging\nimport random\nfrom typing import Optional\n\nimport numpy as np\nimport torch\n\nlogger = logging.getLogger(__name__)\n\n\ndef set_random_seed(seed: Optional[int] = None) -> None:\n \"\"\"Set random seed for random, numpy, and pytorch.\n\n Args:\n seed: The random seed, defaults to `None` which select it randomly.\n \"\"\"\n max_value = np.iinfo(np.uint32).max\n min_value = np.iinfo(np.uint32).min\n\n try:\n seed = int(seed)\n logger.info(f\"Set random seed to {seed}.\")\n except (TypeError, ValueError):\n seed = random.randint(min_value, max_value)\n logger.info(f\"No random seed specified, randomly set random seed to {seed}.\")\n\n if not (min_value <= seed <= max_value):\n new_seed = random.randint(min_value, max_value)\n logger.info(\n f\"Random seed {seed} is not valid, randomly set random seed to {new_seed}.\"\n )\n seed = new_seed\n\n # Set random seed for random\n random.seed(seed)\n # Set random seed for all numpy operations\n np.random.seed(seed=seed)\n # Set random seed for PyTorch\n torch.manual_seed(seed)\n" ]
[ [ "torch.manual_seed", "numpy.iinfo", "numpy.random.seed" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MyBourse/pandas-ta
[ "98478f8bf049a4c8748d6f3c795f4f335ced05ca" ]
[ "pandas_ta/overlap/hilo.py" ]
[ "# -*- coding: utf-8 -*-\nfrom numpy import NaN as npNaN\nfrom pandas import DataFrame, Series\n# from pandas_ta.overlap.ma import ma\nfrom .ma import ma\nfrom pandas_ta.utils import get_offset, verify_series\n\n\ndef hilo(high, low, close, high_length=None, low_length=None, mamode=None, offset=None, **kwargs):\n \"\"\"Indicator: Gann HiLo (HiLo)\"\"\"\n # Validate Arguments\n high = verify_series(high)\n low = verify_series(low)\n close = verify_series(close)\n high_length = int(high_length) if high_length and high_length > 0 else 13\n low_length = int(low_length) if low_length and low_length > 0 else 21\n mamode = mamode.lower() if isinstance(mamode, str) else \"sma\"\n offset = get_offset(offset)\n\n # Calculate Result\n m = close.size\n hilo = Series(npNaN, index=close.index)\n long = Series(npNaN, index=close.index)\n short = Series(npNaN, index=close.index)\n\n high_ma = ma(mamode, high, length=high_length)\n low_ma = ma(mamode, low, length=low_length)\n\n for i in range(1, m):\n if close.iloc[i] > high_ma.iloc[i - 1]:\n hilo.iloc[i] = long.iloc[i] = low_ma.iloc[i]\n elif close.iloc[i] < low_ma.iloc[i - 1]:\n hilo.iloc[i] = short.iloc[i] = high_ma.iloc[i]\n else:\n hilo.iloc[i] = hilo.iloc[i - 1]\n long.iloc[i] = short.iloc[i] = hilo.iloc[i - 1]\n\n # Offset\n if offset != 0:\n hilo = hilo.shift(offset)\n long = long.shift(offset)\n short = short.shift(offset)\n\n # Handle fills\n if \"fillna\" in kwargs:\n hilo.fillna(kwargs[\"fillna\"], inplace=True)\n long.fillna(kwargs[\"fillna\"], inplace=True)\n short.fillna(kwargs[\"fillna\"], inplace=True)\n if \"fill_method\" in kwargs:\n hilo.fillna(method=kwargs[\"fill_method\"], inplace=True)\n long.fillna(method=kwargs[\"fill_method\"], inplace=True)\n short.fillna(method=kwargs[\"fill_method\"], inplace=True)\n\n # Name & Category\n _props = f\"_{high_length}_{low_length}\"\n data = {f\"HILO{_props}\": hilo, f\"HILOl{_props}\": long, f\"HILOs{_props}\": short}\n df = DataFrame(data, index=close.index)\n\n df.name = f\"HILO{_props}\"\n df.category = \"overlap\"\n\n return df\n\n\nhilo.__doc__ = \\\n\"\"\"Gann HiLo Activator(HiLo)\n\nThe Gann High Low Activator Indicator was created by Robert Krausz in a 1998\nissue of Stocks & Commodities Magazine. It is a moving average based trend\nindicator consisting of two different simple moving averages.\n\nThe indicator tracks both curves (of the highs and the lows). The close of the\nbar defines which of the two gets plotted.\n\nIncreasing high_length and decreasing low_length better for short trades,\nvice versa for long positions.\n\nSources:\n https://www.sierrachart.com/index.php?page=doc/StudiesReference.php&ID=447&Name=Gann_HiLo_Activator\n https://www.tradingtechnologies.com/help/x-study/technical-indicator-definitions/simple-moving-average-sma/\n https://www.tradingview.com/script/XNQSLIYb-Gann-High-Low/\n\nCalculation:\n Default Inputs:\n high_length=13, low_length=21, mamode=\"sma\"\n EMA = Exponential Moving Average\n HMA = Hull Moving Average\n SMA = Simple Moving Average # Default\n\n if \"ema\":\n high_ma = EMA(high, high_length)\n low_ma = EMA(low, low_length)\n elif \"hma\":\n high_ma = HMA(high, high_length)\n low_ma = HMA(low, low_length)\n else: # \"sma\"\n high_ma = SMA(high, high_length)\n low_ma = SMA(low, low_length)\n\n # Similar to Supertrend MA selection\n hilo = Series(npNaN, index=close.index)\n for i in range(1, m):\n if close.iloc[i] > high_ma.iloc[i - 1]:\n hilo.iloc[i] = low_ma.iloc[i]\n elif close.iloc[i] < low_ma.iloc[i - 1]:\n hilo.iloc[i] = high_ma.iloc[i]\n else:\n hilo.iloc[i] = hilo.iloc[i - 1]\n\nArgs:\n high (pd.Series): Series of 'high's\n low (pd.Series): Series of 'low's\n close (pd.Series): Series of 'close's\n high_length (int): It's period. Default: 13\n low_length (int): It's period. Default: 21\n mamode (str): Options: 'sma' or 'ema'. Default: 'sma'\n offset (int): How many periods to offset the result. Default: 0\n\nKwargs:\n adjust (bool): Default: True\n presma (bool, optional): If True, uses SMA for initial value.\n fillna (value, optional): pd.DataFrame.fillna(value)\n fill_method (value, optional): Type of fill method\n\nReturns:\n pd.DataFrame: HILO (line), HILOl (long), HILOs (short) columns.\n\"\"\"\n" ]
[ [ "pandas.Series", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
BlueOwlDev/dask
[ "a1187b13321d69565b9c21359d739c239bd04c65" ]
[ "dask/array/wrap.py" ]
[ "from functools import partial\nfrom itertools import product\n\nimport numpy as np\n\nfrom tlz import curry\n\nfrom ..base import tokenize\nfrom ..utils import funcname\nfrom .blockwise import BlockwiseCreateArray\nfrom .core import Array, normalize_chunks\nfrom .utils import (\n meta_from_array,\n empty_like_safe,\n full_like_safe,\n ones_like_safe,\n zeros_like_safe,\n)\n\n\ndef _parse_wrap_args(func, args, kwargs, shape):\n if isinstance(shape, np.ndarray):\n shape = shape.tolist()\n\n if not isinstance(shape, (tuple, list)):\n shape = (shape,)\n\n name = kwargs.pop(\"name\", None)\n chunks = kwargs.pop(\"chunks\", \"auto\")\n\n dtype = kwargs.pop(\"dtype\", None)\n if dtype is None:\n dtype = func(shape, *args, **kwargs).dtype\n dtype = np.dtype(dtype)\n\n chunks = normalize_chunks(chunks, shape, dtype=dtype)\n\n name = name or funcname(func) + \"-\" + tokenize(\n func, shape, chunks, dtype, args, kwargs\n )\n\n return {\n \"shape\": shape,\n \"dtype\": dtype,\n \"kwargs\": kwargs,\n \"chunks\": chunks,\n \"name\": name,\n }\n\n\ndef wrap_func_shape_as_first_arg(func, *args, **kwargs):\n \"\"\"\n Transform np creation function into blocked version\n \"\"\"\n if \"shape\" not in kwargs:\n shape, args = args[0], args[1:]\n else:\n shape = kwargs.pop(\"shape\")\n\n if isinstance(shape, Array):\n raise TypeError(\n \"Dask array input not supported. \"\n \"Please use tuple, list, or a 1D numpy array instead.\"\n )\n\n parsed = _parse_wrap_args(func, args, kwargs, shape)\n shape = parsed[\"shape\"]\n dtype = parsed[\"dtype\"]\n chunks = parsed[\"chunks\"]\n name = parsed[\"name\"]\n kwargs = parsed[\"kwargs\"]\n func = partial(func, dtype=dtype, **kwargs)\n\n graph = BlockwiseCreateArray(\n name,\n func,\n shape,\n chunks,\n )\n return Array(graph, name, chunks, dtype=dtype, meta=kwargs.get(\"meta\", None))\n\n\ndef wrap_func_like(func, *args, **kwargs):\n \"\"\"\n Transform np creation function into blocked version\n \"\"\"\n x = args[0]\n meta = meta_from_array(x)\n shape = kwargs.get(\"shape\", x.shape)\n\n parsed = _parse_wrap_args(func, args, kwargs, shape)\n shape = parsed[\"shape\"]\n dtype = parsed[\"dtype\"]\n chunks = parsed[\"chunks\"]\n name = parsed[\"name\"]\n kwargs = parsed[\"kwargs\"]\n\n keys = product([name], *[range(len(bd)) for bd in chunks])\n shapes = product(*chunks)\n shapes = list(shapes)\n kw = [kwargs for _ in shapes]\n for i, s in enumerate(list(shapes)):\n kw[i][\"shape\"] = s\n vals = ((partial(func, dtype=dtype, **k),) + args for (k, s) in zip(kw, shapes))\n\n dsk = dict(zip(keys, vals))\n\n return Array(dsk, name, chunks, meta=meta.astype(dtype))\n\n\ndef wrap_func_like_safe(func, func_like, *args, **kwargs):\n \"\"\"\n Safe implementation for wrap_func_like(), attempts to use func_like(),\n if the shape keyword argument, falls back to func().\n \"\"\"\n try:\n return func_like(*args, **kwargs)\n except TypeError:\n return func(*args, **kwargs)\n\n\n@curry\ndef wrap(wrap_func, func, **kwargs):\n func_like = kwargs.pop(\"func_like\", None)\n if func_like is None:\n f = partial(wrap_func, func, **kwargs)\n else:\n f = partial(wrap_func, func_like, **kwargs)\n template = \"\"\"\n Blocked variant of %(name)s\n\n Follows the signature of %(name)s exactly except that it also features\n optional keyword arguments ``chunks: int, tuple, or dict`` and ``name: str``.\n\n Original signature follows below.\n \"\"\"\n if func.__doc__ is not None:\n f.__doc__ = template % {\"name\": func.__name__} + func.__doc__\n f.__name__ = \"blocked_\" + func.__name__\n return f\n\n\nw = wrap(wrap_func_shape_as_first_arg)\n\n\n@curry\ndef _broadcast_trick_inner(func, shape, meta=(), *args, **kwargs):\n if shape == ():\n return np.broadcast_to(func(meta, shape=(), *args, **kwargs), shape)\n else:\n return np.broadcast_to(func(meta, shape=1, *args, **kwargs), shape)\n\n\ndef broadcast_trick(func):\n \"\"\"\n Provide a decorator to wrap common numpy function with a broadcast trick.\n\n Dask arrays are currently immutable; thus when we know an array is uniform,\n we can replace the actual data by a single value and have all elements point\n to it, thus reducing the size.\n\n >>> x = np.broadcast_to(1, (100,100,100))\n >>> x.base.nbytes\n 8\n\n Those array are not only more efficient locally, but dask serialisation is\n aware of the _real_ size of those array and thus can send them around\n efficiently and schedule accordingly.\n\n Note that those array are read-only and numpy will refuse to assign to them,\n so should be safe.\n \"\"\"\n\n inner = _broadcast_trick_inner(func)\n\n if func.__doc__ is not None:\n inner.__doc__ = func.__doc__\n inner.__name__ = func.__name__\n if inner.__name__.endswith(\"_like_safe\"):\n inner.__name__ = inner.__name__[:-10]\n return inner\n\n\nones = w(broadcast_trick(ones_like_safe), dtype=\"f8\")\nzeros = w(broadcast_trick(zeros_like_safe), dtype=\"f8\")\nempty = w(broadcast_trick(empty_like_safe), dtype=\"f8\")\n\n\nw_like = wrap(wrap_func_like_safe)\n\n\nempty_like = w_like(np.empty, func_like=np.empty_like)\n\n\n# full and full_like require special casing due to argument check on fill_value\n# Generate wrapped functions only once\n_full = w(broadcast_trick(full_like_safe))\n_full_like = w_like(np.full, func_like=np.full_like)\n\n# workaround for numpy doctest failure: https://github.com/numpy/numpy/pull/17472\n_full.__doc__ = _full.__doc__.replace(\n \"array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])\",\n \"array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1])\",\n)\n\n\ndef full(shape, fill_value, *args, **kwargs):\n # np.isscalar has somewhat strange behavior:\n # https://docs.scipy.org/doc/numpy/reference/generated/numpy.isscalar.html\n if np.ndim(fill_value) != 0:\n raise ValueError(\n f\"fill_value must be scalar. Received {type(fill_value).__name__} instead.\"\n )\n return _full(shape=shape, fill_value=fill_value, *args, **kwargs)\n\n\ndef full_like(a, fill_value, *args, **kwargs):\n if np.ndim(fill_value) != 0:\n raise ValueError(\n f\"fill_value must be scalar. Received {type(fill_value).__name__} instead.\"\n )\n return _full_like(\n a=a,\n fill_value=fill_value,\n *args,\n **kwargs,\n )\n\n\nfull.__doc__ = _full.__doc__\nfull_like.__doc__ = _full_like.__doc__\n" ]
[ [ "numpy.ndim", "numpy.dtype" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
colour-science/sample_code
[ "8bda35b674d770da5a0e6c210634a77691527fce" ]
[ "ty_lib/test_pattern_generator2.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n評価用のテストパターン作成ツール集\n\n\"\"\"\n\nimport os\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom colour.colorimetry import CMFS, ILLUMINANTS\nfrom colour.models import XYZ_to_xy, xy_to_XYZ, XYZ_to_RGB, RGB_to_XYZ\nfrom colour.models import xy_to_xyY, xyY_to_XYZ, Lab_to_XYZ\nfrom colour.models import BT709_COLOURSPACE\nfrom colour.utilities import normalise_maximum\nfrom colour import models\nfrom colour import RGB_COLOURSPACES, COLOURCHECKERS\nfrom scipy.spatial import Delaunay\nfrom scipy.ndimage.filters import convolve\nimport math\n\nimport transfer_functions as tf\n\n\nCMFS_NAME = 'CIE 1931 2 Degree Standard Observer'\nD65_WHITE = ILLUMINANTS[CMFS_NAME]['D65']\nYCBCR_CHECK_MARKER = [0, 0, 0]\n\nUNIVERSAL_COLOR_LIST = [\"#F6AA00\", \"#FFF100\", \"#03AF7A\",\n \"#005AFF\", \"#4DC4FF\", \"#804000\"]\n\n\ndef preview_image(img, order='rgb', over_disp=False):\n if order == 'rgb':\n cv2.imshow('preview', img[:, :, ::-1])\n elif order == 'bgr':\n cv2.imshow('preview', img)\n elif order == 'mono':\n cv2.imshow('preview', img)\n else:\n raise ValueError(\"order parameter is invalid\")\n\n if over_disp:\n cv2.resizeWindow('preview', )\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef equal_devision(length, div_num):\n \"\"\"\n # 概要\n length を div_num で分割する。\n 端数が出た場合は誤差拡散法を使って上手い具合に分散させる。\n \"\"\"\n base = length / div_num\n ret_array = [base for x in range(div_num)]\n\n # 誤差拡散法を使った辻褄合わせを適用\n # -------------------------------------------\n diff = 0\n for idx in range(div_num):\n diff += math.modf(ret_array[idx])[0]\n if diff >= 1.0:\n diff -= 1.0\n ret_array[idx] = int(math.floor(ret_array[idx]) + 1)\n else:\n ret_array[idx] = int(math.floor(ret_array[idx]))\n\n # 計算誤差により最終点が +1 されない場合への対処\n # -------------------------------------------\n diff = length - sum(ret_array)\n if diff != 0:\n ret_array[-1] += diff\n\n # 最終確認\n # -------------------------------------------\n if length != sum(ret_array):\n raise ValueError(\"the output of equal_division() is abnormal.\")\n\n return ret_array\n\n\ndef do_matrix(img, mtx):\n \"\"\"\n img に対して mtx を適用する。\n \"\"\"\n base_shape = img.shape\n\n r, g, b = img[..., 0], img[..., 1], img[..., 2]\n ro = r * mtx[0][0] + g * mtx[0][1] + b * mtx[0][2]\n go = r * mtx[1][0] + g * mtx[1][1] + b * mtx[1][2]\n bo = r * mtx[2][0] + g * mtx[2][1] + b * mtx[2][2]\n\n out_img = np.dstack((ro, go, bo)).reshape(base_shape)\n\n return out_img\n\n\ndef _get_cmfs_xy():\n \"\"\"\n xy色度図のプロットのための馬蹄形の外枠のxy値を求める。\n\n Returns\n -------\n array_like\n xy coordinate for chromaticity diagram\n\n \"\"\"\n # 基本パラメータ設定\n # ------------------\n cmf = CMFS.get(CMFS_NAME)\n d65_white = D65_WHITE\n\n # 馬蹄形のxy値を算出\n # --------------------------\n cmf_xy = XYZ_to_xy(cmf.values, d65_white)\n\n return cmf_xy\n\n\ndef get_primaries(name='ITU-R BT.2020'):\n \"\"\"\n prmary color の座標を求める\n\n\n Parameters\n ----------\n name : str\n a name of the color space.\n\n Returns\n -------\n array_like\n prmaries. [[rx, ry], [gx, gy], [bx, by], [rx, ry]]\n\n \"\"\"\n primaries = RGB_COLOURSPACES[name].primaries\n primaries = np.append(primaries, [primaries[0, :]], axis=0)\n\n rgb = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])\n\n return primaries, rgb\n\n\ndef xy_to_rgb(xy, name='ITU-R BT.2020', normalize='maximum', specific=None):\n \"\"\"\n xy値からRGB値を算出する。\n いい感じに正規化もしておく。\n\n Parameters\n ----------\n xy : array_like\n xy value.\n name : string\n color space name.\n normalize : string\n normalize method. You can select 'maximum', 'specific' or None.\n\n Returns\n -------\n array_like\n rgb value. the value is normalized.\n \"\"\"\n illuminant_XYZ = D65_WHITE\n illuminant_RGB = D65_WHITE\n chromatic_adaptation_transform = 'CAT02'\n large_xyz_to_rgb_matrix = get_xyz_to_rgb_matrix(name)\n if normalize == 'specific':\n xyY = xy_to_xyY(xy)\n xyY[..., 2] = specific\n large_xyz = xyY_to_XYZ(xyY)\n else:\n large_xyz = xy_to_XYZ(xy)\n\n rgb = XYZ_to_RGB(large_xyz, illuminant_XYZ, illuminant_RGB,\n large_xyz_to_rgb_matrix,\n chromatic_adaptation_transform)\n\n \"\"\"\n そのままだとビデオレベルが低かったりするので、\n 各ドット毎にRGB値を正規化&最大化する。必要であれば。\n \"\"\"\n if normalize == 'maximum':\n rgb = normalise_maximum(rgb, axis=-1)\n else:\n if(np.sum(rgb > 1.0) > 0):\n print(\"warning: over flow has occured at xy_to_rgb\")\n if(np.sum(rgb < 0.0) > 0):\n print(\"warning: under flow has occured at xy_to_rgb\")\n rgb[rgb < 0] = 0\n rgb[rgb > 1.0] = 1.0\n\n return rgb\n\n\ndef get_white_point(name):\n \"\"\"\n white point を求める。CIE1931ベース。\n \"\"\"\n if name != \"DCI-P3\":\n illuminant = RGB_COLOURSPACES[name].illuminant\n white_point = ILLUMINANTS[CMFS_NAME][illuminant]\n else:\n white_point = ILLUMINANTS[CMFS_NAME][\"D65\"]\n\n return white_point\n\n\ndef get_secondaries(name='ITU-R BT.2020'):\n \"\"\"\n secondary color の座標を求める\n\n Parameters\n ----------\n name : str\n a name of the color space.\n\n Returns\n -------\n array_like\n secondaries. the order is magenta, yellow, cyan.\n\n \"\"\"\n secondary_rgb = np.array([[1.0, 0.0, 1.0],\n [1.0, 1.0, 0.0],\n [0.0, 1.0, 1.0]])\n illuminant_XYZ = D65_WHITE\n illuminant_RGB = D65_WHITE\n chromatic_adaptation_transform = 'CAT02'\n rgb_to_xyz_matrix = get_rgb_to_xyz_matrix(name)\n large_xyz = RGB_to_XYZ(secondary_rgb, illuminant_RGB,\n illuminant_XYZ, rgb_to_xyz_matrix,\n chromatic_adaptation_transform)\n\n xy = XYZ_to_xy(large_xyz, illuminant_XYZ)\n\n return xy, secondary_rgb.reshape((3, 3))\n\n\n# def plot_chromaticity_diagram(\n# rate=480/755.0*2, xmin=0.0, xmax=0.8, ymin=0.0, ymax=0.9, **kwargs):\n# # キーワード引数の初期値設定\n# # ------------------------------------\n# monitor_primaries = kwargs.get('monitor_primaries', None)\n# secondaries = kwargs.get('secondaries', None)\n# test_scatter = kwargs.get('test_scatter', None)\n# intersection = kwargs.get('intersection', None)\n\n# # プロット用データ準備\n# # ---------------------------------\n# xy_image = get_chromaticity_image(\n# xmin=xmin, xmax=xmax, ymin=ymin, ymax=ymax)\n# cmf_xy = _get_cmfs_xy()\n\n# bt709_gamut, _ = get_primaries(name=cs.BT709)\n# bt2020_gamut, _ = get_primaries(name=cs.BT2020)\n# dci_p3_gamut, _ = get_primaries(name=cs.P3_D65)\n# ap0_gamut, _ = get_primaries(name=cs.ACES_AP0)\n# ap1_gamut, _ = get_primaries(name=cs.ACES_AP1)\n# xlim = (min(0, xmin), max(0.8, xmax))\n# ylim = (min(0, ymin), max(0.9, ymax))\n\n# ax1 = pu.plot_1_graph(fontsize=20 * rate,\n# figsize=((xmax - xmin) * 10 * rate,\n# (ymax - ymin) * 10 * rate),\n# graph_title=\"CIE1931 Chromaticity Diagram\",\n# graph_title_size=None,\n# xlabel=None, ylabel=None,\n# axis_label_size=None,\n# legend_size=18 * rate,\n# xlim=xlim, ylim=ylim,\n# xtick=[x * 0.1 + xmin for x in\n# range(int((xlim[1] - xlim[0])/0.1) + 1)],\n# ytick=[x * 0.1 + ymin for x in\n# range(int((ylim[1] - ylim[0])/0.1) + 1)],\n# xtick_size=17 * rate,\n# ytick_size=17 * rate,\n# linewidth=4 * rate,\n# minor_xtick_num=2,\n# minor_ytick_num=2)\n# ax1.plot(cmf_xy[..., 0], cmf_xy[..., 1], '-k', lw=3.5*rate, label=None)\n# ax1.plot((cmf_xy[-1, 0], cmf_xy[0, 0]), (cmf_xy[-1, 1], cmf_xy[0, 1]),\n# '-k', lw=3.5*rate, label=None)\n# ax1.plot(bt709_gamut[:, 0], bt709_gamut[:, 1],\n# c=UNIVERSAL_COLOR_LIST[0], label=\"BT.709\", lw=2.75*rate)\n# ax1.plot(bt2020_gamut[:, 0], bt2020_gamut[:, 1],\n# c=UNIVERSAL_COLOR_LIST[1], label=\"BT.2020\", lw=2.75*rate)\n# ax1.plot(dci_p3_gamut[:, 0], dci_p3_gamut[:, 1],\n# c=UNIVERSAL_COLOR_LIST[2], label=\"DCI-P3\", lw=2.75*rate)\n# ax1.plot(ap1_gamut[:, 0], ap1_gamut[:, 1],\n# c=UNIVERSAL_COLOR_LIST[3], label=\"ACES AP1\", lw=2.75*rate)\n# ax1.plot(ap0_gamut[:, 0], ap0_gamut[:, 1],\n# c=UNIVERSAL_COLOR_LIST[4], label=\"ACES AP0\", lw=2.75*rate)\n# if monitor_primaries is not None:\n# ax1.plot(monitor_primaries[:, 0], monitor_primaries[:, 1],\n# c=\"#202020\", label=\"???\", lw=3*rate)\n# if secondaries is not None:\n# xy, rgb = secondaries\n# ax1.scatter(xy[..., 0], xy[..., 1], s=700*rate, marker='s', c=rgb,\n# edgecolors='#404000', linewidth=2*rate)\n# if test_scatter is not None:\n# xy, rgb = test_scatter\n# ax1.scatter(xy[..., 0], xy[..., 1], s=300*rate, marker='s', c=rgb,\n# edgecolors='#404040', linewidth=2*rate)\n# if intersection is not None:\n# ax1.scatter(intersection[..., 0], intersection[..., 1],\n# s=300*rate, marker='s', c='#CCCCCC',\n# edgecolors='#404040', linewidth=2*rate)\n\n# ax1.imshow(xy_image, extent=(xmin, xmax, ymin, ymax))\n# plt.legend(loc='upper right')\n# plt.savefig('temp_fig.png', bbox_inches='tight')\n# plt.show()\n\n\ndef get_chromaticity_image(samples=1024, antialiasing=True, bg_color=0.9,\n xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0):\n \"\"\"\n xy色度図の馬蹄形の画像を生成する\n\n Returns\n -------\n ndarray\n rgb image.\n \"\"\"\n\n \"\"\"\n 色域設定。sRGBだと狭くて少し変だったのでBT.2020に設定。\n 若干色が薄くなるのが難点。暇があれば改良したい。\n \"\"\"\n # color_space = models.BT2020_COLOURSPACE\n # color_space = models.S_GAMUT3_COLOURSPACE\n color_space = models.ACES_CG_COLOURSPACE\n\n # 馬蹄形のxy値を算出\n # --------------------------\n cmf_xy = _get_cmfs_xy()\n\n \"\"\"\n 馬蹄の内外の判別をするために三角形で領域分割する(ドロネー図を作成)。\n ドロネー図を作れば後は外積計算で領域の内外を判別できる(たぶん)。\n\n なお、作成したドロネー図は以下のコードでプロット可能。\n 1点補足しておくと、```plt.triplot``` の第三引数は、\n 第一、第二引数から三角形を作成するための **インデックス** のリスト\n になっている。[[0, 1, 2], [2, 4, 3], ...]的な。\n\n ```python\n plt.figure()\n plt.triplot(xy[:, 0], xy[:, 1], triangulation.simplices.copy(), '-o')\n plt.title('triplot of Delaunay triangulation')\n plt.show()\n ```\n \"\"\"\n triangulation = Delaunay(cmf_xy)\n\n \"\"\"\n ```triangulation.find_simplex()``` で xy がどのインデックスの領域か\n 調べることができる。戻り値が ```-1``` の場合は領域に含まれないため、\n 0以下のリストで領域判定の mask を作ることができる。\n \"\"\"\n xx, yy\\\n = np.meshgrid(np.linspace(xmin, xmax, samples),\n np.linspace(ymax, ymin, samples))\n xy = np.dstack((xx, yy))\n mask = (triangulation.find_simplex(xy) < 0).astype(np.float)\n\n # アンチエイリアシングしてアルファチャンネルを滑らかに\n # ------------------------------------------------\n if antialiasing:\n kernel = np.array([\n [0, 1, 0],\n [1, 2, 1],\n [0, 1, 0],\n ]).astype(np.float)\n kernel /= np.sum(kernel)\n mask = convolve(mask, kernel)\n\n # ネガポジ反転\n # --------------------------------\n mask = 1 - mask[:, :, np.newaxis]\n\n # xy のメッシュから色を復元\n # ------------------------\n illuminant_XYZ = D65_WHITE\n illuminant_RGB = color_space.whitepoint\n chromatic_adaptation_transform = 'XYZ Scaling'\n large_xyz_to_rgb_matrix = color_space.XYZ_to_RGB_matrix\n xy[xy == 0.0] = 1.0 # ゼロ割対策\n large_xyz = xy_to_XYZ(xy)\n rgb = XYZ_to_RGB(large_xyz, illuminant_XYZ, illuminant_RGB,\n large_xyz_to_rgb_matrix,\n chromatic_adaptation_transform)\n\n \"\"\"\n そのままだとビデオレベルが低かったりするので、\n 各ドット毎にRGB値を正規化&最大化する。\n \"\"\"\n rgb[rgb == 0] = 1.0 # ゼロ割対策\n rgb = normalise_maximum(rgb, axis=-1)\n\n # mask 適用\n # -------------------------------------\n mask_rgb = np.dstack((mask, mask, mask))\n rgb *= mask_rgb\n\n # 背景色をグレーに変更\n # -------------------------------------\n bg_rgb = np.ones_like(rgb)\n bg_rgb *= (1 - mask_rgb) * bg_color\n\n rgb += bg_rgb\n\n rgb = rgb ** (1/2.2)\n\n return rgb\n\n\ndef get_csf_color_image(width=640, height=480,\n lv1=np.uint16(np.array([1.0, 1.0, 1.0]) * 1023 * 0x40),\n lv2=np.uint16(np.array([1.0, 1.0, 1.0]) * 512 * 0x40),\n stripe_num=18):\n \"\"\"\n 長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。\n 入力信号レベルは16bitに限定する。\n\n Parameters\n ----------\n width : numeric.\n width of the pattern image.\n height : numeric.\n height of the pattern image.\n lv1 : numeric\n video level 1. this value must be 10bit.\n lv2 : numeric\n video level 2. this value must be 10bit.\n stripe_num : numeric\n number of the stripe.\n\n Returns\n -------\n array_like\n a cms pattern image.\n \"\"\"\n width_list = equal_devision(width, stripe_num)\n height_list = equal_devision(height, stripe_num)\n h_pos_list = equal_devision(width // 2, stripe_num)\n v_pos_list = equal_devision(height // 2, stripe_num)\n lv1_16bit = lv1\n lv2_16bit = lv2\n img = np.zeros((height, width, 3), dtype=np.uint16)\n\n width_temp = width\n height_temp = height\n h_pos_temp = 0\n v_pos_temp = 0\n for idx in range(stripe_num):\n lv = lv1_16bit if (idx % 2) == 0 else lv2_16bit\n temp_img = np.ones((height_temp, width_temp, 3), dtype=np.uint16)\n # temp_img *= lv\n temp_img[:, :] = lv\n ed_pos_h = h_pos_temp + width_temp\n ed_pos_v = v_pos_temp + height_temp\n img[v_pos_temp:ed_pos_v, h_pos_temp:ed_pos_h] = temp_img\n width_temp -= width_list[stripe_num - 1 - idx]\n height_temp -= height_list[stripe_num - 1 - idx]\n h_pos_temp += h_pos_list[idx]\n v_pos_temp += v_pos_list[idx]\n\n return img\n\n\ndef plot_xyY_color_space(name='ITU-R BT.2020', samples=1024,\n antialiasing=True):\n \"\"\"\n SONY の HDR説明資料にあるような xyY の図を作る。\n\n Parameters\n ----------\n name : str\n name of the target color space.\n\n Returns\n -------\n None\n\n \"\"\"\n\n # 馬蹄の領域判別用データ作成\n # --------------------------\n primary_xy, _ = get_primaries(name=name)\n triangulation = Delaunay(primary_xy)\n\n xx, yy\\\n = np.meshgrid(np.linspace(0, 1, samples), np.linspace(1, 0, samples))\n xy = np.dstack((xx, yy))\n mask = (triangulation.find_simplex(xy) < 0).astype(np.float)\n\n # アンチエイリアシングしてアルファチャンネルを滑らかに\n # ------------------------------------------------\n if antialiasing:\n kernel = np.array([\n [0, 1, 0],\n [1, 2, 1],\n [0, 1, 0],\n ]).astype(np.float)\n kernel /= np.sum(kernel)\n mask = convolve(mask, kernel)\n\n # ネガポジ反転\n # --------------------------------\n mask = 1 - mask[:, :, np.newaxis]\n\n # xy のメッシュから色を復元\n # ------------------------\n illuminant_XYZ = D65_WHITE\n illuminant_RGB = RGB_COLOURSPACES[name].whitepoint\n chromatic_adaptation_transform = 'CAT02'\n large_xyz_to_rgb_matrix = get_xyz_to_rgb_matrix(name)\n rgb_to_large_xyz_matrix = get_rgb_to_xyz_matrix(name)\n large_xyz = xy_to_XYZ(xy)\n rgb = XYZ_to_RGB(large_xyz, illuminant_XYZ, illuminant_RGB,\n large_xyz_to_rgb_matrix,\n chromatic_adaptation_transform)\n\n \"\"\"\n そのままだとビデオレベルが低かったりするので、\n 各ドット毎にRGB値を正規化&最大化する。\n \"\"\"\n rgb_org = normalise_maximum(rgb, axis=-1)\n\n # mask 適用\n # -------------------------------------\n mask_rgb = np.dstack((mask, mask, mask))\n rgb = rgb_org * mask_rgb\n rgba = np.dstack((rgb, mask))\n\n # こっからもういちど XYZ に変換。Yを求めるために。\n # ---------------------------------------------\n large_xyz2 = RGB_to_XYZ(rgb, illuminant_RGB, illuminant_XYZ,\n rgb_to_large_xyz_matrix,\n chromatic_adaptation_transform)\n\n # ログスケールに変換する準備\n # --------------------------\n large_y = large_xyz2[..., 1] * 1000\n large_y[large_y < 1] = 1.0\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n # ax.plot_wireframe(xy[..., 0], xy[..., 1], np.log10(large_y),\n # rcount=100, ccount=100)\n ax.plot_surface(xy[..., 0], xy[..., 1], np.log10(large_y),\n rcount=64, ccount=64, facecolors=rgb_org)\n ax.set_xlabel(\"x\")\n ax.set_ylabel(\"y\")\n ax.set_zlabel(\"Y\")\n ax.set_zticks([0, 1, 2, 3])\n ax.set_zticklabels([1, 10, 100, 1000])\n\n # chromatcity_image の取得。z=0 の位置に貼り付ける\n # ----------------------------------------------\n cie1931_rgb = get_chromaticity_image(samples=samples, bg_color=0.0)\n\n alpha = np.zeros_like(cie1931_rgb[..., 0])\n rgb_sum = np.sum(cie1931_rgb, axis=-1)\n alpha[rgb_sum > 0.00001] = 1\n cie1931_rgb = np.dstack((cie1931_rgb[..., 0], cie1931_rgb[..., 1],\n cie1931_rgb[..., 2], alpha))\n zz = np.zeros_like(xy[..., 0])\n ax.plot_surface(xy[..., 0], xy[..., 1], zz,\n facecolors=cie1931_rgb)\n\n plt.show()\n\n\ndef log_tick_formatter(val, pos=None):\n return \"{:.0e}\".format(10**val)\n\n\ndef get_3d_grid_cube_format(grid_num=4):\n \"\"\"\n # 概要\n (0, 0, 0), (1, 0, 0), (0, 1, 0), (1, 1, 0), (0, 0, 1), ...\n みたいな配列を返す。\n CUBE形式の3DLUTを作成する時に便利。\n \"\"\"\n\n base = np.linspace(0, 1, grid_num)\n ones_x = np.ones((grid_num, grid_num, 1))\n ones_y = np.ones((grid_num, 1, grid_num))\n ones_z = np.ones((1, grid_num, grid_num))\n r_3d = base[np.newaxis, np.newaxis, :] * ones_x\n g_3d = base[np.newaxis, :, np.newaxis] * ones_y\n b_3d = base[:, np.newaxis, np.newaxis] * ones_z\n r_3d = r_3d.flatten()\n g_3d = g_3d.flatten()\n b_3d = b_3d.flatten()\n\n return np.dstack((r_3d, g_3d, b_3d))\n\n\ndef quadratic_bezier_curve(t, p0, p1, p2, samples=1024):\n # x = ((1 - t) ** 2) * p0[0] + 2 * (1 - t) * t * p1[0]\\\n # + (t ** 2) * p2[0]\n # y = ((1 - t) ** 2) * p0[1] + 2 * (1 - t) * t * p1[1]\\\n # + (t ** 2) * p2[1]\n\n x = ((1 - t) ** 2) * p0[0] + 2 * (1 - t) * t * p1[0]\\\n + (t ** 2) * p2[0]\n y = ((1 - t) ** 2) * p0[1] + 2 * (1 - t) * t * p1[1]\\\n + (t ** 2) * p2[1]\n\n # ax1 = pu.plot_1_graph(fontsize=20,\n # figsize=(10, 8),\n # graph_title=\"Title\",\n # graph_title_size=None,\n # xlabel=\"X Axis Label\", ylabel=\"Y Axis Label\",\n # axis_label_size=None,\n # legend_size=17,\n # xlim=None,\n # ylim=None,\n # xtick=None,\n # ytick=None,\n # xtick_size=None, ytick_size=None,\n # linewidth=3,\n # minor_xtick_num=None,\n # minor_ytick_num=None)\n # ax1.plot(x, y, label='aaa')\n # plt.legend(loc='upper left')\n # plt.show()\n\n\ndef gen_step_gradation(width=1024, height=128, step_num=17,\n bit_depth=10, color=(1.0, 1.0, 1.0),\n direction='h', debug=False):\n \"\"\"\n # 概要\n 階段状に変化するグラデーションパターンを作る。\n なお、引数の調整により正確に1階調ずつ変化するパターンも作成可能。\n\n # 注意事項\n 正確に1階調ずつ変化するグラデーションを作る場合は\n ```step_num = (2 ** bit_depth) + 1```\n となるようにパラメータを指定すること。具体例は以下のExample参照。\n\n # Example\n ```\n grad_8 = gen_step_gradation(width=grad_width, height=grad_height,\n step_num=257, bit_depth=8,\n color=(1.0, 1.0, 1.0), direction='h')\n\n grad_10 = gen_step_gradation(width=grad_width, height=grad_height,\n step_num=1025, bit_depth=10,\n color=(1.0, 1.0, 1.0), direction='h')\n ```\n \"\"\"\n max = 2 ** bit_depth\n\n # グラデーション方向設定\n # ----------------------\n if direction == 'h':\n pass\n else:\n temp = height\n height = width\n width = temp\n\n if (max + 1 != step_num):\n \"\"\"\n 1階調ずつの増加では無いパターン。\n 末尾のデータが 256 や 1024 になるため -1 する。\n \"\"\"\n val_list = np.linspace(0, max, step_num)\n val_list[-1] -= 1\n else:\n \"\"\"\n 正確に1階調ずつ変化するパターン。\n 末尾のデータが 256 や 1024 になるため除外する。\n \"\"\"\n val_list = np.linspace(0, max, step_num)[0:-1]\n step_num -= 1 # step_num は 引数で余計に +1 されてるので引く\n\n # 念のため1階調ずつの変化か確認\n # ---------------------------\n diff = val_list[1:] - val_list[0:-1]\n if (diff == 1).all():\n pass\n else:\n raise ValueError(\"calculated value is invalid.\")\n\n # まずは水平1LINEのグラデーションを作る\n # -----------------------------------\n step_length_list = equal_devision(width, step_num)\n step_bar_list = []\n for step_idx, length in enumerate(step_length_list):\n step = [np.ones((length)) * color[c_idx] * val_list[step_idx]\n for c_idx in range(3)]\n if direction == 'h':\n step = np.dstack(step)\n step_bar_list.append(step)\n step_bar = np.hstack(step_bar_list)\n else:\n step = np.dstack(step).reshape((length, 1, 3))\n step_bar_list.append(step)\n step_bar = np.vstack(step_bar_list)\n\n # ブロードキャストを利用して2次元に拡張する\n # ------------------------------------------\n if direction == 'h':\n img = step_bar * np.ones((height, 1, 3))\n else:\n img = step_bar * np.ones((1, height, 3))\n\n # np.uint16 にコンバート\n # ------------------------------\n # img = np.uint16(np.round(img * (2 ** (16 - bit_depth))))\n\n if debug:\n preview_image(img, 'rgb')\n\n return img\n\n\ndef merge(img_a, img_b, pos=(0, 0)):\n \"\"\"\n img_a に img_b をマージする。\n img_a にデータを上書きする。\n\n pos = (horizontal_st, vertical_st)\n \"\"\"\n b_width = img_b.shape[1]\n b_height = img_b.shape[0]\n\n img_a[pos[1]:b_height+pos[1], pos[0]:b_width+pos[0]] = img_b\n\n\ndef merge_with_alpha(bg_img, fg_img, tf_str=tf.SRGB, pos=(0, 0)):\n \"\"\"\n 合成する。\n\n Parameters\n ----------\n bg_img : array_like(float, 3-channel)\n image data.\n fg_img : array_like(float, 4-channel)\n image data\n tf : strings\n transfer function\n pos : list(int)\n (pos_h, pos_v)\n \"\"\"\n f_width = fg_img.shape[1]\n f_height = fg_img.shape[0]\n\n bg_merge_area = bg_img[pos[1]:f_height+pos[1], pos[0]:f_width+pos[0]]\n bg_linear = tf.eotf_to_luminance(bg_merge_area, tf_str)\n fg_linear = tf.eotf_to_luminance(fg_img, tf_str)\n alpha = fg_linear[:, :, 3:] / tf.PEAK_LUMINANCE[tf_str]\n\n out_linear = (1 - alpha) * bg_linear + fg_linear[:, :, :-1]\n out_merge_area = tf.oetf_from_luminance(out_linear, tf_str)\n bg_img[pos[1]:f_height+pos[1], pos[0]:f_width+pos[0]] = out_merge_area\n\n return bg_img\n\n\ndef dot_pattern(dot_size=4, repeat=4, color=np.array([1.0, 1.0, 1.0])):\n \"\"\"\n dot pattern 作る。\n\n Parameters\n ----------\n dot_size : integer\n dot size.\n repeat : integer\n The number of high-low pairs.\n color : array_like\n color value.\n\n Returns\n -------\n array_like\n dot pattern image.\n\n \"\"\"\n # 水平・垂直のピクセル数\n pixel_num = dot_size * 2 * repeat\n\n # High-Log の 論理配列を生成\n even_logic = [(np.arange(pixel_num) % (dot_size * 2)) - dot_size < 0]\n even_logic = np.dstack((even_logic, even_logic, even_logic))\n odd_logic = np.logical_not(even_logic)\n\n # 着色\n color = color.reshape((1, 1, 3))\n even_line = (np.ones((1, pixel_num, 3)) * even_logic) * color\n odd_line = (np.ones((1, pixel_num, 3)) * odd_logic) * color\n\n # V方向にコピー&Even-Oddの結合\n even_block = np.repeat(even_line, dot_size, axis=0)\n odd_block = np.repeat(odd_line, dot_size, axis=0)\n pair_block = np.vstack((even_block, odd_block))\n\n img = np.vstack([pair_block for x in range(repeat)])\n\n return img\n\n\ndef complex_dot_pattern(kind_num=3, whole_repeat=2,\n fg_color=np.array([1.0, 1.0, 1.0]),\n bg_color=np.array([0.15, 0.15, 0.15])):\n \"\"\"\n dot pattern 作る。\n\n Parameters\n ----------\n kind_num : integer\n 作成するドットサイズの種類。\n 例えば、kind_num=3 ならば、1dot, 2dot, 4dot のパターンを作成。\n whole_repeat : integer\n 異なる複数種類のドットパターンの組数。\n 例えば、kind_num=3, whole_repeat=2 ならば、\n 1dot, 2dot, 4dot のパターンを水平・垂直に2組作る。\n fg_color : array_like\n foreground color value.\n bg_color : array_like\n background color value.\n reduce : bool\n HDRテストパターンの3840x2160専用。縦横を半分にする。\n\n Returns\n -------\n array_like\n dot pattern image.\n\n \"\"\"\n max_dot_width = 2 ** kind_num\n img_list = []\n for size_idx in range(kind_num)[::-1]:\n dot_size = 2 ** size_idx\n repeat = max_dot_width // dot_size\n dot_img = dot_pattern(dot_size, repeat, fg_color)\n img_list.append(dot_img)\n img_list.append(np.ones_like(dot_img) * bg_color)\n # preview_image(dot_img)\n\n line_upper_img = np.hstack(img_list)\n line_upper_img = np.hstack([line_upper_img for x in range(whole_repeat)])\n line_lower_img = line_upper_img.copy()[:, ::-1, :]\n h_unit_img = np.vstack((line_upper_img, line_lower_img))\n\n img = np.vstack([h_unit_img for x in range(kind_num * whole_repeat)])\n # preview_image(img)\n # cv2.imwrite(\"hoge.tiff\", np.uint8(img * 0xFF)[..., ::-1])\n\n return img\n\n\ndef make_csf_color_image(width=640, height=640,\n lv1=np.array([940, 940, 940], dtype=np.uint16),\n lv2=np.array([1023, 1023, 1023], dtype=np.uint16),\n stripe_num=6):\n \"\"\"\n 長方形を複数個ズラして重ねることでCSFパターンっぽいのを作る。\n 入力信号レベルは10bitに限定する。\n\n Parameters\n ----------\n width : numeric.\n width of the pattern image.\n height : numeric.\n height of the pattern image.\n lv1 : array_like\n video level 1. this value must be 10bit.\n lv2 : array_like\n video level 2. this value must be 10bit.\n stripe_num : numeric\n number of the stripe.\n\n Returns\n -------\n array_like\n a cms pattern image.\n \"\"\"\n width_list = equal_devision(width, stripe_num)\n height_list = equal_devision(height, stripe_num)\n h_pos_list = equal_devision(width // 2, stripe_num)\n v_pos_list = equal_devision(height // 2, stripe_num)\n img = np.zeros((height, width, 3), dtype=np.uint16)\n\n width_temp = width\n height_temp = height\n h_pos_temp = 0\n v_pos_temp = 0\n for idx in range(stripe_num):\n lv = lv1 if (idx % 2) == 0 else lv2\n temp_img = np.ones((height_temp, width_temp, 3), dtype=np.uint16)\n temp_img = temp_img * lv.reshape((1, 1, 3))\n ed_pos_h = h_pos_temp + width_temp\n ed_pos_v = v_pos_temp + height_temp\n img[v_pos_temp:ed_pos_v, h_pos_temp:ed_pos_h] = temp_img\n width_temp -= width_list[stripe_num - 1 - idx]\n height_temp -= height_list[stripe_num - 1 - idx]\n h_pos_temp += h_pos_list[idx]\n v_pos_temp += v_pos_list[idx]\n\n # preview_image(img / 1023)\n\n return img\n\n\ndef make_tile_pattern(width=480, height=960, h_tile_num=4,\n v_tile_num=4, low_level=(940, 940, 940),\n high_level=(1023, 1023, 1023)):\n \"\"\"\n タイル状の縞々パターンを作る\n \"\"\"\n width_array = equal_devision(width, h_tile_num)\n height_array = equal_devision(height, v_tile_num)\n high_level = np.array(high_level, dtype=np.uint16)\n low_level = np.array(low_level, dtype=np.uint16)\n\n v_buf = []\n\n for v_idx, height in enumerate(height_array):\n h_buf = []\n for h_idx, width in enumerate(width_array):\n tile_judge = (h_idx + v_idx) % 2 == 0\n h_temp = np.zeros((height, width, 3), dtype=np.uint16)\n h_temp[:, :] = high_level if tile_judge else low_level\n h_buf.append(h_temp)\n\n v_buf.append(np.hstack(h_buf))\n img = np.vstack(v_buf)\n # preview_image(img/1024.0)\n return img\n\n\ndef get_marker_idx(img, marker_value):\n return np.all(img == marker_value, axis=-1)\n\n\ndef make_ycbcr_checker(height=480, v_tile_num=4):\n \"\"\"\n YCbCr係数誤りを確認するテストパターンを作る。\n 正直かなり汚い組み方です。雑に作ったパターンを悪魔合体させています。\n\n Parameters\n ----------\n height : numeric.\n height of the pattern image.\n v_tile_num : numeric\n number of the tile in the vertical direction.\n\n Note\n ----\n 横長のパターンになる。以下の式が成立する。\n\n ```\n h_tile_num = v_tile_num * 2\n width = height * 2\n ```\n\n Returns\n -------\n array_like\n ycbcr checker image\n \"\"\"\n\n cyan_img = make_tile_pattern(width=height, height=height,\n h_tile_num=v_tile_num,\n v_tile_num=v_tile_num,\n low_level=[0, 990, 990],\n high_level=[0, 1023, 1023])\n magenta_img = make_tile_pattern(width=height, height=height,\n h_tile_num=v_tile_num,\n v_tile_num=v_tile_num,\n low_level=[990, 0, 312],\n high_level=[1023, 0, 312])\n\n out_img = np.hstack([cyan_img, magenta_img])\n\n # preview_image(out_img/1023.0)\n\n return out_img\n\n\ndef plot_color_checker_image(rgb, rgb2=None, size=(1920, 1080),\n block_size=1/4.5, padding=0.01):\n \"\"\"\n ColorCheckerをプロットする\n\n Parameters\n ----------\n rgb : array_like\n RGB value of the ColorChecker.\n RGB's shape must be (24, 3).\n rgb2 : array_like\n It's a optional parameter.\n If You want to draw two different ColorCheckers,\n set the RGB value to this variable.\n size : tuple\n canvas size.\n block_size : float\n A each block's size.\n This value is ratio to height of the canvas.\n padding : float\n A padding to the block.\n\n Returns\n -------\n array_like\n A ColorChecker image.\n\n \"\"\"\n IMG_HEIGHT = size[1]\n IMG_WIDTH = size[0]\n COLOR_CHECKER_SIZE = block_size\n COLOR_CHECKER_H_NUM = 6\n COLOR_CHECKER_V_NUM = 4\n COLOR_CHECKER_PADDING = 0.01\n # 基本パラメータ算出\n # --------------------------------------\n COLOR_CHECKER_H_NUM = 6\n COLOR_CHECKER_V_NUM = 4\n img_height = IMG_HEIGHT\n img_width = IMG_WIDTH\n patch_st_h = int(IMG_WIDTH / 2.0\n - (IMG_HEIGHT * COLOR_CHECKER_SIZE\n * COLOR_CHECKER_H_NUM / 2.0\n + (IMG_HEIGHT * COLOR_CHECKER_PADDING\n * (COLOR_CHECKER_H_NUM / 2.0 - 0.5)) / 2.0))\n patch_st_v = int(IMG_HEIGHT / 2.0\n - (IMG_HEIGHT * COLOR_CHECKER_SIZE\n * COLOR_CHECKER_V_NUM / 2.0\n + (IMG_HEIGHT * COLOR_CHECKER_PADDING\n * (COLOR_CHECKER_V_NUM / 2.0 - 0.5)) / 2.0))\n patch_width = int(img_height * COLOR_CHECKER_SIZE)\n patch_height = patch_width\n patch_space = int(img_height * COLOR_CHECKER_PADDING)\n\n # 24ループで1枚の画像に24パッチを描画\n # -------------------------------------------------\n img_all_patch = np.zeros((img_height, img_width, 3), dtype=np.uint8)\n for idx in range(COLOR_CHECKER_H_NUM * COLOR_CHECKER_V_NUM):\n v_idx = idx // COLOR_CHECKER_H_NUM\n h_idx = (idx % COLOR_CHECKER_H_NUM)\n patch = np.ones((patch_height, patch_width, 3))\n patch[:, :] = rgb[idx]\n st_h = patch_st_h + (patch_width + patch_space) * h_idx\n st_v = patch_st_v + (patch_height + patch_space) * v_idx\n img_all_patch[st_v:st_v+patch_height, st_h:st_h+patch_width] = patch\n\n # pt1 = (st_h, st_v) # upper left\n pt2 = (st_h + patch_width, st_v) # upper right\n pt3 = (st_h, st_v + patch_height) # lower left\n pt4 = (st_h + patch_width, st_v + patch_height) # lower right\n pts = np.array((pt2, pt3, pt4))\n sub_color = rgb[idx].tolist() if rgb2 is None else rgb2[idx].tolist()\n cv2.fillPoly(img_all_patch, [pts], sub_color)\n\n preview_image(img_all_patch)\n\n return img_all_patch\n\n\ndef get_log10_x_scale(\n sample_num=8, ref_val=1.0, min_exposure=-1, max_exposure=6):\n \"\"\"\n Log10スケールのx軸データを作る。\n\n Examples\n --------\n >>> get_log2_x_scale(\n ... sample_num=8, ref_val=1.0, min_exposure=-1, max_exposure=6)\n array([ 1.0000e-01 1.0000e+00 1.0000e+01 1.0000e+02\n 1.0000e+03 1.0000e+04 1.0000e+05 1.0000e+06])\n \"\"\"\n x_min = np.log10(ref_val * (10 ** min_exposure))\n x_max = np.log10(ref_val * (10 ** max_exposure))\n x = np.linspace(x_min, x_max, sample_num)\n\n return 10.0 ** x\n\n\ndef get_log2_x_scale(\n sample_num=32, ref_val=1.0, min_exposure=-6.5, max_exposure=6.5):\n \"\"\"\n Log2スケールのx軸データを作る。\n\n Examples\n --------\n >>> get_log2_x_scale(sample_num=10, min_exposure=-4.0, max_exposure=4.0)\n array([[ 0.0625 0.11573434 0.214311 0.39685026 0.73486725\n 1.36079 2.5198421 4.66611616 8.64047791 16. ]])\n \"\"\"\n x_min = np.log2(ref_val * (2 ** min_exposure))\n x_max = np.log2(ref_val * (2 ** max_exposure))\n x = np.linspace(x_min, x_max, sample_num)\n\n return 2.0 ** x\n\n\ndef shaper_func_linear_to_log2(\n x, mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5):\n \"\"\"\n ACESutil.Lin_to_Log2_param.ctl を参考に作成。\n https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Lin_to_Log2_param.ctl\n\n Parameters\n ----------\n x : array_like\n linear data.\n mid_gray : float\n 18% gray value on linear scale.\n min_exposure : float\n minimum value on log scale.\n max_exposure : float\n maximum value on log scale.\n\n Returns\n -------\n array_like\n log2 value that is transformed from linear x value.\n\n Examples\n --------\n >>> shaper_func_linear_to_log2(\n ... x=0.18, mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5)\n 0.5\n >>> shaper_func_linear_to_log2(\n ... x=np.array([0.00198873782209, 16.2917402385])\n ... mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5)\n array([ 1.58232402e-13 1.00000000e+00])\n \"\"\"\n # log2空間への変換。mid_gray が 0.0 となるように補正\n y = np.log2(x / mid_gray)\n\n # min, max の範囲で正規化。\n y_normalized = (y - min_exposure) / (max_exposure - min_exposure)\n\n y_normalized[y_normalized < 0] = 0\n\n return y_normalized\n\n\ndef shaper_func_log2_to_linear(\n x, mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5):\n \"\"\"\n ACESutil.Log2_to_Lin_param.ctl を参考に作成。\n https://github.com/ampas/aces-dev/blob/master/transforms/ctl/utilities/ACESutil.Log2_to_Lin_param.ctl\n\n Log2空間の補足は shaper_func_linear_to_log2() の説明を参照\n\n Examples\n --------\n >>> x = np.array([0.0, 1.0])\n >>> shaper_func_log2_to_linear(\n ... x, mid_gray=0.18, min_exposure=-6.5, max_exposure=6.5)\n array([0.00198873782209, 16.2917402385])\n \"\"\"\n x_re_scale = x * (max_exposure - min_exposure) + min_exposure\n y = (2.0 ** x_re_scale) * mid_gray\n # plt.plot(x, y)\n # plt.show()\n\n return y\n\n\ndef draw_straight_line(img, pt1, pt2, color, thickness):\n \"\"\"\n 直線を引く。OpenCV だと 8bit しか対応してないっぽいので自作。\n\n Parameters\n ----------\n img : array_like\n image data.\n pt1 : list(pos_h, pos_v)\n start point.\n pt2 : list(pos_h, pos_v)\n end point.\n color : array_like\n color\n thickness : int\n thickness.\n\n Returns\n -------\n array_like\n image data with line.\n\n Notes\n -----\n thickness のパラメータは pt1 の点から右下方向に効きます。\n pt1 を中心として太さではない事に注意。\n\n Examples\n --------\n >>> pt1 = (0, 0)\n >>> pt2 = (1920, 0)\n >>> color = (940, 940, 940)\n >>> thickness = 4\n >>> draw_straight_line(img, pt1, pt2, color, thickness)\n \"\"\"\n # parameter check\n if (pt1[0] != pt2[0]) and (pt1[1] != pt2[1]):\n raise ValueError(\"invalid pt1, pt2 parameters\")\n\n # check direction\n if pt1[0] == pt2[0]:\n thickness_direction = 'h'\n else:\n thickness_direction = 'v'\n\n if thickness_direction == 'h':\n for h_idx in range(thickness):\n img[pt1[1]:pt2[1], pt1[0] + h_idx, :] = color\n\n elif thickness_direction == 'v':\n for v_idx in range(thickness):\n img[pt1[1] + v_idx, pt1[0]:pt2[0], :] = color\n\n\ndef draw_outline(img, fg_color, outline_width):\n \"\"\"\n img に対して外枠線を引く\n\n Parameters\n ----------\n img : array_like\n image data.\n fg_color : array_like\n color\n outline_width : int\n thickness.\n\n Returns\n -------\n array_like\n image data with line.\n\n Examples\n --------\n >>> img = np.zeros((1080, 1920, 3))\n >>> color = (940, 940, 940)\n >>> thickness = 2\n >>> draw_outline(img, color, thickness)\n \"\"\"\n width = img.shape[1]\n height = img.shape[0]\n # upper left\n pt1 = (0, 0)\n pt2 = (width, 0)\n draw_straight_line(\n img, pt1, pt2, fg_color, outline_width)\n pt1 = (0, 0)\n pt2 = (0, height)\n draw_straight_line(\n img, pt1, pt2, fg_color, outline_width)\n # lower right\n pt1 = (width - outline_width, 0)\n pt2 = (width - outline_width, height)\n draw_straight_line(\n img, pt1, pt2, fg_color, outline_width)\n pt1 = (0, height - outline_width)\n pt2 = (width, height - outline_width)\n draw_straight_line(\n img, pt1, pt2, fg_color, outline_width)\n\n\ndef convert_luminance_to_color_value(luminance, transfer_function):\n \"\"\"\n 輝度[cd/m2] から code value の RGB値に変換する。\n luminance の単位は [cd/m2]。無彩色である。\n\n Examples\n --------\n >>> convert_luminance_to_color_value(100, tf.GAMMA24)\n >>> [ 1.0 1.0 1.0 ]\n >>> convert_luminance_to_color_value(100, tf.ST2084)\n >>> [ 0.50807842 0.50807842 0.50807842 ]\n \"\"\"\n code_value = convert_luminance_to_code_value(\n luminance, transfer_function)\n return np.array([code_value, code_value, code_value])\n\n\ndef convert_luminance_to_code_value(luminance, transfer_function):\n \"\"\"\n 輝度[cd/m2] から code value に変換する。\n luminance の単位は [cd/m2]\n \"\"\"\n return tf.oetf_from_luminance(luminance, transfer_function)\n\n\ndef calc_rad_patch_idx2(outmost_num=5, current_num=3):\n \"\"\"\n 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの\n RGB値のリストを得る。\n https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png\n\n 得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で\n 得られる変換テーブルを使った変換が必要。\n 本関数はまさにその変換を行う。\n \"\"\"\n base = np.arange(outmost_num ** 2).reshape((outmost_num, outmost_num))\n # print(base)\n t_idx = (outmost_num - current_num) // 2\n trimmed = base[t_idx:t_idx+current_num, t_idx:t_idx+current_num]\n # print(trimmed)\n # print(np.arange(current_num**2).reshape((current_num, current_num)))\n\n half_num = current_num // 2\n conv_idx = []\n for idx in range(half_num):\n val = (current_num ** 2) // 2 + half_num - current_num * idx\n conv_idx.append(val)\n for idx in range(current_num)[::-1]:\n conv_idx.append(idx)\n for idx in range(1, current_num - 1):\n conv_idx.append(idx * current_num)\n for idx in range(current_num):\n val = (current_num ** 2) - current_num + idx\n conv_idx.append(val)\n for idx in range(1, half_num):\n val = (current_num ** 2) - 1 - idx * current_num\n conv_idx.append(val)\n\n conv_idx = trimmed.flatten()[conv_idx]\n\n return conv_idx\n\n\ndef _calc_rgb_from_same_lstar_radial_data(\n lstar, temp_chroma, current_num, color_space):\n \"\"\"\n 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの\n RGB値のリストを得る。\n https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png\n\n 得られたデータは並べ替えが済んでいないため、calc_rad_patch_idx2() で\n 得られる変換テーブルを使った変換が必要。\n \"\"\"\n current_patch_num = (current_num - 1) * 4 if current_num > 1 else 1\n rad = np.linspace(0, 2 * np.pi, current_patch_num, endpoint=False)\n ll = np.ones((current_patch_num)) * lstar\n aa = np.cos(rad) * temp_chroma\n bb = np.sin(rad) * temp_chroma\n lab = np.dstack((ll, aa, bb))\n large_xyz = Lab_to_XYZ(lab)\n rgb = XYZ_to_RGB(large_xyz, D65_WHITE, D65_WHITE,\n color_space.XYZ_to_RGB_matrix)\n\n return np.clip(rgb, 0.0, 1.0)\n\n\ndef calc_same_lstar_radial_color_patch_data(\n lstar=58, chroma=32.5, outmost_num=9,\n color_space=BT709_COLOURSPACE,\n transfer_function=tf.GAMMA24):\n \"\"\"\n 以下のような、中心がGray、周りは CIELAB 空間の a*b*平面のカラーパッチの\n RGB値のリストを得る。\n https://user-images.githubusercontent.com/3609012/75444470-d3bc5600-59a6-11ea-962b-c315648782a9.png\n\n 得られた RGB値のリストは最初のデータが画像左上の緑データ、\n 最後のデータが画像右下の紫データとなるよう既に**並べ替え**が行われている。\n\n よってパッチをプロットする場合はRGB値リストの先頭から順にデータを取り出し、\n 右下に向かって並べていけば良い。\n \"\"\"\n patch_num = outmost_num ** 2\n transfer_function = tf.GAMMA24\n rgb_list = np.ones((patch_num, 3))\n\n current_num_list = range(1, outmost_num + 1, 2)\n chroma_list = np.linspace(0, chroma, len(current_num_list))\n for temp_chroma, current_num in zip(chroma_list, current_num_list):\n current_patch_num = (current_num - 1) * 4 if current_num > 1 else 1\n rgb = _calc_rgb_from_same_lstar_radial_data(\n lstar, temp_chroma, current_num, color_space)\n rgb = np.reshape(rgb, (current_patch_num, 3))\n rgb = tf.oetf(rgb, transfer_function)\n conv_idx = calc_rad_patch_idx2(\n outmost_num=outmost_num, current_num=current_num)\n for idx in range(current_patch_num):\n rgb_list[conv_idx[idx]] = rgb[idx]\n\n return rgb_list\n\n\ndef _plot_same_lstar_radial_color_patch_data(\n lstar=58, chroma=32.5, outmost_num=9,\n color_space=BT709_COLOURSPACE,\n transfer_function=tf.GAMMA24):\n patch_size = 1080 // outmost_num\n img = np.ones((1080, 1080, 3)) * 0.0\n rgb = calc_same_lstar_radial_color_patch_data(\n lstar=lstar, chroma=chroma, outmost_num=outmost_num,\n color_space=color_space, transfer_function=transfer_function)\n\n for idx in range(outmost_num ** 2):\n h_idx = idx % outmost_num\n v_idx = idx // outmost_num\n st_pos = (h_idx * patch_size, v_idx * patch_size)\n temp_img = np.ones((patch_size, patch_size, 3))\\\n * rgb[idx][np.newaxis, np.newaxis, :]\n merge(img, temp_img, st_pos)\n\n cv2.imwrite(\"hoge2.tiff\", np.uint16(np.round(img[:, :, ::-1] * 0xFFFF)))\n\n\ndef get_accelerated_x_1x(sample_num=64):\n \"\"\"\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n\n Examples\n --------\n >>> x0 = np.linspace(0, 1, 8)\n >>> x1 = get_accelerated_x_1x(8)\n >>> print(x0)\n >>> [ 0. 0.142 0.285 0.428 0.571 0.714 0.857 1. ]\n >>> print(x1)\n >>> [ 0. 0.049 0.188 0.388 0.611 0.811 0.950 1. ]\n \"\"\"\n rad = np.linspace(-0.5 * np.pi, 0.5 * np.pi, sample_num)\n x = (np.sin(rad) + 1) / 2\n\n return x\n\n\ndef get_accelerated_x_2x(sample_num=64):\n \"\"\"\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る。\n 加速度が `get_accelerated_x_1x` の2倍!!\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n\n Examples\n --------\n >>> x0 = np.linspace(0, 1, 8)\n >>> x2 = get_accelerated_x_2x(8)\n >>> print(x0)\n >>> [ 0. 0.142 0.285 0.428 0.571 0.714 0.857 1. ]\n >>> print(x2)\n >>> [ 0. 0.006 0.084 0.328 0.671 0.915 0.993 1. ]\n \"\"\"\n rad = np.linspace(-0.5 * np.pi, 0.5 * np.pi, sample_num)\n rad = np.sin(rad) * 0.5 * np.pi\n x = (np.sin(rad) + 1) / 2\n\n return x\n\n\ndef get_accelerated_x_4x(sample_num=64):\n \"\"\"\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る。\n 加速度が `get_accelerated_x_1x` の4倍!!\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n \"\"\"\n rad = np.linspace(-0.5 * np.pi, 0.5 * np.pi, sample_num)\n rad = np.sin(rad) * 0.5 * np.pi\n rad = np.sin(rad) * 0.5 * np.pi\n x = (np.sin(rad) + 1) / 2\n\n return x\n\n\ndef get_accelerated_x_8x(sample_num=64):\n \"\"\"\n 単調増加ではなく、加速度が 0→1→0 となるような x を作る。\n 加速度が `get_accelerated_x_1x` の4倍!!\n\n Parameters\n ----------\n sample_num : int\n the number of the sample.\n\n Returns\n -------\n array_like\n accelerated value list\n \"\"\"\n rad = np.linspace(-0.5 * np.pi, 0.5 * np.pi, sample_num)\n rad = np.sin(rad) * 0.5 * np.pi\n rad = np.sin(rad) * 0.5 * np.pi\n rad = np.sin(rad) * 0.5 * np.pi\n x = (np.sin(rad) + 1) / 2\n\n return x\n\n\ndef generate_color_checker_rgb_value(\n color_space=BT709_COLOURSPACE, target_white=D65_WHITE):\n \"\"\"\n Generate the 24 RGB values of the color checker.\n\n Parameters\n ----------\n color_space : color space\n color space object in `colour` module.\n\n target_white : array_like\n the xy values of the white point of target color space.\n\n Returns\n -------\n array_like\n 24 RGB values. This is linear. OETF is not applied.\n\n Examples\n --------\n >>> generate_color_checker_rgb_value(\n ... color_space=colour.models.BT709_COLOURSPACE,\n ... target_white=[0.3127, 0.3290])\n >>> [[ 0.17289286 0.08205728 0.05714562]\n >>> [ 0.5680292 0.29250401 0.21951748]\n >>> [ 0.10435534 0.19656108 0.32958666]\n >>> [ 0.1008804 0.14839018 0.05327639]\n >>> [ 0.22303549 0.2169701 0.43166537]\n >>> [ 0.10715338 0.513512 0.41415978]\n >>> [ 0.74639182 0.20020473 0.03081343]\n >>> [ 0.05947812 0.10659045 0.39897686]\n >>> [ 0.5673215 0.08485376 0.11945382]\n >>> [ 0.11177253 0.04285397 0.14166202]\n >>> [ 0.34250836 0.5062777 0.0557734 ]\n >>> [ 0.79262553 0.35803886 0.025485 ]\n >>> [ 0.01864598 0.05139665 0.28886469]\n >>> [ 0.054392 0.29876719 0.07187681]\n >>> [ 0.45628547 0.03075684 0.04092033]\n >>> [ 0.85379178 0.56503558 0.01475575]\n >>> [ 0.53533883 0.09006355 0.3047824 ]\n >>> [-0.03662977 0.24753781 0.39824679]\n >>> [ 0.91177068 0.91497623 0.89427332]\n >>> [ 0.57973934 0.59203191 0.59370647]\n >>> [ 0.35495537 0.36538027 0.36772001]\n >>> [ 0.19009594 0.19180133 0.19316719]\n >>> [ 0.08524707 0.08890587 0.09255774]\n >>> [ 0.03038879 0.03118623 0.03279615]]\n \"\"\"\n colour_checker_param = COLOURCHECKERS.get('ColorChecker 2005')\n # 今回の処理では必要ないデータもあるので xyY と whitepoint だけ抽出\n # -------------------------------------------------------------\n _name, data, whitepoint = colour_checker_param\n temp_xyY = []\n for key in data.keys():\n temp_xyY.append(data[key])\n temp_xyY = np.array(temp_xyY)\n large_xyz = xyY_to_XYZ(temp_xyY)\n rgb_white_point = D65_WHITE\n illuminant_XYZ = whitepoint # ColorCheckerのオリジナルデータの白色点\n illuminant_RGB = rgb_white_point # XYZ to RGB 変換後の白色点を設定\n chromatic_adaptation_transform = 'CAT02'\n large_xyz_to_rgb_matrix = color_space.XYZ_to_RGB_matrix\n\n rgb = XYZ_to_RGB(\n large_xyz, illuminant_XYZ, illuminant_RGB,\n large_xyz_to_rgb_matrix, chromatic_adaptation_transform)\n\n return rgb\n\n\ndef make_color_checker_image(rgb, width=1920, padding_rate=0.01):\n \"\"\"\n 6x4 の カラーチェッカーの画像を作る。\n Height は Width から自動計算される。padding_rate で少し値が変わる。\n \"\"\"\n h_patch_num = 6\n v_patch_num = 4\n\n # 各種パラメータ計算\n each_padding = int(width * padding_rate + 0.5)\n h_padding_total = each_padding * (h_patch_num + 1)\n h_patch_width_total = width - h_padding_total\n patch_height = h_patch_width_total // h_patch_num\n height = patch_height * v_patch_num + each_padding * (v_patch_num + 1)\n patch_width_list = equal_devision(h_patch_width_total, h_patch_num)\n\n # パッチを並べる\n img = np.zeros((height, width, 3))\n for v_idx in range(v_patch_num):\n h_pos_st = each_padding\n v_pos_st = each_padding + v_idx * (patch_height + each_padding)\n for h_idx in range(h_patch_num):\n rgb_idx = v_idx * h_patch_num + h_idx\n pos = (h_pos_st, v_pos_st)\n patch_img = np.ones((patch_height, patch_width_list[h_idx], 3))\\\n * rgb[rgb_idx]\n merge(img, patch_img, pos)\n h_pos_st += (patch_width_list[h_idx] + each_padding)\n\n return img\n\n\ndef calc_st_pos_for_centering(bg_size, fg_size):\n \"\"\"\n Calculate start postion for centering.\n\n Parameters\n ----------\n bg_size : touple(int)\n (width, height) of the background image.\n\n fg_size : touple(int)\n (width, height) of the foreground image.\n\n Returns\n -------\n touple (int)\n (st_pos_h, st_pos_v)\n\n Examples\n --------\n >>> calc_st_pos_for_centering(bg_size=(1920, 1080), fg_size=(640, 480))\n >>> (640, 300)\n \"\"\"\n bg_width = bg_size[0]\n bg_height = bg_size[1]\n\n fg_width = fg_size[0]\n fg_height = fg_size[1]\n\n st_pos_h = bg_width // 2 - fg_width // 2\n st_pos_v = bg_height // 2 - fg_height // 2\n\n return (st_pos_h, st_pos_v)\n\n\ndef get_size_from_image(img):\n \"\"\"\n `calc_st_pos_for_centering()` の引数計算が面倒だったので関数化。\n \"\"\"\n return (img.shape[1], img.shape[0])\n\n\nif __name__ == '__main__':\n os.chdir(os.path.dirname(os.path.abspath(__file__)))\n # print(calc_rad_patch_idx(outmost_num=9, current_num=1))\n # _plot_same_lstar_radial_color_patch_data(\n # lstar=58, chroma=32.5, outmost_num=7,\n # color_space=BT709_COLOURSPACE,\n # transfer_function=tf.GAMMA24)\n # calc_rad_patch_idx2(outmost_num=9, current_num=7)\n # print(convert_luminance_to_color_value(100, tf.ST2084))\n # print(generate_color_checker_rgb_value(target_white=[0.3127, 0.3290]))\n print(calc_st_pos_for_centering(bg_size=(1920, 1080), fg_size=(640, 480)))\n" ]
[ [ "numpy.linspace", "numpy.all", "numpy.round", "numpy.zeros_like", "scipy.ndimage.filters.convolve", "numpy.hstack", "numpy.ones_like", "numpy.clip", "numpy.reshape", "numpy.arange", "numpy.sin", "numpy.repeat", "numpy.zeros", "matplotlib.pyplot.figure", "numpy.logical_not", "numpy.append", "numpy.log10", "numpy.array", "matplotlib.pyplot.show", "numpy.sum", "numpy.log2", "scipy.spatial.Delaunay", "numpy.cos", "numpy.dstack", "numpy.ones", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ijinmao/CAM-Localization
[ "dfa214be984f77d577dba1065e2c63e0c1b0b82b" ]
[ "demo.py" ]
[ "\nimport numpy as np\nimport cv2\nimport matplotlib.pylab as plt\nfrom keras.preprocessing.image import load_img\nfrom keras.models import model_from_json\nfrom models import (\n\tcreate_cam_model, preprocess_image, \n\tget_cam_img\n)\n\n# Define CAM conv layer name\nCAM_CONV_LAYER = 'cam_conv_layer'\n\n\ndef read_model(model_path, weigths_path):\n\t\"\"\"Load your pretrained model\n\t\"\"\"\n\tmodel = model_from_json(open(model_path).read())\n\tmodel.load_weights(weigths_path)\n\treturn model\n\ndef train_cam_model(X_train, Y_train, X_test, Y_test, \n\t\t\t\t\tbatch_size, nb_epoch):\n\t\"\"\"Train CAM model based on your pretrained model\n\n\t# Arguments\n\t\tmodel: your pretrained model, CAM model is trained based on this model.\n\n\t\"\"\"\n\n\t# Use your allready trained model\n\tpretrained_model_path = ''\n\tpretrained_weights_path = ''\n\n\t# Your pretrained model name\n\tpretrained_model_name = 'VGG16'\n\n\t# Label class num\n\tnum_classes = 10\n\n\t# CAM input spacial size\n\tgap_spacial_size = 14\n\n\t# The layer before CAM(GAP) layers.\n\t# CAM paper suggests to use the last convnet(VGG) or mergenet(Inception, or other architectures)\n\t# Change this name based on your model.\n\tif pretrained_model_name == 'VGG16':\n\t\tin_layer_name = 'block5_conv3'\n\telif pretrained_model_name == 'InceptionV3':\n\t\tin_layer_name = 'batchnormalization_921'\n\telif pretrained_model_name == 'ResNet50':\n\t\tin_layer_name = 'merge_13'\n\telse:\n\t\tin_layer_name = ''\n\n\t# Load your allready trained model, transfer it to CAM model\n\tpretrained_model = read_model(pretrained_model_path, \n\t\t\t\t\t\t\t\t pretrained_weights_path)\n\n\t# Create CAM model based on trained model\n\tmodel = create_cam_model(pretrained_model,\n\t\t\t\t\t\t\t gap_spacial_size,\n\t\t\t\t\t\t\t num_classes,\n\t\t\t\t\t\t\t in_layer_name,\n\t\t\t\t\t\t\t CAM_CONV_LAYER)\n\n\t# Train your CAM model\n\tmodel.compile(loss='categorical_crossentropy',\n\t\t\t \t optimizer='adadelta',\n\t\t\t \t metrics=['accuracy'])\n\tmodel.fit(X_train, Y_train, \n\t\t\t batch_size=batch_size, \n\t\t\t nb_epoch=nb_epoch,\n\t\t\t shuffle=True, verbose=1, \n\t\t\t validation_data=(X_test, Y_test))\n\n\t# Save model\n\tmodel.save_weights('')\n\treturn model\n\ndef cam_model():\n\t\"\"\"\n\tReturn your trained CAM model\n\t\"\"\"\n\treturn\n\ndef plot_cam_map(img_path, img_size, batch_size, label_plot):\n\t\"\"\"Plot class activation map.\n\n\t\"\"\"\n\t\n\t# CAM input spacial size\n\tgap_spacial_size = 14\n\n\t# Use your trained CAM model\n\tmodel = cam_model()\n\n\t# Load and format data\n\tim_ori = np.asarray(load_img(img_path, target_size=(img_size, img_size)))\n\ttest_data = preprocess_image(img_path, img_size, expand_dims=True)\n\n\t# Get class map image\n\tim_cam = get_cam_img(model,\n\t\t\t\t\t\t test_data,\n\t\t\t\t\t\t label_plot,\n\t\t\t\t\t\t CAM_CONV_LAYER,\n\t\t\t\t\t\t ratio=img_size / gap_spacial_size)\n\n\t# Resize if the shape of class map is not equal to original image\n\tif im_cam.shape != im_ori[:, :, 0].shape:\n\t\tim_cam = cv2.resize(im_cam, (img_size, img_size), cv2.INTER_LINEAR)\n\t\n\t# Show the predictions. You can analyze the class map with the predictions.\n\tprediction_labels = model.predict(test_data.astype('float32'), batch_size=batch_size, verbose=1)\n\tprint('Info: Predictions:\\n{}'.format(prediction_labels))\n\n\t# Plot original image and the class map\n\tplt.imshow(im_ori)\n\tplt.imshow(im_cam,\n\t\t\t cmap='jet',\n\t\t\t alpha=0.5,\n\t\t\t interpolation='bilinear')\n\tplt.show()\n" ]
[ [ "matplotlib.pylab.show", "matplotlib.pylab.imshow" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
reinforcementdriving/cvpods
[ "32d98b74745020be035a0e20337ad934201615c4", "614a975e5425bbaeb66bbd1ffca552d633ba89ca", "32d98b74745020be035a0e20337ad934201615c4", "614a975e5425bbaeb66bbd1ffca552d633ba89ca", "614a975e5425bbaeb66bbd1ffca552d633ba89ca" ]
[ "cvpods/engine/predictor.py", "cvpods/modeling/backbone/splat.py", "cvpods/data/datasets/torchvision_datasets.py", "cvpods/modeling/meta_arch/auto_assign.py", "cvpods/utils/visualizer/visualizer.py" ]
[ "#!/usr/bin/python3\n# -*- coding:utf-8 -*-\nfrom copy import deepcopy\n\nimport torch\n\nfrom cvpods.checkpoint import DefaultCheckpointer\nfrom cvpods.data import build_transform_gens\n\n__all__ = [\"DefaultPredictor\"]\n\n\nclass DefaultPredictor:\n \"\"\"\n Create a simple end-to-end predictor with the given config that runs on\n single device for a single input image.\n Compared to using the model directly, this class does the following additions:\n\n 1. Load checkpoint from `cfg.MODEL.WEIGHTS`.\n 2. Always take BGR image as the input and apply conversion defined by `cfg.INPUT.FORMAT`.\n 3. Apply resizing defined by `cfg.INPUT.{MIN,MAX}_SIZE_TEST`.\n 4. Take one input image and produce a single output, instead of a batch.\n\n If you'd like to do anything more fancy, please refer to its source code\n as examples to build and use the model manually.\n\n Attributes:\n metadata (Metadata): the metadata of the underlying dataset, obtained from\n cfg.DATASETS.TEST.\n\n Examples:\n .. code-block:: python\n\n pred = DefaultPredictor(cfg)\n inputs = cv2.imread(\"input.jpg\")\n outputs = pred(inputs)\n \"\"\"\n def __init__(self, cfg, meta):\n self.cfg = deepcopy(cfg)\n if self.cfg.MODEL.DEVICE.startswith(\"cuda:\"):\n torch.cuda.set_device(self.cfg.MODEL.DEVICE)\n self.cfg.MODEL.DEVICE = \"cuda\"\n self.model = cfg.build_model(self.cfg)\n self.model.eval()\n self.metadata = meta\n\n checkpointer = DefaultCheckpointer(self.model)\n checkpointer.load(cfg.MODEL.WEIGHTS)\n\n self.transform_gen = build_transform_gens(cfg.INPUT.AUG.TEST_PIPELINES)\n\n self.input_format = cfg.INPUT.FORMAT\n assert self.input_format in [\"RGB\", \"BGR\"], self.input_format\n\n def __call__(self, original_image):\n \"\"\"\n Args:\n original_image (np.ndarray): an image of shape (H, W, C) (in BGR order).\n\n Returns:\n predictions (dict):\n the output of the model for one image only.\n See :doc:`/tutorials/models` for details about the format.\n \"\"\"\n with torch.no_grad(\n ): # https://github.com/sphinx-doc/sphinx/issues/4258\n # Apply pre-processing to image.\n if self.input_format == \"RGB\":\n # whether the model expects BGR inputs or RGB\n original_image = original_image[:, :, ::-1]\n height, width = original_image.shape[:2]\n\n image = original_image\n for tfm_gen in self.transform_gen:\n image = tfm_gen.get_transform(image).apply_image(image)\n\n image = torch.as_tensor(image.astype(\"float32\").transpose(2, 0, 1))\n\n inputs = {\"image\": image, \"height\": height, \"width\": width}\n predictions = self.model([inputs])[0]\n return predictions\n", "\"\"\"Split-Attention\"\"\"\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.nn import Module, ReLU\nfrom torch.nn.modules.utils import _pair\n\nfrom cvpods.layers import Conv2d, get_norm\n\n__all__ = ['SplAtConv2d']\n\n\nclass RFConv2d(object):\n def __init__(self, *args, **kwargs):\n raise NotImplementedError\n\n\nclass DropBlock2D(RFConv2d):\n pass\n\n\nclass SplAtConv2d(Module):\n \"\"\"Split-Attention Conv2d\n \"\"\"\n\n def __init__(self,\n in_channels,\n channels,\n kernel_size,\n stride=(1, 1),\n padding=(0, 0),\n dilation=(1, 1),\n groups=1,\n bias=True,\n radix=2,\n reduction_factor=4,\n rectify=False,\n rectify_avg=False,\n norm=None,\n dropblock_prob=0.0,\n **kwargs):\n super(SplAtConv2d, self).__init__()\n padding = _pair(padding)\n self.rectify = rectify and (padding[0] > 0 or padding[1] > 0)\n self.rectify_avg = rectify_avg\n inter_channels = max(in_channels * radix // reduction_factor, 32)\n self.radix = radix\n self.cardinality = groups\n self.channels = channels\n self.dropblock_prob = dropblock_prob\n if self.rectify:\n self.conv = RFConv2d(in_channels,\n channels * radix,\n kernel_size,\n stride,\n padding,\n dilation,\n groups=groups * radix,\n bias=bias,\n average_mode=rectify_avg,\n **kwargs)\n else:\n self.conv = Conv2d(in_channels,\n channels * radix,\n kernel_size,\n stride,\n padding,\n dilation,\n groups=groups * radix,\n bias=bias,\n **kwargs)\n self.use_bn = norm is not None\n self.bn0 = get_norm(norm, channels * radix)\n self.relu = ReLU(inplace=True)\n self.fc1 = Conv2d(channels, inter_channels, 1, groups=self.cardinality)\n self.bn1 = get_norm(norm, inter_channels)\n self.fc2 = Conv2d(inter_channels, channels * radix, 1, groups=self.cardinality)\n if dropblock_prob > 0.0:\n self.dropblock = DropBlock2D(dropblock_prob, 3)\n\n def forward(self, x):\n x = self.conv(x)\n if self.use_bn:\n x = self.bn0(x)\n if self.dropblock_prob > 0.0:\n x = self.dropblock(x)\n x = self.relu(x)\n\n batch, channel = x.shape[:2]\n if self.radix > 1:\n splited = torch.split(x, channel // self.radix, dim=1)\n gap = sum(splited)\n else:\n gap = x\n gap = F.adaptive_avg_pool2d(gap, 1)\n gap = self.fc1(gap)\n\n if self.use_bn:\n gap = self.bn1(gap)\n gap = self.relu(gap)\n\n atten = self.fc2(gap).view((batch, self.radix, self.channels))\n if self.radix > 1:\n atten = F.softmax(atten, dim=1).view(batch, -1, 1, 1)\n else:\n atten = F.sigmoid(atten, dim=1).view(batch, -1, 1, 1)\n\n if self.radix > 1:\n atten = torch.split(atten, channel // self.radix, dim=1)\n out = sum([att * split for (att, split) in zip(atten, splited)])\n else:\n out = atten * x\n return out.contiguous()\n", "import os.path as osp\nfrom copy import deepcopy\nfrom typing import Optional\n\nimport numpy as np\nfrom PIL import Image\n\nimport torch\nfrom torchvision.datasets import CIFAR10, STL10\n\nimport cvpods\nfrom cvpods.data.base_dataset import BaseDataset\nfrom cvpods.data.registry import DATASETS, PATH_ROUTES\n\n_PREDEFINED_SPLITS_CIFAR10 = {\n \"dataset_type\": \"CIFAR10Dataset\",\n \"evaluator_type\": {\"cifar10\": \"classification\"},\n \"cifar10\": {\n \"cifar10_train\": (\"cifar10\", \"train\"),\n \"cifar10_test\": (\"cifar10\", \"test\"),\n },\n}\nPATH_ROUTES.register(_PREDEFINED_SPLITS_CIFAR10, \"CIFAR10\")\n\n\[email protected]()\nclass CIFAR10Dataset(CIFAR10):\n\n def __init__(self, cfg, dataset_name, transforms, is_train=True, **kwargs):\n\n self.cfg = cfg\n self.misc = kwargs\n\n image_root, split = _PREDEFINED_SPLITS_CIFAR10[\"cifar10\"][dataset_name]\n self.data_root = osp.join(osp.split(osp.split(cvpods.__file__)[0])[0], \"datasets\")\n\n if is_train:\n assert split == \"train\"\n else:\n assert split == \"test\"\n\n super(CIFAR10Dataset, self).__init__(\n root=osp.join(self.data_root, image_root),\n train=is_train,\n download=True,\n transform=transforms)\n self.aspect_ratios = np.zeros(len(self), dtype=np.uint8)\n self.transforms = self.transform\n self._apply_transforms = BaseDataset._apply_transforms\n self.meta[\"evaluator_type\"] = \"classification\"\n\n def __getitem__(self, index):\n image, target = Image.fromarray(self.data[index]), self.targets[index]\n dataset_dict = {\"image_id\": index, \"category_id\": target}\n\n image = image.convert(\"RGB\")\n image = np.asarray(image)\n # flip channels if needed for RGB to BGR\n image = image[:, :, ::-1]\n\n images, _ = self._apply_transforms(self, image, dataset_dict)\n\n def process(dd, img):\n if img.shape[0] == 3: # CHW\n dd[\"image\"] = torch.as_tensor(np.ascontiguousarray(img))\n elif len(img.shape) == 3 and img.shape[-1] == 3:\n dd[\"image\"] = torch.as_tensor(\n np.ascontiguousarray(img.transpose(2, 0, 1)))\n elif len(img.shape) == 4 and img.shape[-1] == 3:\n # NHWC -> NCHW\n dd[\"image\"] = torch.as_tensor(\n np.ascontiguousarray(img.transpose(0, 3, 1, 2)))\n\n return dd\n\n if isinstance(images, dict):\n ret = {}\n # multiple input pipelines\n for desc, item in images.items():\n img, anno = item\n ret[desc] = process(deepcopy(dataset_dict), img)\n return ret\n else:\n return process(dataset_dict, images)\n\n\n_PREDEFINED_SPLITS_STL10 = {\n \"dataset_type\": \"STL10Datasets\",\n \"evaluator_type\": {\"stl10\": \"classification\"},\n \"stl10\": {\n \"stl10_train\": (\"stl10\", \"train\"),\n \"stl10_unlabeled\": (\"stl10\", \"unlabeled\"),\n \"stl10_test\": (\"stl10\", \"test\"),\n },\n}\nPATH_ROUTES.register(_PREDEFINED_SPLITS_STL10, \"STL10\")\n\n\[email protected]()\nclass STL10Datasets(STL10):\n def __init__(self, cfg, dataset_name, transforms=[], is_train=True, **kwargs):\n self.cfg = cfg\n self.misc = kwargs\n\n image_root, split = _PREDEFINED_SPLITS_STL10[\"stl10\"][dataset_name]\n self.data_root = osp.join(osp.split(osp.split(cvpods.__file__)[0])[0], \"datasets\")\n self.image_root = osp.join(self.data_root, image_root)\n super(STL10Datasets, self).__init__(\n self.image_root, split=split, download=True, transform=None)\n\n self.aspect_ratios = np.zeros(len(self), dtype=np.uint8)\n self.transforms = transforms\n self._apply_transforms = BaseDataset._apply_transforms\n\n self.is_train = is_train\n self.meta = {\"evaluator_type\": _PREDEFINED_SPLITS_STL10[\"evaluator_type\"][\"stl10\"]}\n\n def __getitem__(self, index):\n\n target: Optional[int]\n if self.labels is not None:\n img, target = self.data[index], int(self.labels[index])\n else:\n img, target = self.data[index], None\n\n # doing this so that it is consistent with all other datasets\n # to return a PIL Image\n image = Image.fromarray(np.transpose(img, (1, 2, 0)))\n dataset_dict = {\"image_id\": index, \"category_id\": target}\n\n # format == BGR in cvpods\n image = image.convert(\"RGB\")\n image = np.asarray(image)\n image = image[:, :, ::-1] # flip channels for RGB -> BGR format\n\n images, _ = self._apply_transforms(self, image, dataset_dict)\n\n def process(dd, img):\n if img.shape[0] == 3: # CHW\n dd[\"image\"] = torch.as_tensor(np.ascontiguousarray(img))\n if len(img.shape) == 3 and img.shape[-1] == 3:\n dd[\"image\"] = torch.as_tensor(np.ascontiguousarray(img.transpose(2, 0, 1)))\n elif len(img.shape) == 4 and img.shape[-1] == 3:\n # NHWC -> NCHW\n dd[\"image\"] = torch.as_tensor(np.ascontiguousarray(img.transpose(0, 3, 1, 2)))\n\n return dd\n\n if isinstance(images, dict):\n ret = {}\n # multiple input pipelines\n for desc, item in images.items():\n img, anno = item\n ret[desc] = process(deepcopy(dataset_dict), img)\n return ret\n else:\n return process(dataset_dict, images)\n", "import logging\nimport math\nfrom typing import List\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn.functional as F\nfrom torch import nn\n\nfrom cvpods.layers import ShapeSpec, batched_nms, cat\nfrom cvpods.modeling.box_regression import Shift2BoxTransform\nfrom cvpods.modeling.losses import iou_loss\nfrom cvpods.modeling.meta_arch.fcos import Scale\nfrom cvpods.modeling.meta_arch.retinanet import permute_to_N_HWA_K\nfrom cvpods.modeling.postprocessing import detector_postprocess\nfrom cvpods.structures import Boxes, ImageList, Instances, pairwise_iou\nfrom cvpods.utils import log_first_n\n\n\ndef positive_bag_loss(logits, mask, gaussian_probs):\n # bag_prob = Mean-max(logits)\n weight = (3 * logits).exp() * gaussian_probs * mask\n w = weight / weight.sum(dim=1, keepdim=True).clamp(min=1e-12)\n bag_prob = (w * logits).sum(dim=1)\n return F.binary_cross_entropy(bag_prob,\n torch.ones_like(bag_prob),\n reduction='none')\n\n\ndef negative_bag_loss(logits, gamma):\n return logits**gamma * F.binary_cross_entropy(\n logits, torch.zeros_like(logits), reduction='none')\n\n\ndef normal_distribution(x, mu=0, sigma=1):\n return (-(x - mu)**2 / (2 * sigma**2)).exp()\n\n\ndef normalize(x):\n return (x - x.min() + 1e-12) / (x.max() - x.min() + 1e-12)\n\n\nclass AutoAssign(nn.Module):\n \"\"\"\n Implement AutoAssign (https://arxiv.org/abs/2007.03496).\n \"\"\"\n def __init__(self, cfg):\n super(AutoAssign, self).__init__()\n\n self.device = torch.device(cfg.MODEL.DEVICE)\n\n # fmt: off\n self.num_classes = cfg.MODEL.FCOS.NUM_CLASSES\n self.in_features = cfg.MODEL.FCOS.IN_FEATURES\n self.fpn_strides = cfg.MODEL.FCOS.FPN_STRIDES\n # Loss parameters:\n self.focal_loss_alpha = cfg.MODEL.FCOS.FOCAL_LOSS_ALPHA\n self.focal_loss_gamma = cfg.MODEL.FCOS.FOCAL_LOSS_GAMMA\n self.iou_loss_type = cfg.MODEL.FCOS.IOU_LOSS_TYPE\n self.reg_weight = cfg.MODEL.FCOS.REG_WEIGHT\n # Inference parameters:\n self.score_threshold = cfg.MODEL.FCOS.SCORE_THRESH_TEST\n self.topk_candidates = cfg.MODEL.FCOS.TOPK_CANDIDATES_TEST\n self.nms_threshold = cfg.MODEL.FCOS.NMS_THRESH_TEST\n self.max_detections_per_image = cfg.TEST.DETECTIONS_PER_IMAGE\n # fmt: on\n\n self.backbone = cfg.build_backbone(\n cfg, input_shape=ShapeSpec(channels=len(cfg.MODEL.PIXEL_MEAN)))\n\n backbone_shape = self.backbone.output_shape()\n feature_shapes = [backbone_shape[f] for f in self.in_features]\n self.head = AutoAssignHead(cfg, feature_shapes)\n self.shift_generator = cfg.build_shift_generator(cfg, feature_shapes)\n\n # Matching and loss\n self.shift2box_transform = Shift2BoxTransform(\n weights=cfg.MODEL.FCOS.BBOX_REG_WEIGHTS)\n self.mu = nn.Parameter(torch.zeros(80, 2))\n self.sigma = nn.Parameter(torch.ones(80, 2))\n\n pixel_mean = torch.Tensor(cfg.MODEL.PIXEL_MEAN).to(self.device).view(\n 3, 1, 1)\n pixel_std = torch.Tensor(cfg.MODEL.PIXEL_STD).to(self.device).view(\n 3, 1, 1)\n self.normalizer = lambda x: (x - pixel_mean) / pixel_std\n self.to(self.device)\n\n def forward(self, batched_inputs):\n \"\"\"\n Args:\n batched_inputs: a list, batched outputs of :class:`DatasetMapper` .\n Each item in the list contains the inputs for one image.\n For now, each item in the list is a dict that contains:\n\n * image: Tensor, image in (C, H, W) format.\n * instances: Instances\n\n Other information that's included in the original dicts, such as:\n\n * \"height\", \"width\" (int): the output resolution of the model, used in inference.\n See :meth:`postprocess` for details.\n Returns:\n dict[str: Tensor]:\n mapping from a named loss to a tensor storing the loss. Used during training only.\n \"\"\"\n images = self.preprocess_image(batched_inputs)\n if \"instances\" in batched_inputs[0]:\n gt_instances = [\n x[\"instances\"].to(self.device) for x in batched_inputs\n ]\n elif \"targets\" in batched_inputs[0]:\n log_first_n(\n logging.WARN,\n \"'targets' in the model inputs is now renamed to 'instances'!\",\n n=10)\n gt_instances = [\n x[\"targets\"].to(self.device) for x in batched_inputs\n ]\n else:\n gt_instances = None\n\n features = self.backbone(images.tensor)\n features = [features[f] for f in self.in_features]\n box_cls, box_delta, box_center = self.head(features)\n shifts = self.shift_generator(features)\n\n if self.training:\n return self.losses(shifts, gt_instances, box_cls, box_delta,\n box_center)\n else:\n results = self.inference(box_cls, box_delta, box_center, shifts,\n images)\n processed_results = []\n for results_per_image, input_per_image, image_size in zip(\n results, batched_inputs, images.image_sizes):\n height = input_per_image.get(\"height\", image_size[0])\n width = input_per_image.get(\"width\", image_size[1])\n r = detector_postprocess(results_per_image, height, width)\n processed_results.append({\"instances\": r})\n return processed_results\n\n def losses(self, shifts, gt_instances, box_cls, box_delta, box_center):\n box_cls_flattened = [\n permute_to_N_HWA_K(x, self.num_classes) for x in box_cls\n ]\n box_delta_flattened = [permute_to_N_HWA_K(x, 4) for x in box_delta]\n box_center_flattened = [permute_to_N_HWA_K(x, 1) for x in box_center]\n pred_class_logits = cat(box_cls_flattened, dim=1)\n pred_shift_deltas = cat(box_delta_flattened, dim=1)\n pred_obj_logits = cat(box_center_flattened, dim=1)\n\n pred_class_probs = pred_class_logits.sigmoid()\n pred_obj_probs = pred_obj_logits.sigmoid()\n pred_box_probs = []\n num_foreground = pred_class_logits.new_zeros(1)\n num_background = pred_class_logits.new_zeros(1)\n positive_losses = []\n gaussian_norm_losses = []\n\n for shifts_per_image, gt_instances_per_image, \\\n pred_class_probs_per_image, pred_shift_deltas_per_image, \\\n pred_obj_probs_per_image in zip(\n shifts, gt_instances, pred_class_probs, pred_shift_deltas,\n pred_obj_probs):\n locations = torch.cat(shifts_per_image, dim=0)\n labels = gt_instances_per_image.gt_classes\n gt_boxes = gt_instances_per_image.gt_boxes\n\n target_shift_deltas = self.shift2box_transform.get_deltas(\n locations, gt_boxes.tensor.unsqueeze(1))\n is_in_boxes = target_shift_deltas.min(dim=-1).values > 0\n\n foreground_idxs = torch.nonzero(is_in_boxes, as_tuple=True)\n\n with torch.no_grad():\n # predicted_boxes_per_image: a_{j}^{loc}, shape: [j, 4]\n predicted_boxes_per_image = self.shift2box_transform.apply_deltas(\n pred_shift_deltas_per_image, locations)\n # gt_pred_iou: IoU_{ij}^{loc}, shape: [i, j]\n gt_pred_iou = pairwise_iou(\n gt_boxes, Boxes(predicted_boxes_per_image)).max(\n dim=0, keepdim=True).values.repeat(\n len(gt_instances_per_image), 1)\n\n # pred_box_prob_per_image: P{a_{j} \\in A_{+}}, shape: [j, c]\n pred_box_prob_per_image = torch.zeros_like(\n pred_class_probs_per_image)\n box_prob = 1 / (1 - gt_pred_iou[foreground_idxs]).clamp_(1e-12)\n for i in range(len(gt_instances_per_image)):\n idxs = foreground_idxs[0] == i\n if idxs.sum() > 0:\n box_prob[idxs] = normalize(box_prob[idxs])\n pred_box_prob_per_image[foreground_idxs[1],\n labels[foreground_idxs[0]]] = box_prob\n pred_box_probs.append(pred_box_prob_per_image)\n\n normal_probs = []\n for stride, shifts_i in zip(self.fpn_strides, shifts_per_image):\n gt_shift_deltas = self.shift2box_transform.get_deltas(\n shifts_i, gt_boxes.tensor.unsqueeze(1))\n distances = (gt_shift_deltas[..., :2] - gt_shift_deltas[..., 2:]) / 2\n normal_probs.append(\n normal_distribution(distances / stride,\n self.mu[labels].unsqueeze(1),\n self.sigma[labels].unsqueeze(1)))\n normal_probs = torch.cat(normal_probs, dim=1).prod(dim=-1)\n\n composed_cls_prob = pred_class_probs_per_image[:, labels] * pred_obj_probs_per_image\n\n # matched_gt_shift_deltas: P_{ij}^{loc}\n loss_box_reg = iou_loss(pred_shift_deltas_per_image.unsqueeze(0),\n target_shift_deltas,\n box_mode=\"ltrb\",\n loss_type=self.iou_loss_type,\n reduction=\"none\") * self.reg_weight\n pred_reg_probs = (-loss_box_reg).exp()\n\n # positive_losses: { -log( Mean-max(P_{ij}^{cls} * P_{ij}^{loc}) ) }\n positive_losses.append(\n positive_bag_loss(composed_cls_prob.transpose(1, 0) * pred_reg_probs,\n is_in_boxes.float(), normal_probs))\n\n num_foreground += len(gt_instances_per_image)\n num_background += normal_probs[foreground_idxs].sum().item()\n\n gaussian_norm_losses.append(\n len(gt_instances_per_image) / normal_probs[foreground_idxs].sum().clamp_(1e-12))\n\n if dist.is_initialized():\n dist.all_reduce(num_foreground)\n num_foreground /= dist.get_world_size()\n dist.all_reduce(num_background)\n num_background /= dist.get_world_size()\n\n # positive_loss: \\sum_{i}{ -log( Mean-max(P_{ij}^{cls} * P_{ij}^{loc}) ) } / ||B||\n positive_loss = torch.cat(positive_losses).sum() / max(1, num_foreground)\n\n # pred_box_probs: P{a_{j} \\in A_{+}}\n pred_box_probs = torch.stack(pred_box_probs, dim=0)\n # negative_loss: \\sum_{j}{ FL( (1 - P{a_{j} \\in A_{+}}) * (1 - P_{j}^{bg}) ) } / n||B||\n negative_loss = negative_bag_loss(\n pred_class_probs * pred_obj_probs * (1 - pred_box_probs),\n self.focal_loss_gamma).sum() / max(1, num_background)\n\n loss_pos = positive_loss * self.focal_loss_alpha\n loss_neg = negative_loss * (1 - self.focal_loss_alpha)\n loss_norm = torch.stack(gaussian_norm_losses).mean() * (1 - self.focal_loss_alpha)\n\n return {\n \"loss_pos\": loss_pos,\n \"loss_neg\": loss_neg,\n \"loss_norm\": loss_norm,\n }\n\n def inference(self, box_cls, box_delta, box_center, shifts, images):\n \"\"\"\n Arguments:\n box_cls, box_delta, box_center: Same as the output of :meth:`AutoAssignHead.forward`\n shifts (list[list[Tensor]): a list of #images elements. Each is a\n list of #feature level tensor. The tensor contain shifts of this\n image on the specific feature level.\n images (ImageList): the input images\n\n Returns:\n results (List[Instances]): a list of #images elements.\n \"\"\"\n assert len(shifts) == len(images)\n results = []\n\n box_cls = [permute_to_N_HWA_K(x, self.num_classes) for x in box_cls]\n box_delta = [permute_to_N_HWA_K(x, 4) for x in box_delta]\n box_center = [permute_to_N_HWA_K(x, 1) for x in box_center]\n # list[Tensor], one per level, each has shape (N, Hi x Wi, K or 4)\n\n for img_idx, shifts_per_image in enumerate(shifts):\n image_size = images.image_sizes[img_idx]\n box_cls_per_image = [\n box_cls_per_level[img_idx] for box_cls_per_level in box_cls\n ]\n box_reg_per_image = [\n box_reg_per_level[img_idx] for box_reg_per_level in box_delta\n ]\n box_ctr_per_image = [\n box_ctr_per_level[img_idx] for box_ctr_per_level in box_center\n ]\n results_per_image = self.inference_single_image(\n box_cls_per_image, box_reg_per_image, box_ctr_per_image,\n shifts_per_image, tuple(image_size))\n results.append(results_per_image)\n return results\n\n def inference_single_image(self, box_cls, box_delta, box_center, shifts,\n image_size):\n \"\"\"\n Single-image inference. Return bounding-box detection results by thresholding\n on scores and applying non-maximum suppression (NMS).\n\n Arguments:\n box_cls (list[Tensor]): list of #feature levels. Each entry contains\n tensor of size (H x W, K)\n box_delta (list[Tensor]): Same shape as 'box_cls' except that K becomes 4.\n box_center (list[Tensor]): Same shape as 'box_cls' except that K becomes 1.\n shifts (list[Tensor]): list of #feature levels. Each entry contains\n a tensor, which contains all the shifts for that\n image in that feature level.\n image_size (tuple(H, W)): a tuple of the image height and width.\n\n Returns:\n Same as `inference`, but for only one image.\n \"\"\"\n boxes_all = []\n scores_all = []\n class_idxs_all = []\n\n # Iterate over every feature level\n for box_cls_i, box_reg_i, box_ctr_i, shifts_i in zip(\n box_cls, box_delta, box_center, shifts):\n # (HxWxK,)\n box_cls_i = (box_cls_i.sigmoid_() * box_ctr_i.sigmoid_()).flatten()\n\n # Keep top k top scoring indices only.\n num_topk = min(self.topk_candidates, box_reg_i.size(0))\n # torch.sort is actually faster than .topk (at least on GPUs)\n predicted_prob, topk_idxs = box_cls_i.sort(descending=True)\n predicted_prob = predicted_prob[:num_topk]\n topk_idxs = topk_idxs[:num_topk]\n\n # filter out the proposals with low confidence score\n keep_idxs = predicted_prob > self.score_threshold\n predicted_prob = predicted_prob[keep_idxs]\n topk_idxs = topk_idxs[keep_idxs]\n\n shift_idxs = topk_idxs // self.num_classes\n classes_idxs = topk_idxs % self.num_classes\n\n box_reg_i = box_reg_i[shift_idxs]\n shifts_i = shifts_i[shift_idxs]\n # predict boxes\n predicted_boxes = self.shift2box_transform.apply_deltas(\n box_reg_i, shifts_i)\n\n boxes_all.append(predicted_boxes)\n scores_all.append(predicted_prob)\n class_idxs_all.append(classes_idxs)\n\n boxes_all, scores_all, class_idxs_all = [\n cat(x) for x in [boxes_all, scores_all, class_idxs_all]\n ]\n keep = batched_nms(boxes_all, scores_all, class_idxs_all,\n self.nms_threshold)\n keep = keep[:self.max_detections_per_image]\n\n result = Instances(image_size)\n result.pred_boxes = Boxes(boxes_all[keep])\n result.scores = scores_all[keep]\n result.pred_classes = class_idxs_all[keep]\n return result\n\n def preprocess_image(self, batched_inputs):\n \"\"\"\n Normalize, pad and batch the input images.\n \"\"\"\n images = [x[\"image\"].to(self.device) for x in batched_inputs]\n images = [self.normalizer(x) for x in images]\n images = ImageList.from_tensors(images,\n self.backbone.size_divisibility)\n return images\n\n\nclass AutoAssignHead(nn.Module):\n \"\"\"\n The head used in FCOS for object classification and box regression.\n It has two subnets for the two tasks, with a common structure but separate parameters.\n \"\"\"\n def __init__(self, cfg, input_shape: List[ShapeSpec]):\n super(AutoAssignHead, self).__init__()\n # fmt: off\n in_channels = input_shape[0].channels\n num_classes = cfg.MODEL.FCOS.NUM_CLASSES\n num_convs = cfg.MODEL.FCOS.NUM_CONVS\n prior_prob = cfg.MODEL.FCOS.PRIOR_PROB\n self.fpn_strides = cfg.MODEL.FCOS.FPN_STRIDES\n self.norm_reg_targets = cfg.MODEL.FCOS.NORM_REG_TARGETS\n # fmt: on\n cls_subnet = []\n bbox_subnet = []\n for _ in range(num_convs):\n cls_subnet.append(\n nn.Conv2d(in_channels,\n in_channels,\n kernel_size=3,\n stride=1,\n padding=1))\n cls_subnet.append(nn.GroupNorm(32, in_channels))\n cls_subnet.append(nn.ReLU())\n bbox_subnet.append(\n nn.Conv2d(in_channels,\n in_channels,\n kernel_size=3,\n stride=1,\n padding=1))\n bbox_subnet.append(nn.GroupNorm(32, in_channels))\n bbox_subnet.append(nn.ReLU())\n\n self.cls_subnet = nn.Sequential(*cls_subnet)\n self.bbox_subnet = nn.Sequential(*bbox_subnet)\n self.cls_score = nn.Conv2d(in_channels,\n num_classes,\n kernel_size=3,\n stride=1,\n padding=1)\n self.bbox_pred = nn.Conv2d(in_channels,\n 4,\n kernel_size=3,\n stride=1,\n padding=1)\n self.obj_score = nn.Conv2d(in_channels,\n 1,\n kernel_size=3,\n stride=1,\n padding=1)\n\n # Initialization\n for modules in [\n self.cls_subnet, self.bbox_subnet, self.cls_score,\n self.bbox_pred, self.obj_score\n ]:\n for layer in modules.modules():\n if isinstance(layer, nn.Conv2d):\n torch.nn.init.normal_(layer.weight, mean=0, std=0.01)\n torch.nn.init.constant_(layer.bias, 0)\n if isinstance(layer, nn.GroupNorm):\n torch.nn.init.constant_(layer.weight, 1)\n torch.nn.init.constant_(layer.bias, 0)\n\n # Use prior in model initialization to improve stability\n bias_value = -math.log((1 - prior_prob) / prior_prob)\n torch.nn.init.constant_(self.cls_score.bias, bias_value)\n torch.nn.init.constant_(self.bbox_pred.bias, 4.0)\n\n self.scales = nn.ModuleList(\n [Scale(init_value=1.0) for _ in range(len(self.fpn_strides))])\n\n def forward(self, features):\n \"\"\"\n Arguments:\n features (list[Tensor]): FPN feature map tensors in high to low resolution.\n Each tensor in the list correspond to different feature levels.\n\n Returns:\n logits (list[Tensor]): #lvl tensors, each has shape (N, K, Hi, Wi).\n The tensor predicts the classification probability\n at each spatial position for each of the K object classes.\n bbox_reg (list[Tensor]): #lvl tensors, each has shape (N, 4, Hi, Wi).\n The tensor predicts 4-vector (dl,dt,dr,db) box\n regression values for every shift. These values are the\n relative offset between the shift and the ground truth box.\n \"\"\"\n logits = []\n bbox_reg = []\n obj_logits = []\n for feature, stride, scale in zip(features, self.fpn_strides,\n self.scales):\n cls_subnet = self.cls_subnet(feature)\n bbox_subnet = self.bbox_subnet(feature)\n\n logits.append(self.cls_score(cls_subnet))\n obj_logits.append(self.obj_score(bbox_subnet))\n\n bbox_pred = scale(self.bbox_pred(bbox_subnet))\n if self.norm_reg_targets:\n bbox_reg.append(F.relu(bbox_pred) * stride)\n else:\n bbox_reg.append(torch.exp(bbox_pred))\n return logits, bbox_reg, obj_logits\n", "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\nimport colorsys\nimport logging\nimport math\nfrom enum import Enum, unique\n\nimport cv2\nimport matplotlib as mpl\nimport matplotlib.colors as mplc\nimport matplotlib.figure as mplfigure\nimport numpy as np\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg\nimport pycocotools.mask as mask_util\n\nimport torch\n\nfrom cvpods.structures import BitMasks, Boxes, BoxMode, Keypoints, PolygonMasks, RotatedBoxes\n\nfrom .colormap import random_color\n\nlogger = logging.getLogger(__name__)\n\n__all__ = [\"ColorMode\", \"VisImage\", \"Visualizer\"]\n\n\n_SMALL_OBJECT_AREA_THRESH = 1000\n_LARGE_MASK_AREA_THRESH = 120000\n_OFF_WHITE = (1.0, 1.0, 240.0 / 255)\n_BLACK = (0, 0, 0)\n_RED = (1.0, 0, 0)\n\n_KEYPOINT_THRESHOLD = 0.05\n\n\n@unique\nclass ColorMode(Enum):\n \"\"\"\n Enum of different color modes to use for instance visualizations.\n\n Attributes:\n IMAGE: Picks a random color for every instance and overlay segmentations with low opacity.\n SEGMENTATION: Let instances of the same category have similar colors, and overlay them with\n high opacity. This provides more attention on the quality of segmentation.\n IMAGE_BW: same as IMAGE, but convert all areas without masks to gray-scale.\n Only available for drawing per-instance mask predictions.\n \"\"\"\n\n IMAGE = 0\n SEGMENTATION = 1\n IMAGE_BW = 2\n\n\nclass GenericMask:\n \"\"\"\n Attribute:\n polygons (list[ndarray]): list[ndarray]: polygons for this mask.\n Each ndarray has format [x, y, x, y, ...]\n mask (ndarray): a binary mask\n \"\"\"\n\n def __init__(self, mask_or_polygons, height, width):\n self._mask = self._polygons = self._has_holes = None\n self.height = height\n self.width = width\n\n m = mask_or_polygons\n if isinstance(m, dict):\n # RLEs\n assert \"counts\" in m and \"size\" in m\n if isinstance(m[\"counts\"], list): # uncompressed RLEs\n h, w = m[\"size\"]\n assert h == height and w == width\n m = mask_util.frPyObjects(m, h, w)\n self._mask = mask_util.decode(m)[:, :]\n return\n\n if isinstance(m, list): # list[ndarray]\n self._polygons = [np.asarray(x).reshape(-1) for x in m]\n return\n\n if isinstance(m, np.ndarray): # assumed to be a binary mask\n assert m.shape[1] != 2, m.shape\n assert m.shape == (height, width), m.shape\n self._mask = m.astype(\"uint8\")\n return\n\n raise ValueError(\"GenericMask cannot handle object {} of type '{}'\".format(m, type(m)))\n\n @property\n def mask(self):\n if self._mask is None:\n self._mask = self.polygons_to_mask(self._polygons)\n return self._mask\n\n @property\n def polygons(self):\n if self._polygons is None:\n self._polygons, self._has_holes = self.mask_to_polygons(self._mask)\n return self._polygons\n\n @property\n def has_holes(self):\n if self._has_holes is None:\n if self._mask is not None:\n self._polygons, self._has_holes = self.mask_to_polygons(self._mask)\n else:\n self._has_holes = False # if original format is polygon, does not have holes\n return self._has_holes\n\n def mask_to_polygons(self, mask):\n # cv2.RETR_CCOMP flag retrieves all the contours and arranges them to a 2-level\n # hierarchy. External contours (boundary) of the object are placed in hierarchy-1.\n # Internal contours (holes) are placed in hierarchy-2.\n # cv2.CHAIN_APPROX_NONE flag gets vertices of polygons from contours.\n mask = np.ascontiguousarray(mask) # some versions of cv2 does not support incontiguous arr\n res = cv2.findContours(mask.astype(\"uint8\"), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE)\n hierarchy = res[-1]\n if hierarchy is None: # empty mask\n return [], False\n has_holes = (hierarchy.reshape(-1, 4)[:, 3] >= 0).sum() > 0\n res = res[-2]\n res = [x.flatten() for x in res]\n res = [x for x in res if len(x) >= 6]\n return res, has_holes\n\n def polygons_to_mask(self, polygons):\n rle = mask_util.frPyObjects(polygons, self.height, self.width)\n rle = mask_util.merge(rle)\n return mask_util.decode(rle)[:, :]\n\n def area(self):\n return self.mask.sum()\n\n def bbox(self):\n p = mask_util.frPyObjects(self.polygons, self.height, self.width)\n p = mask_util.merge(p)\n bbox = mask_util.toBbox(p)\n bbox[2] += bbox[0]\n bbox[3] += bbox[1]\n return bbox\n\n\nclass _PanopticPrediction:\n def __init__(self, panoptic_seg, segments_info):\n self._seg = panoptic_seg\n\n self._sinfo = {s[\"id\"]: s for s in segments_info} # seg id -> seg info\n segment_ids, areas = torch.unique(panoptic_seg, sorted=True, return_counts=True)\n areas = areas.numpy()\n sorted_idxs = np.argsort(-areas)\n self._seg_ids, self._seg_areas = segment_ids[sorted_idxs], areas[sorted_idxs]\n self._seg_ids = self._seg_ids.tolist()\n for sid, area in zip(self._seg_ids, self._seg_areas):\n if sid in self._sinfo:\n self._sinfo[sid][\"area\"] = float(area)\n\n def non_empty_mask(self):\n \"\"\"\n Returns:\n (H, W) array, a mask for all pixels that have a prediction\n \"\"\"\n empty_ids = []\n for id in self._seg_ids:\n if id not in self._sinfo:\n empty_ids.append(id)\n if len(empty_ids) == 0:\n return np.zeros(self._seg.shape, dtype=np.uint8)\n assert (\n len(empty_ids) == 1\n ), \">1 ids corresponds to no labels. This is currently not supported\"\n return (self._seg != empty_ids[0]).numpy().astype(np.bool)\n\n def semantic_masks(self):\n for sid in self._seg_ids:\n sinfo = self._sinfo.get(sid)\n if sinfo is None or sinfo[\"isthing\"]:\n # Some pixels (e.g. id 0 in PanopticFPN) have no instance or semantic predictions.\n continue\n yield (self._seg == sid).numpy().astype(np.bool), sinfo\n\n def instance_masks(self):\n for sid in self._seg_ids:\n sinfo = self._sinfo.get(sid)\n if sinfo is None or not sinfo[\"isthing\"]:\n continue\n mask = (self._seg == sid).numpy().astype(np.bool)\n if mask.sum() > 0:\n yield mask, sinfo\n\n\ndef _create_text_labels(classes, scores, class_names):\n \"\"\"\n Args:\n classes (list[int] or None):\n scores (list[float] or None):\n class_names (list[str] or None):\n\n Returns:\n list[str] or None\n \"\"\"\n labels = None\n if classes is not None and class_names is not None and len(class_names) > 1:\n labels = [class_names[int(i)] for i in classes]\n if scores is not None:\n if labels is None:\n labels = [\"{:.0f}%\".format(s * 100) for s in scores]\n else:\n labels = [\"{} {:.0f}%\".format(label, s * 100) for label, s in zip(labels, scores)]\n return labels\n\n\nclass VisImage:\n def __init__(self, img, scale=1.0):\n \"\"\"\n Args:\n img (ndarray): an RGB image of shape (H, W, 3).\n scale (float): scale the input image\n \"\"\"\n self.img = img\n self.scale = scale\n self.width, self.height = img.shape[1], img.shape[0]\n self._setup_figure()\n\n def _setup_figure(self):\n \"\"\"\n Args:\n Same as in :meth:`__init__()`.\n\n Returns:\n fig (matplotlib.pyplot.figure): top level container for all the image plot elements.\n ax (matplotlib.pyplot.Axes): contains figure elements and sets the coordinate system.\n \"\"\"\n fig = mplfigure.Figure(frameon=False)\n self.dpi = fig.get_dpi()\n # add a small 1e-2 to avoid precision lost due to matplotlib's truncation\n # (https://github.com/matplotlib/matplotlib/issues/15363)\n fig.set_size_inches(\n (self.width * self.scale + 1e-2) / self.dpi,\n (self.height * self.scale + 1e-2) / self.dpi,\n )\n self.canvas = FigureCanvasAgg(fig)\n # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig)\n ax = fig.add_axes([0.0, 0.0, 1.0, 1.0])\n ax.axis(\"off\")\n ax.set_xlim(0.0, self.width)\n ax.set_ylim(self.height)\n\n self.fig = fig\n self.ax = ax\n\n def save(self, filepath):\n \"\"\"\n Args:\n filepath (str): a string that contains the absolute path, including the file name, where\n the visualized image will be saved.\n \"\"\"\n if filepath.lower().endswith(\".jpg\") or filepath.lower().endswith(\".png\"):\n # faster than matplotlib's imshow\n cv2.imwrite(filepath, self.get_image()[:, :, ::-1])\n else:\n # support general formats (e.g. pdf)\n self.ax.imshow(self.img, interpolation=\"nearest\")\n self.fig.savefig(filepath)\n\n def get_image(self):\n \"\"\"\n Returns:\n ndarray: the visualized image of shape (H, W, 3) (RGB) in uint8 type.\n The shape is scaled w.r.t the input image using the given `scale` argument.\n \"\"\"\n canvas = self.canvas\n s, (width, height) = canvas.print_to_buffer()\n if (self.width, self.height) != (width, height):\n img = cv2.resize(self.img, (width, height))\n else:\n img = self.img\n\n # buf = io.BytesIO() # works for cairo backend\n # canvas.print_rgba(buf)\n # width, height = self.width, self.height\n # s = buf.getvalue()\n\n buffer = np.frombuffer(s, dtype=\"uint8\")\n\n # imshow is slow. blend manually (still quite slow)\n img_rgba = buffer.reshape(height, width, 4)\n rgb, alpha = np.split(img_rgba, [3], axis=2)\n\n try:\n import numexpr as ne # fuse them with numexpr\n\n visualized_image = ne.evaluate(\"img * (1 - alpha / 255.0) + rgb * (alpha / 255.0)\")\n except ImportError:\n alpha = alpha.astype(\"float32\") / 255.0\n visualized_image = img * (1 - alpha) + rgb * alpha\n\n visualized_image = visualized_image.astype(\"uint8\")\n\n return visualized_image\n\n\nclass Visualizer:\n def __init__(self, img_rgb, metadata, scale=1.0, instance_mode=ColorMode.IMAGE):\n \"\"\"\n Args:\n img_rgb: a numpy array of shape (H, W, C), where H and W correspond to\n the height and width of the image respectively. C is the number of\n color channels. The image is required to be in RGB format since that\n is a requirement of the Matplotlib library. The image is also expected\n to be in the range [0, 255].\n metadata (MetadataCatalog): image metadata.\n \"\"\"\n self.img = np.asarray(img_rgb).clip(0, 255).astype(np.uint8)\n self.metadata = metadata\n self.output = VisImage(self.img, scale=scale)\n self.cpu_device = torch.device(\"cpu\")\n\n # too small texts are useless, therefore clamp to 9\n self._default_font_size = max(\n np.sqrt(self.output.height * self.output.width) // 90, 10 // scale\n )\n self._instance_mode = instance_mode\n\n def draw_instance_predictions(self, predictions):\n \"\"\"\n Draw instance-level prediction results on an image.\n\n Args:\n predictions (Instances): the output of an instance detection/segmentation\n model. Following fields will be used to draw:\n \"pred_boxes\", \"pred_classes\", \"scores\", \"pred_masks\" (or \"pred_masks_rle\").\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n boxes = predictions.pred_boxes if predictions.has(\"pred_boxes\") else None\n scores = predictions.scores if predictions.has(\"scores\") else None\n classes = predictions.pred_classes if predictions.has(\"pred_classes\") else None\n labels = _create_text_labels(classes, scores, self.metadata.thing_classes)\n keypoints = predictions.pred_keypoints if predictions.has(\"pred_keypoints\") else None\n\n if predictions.has(\"pred_masks\"):\n masks = np.asarray(predictions.pred_masks)\n masks = [GenericMask(x, self.output.height, self.output.width) for x in masks]\n else:\n masks = None\n\n if self._instance_mode == ColorMode.SEGMENTATION and self.metadata.thing_colors:\n colors = [\n self._jitter([x / 255 for x in self.metadata.thing_colors[c]]) for c in classes\n ]\n alpha = 0.8\n else:\n colors = None\n alpha = 0.5\n\n if self._instance_mode == ColorMode.IMAGE_BW:\n assert predictions.has(\"pred_masks\"), \"ColorMode.IMAGE_BW requires segmentations\"\n self.output.img = self._create_grayscale_image(\n (predictions.pred_masks.any(dim=0) > 0).numpy()\n )\n alpha = 0.3\n\n self.overlay_instances(\n masks=masks,\n boxes=boxes,\n labels=labels,\n keypoints=keypoints,\n assigned_colors=colors,\n alpha=alpha,\n )\n return self.output\n\n def draw_sem_seg(self, sem_seg, area_threshold=None, alpha=0.8):\n \"\"\"\n Draw semantic segmentation predictions/labels.\n\n Args:\n sem_seg (Tensor or ndarray): the segmentation of shape (H, W).\n area_threshold (int): segments with less than `area_threshold` are not drawn.\n alpha (float): the larger it is, the more opaque the segmentations are.\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n if isinstance(sem_seg, torch.Tensor):\n sem_seg = sem_seg.numpy()\n labels, areas = np.unique(sem_seg, return_counts=True)\n sorted_idxs = np.argsort(-areas).tolist()\n labels = labels[sorted_idxs]\n for label in filter(lambda l: l < len(self.metadata.stuff_classes), labels):\n try:\n mask_color = [x / 255 for x in self.metadata.stuff_colors[label]]\n except (AttributeError, IndexError):\n mask_color = None\n\n binary_mask = (sem_seg == label).astype(np.uint8)\n text = self.metadata.stuff_classes[label]\n self.draw_binary_mask(\n binary_mask,\n color=mask_color,\n edge_color=_OFF_WHITE,\n text=text,\n alpha=alpha,\n area_threshold=area_threshold,\n )\n return self.output\n\n def draw_panoptic_seg_predictions(\n self, panoptic_seg, segments_info, area_threshold=None, alpha=0.7\n ):\n \"\"\"\n Draw panoptic prediction results on an image.\n\n Args:\n panoptic_seg (Tensor): of shape (height, width) where the values are ids for each\n segment.\n segments_info (list[dict]): Describe each segment in `panoptic_seg`.\n Each dict contains keys \"id\", \"category_id\", \"isthing\".\n area_threshold (int): stuff segments with less than `area_threshold` are not drawn.\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n pred = _PanopticPrediction(panoptic_seg, segments_info)\n\n if self._instance_mode == ColorMode.IMAGE_BW:\n self.output.img = self._create_grayscale_image(pred.non_empty_mask())\n\n # draw mask for all semantic segments first i.e. \"stuff\"\n for mask, sinfo in pred.semantic_masks():\n category_idx = sinfo[\"category_id\"]\n try:\n mask_color = [x / 255 for x in self.metadata.stuff_colors[category_idx]]\n except AttributeError:\n mask_color = None\n\n text = self.metadata.stuff_classes[category_idx]\n self.draw_binary_mask(\n mask,\n color=mask_color,\n edge_color=_OFF_WHITE,\n text=text,\n alpha=alpha,\n area_threshold=area_threshold,\n )\n\n # draw mask for all instances second\n all_instances = list(pred.instance_masks())\n if len(all_instances) == 0:\n return self.output\n masks, sinfo = list(zip(*all_instances))\n category_ids = [x[\"category_id\"] for x in sinfo]\n\n try:\n scores = [x[\"score\"] for x in sinfo]\n except KeyError:\n scores = None\n labels = _create_text_labels(category_ids, scores, self.metadata.thing_classes)\n\n try:\n colors = [random_color(rgb=True, maximum=1) for k in category_ids]\n except AttributeError:\n colors = None\n self.overlay_instances(masks=masks, labels=labels, assigned_colors=colors, alpha=alpha)\n\n return self.output\n\n def draw_dataset_dict(self, dic):\n \"\"\"\n Draw annotations/segmentaions in cvpods Dataset format.\n\n Args:\n dic (dict): annotation/segmentation data of one image, in cvpods Dataset format.\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n annos = dic.get(\"annotations\", None)\n if annos:\n if \"segmentation\" in annos[0]:\n masks = [x[\"segmentation\"] for x in annos]\n else:\n masks = None\n if \"keypoints\" in annos[0]:\n keypts = [x[\"keypoints\"] for x in annos]\n keypts = np.array(keypts).reshape(len(annos), -1, 3)\n else:\n keypts = None\n\n boxes = [BoxMode.convert(x[\"bbox\"], x[\"bbox_mode\"], BoxMode.XYXY_ABS) for x in annos]\n\n labels = [x[\"category_id\"] for x in annos]\n names = self.metadata.thing_classes\n if names:\n labels = [names[i] for i in labels]\n labels = [\n \"{}\".format(i) + (\"|crowd\" if a.get(\"iscrowd\", 0) else \"\")\n for i, a in zip(labels, annos)\n ]\n self.overlay_instances(labels=labels, boxes=boxes, masks=masks, keypoints=keypts)\n\n sem_seg = dic.get(\"sem_seg\", None)\n if sem_seg is None and \"sem_seg_file_name\" in dic:\n sem_seg = cv2.imread(dic[\"sem_seg_file_name\"], cv2.IMREAD_GRAYSCALE)\n if sem_seg is not None:\n self.draw_sem_seg(sem_seg, area_threshold=0, alpha=0.5)\n return self.output\n\n def overlay_instances( # noqa:C901\n self,\n *,\n boxes=None,\n labels=None,\n masks=None,\n keypoints=None,\n assigned_colors=None,\n alpha=0.5\n ):\n \"\"\"\n Args:\n boxes (Boxes, RotatedBoxes or ndarray): either a :class:`Boxes`,\n or an Nx4 numpy array of XYXY_ABS format for the N objects in a single image,\n or a :class:`RotatedBoxes`,\n or an Nx5 numpy array of (x_center, y_center, width, height, angle_degrees) format\n for the N objects in a single image,\n labels (list[str]): the text to be displayed for each instance.\n masks (masks-like object): Supported types are:\n\n * `structures.masks.PolygonMasks`, `structures.masks.BitMasks`.\n * list[list[ndarray]]: contains the segmentation masks for all objects in one image.\n The first level of the list corresponds to individual instances. The second\n level to all the polygon that compose the instance, and the third level\n to the polygon coordinates. The third level should have the format of\n [x0, y0, x1, y1, ..., xn, yn] (n >= 3).\n * list[ndarray]: each ndarray is a binary mask of shape (H, W).\n * list[dict]: each dict is a COCO-style RLE.\n keypoints (Keypoint or array like): an array-like object of shape (N, K, 3),\n where the N is the number of instances and K is the number of keypoints.\n The last dimension corresponds to (x, y, visibility or score).\n assigned_colors (list[matplotlib.colors]): a list of colors, where each color\n corresponds to each mask or box in the image. Refer to 'matplotlib.colors'\n for full list of formats that the colors are accepted in.\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n num_instances = None\n if boxes is not None:\n boxes = self._convert_boxes(boxes)\n num_instances = len(boxes)\n if masks is not None:\n masks = self._convert_masks(masks)\n if num_instances:\n assert len(masks) == num_instances\n else:\n num_instances = len(masks)\n if keypoints is not None:\n if num_instances:\n assert len(keypoints) == num_instances\n else:\n num_instances = len(keypoints)\n keypoints = self._convert_keypoints(keypoints)\n if labels is not None:\n assert len(labels) == num_instances\n if assigned_colors is None:\n assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)]\n if num_instances == 0:\n return self.output\n if boxes is not None and boxes.shape[1] == 5:\n return self.overlay_rotated_instances(\n boxes=boxes, labels=labels, assigned_colors=assigned_colors\n )\n\n # Display in largest to smallest order to reduce occlusion.\n areas = None\n if boxes is not None:\n areas = np.prod(boxes[:, 2:] - boxes[:, :2], axis=1)\n elif masks is not None:\n areas = np.asarray([x.area() for x in masks])\n\n if areas is not None:\n sorted_idxs = np.argsort(-areas).tolist()\n # Re-order overlapped instances in descending order.\n boxes = boxes[sorted_idxs] if boxes is not None else None\n labels = [labels[k] for k in sorted_idxs] if labels is not None else None\n masks = [masks[idx] for idx in sorted_idxs] if masks is not None else None\n assigned_colors = [assigned_colors[idx] for idx in sorted_idxs]\n keypoints = keypoints[sorted_idxs] if keypoints is not None else None\n\n for i in range(num_instances):\n color = assigned_colors[i]\n if boxes is not None:\n self.draw_box(boxes[i], edge_color=color)\n\n if masks is not None:\n for segment in masks[i].polygons:\n self.draw_polygon(segment.reshape(-1, 2), color, alpha=alpha)\n\n if labels is not None:\n # first get a box\n if boxes is not None:\n x0, y0, x1, y1 = boxes[i]\n text_pos = (x0, y0) # if drawing boxes, put text on the box corner.\n horiz_align = \"left\"\n elif masks is not None:\n x0, y0, x1, y1 = masks[i].bbox()\n\n # draw text in the center (defined by median) when box is not drawn\n # median is less sensitive to outliers.\n text_pos = np.median(masks[i].mask.nonzero(), axis=1)[::-1]\n horiz_align = \"center\"\n else:\n continue # drawing the box confidence for keypoints isn't very useful.\n # for small objects, draw text at the side to avoid occlusion\n instance_area = (y1 - y0) * (x1 - x0)\n if (\n instance_area < _SMALL_OBJECT_AREA_THRESH * self.output.scale\n or y1 - y0 < 40 * self.output.scale\n ):\n if y1 >= self.output.height - 5:\n text_pos = (x1, y0)\n else:\n text_pos = (x0, y1)\n\n height_ratio = (y1 - y0) / np.sqrt(self.output.height * self.output.width)\n lighter_color = self._change_color_brightness(color, brightness_factor=0.7)\n font_size = (\n np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2)\n * 0.5\n * self._default_font_size\n )\n self.draw_text(\n labels[i],\n text_pos,\n color=lighter_color,\n horizontal_alignment=horiz_align,\n font_size=font_size,\n )\n\n # draw keypoints\n if keypoints is not None:\n for keypoints_per_instance in keypoints:\n self.draw_and_connect_keypoints(keypoints_per_instance)\n\n return self.output\n\n def overlay_rotated_instances(self, boxes=None, labels=None, assigned_colors=None):\n \"\"\"\n Args:\n boxes (ndarray): an Nx5 numpy array of\n (x_center, y_center, width, height, angle_degrees) format\n for the N objects in a single image.\n labels (list[str]): the text to be displayed for each instance.\n assigned_colors (list[matplotlib.colors]): a list of colors, where each color\n corresponds to each mask or box in the image. Refer to 'matplotlib.colors'\n for full list of formats that the colors are accepted in.\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n\n num_instances = len(boxes)\n\n if assigned_colors is None:\n assigned_colors = [random_color(rgb=True, maximum=1) for _ in range(num_instances)]\n if num_instances == 0:\n return self.output\n\n # Display in largest to smallest order to reduce occlusion.\n if boxes is not None:\n areas = boxes[:, 2] * boxes[:, 3]\n\n sorted_idxs = np.argsort(-areas).tolist()\n # Re-order overlapped instances in descending order.\n boxes = boxes[sorted_idxs]\n labels = [labels[k] for k in sorted_idxs] if labels is not None else None\n colors = [assigned_colors[idx] for idx in sorted_idxs]\n\n for i in range(num_instances):\n self.draw_rotated_box_with_label(\n boxes[i], edge_color=colors[i], label=labels[i] if labels is not None else None\n )\n\n return self.output\n\n def draw_and_connect_keypoints(self, keypoints):\n \"\"\"\n Draws keypoints of an instance and follows the rules for keypoint connections\n to draw lines between appropriate keypoints. This follows color heuristics for\n line color.\n\n Args:\n keypoints (Tensor): a tensor of shape (K, 3), where K is the number of keypoints\n and the last dimension corresponds to (x, y, probability).\n\n Returns:\n output (VisImage): image object with visualizations.\n \"\"\"\n visible = {}\n keypoint_names = self.metadata.keypoint_names\n for idx, keypoint in enumerate(keypoints):\n # draw keypoint\n x, y, prob = keypoint\n if prob > _KEYPOINT_THRESHOLD:\n self.draw_circle((x, y), color=_RED)\n if keypoint_names:\n keypoint_name = keypoint_names[idx]\n visible[keypoint_name] = (x, y)\n\n if self.metadata.keypoint_connection_rules:\n for kp0, kp1, color in self.metadata.keypoint_connection_rules:\n if kp0 in visible and kp1 in visible:\n x0, y0 = visible[kp0]\n x1, y1 = visible[kp1]\n color = tuple(x / 255.0 for x in color)\n self.draw_line([x0, x1], [y0, y1], color=color)\n\n # draw lines from nose to mid-shoulder and mid-shoulder to mid-hip\n # Note that this strategy is specific to person keypoints.\n # For other keypoints, it should just do nothing\n try:\n ls_x, ls_y = visible[\"left_shoulder\"]\n rs_x, rs_y = visible[\"right_shoulder\"]\n mid_shoulder_x, mid_shoulder_y = (ls_x + rs_x) / 2, (ls_y + rs_y) / 2\n except KeyError:\n pass\n else:\n # draw line from nose to mid-shoulder\n nose_x, nose_y = visible.get(\"nose\", (None, None))\n if nose_x is not None:\n self.draw_line([nose_x, mid_shoulder_x], [nose_y, mid_shoulder_y], color=_RED)\n\n try:\n # draw line from mid-shoulder to mid-hip\n lh_x, lh_y = visible[\"left_hip\"]\n rh_x, rh_y = visible[\"right_hip\"]\n except KeyError:\n pass\n else:\n mid_hip_x, mid_hip_y = (lh_x + rh_x) / 2, (lh_y + rh_y) / 2\n self.draw_line([mid_hip_x, mid_shoulder_x], [mid_hip_y, mid_shoulder_y], color=_RED)\n return self.output\n\n \"\"\"\n Primitive drawing functions:\n \"\"\"\n\n def draw_text(\n self,\n text,\n position,\n *,\n font_size=None,\n color=\"g\",\n horizontal_alignment=\"center\",\n rotation=0\n ):\n \"\"\"\n Args:\n text (str): class label\n position (tuple): a tuple of the x and y coordinates to place text on image.\n font_size (int, optional): font of the text. If not provided, a font size\n proportional to the image width is calculated and used.\n color: color of the text. Refer to `matplotlib.colors` for full list\n of formats that are accepted.\n horizontal_alignment (str): see `matplotlib.text.Text`\n rotation: rotation angle in degrees CCW\n\n Returns:\n output (VisImage): image object with text drawn.\n \"\"\"\n if not font_size:\n font_size = self._default_font_size\n\n # since the text background is dark, we don't want the text to be dark\n color = np.maximum(list(mplc.to_rgb(color)), 0.2)\n color[np.argmax(color)] = max(0.8, np.max(color))\n\n x, y = position\n self.output.ax.text(\n x,\n y,\n text,\n size=font_size * self.output.scale,\n family=\"sans-serif\",\n bbox={\"facecolor\": \"black\", \"alpha\": 0.8, \"pad\": 0.7, \"edgecolor\": \"none\"},\n verticalalignment=\"top\",\n horizontalalignment=horizontal_alignment,\n color=color,\n zorder=10,\n rotation=rotation,\n )\n return self.output\n\n def draw_box(self, box_coord, alpha=0.5, edge_color=\"g\", line_style=\"-\"):\n \"\"\"\n Args:\n box_coord (tuple): a tuple containing x0, y0, x1, y1 coordinates, where x0 and y0\n are the coordinates of the image's top left corner. x1 and y1 are the\n coordinates of the image's bottom right corner.\n alpha (float): blending efficient. Smaller values lead to more transparent masks.\n edge_color: color of the outline of the box. Refer to `matplotlib.colors`\n for full list of formats that are accepted.\n line_style (string): the string to use to create the outline of the boxes.\n\n Returns:\n output (VisImage): image object with box drawn.\n \"\"\"\n x0, y0, x1, y1 = box_coord\n width = x1 - x0\n height = y1 - y0\n\n linewidth = max(self._default_font_size / 4, 1)\n\n self.output.ax.add_patch(\n mpl.patches.Rectangle(\n (x0, y0),\n width,\n height,\n fill=False,\n edgecolor=edge_color,\n linewidth=linewidth * self.output.scale,\n alpha=alpha,\n linestyle=line_style,\n )\n )\n return self.output\n\n def draw_rotated_box_with_label(\n self, rotated_box, alpha=0.5, edge_color=\"g\", line_style=\"-\", label=None\n ):\n \"\"\"\n Args:\n rotated_box (tuple): a tuple containing (cnt_x, cnt_y, w, h, angle),\n where cnt_x and cnt_y are the center coordinates of the box.\n w and h are the width and height of the box. angle represents how\n many degrees the box is rotated CCW with regard to the 0-degree box.\n alpha (float): blending efficient. Smaller values lead to more transparent boxes.\n edge_color: color of the outline of the box. Refer to `matplotlib.colors`\n for full list of formats that are accepted.\n line_style (string): the string to use to create the outline of the boxes.\n label (string): label for rotated box. It will not be rendered when set to None.\n\n Returns:\n output (VisImage): image object with box drawn.\n \"\"\"\n cnt_x, cnt_y, w, h, angle = rotated_box\n area = w * h\n # use thinner lines when the box is small\n linewidth = self._default_font_size / (\n 6 if area < _SMALL_OBJECT_AREA_THRESH * self.output.scale else 3\n )\n\n theta = angle * math.pi / 180.0\n c = math.cos(theta)\n s = math.sin(theta)\n rect = [(-w / 2, h / 2), (-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2)]\n # x: left->right ; y: top->down\n rotated_rect = [(s * yy + c * xx + cnt_x, c * yy - s * xx + cnt_y) for (xx, yy) in rect]\n for k in range(4):\n j = (k + 1) % 4\n self.draw_line(\n [rotated_rect[k][0], rotated_rect[j][0]],\n [rotated_rect[k][1], rotated_rect[j][1]],\n color=edge_color,\n linestyle=\"--\" if k == 1 else line_style,\n linewidth=linewidth,\n alpha=alpha\n )\n\n if label is not None:\n text_pos = rotated_rect[1] # topleft corner\n\n height_ratio = h / np.sqrt(self.output.height * self.output.width)\n label_color = self._change_color_brightness(edge_color, brightness_factor=0.7)\n font_size = (\n np.clip((height_ratio - 0.02) / 0.08 + 1, 1.2, 2) * 0.5 * self._default_font_size\n )\n self.draw_text(label, text_pos, color=label_color, font_size=font_size, rotation=angle)\n\n return self.output\n\n def draw_circle(self, circle_coord, color, radius=3):\n \"\"\"\n Args:\n circle_coord (list(int) or tuple(int)): contains the x and y coordinates\n of the center of the circle.\n color: color of the polygon. Refer to `matplotlib.colors` for a full list of\n formats that are accepted.\n radius (int): radius of the circle.\n\n Returns:\n output (VisImage): image object with box drawn.\n \"\"\"\n x, y = circle_coord\n self.output.ax.add_patch(\n mpl.patches.Circle(circle_coord, radius=radius, fill=True, color=color)\n )\n return self.output\n\n def draw_line(self, x_data, y_data, color, linestyle=\"-\", linewidth=None, alpha=1.0):\n \"\"\"\n Args:\n x_data (list[int]): a list containing x values of all the points being drawn.\n Length of list should match the length of y_data.\n y_data (list[int]): a list containing y values of all the points being drawn.\n Length of list should match the length of x_data.\n color: color of the line. Refer to `matplotlib.colors` for a full list of\n formats that are accepted.\n linestyle: style of the line. Refer to `matplotlib.lines.Line2D`\n for a full list of formats that are accepted.\n linewidth (float or None): width of the line. When it's None,\n a default value will be computed and used.\n alpha (float): blending efficient. Smaller values lead to more transparent lines.\n\n Returns:\n output (VisImage): image object with line drawn.\n \"\"\"\n if linewidth is None:\n linewidth = self._default_font_size / 3\n linewidth = max(linewidth, 1)\n self.output.ax.add_line(\n mpl.lines.Line2D(\n x_data,\n y_data,\n linewidth=linewidth * self.output.scale,\n color=color,\n linestyle=linestyle,\n alpha=alpha\n )\n )\n return self.output\n\n def draw_binary_mask(\n self, binary_mask, color=None, *, edge_color=None, text=None, alpha=0.5, area_threshold=4096\n ):\n \"\"\"\n Args:\n binary_mask (ndarray): numpy array of shape (H, W), where H is the image height and\n W is the image width. Each value in the array is either a 0 or 1 value of uint8\n type.\n color: color of the mask. Refer to `matplotlib.colors` for a full list of\n formats that are accepted. If None, will pick a random color.\n edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a\n full list of formats that are accepted.\n text (str): if None, will be drawn in the object's center of mass.\n alpha (float): blending efficient. Smaller values lead to more transparent masks.\n area_threshold (float): a connected component small than this will not be shown.\n\n Returns:\n output (VisImage): image object with mask drawn.\n \"\"\"\n if color is None:\n color = random_color(rgb=True, maximum=1)\n if area_threshold is None:\n area_threshold = 4096\n\n has_valid_segment = False\n binary_mask = binary_mask.astype(\"uint8\") # opencv needs uint8\n mask = GenericMask(binary_mask, self.output.height, self.output.width)\n shape2d = (binary_mask.shape[0], binary_mask.shape[1])\n\n if not mask.has_holes:\n # draw polygons for regular masks\n for segment in mask.polygons:\n area = mask_util.area(mask_util.frPyObjects([segment], shape2d[0], shape2d[1]))\n if area < area_threshold:\n continue\n has_valid_segment = True\n segment = segment.reshape(-1, 2)\n self.draw_polygon(segment, color=color, edge_color=edge_color, alpha=alpha)\n else:\n rgba = np.zeros(shape2d + (4,), dtype=\"float32\")\n rgba[:, :, :3] = color\n rgba[:, :, 3] = (mask.mask == 1).astype(\"float32\") * alpha\n has_valid_segment = True\n self.output.ax.imshow(rgba)\n\n if text is not None and has_valid_segment:\n # TODO sometimes drawn on wrong objects. the heuristics here can improve.\n lighter_color = self._change_color_brightness(color, brightness_factor=0.7)\n _num_cc, cc_labels, stats, centroids = cv2.connectedComponentsWithStats(binary_mask, 8)\n largest_component_id = np.argmax(stats[1:, -1]) + 1\n\n # draw text on the largest component, as well as other very large components.\n for cid in range(1, _num_cc):\n if cid == largest_component_id or stats[cid, -1] > _LARGE_MASK_AREA_THRESH:\n # median is more stable than centroid\n # center = centroids[largest_component_id]\n center = np.median((cc_labels == cid).nonzero(as_tuple=False), axis=1)[::-1]\n self.draw_text(text, center, color=lighter_color)\n return self.output\n\n def draw_polygon(self, segment, color, edge_color=None, alpha=0.5):\n \"\"\"\n Args:\n segment: numpy array of shape Nx2, containing all the points in the polygon.\n color: color of the polygon. Refer to `matplotlib.colors` for a full list of\n formats that are accepted.\n edge_color: color of the polygon edges. Refer to `matplotlib.colors` for a\n full list of formats that are accepted. If not provided, a darker shade\n of the polygon color will be used instead.\n alpha (float): blending efficient. Smaller values lead to more transparent masks.\n\n Returns:\n output (VisImage): image object with polygon drawn.\n \"\"\"\n if edge_color is None:\n # make edge color darker than the polygon color\n if alpha > 0.8:\n edge_color = self._change_color_brightness(color, brightness_factor=-0.7)\n else:\n edge_color = color\n edge_color = mplc.to_rgb(edge_color) + (1,)\n\n polygon = mpl.patches.Polygon(\n segment,\n fill=True,\n facecolor=mplc.to_rgb(color) + (alpha,),\n edgecolor=edge_color,\n linewidth=max(self._default_font_size // 15 * self.output.scale, 1),\n )\n self.output.ax.add_patch(polygon)\n return self.output\n\n \"\"\"\n Internal methods:\n \"\"\"\n\n def _jitter(self, color):\n \"\"\"\n Randomly modifies given color to produce a slightly different color than the color given.\n\n Args:\n color (tuple[double]): a tuple of 3 elements, containing the RGB values of the color\n picked. The values in the list are in the [0.0, 1.0] range.\n\n Returns:\n jittered_color (tuple[double]): a tuple of 3 elements, containing the RGB values of the\n color after being jittered. The values in the list are in the [0.0, 1.0] range.\n \"\"\"\n color = mplc.to_rgb(color)\n vec = np.random.rand(3)\n # better to do it in another color space\n vec = vec / np.linalg.norm(vec) * 0.5\n res = np.clip(vec + color, 0, 1)\n return tuple(res)\n\n def _create_grayscale_image(self, mask=None):\n \"\"\"\n Create a grayscale version of the original image.\n The colors in masked area, if given, will be kept.\n \"\"\"\n img_bw = self.img.astype(\"f4\").mean(axis=2)\n img_bw = np.stack([img_bw] * 3, axis=2)\n if mask is not None:\n img_bw[mask] = self.img[mask]\n return img_bw\n\n def _change_color_brightness(self, color, brightness_factor):\n \"\"\"\n Depending on the brightness_factor, gives a lighter or darker color i.e. a color with\n less or more saturation than the original color.\n\n Args:\n color: color of the polygon. Refer to `matplotlib.colors` for a full list of\n formats that are accepted.\n brightness_factor (float): a value in [-1.0, 1.0] range. A lightness factor of\n 0 will correspond to no change, a factor in [-1.0, 0) range will result in\n a darker color and a factor in (0, 1.0] range will result in a lighter color.\n\n Returns:\n modified_color (tuple[double]): a tuple containing the RGB values of the\n modified color. Each value in the tuple is in the [0.0, 1.0] range.\n \"\"\"\n assert brightness_factor >= -1.0 and brightness_factor <= 1.0\n color = mplc.to_rgb(color)\n polygon_color = colorsys.rgb_to_hls(*mplc.to_rgb(color))\n modified_lightness = polygon_color[1] + (brightness_factor * polygon_color[1])\n modified_lightness = 0.0 if modified_lightness < 0.0 else modified_lightness\n modified_lightness = 1.0 if modified_lightness > 1.0 else modified_lightness\n modified_color = colorsys.hls_to_rgb(polygon_color[0], modified_lightness, polygon_color[2])\n return modified_color\n\n def _convert_boxes(self, boxes):\n \"\"\"\n Convert different format of boxes to an NxB array, where B = 4 or 5 is the box dimension.\n \"\"\"\n if isinstance(boxes, Boxes) or isinstance(boxes, RotatedBoxes):\n return boxes.tensor.numpy()\n else:\n return np.asarray(boxes)\n\n def _convert_masks(self, masks_or_polygons):\n \"\"\"\n Convert different format of masks or polygons to a tuple of masks and polygons.\n\n Returns:\n list[GenericMask]:\n \"\"\"\n\n m = masks_or_polygons\n if isinstance(m, PolygonMasks):\n m = m.polygons\n if isinstance(m, BitMasks):\n m = m.tensor.numpy()\n if isinstance(m, torch.Tensor):\n m = m.numpy()\n ret = []\n for x in m:\n if isinstance(x, GenericMask):\n ret.append(x)\n else:\n ret.append(GenericMask(x, self.output.height, self.output.width))\n return ret\n\n def _convert_keypoints(self, keypoints):\n if isinstance(keypoints, Keypoints):\n keypoints = keypoints.tensor\n keypoints = np.asarray(keypoints)\n return keypoints\n\n def get_output(self):\n \"\"\"\n Returns:\n output (VisImage): the image output containing the visualizations added\n to the image.\n \"\"\"\n return self.output\n" ]
[ [ "torch.no_grad", "torch.cuda.set_device" ], [ "torch.nn.functional.softmax", "torch.nn.modules.utils._pair", "torch.nn.functional.adaptive_avg_pool2d", "torch.nn.functional.sigmoid", "torch.split", "torch.nn.ReLU" ], [ "numpy.asarray", "numpy.ascontiguousarray", "numpy.transpose" ], [ "torch.zeros", "torch.cat", "torch.no_grad", "torch.device", "torch.ones", "torch.nn.functional.relu", "torch.nonzero", "torch.nn.GroupNorm", "torch.ones_like", "torch.nn.Sequential", "torch.nn.init.constant_", "torch.nn.Conv2d", "torch.distributed.is_initialized", "torch.zeros_like", "torch.exp", "torch.nn.init.normal_", "torch.stack", "torch.distributed.get_world_size", "torch.Tensor", "torch.nn.ReLU", "torch.distributed.all_reduce" ], [ "numpy.split", "numpy.sqrt", "numpy.asarray", "numpy.max", "torch.unique", "torch.device", "matplotlib.colors.to_rgb", "numpy.unique", "matplotlib.backends.backend_agg.FigureCanvasAgg", "numpy.clip", "numpy.stack", "numpy.frombuffer", "numpy.argmax", "numpy.zeros", "numpy.ascontiguousarray", "matplotlib.patches.Rectangle", "matplotlib.patches.Circle", "numpy.random.rand", "numpy.argsort", "numpy.array", "matplotlib.figure.Figure", "matplotlib.lines.Line2D", "numpy.linalg.norm", "numpy.prod" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Tapot/evidently
[ "ab9b91425d622566b663565508dd1c43e741f515", "ab9b91425d622566b663565508dd1c43e741f515", "ab9b91425d622566b663565508dd1c43e741f515", "ab9b91425d622566b663565508dd1c43e741f515" ]
[ "tests/dashboard/widgets/test_reg_error_normality_widget.py", "src/evidently/dashboard/widgets/num_output_values_widget.py", "tests/dashboard/widgets/test_percent_widget.py", "tests/dashboard/widgets/test_reg_pred_vs_actual_widget.py" ]
[ "from typing import Optional\n\nimport pandas as pd\n\nimport pytest\n\nfrom evidently.analyzers.regression_performance_analyzer import RegressionPerformanceAnalyzer\nfrom evidently.model.widget import BaseWidgetInfo\nfrom evidently.options import OptionsProvider\nfrom evidently.pipeline.column_mapping import ColumnMapping\nfrom evidently.dashboard.widgets.reg_error_normality_widget import RegErrorNormalityWidget\n\n\[email protected]\ndef widget() -> RegErrorNormalityWidget:\n options_provider = OptionsProvider()\n\n widget = RegErrorNormalityWidget(\"test_widget\")\n widget.options_provider = options_provider\n return widget\n\n\ndef test_reg_error_normality_widget_analyzer_list(widget: RegErrorNormalityWidget) -> None:\n assert widget.analyzers() == [RegressionPerformanceAnalyzer]\n\n\[email protected](\n \"reference_data, current_data, data_mapping, dataset, expected_result\",\n (\n (\n pd.DataFrame({\"target\": [1, 2, 3, 4], \"prediction\": [1, 2, 3, 4]}),\n None,\n ColumnMapping(),\n None,\n BaseWidgetInfo(type=\"big_graph\", title=\"test_widget\", size=1),\n ),\n (\n pd.DataFrame({\"target\": [1, 2, 3, 4], \"prediction\": [1, 2, 3, 4]}),\n pd.DataFrame({\"target\": [1, 2, 3, 4], \"prediction\": [1, 2, 3, 4]}),\n ColumnMapping(),\n \"reference\",\n BaseWidgetInfo(type=\"big_graph\", title=\"test_widget\", size=1),\n ),\n ),\n)\ndef test_reg_error_normality_widget_simple_case(\n widget: RegErrorNormalityWidget,\n reference_data: pd.DataFrame,\n current_data: pd.DataFrame,\n data_mapping: ColumnMapping,\n dataset: Optional[str],\n expected_result: BaseWidgetInfo,\n) -> None:\n if dataset is not None:\n widget.dataset = dataset\n\n analyzer = RegressionPerformanceAnalyzer()\n analyzer.options_provider = widget.options_provider\n analyzer_results = analyzer.calculate(reference_data, current_data, data_mapping)\n result = widget.calculate(\n reference_data, current_data, data_mapping, {RegressionPerformanceAnalyzer: analyzer_results}\n )\n\n if expected_result is not None:\n # we have some widget for visualization\n assert result.type == expected_result.type\n assert result.title == expected_result.title\n assert result.size == expected_result.size\n assert result.params is not None\n\n else:\n # no widget data, show nothing\n assert result is None\n", "#!/usr/bin/env python\n# coding: utf-8\n\nimport json\nfrom typing import Optional\n\nimport pandas as pd\nimport numpy as np\n\nimport plotly.graph_objs as go\n\nfrom evidently import ColumnMapping\nfrom evidently.analyzers.num_target_drift_analyzer import NumTargetDriftAnalyzer\nfrom evidently.model.widget import BaseWidgetInfo\nfrom evidently.dashboard.widgets.widget import Widget\nfrom evidently.options import ColorOptions\nfrom evidently.options import QualityMetricsOptions\n\n\nclass NumOutputValuesWidget(Widget):\n def __init__(self, title: str, kind: str = 'target'):\n super().__init__(title)\n self.title = title\n self.kind = kind # target or prediction\n\n def analyzers(self):\n return [NumTargetDriftAnalyzer]\n\n def calculate(self,\n reference_data: pd.DataFrame,\n current_data: Optional[pd.DataFrame],\n column_mapping: ColumnMapping,\n analyzers_results) -> Optional[BaseWidgetInfo]:\n color_options = self.options_provider.get(ColorOptions)\n results = NumTargetDriftAnalyzer.get_results(analyzers_results)\n quality_metrics_options = self.options_provider.get(QualityMetricsOptions)\n conf_interval_n_sigmas = quality_metrics_options.conf_interval_n_sigmas\n\n if current_data is None:\n raise ValueError(\"current_data should be present\")\n\n if self.kind == 'target':\n if results.columns.utility_columns.target is None:\n return None\n\n column_name = results.columns.utility_columns.target\n\n elif self.kind == 'prediction':\n if results.columns.utility_columns.prediction is None:\n return None\n\n if not isinstance(results.columns.utility_columns.prediction, str):\n raise ValueError(f\"Widget [{self.title}] requires one str value for 'prediction' column\")\n\n column_name = results.columns.utility_columns.prediction\n\n else:\n raise ValueError(f\"Widget [{self.title}] requires 'target' or 'prediction' kind parameter value\")\n\n utility_columns_date = results.columns.utility_columns.date\n # plot values\n reference_mean = np.mean(reference_data[column_name])\n reference_std = np.std(reference_data[column_name], ddof=1)\n x_title = \"Timestamp\" if utility_columns_date else \"Index\"\n\n output_values = go.Figure()\n\n output_values.add_trace(go.Scatter(\n x=reference_data[utility_columns_date] if utility_columns_date else reference_data.index,\n y=reference_data[column_name],\n mode='markers',\n name='Reference',\n marker=dict(\n size=6,\n color=color_options.get_reference_data_color()\n )\n ))\n\n output_values.add_trace(go.Scatter(\n x=current_data[utility_columns_date] if utility_columns_date else current_data.index,\n y=current_data[column_name],\n mode='markers',\n name='Current',\n marker=dict(\n size=6,\n color=color_options.get_current_data_color()\n )\n ))\n\n if utility_columns_date:\n x0 = current_data[utility_columns_date].sort_values()[1]\n else:\n x0 = current_data.index.sort_values()[1]\n\n output_values.add_trace(go.Scatter(\n x=[x0, x0],\n y=[reference_mean - conf_interval_n_sigmas * reference_std,\n reference_mean + conf_interval_n_sigmas * reference_std],\n mode='markers',\n name='Current',\n marker=dict(\n size=0.01,\n color=color_options.non_visible_color,\n opacity=0.005\n ),\n showlegend=False\n ))\n\n output_values.update_layout(\n xaxis_title=x_title,\n yaxis_title=self.kind.title() + ' Value',\n showlegend=True,\n legend=dict(\n orientation=\"h\",\n yanchor=\"bottom\",\n y=1.02,\n xanchor=\"right\",\n x=1\n ),\n shapes=[\n dict(\n type=\"rect\",\n # x-reference is assigned to the x-values\n xref=\"paper\",\n # y-reference is assigned to the plot paper [0,1]\n yref=\"y\",\n x0=0,\n y0=reference_mean - conf_interval_n_sigmas * reference_std,\n x1=1,\n y1=reference_mean + conf_interval_n_sigmas * reference_std,\n fillcolor=color_options.fill_color,\n opacity=0.5,\n layer=\"below\",\n line_width=0,\n ),\n dict(\n type=\"line\",\n name='Reference',\n xref=\"paper\",\n yref=\"y\",\n x0=0, # min(testset_agg_by_date.index),\n y0=reference_mean,\n x1=1, # max(testset_agg_by_date.index),\n y1=reference_mean,\n line=dict(\n color=color_options.zero_line_color,\n width=3\n )\n ),\n ]\n )\n\n output_values_json = json.loads(output_values.to_json())\n\n return BaseWidgetInfo(\n title=self.title,\n type=\"big_graph\",\n size=1,\n params={\n \"data\": output_values_json['data'],\n \"layout\": output_values_json['layout']\n },\n )\n", "import pandas as pd\n\nfrom evidently.dashboard.widgets.percent_widget import PercentWidget\nfrom evidently.pipeline.column_mapping import ColumnMapping\n\n\ndef test_percent_widget_simple_case() -> None:\n reference_data = pd.DataFrame(\n {\n \"test\": [1, 2, 3, 1],\n }\n )\n\n # the widget does not use analyzers results, skip analyzers calculation\n\n widget = PercentWidget(\"test_widget\")\n assert widget.analyzers() == []\n result = widget.calculate(reference_data, None, ColumnMapping(), {})\n assert result is not None\n assert result.title == \"Example Percent Widget\"\n assert result.params is not None\n", "from typing import Optional\n\nimport pandas as pd\n\nimport pytest\n\nfrom evidently.analyzers.regression_performance_analyzer import RegressionPerformanceAnalyzer\nfrom evidently.model.widget import BaseWidgetInfo\nfrom evidently.options import OptionsProvider\nfrom evidently.pipeline.column_mapping import ColumnMapping\nfrom evidently.dashboard.widgets.reg_pred_vs_actual_widget import RegPredActualWidget\n\n\[email protected]\ndef widget() -> RegPredActualWidget:\n options_provider = OptionsProvider()\n\n widget = RegPredActualWidget(\"test_widget\")\n widget.options_provider = options_provider\n return widget\n\n\ndef test_reg_pred_actual_widget_analyzer_list(widget: RegPredActualWidget) -> None:\n assert widget.analyzers() == [RegressionPerformanceAnalyzer]\n\n\[email protected](\n \"reference_data, current_data, data_mapping, dataset, expected_result\",\n (\n (\n pd.DataFrame({\"target\": [1, 2, 3, 4], \"prediction\": [1, 2, 3, 4]}),\n None,\n ColumnMapping(),\n None,\n BaseWidgetInfo(type=\"big_graph\", title=\"test_widget\", size=1),\n ),\n (\n pd.DataFrame({\"target\": [1, 2, 3, 4], \"prediction\": [1, 2, 3, 4]}),\n pd.DataFrame({\"target\": [1, 2, 3, 4], \"prediction\": [1, 2, 3, 4]}),\n ColumnMapping(),\n \"reference\",\n BaseWidgetInfo(type=\"big_graph\", title=\"test_widget\", size=1),\n ),\n ),\n)\ndef test_reg_pred_actual_widget_simple_case(\n widget: RegPredActualWidget,\n reference_data: pd.DataFrame,\n current_data: pd.DataFrame,\n data_mapping: ColumnMapping,\n dataset: Optional[str],\n expected_result: BaseWidgetInfo,\n) -> None:\n if dataset is not None:\n widget.dataset = dataset\n\n analyzer = RegressionPerformanceAnalyzer()\n analyzer.options_provider = widget.options_provider\n analyzer_results = analyzer.calculate(reference_data, current_data, data_mapping)\n result = widget.calculate(\n reference_data, current_data, data_mapping, {RegressionPerformanceAnalyzer: analyzer_results}\n )\n\n if expected_result is not None:\n # we have some widget for visualization\n assert result.type == expected_result.type\n assert result.title == expected_result.title\n assert result.size == expected_result.size\n assert result.params is not None\n\n else:\n # no widget data, show nothing\n assert result is None\n" ]
[ [ "pandas.DataFrame" ], [ "numpy.std", "numpy.mean" ], [ "pandas.DataFrame" ], [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
hohsieh/osgeopy-code
[ "bc85f4ec7a630b53502ee491e400057b67cdab22" ]
[ "Chapter13/listing13_7.py" ]
[ "# Script that uses meshgrid to get map coordinates and then plots\n# the DEM in 3d.\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom osgeo import gdal\n\n\nds = gdal.Open(r'D:\\osgeopy-data\\Washington\\dem\\sthelens_utm.tif')\nband = ds.GetRasterBand(1)\nov_band = band.GetOverview(band.GetOverviewCount() - 3)\ndata = ov_band.ReadAsArray()\n\n# Calculate bounding coordinates.\ngeotransform = ds.GetGeoTransform()\nminx = geotransform[0]\nmaxy = geotransform[3]\nmaxx = minx + ov_band.XSize * geotransform[1]\nminy = maxy + ov_band.YSize * geotransform[5]\n\n# Get the x and y arrays.\nx = np.arange(minx, maxx, geotransform[1])\ny = np.arange(maxy, miny, geotransform[5])\nx, y = np.meshgrid(x[:ov_band.XSize], y[:ov_band.YSize])\n\n# Make the 3D plot.\nfig = plt.figure()\nax = fig.gca(projection='3d')\nax.plot_surface(x, y, data, cmap='gist_earth', lw=0)\nplt.axis('equal')\n\n# # Change the viewpoint and turn the ticks off.\n# ax.view_init(elev=55, azim=60)\n# plt.axis('off')\n\n# # Create an animation.\n# import matplotlib.animation as animation\n# def animate(i):\n# ax.view_init(elev=65, azim=i)\n# anim = animation.FuncAnimation(\n# fig, animate, frames=range(0, 360, 10), interval=100)\n# plt.axis('off')\n\n# # If you have FFmpeg and it's in your path, you can save the\n# # animation.\n# anim.save('d:/temp/helens.mp4', 'ffmpeg')\n\nplt.show()\n" ]
[ [ "numpy.arange", "matplotlib.pyplot.axis", "numpy.meshgrid", "matplotlib.pyplot.show", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
taesup-aws/autogluon
[ "51b20c4a18de148b4f06b384e56b102c86727153", "51b20c4a18de148b4f06b384e56b102c86727153" ]
[ "tabular/src/autogluon/tabular/models/knn/knn_model.py", "core/src/autogluon/core/scheduler/mo_asha.py" ]
[ "import logging\n\nimport numpy as np\nimport math\nimport psutil\nimport time\n\nfrom autogluon.common.features.types import R_BOOL, R_CATEGORY, R_OBJECT, S_BOOL, S_TEXT_NGRAM, S_TEXT_SPECIAL, S_DATETIME_AS_INT\nfrom autogluon.core.constants import REGRESSION\nfrom autogluon.core.utils.exceptions import NotEnoughMemoryError\nfrom autogluon.core.models.abstract.model_trial import skip_hpo\nfrom autogluon.core.models import AbstractModel\nfrom autogluon.core.utils.utils import normalize_pred_probas\n\nlogger = logging.getLogger(__name__)\n\n\n# TODO: Normalize data!\nclass KNNModel(AbstractModel):\n \"\"\"\n KNearestNeighbors model (scikit-learn): https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html\n \"\"\"\n def __init__(self, **kwargs):\n super().__init__(**kwargs)\n self._X_unused_index = None # Keeps track of unused training data indices, necessary for LOO OOF generation\n\n def _get_model_type(self):\n if self.params_aux.get('use_daal', True):\n try:\n # TODO: Add more granular switch, currently this affects all future KNN models even if they had `use_daal=False`\n from sklearnex import patch_sklearn\n patch_sklearn(\"knn_classifier\")\n patch_sklearn(\"knn_regressor\")\n # daal backend for KNN seems to be 20-40x+ faster than native sklearn with no downsides.\n logger.log(15, '\\tUsing daal4py KNN backend...')\n except:\n pass\n try:\n from ._knn_loo_variants import KNeighborsClassifier, KNeighborsRegressor\n except:\n from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor\n logger.warning('WARNING: Leave-one-out variants of KNN failed to import. Falling back to standard KNN implementations.')\n if self.problem_type == REGRESSION:\n return KNeighborsRegressor\n else:\n return KNeighborsClassifier\n\n def _preprocess(self, X, **kwargs):\n X = super()._preprocess(X, **kwargs)\n X = X.fillna(0).to_numpy(dtype=np.float32)\n return X\n\n def _set_default_params(self):\n default_params = {\n 'weights': 'uniform',\n 'n_jobs': -1,\n }\n for param, val in default_params.items():\n self._set_default_param_value(param, val)\n\n def _get_default_auxiliary_params(self) -> dict:\n default_auxiliary_params = super()._get_default_auxiliary_params()\n extra_auxiliary_params = dict(\n ignored_type_group_raw=[R_BOOL, R_CATEGORY, R_OBJECT], # TODO: Eventually use category features\n ignored_type_group_special=[S_BOOL, S_TEXT_NGRAM, S_TEXT_SPECIAL, S_DATETIME_AS_INT],\n )\n default_auxiliary_params.update(extra_auxiliary_params)\n return default_auxiliary_params\n\n @classmethod\n def _get_default_ag_args(cls) -> dict:\n default_ag_args = super()._get_default_ag_args()\n extra_ag_args = {'valid_stacker': False}\n default_ag_args.update(extra_ag_args)\n return default_ag_args\n\n @classmethod\n def _get_default_ag_args_ensemble(cls, **kwargs) -> dict:\n default_ag_args_ensemble = super()._get_default_ag_args_ensemble(**kwargs)\n extra_ag_args_ensemble = {'use_child_oof': True}\n default_ag_args_ensemble.update(extra_ag_args_ensemble)\n return default_ag_args_ensemble\n\n # TODO: Enable HPO for KNN\n def _get_default_searchspace(self):\n spaces = {}\n return spaces\n\n def _fit(self,\n X,\n y,\n time_limit=None,\n sample_weight=None,\n **kwargs):\n time_start = time.time()\n X = self.preprocess(X)\n self._validate_fit_memory_usage(X=X) # TODO: Can incorporate this into samples, can fit on portion of data to satisfy memory instead of raising exception immediately\n if sample_weight is not None: # TODO: support\n logger.log(15, \"sample_weight not yet supported for KNNModel, this model will ignore them in training.\")\n\n num_rows_max = len(X)\n # FIXME: v0.1 Must store final num rows for refit_full or else will use everything! Worst case refit_full could train far longer than the original model.\n if time_limit is None or num_rows_max <= 10000:\n self.model = self._get_model_type()(**self._get_model_params()).fit(X, y)\n else:\n self.model = self._fit_with_samples(X=X, y=y, time_limit=time_limit - (time.time() - time_start))\n\n def _validate_fit_memory_usage(self, X):\n max_memory_usage_ratio = self.params_aux['max_memory_usage_ratio']\n model_size_bytes = 4 * X.shape[0] * X.shape[1] # Assuming float32 types\n expected_final_model_size_bytes = model_size_bytes * 3.6 # Roughly what can be expected of the final KNN model in memory size\n if expected_final_model_size_bytes > 10000000: # Only worth checking if expected model size is >10MB\n available_mem = psutil.virtual_memory().available\n model_memory_ratio = expected_final_model_size_bytes / available_mem\n if model_memory_ratio > (0.15 * max_memory_usage_ratio):\n logger.warning(f'\\tWarning: Model is expected to require {round(model_memory_ratio * 100, 2)}% of available memory...')\n if model_memory_ratio > (0.20 * max_memory_usage_ratio):\n raise NotEnoughMemoryError # don't train full model to avoid OOM error\n\n # TODO: Won't work for RAPIDS without modification\n # TODO: Technically isn't OOF, but can be used inplace of OOF. Perhaps rename to something more accurate?\n def get_oof_pred_proba(self, X, normalize=None, **kwargs):\n \"\"\"X should be the same X passed to `.fit`\"\"\"\n y_oof_pred_proba = self._get_oof_pred_proba(X=X, **kwargs)\n if normalize is None:\n normalize = self.normalize_pred_probas\n if normalize:\n y_oof_pred_proba = normalize_pred_probas(y_oof_pred_proba, self.problem_type)\n y_oof_pred_proba = y_oof_pred_proba.astype(np.float32)\n return y_oof_pred_proba\n\n def _get_oof_pred_proba(self, X, **kwargs):\n if callable(getattr(self.model, \"predict_proba_loo\", None)):\n y_oof_pred_proba = self.model.predict_proba_loo()\n elif callable(getattr(self.model, \"predict_loo\", None)):\n y_oof_pred_proba = self.model.predict_loo()\n else:\n raise AssertionError(f'Model class {type(self.model)} does not support out-of-fold prediction generation.')\n y_oof_pred_proba = self._convert_proba_to_unified_form(y_oof_pred_proba)\n if X is not None and self._X_unused_index:\n X_unused = X.iloc[self._X_unused_index]\n y_pred_proba_new = self.predict_proba(X_unused)\n X_unused_index = set(self._X_unused_index)\n num_rows = len(X)\n X_used_index = [i for i in range(num_rows) if i not in X_unused_index]\n oof_pred_shape = y_oof_pred_proba.shape\n if len(oof_pred_shape) == 1:\n y_oof_tmp = np.zeros(num_rows, dtype=np.float32)\n y_oof_tmp[X_used_index] = y_oof_pred_proba\n y_oof_tmp[self._X_unused_index] = y_pred_proba_new\n else:\n y_oof_tmp = np.zeros((num_rows, oof_pred_shape[1]), dtype=np.float32)\n y_oof_tmp[X_used_index, :] = y_oof_pred_proba\n y_oof_tmp[self._X_unused_index, :] = y_pred_proba_new\n y_oof_pred_proba = y_oof_tmp\n return y_oof_pred_proba\n\n # TODO: Consider making this fully generic and available to all models\n def _fit_with_samples(self,\n X,\n y,\n time_limit,\n start_samples=10000,\n max_samples=None,\n sample_growth_factor=2,\n sample_time_growth_factor=8):\n \"\"\"\n Fit model with samples of the data repeatedly, gradually increasing the amount of data until time_limit is reached or all data is used.\n\n X and y must already be preprocessed.\n\n Parameters\n ----------\n X : np.ndarray\n The training data features (preprocessed).\n y : Series\n The training data ground truth labels.\n time_limit : float, default = None\n Time limit in seconds to adhere to when fitting model.\n start_samples : int, default = 10000\n Number of samples to start with. This will be multiplied by sample_growth_factor after each model fit to determine the next number of samples.\n For example, if start_samples=10000, sample_growth_factor=2, then the number of samples per model fit would be [10000, 20000, 40000, 80000, ...]\n max_samples : int, default = None\n The maximum number of samples to use.\n If None or greater than the number of rows in X, then it is set equal to the number of rows in X.\n sample_growth_factor : float, default = 2\n The rate of growth in sample size between each model fit. If 2, then the sample size doubles after each fit.\n sample_time_growth_factor : float, default = 8\n The multiplier to the expected fit time of the next model. If `sample_time_growth_factor=8` and a model took 10 seconds to train, the next model fit will be expected to take 80 seconds.\n If an expected time is greater than the remaining time in `time_limit`, the model will not be trained and the method will return early.\n \"\"\"\n time_start = time.time()\n\n num_rows_samples = []\n if max_samples is None:\n num_rows_max = len(X)\n else:\n num_rows_max = min(len(X), max_samples)\n num_rows_cur = start_samples\n while True:\n num_rows_cur = min(num_rows_cur, num_rows_max)\n num_rows_samples.append(num_rows_cur)\n if num_rows_cur == num_rows_max:\n break\n num_rows_cur *= sample_growth_factor\n num_rows_cur = math.ceil(num_rows_cur)\n if num_rows_cur * 1.5 >= num_rows_max:\n num_rows_cur = num_rows_max\n\n def sample_func(chunk, frac):\n # Guarantee at least 1 sample (otherwise log_loss would crash or model would return different column counts in pred_proba)\n n = max(math.ceil(len(chunk) * frac), 1)\n return chunk.sample(n=n, replace=False, random_state=0)\n\n if self.problem_type != REGRESSION:\n y_df = y.to_frame(name='label').reset_index(drop=True)\n else:\n y_df = None\n\n time_start_sample_loop = time.time()\n time_limit_left = time_limit - (time_start_sample_loop - time_start)\n model_type = self._get_model_type()\n idx = None\n for i, samples in enumerate(num_rows_samples):\n if samples != num_rows_max:\n if self.problem_type == REGRESSION:\n idx = np.random.choice(num_rows_max, size=samples, replace=False)\n else:\n idx = y_df.groupby('label', group_keys=False).apply(sample_func, frac=samples/num_rows_max).index\n X_samp = X[idx, :]\n y_samp = y.iloc[idx]\n else:\n X_samp = X\n y_samp = y\n idx = None\n self.model = model_type(**self._get_model_params()).fit(X_samp, y_samp)\n time_limit_left_prior = time_limit_left\n time_fit_end_sample = time.time()\n time_limit_left = time_limit - (time_fit_end_sample - time_start)\n time_fit_sample = time_limit_left_prior - time_limit_left\n time_required_for_next = time_fit_sample * sample_time_growth_factor\n logger.log(15, f'\\t{round(time_fit_sample, 2)}s \\t= Train Time (Using {samples}/{num_rows_max} rows) ({round(time_limit_left, 2)}s remaining time)')\n if time_required_for_next > time_limit_left and i != len(num_rows_samples) - 1:\n logger.log(20, f'\\tNot enough time to train KNN model on all training rows. Fit {samples}/{num_rows_max} rows. (Training KNN model on {num_rows_samples[i+1]} rows is expected to take {round(time_required_for_next, 2)}s)')\n break\n if idx is not None:\n idx = set(idx)\n self._X_unused_index = [i for i in range(num_rows_max) if i not in idx]\n return self.model\n\n # TODO: Add HPO\n def _hyperparameter_tune(self, **kwargs):\n return skip_hpo(self, **kwargs)\n\n def _more_tags(self):\n return {'valid_oof': True}\n\n\nclass FAISSModel(KNNModel):\n def _get_model_type(self):\n from .knn_utils import FAISSNeighborsClassifier, FAISSNeighborsRegressor\n if self.problem_type == REGRESSION:\n return FAISSNeighborsRegressor\n else:\n return FAISSNeighborsClassifier\n\n def _set_default_params(self):\n default_params = {\n 'index_factory_string': 'Flat',\n }\n for param, val in default_params.items():\n self._set_default_param_value(param, val)\n super()._set_default_params()\n\n @classmethod\n def _get_default_ag_args_ensemble(cls, **kwargs) -> dict:\n default_ag_args_ensemble = super()._get_default_ag_args_ensemble(**kwargs)\n extra_ag_args_ensemble = {'use_child_oof': False}\n default_ag_args_ensemble.update(extra_ag_args_ensemble)\n return default_ag_args_ensemble\n\n def _more_tags(self):\n return {'valid_oof': False}", "import logging\nimport copy\nimport numpy as np\n\nfrom .hyperband import HyperbandScheduler, HyperbandBracketManager\nfrom .mo_asha_promotion import MOPromotionRungSystem, EPS_NET, NSGA_II\nfrom ..utils.default_arguments import Integer, Boolean, Categorical, \\\n filter_by_key\nfrom ..utils.mo_hbo_utils import prepare_sign_vector\nfrom ..utils.mo_hbo_utils import retrieve_pareto_front\n\n__all__ = ['MOASHAScheduler']\n\nlogger = logging.getLogger(__name__)\n\n_ARGUMENT_KEYS = {\n 'objectives',\n}\n\n\nclass MOASHAScheduler(HyperbandScheduler):\n r\"\"\"Implements different variants of asynchronous multi-objective Hyperband\n by extending the standard HyperbandScheduler using a multi-objective\n version of ASHA. This version internally ranks candidates by first sorting\n them into different Pareto frontiers and then spaces them out evenly based\n on euclidean distance.\n\n Parameters\n ----------\n objectives : dict\n Dictionary with the names of objectives of interest. The corresponding\n values are allowed to be either \"MAX\" or \"MIN\" and indicate if an\n objective is to be maximized or minimized.\n\n Examples\n --------\n examples/mo_hpo/mo_asha.ipynb\n \"\"\"\n\n _CONSTRAINTS = {\n 'resume': Boolean(),\n 'max_t': Integer(1, None),\n 'grace_period': Integer(1, None),\n 'reduction_factor': Integer(2, None),\n 'brackets': Integer(1, None),\n 'type': Categorical((EPS_NET, NSGA_II)),\n 'searcher_data': Categorical(\n ('rungs', 'all', 'rungs_and_last')),\n 'do_snapshots': Boolean(),\n 'rung_system_per_bracket': Boolean(),\n 'random_seed': Integer(0, None)}\n\n def __init__(self, train_fn, **kwargs):\n self._objectives = kwargs[\"objectives\"]\n assert kwargs[\"type\"] in self._CONSTRAINTS[\"type\"].choices, \\\n \"Only eps_net and nsga_ii are supported\"\n # NOTE: This is just a dummy objective\n kwargs[\"reward_attr\"] = list(self._objectives.keys())[0]\n super().__init__(train_fn, **filter_by_key(kwargs, _ARGUMENT_KEYS))\n\n def _init_bracket_manager(self, scheduler_type, max_t, rung_levels,\n brackets, rung_system_per_bracket, random_seed):\n # Initialize bracket manager.\n terminator = MOHyperbandBracketManager(\n scheduler_type, self._time_attr, self._reward_attr, max_t,\n rung_levels, brackets, rung_system_per_bracket,\n random_seed, self._objectives)\n return terminator\n\n def get_pareto_front(self):\n \"\"\"Retrieves the pareto efficient points discovered during the search\n process. Raises an error if called before search was conducted.\n\n Returns\n ----------\n front: list\n A list containing the Pareto efficient points among all points\n that were found during the search process.\n \"\"\"\n assert len(self.finished_tasks) > 0, \"Can only extract front after \\\n jobs have been completed.\"\n pareto_front = retrieve_pareto_front(self.training_history,\n self._objectives)\n return pareto_front\n\n\nclass MOHyperbandBracketManager(HyperbandBracketManager):\n \"\"\"MO-Hyperband Bracket Manager\n\n Arguments follow the parent class\n\n Args:\n objectives : dict\n Indicates objectives of interest for the rung system\n \"\"\"\n def __init__(\n self, scheduler_type, time_attr, reward_attr, max_t, rung_levels,\n brackets, rung_system_per_bracket, random_seed, objectives):\n # Sign vector ensures that we deal with a pure minimization problem\n self.sign_vector = -prepare_sign_vector(objectives)\n self.objectives = objectives\n super().__init__(scheduler_type, time_attr, reward_attr, max_t,\n rung_levels, brackets, rung_system_per_bracket,\n random_seed)\n\n @staticmethod\n def _init_rung_systems(scheduler_type, rung_levels, promote_quantiles,\n max_t, num_systems):\n # Initialize MOPromotionRungSystem rung system for each level.\n rung_systems = [\n MOPromotionRungSystem(rung_levels[s:], promote_quantiles[s:], max_t, scheduler_type)\n for s in range(num_systems)\n ]\n return rung_systems\n\n def _prepare_objective_vector(self, result):\n values = np.array([result[k] for k in self.objectives])\n values = values * self.sign_vector\n return values\n\n def on_task_report(self, task, result):\n \"\"\"Passes a modified result dictionary to the parent class which causes\n the bracket manager to pass a numpy array containing multiple objective\n values to the rung system.\n\n :param task: Only task.task_id is used\n :param result: Current reported results from task\n :return: See parent class\n \"\"\"\n result_copy = copy.copy(result)\n result_copy[\"_REWARD_VECTOR\"] = \\\n self._prepare_objective_vector(result_copy)\n return super().on_task_report(task, result_copy)\n\n def _report_to_rung_sys(self, rung_sys, task, result, skip_rungs):\n # Pass result to rung system to decide if task may continue.\n rung_info = rung_sys.on_task_report(\n task, result[self._time_attr], result[\"_REWARD_VECTOR\"],\n skip_rungs=skip_rungs)\n return rung_info\n" ]
[ [ "numpy.zeros", "numpy.random.choice" ], [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
winnerineast/keras
[ "1e94c43d7ba0d7b6b629b2300e40470f495bdbe0", "1e94c43d7ba0d7b6b629b2300e40470f495bdbe0", "1e94c43d7ba0d7b6b629b2300e40470f495bdbe0" ]
[ "keras/initializers/initializers_v2.py", "keras/benchmarks/keras_examples_benchmarks/cifar10_cnn_benchmark_test.py", "keras/preprocessing/text_dataset_test.py" ]
[ "# Copyright 2020 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\"\"\"Keras initializers for TF 2.\n\"\"\"\n# pylint: disable=g-classes-have-attributes\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom keras import backend\nfrom tensorflow.python.ops import init_ops_v2\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n@keras_export('keras.initializers.Initializer')\nclass Initializer(object):\n \"\"\"Initializer base class: all Keras initializers inherit from this class.\n\n Initializers should implement a `__call__` method with the following\n signature:\n\n ```python\n def __call__(self, shape, dtype=None, **kwargs):\n # returns a tensor of shape `shape` and dtype `dtype`\n # containing values drawn from a distribution of your choice.\n ```\n\n Optionally, you an also implement the method `get_config` and the class\n method `from_config` in order to support serialization -- just like with\n any Keras object.\n\n Here's a simple example: a random normal initializer.\n\n ```python\n import tensorflow as tf\n\n class ExampleRandomNormal(tf.keras.initializers.Initializer):\n\n def __init__(self, mean, stddev):\n self.mean = mean\n self.stddev = stddev\n\n def __call__(self, shape, dtype=None, **kwargs):\n return tf.random.normal(\n shape, mean=self.mean, stddev=self.stddev, dtype=dtype)\n\n def get_config(self): # To support serialization\n return {\"mean\": self.mean, \"stddev\": self.stddev}\n ```\n\n Note that we don't have to implement `from_config` in the example above since\n the constructor arguments of the class the keys in the config returned by\n `get_config` are the same. In this case, the default `from_config`\n works fine.\n \"\"\"\n\n def __call__(self, shape, dtype=None, **kwargs):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor.\n **kwargs: Additional keyword arguments.\n \"\"\"\n raise NotImplementedError\n\n def get_config(self):\n \"\"\"Returns the configuration of the initializer as a JSON-serializable dict.\n\n Returns:\n A JSON-serializable Python dict.\n \"\"\"\n return {}\n\n @classmethod\n def from_config(cls, config):\n \"\"\"Instantiates an initializer from a configuration dictionary.\n\n Example:\n\n ```python\n initializer = RandomUniform(-1, 1)\n config = initializer.get_config()\n initializer = RandomUniform.from_config(config)\n ```\n\n Args:\n config: A Python dictionary, the output of `get_config`.\n\n Returns:\n A `tf.keras.initializers.Initializer` instance.\n \"\"\"\n config.pop('dtype', None)\n return cls(**config)\n\n\n@keras_export('keras.initializers.Zeros', 'keras.initializers.zeros', v1=[])\nclass Zeros(tf.zeros_initializer, Initializer):\n \"\"\"Initializer that generates tensors initialized to 0.\n\n Also available via the shortcut function `tf.keras.initializers.zeros`.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.Zeros()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.Zeros()\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n \"\"\"\n\n def __call__(self, shape, dtype=None, **kwargs):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are\n supported. If not specified, `tf.keras.backend.floatx()` is used,\n which default to `float32` unless you configured it otherwise\n (via `tf.keras.backend.set_floatx(float_dtype)`).\n **kwargs: Additional keyword arguments.\n \"\"\"\n return super(Zeros, self).__call__(shape, dtype=_get_dtype(dtype), **kwargs)\n\n\n@keras_export('keras.initializers.Ones', 'keras.initializers.ones', v1=[])\nclass Ones(tf.ones_initializer, Initializer):\n \"\"\"Initializer that generates tensors initialized to 1.\n\n Also available via the shortcut function `tf.keras.initializers.ones`.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.Ones()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.Ones()\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n \"\"\"\n\n def __call__(self, shape, dtype=None, **kwargs):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only numeric or boolean dtypes are\n supported. If not specified, `tf.keras.backend.floatx()` is used,\n which default to `float32` unless you configured it otherwise\n (via `tf.keras.backend.set_floatx(float_dtype)`).\n **kwargs: Additional keyword arguments.\n \"\"\"\n return super(Ones, self).__call__(shape, dtype=_get_dtype(dtype), **kwargs)\n\n\n@keras_export('keras.initializers.Constant',\n 'keras.initializers.constant',\n v1=[])\nclass Constant(Initializer):\n \"\"\"Initializer that generates tensors with constant values.\n\n Also available via the shortcut function `tf.keras.initializers.constant`.\n\n Only scalar values are allowed.\n The constant value provided must be convertible to the dtype requested\n when calling the initializer.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.Constant(3.)\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.Constant(3.)\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Args:\n value: A Python scalar.\n \"\"\"\n\n def __init__(self, value=0):\n self.value = value\n\n def __call__(self, shape, dtype=None, **kwargs):\n \"\"\"Returns a tensor object initialized to `self.value`.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. If not specified,\n `tf.keras.backend.floatx()` is used,\n which default to `float32` unless you configured it otherwise\n (via `tf.keras.backend.set_floatx(float_dtype)`).\n **kwargs: Additional keyword arguments.\n \"\"\"\n del kwargs\n return tf.constant(\n self.value, dtype=_get_dtype(dtype), shape=shape)\n\n def get_config(self):\n return {'value': self.value}\n\n\n@keras_export('keras.initializers.RandomUniform',\n 'keras.initializers.random_uniform',\n v1=[])\nclass RandomUniform(tf.random_uniform_initializer, Initializer):\n \"\"\"Initializer that generates tensors with a uniform distribution.\n\n Also available via the shortcut function\n `tf.keras.initializers.random_uniform`.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.RandomUniform(minval=0., maxval=1.)\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.RandomUniform(minval=0., maxval=1.)\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Args:\n minval: A python scalar or a scalar tensor. Lower bound of the range of\n random values to generate (inclusive).\n maxval: A python scalar or a scalar tensor. Upper bound of the range of\n random values to generate (exclusive).\n seed: A Python integer. An initializer created with a given seed will\n always produce the same random tensor for a given shape and dtype.\n \"\"\"\n\n def __call__(self, shape, dtype=None, **kwargs):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point and integer\n types are supported. If not specified,\n `tf.keras.backend.floatx()` is used,\n which default to `float32` unless you configured it otherwise\n (via `tf.keras.backend.set_floatx(float_dtype)`).\n **kwargs: Additional keyword arguments.\n \"\"\"\n return super(RandomUniform, self).__call__(\n shape, dtype=_get_dtype(dtype), **kwargs)\n\n\n@keras_export('keras.initializers.RandomNormal',\n 'keras.initializers.random_normal',\n v1=[])\nclass RandomNormal(tf.random_normal_initializer, Initializer):\n \"\"\"Initializer that generates tensors with a normal distribution.\n\n Also available via the shortcut function\n `tf.keras.initializers.random_normal`.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.RandomNormal(mean=0., stddev=1.)\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.RandomNormal(mean=0., stddev=1.)\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Args:\n mean: a python scalar or a scalar tensor. Mean of the random values to\n generate.\n stddev: a python scalar or a scalar tensor. Standard deviation of the random\n values to generate.\n seed: A Python integer. An initializer created with a given seed will\n always produce the same random tensor for a given shape and dtype.\n \"\"\"\n\n def __call__(self, shape, dtype=None, **kwargs):\n \"\"\"Returns a tensor object initialized to random normal values.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point types are\n supported. If not specified, `tf.keras.backend.floatx()` is used, which\n default to `float32` unless you configured it otherwise (via\n `tf.keras.backend.set_floatx(float_dtype)`)\n **kwargs: Additional keyword arguments.\n \"\"\"\n return super(RandomNormal, self).__call__(\n shape, dtype=_get_dtype(dtype), **kwargs)\n\n\n@keras_export('keras.initializers.TruncatedNormal',\n 'keras.initializers.truncated_normal',\n v1=[])\nclass TruncatedNormal(init_ops_v2.TruncatedNormal, Initializer):\n \"\"\"Initializer that generates a truncated normal distribution.\n\n Also available via the shortcut function\n `tf.keras.initializers.truncated_normal`.\n\n The values generated are similar to values from a\n `tf.keras.initializers.RandomNormal` initializer except that values more\n than two standard deviations from the mean are\n discarded and re-drawn.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.TruncatedNormal(mean=0., stddev=1.)\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.TruncatedNormal(mean=0., stddev=1.)\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Args:\n mean: a python scalar or a scalar tensor. Mean of the random values\n to generate.\n stddev: a python scalar or a scalar tensor. Standard deviation of the\n random values to generate.\n seed: A Python integer. An initializer created with a given seed will\n always produce the same random tensor for a given shape and dtype.\n \"\"\"\n\n def __call__(self, shape, dtype=None, **kwargs):\n \"\"\"Returns a tensor object initialized to random normal values (truncated).\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point types are\n supported. If not specified, `tf.keras.backend.floatx()` is used, which\n default to `float32` unless you configured it otherwise (via\n `tf.keras.backend.set_floatx(float_dtype)`)\n **kwargs: Additional keyword arguments.\n \"\"\"\n return super(TruncatedNormal, self).__call__(\n shape, dtype=_get_dtype(dtype), **kwargs)\n\n\n@keras_export('keras.initializers.VarianceScaling',\n 'keras.initializers.variance_scaling',\n v1=[])\nclass VarianceScaling(init_ops_v2.VarianceScaling, Initializer):\n \"\"\"Initializer capable of adapting its scale to the shape of weights tensors.\n\n Also available via the shortcut function\n `tf.keras.initializers.variance_scaling`.\n\n With `distribution=\"truncated_normal\" or \"untruncated_normal\"`, samples are\n drawn from a truncated/untruncated normal distribution with a mean of zero and\n a standard deviation (after truncation, if used) `stddev = sqrt(scale / n)`,\n where `n` is:\n\n - number of input units in the weight tensor, if `mode=\"fan_in\"`\n - number of output units, if `mode=\"fan_out\"`\n - average of the numbers of input and output units, if `mode=\"fan_avg\"`\n\n With `distribution=\"uniform\"`, samples are drawn from a uniform distribution\n within `[-limit, limit]`, where `limit = sqrt(3 * scale / n)`.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.VarianceScaling(\n ... scale=0.1, mode='fan_in', distribution='uniform')\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.VarianceScaling(\n ... scale=0.1, mode='fan_in', distribution='uniform')\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Args:\n scale: Scaling factor (positive float).\n mode: One of \"fan_in\", \"fan_out\", \"fan_avg\".\n distribution: Random distribution to use. One of \"truncated_normal\",\n \"untruncated_normal\" and \"uniform\".\n seed: A Python integer. An initializer created with a given seed will\n always produce the same random tensor for a given shape and dtype.\n \"\"\"\n\n def __call__(self, shape, dtype=None, **kwargs):\n \"\"\"Returns a tensor object initialized as specified by the initializer.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point types are\n supported. If not specified, `tf.keras.backend.floatx()` is used, which\n default to `float32` unless you configured it otherwise (via\n `tf.keras.backend.set_floatx(float_dtype)`)\n **kwargs: Additional keyword arguments.\n \"\"\"\n return super(VarianceScaling, self).__call__(\n shape, dtype=_get_dtype(dtype), **kwargs)\n\n\n@keras_export('keras.initializers.Orthogonal',\n 'keras.initializers.orthogonal',\n v1=[])\nclass Orthogonal(init_ops_v2.Orthogonal, Initializer):\n \"\"\"Initializer that generates an orthogonal matrix.\n\n Also available via the shortcut function `tf.keras.initializers.orthogonal`.\n\n If the shape of the tensor to initialize is two-dimensional, it is initialized\n with an orthogonal matrix obtained from the QR decomposition of a matrix of\n random numbers drawn from a normal distribution.\n If the matrix has fewer rows than columns then the output will have orthogonal\n rows. Otherwise, the output will have orthogonal columns.\n\n If the shape of the tensor to initialize is more than two-dimensional,\n a matrix of shape `(shape[0] * ... * shape[n - 2], shape[n - 1])`\n is initialized, where `n` is the length of the shape vector.\n The matrix is subsequently reshaped to give a tensor of the desired shape.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.Orthogonal()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.Orthogonal()\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Args:\n gain: multiplicative factor to apply to the orthogonal matrix\n seed: A Python integer. An initializer created with a given seed will\n always produce the same random tensor for a given shape and dtype.\n\n References:\n [Saxe et al., 2014](https://openreview.net/forum?id=_wzZwKpTDF_9C)\n ([pdf](https://arxiv.org/pdf/1312.6120.pdf))\n \"\"\"\n\n def __call__(self, shape, dtype=None, **kwargs):\n \"\"\"Returns a tensor object initialized to an orthogonal matrix.\n\n Args:\n shape: Shape of the tensor.\n dtype: Optional dtype of the tensor. Only floating point types are\n supported. If not specified, `tf.keras.backend.floatx()` is used,\n which default to `float32` unless you configured it otherwise\n (via `tf.keras.backend.set_floatx(float_dtype)`)\n **kwargs: Additional keyword arguments.\n \"\"\"\n return super(Orthogonal, self).__call__(\n shape, dtype=_get_dtype(dtype), **kwargs)\n\n\n@keras_export('keras.initializers.Identity',\n 'keras.initializers.identity',\n v1=[])\nclass Identity(init_ops_v2.Identity, Initializer):\n \"\"\"Initializer that generates the identity matrix.\n\n Also available via the shortcut function `tf.keras.initializers.identity`.\n\n Only usable for generating 2D matrices.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.Identity()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.Identity()\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Args:\n gain: Multiplicative factor to apply to the identity matrix.\n \"\"\"\n\n def __call__(self, shape, dtype=None, **kwargs):\n \"\"\"Returns a tensor object initialized to a 2D identity matrix.\n\n Args:\n shape: Shape of the tensor. It should have exactly rank 2.\n dtype: Optional dtype of the tensor. Only floating point types are\n supported. If not specified, `tf.keras.backend.floatx()` is used,\n which default to `float32` unless you configured it otherwise\n (via `tf.keras.backend.set_floatx(float_dtype)`)\n **kwargs: Additional keyword arguments.\n \"\"\"\n return super(Identity, self).__call__(\n shape, dtype=_get_dtype(dtype), **kwargs)\n\n\n@keras_export('keras.initializers.GlorotUniform',\n 'keras.initializers.glorot_uniform',\n v1=[])\nclass GlorotUniform(VarianceScaling):\n \"\"\"The Glorot uniform initializer, also called Xavier uniform initializer.\n\n Also available via the shortcut function\n `tf.keras.initializers.glorot_uniform`.\n\n Draws samples from a uniform distribution within `[-limit, limit]`, where\n `limit = sqrt(6 / (fan_in + fan_out))` (`fan_in` is the number of input units\n in the weight tensor and `fan_out` is the number of output units).\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.GlorotUniform()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.GlorotUniform()\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Args:\n seed: A Python integer. An initializer created with a given seed will\n always produce the same random tensor for a given shape and dtype.\n\n References:\n [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html)\n ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf))\n \"\"\"\n\n def __init__(self, seed=None):\n super(GlorotUniform, self).__init__(\n scale=1.0,\n mode='fan_avg',\n distribution='uniform',\n seed=seed)\n\n def get_config(self):\n return {'seed': self.seed}\n\n\n@keras_export('keras.initializers.GlorotNormal',\n 'keras.initializers.glorot_normal',\n v1=[])\nclass GlorotNormal(VarianceScaling):\n \"\"\"The Glorot normal initializer, also called Xavier normal initializer.\n\n Also available via the shortcut function\n `tf.keras.initializers.glorot_normal`.\n\n Draws samples from a truncated normal distribution centered on 0 with `stddev\n = sqrt(2 / (fan_in + fan_out))` where `fan_in` is the number of input units in\n the weight tensor and `fan_out` is the number of output units in the weight\n tensor.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.GlorotNormal()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.GlorotNormal()\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Args:\n seed: A Python integer. An initializer created with a given seed will\n always produce the same random tensor for a given shape and dtype.\n\n References:\n [Glorot et al., 2010](http://proceedings.mlr.press/v9/glorot10a.html)\n ([pdf](http://jmlr.org/proceedings/papers/v9/glorot10a/glorot10a.pdf))\n \"\"\"\n\n def __init__(self, seed=None):\n super(GlorotNormal, self).__init__(\n scale=1.0,\n mode='fan_avg',\n distribution='truncated_normal',\n seed=seed)\n\n def get_config(self):\n return {'seed': self.seed}\n\n\n@keras_export('keras.initializers.LecunNormal',\n 'keras.initializers.lecun_normal',\n v1=[])\nclass LecunNormal(VarianceScaling):\n \"\"\"Lecun normal initializer.\n\n Also available via the shortcut function\n `tf.keras.initializers.lecun_normal`.\n\n Initializers allow you to pre-specify an initialization strategy, encoded in\n the Initializer object, without knowing the shape and dtype of the variable\n being initialized.\n\n Draws samples from a truncated normal distribution centered on 0 with `stddev\n = sqrt(1 / fan_in)` where `fan_in` is the number of input units in the weight\n tensor.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.LecunNormal()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.LecunNormal()\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Arguments:\n seed: A Python integer. Used to seed the random generator.\n\n References:\n - Self-Normalizing Neural Networks,\n [Klambauer et al., 2017]\n (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks)\n ([pdf]\n (https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf))\n - Efficient Backprop,\n [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)\n \"\"\"\n\n def __init__(self, seed=None):\n super(LecunNormal, self).__init__(\n scale=1., mode='fan_in', distribution='truncated_normal', seed=seed)\n\n def get_config(self):\n return {'seed': self.seed}\n\n\n@keras_export('keras.initializers.LecunUniform',\n 'keras.initializers.lecun_uniform',\n v1=[])\nclass LecunUniform(VarianceScaling):\n \"\"\"Lecun uniform initializer.\n\n Also available via the shortcut function\n `tf.keras.initializers.lecun_uniform`.\n\n Draws samples from a uniform distribution within `[-limit, limit]`,\n where `limit = sqrt(3 / fan_in)` (`fan_in` is the number of input units in the\n weight tensor).\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.LecunUniform()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.LecunUniform()\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Arguments:\n seed: A Python integer. An initializer created with a given seed will\n always produce the same random tensor for a given shape and dtype.\n\n References:\n - Self-Normalizing Neural Networks,\n [Klambauer et al., 2017](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks) # pylint: disable=line-too-long\n ([pdf](https://papers.nips.cc/paper/6698-self-normalizing-neural-networks.pdf))\n - Efficient Backprop,\n [Lecun et al., 1998](http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf)\n \"\"\"\n\n def __init__(self, seed=None):\n super(LecunUniform, self).__init__(\n scale=1., mode='fan_in', distribution='uniform', seed=seed)\n\n def get_config(self):\n return {'seed': self.seed}\n\n\n@keras_export('keras.initializers.HeNormal',\n 'keras.initializers.he_normal',\n v1=[])\nclass HeNormal(VarianceScaling):\n \"\"\"He normal initializer.\n\n Also available via the shortcut function\n `tf.keras.initializers.he_normal`.\n\n It draws samples from a truncated normal distribution centered on 0 with\n `stddev = sqrt(2 / fan_in)` where `fan_in` is the number of input units in the\n weight tensor.\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.HeNormal()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.HeNormal()\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Arguments:\n seed: A Python integer. An initializer created with a given seed will\n always produce the same random tensor for a given shape and dtype.\n\n References:\n [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long\n ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf))\n \"\"\"\n\n def __init__(self, seed=None):\n super(HeNormal, self).__init__(\n scale=2., mode='fan_in', distribution='truncated_normal', seed=seed)\n\n def get_config(self):\n return {'seed': self.seed}\n\n\n@keras_export('keras.initializers.HeUniform',\n 'keras.initializers.he_uniform',\n v1=[])\nclass HeUniform(VarianceScaling):\n \"\"\"He uniform variance scaling initializer.\n\n Also available via the shortcut function\n `tf.keras.initializers.he_uniform`.\n\n Draws samples from a uniform distribution within `[-limit, limit]`, where\n `limit = sqrt(6 / fan_in)` (`fan_in` is the number of input units in the\n weight tensor).\n\n Examples:\n\n >>> # Standalone usage:\n >>> initializer = tf.keras.initializers.HeUniform()\n >>> values = initializer(shape=(2, 2))\n\n >>> # Usage in a Keras layer:\n >>> initializer = tf.keras.initializers.HeUniform()\n >>> layer = tf.keras.layers.Dense(3, kernel_initializer=initializer)\n\n Arguments:\n seed: A Python integer. An initializer created with a given seed will\n always produce the same random tensor for a given shape and dtype.\n\n References:\n [He et al., 2015](https://www.cv-foundation.org/openaccess/content_iccv_2015/html/He_Delving_Deep_into_ICCV_2015_paper.html) # pylint: disable=line-too-long\n ([pdf](https://www.cv-foundation.org/openaccess/content_iccv_2015/papers/He_Delving_Deep_into_ICCV_2015_paper.pdf))\n \"\"\"\n\n def __init__(self, seed=None):\n super(HeUniform, self).__init__(\n scale=2., mode='fan_in', distribution='uniform', seed=seed)\n\n def get_config(self):\n return {'seed': self.seed}\n\n\ndef _get_dtype(dtype):\n if dtype is None:\n dtype = backend.floatx()\n return tf.as_dtype(dtype)\n", "# Copyright 2020 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\"\"\"Benchmarks on CNN on cifar10 dataset.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom keras.benchmarks import benchmark_util\n\n\nclass Cifar10CNNBenchmark(tf.test.Benchmark):\n \"\"\"Benchmarks for CNN using `tf.test.Benchmark`.\"\"\"\n\n def __init__(self):\n super(Cifar10CNNBenchmark, self).__init__()\n self.num_classes = 10\n (self.x_train, self.y_train), _ = tf.keras.datasets.cifar10.load_data()\n self.x_train = self.x_train.astype('float32') / 255\n self.y_train = tf.keras.utils.to_categorical(self.y_train, self.num_classes)\n self.epochs = 5\n\n def _build_model(self):\n \"\"\"Model from https://github.com/keras-team/keras/blob/master/examples/cifar10_cnn.py.\"\"\"\n model = tf.keras.Sequential()\n model.add(\n tf.keras.layers.Conv2D(\n 32, (3, 3), padding='same', input_shape=self.x_train.shape[1:]))\n model.add(tf.keras.layers.Activation('relu'))\n model.add(tf.keras.layers.Conv2D(32, (3, 3)))\n model.add(tf.keras.layers.Activation('relu'))\n model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(tf.keras.layers.Dropout(0.25))\n\n model.add(tf.keras.layers.Conv2D(64, (3, 3), padding='same'))\n model.add(tf.keras.layers.Activation('relu'))\n model.add(tf.keras.layers.Conv2D(64, (3, 3)))\n model.add(tf.keras.layers.Activation('relu'))\n model.add(tf.keras.layers.MaxPooling2D(pool_size=(2, 2)))\n model.add(tf.keras.layers.Dropout(0.25))\n\n model.add(tf.keras.layers.Flatten())\n model.add(tf.keras.layers.Dense(512))\n model.add(tf.keras.layers.Activation('relu'))\n model.add(tf.keras.layers.Dropout(0.5))\n model.add(tf.keras.layers.Dense(self.num_classes))\n model.add(tf.keras.layers.Activation('softmax'))\n return model\n\n # In each benchmark test, the required arguments for the\n # method `measure_performance` include:\n # x: Input data, it could be Numpy or loaded from tfds.\n # y: Target data. If `x` is a dataset or generator instance,\n # `y` should not be specified.\n # loss: Loss function for model.\n # optimizer: Optimizer for model.\n # Check more details in `measure_performance()` method of\n # benchmark_util.\n def benchmark_cnn_cifar10_bs_256(self):\n \"\"\"Measure performance with batch_size=256.\"\"\"\n batch_size = 256\n metrics, wall_time, extras = benchmark_util.measure_performance(\n self._build_model,\n x=self.x_train,\n y=self.y_train,\n batch_size=batch_size,\n epochs=self.epochs,\n optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.0001, decay=1e-6),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n self.report_benchmark(wall_time=wall_time, metrics=metrics, extras=extras)\n\n def benchmark_cnn_cifar10_bs_512(self):\n \"\"\"Measure performance with batch_size=512.\"\"\"\n batch_size = 512\n metrics, wall_time, extras = benchmark_util.measure_performance(\n self._build_model,\n x=self.x_train,\n y=self.y_train,\n batch_size=batch_size,\n epochs=self.epochs,\n optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.0001, decay=1e-6),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n self.report_benchmark(wall_time=wall_time, metrics=metrics, extras=extras)\n\n def benchmark_cnn_cifar10_bs_1024(self):\n \"\"\"Measure performance with batch_size=1024.\"\"\"\n batch_size = 1024\n metrics, wall_time, extras = benchmark_util.measure_performance(\n self._build_model,\n x=self.x_train,\n y=self.y_train,\n batch_size=batch_size,\n epochs=self.epochs,\n optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.0001, decay=1e-6),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n self.report_benchmark(wall_time=wall_time, metrics=metrics, extras=extras)\n\n def benchmark_cnn_cifar10_bs_1024_gpu_2(self):\n \"\"\"Measure performance with batch_size=1024, gpu=2 and\n\n distribution_strategy=`mirrored`.\n \"\"\"\n batch_size = 1024\n metrics, wall_time, extras = benchmark_util.measure_performance(\n self._build_model,\n x=self.x_train,\n y=self.y_train,\n batch_size=batch_size,\n num_gpus=2,\n distribution_strategy='mirrored',\n epochs=self.epochs,\n optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.0001, decay=1e-6),\n loss='categorical_crossentropy',\n metrics=['accuracy'])\n\n self.report_benchmark(wall_time=wall_time, metrics=metrics, extras=extras)\n\n\nif __name__ == '__main__':\n tf.test.main()\n", "# Copyright 2020 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\"\"\"Tests for text_dataset.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nimport os\nimport random\nimport shutil\nimport string\nfrom keras import keras_parameterized\nfrom keras.preprocessing import text_dataset\n\n\nclass TextDatasetFromDirectoryTest(keras_parameterized.TestCase):\n\n def _prepare_directory(self,\n num_classes=2,\n nested_dirs=False,\n count=16,\n length=20):\n # Get a unique temp directory\n temp_dir = os.path.join(self.get_temp_dir(), str(random.randint(0, 1e6)))\n os.mkdir(temp_dir)\n self.addCleanup(shutil.rmtree, temp_dir)\n\n # Generate paths to class subdirectories\n paths = []\n for class_index in range(num_classes):\n class_directory = 'class_%s' % (class_index,)\n if nested_dirs:\n class_paths = [\n class_directory, os.path.join(class_directory, 'subfolder_1'),\n os.path.join(class_directory, 'subfolder_2'), os.path.join(\n class_directory, 'subfolder_1', 'sub-subfolder')\n ]\n else:\n class_paths = [class_directory]\n for path in class_paths:\n os.mkdir(os.path.join(temp_dir, path))\n paths += class_paths\n\n for i in range(count):\n path = paths[count % len(paths)]\n filename = os.path.join(path, 'text_%s.txt' % (i,))\n f = open(os.path.join(temp_dir, filename), 'w')\n text = ''.join([random.choice(string.printable) for _ in range(length)])\n f.write(text)\n f.close()\n return temp_dir\n\n def test_text_dataset_from_directory_binary(self):\n directory = self._prepare_directory(num_classes=2)\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=8, label_mode='int', max_length=10)\n batch = next(iter(dataset))\n self.assertLen(batch, 2)\n self.assertEqual(batch[0].shape, (8,))\n self.assertEqual(batch[0].dtype.name, 'string')\n self.assertEqual(len(batch[0].numpy()[0]), 10) # Test max_length\n self.assertEqual(batch[1].shape, (8,))\n self.assertEqual(batch[1].dtype.name, 'int32')\n\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=8, label_mode='binary')\n batch = next(iter(dataset))\n self.assertLen(batch, 2)\n self.assertEqual(batch[0].shape, (8,))\n self.assertEqual(batch[0].dtype.name, 'string')\n self.assertEqual(batch[1].shape, (8, 1))\n self.assertEqual(batch[1].dtype.name, 'float32')\n\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=8, label_mode='categorical')\n batch = next(iter(dataset))\n self.assertLen(batch, 2)\n self.assertEqual(batch[0].shape, (8,))\n self.assertEqual(batch[0].dtype.name, 'string')\n self.assertEqual(batch[1].shape, (8, 2))\n self.assertEqual(batch[1].dtype.name, 'float32')\n\n def test_sample_count(self):\n directory = self._prepare_directory(num_classes=4, count=15)\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=8, label_mode=None)\n sample_count = 0\n for batch in dataset:\n sample_count += batch.shape[0]\n self.assertEqual(sample_count, 15)\n\n def test_text_dataset_from_directory_multiclass(self):\n directory = self._prepare_directory(num_classes=4, count=15)\n\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=8, label_mode=None)\n batch = next(iter(dataset))\n self.assertEqual(batch.shape, (8,))\n\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=8, label_mode=None)\n sample_count = 0\n iterator = iter(dataset)\n for batch in dataset:\n sample_count += next(iterator).shape[0]\n self.assertEqual(sample_count, 15)\n\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=8, label_mode='int')\n batch = next(iter(dataset))\n self.assertLen(batch, 2)\n self.assertEqual(batch[0].shape, (8,))\n self.assertEqual(batch[0].dtype.name, 'string')\n self.assertEqual(batch[1].shape, (8,))\n self.assertEqual(batch[1].dtype.name, 'int32')\n\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=8, label_mode='categorical')\n batch = next(iter(dataset))\n self.assertLen(batch, 2)\n self.assertEqual(batch[0].shape, (8,))\n self.assertEqual(batch[0].dtype.name, 'string')\n self.assertEqual(batch[1].shape, (8, 4))\n self.assertEqual(batch[1].dtype.name, 'float32')\n\n def test_text_dataset_from_directory_validation_split(self):\n directory = self._prepare_directory(num_classes=2, count=10)\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=10, validation_split=0.2, subset='training',\n seed=1337)\n batch = next(iter(dataset))\n self.assertLen(batch, 2)\n self.assertEqual(batch[0].shape, (8,))\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=10, validation_split=0.2, subset='validation',\n seed=1337)\n batch = next(iter(dataset))\n self.assertLen(batch, 2)\n self.assertEqual(batch[0].shape, (2,))\n\n def test_text_dataset_from_directory_manual_labels(self):\n directory = self._prepare_directory(num_classes=2, count=2)\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=8, labels=[0, 1], shuffle=False)\n batch = next(iter(dataset))\n self.assertLen(batch, 2)\n self.assertAllClose(batch[1], [0, 1])\n\n def test_text_dataset_from_directory_follow_links(self):\n directory = self._prepare_directory(num_classes=2, count=25,\n nested_dirs=True)\n dataset = text_dataset.text_dataset_from_directory(\n directory, batch_size=8, label_mode=None, follow_links=True)\n sample_count = 0\n for batch in dataset:\n sample_count += batch.shape[0]\n self.assertEqual(sample_count, 25)\n\n def test_text_dataset_from_directory_errors(self):\n directory = self._prepare_directory(num_classes=3, count=5)\n\n with self.assertRaisesRegex(ValueError, '`labels` argument should be'):\n _ = text_dataset.text_dataset_from_directory(\n directory, labels=None)\n\n with self.assertRaisesRegex(ValueError, '`label_mode` argument must be'):\n _ = text_dataset.text_dataset_from_directory(\n directory, label_mode='other')\n\n with self.assertRaisesRegex(\n ValueError, 'only pass `class_names` if the labels are inferred'):\n _ = text_dataset.text_dataset_from_directory(\n directory, labels=[0, 0, 1, 1, 1],\n class_names=['class_0', 'class_1', 'class_2'])\n\n with self.assertRaisesRegex(\n ValueError,\n 'Expected the lengths of `labels` to match the number of files'):\n _ = text_dataset.text_dataset_from_directory(\n directory, labels=[0, 0, 1, 1])\n\n with self.assertRaisesRegex(\n ValueError, '`class_names` passed did not match'):\n _ = text_dataset.text_dataset_from_directory(\n directory, class_names=['class_0', 'class_2'])\n\n with self.assertRaisesRegex(ValueError, 'there must exactly 2 classes'):\n _ = text_dataset.text_dataset_from_directory(\n directory, label_mode='binary')\n\n with self.assertRaisesRegex(ValueError,\n '`validation_split` must be between 0 and 1'):\n _ = text_dataset.text_dataset_from_directory(\n directory, validation_split=2)\n\n with self.assertRaisesRegex(ValueError,\n '`subset` must be either \"training\" or'):\n _ = text_dataset.text_dataset_from_directory(\n directory, validation_split=0.2, subset='other')\n\n with self.assertRaisesRegex(ValueError, '`validation_split` must be set'):\n _ = text_dataset.text_dataset_from_directory(\n directory, validation_split=0, subset='training')\n\n with self.assertRaisesRegex(ValueError, 'must provide a `seed`'):\n _ = text_dataset.text_dataset_from_directory(\n directory, validation_split=0.2, subset='training')\n\n\nif __name__ == '__main__':\n tf.compat.v1.enable_v2_behavior()\n tf.test.main()\n" ]
[ [ "tensorflow.python.util.tf_export.keras_export", "tensorflow.as_dtype" ], [ "tensorflow.keras.layers.Activation", "tensorflow.keras.layers.Dense", "tensorflow.keras.layers.Conv2D", "tensorflow.keras.Sequential", "tensorflow.keras.datasets.cifar10.load_data", "tensorflow.test.main", "tensorflow.keras.optimizers.RMSprop", "tensorflow.keras.layers.Dropout", "tensorflow.keras.layers.MaxPooling2D", "tensorflow.keras.layers.Flatten", "tensorflow.keras.utils.to_categorical" ], [ "tensorflow.compat.v1.enable_v2_behavior", "tensorflow.test.main" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "1.12", "2.6", "2.2", "1.13", "2.3", "2.4", "1.4", "2.9", "1.5", "1.7", "2.5", "0.12", "1.0", "2.8", "1.2", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "2.7", "2.6", "2.4", "2.3", "2.5", "2.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
BradyBromley/botorch
[ "270599207f5b9bf8c66e1197ad2632bb69c3d3b9" ]
[ "botorch/acquisition/monte_carlo.py" ]
[ "#!/usr/bin/env python3\n\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\nr\"\"\"\nBatch acquisition functions using the reparameterization trick in combination\nwith (quasi) Monte-Carlo sampling. See [Rezende2014reparam]_ and\n[Wilson2017reparam]_\n\n.. [Rezende2014reparam]\n D. J. Rezende, S. Mohamed, and D. Wierstra. Stochastic backpropagation and\n approximate inference in deep generative models. ICML 2014.\n\n.. [Wilson2017reparam]\n J. T. Wilson, R. Moriconi, F. Hutter, and M. P. Deisenroth.\n The reparameterization trick for acquisition functions. ArXiv 2017.\n\"\"\"\n\nimport math\nfrom abc import ABC, abstractmethod\nfrom typing import Optional, Union\n\nimport torch\nfrom torch import Tensor\n\nfrom ..exceptions.errors import UnsupportedError\nfrom ..models.model import Model\nfrom ..sampling.samplers import MCSampler, SobolQMCNormalSampler\nfrom ..utils.transforms import (\n concatenate_pending_points,\n match_batch_shape,\n t_batch_mode_transform,\n)\nfrom .acquisition import AcquisitionFunction\nfrom .objective import IdentityMCObjective, MCAcquisitionObjective\nfrom .utils import prune_inferior_points\n\n\nclass MCAcquisitionFunction(AcquisitionFunction, ABC):\n r\"\"\"Abstract base class for Monte-Carlo based batch acquisition functions.\"\"\"\n\n def __init__(\n self,\n model: Model,\n sampler: Optional[MCSampler] = None,\n objective: Optional[MCAcquisitionObjective] = None,\n X_pending: Optional[Tensor] = None,\n ) -> None:\n r\"\"\"Constructor for the MCAcquisitionFunction base class.\n\n Args:\n model: A fitted model.\n sampler: The sampler used to draw base samples. Defaults to\n `SobolQMCNormalSampler(num_samples=512, collapse_batch_dims=True)`.\n objective: The MCAcquisitionObjective under which the samples are\n evaluated. Defaults to `IdentityMCObjective()`.\n X_pending: A `m x d`-dim Tensor of `m` design points that have\n points that have been submitted for function evaluation\n but have not yet been evaluated.\n \"\"\"\n super().__init__(model=model)\n if sampler is None:\n sampler = SobolQMCNormalSampler(num_samples=512, collapse_batch_dims=True)\n self.add_module(\"sampler\", sampler)\n if objective is None:\n objective = IdentityMCObjective()\n elif not isinstance(objective, MCAcquisitionObjective):\n raise UnsupportedError(\n \"Only objectives of type MCAcquisitionObjective are supported for \"\n \"MC acquisition functions.\"\n )\n self.add_module(\"objective\", objective)\n self.set_X_pending(X_pending)\n\n @abstractmethod\n def forward(self, X: Tensor) -> Tensor:\n r\"\"\"Takes in a `(b) x q x d` X Tensor of `(b)` t-batches with `q` `d`-dim\n design points each, and returns a one-dimensional Tensor with\n `(b)` elements. Should utilize the result of set_X_pending as needed\n to account for pending function evaluations.\n \"\"\"\n pass # pragma: no cover\n\n\nclass qExpectedImprovement(MCAcquisitionFunction):\n r\"\"\"MC-based batch Expected Improvement.\n\n This computes qEI by\n (1) sampling the joint posterior over q points\n (2) evaluating the improvement over the current best for each sample\n (3) maximizing over q\n (4) averaging over the samples\n\n `qEI(X) = E(max(max Y - best_f, 0)), Y ~ f(X), where X = (x_1,...,x_q)`\n\n Example:\n >>> model = SingleTaskGP(train_X, train_Y)\n >>> best_f = train_Y.max()[0]\n >>> sampler = SobolQMCNormalSampler(1000)\n >>> qEI = qExpectedImprovement(model, best_f, sampler)\n >>> qei = qEI(test_X)\n \"\"\"\n\n def __init__(\n self,\n model: Model,\n best_f: Union[float, Tensor],\n sampler: Optional[MCSampler] = None,\n objective: Optional[MCAcquisitionObjective] = None,\n X_pending: Optional[Tensor] = None,\n ) -> None:\n r\"\"\"q-Expected Improvement.\n\n Args:\n model: A fitted model.\n best_f: The best objective value observed so far (assumed noiseless).\n sampler: The sampler used to draw base samples. Defaults to\n `SobolQMCNormalSampler(num_samples=500, collapse_batch_dims=True)`\n objective: The MCAcquisitionObjective under which the samples are\n evaluated. Defaults to `IdentityMCObjective()`.\n X_pending: A `m x d`-dim Tensor of `m` design points that have\n points that have been submitted for function evaluation\n but have not yet been evaluated. Concatenated into X upon\n forward call. Copied and set to have no gradient.\n \"\"\"\n super().__init__(\n model=model, sampler=sampler, objective=objective, X_pending=X_pending\n )\n if not torch.is_tensor(best_f):\n best_f = torch.tensor(float(best_f))\n self.register_buffer(\"best_f\", best_f)\n\n @concatenate_pending_points\n @t_batch_mode_transform()\n def forward(self, X: Tensor) -> Tensor:\n r\"\"\"Evaluate qExpectedImprovement on the candidate set `X`.\n\n Args:\n X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim\n design points each.\n\n Returns:\n A `(b)`-dim Tensor of Expected Improvement values at the given\n design points `X`.\n \"\"\"\n posterior = self.model.posterior(X)\n samples = self.sampler(posterior)\n obj = self.objective(samples)\n obj = (obj - self.best_f).clamp_min(0)\n q_ei = obj.max(dim=-1)[0].mean(dim=0)\n return q_ei\n\n\nclass qNoisyExpectedImprovement(MCAcquisitionFunction):\n r\"\"\"MC-based batch Noisy Expected Improvement.\n\n This function does not assume a `best_f` is known (which would require\n noiseless observations). Instead, it uses samples from the joint posterior\n over the `q` test points and previously observed points. The improvement\n over previously observed points is computed for each sample and averaged.\n\n `qNEI(X) = E(max(max Y - max Y_baseline, 0))`, where\n `(Y, Y_baseline) ~ f((X, X_baseline)), X = (x_1,...,x_q)`\n\n Example:\n >>> model = SingleTaskGP(train_X, train_Y)\n >>> sampler = SobolQMCNormalSampler(1000)\n >>> qNEI = qNoisyExpectedImprovement(model, train_X, sampler)\n >>> qnei = qNEI(test_X)\n \"\"\"\n\n def __init__(\n self,\n model: Model,\n X_baseline: Tensor,\n sampler: Optional[MCSampler] = None,\n objective: Optional[MCAcquisitionObjective] = None,\n X_pending: Optional[Tensor] = None,\n prune_baseline: bool = False,\n ) -> None:\n r\"\"\"q-Noisy Expected Improvement.\n\n Args:\n model: A fitted model.\n X_baseline: A `r x d`-dim Tensor of `r` design points that have\n already been observed. These points are considered as the\n potential best design point.\n sampler: The sampler used to draw base samples. Defaults to\n `SobolQMCNormalSampler(num_samples=500, collapse_batch_dims=True)`.\n objective: The MCAcquisitionObjective under which the samples are\n evaluated. Defaults to `IdentityMCObjective()`.\n X_pending: A `m x d`-dim Tensor of `m` design points that have\n points that have been submitted for function evaluation\n but have not yet been evaluated. Concatenated into X upon\n forward call. Copied and set to have no gradient.\n prune_baseline: If True, remove points in `X_baseline` that are\n highly unlikely to be the best point. This can significantly\n improve performance and is generally recommended. In order to\n customize pruning parameters, instead manually call\n `botorch.acquisition.utils.prune_inferior_points` on `X_baseline`\n before instantiating the acquisition function.\n \"\"\"\n super().__init__(\n model=model, sampler=sampler, objective=objective, X_pending=X_pending\n )\n if prune_baseline:\n X_baseline = prune_inferior_points(\n model=model, X=X_baseline, objective=objective\n )\n self.register_buffer(\"X_baseline\", X_baseline)\n\n @concatenate_pending_points\n @t_batch_mode_transform()\n def forward(self, X: Tensor) -> Tensor:\n r\"\"\"Evaluate qNoisyExpectedImprovement on the candidate set `X`.\n\n Args:\n X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim\n design points each.\n\n Returns:\n A `(b)`-dim Tensor of Noisy Expected Improvement values at the given\n design points `X`.\n \"\"\"\n q = X.shape[-2]\n X_full = torch.cat([X, match_batch_shape(self.X_baseline, X)], dim=-2)\n # TODO (T41248036): Implement more efficient way to compute posterior\n # over both training and test points in GPyTorch\n posterior = self.model.posterior(X_full)\n samples = self.sampler(posterior)\n obj = self.objective(samples)\n diffs = obj[:, :, :q].max(dim=-1)[0] - obj[:, :, q:].max(dim=-1)[0]\n return diffs.clamp_min(0).mean(dim=0)\n\n\nclass qProbabilityOfImprovement(MCAcquisitionFunction):\n r\"\"\"MC-based batch Probability of Improvement.\n\n Estimates the probability of improvement over the current best observed\n value by sampling from the joint posterior distribution of the q-batch.\n MC-based estimates of a probability involves taking expectation of an\n indicator function; to support auto-differntiation, the indicator is\n replaced with a sigmoid function with temperature parameter `tau`.\n\n `qPI(X) = P(max Y >= best_f), Y ~ f(X), X = (x_1,...,x_q)`\n\n Example:\n >>> model = SingleTaskGP(train_X, train_Y)\n >>> best_f = train_Y.max()[0]\n >>> sampler = SobolQMCNormalSampler(1000)\n >>> qPI = qProbabilityOfImprovement(model, best_f, sampler)\n >>> qpi = qPI(test_X)\n \"\"\"\n\n def __init__(\n self,\n model: Model,\n best_f: Union[float, Tensor],\n sampler: Optional[MCSampler] = None,\n objective: Optional[MCAcquisitionObjective] = None,\n X_pending: Optional[Tensor] = None,\n tau: float = 1e-3,\n ) -> None:\n r\"\"\"q-Probability of Improvement.\n\n Args:\n model: A fitted model.\n best_f: The best objective value observed so far (assumed noiseless).\n sampler: The sampler used to draw base samples. Defaults to\n `SobolQMCNormalSampler(num_samples=500, collapse_batch_dims=True)`\n objective: The MCAcquisitionObjective under which the samples are\n evaluated. Defaults to `IdentityMCObjective()`.\n X_pending: A `m x d`-dim Tensor of `m` design points that have\n points that have been submitted for function evaluation\n but have not yet been evaluated. Concatenated into X upon\n forward call. Copied and set to have no gradient.\n tau: The temperature parameter used in the sigmoid approximation\n of the step function. Smaller values yield more accurate\n approximations of the function, but result in gradients\n estimates with higher variance.\n \"\"\"\n super().__init__(\n model=model, sampler=sampler, objective=objective, X_pending=X_pending\n )\n if not torch.is_tensor(best_f):\n best_f = torch.tensor(float(best_f))\n self.register_buffer(\"best_f\", best_f)\n if not torch.is_tensor(tau):\n tau = torch.tensor(float(tau))\n self.register_buffer(\"tau\", tau)\n\n @concatenate_pending_points\n @t_batch_mode_transform()\n def forward(self, X: Tensor) -> Tensor:\n r\"\"\"Evaluate qProbabilityOfImprovement on the candidate set `X`.\n\n Args:\n X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim\n design points each.\n\n Returns:\n A `(b)`-dim Tensor of Probability of Improvement values at the given\n design points `X`.\n \"\"\"\n posterior = self.model.posterior(X)\n samples = self.sampler(posterior)\n obj = self.objective(samples)\n max_obj = obj.max(dim=-1)[0]\n val = torch.sigmoid((max_obj - self.best_f) / self.tau).mean(dim=0)\n return val\n\n\nclass qSimpleRegret(MCAcquisitionFunction):\n r\"\"\"MC-based batch Simple Regret.\n\n Samples from the joint posterior over the q-batch and computes the simple\n regret.\n\n `qSR(X) = E(max Y), Y ~ f(X), X = (x_1,...,x_q)`\n\n Example:\n >>> model = SingleTaskGP(train_X, train_Y)\n >>> sampler = SobolQMCNormalSampler(1000)\n >>> qSR = qSimpleRegret(model, sampler)\n >>> qsr = qSR(test_X)\n \"\"\"\n\n @concatenate_pending_points\n @t_batch_mode_transform()\n def forward(self, X: Tensor) -> Tensor:\n r\"\"\"Evaluate qSimpleRegret on the candidate set `X`.\n\n Args:\n X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim\n design points each.\n\n Returns:\n A `(b)`-dim Tensor of Simple Regret values at the given design\n points `X`.\n \"\"\"\n posterior = self.model.posterior(X)\n samples = self.sampler(posterior)\n obj = self.objective(samples)\n val = obj.max(dim=-1)[0].mean(dim=0)\n return val\n\n\nclass qUpperConfidenceBound(MCAcquisitionFunction):\n r\"\"\"MC-based batch Upper Confidence Bound.\n\n Uses a reparameterization to extend UCB to qUCB for q > 1 (See Appendix A\n of [Wilson2017reparam].)\n\n `qUCB = E(max(mu + |Y_tilde - mu|))`, where `Y_tilde ~ N(mu, beta pi/2 Sigma)`\n and `f(X)` has distribution `N(mu, Sigma)`.\n\n Example:\n >>> model = SingleTaskGP(train_X, train_Y)\n >>> sampler = SobolQMCNormalSampler(1000)\n >>> qUCB = qUpperConfidenceBound(model, 0.1, sampler)\n >>> qucb = qUCB(test_X)\n \"\"\"\n\n def __init__(\n self,\n model: Model,\n beta: float,\n sampler: Optional[MCSampler] = None,\n objective: Optional[MCAcquisitionObjective] = None,\n X_pending: Optional[Tensor] = None,\n ) -> None:\n r\"\"\"q-Upper Confidence Bound.\n\n Args:\n model: A fitted model.\n beta: Controls tradeoff between mean and standard deviation in UCB.\n sampler: The sampler used to draw base samples. Defaults to\n `SobolQMCNormalSampler(num_samples=500, collapse_batch_dims=True)`\n objective: The MCAcquisitionObjective under which the samples are\n evaluated. Defaults to `IdentityMCObjective()`.\n X_pending: A `m x d`-dim Tensor of `m` design points that have\n points that have been submitted for function evaluation\n but have not yet been evaluated. Concatenated into X upon\n forward call. Copied and set to have no gradient.\n \"\"\"\n super().__init__(\n model=model, sampler=sampler, objective=objective, X_pending=X_pending\n )\n self.beta_prime = math.sqrt(beta * math.pi / 2)\n\n @concatenate_pending_points\n @t_batch_mode_transform()\n def forward(self, X: Tensor) -> Tensor:\n r\"\"\"Evaluate qUpperConfidenceBound on the candidate set `X`.\n\n Args:\n X: A `(b) x q x d`-dim Tensor of `(b)` t-batches with `q` `d`-dim\n design points each.\n\n Returns:\n A `(b)`-dim Tensor of Upper Confidence Bound values at the given\n design points `X`.\n \"\"\"\n posterior = self.model.posterior(X)\n samples = self.sampler(posterior)\n obj = self.objective(samples)\n mean = obj.mean(dim=0)\n ucb_samples = mean + self.beta_prime * (obj - mean).abs()\n return ucb_samples.max(dim=-1)[0].mean(dim=0)\n" ]
[ [ "torch.sigmoid", "torch.is_tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
erialc-cal/NLP-FOMC
[ "2a8ad113a87e79f5d7beefa6cfd4653f445c92d5", "2a8ad113a87e79f5d7beefa6cfd4653f445c92d5" ]
[ "RA_project/code_python/image_score_posi.py", "LDA_qje/QJE_prep.py" ]
[ "import pandas as pd\nimport datetime\nimport matplotlib.pyplot as plt\nimport ast\nfrom gensim.parsing.preprocessing import STOPWORDS\nfrom nltk.corpus import stopwords\nfrom collections import defaultdict\nfrom nltk.stem import WordNetLemmatizer \nimport datetime\n\n\n\nstop_words = stopwords.words('english')\nlemmatizer = WordNetLemmatizer() \n\n\n\n\"\"\"\nDates and dico\n\"\"\"\n\ndf_sentiment = pd.read_excel('/Users/etiennelenaour/Desktop/Stage/vocab_sentiment.xlsx')\n\nproject_directory = '/Users/etiennelenaour/Desktop/Stage/'\nl_month = ['January','February','March','April','May','June','July','August','September','October','November','December']\nl_dates = list()\n\n\nwith open ('/Users/etiennelenaour/Desktop/Stage/csv_files/dates_fomc.csv', 'r') as doc :\n head = doc.readline()\n dates = doc.readlines()\n dates_to_chg = []\n for line in dates :\n if line.split(',')[1] == ' Y' :\n dates_to_chg += [line.split(';')[0]]\n date = 0\n m = 1 \n for month in l_month :\n if month[:3] == line.split(';')[0].split('/')[0] :\n date += 100 * m\n m += 1\n date += int(line.split(',')[0].split('/')[2])*10000\n date += int(line.split(',')[0].split('/')[1])\n l_dates.append(date)\n\nl_dates_final = l_dates[101:]\n\ndate_to_append = [20120125, 20120425, 20120620, 20120801, 20120913, 20121024, 20121212, 20130130,\n20130130, 20130320, 20130501, 20130619, 20130918, 20131030, 20131218, 20140129,\n20140129, 20140430, 20140618, 20140917, 20141029, 20141217]\n\n\nfor date in date_to_append:\n l_dates_final.append(date)\n\n\"\"\"\ncleaning functions\n\"\"\"\n\n\ndef clean_dico_new_line(dico):\n\n\tnew_dico = defaultdict(lambda: list())\n\n\tfor keys, list_dico in dico.items():\n\n\t\tnew_liste = [string.rstrip(\"\\\\n\").lower() for string in list_dico]\n\t\tnew_dico[keys] = new_liste\n\n\n\treturn new_dico\n\n\ndef remove_stop_word(dico):\n\n\n\tnew_dico = defaultdict(lambda: list())\n\n\tfor keys, list_dico in dico.items():\n\n\t\tfinal_list = list()\n\n\t\tfor ele in list_dico:\n\n\t\t if (ele not in STOPWORDS) and (ele not in stop_words):\n\t\t final_list.append(ele)\n\n\t\tnew_dico[keys] = final_list\n\n\treturn new_dico\n\n\ndef remove_nan_from_list(liste):\n\n\tnew_liste = list()\n\n\tfor ele in liste:\n\t\tif type(ele) == str:\n\t\t\tnew_liste.append(ele)\n\t\telse:\n\t\t\tpass\n\n\treturn new_liste\n\n\n\"\"\"\nScore functions\n\"\"\" \n\nnegative_word_list = [ele.lower() for ele in df_sentiment.Negative.tolist()]\npositive_word_list = [ele.lower() for ele in remove_nan_from_list(df_sentiment.Positive.tolist())]\n\ndef compute_positivity(dico):\n \"\"\" This computes the positivity score of each statement. \n Takes a dictionary with each statement as liste item and the corresponding interlocutor's name in names item \n \n \"\"\" \n dico_score = defaultdict(lambda: list())\n for name, liste in dico.items():\n neg_score = 0\n pos_score = 0\n for ele in liste:\n if ele in negative_word_list:\n neg_score += 1\n elif ele in positive_word_list:\n pos_score += 1\n else:\n pass\n if neg_score < 30 or pos_score < 30:\n pass\n else:\n score = (pos_score - neg_score) / (pos_score + neg_score)\n dico_score[name] = score\n return dico_score\n\n\ndef compute_mean_positivity(dico):\n\n\tneg_score = 0\n\tpos_score = 0\n\n\tfor liste in dico.values():\n\n\t\tfor ele in liste:\n\n\t\t\tif ele in negative_word_list:\n\t\t\t\tneg_score += 1\n\n\t\t\telif ele in positive_word_list:\n\t\t\t\tpos_score += 1\n\n\n\t\t\telse:\n\t\t\t\tpass\n\n\tscore = (pos_score - neg_score) / (pos_score + neg_score)\n\n\treturn score\n\n\"\"\"\nDate function\n\"\"\"\n\n\ndef from_int_dates(integ):\n string = str(integ)\n new_string = string[0]+ string[1] + string[2] + string[3] + \"/\" + string[4] + string[5] + \"/\" + string[6] + string[7]\n\n return datetime.datetime.strptime(new_string, \"%Y/%m/%d\") \n\n\n\"\"\"\nplot positivity\n\"\"\"\n\ndef plot_positivity_persons(date, dico_score, score_moyen):\n\n list_score = list()\n list_names = list()\n\n for name, score in dico_score.items():\n list_score.append(score)\n list_names.append(name)\n\n\n plt.bar(list_names, list_score, color='r')\n plt.grid()\n plt.xticks(rotation=90)\n plt.text(-1, 0, date, horizontalalignment='left', verticalalignment='top', fontweight='bold')\n plt.hlines(y=score_moyen, xmin = -1, xmax = len(list_names))\n plt.ylabel(\"Score de positivité\")\n plt.title(\"Score de positivité des principaux speakers\")\n plt.tight_layout()\n #plt.show()\n plt.savefig(project_directory + 'image_score_posi/' + 'score_posi_' + str(date) + '.png')\n plt.close()\n\n return None\n\n\n\n\"\"\"\nMain\n\"\"\"\n\n\n\n\nfor date in l_dates_final[-50:]:\n\n\twith open (project_directory+'sentences_by_names/'+str(date)+'meeting.txt', 'r') as doc:\n\t\tcontent = doc.readlines()[0]\n\t\t\t \n\tdictionary = ast.literal_eval(content)\n\n\t#Cleaning \n\tdico_clean = remove_stop_word(clean_dico_new_line(dictionary))\n\tplot_positivity_persons(date, compute_positivity(dico_clean), compute_mean_positivity(dico_clean))\n\n\t\n\t\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n", "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 14 15:35:24 2021\n\n@author: Claire He\n Inspired by QJE Hansen article \n\n\"\"\"\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom tqdm import trange \nfrom gensim.parsing.preprocessing import STOPWORDS\nimport seaborn as sns\nimport nltk\nnltk.data.path.append('nltk_data')\nfrom nltk.corpus import stopwords\n\nfrom nltk.stem import WordNetLemmatizer \n\nfrom nltk.tokenize import word_tokenize\n\nfrom itertools import groupby\nstop_words = stopwords.words('english')\nlemmatizer = WordNetLemmatizer() \nimport datetime as dt\n\n#%%\n#### Prepare speech document : \nfile_path ='/Users/h2jw/Documents/GitHub/NLP-FOMC/updated_version_8.csv'\n\ndf = pd.read_csv(file_path, low_memory=True)\ndf.Date = df.Date.astype('datetime64')\ndf1 = df #df[df.Date.dt.year==2015]\n\n#%%\nstatement = df.statement[[230]][230]\n\ntext = word_tokenize(statement)\nPOS = nltk.pos_tag(text)\n\n\n#%% \n\n### VOCABULARY AND MODEL SELECTION\n\n## COLLOQUIAL TRANSFORMATION\n# \" First, we identify collocations, or sequences of words that have\n# a specific meaning. For example, “labor market” corresponds to a\n# single economic concept but is composed of two separate words.\n# To do this we first use the part-of-speech tagger described in\n# Toutanova et al. (2003) to tag every word in the FOMCtranscripts.\n# We then tabulate the frequencies of part-of-speech patterns identified\n# in Justeson and Katz (1995).\n# These are adjective-noun; noun-noun; adjective-adjective-noun; adjectivenoun-\n# noun; noun-adjective-noun; noun-noun-noun; and noun-preposition-noun.\n# Finally we create a single term for two-word (three-word) as likely to correspond to collocations.\n# sequences whose frequency is above 100 (50). \" \n\n\n\n# We try to reproduce this work but we don't use Toutanova's work since it \n# runs on Java but with the nltk POS tagger \n# Original can be found here :\n# >>> https://nlp.stanford.edu/software/tagger.shtml POS TAGGER\n \n\ndef colloquial_transformation(statement):\n \n \"\"\" NLTK POS TAGGER : \n find the list of abbreviations here : https://medium.com/@muddaprince456/categorizing-and-pos-tagging-with-nltk-python-28f2bc9312c3\n \n Js = JJR or JJR or JJS\n Ns = NN or NNP or NNS or NNPS \n \n Colloquial combinations according to Justeson and Katz (1995) :\n - Js+Ns\n - Js*2+Ns\n - Ns*2\n - Js+Ns*2\n - Ns+Js+Ns\n - Ns*3\n - Ns+IN+Ns\n \n Returns list of colloquials\n \"\"\"\n \n text = word_tokenize(statement)\n POS = nltk.pos_tag(text)\n colloquial=[]\n pos_list=[]\n for i, pos in enumerate(POS[1:len(POS)-1]):\n word, tag = pos\n bw, btag = POS[i-1]\n try:\n aw, atag = POS[i+1]\n except:\n pass\n \n if ('NN' in tag) and ('NN' in atag) and ('NN' in btag):\n colloquial.append(bw+' '+word+' '+aw)\n pos_list.append(pos)\n elif ('JJ' in btag) and ('NN' in tag) and ('JJ' in atag):\n colloquial.append(bw+' '+word+' '+aw)\n pos_list.append(pos)\n elif ('NN' in btag) and ('JJ' in tag) and ('NN' in atag):\n colloquial.append(bw+' '+word+' '+aw)\n pos_list.append(pos)\n elif ('JJ' in btag) and ('JJ' in tag) and ('NN' in atag):\n colloquial.append(bw+' '+word+' '+aw)\n pos_list.append(pos)\n elif ('NN' in btag) and ('IN' in tag) and ('NN' in atag):\n colloquial.append(bw+' '+word+' '+aw)\n pos_list.append(pos)\n elif ('NN' in tag) and ('NN' in atag) :\n colloquial.append(word+' '+aw)\n pos_list.append(pos)\n elif ('JJ' in tag) and ('NN' in atag) :\n colloquial.append(word+' '+aw)\n pos_list.append(pos)\n else :\n pass\n return colloquial, pos_list\n\n\ndef get_freq_two_three(statement):\n \"\"\" Gets the colloquials whose frequency are above 100 \"\"\"\n final_col, final_pos = [],[]\n col_list, pos_list =colloquial_transformation(statement)\n freq = [len(list(group)) for key, group in groupby(col_list)]\n for idx in range(len(freq)):\n if freq[idx] >= 100:\n final_col.append(col_list[idx])\n final_pos.append(pos_list[idx])\n else : \n pass\n return final_col, final_pos\n\n\ndef plot_freq_colloquial(list_statement):\n \"\"\" Plots colloquial sentences' frequency distributions \"\"\"\n # Concaténer tous les statements\n statement = \"\"\n for s in list_statement:\n statement += \" \"+s\n col_list, pos_list = colloquial_transformation(statement)\n freq = [len(list(group)) for key, group in groupby(col_list)]\n fig = plt.figure()\n plt.title(\"Colloquial frequency distribution\")\n plt.hist(freq)\n plt.plot()\n\ndef replace_words_by_colloquials(statement):\n \"\"\" Replaces in statement the individual words by colloquial sentences \"\"\"\n text = word_tokenize(statement)\n new_text=\"\"\n col, pos = get_freq_two_three(statement)\n for idx, word in enumerate(text):\n if (idx in pos) :\n ind = pos.index(idx)# two-words colloquial\n if len(col[ind].split())==2:\n new_text+=\" \"+col[ind]\n elif len(col[ind].split())==3: #three-words colloquial\n new_text+= \" \"+col[ind]\n else :\n new_text+= \" \"+word\n return new_text \n \n \n \n# The second step of preprocessing is to remove common stopwords\n# like “the” and “of” that appear frequently in all texts. The\n# third step is to convert the remaining terms into their linguistic\n# roots through stemming so that, for example, “preferences”,\n# “preference,” and “prefers” all become “prefer.” The outcome of\n# stemming need not be an English word. Finally, we follow the\n# suggestion of Blei and Lafferty (2009) and rank the remaining\n# words using term frequency-inverse document frequency (tf-idf), a\n# measure of informativeness that punishes both rare and frequent\n# words. Figure I plots the tf-idf values for each word; based on inspection\n# we drop all terms ranked 9,000 or lower.\n\n\ndef stem_tfidf(statement):\n lemmatize_list=\"\"\n final_list = list()\n intermed_list = statement.lower().split()\n for ele in intermed_list:\n if (ele not in STOPWORDS) and (ele not in stop_words) :\n final_list.append(ele)\n else:\n pass\n final_list = list(filter(None, final_list))\n for ele in final_list:\n lemmatize_list += \" \"+lemmatizer.lemmatize(ele) \n \n return lemmatize_list\n\n\n\n\n#%%\ndf1 = df1.reset_index()\n\nclean=[]\nfor i in trange(len(df1.statement)):\n statement = str(df1.statement.iloc[[i]][i])\n try:\n statement = stem_tfidf(statement)\n except: \n pass\n clean_statement = replace_words_by_colloquials(statement)\n clean.append(clean_statement)\n \ndf1['cleaned']=clean\n#%%\n\n\ndf1[['cleaned','chair_in_charge', 'Date']].to_csv('clean_statements.csv')\n\n" ]
[ [ "pandas.read_excel", "matplotlib.pyplot.tight_layout", "matplotlib.pyplot.title", "matplotlib.pyplot.grid", "matplotlib.pyplot.bar", "matplotlib.pyplot.close", "matplotlib.pyplot.text", "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel" ], [ "pandas.read_csv", "matplotlib.pyplot.title", "matplotlib.pyplot.plot", "matplotlib.pyplot.hist", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
tszumowski/lightning-flash
[ "d094fee4065d3d8d1337eed451041ee17fdf50aa" ]
[ "flash_examples/object_detection.py" ]
[ "# Copyright The PyTorch Lightning team.\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.\nimport torch\n\nimport flash\nfrom flash.core.data.utils import download_data\nfrom flash.image import ObjectDetectionData, ObjectDetector\n\n# 1. Create the DataModule\n# Dataset Credit: https://www.kaggle.com/ultralytics/coco128\ndownload_data(\"https://github.com/zhiqwang/yolov5-rt-stack/releases/download/v0.3.0/coco128.zip\", \"data/\")\n\ndatamodule = ObjectDetectionData.from_coco(\n train_folder=\"data/coco128/images/train2017/\",\n train_ann_file=\"data/coco128/annotations/instances_train2017.json\",\n val_split=0.1,\n batch_size=2,\n)\n\n# 2. Build the task\nmodel = ObjectDetector(model=\"retinanet\", num_classes=datamodule.num_classes)\n\n# 3. Create the trainer and finetune the model\ntrainer = flash.Trainer(max_epochs=3, gpus=torch.cuda.device_count())\ntrainer.finetune(model, datamodule=datamodule)\n\n# 4. Detect objects in a few images!\npredictions = model.predict(\n [\n \"data/coco128/images/train2017/000000000625.jpg\",\n \"data/coco128/images/train2017/000000000626.jpg\",\n \"data/coco128/images/train2017/000000000629.jpg\",\n ]\n)\nprint(predictions)\n\n# 5. Save the model!\ntrainer.save_checkpoint(\"object_detection_model.pt\")\n" ]
[ [ "torch.cuda.device_count" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
MPGek/client
[ "541d760c5cb8776b1ad5fcf1362d7382811cbc61" ]
[ "wandb/fastai/__init__.py" ]
[ "'''\nThis module hooks fast.ai Learners to Weights & Biases through a callback.\nRequested logged data can be configured through the callback constructor.\n\nExamples:\n WandbCallback can be used when initializing the Learner::\n\n ```\n from wandb.fastai import WandbCallback\n [...]\n learn = Learner(data, ..., callback_fns=WandbCallback)\n learn.fit(epochs)\n ```\n\n Custom parameters can be given using functools.partial::\n\n ```\n from wandb.fastai import WandbCallback\n from functools import partial\n [...]\n learn = Learner(data, ..., callback_fns=partial(WandbCallback, ...))\n learn.fit(epochs)\n ```\n\n Finally, it is possible to use WandbCallback only when starting\n training. In this case it must be instantiated::\n\n ```\n learn.fit(..., callbacks=WandbCallback(learn))\n ```\n\n or, with custom parameters::\n\n ```\n learn.fit(..., callbacks=WandbCallback(learn, ...))\n ```\n'''\nimport wandb\nimport fastai\nfrom fastai.callbacks import TrackerCallback\nfrom pathlib import Path\nimport random\ntry:\n import matplotlib\n matplotlib.use('Agg') # non-interactive backend (avoid tkinter issues)\n import matplotlib.pyplot as plt\nexcept:\n print('Warning: matplotlib required if logging sample image predictions')\n\n\nclass WandbCallback(TrackerCallback):\n \"\"\"\n Automatically saves model topology, losses & metrics.\n Optionally logs weights, gradients, sample predictions and best trained model.\n\n Args:\n learn (fastai.basic_train.Learner): the fast.ai learner to hook.\n log (str): \"gradients\", \"parameters\", \"all\", or None. Losses & metrics are always logged.\n save_model (bool): save model at the end of each epoch. It will also load best model at the end of training.\n monitor (str): metric to monitor for saving best model. None uses default TrackerCallback monitor value.\n mode (str): \"auto\", \"min\" or \"max\" to compare \"monitor\" values and define best model.\n input_type (str): \"images\" or None. Used to display sample predictions.\n validation_data (list): data used for sample predictions if input_type is set.\n predictions (int): number of predictions to make if input_type is set and validation_data is None.\n seed (int): initialize random generator for sample predictions if input_type is set and validation_data is None.\n \"\"\"\n\n # Record if watch has been called previously (even in another instance)\n _watch_called = False\n\n def __init__(self,\n learn,\n log=\"gradients\",\n save_model=True,\n monitor=None,\n mode='auto',\n input_type=None,\n validation_data=None,\n predictions=36,\n seed=12345):\n\n # Check if wandb.init has been called\n if wandb.run is None:\n raise ValueError(\n 'You must call wandb.init() before WandbCallback()')\n\n # Adapted from fast.ai \"SaveModelCallback\"\n if monitor is None:\n # use default TrackerCallback monitor value\n super().__init__(learn, mode=mode)\n else:\n super().__init__(learn, monitor=monitor, mode=mode)\n self.save_model = save_model\n self.model_path = Path(wandb.run.dir) / 'bestmodel.pth'\n\n self.log = log\n self.input_type = input_type\n self.best = None\n\n # Select items for sample predictions to see evolution along training\n self.validation_data = validation_data\n if input_type and not self.validation_data:\n wandbRandom = random.Random(seed) # For repeatability\n predictions = min(predictions, len(learn.data.valid_ds))\n indices = wandbRandom.sample(range(len(learn.data.valid_ds)),\n predictions)\n self.validation_data = [learn.data.valid_ds[i] for i in indices]\n\n def on_train_begin(self, **kwargs):\n \"Call watch method to log model topology, gradients & weights\"\n\n # Set self.best, method inherited from \"TrackerCallback\" by \"SaveModelCallback\"\n super().on_train_begin()\n\n # Ensure we don't call \"watch\" multiple times\n if not WandbCallback._watch_called:\n WandbCallback._watch_called = True\n\n # Logs model topology and optionally gradients and weights\n wandb.watch(self.learn.model, log=self.log)\n\n def on_epoch_end(self, epoch, smooth_loss, last_metrics, **kwargs):\n \"Logs training loss, validation loss and custom metrics & log prediction samples & save model\"\n\n if self.save_model:\n # Adapted from fast.ai \"SaveModelCallback\"\n current = self.get_monitor_value()\n if current is not None and self.operator(current, self.best):\n print(\n 'Better model found at epoch {} with {} value: {}.'.format(\n epoch, self.monitor, current))\n self.best = current\n\n # Save within wandb folder\n with self.model_path.open('wb') as model_file:\n self.learn.save(model_file)\n\n # Log sample predictions if learn.predict is available\n if self.validation_data:\n try:\n self._wandb_log_predictions()\n except FastaiError as e:\n wandb.termwarn(e.message)\n self.validation_data = None # prevent from trying again on next loop\n except Exception as e:\n wandb.termwarn(\"Unable to log prediction samples.\\n{}\".format(e))\n self.validation_data=None # prevent from trying again on next loop\n\n # Log losses & metrics\n # Adapted from fast.ai \"CSVLogger\"\n logs = {\n name: stat\n for name, stat in list(\n zip(self.learn.recorder.names, [epoch, smooth_loss] +\n last_metrics))\n }\n wandb.log(logs)\n\n def on_train_end(self, **kwargs):\n \"Load the best model.\"\n\n if self.save_model:\n # Adapted from fast.ai \"SaveModelCallback\"\n if self.model_path.is_file():\n with self.model_path.open('rb') as model_file:\n self.learn.load(model_file, purge=False)\n print('Loaded best saved model from {}'.format(\n self.model_path))\n\n def _wandb_log_predictions(self):\n \"Log prediction samples\"\n\n pred_log = []\n\n for x, y in self.validation_data:\n try:\n pred=self.learn.predict(x)\n except:\n raise FastaiError('Unable to run \"predict\" method from Learner to log prediction samples.')\n\n # scalar -> likely to be a category\n if not pred[1].shape:\n pred_log.append(\n wandb.Image(\n x.data,\n caption='Ground Truth: {}\\nPrediction: {}'.format(\n y, pred[0])))\n\n # most vision datasets have a \"show\" function we can use\n elif hasattr(x, \"show\"):\n # log input data\n pred_log.append(\n wandb.Image(x.data, caption='Input data', grouping=3))\n\n # log label and prediction\n for im, capt in ((pred[0], \"Prediction\"),\n (y, \"Ground Truth\")):\n # Resize plot to image resolution\n # from https://stackoverflow.com/a/13714915\n my_dpi = 100\n fig = plt.figure(frameon=False, dpi=my_dpi)\n h, w = x.size\n fig.set_size_inches(w / my_dpi, h / my_dpi)\n ax = plt.Axes(fig, [0., 0., 1., 1.])\n ax.set_axis_off()\n fig.add_axes(ax)\n\n # Superpose label or prediction to input image\n x.show(ax=ax, y=im)\n pred_log.append(wandb.Image(fig, caption=capt))\n plt.close(fig)\n\n # likely to be an image\n elif hasattr(y, \"shape\") and (\n (len(y.shape) == 2) or\n (len(y.shape) == 3 and y.shape[0] in [1, 3, 4])):\n\n pred_log.extend([\n wandb.Image(x.data, caption='Input data', grouping=3),\n wandb.Image(pred[0].data, caption='Prediction'),\n wandb.Image(y.data, caption='Ground Truth')\n ])\n\n # we just log input data\n else:\n pred_log.append(wandb.Image(x.data, caption='Input data'))\n\n wandb.log({\"Prediction Samples\": pred_log}, commit=False)\n\n\nclass FastaiError(wandb.Error):\n pass\n" ]
[ [ "matplotlib.use", "matplotlib.pyplot.Axes", "matplotlib.pyplot.close", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
garg-aayush/devito
[ "b1e8fffdee7d6b556ff19a372d69ed1aebee675a" ]
[ "devito/passes/clusters/aliases.py" ]
[ "from collections import OrderedDict, defaultdict, namedtuple\nfrom functools import partial\nfrom itertools import groupby\n\nfrom cached_property import cached_property\nimport numpy as np\n\nfrom devito.ir import (SEQUENTIAL, PARALLEL, PARALLEL_IF_PVT, ROUNDABLE, DataSpace,\n Forward, IterationInstance, IterationSpace, Interval,\n IntervalGroup, LabeledVector, Context, detect_accesses,\n build_intervals, normalize_properties)\nfrom devito.passes.clusters.utils import timed_pass\nfrom devito.symbolics import (Uxmapper, compare_ops, estimate_cost, q_constant,\n q_leaf, retrieve_indexed, search, uxreplace)\nfrom devito.tools import as_tuple, flatten, split\nfrom devito.types import (Array, TempFunction, Eq, Symbol, ModuloDimension,\n CustomDimension, IncrDimension)\n\n__all__ = ['cire']\n\n\n@timed_pass(name='cire')\ndef cire(clusters, mode, sregistry, options, platform):\n \"\"\"\n Cross-iteration redundancies elimination.\n\n Parameters\n ----------\n cluster : Cluster\n Input Cluster, subject of the optimization pass.\n mode : str\n The transformation mode. Accepted: ['invariants', 'sops'].\n * 'invariants' is for sub-expressions that are invariant w.r.t. one or\n more Dimensions.\n * 'sops' stands for sums-of-products, that is redundancies are searched\n across all expressions in sum-of-product form.\n sregistry : SymbolRegistry\n The symbol registry, to create unique temporary names.\n options : dict\n The optimization options.\n Accepted: ['min-storage', 'cire-maxpar', 'cire-rotate', 'cire-maxalias'].\n * 'min-storage': if True, the pass will try to minimize the amount of\n storage introduced for the tensor temporaries. This might also reduce\n the operation count. On the other hand, this might affect fusion and\n therefore data locality. Defaults to False (legacy).\n * 'cire-maxpar': if True, privilege parallelism over working set size,\n that is the pass will try to create as many parallel loops as possible,\n even though this will require more space (Dimensions) for the temporaries.\n Defaults to False.\n * 'cire-rotate': if True, the pass will use modulo indexing for the\n outermost Dimension iterated over by the temporaries. This will sacrifice\n a parallel loop for a reduced working set size. Defaults to False (legacy).\n * 'cire-maxalias': if True, capture the largest redundancies. This will\n minimize the flop count while maximizing the number of tensor temporaries,\n thus increasing the working set size.\n platform : Platform\n The underlying platform. Used to optimize the shape of the introduced\n tensor symbols.\n\n Examples\n --------\n 1) 'invariants'. Here's an expensive expression invariant w.r.t. `t`\n\n t0 = (cos(a[x,y,z])*sin(b[x,y,z]))*c[t,x,y,z]\n\n which after CIRE becomes\n\n t1[x,y,z] = cos(a[x,y,z])*sin(b[x,y,z])\n t0 = t1[x,y,z]*c[t,x,y,z]\n\n 2) 'sops'. Below we see two expressions in sum-of-product form (in this\n case, the sum degenerates to a single product).\n\n t0 = 2.0*a[x,y,z]*b[x,y,z]\n t1 = 3.0*a[x,y,z+1]*b[x,y,z+1]\n\n CIRE detects that these two expressions are actually redundant and rewrites\n them as:\n\n t2[x,y,z] = a[x,y,z]*b[x,y,z]\n t0 = 2.0*t2[x,y,z]\n t1 = 3.0*t2[x,y,z+1]\n \"\"\"\n if mode == 'invariants':\n space = ('inv-basic', 'inv-compound')\n elif mode in ('sops',):\n space = (mode,)\n else:\n assert False, \"Unknown CIRE mode `%s`\" % mode\n\n processed = []\n for c in clusters:\n # We don't care about sparse Clusters. Their computational cost is\n # negligible and processing all of them would only increase compilation\n # time and potentially make the generated code more chaotic\n if not c.is_dense:\n processed.append(c)\n continue\n\n # Some of the CIRE transformers need to look inside all scopes\n # surrounding `c` to perform data dependencies analysis\n context = Context(c).process(clusters)\n\n # Applying CIRE may change `c` as well as creating one or more new Clusters\n transformed = _cire(c, context, space, sregistry, options, platform)\n\n processed.extend(transformed)\n\n return processed\n\n\ndef _cire(cluster, context, space, sregistry, options, platform):\n # Construct the space of variants\n variants = [modes[mode](sregistry, options).make_schedule(cluster, context)\n for mode in space]\n if not any(i.schedule for i in variants):\n return [cluster]\n\n # Pick the variant with the highest score, that is the variant with the best\n # trade-off between operation count reduction and working set size increase\n schedule, exprs = pick_best(variants)\n\n # Schedule -> [Clusters]\n schedule = optimize_schedule(cluster, schedule, platform, sregistry, options)\n clusters, subs = lower_schedule(cluster, schedule, sregistry, options)\n clusters.append(rebuild(cluster, exprs, subs, schedule))\n\n return clusters\n\n\nclass Cire(object):\n\n \"\"\"\n Base class for CIRE transformers.\n \"\"\"\n\n optname = None\n mode = None\n\n def __init__(self, sregistry, options):\n self.sregistry = sregistry\n\n self._opt_minstorage = options['min-storage']\n self._opt_mincost = options['cire-mincost'][self.optname]\n self._opt_maxpar = options['cire-maxpar']\n self._opt_maxalias = options['cire-maxalias']\n\n def make_schedule(self, cluster, context):\n # Capture aliases within `exprs`\n aliases = AliasMapper()\n score = 0\n exprs = cluster.exprs\n ispace = cluster.ispace\n for n in range(self._nrepeats(cluster)):\n # Extract potentially aliasing expressions\n mapper = self._extract(exprs, context, n)\n\n # Search aliasing expressions\n found = collect(mapper.extracted, ispace, self._opt_minstorage)\n\n # Choose the aliasing expressions with a good flops/memory trade-off\n exprs, chosen, pscore = choose(found, exprs, mapper, self._selector)\n aliases.update(chosen)\n score += pscore\n\n # AliasMapper -> Schedule\n schedule = lower_aliases(cluster, aliases, self._in_writeto, self._opt_maxpar)\n\n # The actual score is a 2-tuple <flop-reduction-score, workin-set-score>\n score = (score, len(aliases))\n\n return SpacePoint(schedule, exprs, score)\n\n def _make_symbol(self):\n return Symbol(name=self.sregistry.make_name('dummy'))\n\n def _nrepeats(self, cluster):\n raise NotImplementedError\n\n def _extract(self, exprs, context, n):\n raise NotImplementedError\n\n def _in_writeto(self, dim, cluster):\n raise NotImplementedError\n\n def _selector(self, e, naliases):\n raise NotImplementedError\n\n\nclass CireInvariants(Cire):\n\n optname = 'invariants'\n\n def _nrepeats(self, cluster):\n return 1\n\n def _rule(self, e):\n return (e.is_Function or\n (e.is_Pow and e.exp.is_Number and e.exp < 1))\n\n def _extract(self, exprs, context, n):\n mapper = Uxmapper()\n for prefix, clusters in context.items():\n if not prefix:\n continue\n\n exclude = set().union(*[c.scope.writes for c in clusters])\n exclude.add(prefix[-1].dim)\n\n for e in exprs:\n for i in search(e, self._rule, 'all', 'bfs_first_hit'):\n if {a.function for a in i.free_symbols} & exclude:\n continue\n mapper.add(i, self._make_symbol)\n\n return mapper\n\n def _in_writeto(self, dim, cluster):\n return PARALLEL in cluster.properties[dim]\n\n def _selector(self, e, naliases):\n if all(i.function.is_Symbol for i in e.free_symbols):\n # E.g., `dt**(-2)`\n mincost = self._opt_mincost['scalar']\n else:\n mincost = self._opt_mincost['tensor']\n return estimate_cost(e, True)*naliases // mincost\n\n\nclass CireInvariantsBasic(CireInvariants):\n\n mode = 'inv-basic'\n\n\nclass CireInvariantsCompound(CireInvariants):\n\n mode = 'inv-compound'\n\n def _extract(self, exprs, context, n):\n extracted = super()._extract(exprs, context, n).extracted\n\n rule = lambda e: any(a in extracted for a in e.args)\n\n mapper = Uxmapper()\n for e in exprs:\n for i in search(e, rule, 'all', 'dfs'):\n if not i.is_commutative:\n continue\n\n key = lambda a: a in extracted\n terms, others = split(i.args, key)\n\n mapper.add(i, self._make_symbol, terms)\n\n return mapper\n\n\nclass CireSOPS(Cire):\n\n optname = 'sops'\n mode = 'sops'\n\n def _nrepeats(self, cluster):\n # The `nrepeats` is calculated such that we analyze all potential derivatives\n # in `cluster`\n return potential_max_deriv_order(cluster.exprs)\n\n def _extract(self, exprs, context, n):\n # Forbid CIRE involving Dimension-independent dependencies, e.g.:\n # r0 = ...\n # u[x, y] = ... r0*a[x, y] ...\n # NOTE: if one uses the DSL in a conventional way and sticks to the default\n # compilation pipelines where CSE always happens after CIRE, then `exclude`\n # will always be empty\n exclude = {i.source.indexed for i in context[None].scope.d_flow.independent()}\n\n mapper = Uxmapper()\n for e in exprs:\n for i in search_potential_deriv(e, n):\n if i.free_symbols & exclude:\n continue\n\n key = lambda a: a.is_Add\n terms, others = split(i.args, key)\n\n if self._opt_maxalias:\n # Treat `e` as an FD expression and pull out the derivative\n # coefficient from `i`\n # Note: typically derivative coefficients are numbers, but\n # sometimes they could be provided in symbolic form through an\n # arbitrary Function. In the latter case, we rely on the\n # heuristic that such Function's basically never span the whole\n # grid, but rather a single Grid dimension (e.g., `c[z, n]` for a\n # stencil of diameter `n` along `z`)\n if e.grid is not None and terms:\n key = partial(maybe_coeff_key, e.grid)\n others, more_terms = split(others, key)\n terms += more_terms\n\n mapper.add(i, self._make_symbol, terms)\n\n return mapper\n\n def _in_writeto(self, dim, cluster):\n return self._opt_maxpar and PARALLEL in cluster.properties[dim]\n\n def _selector(self, e, naliases):\n if naliases <= 1:\n return 0\n else:\n return estimate_cost(e, True)*naliases // self._opt_mincost\n\n\nmodes = {\n CireInvariantsBasic.mode: CireInvariantsBasic,\n CireInvariantsCompound.mode: CireInvariantsCompound,\n CireSOPS.mode: CireSOPS\n}\n\n\ndef collect(extracted, ispace, min_storage):\n \"\"\"\n Find groups of aliasing expressions.\n\n We shall introduce the following (loose) terminology:\n\n * A ``terminal`` is the leaf of a mathematical operation. Terminals\n can be numbers (n), literals (l), or Indexeds (I).\n * ``R`` is the relaxation operator := ``R(n) = n``, ``R(l) = l``,\n ``R(I) = J``, where ``J`` has the same base as ``I`` but with all\n offsets stripped away. For example, ``R(a[i+2,j-1]) = a[i,j]``.\n * A ``relaxed expression`` is an expression in which all of the\n terminals are relaxed.\n\n Now we define the concept of aliasing. We say that an expression A\n aliases an expression B if:\n\n * ``R(A) == R(B)``\n * all pairwise Indexeds in A and B access memory locations at a\n fixed constant distance along each Dimension.\n\n For example, consider the following expressions:\n\n * a[i+1] + b[i+1]\n * a[i+1] + b[j+1]\n * a[i] + c[i]\n * a[i+2] - b[i+2]\n * a[i+2] + b[i]\n * a[i-1] + b[i-1]\n\n Out of the expressions above, the following alias to `a[i] + b[i]`:\n\n * a[i+1] + b[i+1] : same operands and operations, distance along i: 1\n * a[i-1] + b[i-1] : same operands and operations, distance along i: -1\n\n Whereas the following do not:\n\n * a[i+1] + b[j+1] : because at least one index differs\n * a[i] + c[i] : because at least one of the operands differs\n * a[i+2] - b[i+2] : because at least one operation differs\n * a[i+2] + b[i] : because the distances along ``i`` differ (+2 and +0)\n \"\"\"\n # Find the potential aliases\n found = []\n for expr in extracted:\n assert not expr.is_Equality\n\n indexeds = retrieve_indexed(expr)\n\n bases = []\n offsets = []\n for i in indexeds:\n ii = IterationInstance(i)\n if ii.is_irregular:\n break\n\n base = []\n offset = []\n for e, ai in zip(ii, ii.aindices):\n if q_constant(e):\n base.append(e)\n else:\n base.append(ai)\n offset.append((ai, e - ai))\n bases.append(tuple(base))\n offsets.append(LabeledVector(offset))\n\n if not indexeds or len(bases) == len(indexeds):\n found.append(Candidate(expr, ispace, indexeds, bases, offsets))\n\n # Create groups of aliasing expressions\n mapper = OrderedDict()\n unseen = list(found)\n while unseen:\n c = unseen.pop(0)\n group = [c]\n for u in list(unseen):\n # Is the arithmetic structure of `c` and `u` equivalent ?\n if not compare_ops(c.expr, u.expr):\n continue\n\n # Is `c` translated w.r.t. `u` ?\n if not c.translated(u):\n continue\n\n group.append(u)\n unseen.remove(u)\n group = Group(group)\n\n if min_storage:\n k = group.dimensions_translated\n else:\n k = group.dimensions\n mapper.setdefault(k, []).append(group)\n\n aliases = AliasMapper()\n queue = list(mapper.values())\n while queue:\n groups = queue.pop(0)\n\n while groups:\n # For each Dimension, determine the Minimum Intervals (MI) spanning\n # all of the Groups diameters\n # Example: x's largest_diameter=2 => [x[-2,0], x[-1,1], x[0,2]]\n # Note: Groups that cannot evaluate their diameter are dropped\n mapper = defaultdict(int)\n for g in list(groups):\n try:\n mapper.update({d: max(mapper[d], v) for d, v in g.diameter.items()})\n except ValueError:\n groups.remove(g)\n intervalss = {d: make_rotations_table(d, v) for d, v in mapper.items()}\n\n # For each Group, find a rotation that is compatible with a given MI\n mapper = {}\n\n for d, intervals in intervalss.items():\n # Not all groups may access all dimensions\n # Example: `d=t` and groups=[Group(...[t, x]...), Group(...[time, x]...)]\n impacted = [g for g in groups if d in g.dimensions]\n\n for interval in list(intervals):\n found = {g: g.find_rotation_distance(d, interval) for g in impacted}\n if all(distance is not None for distance in found.values()):\n # `interval` is OK !\n mapper[interval] = found\n break\n\n if len(mapper) == len(intervalss):\n break\n\n # Try again with fewer groups\n # Heuristic: first try retaining the larger ones\n smallest = len(min(groups, key=len))\n fallback = groups\n groups, remainder = split(groups, lambda g: len(g) > smallest)\n if groups:\n queue.append(remainder)\n elif len(remainder) > 1:\n # No luck with the heuristic, e.g. there are two groups\n # and both have same `len`\n queue.append(fallback[1:])\n groups = [fallback.pop(0)]\n else:\n break\n\n for g in groups:\n c = g.pivot\n distances = defaultdict(int, [(i.dim, v.get(g)) for i, v in mapper.items()])\n\n # Create the basis alias\n offsets = [LabeledVector([(l, v[l] + distances[l]) for l in v.labels])\n for v in c.offsets]\n subs = {i: i.function[[l + v.fromlabel(l, 0) for l in b]]\n for i, b, v in zip(c.indexeds, c.bases, offsets)}\n alias = uxreplace(c.expr, subs)\n\n # All aliased expressions\n aliaseds = [extracted[i.expr] for i in g]\n\n # Distance of each aliased expression from the basis alias\n distances = []\n for i in g:\n distance = [o.distance(v) for o, v in zip(i.offsets, offsets)]\n distance = [(d, set(v)) for d, v in LabeledVector.transpose(*distance)]\n distances.append(LabeledVector([(d, v.pop()) for d, v in distance]))\n\n aliases.add(alias, list(mapper), aliaseds, distances)\n\n return aliases\n\n\ndef choose(aliases, exprs, mapper, selector):\n \"\"\"\n Analyze the detected aliases and, after applying a cost model to rule out\n the aliases with a bad flops/memory trade-off, inject them into the original\n expressions.\n \"\"\"\n tot = 0\n retained = AliasMapper()\n\n # Pass 1: a set of aliasing expressions is retained only if its cost\n # exceeds the mode's threshold\n candidates = OrderedDict()\n aliaseds = []\n others = []\n for e, v in aliases.items():\n score = selector(e, len(v.aliaseds))\n if score > 0:\n candidates[e] = score\n aliaseds.extend(v.aliaseds)\n else:\n others.append(e)\n\n # Do not waste time if unneccesary\n if not candidates:\n return exprs, retained, tot\n\n # Project the candidate aliases into exprs to determine what the new\n # working set would be\n mapper = {k: v for k, v in mapper.items() if v.free_symbols & set(aliaseds)}\n templated = [uxreplace(e, mapper) for e in exprs]\n\n # Pass 2: a set of aliasing expressions is retained only if the tradeoff\n # between operation count reduction and working set increase is favorable\n owset = wset(others + templated)\n for e, v in aliases.items():\n try:\n score = candidates[e]\n except KeyError:\n score = 0\n if score > 1 or \\\n score == 1 and max(len(wset(e)), 1) > len(wset(e) & owset):\n retained[e] = v\n tot += score\n\n # Do not waste time if unneccesary\n if not retained:\n return exprs, retained, tot\n\n # Substitute the chosen aliasing sub-expressions\n mapper = {k: v for k, v in mapper.items() if v.free_symbols & set(retained.aliaseds)}\n exprs = [uxreplace(e, mapper) for e in exprs]\n\n return exprs, retained, tot\n\n\ndef lower_aliases(cluster, aliases, in_writeto, maxpar):\n \"\"\"\n Create a Schedule from an AliasMapper.\n \"\"\"\n dmapper = {}\n processed = []\n for alias, v in aliases.items():\n imapper = {**{i.dim: i for i in v.intervals},\n **{i.dim.parent: i for i in v.intervals if i.dim.is_NonlinearDerived}}\n\n intervals = []\n writeto = []\n sub_iterators = {}\n indicess = [[] for _ in v.distances]\n for i in cluster.ispace.intervals:\n try:\n interval = imapper[i.dim]\n except KeyError:\n # E.g., `x0_blk0` or (`a[y_m+1]` => `y not in imapper`)\n intervals.append(i)\n continue\n\n assert i.stamp >= interval.stamp\n\n if not (writeto or interval != interval.zero() or in_writeto(i.dim, cluster)):\n # The alias doesn't require a temporary Dimension along i.dim\n intervals.append(i)\n continue\n\n assert not i.dim.is_NonlinearDerived\n\n # `i.dim` is necessarily part of the write-to region, so\n # we have to adjust the Interval's stamp. For example, consider\n # `i=x[0,0]<1>` and `interval=x[-4,4]<0>`; here we need to\n # use `<1>` as stamp, which is what appears in `cluster`\n interval = interval.lift(i.stamp)\n\n # We further bump the interval stamp if we were requested to trade\n # fusion for more collapse-parallelism\n interval = interval.lift(interval.stamp + int(maxpar))\n\n writeto.append(interval)\n intervals.append(interval)\n\n if i.dim.is_Incr:\n # Suitable IncrDimensions must be used to avoid OOB accesses.\n # E.g., r[xs][ys][z] => both `xs` and `ys` must be initialized such\n # that all accesses are within bounds. This requires traversing the\n # hierarchy of IncrDimensions to set `xs` (`ys`) in a way that\n # consecutive blocks access consecutive regions in `r` (e.g.,\n # `xs=x0_blk1-x0_blk0` with `blocklevels=2`; `xs=0` with\n # `blocklevels=1`, that is it degenerates in this case)\n try:\n d = dmapper[i.dim]\n except KeyError:\n dd = i.dim.parent\n assert dd.is_Incr\n if dd.parent.is_Incr:\n # An IncrDimension in between IncrDimensions\n m = i.dim.symbolic_min - i.dim.parent.symbolic_min\n else:\n m = 0\n d = dmapper[i.dim] = IncrDimension(\"%ss\" % i.dim.name, i.dim, m,\n dd.symbolic_size, 1, dd.step)\n sub_iterators[i.dim] = d\n else:\n d = i.dim\n\n # Given the iteration `interval`, lower distances to indices\n for distance, indices in zip(v.distances, indicess):\n indices.append(d - interval.lower + distance[interval.dim])\n\n # The alias write-to space\n writeto = IterationSpace(IntervalGroup(writeto), sub_iterators)\n\n # The alias iteration space\n intervals = IntervalGroup(intervals, cluster.ispace.relations)\n ispace = IterationSpace(intervals, cluster.sub_iterators, cluster.directions)\n ispace = ispace.augment(sub_iterators)\n\n processed.append(ScheduledAlias(alias, writeto, ispace, v.aliaseds, indicess))\n\n # The [ScheduledAliases] must be ordered so as to reuse as many of the\n # `cluster`'s IterationIntervals as possible in order to honor the\n # write-to region. Another fundamental reason for ordering is to ensure\n # deterministic code generation\n processed = sorted(processed, key=lambda i: cit(cluster.ispace, i.ispace))\n\n return Schedule(*processed, dmapper=dmapper)\n\n\ndef optimize_schedule(cluster, schedule, platform, sregistry, options):\n \"\"\"\n Rewrite the schedule for performance optimization.\n \"\"\"\n if options['cire-rotate']:\n schedule = _optimize_schedule_rotations(schedule, sregistry)\n\n schedule = _optimize_schedule_padding(cluster, schedule, platform)\n\n return schedule\n\n\ndef _optimize_schedule_rotations(schedule, sregistry):\n \"\"\"\n Transform the schedule such that the tensor temporaries \"rotate\" along\n the outermost Dimension. This trades a parallel Dimension for a smaller\n working set size.\n \"\"\"\n # The rotations Dimension is the outermost\n ridx = 0\n\n rmapper = defaultdict(list)\n processed = []\n for k, group in groupby(schedule, key=lambda i: i.writeto):\n g = list(group)\n\n candidate = k[ridx]\n d = candidate.dim\n try:\n ds = schedule.dmapper[d]\n except KeyError:\n # Can't do anything if `d` isn't an IncrDimension over a block\n processed.extend(g)\n continue\n\n n = candidate.min_size\n assert n > 0\n\n iis = candidate.lower\n iib = candidate.upper\n\n ii = ModuloDimension('%sii' % d, ds, iis, incr=iib)\n cd = CustomDimension(name='%s%s' % (d, d), symbolic_min=ii, symbolic_max=iib,\n symbolic_size=n)\n dsi = ModuloDimension('%si' % ds, cd, cd + ds - iis, n)\n\n mapper = OrderedDict()\n for i in g:\n # Update `indicess` to use `xs0`, `xs1`, ...\n mds = []\n for indices in i.indicess:\n v = indices[ridx]\n try:\n md = mapper[v]\n except KeyError:\n name = sregistry.make_name(prefix='%sr' % d.name)\n md = mapper.setdefault(v, ModuloDimension(name, ds, v, n))\n mds.append(md)\n indicess = [indices[:ridx] + [md] + indices[ridx + 1:]\n for md, indices in zip(mds, i.indicess)]\n\n # Update `writeto` by switching `d` to `dsi`\n intervals = k.intervals.switch(d, dsi).zero(dsi)\n sub_iterators = dict(k.sub_iterators)\n sub_iterators[d] = dsi\n writeto = IterationSpace(intervals, sub_iterators)\n\n # Transform `alias` by adding `i`\n alias = i.alias.xreplace({d: d + cd})\n\n # Extend `ispace` to iterate over rotations\n d1 = writeto[ridx+1].dim # Note: we're by construction in-bounds here\n intervals = IntervalGroup(Interval(cd, 0, 0), relations={(d, cd, d1)})\n rispace = IterationSpace(intervals, {cd: dsi}, {cd: Forward})\n aispace = i.ispace.zero(d)\n aispace = aispace.augment({d: mds + [ii]})\n ispace = IterationSpace.union(rispace, aispace)\n\n processed.append(ScheduledAlias(alias, writeto, ispace, i.aliaseds, indicess))\n\n # Update the rotations mapper\n rmapper[d].extend(list(mapper.values()))\n\n return Schedule(*processed, dmapper=schedule.dmapper, rmapper=rmapper)\n\n\ndef _optimize_schedule_padding(cluster, schedule, platform):\n \"\"\"\n Round up the innermost IterationInterval of the tensor temporaries IterationSpace\n to a multiple of the SIMD vector length. This is not always possible though (it\n depends on how much halo is safely accessible in all read Functions).\n \"\"\"\n processed = []\n for i in schedule:\n try:\n it = i.ispace.itintervals[-1]\n if ROUNDABLE in cluster.properties[it.dim]:\n vl = platform.simd_items_per_reg(cluster.dtype)\n ispace = i.ispace.add(Interval(it.dim, 0, it.interval.size % vl))\n else:\n ispace = i.ispace\n processed.append(ScheduledAlias(i.alias, i.writeto, ispace, i.aliaseds,\n i.indicess))\n except (TypeError, KeyError):\n processed.append(i)\n\n return Schedule(*processed, dmapper=schedule.dmapper, rmapper=schedule.rmapper)\n\n\ndef lower_schedule(cluster, schedule, sregistry, options):\n \"\"\"\n Turn a Schedule into a sequence of Clusters.\n \"\"\"\n ftemps = options['cire-ftemps']\n\n if ftemps:\n make = TempFunction\n else:\n # Typical case -- the user does *not* \"see\" the CIRE-created temporaries\n make = Array\n\n clusters = []\n subs = {}\n for alias, writeto, ispace, aliaseds, indicess in schedule:\n # Basic info to create the temporary that will hold the alias\n name = sregistry.make_name()\n dtype = cluster.dtype\n\n if writeto:\n # The Dimensions defining the shape of Array\n # Note: with SubDimensions, we may have the following situation:\n #\n # for zi = z_m + zi_ltkn; zi <= z_M - zi_rtkn; ...\n # r[zi] = ...\n #\n # Instead of `r[zi - z_m - zi_ltkn]` we have just `r[zi]`, so we'll need\n # as much room as in `zi`'s parent to avoid going OOB\n # Aside from ugly generated code, the reason we do not rather shift the\n # indices is that it prevents future passes to transform the loop bounds\n # (e.g., MPI's comp/comm overlap does that)\n dimensions = [d.parent if d.is_Sub else d for d in writeto.itdimensions]\n\n # The halo must be set according to the size of writeto space\n halo = [(abs(i.lower), abs(i.upper)) for i in writeto]\n\n # The indices used to write into the Array\n indices = []\n for i in writeto:\n try:\n # E.g., `xs`\n sub_iterators = writeto.sub_iterators[i.dim]\n assert len(sub_iterators) == 1\n indices.append(sub_iterators[0])\n except KeyError:\n # E.g., `z` -- a non-shifted Dimension\n indices.append(i.dim - i.lower)\n\n obj = make(name=name, dimensions=dimensions, halo=halo, dtype=dtype)\n expression = Eq(obj[indices], alias)\n\n callback = lambda idx: obj[idx]\n else:\n # Degenerate case: scalar expression\n assert writeto.size == 0\n\n obj = Symbol(name=name, dtype=dtype)\n expression = Eq(obj, alias)\n\n callback = lambda idx: obj\n\n # Create the substitution rules for the aliasing expressions\n subs.update({aliased: callback(indices)\n for aliased, indices in zip(aliaseds, indicess)})\n\n # Construct the `alias` DataSpace\n accesses = detect_accesses(expression)\n parts = {k: IntervalGroup(build_intervals(v)).add(ispace.intervals).relaxed\n for k, v in accesses.items() if k}\n dspace = DataSpace(cluster.dspace.intervals, parts)\n\n # Drop or weaken parallelism if necessary\n properties = dict(cluster.properties)\n for d, v in cluster.properties.items():\n if any(i.is_Modulo for i in ispace.sub_iterators[d]):\n properties[d] = normalize_properties(v, {SEQUENTIAL})\n elif d not in writeto.dimensions:\n properties[d] = normalize_properties(v, {PARALLEL_IF_PVT})\n\n # Finally, build the `alias` Cluster\n clusters.append(cluster.rebuild(exprs=expression, ispace=ispace,\n dspace=dspace, properties=properties))\n\n return clusters, subs\n\n\ndef pick_best(variants):\n \"\"\"\n Use the variant score and heuristics to return the variant with the best\n trade-off between operation count reduction and working set increase.\n \"\"\"\n best = variants.pop(0)\n for i in variants:\n best_flop_score, best_ws_score = best.score\n if best_flop_score == 0:\n best = i\n continue\n\n i_flop_score, i_ws_score = i.score\n\n # The current heustic is fairly basic: the one with smaller working\n # set size increase wins, unless there's a massive reduction in operation\n # count in the other one\n delta = i_ws_score - best_ws_score\n if (delta > 0 and i_flop_score / best_flop_score > 100) or \\\n (delta == 0 and i_flop_score > best_flop_score) or \\\n (delta < 0 and best_flop_score / i_flop_score <= 100):\n best = i\n\n schedule, exprs, _ = best\n\n return schedule, exprs\n\n\ndef rebuild(cluster, exprs, subs, schedule):\n \"\"\"\n Plug the optimized aliases into the input Cluster. This leads to creating\n a new Cluster with suitable IterationSpace and DataSpace.\n \"\"\"\n exprs = [uxreplace(e, subs) for e in exprs]\n\n ispace = cluster.ispace.augment(schedule.dmapper)\n ispace = ispace.augment(schedule.rmapper)\n\n accesses = detect_accesses(exprs)\n parts = {k: IntervalGroup(build_intervals(v)).relaxed\n for k, v in accesses.items() if k}\n dspace = DataSpace(cluster.dspace.intervals, parts)\n\n return cluster.rebuild(exprs=exprs, ispace=ispace, dspace=dspace)\n\n\n# Utilities\n\n\nclass Candidate(object):\n\n def __init__(self, expr, ispace, indexeds, bases, offsets):\n self.expr = expr\n self.shifts = ispace.intervals\n self.indexeds = indexeds\n self.bases = bases\n self.offsets = offsets\n\n def __repr__(self):\n return \"Candidate(expr=%s)\" % self.expr\n\n def translated(self, other):\n \"\"\"\n True if ``self`` is translated w.r.t. ``other``, False otherwise.\n\n Examples\n --------\n Two candidates are translated if their bases are the same and\n their offsets are pairwise translated.\n\n c := A[i,j] op A[i,j+1] -> Toffsets = {i: [0,0], j: [0,1]}\n u := A[i+1,j] op A[i+1,j+1] -> Toffsets = {i: [1,1], j: [0,1]}\n\n Then `c` is translated w.r.t. `u` with distance `{i: 1, j: 0}`\n \"\"\"\n if len(self.Toffsets) != len(other.Toffsets):\n return False\n if len(self.bases) != len(other.bases):\n return False\n\n # Check the bases\n if any(b0 != b1 for b0, b1 in zip(self.bases, other.bases)):\n return False\n\n # Check the offsets\n for (d0, o0), (d1, o1) in zip(self.Toffsets, other.Toffsets):\n if d0 is not d1:\n return False\n\n distance = set(o0 - o1)\n if len(distance) != 1:\n return False\n\n return True\n\n @cached_property\n def Toffsets(self):\n return LabeledVector.transpose(*self.offsets)\n\n @cached_property\n def dimensions(self):\n return frozenset(i for i, _ in self.Toffsets)\n\n\nclass Group(tuple):\n\n \"\"\"\n A collection of aliasing expressions.\n \"\"\"\n\n def __repr__(self):\n return \"Group(%s)\" % \", \".join([str(i) for i in self])\n\n def find_rotation_distance(self, d, interval):\n \"\"\"\n The distance from the Group pivot of a rotation along Dimension ``d`` that\n can safely iterate over the ``interval``.\n \"\"\"\n assert d is interval.dim\n\n for rotation, distance in self._pivot_legal_rotations[d]:\n # Does `rotation` cover the `interval` ?\n if rotation.union(interval) != rotation:\n continue\n\n # Infer the `rotation`'s min_intervals from the pivot's\n min_interval = self._pivot_min_intervals[d].translate(-distance)\n\n # Does the `interval` actually cover the `rotation`'s `min_interval`?\n if interval.union(min_interval) == interval:\n return distance\n\n return None\n\n @cached_property\n def Toffsets(self):\n return [LabeledVector.transpose(*i) for i in zip(*[i.offsets for i in self])]\n\n @cached_property\n def diameter(self):\n \"\"\"\n The size of the iteration space required to evaluate all aliasing expressions\n in this Group, along each Dimension.\n \"\"\"\n ret = defaultdict(int)\n for i in self.Toffsets:\n for d, v in i:\n try:\n distance = int(max(v) - min(v))\n except TypeError:\n # An entry in `v` has symbolic components, e.g. `x_m + 2`\n if len(set(v)) == 1:\n continue\n else:\n raise ValueError\n ret[d] = max(ret[d], distance)\n\n return ret\n\n @property\n def pivot(self):\n \"\"\"\n A deterministically chosen Candidate for this Group.\n \"\"\"\n return self[0]\n\n @property\n def dimensions(self):\n return self.pivot.dimensions\n\n @property\n def dimensions_translated(self):\n return frozenset(d for d, v in self.diameter.items() if v > 0)\n\n @cached_property\n def _pivot_legal_rotations(self):\n \"\"\"\n All legal rotations along each Dimension for the Group pivot.\n \"\"\"\n ret = {}\n for d, (maxd, mini) in self._pivot_legal_shifts.items():\n # Rotation size = mini (min-increment) - maxd (max-decrement)\n v = mini - maxd\n\n # Build the table of all possible rotations\n m = make_rotations_table(d, v)\n\n distances = []\n for rotation in m:\n # Distance of the rotation `i` from `c`\n distance = maxd - rotation.lower\n assert distance == mini - rotation.upper\n distances.append(distance)\n\n ret[d] = list(zip(m, distances))\n\n return ret\n\n @cached_property\n def _pivot_min_intervals(self):\n \"\"\"\n The minimum Interval along each Dimension such that by evaluating the\n pivot, all Candidates are evaluated too.\n \"\"\"\n c = self.pivot\n\n ret = defaultdict(lambda: [np.inf, -np.inf])\n for i in self:\n distance = [o.distance(v) for o, v in zip(i.offsets, c.offsets)]\n distance = [(d, set(v)) for d, v in LabeledVector.transpose(*distance)]\n\n for d, v in distance:\n value = v.pop()\n ret[d][0] = min(ret[d][0], value)\n ret[d][1] = max(ret[d][1], value)\n\n ret = {d: Interval(d, m, M) for d, (m, M) in ret.items()}\n\n return ret\n\n @cached_property\n def _pivot_legal_shifts(self):\n \"\"\"\n The max decrement and min increment along each Dimension such that the\n Group pivot does not go OOB.\n \"\"\"\n c = self.pivot\n\n ret = defaultdict(lambda: (-np.inf, np.inf))\n for i, ofs in zip(c.indexeds, c.offsets):\n f = i.function\n for l in ofs.labels:\n # `f`'s cumulative halo size along `l`\n hsize = sum(f._size_halo[l])\n\n # Any `ofs`'s shift due to non-[0,0] iteration space\n lower, upper = c.shifts[l].offsets\n\n try:\n # Assume `ofs[d]` is a number (typical case)\n maxd = min(0, max(ret[l][0], -ofs[l] - lower))\n mini = max(0, min(ret[l][1], hsize - ofs[l] - upper))\n\n ret[l] = (maxd, mini)\n except TypeError:\n # E.g., `ofs[d] = x_m - x + 5`\n ret[l] = (0, 0)\n\n return ret\n\n\nAliasedGroup = namedtuple('AliasedGroup', 'intervals aliaseds distances')\n\nScheduledAlias = namedtuple('ScheduledAlias', 'alias writeto ispace aliaseds indicess')\nScheduledAlias.__new__.__defaults__ = (None,) * len(ScheduledAlias._fields)\n\nSpacePoint = namedtuple('SpacePoint', 'schedule exprs score')\n\n\nclass Schedule(tuple):\n\n def __new__(cls, *items, dmapper=None, rmapper=None):\n obj = super(Schedule, cls).__new__(cls, items)\n obj.dmapper = dmapper or {}\n obj.rmapper = rmapper or {}\n return obj\n\n\nclass AliasMapper(OrderedDict):\n\n def add(self, alias, intervals, aliaseds, distances):\n assert len(aliaseds) == len(distances)\n self[alias] = AliasedGroup(intervals, aliaseds, distances)\n\n def update(self, aliases):\n for k, v in aliases.items():\n try:\n v0 = self[k]\n if v0.intervals != v.intervals:\n raise ValueError\n v0.aliaseds.extend(v.aliaseds)\n v0.distances.extend(v.distances)\n except KeyError:\n self[k] = v\n\n @property\n def aliaseds(self):\n return flatten(i.aliaseds for i in self.values())\n\n\ndef make_rotations_table(d, v):\n \"\"\"\n All possible rotations of `range(v+1)`.\n \"\"\"\n m = np.array([[j-i if j > i else 0 for j in range(v+1)] for i in range(v+1)])\n m = (m - m.T)[::-1, :]\n\n # Shift the table so that the middle rotation is at the top\n m = np.roll(m, int(-np.floor(v/2)), axis=0)\n\n # Turn into a more compact representation as a list of Intervals\n m = [Interval(d, min(i), max(i)) for i in m]\n\n return m\n\n\ndef cit(ispace0, ispace1):\n \"\"\"\n The Common IterationIntervals of two IterationSpaces.\n \"\"\"\n found = []\n for it0, it1 in zip(ispace0.itintervals, ispace1.itintervals):\n if it0 == it1:\n found.append(it0)\n else:\n break\n return tuple(found)\n\n\ndef maybe_coeff_key(grid, expr):\n \"\"\"\n True if `expr` could be the coefficient of an FD derivative, False otherwise.\n \"\"\"\n if expr.is_Number:\n return True\n indexeds = [i for i in expr.free_symbols if i.is_Indexed]\n return any(not set(grid.dimensions) <= set(i.function.dimensions) for i in indexeds)\n\n\ndef wset(exprs):\n \"\"\"\n Extract the working set out of a set of equations.\n \"\"\"\n return {i.function for i in flatten([e.free_symbols for e in as_tuple(exprs)])\n if i.function.is_AbstractFunction}\n\n\ndef potential_max_deriv_order(exprs):\n \"\"\"\n The maximum FD derivative order in a list of expressions.\n \"\"\"\n # NOTE: e might propagate the Derivative(...) information down from the\n # symbolic language, but users may do crazy things and write their own custom\n # expansions \"by hand\" (i.e., not resorting to Derivative(...)), hence instead\n # of looking for Derivative(...) we use the following heuristic:\n # add(mul, mul, ...) -> stems from first order derivative\n # add(mul(add(mul, mul, ...), ...), ...) -> stems from second order derivative\n # ...\n nadds = lambda e: (int(e.is_Add) +\n max([nadds(a) for a in e.args], default=0) if not q_leaf(e) else 0)\n return max([nadds(e) for e in exprs], default=0)\n\n\ndef search_potential_deriv(expr, n, c=0):\n \"\"\"\n Retrieve the expressions at depth `n` that potentially stem from FD derivatives.\n \"\"\"\n assert n >= c >= 0\n if q_leaf(expr) or expr.is_Pow:\n return []\n elif expr.is_Mul:\n if c == n:\n return [expr]\n else:\n return flatten([search_potential_deriv(a, n, c+1) for a in expr.args])\n else:\n return flatten([search_potential_deriv(a, n, c) for a in expr.args])\n" ]
[ [ "numpy.floor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
harshgrovr/Graphs_Thesis
[ "36daf66f6216bad4d30651311bcb87aa45dd33d5", "9ffd0d23c8f8b4bd53db9fd5b9bf5776666814e0" ]
[ "examples/pytorch/ogb/line/reading_data.py", "related_code/3-basics/tutorial_utils.py" ]
[ "import os\nimport numpy as np\nimport scipy.sparse as sp\nimport pickle\nimport torch\nfrom torch.utils.data import DataLoader\nfrom dgl.data.utils import download, _get_dgl_url, get_download_dir, extract_archive\nimport random\nimport time\nimport dgl\n\ndef ReadTxtNet(file_path=\"\", undirected=True):\n \"\"\" Read the txt network file. \n Notations: The network is unweighted.\n\n Parameters\n ----------\n file_path str : path of network file\n undirected bool : whether the edges are undirected\n\n Return\n ------\n net dict : a dict recording the connections in the graph\n node2id dict : a dict mapping the nodes to their embedding indices \n id2node dict : a dict mapping nodes embedding indices to the nodes\n \"\"\"\n if file_path == 'youtube' or file_path == 'blog':\n name = file_path\n dir = get_download_dir()\n zip_file_path='{}/{}.zip'.format(dir, name)\n download(_get_dgl_url(os.path.join('dataset/DeepWalk/', '{}.zip'.format(file_path))), path=zip_file_path)\n extract_archive(zip_file_path,\n '{}/{}'.format(dir, name))\n file_path = \"{}/{}/{}-net.txt\".format(dir, name, name)\n\n node2id = {}\n id2node = {}\n cid = 0\n\n src = []\n dst = []\n weight = []\n net = {}\n with open(file_path, \"r\") as f:\n for line in f.readlines():\n tup = list(map(int, line.strip().split(\" \")))\n assert len(tup) in [2, 3], \"The format of network file is unrecognizable.\"\n if len(tup) == 3:\n n1, n2, w = tup\n elif len(tup) == 2:\n n1, n2 = tup\n w = 1\n if n1 not in node2id:\n node2id[n1] = cid\n id2node[cid] = n1\n cid += 1\n if n2 not in node2id:\n node2id[n2] = cid\n id2node[cid] = n2\n cid += 1\n\n n1 = node2id[n1]\n n2 = node2id[n2]\n if n1 not in net:\n net[n1] = {n2: w}\n src.append(n1)\n dst.append(n2)\n weight.append(w)\n elif n2 not in net[n1]:\n net[n1][n2] = w\n src.append(n1)\n dst.append(n2)\n weight.append(w)\n \n if undirected:\n if n2 not in net:\n net[n2] = {n1: w}\n src.append(n2)\n dst.append(n1)\n weight.append(w)\n elif n1 not in net[n2]:\n net[n2][n1] = w\n src.append(n2)\n dst.append(n1)\n weight.append(w)\n\n print(\"node num: %d\" % len(net))\n print(\"edge num: %d\" % len(src))\n assert max(net.keys()) == len(net) - 1, \"error reading net, quit\"\n\n sm = sp.coo_matrix(\n (np.array(weight), (src, dst)),\n dtype=np.float32)\n\n return net, node2id, id2node, sm\n\ndef net2graph(net_sm):\n \"\"\" Transform the network to DGL graph\n\n Return \n ------\n G DGLGraph : graph by DGL\n \"\"\"\n start = time.time()\n G = dgl.DGLGraph(net_sm)\n end = time.time()\n t = end - start\n print(\"Building DGLGraph in %.2fs\" % t)\n return G\n\ndef make_undirected(G):\n #G.readonly(False)\n G.add_edges(G.edges()[1], G.edges()[0])\n return G\n\ndef find_connected_nodes(G):\n nodes = torch.nonzero(G.out_degrees()).squeeze(-1)\n return nodes\n\nclass LineDataset:\n def __init__(self, \n net_file,\n batch_size,\n num_samples,\n negative=5,\n gpus=[0],\n fast_neg=True,\n ogbl_name=\"\",\n load_from_ogbl=False,\n ogbn_name=\"\",\n load_from_ogbn=False,\n ):\n \"\"\" This class has the following functions:\n 1. Transform the txt network file into DGL graph;\n 2. Generate random walk sequences for the trainer;\n 3. Provide the negative table if the user hopes to sample negative\n nodes according to nodes' degrees;\n\n Parameter\n ---------\n net_file str : path of the dgl network file\n walk_length int : number of nodes in a sequence\n window_size int : context window size\n num_walks int : number of walks for each node\n batch_size int : number of node sequences in each batch\n negative int : negative samples for each positve node pair\n fast_neg bool : whether do negative sampling inside a batch\n \"\"\"\n self.batch_size = batch_size\n self.negative = negative\n self.num_samples = num_samples\n self.num_procs = len(gpus)\n self.fast_neg = fast_neg\n\n if load_from_ogbl:\n assert len(gpus) == 1, \"ogb.linkproppred is not compatible with multi-gpu training.\"\n from load_dataset import load_from_ogbl_with_name\n self.G = load_from_ogbl_with_name(ogbl_name)\n elif load_from_ogbn:\n assert len(gpus) == 1, \"ogb.linkproppred is not compatible with multi-gpu training.\"\n from load_dataset import load_from_ogbn_with_name\n self.G = load_from_ogbn_with_name(ogbn_name)\n else:\n self.G = dgl.load_graphs(net_file)[0][0]\n self.G = make_undirected(self.G)\n print(\"Finish reading graph\")\n\n self.num_nodes = self.G.number_of_nodes()\n\n start = time.time()\n seeds = np.random.choice(np.arange(self.G.number_of_edges()), \n self.num_samples, \n replace=True) # edge index\n self.seeds = torch.split(torch.LongTensor(seeds), \n int(np.ceil(self.num_samples / self.num_procs)), \n 0)\n end = time.time()\n t = end - start\n print(\"generate %d samples in %.2fs\" % (len(seeds), t))\n\n # negative table for true negative sampling\n self.valid_nodes = find_connected_nodes(self.G)\n if not fast_neg:\n node_degree = self.G.out_degrees(self.valid_nodes).numpy()\n node_degree = np.power(node_degree, 0.75)\n node_degree /= np.sum(node_degree)\n node_degree = np.array(node_degree * 1e8, dtype=np.int)\n self.neg_table = []\n \n for idx, node in enumerate(self.valid_nodes):\n self.neg_table += [node] * node_degree[idx]\n self.neg_table_size = len(self.neg_table)\n self.neg_table = np.array(self.neg_table, dtype=np.long)\n del node_degree\n\n def create_sampler(self, i):\n \"\"\" create random walk sampler \"\"\"\n return EdgeSampler(self.G, self.seeds[i])\n\n def save_mapping(self, map_file):\n with open(map_file, \"wb\") as f:\n pickle.dump(self.node2id, f)\n\nclass EdgeSampler(object):\n def __init__(self, G, seeds):\n self.G = G\n self.seeds = seeds\n self.edges = torch.cat((self.G.edges()[0].unsqueeze(0), self.G.edges()[1].unsqueeze(0)), 0).t()\n \n def sample(self, seeds):\n \"\"\" seeds torch.LongTensor : a batch of indices of edges \"\"\"\n return self.edges[torch.LongTensor(seeds)]", "import dgl\nimport pandas as pd\nimport torch\nimport torch.nn.functional as F\n\ndef load_zachery():\n nodes_data = pd.read_csv('data/nodes.csv')\n edges_data = pd.read_csv('data/edges.csv')\n src = edges_data['Src'].to_numpy()\n dst = edges_data['Dst'].to_numpy()\n g = dgl.graph((src, dst))\n club = nodes_data['Club'].to_list()\n # Convert to categorical integer values with 0 for 'Mr. Hi', 1 for 'Officer'.\n club = torch.tensor([c == 'Officer' for c in club]).long()\n # We can also convert it to one-hot encoding.\n club_onehot = F.one_hot(club)\n g.ndata.update({'club' : club, 'club_onehot' : club_onehot})\n return g\n" ]
[ [ "torch.LongTensor", "numpy.power", "numpy.ceil", "numpy.array", "numpy.sum" ], [ "torch.nn.functional.one_hot", "pandas.read_csv", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
danielvarga/vat_tf
[ "0b40b256922b7996558504a5d2c3556b5f9fff15" ]
[ "train_semisup.py" ]
[ "import time\n\nimport numpy as np\nimport tensorflow as tf\n\nimport layers as L\nimport vat\n\nFLAGS = tf.app.flags.FLAGS\n\ntf.app.flags.DEFINE_string('device', '/gpu:0', \"device\")\n\ntf.app.flags.DEFINE_string('dataset', 'cifar10', \"{cifar10, svhn}\")\n\ntf.app.flags.DEFINE_string('log_dir', \"\", \"log_dir\")\ntf.app.flags.DEFINE_integer('seed', 1, \"initial random seed\")\ntf.app.flags.DEFINE_bool('validation', False, \"\")\n\ntf.app.flags.DEFINE_integer('batch_size', 32, \"the number of examples in a batch\")\ntf.app.flags.DEFINE_integer('ul_batch_size', 128, \"the number of unlabeled examples in a batch\")\ntf.app.flags.DEFINE_integer('eval_batch_size', 100, \"the number of eval examples in a batch\")\ntf.app.flags.DEFINE_integer('eval_freq', 5, \"\")\ntf.app.flags.DEFINE_integer('num_epochs', 120, \"the number of epochs for training\")\ntf.app.flags.DEFINE_integer('epoch_decay_start', 80, \"epoch of starting learning rate decay\")\ntf.app.flags.DEFINE_integer('num_iter_per_epoch', 400, \"the number of updates per epoch\")\ntf.app.flags.DEFINE_float('learning_rate', 0.001, \"initial leanring rate\")\ntf.app.flags.DEFINE_float('mom1', 0.9, \"initial momentum rate\")\ntf.app.flags.DEFINE_float('mom2', 0.5, \"momentum rate after epoch_decay_start\")\n\ntf.app.flags.DEFINE_string('method', 'vat', \"{vat, vatent, baseline}\")\n\n\nif FLAGS.dataset == 'cifar10':\n from cifar10 import inputs, unlabeled_inputs\nelif FLAGS.dataset == 'svhn':\n from svhn import inputs, unlabeled_inputs \nelse: \n raise NotImplementedError\n\n\nNUM_EVAL_EXAMPLES = 5000\n\n\ndef build_training_graph(x, y, ul_x, ul_u, lr, mom):\n global_step = tf.get_variable(\n name=\"global_step\",\n shape=[],\n dtype=tf.float32,\n initializer=tf.constant_initializer(0.0),\n trainable=False,\n )\n logit = vat.forward(x)\n nll_loss = L.ce_loss(logit, y)\n with tf.variable_scope(tf.get_variable_scope(), reuse=True):\n if FLAGS.method == 'vat':\n ul_logit = vat.forward(ul_x, is_training=True, update_batch_stats=False)\n vat_loss, ul_u_updated = vat.virtual_adversarial_loss(ul_x, ul_u, ul_logit)\n additional_loss = vat_loss\n elif FLAGS.method == 'vatent':\n ul_logit = vat.forward(ul_x, is_training=True, update_batch_stats=False)\n vat_loss, ul_u_updated = vat.virtual_adversarial_loss(ul_x, ul_u, ul_logit)\n ent_loss = L.entropy_y_x(ul_logit)\n additional_loss = vat_loss + ent_loss\n elif FLAGS.method == 'baseline':\n additional_loss = 0\n else:\n raise NotImplementedError\n loss = nll_loss + additional_loss\n\n opt = tf.train.AdamOptimizer(learning_rate=lr, beta1=mom)\n tvars = tf.trainable_variables()\n grads_and_vars = opt.compute_gradients(loss, tvars)\n train_op = opt.apply_gradients(grads_and_vars, global_step=global_step)\n return loss, train_op, global_step, ul_u_updated\n\n\ndef build_eval_graph(x, y, ul_x, ul_u):\n losses = {}\n logit = vat.forward(x, is_training=False, update_batch_stats=False)\n nll_loss = L.ce_loss(logit, y)\n losses['NLL'] = nll_loss\n acc = L.accuracy(logit, y)\n losses['Acc'] = acc\n scope = tf.get_variable_scope()\n scope.reuse_variables()\n # at_loss = vat.adversarial_loss(x, y, nll_loss, is_training=False)\n # losses['AT_loss'] = at_loss\n ul_logit = vat.forward(ul_x, is_training=False, update_batch_stats=False)\n vat_loss = vat.virtual_adversarial_loss(ul_x, ul_u, ul_logit, is_training=False)\n losses['VAT_loss'] = vat_loss\n return losses\n\n\ndef main(_):\n print(FLAGS.epsilon, FLAGS.top_bn)\n np.random.seed(seed=FLAGS.seed)\n tf.set_random_seed(np.random.randint(1234))\n with tf.Graph().as_default() as g:\n with tf.device(\"/cpu:0\"):\n images, labels = inputs(batch_size=FLAGS.batch_size,\n train=True,\n validation=FLAGS.validation,\n shuffle=True)\n ul_images = tf.placeholder(shape=images.shape, dtype=tf.float32)\n '''unlabeled_inputs(batch_size=FLAGS.ul_batch_size,\n validation=FLAGS.validation,\n shuffle=True)'''\n\n images_eval_train, labels_eval_train = inputs(batch_size=FLAGS.eval_batch_size,\n train=True,\n validation=FLAGS.validation,\n shuffle=True)\n ul_images_eval_train = unlabeled_inputs(batch_size=FLAGS.eval_batch_size,\n validation=FLAGS.validation,\n shuffle=True)\n\n images_eval_test, labels_eval_test = inputs(batch_size=FLAGS.eval_batch_size,\n train=False,\n validation=FLAGS.validation,\n shuffle=True)\n\n def placeholder_like(x, name=None):\n return tf.placeholder(shape=x.shape, dtype=tf.float32, name=name)\n\n def random_sphere(shape):\n n = tf.random_normal(shape=shape, dtype=tf.float32)\n n = tf.reshape(n, shape=(int(shape[0]), -1))\n n = tf.nn.l2_normalize(n, dim=1)\n n = tf.reshape(n, shape)\n return n\n\n def random_sphere_numpy(shape):\n n = np.random.normal(size=shape)\n proj_shape = tuple([n.shape[0]] + [1 for _ in range(len(shape) - 1)])\n return n / np.linalg.norm(n.reshape((n.shape[0], -1)), axis=1).reshape(proj_shape)\n\n print(ul_images.shape)\n # ul_u = random_sphere(ul_images.shape)\n # ul_u_eval_train = random_sphere(ul_images_eval_train.shape)\n # ul_u_eval_test = random_sphere(images_eval_test.shape)\n ul_u = placeholder_like(ul_images, \"ul_u\")\n ul_u_eval_train = placeholder_like(ul_images_eval_train, \"ul_u_eval_train\")\n ul_u_eval_test = placeholder_like(images_eval_test, \"ul_u_eval_test\")\n\n with tf.device(FLAGS.device):\n lr = tf.placeholder(tf.float32, shape=[], name=\"learning_rate\")\n mom = tf.placeholder(tf.float32, shape=[], name=\"momentum\")\n with tf.variable_scope(\"CNN\") as scope:\n # Build training graph\n loss, train_op, global_step, ul_u_updated = build_training_graph(\n images, labels, ul_images, ul_u, lr, mom)\n scope.reuse_variables()\n # Build eval graph\n losses_eval_train = build_eval_graph(images_eval_train, labels_eval_train, ul_images_eval_train, ul_u_eval_train)\n losses_eval_test = build_eval_graph(images_eval_test, labels_eval_test, images_eval_test, ul_u_eval_test)\n\n init_op = tf.global_variables_initializer()\n\n if not FLAGS.log_dir:\n logdir = None\n writer_train = None\n writer_test = None\n else:\n logdir = FLAGS.log_dir\n writer_train = tf.summary.FileWriter(FLAGS.log_dir + \"/train\", g)\n writer_test = tf.summary.FileWriter(FLAGS.log_dir + \"/test\", g)\n\n saver = tf.train.Saver(tf.global_variables())\n sv = tf.train.Supervisor(\n is_chief=True,\n logdir=logdir,\n init_op=init_op,\n init_feed_dict={lr: FLAGS.learning_rate, mom: FLAGS.mom1},\n saver=saver,\n global_step=global_step,\n summary_op=None,\n summary_writer=None,\n save_model_secs=150, recovery_wait_secs=0)\n\n ul_images_np = np.load(\"train_images.npy\").reshape((-1, 32, 32, 3))\n print(\"TRUNCATING UL DATA\")\n ul_images_np = ul_images_np[:FLAGS.batch_size]\n ul_u_np = random_sphere_numpy(ul_images_np.shape)\n print(ul_images_np.shape, ul_u_np.shape)\n\n print(\"Training...\")\n with sv.managed_session() as sess:\n for ep in range(FLAGS.num_epochs):\n if sv.should_stop():\n break\n\n if ep < FLAGS.epoch_decay_start:\n feed_dict = {lr: FLAGS.learning_rate, mom: FLAGS.mom1}\n else:\n decayed_lr = ((FLAGS.num_epochs - ep) / float(\n FLAGS.num_epochs - FLAGS.epoch_decay_start)) * FLAGS.learning_rate\n feed_dict = {lr: decayed_lr, mom: FLAGS.mom2}\n\n sum_loss = 0\n start = time.time()\n for i in range(FLAGS.num_iter_per_epoch):\n picked = range(FLAGS.batch_size) # np.random.choice(len(ul_images_np), size=FLAGS.batch_size, replace=False)\n feed_dict[ul_images] = ul_images_np[picked]\n feed_dict[ul_u] = ul_u_np[picked]\n ul_u_updated_np, _, batch_loss, _ = sess.run([ul_u_updated, train_op, loss, global_step],\n feed_dict=feed_dict)\n delta = ul_u_updated_np - ul_u_np[picked]\n # print(\"pos\", ul_u_updated_np.reshape((FLAGS.batch_size, -1))[0, :4])\n # print(\"delta\", np.linalg.norm(delta.reshape((FLAGS.batch_size, -1)), axis=1)[:4])\n print(np.linalg.norm(ul_u_updated_np - ul_u_np[picked]), ul_u_updated_np.reshape((FLAGS.batch_size, -1))[0, :3])\n ul_u_np[picked] = ul_u_updated_np\n sum_loss += batch_loss\n end = time.time()\n print(\"Epoch:\", ep, \"CE_loss_train:\", sum_loss / FLAGS.num_iter_per_epoch, \"elapsed_time:\", end - start)\n\n if (ep + 1) % FLAGS.eval_freq == 0 or ep + 1 == FLAGS.num_epochs:\n # Eval on training data\n act_values_dict = {}\n feed_dict = {ul_u_eval_train: random_sphere_numpy(ul_u_eval_train.shape)}\n for key, _ in losses_eval_train.iteritems():\n act_values_dict[key] = 0\n n_iter_per_epoch = NUM_EVAL_EXAMPLES / FLAGS.eval_batch_size\n for i in range(n_iter_per_epoch):\n values = losses_eval_train.values()\n act_values = sess.run(values, feed_dict=feed_dict)\n for key, value in zip(act_values_dict.keys(), act_values):\n act_values_dict[key] += value\n summary = tf.Summary()\n current_global_step = sess.run(global_step)\n for key, value in act_values_dict.iteritems():\n print(\"train-\" + key, value / n_iter_per_epoch)\n summary.value.add(tag=key, simple_value=value / n_iter_per_epoch)\n if writer_train is not None:\n writer_train.add_summary(summary, current_global_step)\n\n # Eval on test data\n act_values_dict = {}\n print(\"HOW COME THIS DOES NOT DEPEND ON ul_images_eval_train? SOMETHING'S WRONG HERE.\")\n feed_dict = {ul_u_eval_test: random_sphere_numpy(ul_u_eval_test.shape)}\n for key, _ in losses_eval_test.iteritems():\n act_values_dict[key] = 0\n n_iter_per_epoch = NUM_EVAL_EXAMPLES / FLAGS.eval_batch_size\n for i in range(n_iter_per_epoch):\n values = losses_eval_test.values()\n act_values = sess.run(values, feed_dict=feed_dict)\n for key, value in zip(act_values_dict.keys(), act_values):\n act_values_dict[key] += value\n summary = tf.Summary()\n current_global_step = sess.run(global_step)\n for key, value in act_values_dict.iteritems():\n print(\"test-\" + key, value / n_iter_per_epoch)\n summary.value.add(tag=key, simple_value=value / n_iter_per_epoch)\n if writer_test is not None:\n writer_test.add_summary(summary, current_global_step)\n\n saver.save(sess, sv.save_path, global_step=global_step)\n sv.stop()\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n" ]
[ [ "tensorflow.device", "tensorflow.global_variables", "tensorflow.app.flags.DEFINE_string", "tensorflow.train.AdamOptimizer", "numpy.random.randint", "tensorflow.Graph", "tensorflow.app.flags.DEFINE_integer", "tensorflow.trainable_variables", "numpy.load", "tensorflow.Summary", "tensorflow.app.run", "tensorflow.nn.l2_normalize", "tensorflow.app.flags.DEFINE_bool", "tensorflow.placeholder", "tensorflow.global_variables_initializer", "tensorflow.summary.FileWriter", "numpy.random.seed", "tensorflow.reshape", "numpy.linalg.norm", "tensorflow.constant_initializer", "numpy.random.normal", "tensorflow.train.Supervisor", "tensorflow.app.flags.DEFINE_float", "tensorflow.variable_scope", "tensorflow.get_variable_scope", "tensorflow.random_normal" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] } ]
yuvallanger/matplotlib
[ "c9898ea9a30c67c579ab27cd61b68e2abae0fb0e", "c9898ea9a30c67c579ab27cd61b68e2abae0fb0e", "c9898ea9a30c67c579ab27cd61b68e2abae0fb0e" ]
[ "examples/pylab_examples/mri_with_eeg.py", "examples/pylab_examples/dashpointlabel.py", "examples/pylab_examples/log_bar.py" ]
[ "#!/usr/bin/env python\n\n\"\"\"\nThis now uses the imshow command instead of pcolor which *is much\nfaster*\n\"\"\"\nfrom __future__ import division, print_function\n\nimport numpy as np\n\nfrom matplotlib.pyplot import *\nfrom matplotlib.collections import LineCollection\nimport matplotlib.cbook as cbook\n# I use if 1 to break up the different regions of code visually\n\nif 1: # load the data\n # data are 256x256 16 bit integers\n dfile = cbook.get_sample_data('s1045.ima.gz')\n im = np.fromstring(dfile.read(), np.uint16).astype(float)\n im.shape = 256, 256\n\nif 1: # plot the MRI in pcolor\n subplot(221)\n imshow(im, cmap=cm.gray)\n axis('off')\n\nif 1: # plot the histogram of MRI intensity\n subplot(222)\n im = np.ravel(im)\n im = im[np.nonzero(im)] # ignore the background\n im = im/(2.0**15) # normalize\n hist(im, 100)\n xticks([-1, -.5, 0, .5, 1])\n yticks([])\n xlabel('intensity')\n ylabel('MRI density')\n\nif 1: # plot the EEG\n # load the data\n\n numSamples, numRows = 800,4\n eegfile = cbook.get_sample_data('eeg.dat', asfileobj=False)\n print('loading eeg %s' % eegfile)\n data = np.fromstring(open(eegfile, 'rb').read(), float)\n data.shape = numSamples, numRows\n t = 10.0 * np.arange(numSamples, dtype=float)/numSamples\n ticklocs = []\n ax = subplot(212)\n xlim(0,10)\n xticks(np.arange(10))\n dmin = data.min()\n dmax = data.max()\n dr = (dmax - dmin)*0.7 # Crowd them a bit.\n y0 = dmin\n y1 = (numRows-1) * dr + dmax\n ylim(y0, y1)\n\n segs = []\n for i in range(numRows):\n segs.append(np.hstack((t[:,np.newaxis], data[:,i,np.newaxis])))\n ticklocs.append(i*dr)\n\n offsets = np.zeros((numRows,2), dtype=float)\n offsets[:,1] = ticklocs\n\n lines = LineCollection(segs, offsets=offsets,\n transOffset=None,\n )\n\n ax.add_collection(lines)\n\n # set the yticks to use axes coords on the y axis\n ax.set_yticks(ticklocs)\n ax.set_yticklabels(['PG3', 'PG5', 'PG7', 'PG9'])\n\n xlabel('time (s)')\n\nshow()\n", "import matplotlib.pyplot as plt\n\nDATA = ((1, 3),\n (2, 4),\n (3, 1),\n (4, 2))\n# dash_style =\n# direction, length, (text)rotation, dashrotation, push\n# (The parameters are varied to show their effects,\n# not for visual appeal).\ndash_style = (\n (0, 20, -15, 30, 10),\n (1, 30, 0, 15, 10),\n (0, 40, 15, 15, 10),\n (1, 20, 30, 60, 10),\n )\n\nfig, ax = plt.subplots()\n\n(x,y) = zip(*DATA)\nax.plot(x, y, marker='o')\nfor i in range(len(DATA)):\n (x,y) = DATA[i]\n (dd, dl, r, dr, dp) = dash_style[i]\n #print('dashlen call %d' % dl)\n t = ax.text(x, y, str((x,y)), withdash=True,\n dashdirection=dd,\n dashlength=dl,\n rotation=r,\n dashrotation=dr,\n dashpush=dp,\n )\n\nax.set_xlim((0.0, 5.0))\nax.set_ylim((0.0, 5.0))\n\nplt.show()\n", "#!/usr/bin/env python\n\nfrom matplotlib import pylab\n\ndata = ((3,1000), (10,3), (100,30), (500, 800), (50,1))\n\npylab.xlabel(\"FOO\")\npylab.ylabel(\"FOO\")\npylab.title(\"Testing\")\npylab.gca().set_yscale('log')\n\ndim = len(data[0])\nw = 0.75\ndimw = w / dim\n\nx = pylab.arange(len(data))\nfor i in range(len(data[0])) :\n y = [d[i] for d in data]\n b = pylab.bar(x + i * dimw, y, dimw, bottom=0.001)\npylab.gca().set_xticks(x + w / 2)\npylab.gca().set_ylim((0.001,1000))\n\npylab.show()\n" ]
[ [ "numpy.hstack", "numpy.nonzero", "matplotlib.collections.LineCollection", "numpy.arange", "numpy.ravel", "matplotlib.cbook.get_sample_data", "numpy.zeros" ], [ "matplotlib.pyplot.show", "matplotlib.pyplot.subplots" ], [ "matplotlib.pylab.show", "matplotlib.pylab.bar", "matplotlib.pylab.title", "matplotlib.pylab.gca", "matplotlib.pylab.ylabel", "matplotlib.pylab.xlabel" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
TristanThomson/Year-3-Final-Project
[ "07a588ff3312040c6ff41fd170c1909357991c66" ]
[ "Twitter_scraping/graph_builder.py" ]
[ "import os\nimport networkx as nx\nimport pandas as pd\nfrom pathlib import Path\nfrom Twitter_scraping.scraper_helper import RandomPicker\n\nG = nx.DiGraph() # initialises empty NetworkX graph\nmin_list = RandomPicker().min_df[\"Twitter\"].dropna() # Pandas series from the \"Twitter\" col of the SYI dataset\nmep_list = RandomPicker().all_df[\"Twitter\"].dropna()\nrootdir = os.getcwd() # path to parent folder of current file\n\n\ndef check_minorities():\n for path in Path(rootdir).rglob('*.csv'):\n curparent = str(path.parent.name)\n if curparent in map(lambda x: x.lower(),min_list[\"Twitter\"].dropna()) and not path.parent.parent.name == \"minority\":\n print(curparent)\n original = str(rootdir) + \"/\" + str(path.parent.parent.parent.name) + \"/majority/\" + str(\n curparent) + \"/\" + str(path.name)\n new = str(rootdir) + \"/\" + str(path.parent.parent.parent.name) + \"/minority/\" + str(curparent) + \"/\" + str(\n path.name)\n os.rename(original, new)\n\nfor path in Path(rootdir).rglob('*.csv'):\n curparent = str(path.parent.name)\n curfile = pd.read_csv(path, encoding='utf-8-sig')\n if curparent.lower() in map(lambda x: x.lower(), min_list):\n G.add_node(curparent, is_mep=1)\n if str(path.name) == \"following.csv\":\n print(path.name)\n for i in curfile[\"username\"]:\n if i in map(lambda x: x.lower(), mep_list):\n G.add_node(str(i), is_mep=1)\n else:\n G.add_node(str(i), is_mep=0)\n G.add_edge(curparent, i)\n else:\n print(path.name)\n for i in curfile[\"username\"]:\n if i in map(lambda x: x.lower(), mep_list):\n G.add_node(str(i), is_mep=1)\n else:\n G.add_node(str(i), is_mep=0)\n G.add_edge(str(i), curparent)\n\nnx.write_gexf(G, \"minority.gexf\")\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
evgps/mmdetection_trashcan
[ "aaf4237c2c0d473425cdc7b741d3009177b79751", "aaf4237c2c0d473425cdc7b741d3009177b79751", "aaf4237c2c0d473425cdc7b741d3009177b79751" ]
[ "mmdet/models/backbones/res2net.py", "tests/test_utils/test_assigner.py", "mmdet/models/dense_heads/free_anchor_retina_head.py" ]
[ "import math\n\nimport torch\nimport torch.nn as nn\nimport torch.utils.checkpoint as cp\nfrom mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,\n kaiming_init)\nfrom mmcv.runner import load_checkpoint\nfrom torch.nn.modules.batchnorm import _BatchNorm\n\nfrom mmdet.utils import get_root_logger\nfrom ..builder import BACKBONES\nfrom .resnet import Bottleneck as _Bottleneck\nfrom .resnet import ResNet\n\n\nclass Bottle2neck(_Bottleneck):\n expansion = 4\n\n def __init__(self,\n inplanes,\n planes,\n scales=4,\n base_width=26,\n base_channels=64,\n stage_type='normal',\n **kwargs):\n \"\"\"Bottle2neck block for Res2Net.\n\n If style is \"pytorch\", the stride-two layer is the 3x3 conv layer, if\n it is \"caffe\", the stride-two layer is the first 1x1 conv layer.\n \"\"\"\n super(Bottle2neck, self).__init__(inplanes, planes, **kwargs)\n assert scales > 1, 'Res2Net degenerates to ResNet when scales = 1.'\n width = int(math.floor(self.planes * (base_width / base_channels)))\n\n self.norm1_name, norm1 = build_norm_layer(\n self.norm_cfg, width * scales, postfix=1)\n self.norm3_name, norm3 = build_norm_layer(\n self.norm_cfg, self.planes * self.expansion, postfix=3)\n\n self.conv1 = build_conv_layer(\n self.conv_cfg,\n self.inplanes,\n width * scales,\n kernel_size=1,\n stride=self.conv1_stride,\n bias=False)\n self.add_module(self.norm1_name, norm1)\n\n if stage_type == 'stage' and self.conv2_stride != 1:\n self.pool = nn.AvgPool2d(\n kernel_size=3, stride=self.conv2_stride, padding=1)\n convs = []\n bns = []\n\n fallback_on_stride = False\n if self.with_dcn:\n fallback_on_stride = self.dcn.pop('fallback_on_stride', False)\n if not self.with_dcn or fallback_on_stride:\n for i in range(scales - 1):\n convs.append(\n build_conv_layer(\n self.conv_cfg,\n width,\n width,\n kernel_size=3,\n stride=self.conv2_stride,\n padding=self.dilation,\n dilation=self.dilation,\n bias=False))\n bns.append(\n build_norm_layer(self.norm_cfg, width, postfix=i + 1)[1])\n self.convs = nn.ModuleList(convs)\n self.bns = nn.ModuleList(bns)\n else:\n assert self.conv_cfg is None, 'conv_cfg must be None for DCN'\n for i in range(scales - 1):\n convs.append(\n build_conv_layer(\n self.dcn,\n width,\n width,\n kernel_size=3,\n stride=self.conv2_stride,\n padding=self.dilation,\n dilation=self.dilation,\n bias=False))\n bns.append(\n build_norm_layer(self.norm_cfg, width, postfix=i + 1)[1])\n self.convs = nn.ModuleList(convs)\n self.bns = nn.ModuleList(bns)\n\n self.conv3 = build_conv_layer(\n self.conv_cfg,\n width * scales,\n self.planes * self.expansion,\n kernel_size=1,\n bias=False)\n self.add_module(self.norm3_name, norm3)\n\n self.stage_type = stage_type\n self.scales = scales\n self.width = width\n delattr(self, 'conv2')\n delattr(self, self.norm2_name)\n\n def forward(self, x):\n \"\"\"Forward function.\"\"\"\n\n def _inner_forward(x):\n identity = x\n\n out = self.conv1(x)\n out = self.norm1(out)\n out = self.relu(out)\n\n if self.with_plugins:\n out = self.forward_plugin(out, self.after_conv1_plugin_names)\n\n spx = torch.split(out, self.width, 1)\n sp = self.convs[0](spx[0].contiguous())\n sp = self.relu(self.bns[0](sp))\n out = sp\n for i in range(1, self.scales - 1):\n if self.stage_type == 'stage':\n sp = spx[i]\n else:\n sp = sp + spx[i]\n sp = self.convs[i](sp.contiguous())\n sp = self.relu(self.bns[i](sp))\n out = torch.cat((out, sp), 1)\n\n if self.stage_type == 'normal' or self.conv2_stride == 1:\n out = torch.cat((out, spx[self.scales - 1]), 1)\n elif self.stage_type == 'stage':\n out = torch.cat((out, self.pool(spx[self.scales - 1])), 1)\n\n if self.with_plugins:\n out = self.forward_plugin(out, self.after_conv2_plugin_names)\n\n out = self.conv3(out)\n out = self.norm3(out)\n\n if self.with_plugins:\n out = self.forward_plugin(out, self.after_conv3_plugin_names)\n\n if self.downsample is not None:\n identity = self.downsample(x)\n\n out += identity\n\n return out\n\n if self.with_cp and x.requires_grad:\n out = cp.checkpoint(_inner_forward, x)\n else:\n out = _inner_forward(x)\n\n out = self.relu(out)\n\n return out\n\n\nclass Res2Layer(nn.Sequential):\n \"\"\"Res2Layer to build Res2Net style backbone.\n\n Args:\n block (nn.Module): block used to build ResLayer.\n inplanes (int): inplanes of block.\n planes (int): planes of block.\n num_blocks (int): number of blocks.\n stride (int): stride of the first block. Default: 1\n avg_down (bool): Use AvgPool instead of stride conv when\n downsampling in the bottle2neck. Default: False\n conv_cfg (dict): dictionary to construct and config conv layer.\n Default: None\n norm_cfg (dict): dictionary to construct and config norm layer.\n Default: dict(type='BN')\n scales (int): Scales used in Res2Net. Default: 4\n base_width (int): Basic width of each scale. Default: 26\n \"\"\"\n\n def __init__(self,\n block,\n inplanes,\n planes,\n num_blocks,\n stride=1,\n avg_down=True,\n conv_cfg=None,\n norm_cfg=dict(type='BN'),\n scales=4,\n base_width=26,\n **kwargs):\n self.block = block\n\n downsample = None\n if stride != 1 or inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.AvgPool2d(\n kernel_size=stride,\n stride=stride,\n ceil_mode=True,\n count_include_pad=False),\n build_conv_layer(\n conv_cfg,\n inplanes,\n planes * block.expansion,\n kernel_size=1,\n stride=1,\n bias=False),\n build_norm_layer(norm_cfg, planes * block.expansion)[1],\n )\n\n layers = []\n layers.append(\n block(\n inplanes=inplanes,\n planes=planes,\n stride=stride,\n downsample=downsample,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n scales=scales,\n base_width=base_width,\n stage_type='stage',\n **kwargs))\n inplanes = planes * block.expansion\n for i in range(1, num_blocks):\n layers.append(\n block(\n inplanes=inplanes,\n planes=planes,\n stride=1,\n conv_cfg=conv_cfg,\n norm_cfg=norm_cfg,\n scales=scales,\n base_width=base_width,\n **kwargs))\n super(Res2Layer, self).__init__(*layers)\n\n\[email protected]_module()\nclass Res2Net(ResNet):\n \"\"\"Res2Net backbone.\n\n Args:\n scales (int): Scales used in Res2Net. Default: 4\n base_width (int): Basic width of each scale. Default: 26\n depth (int): Depth of res2net, from {50, 101, 152}.\n in_channels (int): Number of input image channels. Default: 3.\n num_stages (int): Res2net stages. Default: 4.\n strides (Sequence[int]): Strides of the first block of each stage.\n dilations (Sequence[int]): Dilation of each stage.\n out_indices (Sequence[int]): Output from which stages.\n style (str): `pytorch` or `caffe`. If set to \"pytorch\", the stride-two\n layer is the 3x3 conv layer, otherwise the stride-two layer is\n the first 1x1 conv layer.\n deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv\n avg_down (bool): Use AvgPool instead of stride conv when\n downsampling in the bottle2neck.\n frozen_stages (int): Stages to be frozen (stop grad and set eval mode).\n -1 means not freezing any parameters.\n norm_cfg (dict): Dictionary to construct and config norm layer.\n norm_eval (bool): Whether to set norm layers to eval mode, namely,\n freeze running stats (mean and var). Note: Effect on Batch Norm\n and its variants only.\n plugins (list[dict]): List of plugins for stages, each dict contains:\n\n - cfg (dict, required): Cfg dict to build plugin.\n - position (str, required): Position inside block to insert\n plugin, options are 'after_conv1', 'after_conv2', 'after_conv3'.\n - stages (tuple[bool], optional): Stages to apply plugin, length\n should be same as 'num_stages'.\n with_cp (bool): Use checkpoint or not. Using checkpoint will save some\n memory while slowing down the training speed.\n zero_init_residual (bool): Whether to use zero init for last norm layer\n in resblocks to let them behave as identity.\n\n Example:\n >>> from mmdet.models import Res2Net\n >>> import torch\n >>> self = Res2Net(depth=50, scales=4, base_width=26)\n >>> self.eval()\n >>> inputs = torch.rand(1, 3, 32, 32)\n >>> level_outputs = self.forward(inputs)\n >>> for level_out in level_outputs:\n ... print(tuple(level_out.shape))\n (1, 256, 8, 8)\n (1, 512, 4, 4)\n (1, 1024, 2, 2)\n (1, 2048, 1, 1)\n \"\"\"\n\n arch_settings = {\n 50: (Bottle2neck, (3, 4, 6, 3)),\n 101: (Bottle2neck, (3, 4, 23, 3)),\n 152: (Bottle2neck, (3, 8, 36, 3))\n }\n\n def __init__(self,\n scales=4,\n base_width=26,\n style='pytorch',\n deep_stem=True,\n avg_down=True,\n **kwargs):\n self.scales = scales\n self.base_width = base_width\n super(Res2Net, self).__init__(\n style='pytorch', deep_stem=True, avg_down=True, **kwargs)\n\n def make_res_layer(self, **kwargs):\n return Res2Layer(\n scales=self.scales,\n base_width=self.base_width,\n base_channels=self.base_channels,\n **kwargs)\n\n def init_weights(self, pretrained=None):\n \"\"\"Initialize the weights in backbone.\n\n Args:\n pretrained (str, optional): Path to pre-trained weights.\n Defaults to None.\n \"\"\"\n if isinstance(pretrained, str):\n logger = get_root_logger()\n load_checkpoint(self, pretrained, strict=False, logger=logger)\n elif pretrained is None:\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n kaiming_init(m)\n elif isinstance(m, (_BatchNorm, nn.GroupNorm)):\n constant_init(m, 1)\n\n if self.dcn is not None:\n for m in self.modules():\n if isinstance(m, Bottle2neck):\n # dcn in Res2Net bottle2neck is in ModuleList\n for n in m.convs:\n if hasattr(n, 'conv_offset'):\n constant_init(n.conv_offset, 0)\n\n if self.zero_init_residual:\n for m in self.modules():\n if isinstance(m, Bottle2neck):\n constant_init(m.norm3, 0)\n else:\n raise TypeError('pretrained must be a str or None')\n", "\"\"\"Tests the Assigner objects.\n\nCommandLine:\n pytest tests/test_utils/test_assigner.py\n xdoctest tests/test_utils/test_assigner.py zero\n\"\"\"\nimport torch\n\nfrom mmdet.core.bbox.assigners import (ApproxMaxIoUAssigner,\n CenterRegionAssigner, HungarianAssigner,\n MaxIoUAssigner, PointAssigner)\n\n\ndef test_max_iou_assigner():\n self = MaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n )\n bboxes = torch.FloatTensor([\n [0, 0, 10, 10],\n [10, 10, 20, 20],\n [5, 5, 15, 15],\n [32, 32, 38, 42],\n ])\n gt_bboxes = torch.FloatTensor([\n [0, 0, 10, 9],\n [0, 10, 10, 19],\n ])\n gt_labels = torch.LongTensor([2, 3])\n assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels)\n assert len(assign_result.gt_inds) == 4\n assert len(assign_result.labels) == 4\n\n expected_gt_inds = torch.LongTensor([1, 0, 2, 0])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)\n\n\ndef test_max_iou_assigner_with_ignore():\n self = MaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n ignore_iof_thr=0.5,\n ignore_wrt_candidates=False,\n )\n bboxes = torch.FloatTensor([\n [0, 0, 10, 10],\n [10, 10, 20, 20],\n [5, 5, 15, 15],\n [30, 32, 40, 42],\n ])\n gt_bboxes = torch.FloatTensor([\n [0, 0, 10, 9],\n [0, 10, 10, 19],\n ])\n gt_bboxes_ignore = torch.Tensor([\n [30, 30, 40, 40],\n ])\n assign_result = self.assign(\n bboxes, gt_bboxes, gt_bboxes_ignore=gt_bboxes_ignore)\n\n expected_gt_inds = torch.LongTensor([1, 0, 2, -1])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)\n\n\ndef test_max_iou_assigner_with_empty_gt():\n \"\"\"Test corner case where an image might have no true detections.\"\"\"\n self = MaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n )\n bboxes = torch.FloatTensor([\n [0, 0, 10, 10],\n [10, 10, 20, 20],\n [5, 5, 15, 15],\n [32, 32, 38, 42],\n ])\n gt_bboxes = torch.empty(0, 4)\n assign_result = self.assign(bboxes, gt_bboxes)\n\n expected_gt_inds = torch.LongTensor([0, 0, 0, 0])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)\n\n\ndef test_max_iou_assigner_with_empty_boxes():\n \"\"\"Test corner case where a network might predict no boxes.\"\"\"\n self = MaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n )\n bboxes = torch.empty((0, 4))\n gt_bboxes = torch.FloatTensor([\n [0, 0, 10, 9],\n [0, 10, 10, 19],\n ])\n gt_labels = torch.LongTensor([2, 3])\n\n # Test with gt_labels\n assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels)\n assert len(assign_result.gt_inds) == 0\n assert tuple(assign_result.labels.shape) == (0, )\n\n # Test without gt_labels\n assign_result = self.assign(bboxes, gt_bboxes, gt_labels=None)\n assert len(assign_result.gt_inds) == 0\n assert assign_result.labels is None\n\n\ndef test_max_iou_assigner_with_empty_boxes_and_ignore():\n \"\"\"Test corner case where a network might predict no boxes and\n ignore_iof_thr is on.\"\"\"\n self = MaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n ignore_iof_thr=0.5,\n )\n bboxes = torch.empty((0, 4))\n gt_bboxes = torch.FloatTensor([\n [0, 0, 10, 9],\n [0, 10, 10, 19],\n ])\n gt_bboxes_ignore = torch.Tensor([\n [30, 30, 40, 40],\n ])\n gt_labels = torch.LongTensor([2, 3])\n\n # Test with gt_labels\n assign_result = self.assign(\n bboxes,\n gt_bboxes,\n gt_labels=gt_labels,\n gt_bboxes_ignore=gt_bboxes_ignore)\n assert len(assign_result.gt_inds) == 0\n assert tuple(assign_result.labels.shape) == (0, )\n\n # Test without gt_labels\n assign_result = self.assign(\n bboxes, gt_bboxes, gt_labels=None, gt_bboxes_ignore=gt_bboxes_ignore)\n assert len(assign_result.gt_inds) == 0\n assert assign_result.labels is None\n\n\ndef test_max_iou_assigner_with_empty_boxes_and_gt():\n \"\"\"Test corner case where a network might predict no boxes and no gt.\"\"\"\n self = MaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n )\n bboxes = torch.empty((0, 4))\n gt_bboxes = torch.empty((0, 4))\n assign_result = self.assign(bboxes, gt_bboxes)\n assert len(assign_result.gt_inds) == 0\n\n\ndef test_point_assigner():\n self = PointAssigner()\n points = torch.FloatTensor([ # [x, y, stride]\n [0, 0, 1],\n [10, 10, 1],\n [5, 5, 1],\n [32, 32, 1],\n ])\n gt_bboxes = torch.FloatTensor([\n [0, 0, 10, 9],\n [0, 10, 10, 19],\n ])\n assign_result = self.assign(points, gt_bboxes)\n expected_gt_inds = torch.LongTensor([1, 2, 1, 0])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)\n\n\ndef test_point_assigner_with_empty_gt():\n \"\"\"Test corner case where an image might have no true detections.\"\"\"\n self = PointAssigner()\n points = torch.FloatTensor([ # [x, y, stride]\n [0, 0, 1],\n [10, 10, 1],\n [5, 5, 1],\n [32, 32, 1],\n ])\n gt_bboxes = torch.FloatTensor([])\n assign_result = self.assign(points, gt_bboxes)\n\n expected_gt_inds = torch.LongTensor([0, 0, 0, 0])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)\n\n\ndef test_point_assigner_with_empty_boxes_and_gt():\n \"\"\"Test corner case where an image might predict no points and no gt.\"\"\"\n self = PointAssigner()\n points = torch.FloatTensor([])\n gt_bboxes = torch.FloatTensor([])\n assign_result = self.assign(points, gt_bboxes)\n assert len(assign_result.gt_inds) == 0\n\n\ndef test_approx_iou_assigner():\n self = ApproxMaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n )\n bboxes = torch.FloatTensor([\n [0, 0, 10, 10],\n [10, 10, 20, 20],\n [5, 5, 15, 15],\n [32, 32, 38, 42],\n ])\n gt_bboxes = torch.FloatTensor([\n [0, 0, 10, 9],\n [0, 10, 10, 19],\n ])\n approxs_per_octave = 1\n approxs = bboxes\n squares = bboxes\n assign_result = self.assign(approxs, squares, approxs_per_octave,\n gt_bboxes)\n\n expected_gt_inds = torch.LongTensor([1, 0, 2, 0])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)\n\n\ndef test_approx_iou_assigner_with_empty_gt():\n \"\"\"Test corner case where an image might have no true detections.\"\"\"\n self = ApproxMaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n )\n bboxes = torch.FloatTensor([\n [0, 0, 10, 10],\n [10, 10, 20, 20],\n [5, 5, 15, 15],\n [32, 32, 38, 42],\n ])\n gt_bboxes = torch.FloatTensor([])\n approxs_per_octave = 1\n approxs = bboxes\n squares = bboxes\n assign_result = self.assign(approxs, squares, approxs_per_octave,\n gt_bboxes)\n\n expected_gt_inds = torch.LongTensor([0, 0, 0, 0])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)\n\n\ndef test_approx_iou_assigner_with_empty_boxes():\n \"\"\"Test corner case where an network might predict no boxes.\"\"\"\n self = ApproxMaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n )\n bboxes = torch.empty((0, 4))\n gt_bboxes = torch.FloatTensor([\n [0, 0, 10, 9],\n [0, 10, 10, 19],\n ])\n approxs_per_octave = 1\n approxs = bboxes\n squares = bboxes\n assign_result = self.assign(approxs, squares, approxs_per_octave,\n gt_bboxes)\n assert len(assign_result.gt_inds) == 0\n\n\ndef test_approx_iou_assigner_with_empty_boxes_and_gt():\n \"\"\"Test corner case where an network might predict no boxes and no gt.\"\"\"\n self = ApproxMaxIoUAssigner(\n pos_iou_thr=0.5,\n neg_iou_thr=0.5,\n )\n bboxes = torch.empty((0, 4))\n gt_bboxes = torch.empty((0, 4))\n approxs_per_octave = 1\n approxs = bboxes\n squares = bboxes\n assign_result = self.assign(approxs, squares, approxs_per_octave,\n gt_bboxes)\n assert len(assign_result.gt_inds) == 0\n\n\ndef test_random_assign_result():\n \"\"\"Test random instantiation of assign result to catch corner cases.\"\"\"\n from mmdet.core.bbox.assigners.assign_result import AssignResult\n AssignResult.random()\n\n AssignResult.random(num_gts=0, num_preds=0)\n AssignResult.random(num_gts=0, num_preds=3)\n AssignResult.random(num_gts=3, num_preds=3)\n AssignResult.random(num_gts=0, num_preds=3)\n AssignResult.random(num_gts=7, num_preds=7)\n AssignResult.random(num_gts=7, num_preds=64)\n AssignResult.random(num_gts=24, num_preds=3)\n\n\ndef test_center_region_assigner():\n self = CenterRegionAssigner(pos_scale=0.3, neg_scale=1)\n bboxes = torch.FloatTensor([[0, 0, 10, 10], [10, 10, 20, 20], [8, 8, 9,\n 9]])\n gt_bboxes = torch.FloatTensor([\n [0, 0, 11, 11], # match bboxes[0]\n [10, 10, 20, 20], # match bboxes[1]\n [4.5, 4.5, 5.5, 5.5], # match bboxes[0] but area is too small\n [0, 0, 10, 10], # match bboxes[1] and has a smaller area than gt[0]\n ])\n gt_labels = torch.LongTensor([2, 3, 4, 5])\n assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels)\n assert len(assign_result.gt_inds) == 3\n assert len(assign_result.labels) == 3\n expected_gt_inds = torch.LongTensor([4, 2, 0])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)\n shadowed_labels = assign_result.get_extra_property('shadowed_labels')\n # [8, 8, 9, 9] in the shadowed region of [0, 0, 11, 11] (label: 2)\n assert torch.any(shadowed_labels == torch.LongTensor([[2, 2]]))\n # [8, 8, 9, 9] in the shadowed region of [0, 0, 10, 10] (label: 5)\n assert torch.any(shadowed_labels == torch.LongTensor([[2, 5]]))\n # [0, 0, 10, 10] is already assigned to [4.5, 4.5, 5.5, 5.5].\n # Therefore, [0, 0, 11, 11] (label: 2) is shadowed\n assert torch.any(shadowed_labels == torch.LongTensor([[0, 2]]))\n\n\ndef test_center_region_assigner_with_ignore():\n self = CenterRegionAssigner(\n pos_scale=0.5,\n neg_scale=1,\n )\n bboxes = torch.FloatTensor([\n [0, 0, 10, 10],\n [10, 10, 20, 20],\n ])\n gt_bboxes = torch.FloatTensor([\n [0, 0, 10, 10], # match bboxes[0]\n [10, 10, 20, 20], # match bboxes[1]\n ])\n gt_bboxes_ignore = torch.FloatTensor([\n [0, 0, 10, 10], # match bboxes[0]\n ])\n gt_labels = torch.LongTensor([1, 2])\n assign_result = self.assign(\n bboxes,\n gt_bboxes,\n gt_bboxes_ignore=gt_bboxes_ignore,\n gt_labels=gt_labels)\n assert len(assign_result.gt_inds) == 2\n assert len(assign_result.labels) == 2\n\n expected_gt_inds = torch.LongTensor([-1, 2])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)\n\n\ndef test_center_region_assigner_with_empty_bboxes():\n self = CenterRegionAssigner(\n pos_scale=0.5,\n neg_scale=1,\n )\n bboxes = torch.empty((0, 4)).float()\n gt_bboxes = torch.FloatTensor([\n [0, 0, 10, 10], # match bboxes[0]\n [10, 10, 20, 20], # match bboxes[1]\n ])\n gt_labels = torch.LongTensor([1, 2])\n assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels)\n assert assign_result.gt_inds is None or assign_result.gt_inds.numel() == 0\n assert assign_result.labels is None or assign_result.labels.numel() == 0\n\n\ndef test_center_region_assigner_with_empty_gts():\n self = CenterRegionAssigner(\n pos_scale=0.5,\n neg_scale=1,\n )\n bboxes = torch.FloatTensor([\n [0, 0, 10, 10],\n [10, 10, 20, 20],\n ])\n gt_bboxes = torch.empty((0, 4)).float()\n gt_labels = torch.empty((0, )).long()\n assign_result = self.assign(bboxes, gt_bboxes, gt_labels=gt_labels)\n assert len(assign_result.gt_inds) == 2\n expected_gt_inds = torch.LongTensor([0, 0])\n assert torch.all(assign_result.gt_inds == expected_gt_inds)\n\n\ndef test_hungarian_match_assigner():\n self = HungarianAssigner()\n assert self.iou_cost.iou_mode == 'giou'\n\n # test no gt bboxes\n bbox_pred = torch.rand((10, 4))\n cls_pred = torch.rand((10, 81))\n gt_bboxes = torch.empty((0, 4)).float()\n gt_labels = torch.empty((0, )).long()\n img_meta = dict(img_shape=(10, 8, 3))\n assign_result = self.assign(bbox_pred, cls_pred, gt_bboxes, gt_labels,\n img_meta)\n assert torch.all(assign_result.gt_inds == 0)\n assert torch.all(assign_result.labels == -1)\n\n # test with gt bboxes\n gt_bboxes = torch.FloatTensor([[0, 0, 5, 7], [3, 5, 7, 8]])\n gt_labels = torch.LongTensor([1, 20])\n assign_result = self.assign(bbox_pred, cls_pred, gt_bboxes, gt_labels,\n img_meta)\n assert torch.all(assign_result.gt_inds > -1)\n assert (assign_result.gt_inds > 0).sum() == gt_bboxes.size(0)\n assert (assign_result.labels > -1).sum() == gt_bboxes.size(0)\n\n # test iou mode\n self = HungarianAssigner(\n iou_cost=dict(type='IoUCost', iou_mode='iou', weight=1.0))\n assert self.iou_cost.iou_mode == 'iou'\n assign_result = self.assign(bbox_pred, cls_pred, gt_bboxes, gt_labels,\n img_meta)\n assert torch.all(assign_result.gt_inds > -1)\n assert (assign_result.gt_inds > 0).sum() == gt_bboxes.size(0)\n assert (assign_result.labels > -1).sum() == gt_bboxes.size(0)\n\n # test focal loss mode\n self = HungarianAssigner(\n iou_cost=dict(type='IoUCost', iou_mode='giou', weight=1.0),\n cls_cost=dict(type='FocalLossCost', weight=1.))\n assert self.iou_cost.iou_mode == 'giou'\n assign_result = self.assign(bbox_pred, cls_pred, gt_bboxes, gt_labels,\n img_meta)\n assert torch.all(assign_result.gt_inds > -1)\n assert (assign_result.gt_inds > 0).sum() == gt_bboxes.size(0)\n assert (assign_result.labels > -1).sum() == gt_bboxes.size(0)\n", "import torch\nimport torch.nn.functional as F\n\nfrom mmdet.core import bbox_overlaps\nfrom ..builder import HEADS\nfrom .retina_head import RetinaHead\n\nEPS = 1e-12\n\n\[email protected]_module()\nclass FreeAnchorRetinaHead(RetinaHead):\n \"\"\"FreeAnchor RetinaHead used in https://arxiv.org/abs/1909.02466.\n\n Args:\n num_classes (int): Number of categories excluding the background\n category.\n in_channels (int): Number of channels in the input feature map.\n stacked_convs (int): Number of conv layers in cls and reg tower.\n Default: 4.\n conv_cfg (dict): dictionary to construct and config conv layer.\n Default: None.\n norm_cfg (dict): dictionary to construct and config norm layer.\n Default: norm_cfg=dict(type='GN', num_groups=32,\n requires_grad=True).\n pre_anchor_topk (int): Number of boxes that be token in each bag.\n bbox_thr (float): The threshold of the saturated linear function. It is\n usually the same with the IoU threshold used in NMS.\n gamma (float): Gamma parameter in focal loss.\n alpha (float): Alpha parameter in focal loss.\n \"\"\" # noqa: W605\n\n def __init__(self,\n num_classes,\n in_channels,\n stacked_convs=4,\n conv_cfg=None,\n norm_cfg=None,\n pre_anchor_topk=50,\n bbox_thr=0.6,\n gamma=2.0,\n alpha=0.5,\n **kwargs):\n super(FreeAnchorRetinaHead,\n self).__init__(num_classes, in_channels, stacked_convs, conv_cfg,\n norm_cfg, **kwargs)\n\n self.pre_anchor_topk = pre_anchor_topk\n self.bbox_thr = bbox_thr\n self.gamma = gamma\n self.alpha = alpha\n\n def loss(self,\n cls_scores,\n bbox_preds,\n gt_bboxes,\n gt_labels,\n img_metas,\n gt_bboxes_ignore=None):\n \"\"\"Compute losses of the head.\n\n Args:\n cls_scores (list[Tensor]): Box scores for each scale level\n Has shape (N, num_anchors * num_classes, H, W)\n bbox_preds (list[Tensor]): Box energies / deltas for each scale\n level with shape (N, num_anchors * 4, H, W)\n gt_bboxes (list[Tensor]): each item are the truth boxes for each\n image in [tl_x, tl_y, br_x, br_y] format.\n gt_labels (list[Tensor]): class indices corresponding to each box\n img_metas (list[dict]): Meta information of each image, e.g.,\n image size, scaling factor, etc.\n gt_bboxes_ignore (None | list[Tensor]): specify which bounding\n boxes can be ignored when computing the loss.\n\n Returns:\n dict[str, Tensor]: A dictionary of loss components.\n \"\"\"\n featmap_sizes = [featmap.size()[-2:] for featmap in cls_scores]\n assert len(featmap_sizes) == len(self.anchor_generator.base_anchors)\n\n anchor_list, _ = self.get_anchors(featmap_sizes, img_metas)\n anchors = [torch.cat(anchor) for anchor in anchor_list]\n\n # concatenate each level\n cls_scores = [\n cls.permute(0, 2, 3,\n 1).reshape(cls.size(0), -1, self.cls_out_channels)\n for cls in cls_scores\n ]\n bbox_preds = [\n bbox_pred.permute(0, 2, 3, 1).reshape(bbox_pred.size(0), -1, 4)\n for bbox_pred in bbox_preds\n ]\n cls_scores = torch.cat(cls_scores, dim=1)\n bbox_preds = torch.cat(bbox_preds, dim=1)\n\n cls_prob = torch.sigmoid(cls_scores)\n box_prob = []\n num_pos = 0\n positive_losses = []\n for _, (anchors_, gt_labels_, gt_bboxes_, cls_prob_,\n bbox_preds_) in enumerate(\n zip(anchors, gt_labels, gt_bboxes, cls_prob, bbox_preds)):\n\n with torch.no_grad():\n if len(gt_bboxes_) == 0:\n image_box_prob = torch.zeros(\n anchors_.size(0),\n self.cls_out_channels).type_as(bbox_preds_)\n else:\n # box_localization: a_{j}^{loc}, shape: [j, 4]\n pred_boxes = self.bbox_coder.decode(anchors_, bbox_preds_)\n\n # object_box_iou: IoU_{ij}^{loc}, shape: [i, j]\n object_box_iou = bbox_overlaps(gt_bboxes_, pred_boxes)\n\n # object_box_prob: P{a_{j} -> b_{i}}, shape: [i, j]\n t1 = self.bbox_thr\n t2 = object_box_iou.max(\n dim=1, keepdim=True).values.clamp(min=t1 + 1e-12)\n object_box_prob = ((object_box_iou - t1) /\n (t2 - t1)).clamp(\n min=0, max=1)\n\n # object_cls_box_prob: P{a_{j} -> b_{i}}, shape: [i, c, j]\n num_obj = gt_labels_.size(0)\n indices = torch.stack([\n torch.arange(num_obj).type_as(gt_labels_), gt_labels_\n ],\n dim=0)\n object_cls_box_prob = torch.sparse_coo_tensor(\n indices, object_box_prob)\n\n # image_box_iou: P{a_{j} \\in A_{+}}, shape: [c, j]\n \"\"\"\n from \"start\" to \"end\" implement:\n image_box_iou = torch.sparse.max(object_cls_box_prob,\n dim=0).t()\n\n \"\"\"\n # start\n box_cls_prob = torch.sparse.sum(\n object_cls_box_prob, dim=0).to_dense()\n\n indices = torch.nonzero(box_cls_prob, as_tuple=False).t_()\n if indices.numel() == 0:\n image_box_prob = torch.zeros(\n anchors_.size(0),\n self.cls_out_channels).type_as(object_box_prob)\n else:\n nonzero_box_prob = torch.where(\n (gt_labels_.unsqueeze(dim=-1) == indices[0]),\n object_box_prob[:, indices[1]],\n torch.tensor([\n 0\n ]).type_as(object_box_prob)).max(dim=0).values\n\n # upmap to shape [j, c]\n image_box_prob = torch.sparse_coo_tensor(\n indices.flip([0]),\n nonzero_box_prob,\n size=(anchors_.size(0),\n self.cls_out_channels)).to_dense()\n # end\n\n box_prob.append(image_box_prob)\n\n # construct bags for objects\n match_quality_matrix = bbox_overlaps(gt_bboxes_, anchors_)\n _, matched = torch.topk(\n match_quality_matrix,\n self.pre_anchor_topk,\n dim=1,\n sorted=False)\n del match_quality_matrix\n\n # matched_cls_prob: P_{ij}^{cls}\n matched_cls_prob = torch.gather(\n cls_prob_[matched], 2,\n gt_labels_.view(-1, 1, 1).repeat(1, self.pre_anchor_topk,\n 1)).squeeze(2)\n\n # matched_box_prob: P_{ij}^{loc}\n matched_anchors = anchors_[matched]\n matched_object_targets = self.bbox_coder.encode(\n matched_anchors,\n gt_bboxes_.unsqueeze(dim=1).expand_as(matched_anchors))\n loss_bbox = self.loss_bbox(\n bbox_preds_[matched],\n matched_object_targets,\n reduction_override='none').sum(-1)\n matched_box_prob = torch.exp(-loss_bbox)\n\n # positive_losses: {-log( Mean-max(P_{ij}^{cls} * P_{ij}^{loc}) )}\n num_pos += len(gt_bboxes_)\n positive_losses.append(\n self.positive_bag_loss(matched_cls_prob, matched_box_prob))\n positive_loss = torch.cat(positive_losses).sum() / max(1, num_pos)\n\n # box_prob: P{a_{j} \\in A_{+}}\n box_prob = torch.stack(box_prob, dim=0)\n\n # negative_loss:\n # \\sum_{j}{ FL((1 - P{a_{j} \\in A_{+}}) * (1 - P_{j}^{bg})) } / n||B||\n negative_loss = self.negative_bag_loss(cls_prob, box_prob).sum() / max(\n 1, num_pos * self.pre_anchor_topk)\n\n # avoid the absence of gradients in regression subnet\n # when no ground-truth in a batch\n if num_pos == 0:\n positive_loss = bbox_preds.sum() * 0\n\n losses = {\n 'positive_bag_loss': positive_loss,\n 'negative_bag_loss': negative_loss\n }\n return losses\n\n def positive_bag_loss(self, matched_cls_prob, matched_box_prob):\n \"\"\"Compute positive bag loss.\n\n :math:`-log( Mean-max(P_{ij}^{cls} * P_{ij}^{loc}) )`.\n\n :math:`P_{ij}^{cls}`: matched_cls_prob, classification probability of matched samples.\n\n :math:`P_{ij}^{loc}`: matched_box_prob, box probability of matched samples.\n\n Args:\n matched_cls_prob (Tensor): Classification probabilty of matched\n samples in shape (num_gt, pre_anchor_topk).\n matched_box_prob (Tensor): BBox probability of matched samples,\n in shape (num_gt, pre_anchor_topk).\n\n Returns:\n Tensor: Positive bag loss in shape (num_gt,).\n \"\"\" # noqa: E501, W605\n # bag_prob = Mean-max(matched_prob)\n matched_prob = matched_cls_prob * matched_box_prob\n weight = 1 / torch.clamp(1 - matched_prob, 1e-12, None)\n weight /= weight.sum(dim=1).unsqueeze(dim=-1)\n bag_prob = (weight * matched_prob).sum(dim=1)\n # positive_bag_loss = -self.alpha * log(bag_prob)\n return self.alpha * F.binary_cross_entropy(\n bag_prob, torch.ones_like(bag_prob), reduction='none')\n\n def negative_bag_loss(self, cls_prob, box_prob):\n \"\"\"Compute negative bag loss.\n\n :math:`FL((1 - P_{a_{j} \\in A_{+}}) * (1 - P_{j}^{bg}))`.\n\n :math:`P_{a_{j} \\in A_{+}}`: Box_probability of matched samples.\n\n :math:`P_{j}^{bg}`: Classification probability of negative samples.\n\n Args:\n cls_prob (Tensor): Classification probability, in shape\n (num_img, num_anchors, num_classes).\n box_prob (Tensor): Box probability, in shape\n (num_img, num_anchors, num_classes).\n\n Returns:\n Tensor: Negative bag loss in shape (num_img, num_anchors, num_classes).\n \"\"\" # noqa: E501, W605\n prob = cls_prob * (1 - box_prob)\n # There are some cases when neg_prob = 0.\n # This will cause the neg_prob.log() to be inf without clamp.\n prob = prob.clamp(min=EPS, max=1 - EPS)\n negative_bag_loss = prob**self.gamma * F.binary_cross_entropy(\n prob, torch.zeros_like(prob), reduction='none')\n return (1 - self.alpha) * negative_bag_loss\n" ]
[ [ "torch.cat", "torch.nn.ModuleList", "torch.nn.AvgPool2d", "torch.utils.checkpoint.checkpoint", "torch.split" ], [ "torch.all", "torch.LongTensor", "torch.empty", "torch.Tensor", "torch.FloatTensor", "torch.rand" ], [ "torch.sigmoid", "torch.cat", "torch.topk", "torch.zeros_like", "torch.sparse_coo_tensor", "torch.exp", "torch.tensor", "torch.no_grad", "torch.nonzero", "torch.arange", "torch.stack", "torch.clamp", "torch.ones_like", "torch.sparse.sum" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
RedVoxInc/libquantum
[ "5e0d741e69be0ac1b94c018a4a0de99f4630deae" ]
[ "examples/03_sweep_linear.py" ]
[ "\"\"\"\nlibquantum example 3: 03_sweep_linear.py\nConstruct classic linear chirp and illustrate CWT and STFT TRFs.\n\"\"\"\n\nimport os\nfrom pathlib import Path\nimport numpy as np\nimport scipy.io.wavfile\nimport matplotlib.pyplot as plt\nfrom libquantum import atoms, entropy, scales, spectra, utils, synthetics\nimport libquantum.plot_templates.plot_time_frequency_reps as pltq\n\n\nif __name__ == \"__main__\":\n \"\"\"\n Exercises with classic linear sweep\n Option of exporting to wav\n \"\"\"\n\n # Do you want to export a wav file? True or False\n do_save_wave = False\n # If True, saves to home directory\n home_dir: str = str(Path.home())\n # Or can specify a preferred wav file directory\n # home_dir: str = \"/Users/mgarces/Documents/DATA_API_M/synthetics\"\n output_wav_directory = os.path.join(home_dir, \"wav\")\n\n EVENT_NAME = \"redshift_linear_sweep\"\n print(\"Event Name: \" + EVENT_NAME)\n wav_filename = EVENT_NAME\n order_number_input = 3\n\n station_id_str = 'Synth'\n run_time_epoch_s = utils.datetime_now_epoch_s()\n\n # Chirp type\n is_redshift = True\n\n sig_wf_sample_rate_hz = 8000.\n sig_frequency_hz_start = 40.\n sig_frequency_hz_end = 400.\n sig_duration_s = 13.19675\n head_s = 0.5\n\n # sig_wf_sample_rate_hz = 8000.\n # sig_frequency_hz_start = 40.\n # sig_frequency_hz_end = 400.\n # sig_duration_s = 13.19675\n # head_s = 0.5\n\n\n # Blueshift sweep\n sig_wf_blu, sig_wf_epoch_s = synthetics.chirp_linear_in_noise(snr_bits=12.,\n sample_rate_hz=sig_wf_sample_rate_hz,\n duration_s=sig_duration_s,\n frequency_start_hz=sig_frequency_hz_start,\n frequency_end_hz=sig_frequency_hz_end,\n intro_s=head_s,\n outro_s=head_s)\n sig_wf_red = np.flipud(sig_wf_blu)\n\n # Choose origin and red/blue shift\n sig_wf_epoch_s += run_time_epoch_s\n sig_wf = np.copy(sig_wf_red)\n\n # Antialias filter synthetic\n synthetics.antialias_halfNyquist(synth=sig_wf)\n\n # Export to wav directory\n if do_save_wave:\n wav_sample_rate_hz = 8000.\n export_filename = os.path.join(output_wav_directory, wav_filename + \"_8kz.wav\")\n synth_wav = 0.9 * np.real(sig_wf) / np.max(np.abs((np.real(sig_wf))))\n scipy.io.wavfile.write(export_filename, int(wav_sample_rate_hz), synth_wav)\n\n # Frame to mic start and end and plot\n event_reference_time_epoch_s = sig_wf_epoch_s[0]\n\n max_time_s, min_frequency_hz = scales.from_duration(band_order_Nth=order_number_input,\n sig_duration_s=sig_duration_s)\n print('\\nRequest Order N=', order_number_input)\n print('Lowest frequency in hz that can support this order for this signal duration is ', min_frequency_hz)\n print('Scale with signal duration and to Nyquist, default G2 base re F1')\n\n # Select plot frequencies\n fmin = np.ceil(min_frequency_hz)\n fmax = sig_wf_sample_rate_hz/2.\n\n # TFR SECTION\n # Compute complex wavelet transform (cwt) from signal duration\n if is_redshift:\n mic_cwt, mic_cwt_bits, mic_cwt_time_s, mic_cwt_frequency_hz = \\\n atoms.cwt_chirp_from_sig(sig_wf=sig_wf,\n frequency_sample_rate_hz=sig_wf_sample_rate_hz,\n band_order_Nth=order_number_input,\n dictionary_type=\"tone\",\n index_shift=-1)\n\n else:\n mic_cwt, mic_cwt_bits, mic_cwt_time_s, mic_cwt_frequency_hz = \\\n atoms.cwt_chirp_from_sig(sig_wf=sig_wf,\n frequency_sample_rate_hz=sig_wf_sample_rate_hz,\n band_order_Nth=order_number_input,\n dictionary_type=\"tone\")\n\n mic_cwt_snr, mic_cwt_snr_bits, mic_cwt_snr_entropy = entropy.snr_mean_max(tfr_coeff_complex=mic_cwt)\n\n pltq.plot_wf_mesh_mesh_vert(redvox_id=station_id_str,\n wf_panel_2_sig=sig_wf,\n wf_panel_2_time=sig_wf_epoch_s,\n mesh_time=mic_cwt_time_s,\n mesh_frequency=mic_cwt_frequency_hz,\n mesh_panel_1_trf=mic_cwt_bits,\n mesh_panel_1_colormap_scaling=\"range\",\n mesh_panel_0_tfr=mic_cwt_snr_entropy,\n wf_panel_2_units=\"Norm\",\n mesh_panel_1_cbar_units=\"bits\",\n mesh_panel_0_cbar_units=\"eSNR bits\",\n start_time_epoch=event_reference_time_epoch_s,\n figure_title=\"CWT for \" + EVENT_NAME,\n frequency_hz_ymin=fmin,\n frequency_hz_ymax=fmax)\n\n # Compute short term Fourier transform (STFT) from segmented signal duration\n mic_stft, mic_stft_bits, mic_stft_time_s, mic_stft_frequency_hz = \\\n spectra.stft_from_sig(sig_wf=sig_wf,\n frequency_sample_rate_hz=sig_wf_sample_rate_hz,\n band_order_Nth=order_number_input)\n\n mic_stft_snr, mic_stft_snr_bits, mic_stft_snr_entropy = entropy.snr_mean_max(tfr_coeff_complex=mic_stft)\n\n # Log frequency is the default, for linear use frequency_scaling=\"linear\",\n pltq.plot_wf_mesh_mesh_vert(frequency_scaling=\"log\",\n redvox_id=station_id_str,\n wf_panel_2_sig=sig_wf,\n wf_panel_2_time=sig_wf_epoch_s,\n mesh_time=mic_stft_time_s,\n mesh_frequency=mic_stft_frequency_hz,\n mesh_panel_1_trf=mic_stft_bits,\n mesh_panel_1_colormap_scaling=\"range\",\n mesh_panel_0_tfr=mic_stft_snr_entropy,\n wf_panel_2_units=\"Norm\",\n mesh_panel_1_cbar_units=\"bits\",\n mesh_panel_0_cbar_units=\"eSNR bits\",\n figure_title=\"STFT for \" + EVENT_NAME,\n frequency_hz_ymin=fmin,\n frequency_hz_ymax=fmax)\n plt.show()\n\n" ]
[ [ "numpy.flipud", "numpy.ceil", "numpy.copy", "numpy.real", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jiangnanboy/gcn_for_prediction_of_protein_interactions
[ "b2a9eb06cdfe0971d0c352299db1075ec4827dd9" ]
[ "src/graph_nheads_att_gan/train.py" ]
[ "import scipy.sparse as sp\nimport numpy as np\nimport torch\nimport time\nimport os\nfrom configparser import ConfigParser\n\nimport sys\nsys.path.append('/home/shiyan/project/gcn_for_prediction_of_protein_interactions/')\n\nfrom src.util.load_data import load_data, sparse_to_tuple, mask_test_edges, preprocess_graph\nfrom src.util.loss import arga_loss_function, varga_loss_function\nfrom src.util.metrics import get_roc_score\nfrom src.util import define_optimizer\nfrom src.graph_nheads_att_gan.model import NHGATModelGAN\n\nDEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\nclass Train():\n def __init__(self):\n pass\n\n def train_model(self, config_path):\n if os.path.exists(config_path) and (os.path.split(config_path)[1].split('.')[0] == 'config') and (\n os.path.splitext(config_path)[1].split('.')[1] == 'cfg'):\n # load config file\n config = ConfigParser()\n config.read(config_path)\n section = config.sections()[0]\n\n # data catalog path\n data_catalog = config.get(section, \"data_catalog\")\n\n # train file path\n train_file_name = config.get(section, \"train_file_name\")\n\n # model save/load path\n model_path = config.get(section, \"model_path\")\n\n # model param config\n hidden_dim1 = config.getint(section, \"hidden_dim1\")\n hidden_dim2 = config.getint(section, \"hidden_dim2\")\n hidden_dim3 = config.getint(section, 'hidden_dim3')\n num_heads = config.getint(section, 'num_heads')\n dropout = config.getfloat(section, \"dropout\")\n vae_bool = config.getboolean(section, 'vae_bool')\n alpha = config.getfloat(section, 'alpha')\n lr = config.getfloat(section, \"lr\")\n lr_decay = config.getfloat(section, 'lr_decay')\n weight_decay = config.getfloat(section, \"weight_decay\")\n gamma = config.getfloat(section, \"gamma\")\n momentum = config.getfloat(section, \"momentum\")\n eps = config.getfloat(section, \"eps\")\n clip = config.getfloat(section, \"clip\")\n epochs = config.getint(section, \"epochs\")\n optimizer_name = config.get(section, \"optimizer\")\n\n # 加载相关数据\n adj = load_data(os.path.join(data_catalog, train_file_name))\n num_nodes = adj.shape[0]\n num_edges = adj.sum()\n\n features = sparse_to_tuple(sp.identity(num_nodes))\n num_features = features[2][1]\n\n # 去除对角线元素\n # 下边的右部分为:返回adj_orig的对角元素(一维),并增加一维,抽出adj_orig的对角元素并构建只有这些对角元素的对角矩阵\n adj_orig = adj - sp.dia_matrix((adj.diagonal()[np.newaxis, :], [0]), shape=adj.shape)\n adj_orig.eliminate_zeros()\n\n adj_train, train_edges, val_edges, val_edges_false, test_edges, test_edges_false = mask_test_edges(adj_orig)\n\n adj = adj_train\n\n # 返回D^{-0.5}SD^{-0.5}的coords, data, shape,其中S=A+I\n adj_norm = preprocess_graph(adj)\n adj_label = adj_train + sp.eye(adj_train.shape[0])\n # adj_label = sparse_to_tuple(adj_label)\n adj_label = torch.FloatTensor(adj_label.toarray()).to(DEVICE)\n '''\n 注意,adj的每个元素非1即0。pos_weight是用于训练的邻接矩阵中负样本边(既不存在的边)和正样本边的倍数(即比值),这个数值在二分类交叉熵损失函数中用到,\n 如果正样本边所占的比例和负样本边所占比例失衡,比如正样本边很多,负样本边很少,那么在求loss的时候可以提供weight参数,将正样本边的weight设置小一点,负样本边的weight设置大一点,\n 此时能够很好的平衡两类在loss中的占比,任务效果可以得到进一步提升。参考:https://www.zhihu.com/question/383567632\n 负样本边的weight都为1,正样本边的weight都为pos_weight\n '''\n pos_weight = float(adj.shape[0] * adj.shape[0] - num_edges) / num_edges\n norm = adj.shape[0] * adj.shape[0] / float((adj.shape[0] * adj.shape[0] - adj.sum()) * 2)\n\n # create model\n print('create model ...')\n model = NHGATModelGAN(num_features, hidden_dim1=hidden_dim1, hidden_dim2=hidden_dim2, hidden_dim3=hidden_dim3, num_heads=num_heads, dropout=dropout, alpha=alpha, vae_bool=vae_bool)\n\n # define optimizer\n if optimizer_name == 'adam':\n optimizer = define_optimizer.define_optimizer_adam(model, lr=lr, weight_decay=weight_decay)\n\n elif optimizer_name == 'adamw':\n optimizer = define_optimizer.define_optimizer_adamw(model, lr=lr, weight_decay=weight_decay)\n\n elif optimizer_name == 'sgd':\n optimizer = define_optimizer.define_optimizer_sgd(model, lr=lr, momentum=momentum,\n weight_decay=weight_decay)\n\n elif optimizer_name == 'adagrad':\n optimizer = define_optimizer.define_optimizer_adagrad(model, lr=lr, lr_decay=lr_decay,\n weight_decay=weight_decay)\n\n elif optimizer_name == 'rmsprop':\n optimizer = define_optimizer.define_optimizer_rmsprop(model, lr=lr, weight_decay=weight_decay,\n momentum=momentum)\n\n elif optimizer_name == 'adadelta':\n optimizer = define_optimizer.define_optimizer_adadelta(model, lr=lr, weight_decay=weight_decay)\n\n else:\n raise NameError('No define optimization function name!')\n\n model = model.to(DEVICE)\n # 稀疏张量被表示为一对致密张量:一维张量和二维张量的索引。可以通过提供这两个张量来构造稀疏张量\n adj_norm = torch.sparse.FloatTensor(torch.LongTensor(adj_norm[0].T),\n torch.FloatTensor(adj_norm[1]),\n torch.Size(adj_norm[2]))\n features = torch.sparse.FloatTensor(torch.LongTensor(features[0].T),\n torch.FloatTensor(features[1]),\n torch.Size(features[2])).to_dense()\n adj_norm = adj_norm.to(DEVICE)\n features = features.to(DEVICE)\n norm = torch.FloatTensor(np.array(norm)).to(DEVICE)\n pos_weight = torch.tensor(pos_weight).to(DEVICE)\n num_nodes = torch.tensor(num_nodes).to(DEVICE)\n\n print('start training...')\n best_valid_roc_score = float('-inf')\n hidden_emb = None\n model.train()\n for epoch in range(epochs):\n t = time.time()\n optimizer.zero_grad()\n # 解码后的邻接矩阵,判别器\n recovered, dis_real, dis_fake, mu, logvar = model(features, adj_norm)\n if vae_bool:\n loss = varga_loss_function(preds=recovered, labels=adj_label,\n mu=mu, logvar=logvar,\n dis_real=dis_real, dis_fake=dis_fake,\n n_nodes=num_nodes,\n norm=norm, pos_weight=pos_weight)\n else:\n loss = arga_loss_function(preds=recovered, labels=adj_label,\n dis_real=dis_real, dis_fake=dis_fake,\n norm=norm, pos_weight=pos_weight)\n loss.backward()\n torch.nn.utils.clip_grad_norm_(model.parameters(), clip)\n cur_loss = loss.item()\n optimizer.step()\n\n hidden_emb = mu.data.cpu().numpy()\n # 评估验证集,val set\n roc_score, ap_score = get_roc_score(hidden_emb, adj_orig, val_edges, val_edges_false)\n # 保存最好的roc score\n if roc_score > best_valid_roc_score:\n best_valid_roc_score = roc_score\n # 不需要保存整个model,只需保存hidden_emb,因为后面的解码是用hidden_emb内积的形式作推断\n np.save(model_path, hidden_emb)\n\n print(\"Epoch:\", '%04d' % (epoch + 1), \"train_loss = \", \"{:.5f}\".format(cur_loss),\n \"val_roc_score = \", \"{:.5f}\".format(roc_score),\n \"average_precision_score = \", \"{:.5f}\".format(ap_score),\n \"time=\", \"{:.5f}\".format(time.time() - t)\n )\n\n print(\"Optimization Finished!\")\n\n # 评估测试集,test set\n roc_score, ap_score = get_roc_score(hidden_emb, adj_orig, test_edges, test_edges_false)\n print('test roc score: {}'.format(roc_score))\n print('test ap score: {}'.format(ap_score))\n\n else:\n raise FileNotFoundError('File config.cfg not found : ' + config_path)\n\nif __name__ == '__main__':\n config_path = os.path.join(os.getcwd(), 'config.cfg')\n train = Train()\n train.train_model(config_path)\n" ]
[ [ "torch.LongTensor", "torch.Size", "scipy.sparse.eye", "numpy.save", "torch.tensor", "scipy.sparse.identity", "torch.FloatTensor", "torch.cuda.is_available", "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.7", "1.0", "0.10", "1.2", "0.14", "0.19", "1.5", "0.12", "0.17", "0.13", "1.6", "1.4", "1.9", "1.3", "1.10", "0.15", "0.18", "0.16", "1.8" ], "tensorflow": [] } ]
DocYard-ai/UCR
[ "7618aa336f56e71d9fd8cdc2d591e3d138e3dc68" ]
[ "ucr/core/architecture/head/rec_srn_head.py" ]
[ "# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.\n#\n# Modifications copyright (c) 2021 DocYard Authors. All Rights Reserve.\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 __future__ import absolute_import, division, print_function\n\nfrom collections import OrderedDict\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nfrom .self_attention import WrapEncoder, WrapEncoderForFeature\n\ngradient_clip = 10\n\nfrom functools import partial\n\n\nclass PVAM(nn.Module):\n def __init__(\n self,\n in_channels,\n char_num,\n max_text_length,\n num_heads,\n num_encoder_tus,\n hidden_dims,\n ):\n super(PVAM, self).__init__()\n self.char_num = char_num\n self.max_length = max_text_length\n self.num_heads = num_heads\n self.num_encoder_TUs = num_encoder_tus\n self.hidden_dims = hidden_dims\n # Transformer encoder\n t = 256\n self.wrap_encoder_for_feature = WrapEncoderForFeature(\n src_vocab_size=1,\n max_length=t,\n n_layer=self.num_encoder_TUs,\n n_head=self.num_heads,\n d_key=int(self.hidden_dims / self.num_heads),\n d_value=int(self.hidden_dims / self.num_heads),\n d_model=self.hidden_dims,\n d_inner_hid=self.hidden_dims,\n prepostprocess_dropout=0.1,\n attention_dropout=0.1,\n relu_dropout=0.1,\n preprocess_cmd=\"n\",\n postprocess_cmd=\"da\",\n weight_sharing=True,\n )\n\n # PVAM\n self.flatten0 = nn.Flatten(start_dim=0, end_dim=1)\n self.fc0 = nn.Linear(\n in_features=in_channels,\n out_features=in_channels,\n )\n self.emb = nn.Embedding(\n num_embeddings=self.max_length, embedding_dim=in_channels\n )\n self.flatten1 = nn.Flatten(start_dim=0, end_dim=2)\n self.fc1 = nn.Linear(\n in_features=in_channels, out_features=1, bias=False\n )\n\n def forward(self, inputs, encoder_word_pos, gsrm_word_pos):\n b, c, h, w = inputs.shape\n conv_features = torch.reshape(inputs, shape=(-1, c, h * w))\n conv_features = conv_features.permute(0, 2, 1)\n # transformer encoder\n b, t, c = conv_features.shape\n\n enc_inputs = [conv_features, encoder_word_pos, None]\n word_features = self.wrap_encoder_for_feature(enc_inputs)\n\n # pvam\n b, t, c = word_features.shape\n word_features = self.fc0(word_features)\n word_features_ = torch.reshape(word_features, (-1, 1, t, c))\n word_features_ = torch.tile(word_features_, (1, self.max_length, 1, 1))\n word_pos_feature = self.emb(gsrm_word_pos)\n word_pos_feature_ = torch.reshape(\n word_pos_feature, (-1, self.max_length, 1, c)\n )\n word_pos_feature_ = torch.tile(word_pos_feature_, (1, 1, t, 1))\n y = word_pos_feature_ + word_features_\n y = F.tanh(y)\n attention_weight = self.fc1(y)\n attention_weight = torch.reshape(\n attention_weight, shape=(-1, self.max_length, t)\n )\n attention_weight = F.softmax(attention_weight, dim=-1)\n pvam_features = torch.bmm(\n attention_weight, word_features\n ) # [b, max_length, c]\n return pvam_features\n\n\nclass GSRM(nn.Module):\n def __init__(\n self,\n in_channels,\n char_num,\n max_text_length,\n num_heads,\n num_encoder_tus,\n num_decoder_tus,\n hidden_dims,\n ):\n super(GSRM, self).__init__()\n self.char_num = char_num\n self.max_length = max_text_length\n self.num_heads = num_heads\n self.num_encoder_TUs = num_encoder_tus\n self.num_decoder_TUs = num_decoder_tus\n self.hidden_dims = hidden_dims\n\n self.fc0 = nn.Linear(\n in_features=in_channels, out_features=self.char_num\n )\n self.wrap_encoder0 = WrapEncoder(\n src_vocab_size=self.char_num + 1,\n max_length=self.max_length,\n n_layer=self.num_decoder_TUs,\n n_head=self.num_heads,\n d_key=int(self.hidden_dims / self.num_heads),\n d_value=int(self.hidden_dims / self.num_heads),\n d_model=self.hidden_dims,\n d_inner_hid=self.hidden_dims,\n prepostprocess_dropout=0.1,\n attention_dropout=0.1,\n relu_dropout=0.1,\n preprocess_cmd=\"n\",\n postprocess_cmd=\"da\",\n weight_sharing=True,\n )\n\n self.wrap_encoder1 = WrapEncoder(\n src_vocab_size=self.char_num + 1,\n max_length=self.max_length,\n n_layer=self.num_decoder_TUs,\n n_head=self.num_heads,\n d_key=int(self.hidden_dims / self.num_heads),\n d_value=int(self.hidden_dims / self.num_heads),\n d_model=self.hidden_dims,\n d_inner_hid=self.hidden_dims,\n prepostprocess_dropout=0.1,\n attention_dropout=0.1,\n relu_dropout=0.1,\n preprocess_cmd=\"n\",\n postprocess_cmd=\"da\",\n weight_sharing=True,\n )\n\n # self.mul = lambda x: torch.matmul(x,\n # (self.wrap_encoder0.prepare_decoder.emb0.weightk).transpose(-2, -1)) # ! This is an error here, weightk is wrong correct it by visualizing torch model_dict\n\n self.mul = partial(\n self.f, self.wrap_encoder0.prepare_decoder.emb0.weight\n )\n\n @staticmethod\n def f(w, x):\n return torch.matmul(x, w.transpose(-2, -1))\n\n def forward(\n self, inputs, gsrm_word_pos, gsrm_slf_attn_bias1, gsrm_slf_attn_bias2\n ):\n # ===== GSRM Visual-to-semantic embedding block =====\n b, t, c = inputs.shape\n pvam_features = torch.reshape(inputs, (-1, c))\n word_out = self.fc0(pvam_features)\n word_ids = torch.argmax(F.softmax(word_out), dim=1)\n word_ids = torch.reshape(word_ids, shape=(-1, t, 1))\n\n # ===== GSRM Semantic reasoning block =====\n \"\"\"\n This module is achieved through bi-transformers,\n ngram_feature1 is the froward one, ngram_fetaure2 is the backward one\n \"\"\"\n pad_idx = self.char_num\n\n word1 = word_ids.float()\n pad1 = nn.ConstantPad1d((1, 0), value=1.0 * pad_idx)\n word1 = pad1(word1.permute(0, 2, 1)).permute(0, 2, 1)\n word1 = word1.long()\n word1 = word1[:, :-1, :]\n word2 = word_ids\n\n enc_inputs_1 = [word1, gsrm_word_pos, gsrm_slf_attn_bias1]\n enc_inputs_2 = [word2, gsrm_word_pos, gsrm_slf_attn_bias2]\n\n gsrm_feature1 = self.wrap_encoder0(enc_inputs_1)\n gsrm_feature2 = self.wrap_encoder1(enc_inputs_2)\n\n pad = nn.ConstantPad1d((0, 1), value=0.0)\n gsrm_feature2 = pad(gsrm_feature2.permute(0, 2, 1)).permute(0, 2, 1)\n gsrm_feature2 = gsrm_feature2[\n :,\n 1:,\n ]\n gsrm_features = gsrm_feature1 + gsrm_feature2\n\n gsrm_out = self.mul(gsrm_features)\n\n b, t, c = gsrm_out.shape\n gsrm_out = torch.reshape(gsrm_out, (-1, c))\n\n return gsrm_features, word_out, gsrm_out\n\n\nclass VSFD(nn.Module):\n def __init__(self, in_channels=512, pvam_ch=512, char_num=38):\n super(VSFD, self).__init__()\n self.char_num = char_num\n self.fc0 = nn.Linear(in_features=in_channels * 2, out_features=pvam_ch)\n self.fc1 = nn.Linear(in_features=pvam_ch, out_features=self.char_num)\n\n def forward(self, pvam_feature, gsrm_feature):\n b, t, c1 = pvam_feature.shape\n b, t, c2 = gsrm_feature.shape\n combine_feature_ = torch.cat([pvam_feature, gsrm_feature], dim=2)\n img_comb_feature_ = torch.reshape(\n combine_feature_, shape=(-1, c1 + c2)\n )\n img_comb_feature_map = self.fc0(img_comb_feature_)\n img_comb_feature_map = torch.sigmoid(img_comb_feature_map)\n img_comb_feature_map = torch.reshape(\n img_comb_feature_map, shape=(-1, t, c1)\n )\n combine_feature = (\n img_comb_feature_map * pvam_feature\n + (1.0 - img_comb_feature_map) * gsrm_feature\n )\n img_comb_feature = torch.reshape(combine_feature, shape=(-1, c1))\n\n out = self.fc1(img_comb_feature)\n return out\n\n\nclass SRNHead(nn.Module):\n def __init__(\n self,\n in_channels,\n out_channels,\n max_text_length,\n num_heads,\n num_encoder_TUs,\n num_decoder_TUs,\n hidden_dims,\n **kwargs\n ):\n super(SRNHead, self).__init__()\n self.char_num = out_channels\n self.max_length = max_text_length\n self.num_heads = num_heads\n self.num_encoder_TUs = num_encoder_TUs\n self.num_decoder_TUs = num_decoder_TUs\n self.hidden_dims = hidden_dims\n\n self.pvam = PVAM(\n in_channels=in_channels,\n char_num=self.char_num,\n max_text_length=self.max_length,\n num_heads=self.num_heads,\n num_encoder_tus=self.num_encoder_TUs,\n hidden_dims=self.hidden_dims,\n )\n\n self.gsrm = GSRM(\n in_channels=in_channels,\n char_num=self.char_num,\n max_text_length=self.max_length,\n num_heads=self.num_heads,\n num_encoder_tus=self.num_encoder_TUs,\n num_decoder_tus=self.num_decoder_TUs,\n hidden_dims=self.hidden_dims,\n )\n self.vsfd = VSFD(in_channels=in_channels, char_num=self.char_num)\n\n self.gsrm.wrap_encoder1.prepare_decoder.emb0 = (\n self.gsrm.wrap_encoder0.prepare_decoder.emb0\n )\n\n def forward(self, inputs, others):\n encoder_word_pos = others[0]\n gsrm_word_pos = others[1]\n gsrm_slf_attn_bias1 = others[2]\n gsrm_slf_attn_bias2 = others[3]\n\n pvam_feature = self.pvam(inputs, encoder_word_pos, gsrm_word_pos)\n\n gsrm_feature, word_out, gsrm_out = self.gsrm(\n pvam_feature,\n gsrm_word_pos,\n gsrm_slf_attn_bias1,\n gsrm_slf_attn_bias2,\n )\n\n final_out = self.vsfd(pvam_feature, gsrm_feature)\n if not self.training:\n final_out = F.softmax(final_out, dim=1)\n\n _, decoded_out = torch.topk(final_out, k=1)\n\n predicts = OrderedDict(\n [\n (\"predict\", final_out),\n (\"pvam_feature\", pvam_feature),\n (\"decoded_out\", decoded_out),\n (\"word_out\", word_out),\n (\"gsrm_out\", gsrm_out),\n ]\n )\n\n return predicts\n" ]
[ [ "torch.nn.ConstantPad1d", "torch.nn.functional.softmax", "torch.sigmoid", "torch.cat", "torch.tile", "torch.reshape", "torch.nn.Flatten", "torch.nn.Embedding", "torch.nn.Linear", "torch.bmm", "torch.topk", "torch.nn.functional.tanh" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
glee1228/segment_temporal_context_aggregation
[ "e5778f848f1cfd89bd1f77beb5e1b38a66a2f13d" ]
[ "utils.py" ]
[ "import io\nimport os\nimport random\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom PIL import Image\n\n\ndef resize_axis(tensor, axis, new_size, fill_value=0, random_sampling=False):\n \"\"\"Truncates or pads a tensor to new_size on on a given axis.\n Truncate or extend tensor such that tensor.shape[axis] == new_size. If the\n size increases, the padding will be performed at the end, using fill_value.\n Args:\n tensor: The tensor to be resized.\n axis: An integer representing the dimension to be sliced.\n new_size: An integer or 0d tensor representing the new value for\n tensor.shape[axis].\n fill_value: Value to use to fill any new entries in the tensor. Will be\n cast to the type of tensor.\n Returns:\n The resized tensor.\n \"\"\"\n tensor = torch.Tensor(tensor)\n shape = list(tensor.shape)\n\n pad_shape = shape[:]\n pad_shape[axis] = max(0, new_size - shape[axis])\n\n start = 0 if shape[axis] <= new_size else np.random.randint(\n shape[axis] - new_size) # random clip\n old_length = shape[axis]\n shape[axis] = min(shape[axis], new_size)\n\n resized = torch.cat([\n torch.index_select(tensor, dim=axis, index=torch.randint(old_length, (new_size,))\n ) if start > 0 and random_sampling else torch.narrow(tensor, dim=axis, start=start, length=shape[axis]),\n torch.Tensor(*pad_shape).fill_(fill_value)\n ], dim=axis)\n\n return resized\n\n\nclass CircleLoss(torch.nn.Module):\n def __init__(self, m=0.25, gamma=256):\n super(CircleLoss, self).__init__()\n self.m = m\n self.gamma = gamma\n self.loss = torch.nn.CrossEntropyLoss()\n\n def forward(self, logits, labels):\n alpha = torch.clamp_min(logits + self.m, min=0).detach() # an\n alpha[labels] = torch.clamp_min(-logits[labels] + 1 + self.m, min=0).detach() # ap\n\n delta = torch.ones_like(logits, device=logits.device, dtype=logits.dtype) * self.m # delta_n\n delta[labels] = 1 - self.m # delta_p\n\n return self.loss(alpha * (logits - delta) * self.gamma, labels)" ]
[ [ "torch.nn.CrossEntropyLoss", "torch.randint", "torch.Tensor", "torch.narrow", "torch.clamp_min", "torch.ones_like", "numpy.random.randint" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
WISE-Project/wiselib2
[ "9daf7b3b72e81d154fe094c05000406ee203c3de" ]
[ "wiselib2/Noise.py" ]
[ "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 07 14:08:31 2016\n\n@author: Mic\n\"\"\"\nfrom __future__ import division\nfrom wiselib2.must import *\nimport numpy as np\nimport wiselib2.Rayman as rm\nGauss1d = lambda x ,y : None\nfrom scipy import interpolate as interpolate\n\nfrom matplotlib import pyplot as plt\n\nclass PsdFuns:\n\t'''\n\tEnsemble of possible Psd Functions.\n\tEach element is a callable Psd.\n\tMost used are\n\t\tPsdFuns.PowerLaw(x,a,b)\n\t\tPsdFuns.Interp(x, xData, yData)\n\t'''\n\t@staticmethod\n\tdef Flat(x, *args):\n\t\tN = len(x)\n\t\treturn np.zeros([1,N]) +1\n\t@staticmethod\n\tdef PowerLaw(x,a,b):\n\t\treturn a*x**b\n\t@staticmethod\n\tdef Gaussian(x,sigma, x0=0):\n\t\treturn np.exp(-0.5 * (x-x0)**2/sigma**2)\n\t@staticmethod\n\tdef Interp(x, xData, yData):\n\t\tf = interpolate.interp1d(xData, yData)\n\n\t\treturn f(x)\n\n\ndef PsdFun2Noise_1d(N,dx, PsdFun, PsdArgs):\n\t'''\n\t\tGenerates a noise pattern based an the Power spectral density returned\n\t\tby PsdFun\n\t'''\n\tx = np.arange(0,N//2+1, dx)\n\tyHalf = PsdFun(x, *PsdArgs)\n\ty = Psd2NoisePattern_1d(yHalf, Semiaxis = True \t)\n\treturn x,y\n\n\n#============================================================================\n#\tFUN: \tPsdArray2Noise_1d_v2\n#============================================================================\ndef PsdArray2Noise_1d_v2(f_in, Psd_in, L_mm,N):\n\t'''\n\t\tReturns meters\n\t'''\n\tfrom scipy import interpolate\n\tlog=np.log\n\tfft = np.fft.fft\n\tfftshift = np.fft.fftshift\n\n\tff = f_in\n\tyy = Psd_in\n\tL = L_mm\n\tN = int(N)\n\tN2 = int(N//2)\n\tL =300 # (mm)\n\tL_um = L*1e3\n\tL_nm = L*1e6\n\n\tfMin = 1/L_um\n\n\t##vecchia riga\n\t##fSpline = (np.array(range(N2))+1)/L_um # um^-1\n\tfSpline = np.arange(N2)/N2 * (max(ff) - min(ff)) + min(ff)\n\n\tfun = interpolate.splrep(log(ff), log(yy), s=2)\n\tyPsd_log = interpolate.splev(log(fSpline), fun)\n\tySpline = np.exp(yPsd_log)\n\tyPsd = ySpline\n\n\t# tolgo\n\tyPsd[fSpline<ff[0]] = 200\n\tn = len(yPsd)\n\n\n\tplt.plot(fSpline, yPsd,'-')\n\tplt.plot(ff, yy,'x')\n\tplt.legend(['ySpline','Data'])\n\tax = plt.axes()\n\t#ax.set_yscale('log')\n\t#ax.set_xscale('log')\n\n\t#% controllo RMS integrando la yPsd\n\timport scipy.integrate as integrate\n\n\tRMS = np.sqrt(integrate.trapz(yPsd, fSpline/1000))\n\n\t#% Modo Manfredda style\n\n\t#yPsdNorm = np.sqrt(yPsd/L_um/1000)\n\t#yPsdNorm_reverse = yPsdNorm[::-1]\n\tyPsd_reverse = yPsd[::-1]\n\tell= 1/(fSpline[1] - fSpline[0])\n\n\tif N%2 == 0:\n\t\tyPsd2 = np.hstack((yPsd_reverse ,0,yPsd[0:-1]))\n\telse:\n\t\tyPsd2 = np.hstack((yPsd_reverse ,0,yPsd))\n\t##yPsd2Norm = np.sqrt(yPsd2/ell/1000/2)\n\tyPsd2Norm = np.sqrt(yPsd2/ell/1000)\n\tn_ = len(yPsd2)\n\tprint('len(yPsd2) = %0.2d' % len(yPsd2Norm))\n\tphi = 2*np.pi * np.random.rand(n_)\n\tr = np.exp(1j*phi)\n\n\tyPsd2Norm_ = fftshift(yPsd2Norm)\n\t#yPsd2Norm_[len(yPsd2Norm_)//2] = 0\n\n\tyRaf = np.fft.fft(r*yPsd2Norm_)\n\tyRaf = np.real(yRaf)\n\tprint('Rms = %0.2e nm' % np.std(yRaf))\n\n\tplt.plot(yPsd2Norm_)\n\n\tprint('max yPsd_ = %d nm' % max(yPsd2))\n\tprint('max yPsd2Norm = %0.4f nm' % max(yPsd2Norm))\n\tprint('Rms yRaf2 = %0.2e nm' % np.std(yRaf))\n\treturn yRaf * 1e-9\n\n#============================================================================\n#\tFUN: \tPsd2Noise\n#============================================================================\ndef PsdArray2Noise_1d(PsdArray, N, Semiaxis = True, Real = True):\n\t'''\n\tGenerates a noise pattern whose Power Spectral density is given by Psd.\n\n\tParameters\n\t---------------------\n\tPsd : 1d array\n\t\tContains the numeric Psd (treated as evenly spaced array)\n\n\tSemiaxis :\n\t\t0 : does nothing\n\t\t1 : halvens Pds, then replicates the halven part for left frequencies,\n\t\t\tproducing an output as long as Psd\n\t\t2 : replicates all Pds for lef frequencies as well, producing an output\n\t\t\ttwice as long as Psd\n\tReal : boolean\n\t\tIf True, the real part of the output is returned (default)\n\n\tReturns:\n\t---------------------\n\t\tAn array of the same length of Psd\n\t'''\n\n\tif Semiaxis == True:\n\t\tyHalf = PsdArray\n\t\tPsdArrayNew = np.hstack((yHalf[-1:0:-1], yHalf))\n\t\tidelta = len(PsdArrayNew) - N\n\t\tif idelta == 1:# piu lungo\n\t\t\tPsdArrayNew = PsdArrayNew[0:-1] # uguale\n\t\telif idelta == 0:\n\t\t\tpass\n\t\telse:\n\t\t\tprint('Error! len(PsdArrayNew) - len(PsdArray) = %0d' % idelta)\n\ty = np.fft.fftshift(PsdArrayNew)\n\tr = 2*np.pi * np.random.rand(len(PsdArrayNew))\n\n\tf = np.fft.ifft(y * np.exp(1j*r))\n\n\tif Real:\n\t\treturn np.real(f)\n\telse:\n\t\treturn f\nPsd2Noise_1d = PsdArray2Noise_1d\n#============================================================================\n#\tFUN: \tNoNoise_1d\n#============================================================================\ndef NoNoise_1d(N, *args):\n\treturn np.zeros([1,N])\n\n#============================================================================\n#\tFUN: \tGaussianNoise_1d\n#============================================================================\ndef GaussianNoise_1d(N,dx, Sigma):\n\t'''\n\tPSD(f) = np.exp(-0.5^f/Sigma^2)\n\t'''\n\tx = np.linspace( - N//2 *dx, N//2-1 * dx,N)\n\ty = np.exp(-0.5*x**2/Sigma**2)\n\treturn Psd2NoisePattern_1d(y)\n\n\n#============================================================================\n#\tFUN: \tPowerLawNoise_1d\n#============================================================================\ndef PowerLawNoise_1d(N, dx, a, b):\n\t'''\n\tPSD(x) = a*x^b\n\t'''\n\tx = np.arange(0,N//2+1, dx)\n\tyHalf = a * x**b\n#\ty = np.hstack((yHalf[-1:0:-1], 0, yHalf[1:-1]))\n\treturn Psd2NoisePattern_1d(y, Semiaxis = True)\n\n#============================================================================\n#\tFUN: \tCustomNoise_1d\n#============================================================================\ndef CustomNoise_1d(N, dx, xPsd, yPsd):\n\txPsd_, yPsd_ = rm.FastResample1d(xPsd, yPsd,N)\n\treturn Psd2NoisePattern_1d(yPsd_, Semiaxis = True)\n\n#============================================================================\n#\tCLASS: \tNoiseGenerator\n#============================================================================\nclass PsdGenerator:\n\tNoNoise = staticmethod(NoNoise_1d)\n\tGauss = staticmethod(GaussianNoise_1d)\n\tPowerLaw = staticmethod(PowerLawNoise_1d)\n\tNumericArray = staticmethod(CustomNoise_1d)\n\n\n\n#============================================================================\n#\tFUN: \tFitPowerLaw\n#============================================================================\ndef FitPowerLaw(x,y):\n\t'''\n\tFits the input data in the form\n\t\ty = a*x^b\n\treturns a,b\n\t'''\n\timport scipy.optimize as optimize\n\n\tfFit = lambda p, x: p[0] * x ** p[1]\n\tfErr = lambda p, x, y: (y - fFit(p, x))\n\n\tp0 = [max(y), -1.0]\n\tout = optimize.leastsq(fErr, p0, args=(x, y), full_output=1)\n\n\tpOut = out[0]\n\n\tb = pOut[1]\n\ta = pOut[0]\n\n#\tindexErr = np.np.sqrt( covar[0][0] )\n#\tampErr = np.np.sqrt( covar[1][1] ) * amp\n\n\treturn a,b\n\n#==============================================================================\n# \tCLASS: RoughnessMaker\n#==============================================================================\n\nclass RoughnessMaker(object):\n\n\tclass Options():\n\t\tFIT_NUMERIC_DATA_WITH_POWER_LAW = True\n\t\tAUTO_ZERO_MEAN_FOR_NUMERIC_DATA = True\n\t\tAUTO_FILL_NUMERIC_DATA_WITH_ZERO = True\n\t\tAUTO_RESET_CUTOFF_ON_PSDTYPE_CHANGE = True\n\n\tdef __init__(self):\n\t\tself.PsdType = PsdFuns.PowerLaw\n\t\tself.PsdParams = np.array([1,1])\n\t\tself._IsNumericPsdInFreq = None\n\t\tself.CutoffLowHigh = [None, None]\n\t\tself.ProfileScaling = 1\n\t\treturn None\n\n\t@property\n\tdef PsdType(self):\n\t\treturn self._PsdType\n\[email protected]\n\tdef PsdType(self, Val):\n\t\t'''\n\t\tNote: each time that the Property value is set, self.CutoffLowHigh is\n\t\treset, is specified by options\n\t\t'''\n\t\tself. _PsdType = Val\n\t\tif self.Options.AUTO_RESET_CUTOFF_ON_PSDTYPE_CHANGE == True:\n\t\t\tself.PsdCutoffLowHigh = [None, None]\n\n\t#======================================================================\n\t# \tFUN: PdfEval\n\t#======================================================================\n\tdef PsdEval(self, N, df, CutoffLowHigh = [None, None]):\n\t\t'''\n\t\tEvals the PSD in the range [0 - N*df]\n\t\tIt's good custom to have PSD[0] = 0, so that the noise pattern is\n\t\tzero-mean.\n\n\t\tParameters:\n\t\t----------------------\n\t\t\tN : int\n\t\t\t\t#of samples\n\t\t\tdf : float\n\t\t\t\tspacing of spatial frequencies (df=1/TotalLength)\n\t\t\tCutoffLowHigh : [LowCutoff, HighCutoff]\n\t\t\t\tif >0, then Psd(f<Cutoff) is set to 0.\n\t\t\t\t\t\tif None, then LowCutoff = min()\n\t\tReturns : fAll, yPsdAll\n\t\t----------------------\n\t\t\tfAll : 1d array\n\t\t\t\tcontains the spatial frequencies\n\t\t\tyPsd : 1d array\n\t\t\t\tcontains the Psd\n\t\t'''\n\n\t\t'''\n\t\tThe Pdf is evaluated only within LowCutoff and HoghCutoff\n\t\tIf the Pdf is PsdFuns.Interp, then LowCutoff and HighCutoff are\n\t\tautomatically set to min and max values of the experimental data\n\t\t'''\n\t\tStrMessage = ''\n\t\tdef GetInRange(fAll, LowCutoff, HighCutoff):\n\t\t\t_tmpa = fAll >= LowCutoff\n\t\t\t_tmpb = fAll <= HighCutoff\n\t\t\tfMid_Pos = np.all([_tmpa, _tmpb],0)\n\t\t\tfMid = fAll[fMid_Pos]\n\t\t\treturn fMid_Pos, fMid\n\n\t\tLowCutoff, HighCutoff = CutoffLowHigh\n\t\tfMin = 0\n\t\tfMax = (N-1)*df\n\t\tfAll = np.linspace(0, fMax, N)\n\t\tyPsdAll = fAll* 0 # init\n\n\t\tLowCutoff = 0 if LowCutoff is None else LowCutoff\n\t\tHighCutoff = N*df if HighCutoff is None else HighCutoff\n\n\n\n\t\t# Numeric PSD\n\t\t# Note: by default returned yPsd is always 0 outside the input data range\n\t\tif self.PsdType == PsdFuns.Interp:\n\t\t\t# Use Auto-Fit + PowerLaw\n\t\t\tif self.Options.FIT_NUMERIC_DATA_WITH_POWER_LAW == True:\n\t\t\t\t\txFreq,y = self.NumericPsdGetXY()\n\t\t\t\t\tp = FitPowerLaw(1/xFreq,y)\n\t\t\t\t\t_PsdParams = p[0], -p[1]\n\t\t\t\t\tLowCutoff = np.amin(self._PsdNumericX)\n\t\t\t\t\tHighCutoff = np.amin(self._PsdNumericX)\n\t\t\t\t\tfMid_Pos, fMid = GetInRange(fAll, LowCutoff, HighCutoff)\n\t\t\t\t\tyPsd = PsdFuns.PowerLaw(fMid, *_PsdParams )\n\t\t\t# Use Interpolation\n\t\t\telse:\n\t\t\t\t# check Cutoff\n\t\t\t\tLowVal = np.amin(self._PsdNumericX)\n\t\t\t\tHighVal = np.amax(self._PsdNumericX)\n\t\t\t\tLowCutoff = LowVal if LowCutoff <= LowVal else LowCutoff\n\t\t\t\tHighCutoff = HighVal if HighCutoff >= HighVal else HighCutoff\n\n\n\t\t\t\t# Get the list of good frequency values (fMid) and their positions\n\t\t\t\t# (fMid_Pos)\n\t\t\t\tfMid_Pos, fMid = GetInRange(fAll, LowCutoff, HighCutoff)\n\n\t\t\t\t##yPsd = self.PsdType(fMid, *self.PsdParams)\n\t\t\t\t## non funziona, rimpiazzo a mano\n\t\t\t\tyPsd = PsdFuns.Interp(fMid, self._PsdNumericX, self._PsdNumericY)\n\n\t\t# Analytical Psd\n\t\telse:\n\t\t\tfMid_Pos, fMid = GetInRange(fAll, LowCutoff, HighCutoff)\n\t\t\tyPsd = self.PsdType(fMid, *self.PsdParams)\n\n\t\t# copying array subset\n\t\tyPsdAll[fMid_Pos] = yPsd\n\n\t\treturn fAll, yPsdAll\n\n\t#======================================================================\n\t# \tFUN: _FitNumericPsdWithPowerLaw\n\t#======================================================================\n# in disusos\n\tdef _FitNumericPsdWithPowerLaw(self):\n\t\tx,y = self.NumericPsdGetXY()\n\t\tif self._IsNumericPsdInFreq == True:\n\t\t\tp = FitPowerLaw(1/x,y)\n\t\t\tself.PsdParams = p[0], -p[1]\n\t\telse:\n\t\t\tp = FitPowerLaw(x,y)\n\t\t\tself.PsdParams = p[0], p[1]\n\n\n\t#======================================================================\n\t# \tFUN: MakeProfile\n\t#======================================================================\n\tdef MakeProfile(self, L,N):\n\t\t'''\n\t\t\tEvaluates the psd according to .PsdType, .PsdParams and .Options directives\n\t\t\tReturns an evenly-spaced array.\n\t\t\tIf PsdType = NumericArray, linear interpolation is performed.\n\n\t\t\t:PARAM: N: # of samples\n\t\t\t:PARAM: dx: grid spacing (spatial frequency)\n\n\t\t\treturns:\n\t\t\t\t1d arr\n\t\t'''\n\n\n\t\tif self.PsdType == PsdFuns.Interp:\n\t\t\t# chiama codice ad hoc\n\t\t\tL_mm = L*1e3\n\t\t\tyRoughness = PsdArray2Noise_1d_v2(self._PsdNumericX, self._PsdNumericY, L_mm, N)\n\t\telse:\n\t\t\tprint('Irreversible error. The code was not completed to handle this instance')\n\t\treturn yRoughness * self.ProfileScaling\n#\t\tf, yPsd = self.PsdEval(N//2 + 1,df)\n\n\n\t\t# Special case\n#\t\tif self.Options.FIT_NUMERIC_DATA_WITH_POWER_LAW == True:\n#\t\t\tself.PsdParams = list(FitPowerLaw(*self.NumericPsdGetXY()))\n#\t\t\tyPsd = PsdFuns.PowerLaw(x, *self.PsdParams)\n#\t\telse: # general calse\n#\t\t\tyPsd = self.PsdType(x, *self.PsdParams)\n\n#\t\tyRoughness = Psd2Noise_1d(yPsd, N, Semiaxis = True)\n\n\n#\t\tx = np.linspace(0, N*dx,N)\n#\t\t# Special case\n#\t\tif self.Options.FIT_NUMERIC_DATA_WITH_POWER_LAW == True:\n#\t\t\tself.PsdParams = list(FitPowerLaw(*self.NumericPsdGetXY()))\n#\t\t\ty = PowerLawNoise_1d(N, dx, *self.PsdParams)\n#\t\telse: # general calse\n#\t\t\ty = self.PsdType(N,dx, *self.PsdParams)\n#\t\treturn y\n\tGenerate = MakeProfile\n\t#======================================================================\n\t# \tFUN: NumericPsdSetXY\n\t#======================================================================\n\tdef NumericPsdSetXY(self,x,y):\n\t\tself._PsdNumericX = x\n\t\tself._PsdNumericY = y\n\n\n\t#======================================================================\n\t# \tFUN: NumericPsdGetXY\n\t#======================================================================\n\n\tdef NumericPsdGetXY(self):\n\t\ttry:\n\t\t\treturn self._PsdNumericX, self._PsdNumericY\n\t\texcept:\n\t\t\tprint('Error in RoughnessMaker.NumericPsdGetXY. Maybe the data file was not properly loaded')\n\t#======================================================================\n\t# \tFUN: NumericPsdLoadXY\n\t#======================================================================\n\tdef NumericPsdLoadXY(self, FilePath, xScaling = 1, yScaling = 1 , xIsSpatialFreq = True):\n\t\t''' @TODO: specificare formati e tipi di file\n\n\t\tParameters\n\t\t----------------------------\n\t\txIsSpatialFreq : bool\n\t\t\t\t\t\ttrue If the first column (Read_x_values) contains spatial\n\t\t\t\t\t\tfrequencies. False if it contains lenghts. Default = True\n\t\txScaling, yScaling: floats\n\t\t\t\t\t\tRead_x_values => Read_x_values * xScaling\n\n\t\t\t\t\t\tRead_y_values => Read_y_values * yScaling\n\n\t\t\t\t\t\tSometimes, properly setting the x and y scaling values may be confusing (although just matter of high-school considerations). On this purpose, the property .RoughnessMaker.ProfileScaling property can be used also..ProfileScaling is the scale factor that acts on the output of MakeProfile() function only.\n\n\t\tremarks\n\t\t\t\t\t\t--------\n\t\t\t\t\t\tpippo\n\n\t\t'''\n\n\t\ttry:\n\t\t\tself._IsNumericPsdInFreq = xIsSpatialFreq\n\n\t\t\ts = np.loadtxt(FilePath)\n\t\t\tx = s[:,0]\n\t\t\ty = s[:,1]\n\n\t\t\tx = x * xScaling\n\t\t\ty = y * yScaling\n\n\t\t\t# inversion of x-axis if not spatial frequencies\n\t\t\tif xIsSpatialFreq == False:\n\t\t\t\tf = 1/x\n\t\t\telse:\n\t\t\t\tf = x\n\t\t\t# array sorting\n\t\t\ti = np.argsort(f)\n\t\t\tf = f[i]\n\t\t\ty = y[i]\n\t\t\t# I set the Cutoff value of the class according to available data\n\t\t\tself.PsdCutoffLowHigh = [np.amin, np.amax(f)]\n\n\t\t\t# I set class operating variables\n\t\t\tself.PsdType = PsdFuns.Interp\n\t\t\tself.PsdParams = [f,y]\n\n\n\t\t\t# Auto-set\n\t\t\t# fill 0-value (DC Component)\n\t#\t\tif self.Options.AUTO_FILL_NUMERIC_DATA_WITH_ZERO == True:\n\t#\t\t\tif np.amin(x >0):\n\t#\t\t\t\tx = np.insert(x,0,0)\n\t#\t\t\t\ty = np.insert(y,0,0)\t# 0 in psd => 0-mean value in the noise pattern\n\n\n\t\t\t# sync other class values\n\t\t\tself.NumericPsdSetXY(f, y)\n\t\texcept:\n\t\t\tpass\n\n\t\tdef Generate(self, N = None, dx = None, CutoffLowHigh = [None, None]):\n\t\t\t'''\n\t\t\tParameters\n\t\t\t\tN: # of output samples\n\t\t\t\tdx: step of the x axis\n\t\t\tNote: generates an evenly spaced array\n\t\t\t'''\n\t\t\tL = dx * N\n\t\t\tdf = 1/L\n\t\t\tfPsd, yPsd = self.PsdEval(N//2 +1 , df = df,\n\t\t\t\t\t\t\t\t\t\t\tCutoffLowHigh = CutoffLowHigh )\n\t\t\th = Psd2Noise_1d(yPsd, Semiaxis = True)\n\n\t\t\treturn h\n\n\t#======================================================================\n\t# \tFUN: NumericPsdCheck\n\t#======================================================================\n\tdef NumericPsdCheck(self, N, L):\n\n\t\tdf = 1/L\n\t\t# Stored data\n\t\tff,yy = self.NumericPsdGetXY()\n\t\t# Evaluated data\n\t\tfPsd, yPsd = self.PsdEval(N, df)\n\n\n\t\tplt.plot(fPsd, np.log10(yPsd),'x')\n\t\tplt.plot(ff, np.log10(yy),'.r')\n\t\tplt.legend(['Evaluated data', 'Stored data'])\n\t\tplt.suptitle('Usage of stored data (PSD)')\n\n\t\tfMax = df*(N//2)\n\t\tfMin = df\n\t\tStrMsg = ''\n\t\t_max = np.max(ff)\n\t\t_min = np.min(ff)\n\t\tprint('fMax query = %0.1e m^-1' % fMax )\n\t\tprint('fMax data= %0.1e m^-1 = %0.2e um^-1' % (_max, (_max * 1e6) ))\n\t\tprint('fMin query= %0.1e m^-1' % fMin )\n\t\tprint('fMin data= %0.1e m^-1 = %0.2e um^-1' % (_min, (_min * 1e6) ))\n\n\t\treturn StrMsg" ]
[ [ "matplotlib.pyplot.legend", "numpy.amax", "numpy.sqrt", "numpy.linspace", "numpy.fft.fftshift", "matplotlib.pyplot.plot", "matplotlib.pyplot.axes", "numpy.max", "numpy.all", "numpy.exp", "numpy.hstack", "numpy.arange", "scipy.integrate.trapz", "numpy.real", "scipy.optimize.leastsq", "scipy.interpolate.interp1d", "numpy.std", "numpy.zeros", "numpy.min", "numpy.amin", "numpy.log10", "numpy.random.rand", "numpy.argsort", "matplotlib.pyplot.suptitle", "numpy.array", "numpy.fft.fft", "numpy.loadtxt" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.10", "1.9", "1.7", "1.8" ], "tensorflow": [] } ]
OYukiya/PyIntroduction
[ "433142b25de36552867b209649b17113ca2e11c6" ]
[ "opencv/pycv_tutorial/color_space.py" ]
[ "\n# -*- coding: utf-8 -*-\n## @package pycv_tutorial.color_space\n#\n# 画像処理: 色空間の変換\n# @author tody\n# @date 2016/06/27\n\nimport cv2\nimport matplotlib.pyplot as plt\n\n# RGB画像の表示\ndef showImageRGB(image_file):\n image_bgr = cv2.imread(image_file)\n image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB)\n plt.title('RGB')\n plt.imshow(image_rgb)\n plt.axis('off')\n plt.show()\n\n\n# グレースケール画像の表示\ndef showImageGray(image_file):\n image_gray = cv2.imread(image_file, 0)\n plt.title('Gray')\n plt.gray()\n plt.imshow(image_gray)\n plt.axis('off')\n plt.show()\n\n\n# HSVチャンネルの表示\ndef showImageHSV(image_file):\n image_bgr = cv2.imread(image_file)\n image_hsv = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2HSV)\n\n H = image_hsv[:, :, 0]\n S = image_hsv[:, :, 1]\n V = image_hsv[:, :, 2]\n\n plt.subplot(1, 3, 1)\n plt.title('Hue')\n plt.gray()\n plt.imshow(H)\n plt.axis('off')\n\n plt.subplot(1, 3, 2)\n plt.title('Saturation')\n plt.gray()\n plt.imshow(S)\n plt.axis('off')\n\n plt.subplot(1, 3, 3)\n plt.title('Value')\n plt.gray()\n plt.imshow(V)\n plt.axis('off')\n\n plt.show()\n\n\n# Labチャンネルの表示\ndef showImageLab(image_file):\n image_bgr = cv2.imread(image_file)\n image_Lab = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2LAB)\n\n L = image_Lab[:, :, 0]\n a = image_Lab[:, :, 1]\n b = image_Lab[:, :, 2]\n\n plt.subplot(1, 3, 1)\n plt.title('L')\n plt.gray()\n plt.imshow(L)\n plt.axis('off')\n\n plt.subplot(1, 3, 2)\n plt.title('a')\n plt.gray()\n plt.imshow(a)\n plt.axis('off')\n\n plt.subplot(1, 3, 3)\n plt.title('b')\n plt.gray()\n plt.imshow(b)\n plt.axis('off')\n\n plt.show()\n\n\nif __name__ == '__main__':\n image_file = \"images/peppers.png\"\n showImageRGB(image_file)\n showImageGray(image_file)\n showImageHSV(image_file)\n showImageLab(image_file)" ]
[ [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.gray", "matplotlib.pyplot.title", "matplotlib.pyplot.subplot", "matplotlib.pyplot.axis", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
JohnnySun8/TextWorld
[ "9a54e9d642f7605a0f3ebba3285cdd04047975e2" ]
[ "scripts/sample_quests.py" ]
[ "#!/usr/bin/env python\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\n\nimport os\nimport argparse\nfrom os.path import join as pjoin\n\nimport numpy as np\nimport networkx as nx\n\nfrom textworld.render import visualize\nfrom textworld.generator import Game\nfrom textworld.generator.inform7 import Inform7Game\nfrom textworld.generator.chaining import ChainingOptions\nfrom textworld.generator.chaining import sample_quest\nfrom textworld.utils import save_graph_to_svg\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"game\",\n help=\"Use initial state of the provided game.\")\n parser.add_argument(\"--output\", default=\"./\",\n help=\"Output folder where to sample the images. Default: %(default)s\")\n parser.add_argument(\"--quest-length\", type=int, default=5,\n help=\"Minimum nb. of actions required to complete the quest. Default: %(default)s\")\n parser.add_argument(\"--quest-breadth\", type=int, default=1,\n help=\"Control how non-linear a quest can be.\")\n parser.add_argument(\"--nb-quests\", type=int, default=10,\n help=\"Number of quests to sample. Default: %(default)s\")\n parser.add_argument(\"--seed\", type=int,\n help=\"Seed for random generator. Default: always different.\")\n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\",\n help=\"Print more information.\")\n\n return parser.parse_args()\n\n\ndef build_tree_from_chains(chains, inform7):\n G = nx.DiGraph()\n root = \"root\"\n labels = {}\n for chain in chains:\n commands = [root] + inform7.gen_commands_from_actions(chain.actions)\n G.add_nodes_from(commands)\n G.add_edges_from(zip(commands[:-1], commands[1:]))\n labels.update(dict(zip(commands, commands)))\n\n return G, labels\n\n\ndef print_chains(chains, inform7):\n for i, chain in enumerate(chains):\n commands = inform7.gen_commands_from_actions(chain.actions)\n print(\"{:2d}. {}\".format(i + 1, \" > \".join(commands)))\n\n\ndef main():\n args = parse_args()\n\n # Load game for which to sample quests for.\n game = Game.load(args.game.replace(\".ulx\", \".json\"))\n\n options = ChainingOptions()\n options.backward = False\n options.max_depth = args.quest_length\n options.max_breadth = args.quest_breadth\n options.rules_per_depth = {}\n options.create_variables = False\n options.rng = np.random.RandomState(args.seed)\n\n # Sample quests.\n chains = []\n for i in range(args.nb_quests):\n chain = sample_quest(game.world.state, options)\n chains.append(chain)\n\n inform7 = Inform7Game(game)\n print_chains(chains, inform7)\n\n # Convert chains to networkx graph/tree\n filename_world = pjoin(args.output, \"sample_world.png\")\n filename_tree = pjoin(args.output, \"sample_tree.svg\")\n filename_graph = pjoin(args.output, \"sample_graph.svg\")\n G, labels = build_tree_from_chains(chains, inform7)\n if len(G) > 0:\n image = visualize(game)\n image.save(filename_world)\n tree = nx.bfs_tree(G, \"root\")\n save_graph_to_svg(tree, labels, filename_tree)\n save_graph_to_svg(G, labels, filename_graph)\n else:\n try:\n os.remove(filename_world)\n os.remove(filename_tree)\n os.remove(filename_graph)\n except OSError:\n pass\n\n\nif __name__ == \"__main__\":\n main()\n" ]
[ [ "numpy.random.RandomState" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
zuru/pytorch_cluster
[ "442e8d9c8cec0c7621966dc45f9f7dd151209044" ]
[ "torch_cluster/fps.py" ]
[ "from typing import Optional\n\nimport torch\nfrom torch import Tensor\n\n\[email protected]._overload # noqa\ndef fps(src, batch=None, ratio=None, random_start=True): # noqa\n # type: (Tensor, Optional[Tensor], Optional[float], bool) -> Tensor\n pass # pragma: no cover\n\n\[email protected]._overload # noqa\ndef fps(src, batch=None, ratio=None, random_start=True): # noqa\n # type: (Tensor, Optional[Tensor], Optional[Tensor], bool) -> Tensor\n pass # pragma: no cover\n\n\ndef fps(src: torch.Tensor, batch=None, ratio=None, random_start=True): # noqa\n r\"\"\"\"A sampling algorithm from the `\"PointNet++: Deep Hierarchical Feature\n Learning on Point Sets in a Metric Space\"\n <https://arxiv.org/abs/1706.02413>`_ paper, which iteratively samples the\n most distant point with regard to the rest points.\n\n Args:\n src (Tensor): Point feature matrix\n :math:`\\mathbf{X} \\in \\mathbb{R}^{N \\times F}`.\n batch (LongTensor, optional): Batch vector\n :math:`\\mathbf{b} \\in {\\{ 0, \\ldots, B-1\\}}^N`, which assigns each\n node to a specific example. (default: :obj:`None`)\n ratio (float or Tensor, optional): Sampling ratio.\n (default: :obj:`0.5`)\n random_start (bool, optional): If set to :obj:`False`, use the first\n node in :math:`\\mathbf{X}` as starting node. (default: obj:`True`)\n\n :rtype: :class:`LongTensor`\n\n\n .. code-block:: python\n\n import torch\n from torch_cluster import fps\n\n src = torch.Tensor([[-1, -1], [-1, 1], [1, -1], [1, 1]])\n batch = torch.tensor([0, 0, 0, 0])\n index = fps(src, batch, ratio=0.5)\n \"\"\"\n\n r: Optional[Tensor] = None\n if ratio is None:\n r = torch.tensor(0.5, dtype=src.dtype, device=src.device)\n elif isinstance(ratio, float):\n r = torch.tensor(ratio, dtype=src.dtype, device=src.device)\n else:\n r = ratio\n assert r is not None\n\n if batch is not None:\n assert src.size(0) == batch.numel()\n batch_size = int(batch.max()) + 1\n\n deg = src.new_zeros(batch_size, dtype=torch.long)\n deg.scatter_add_(0, batch, torch.ones_like(batch))\n\n ptr = deg.new_zeros(batch_size + 1)\n torch.cumsum(deg, 0, out=ptr[1:])\n else:\n ptr = torch.tensor([0, src.size(0)], device=src.device)\n\n return torch.ops.torch_cluster.fps(src, ptr, r, random_start)\n" ]
[ [ "torch.ones_like", "torch.cumsum", "torch.ops.torch_cluster.fps", "torch.tensor" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
f74066357/Image_Inpainting
[ "1c89cdadcf420633d29136c8bdcbd280f2546769", "1c89cdadcf420633d29136c8bdcbd280f2546769" ]
[ "mmedit/models/inpaintors/vic/common.py", "mmedit/models/inpaintors/one_stage.py" ]
[ "\"\"\"\nBasicSR/codes/dataops/common.py (8-Nov-20)\nhttps://github.com/victorca25/BasicSR/blob/dev2/codes/dataops/common.py\n\"\"\"\n\nimport os\nimport math\nimport pickle\nimport random\nimport numpy as np\nimport torch\nimport cv2\nimport logging\n\nimport copy\nfrom torchvision.utils import make_grid\n\n#from dataops.colors import *\nfrom .colors import *\n#from dataops.debug import tmp_vis, describe_numpy, describe_tensor\n\n####################\n# Files & IO\n####################\n\n###################### get image path list ######################\nIMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', '.dng', '.DNG', '.webp','.npy', '.NPY']\n\ndef is_image_file(filename):\n return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)\n\n\ndef _get_paths_from_images(path):\n '''get image path list from image folder'''\n assert os.path.isdir(path), '{:s} is not a valid directory'.format(path)\n images = []\n for dirpath, _, fnames in sorted(os.walk(path)):\n for fname in sorted(fnames):\n if is_image_file(fname):\n img_path = os.path.join(dirpath, fname)\n images.append(img_path)\n assert images, '{:s} has no valid image file'.format(path)\n return images\n\n\ndef _get_paths_from_lmdb(dataroot):\n '''get image path list from lmdb'''\n import lmdb\n env = lmdb.open(dataroot, readonly=True, lock=False, readahead=False, meminit=False)\n keys_cache_file = os.path.join(dataroot, '_keys_cache.p')\n logger = logging.getLogger('base')\n if os.path.isfile(keys_cache_file):\n logger.info('Read lmdb keys from cache: {}'.format(keys_cache_file))\n keys = pickle.load(open(keys_cache_file, \"rb\"))\n else:\n with env.begin(write=False) as txn:\n logger.info('Creating lmdb keys cache: {}'.format(keys_cache_file))\n keys = [key.decode('ascii') for key, _ in txn.cursor()]\n pickle.dump(keys, open(keys_cache_file, 'wb'))\n paths = sorted([key for key in keys if not key.endswith('.meta')])\n return env, paths\n\n\ndef get_image_paths(data_type, dataroot):\n '''get image path list\n support lmdb or image files'''\n env, paths = None, None\n if dataroot is not None:\n if data_type == 'lmdb':\n env, paths = _get_paths_from_lmdb(dataroot)\n elif data_type == 'img':\n paths = sorted(_get_paths_from_images(dataroot))\n else:\n raise NotImplementedError('data_type [{:s}] is not recognized.'.format(data_type))\n return env, paths\n\n\n###################### read images ######################\ndef _read_lmdb_img(env, path):\n with env.begin(write=False) as txn:\n buf = txn.get(path.encode('ascii'))\n buf_meta = txn.get((path + '.meta').encode('ascii')).decode('ascii')\n img_flat = np.frombuffer(buf, dtype=np.uint8)\n H, W, C = [int(s) for s in buf_meta.split(',')]\n img = img_flat.reshape(H, W, C)\n return img\n\n\ndef read_img(env, path, out_nc=3, fix_channels=True):\n '''\n Reads image using cv2 (rawpy if dng) or from lmdb by default\n (can also use using PIL instead of cv2)\n Arguments:\n out_nc: Desired number of channels\n fix_channels: changes the images to the desired number of channels\n Output:\n Numpy uint8, HWC, BGR, [0,255] by default\n '''\n\n img = None\n if env is None: # img\n if(path[-3:].lower() == 'dng'): # if image is a DNG\n import rawpy\n with rawpy.imread(path) as raw:\n img = raw.postprocess()\n if(path[-3:].lower() == 'npy'): # if image is a NPY numpy array\n with open(path, 'rb') as f:\n img = np.load(f)\n else: # else, if image can be read by cv2\n img = cv2.imread(path, cv2.IMREAD_UNCHANGED)\n #TODO: add variable detecting if cv2 is not available and try PIL instead\n # elif: # using PIL instead of OpenCV\n # img = Image.open(path).convert('RGB')\n # else: # For other images unrecognized by cv2\n # import matplotlib.pyplot as plt\n # img = (255*plt.imread(path)[:,:,:3]).astype('uint8')\n else:\n img = _read_lmdb_img(env, path)\n\n # if not img:\n # raise ValueError(f\"Failed to read image: {path}\")\n\n if fix_channels:\n img = fix_img_channels(img, out_nc)\n\n return img\n\ndef fix_img_channels(img, out_nc):\n '''\n fix image channels to the expected number\n '''\n\n # if image has only 2 dimensions, add \"channel\" dimension (1)\n if img.ndim == 2:\n #img = img[..., np.newaxis] #alt\n #img = np.expand_dims(img, axis=2)\n img = np.tile(np.expand_dims(img, axis=2), (1, 1, 3))\n # special case: properly remove alpha channel\n if out_nc == 3 and img.shape[2] == 4:\n img = bgra2rgb(img)\n # remove all extra channels\n elif img.shape[2] > out_nc:\n img = img[:, :, :out_nc]\n # if alpha is expected, add solid alpha channel\n elif img.shape[2] == 3 and out_nc == 4:\n img = np.dstack((img, np.full(img.shape[:-1], 255, dtype=np.uint8)))\n return img\n\n\n####################\n# image processing\n# process on numpy image\n####################\n\ndef bgra2rgb(img):\n '''\n cv2.cvtColor(img, cv2.COLOR_BGRA2BGR) has an issue removing the alpha channel,\n this gets rid of wrong transparent colors that can harm training\n '''\n if img.shape[2] == 4:\n #b, g, r, a = cv2.split((img*255).astype(np.uint8))\n b, g, r, a = cv2.split((img.astype(np.uint8)))\n b = cv2.bitwise_and(b, b, mask=a)\n g = cv2.bitwise_and(g, g, mask=a)\n r = cv2.bitwise_and(r, r, mask=a)\n #return cv2.merge([b, g, r]).astype(np.float32)/255.\n return cv2.merge([b, g, r])\n return img\n\ndef channel_convert(in_c, tar_type, img_list):\n # conversion among BGR, gray and y\n # Note: OpenCV uses inverted channels BGR, instead of RGB.\n # If images are loaded with something other than OpenCV,\n # check that the channels are in the correct order and use\n # the alternative conversion functions.\n #if in_c == 4 and tar_type == 'RGB-A': # BGRA to BGR, remove alpha channel\n #return [cv2.cvtColor(img, cv2.COLOR_BGRA2BGR) for img in img_list]\n #return [bgra2rgb(img) for img in img_list]\n if in_c == 3 and tar_type == 'gray': # BGR to gray\n gray_list = [cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) for img in img_list]\n return [np.expand_dims(img, axis=2) for img in gray_list]\n elif in_c == 3 and tar_type == 'RGB-LAB': #RGB to LAB\n return [cv2.cvtColor(img, cv2.COLOR_BGR2LAB) for img in img_list]\n elif in_c == 3 and tar_type == 'LAB-RGB': #RGB to LAB\n return [cv2.cvtColor(img, cv2.COLOR_LAB2BGR) for img in img_list]\n elif in_c == 3 and tar_type == 'y': # BGR to y\n y_list = [bgr2ycbcr(img, only_y=True) for img in img_list]\n return [np.expand_dims(img, axis=2) for img in y_list]\n elif in_c == 1 and tar_type == 'RGB': # gray/y to BGR\n return [cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) for img in img_list]\n else:\n return img_list\n\ndef rgb2ycbcr(img, only_y=True):\n '''same as matlab rgb2ycbcr\n only_y: only return Y channel\n Input:\n uint8, [0, 255]\n float, [0, 1]\n '''\n in_img_type = img.dtype\n img_ = img.astype(np.float32)\n if in_img_type != np.uint8:\n img_ *= 255.\n # convert\n if only_y:\n rlt = np.dot(img_ , [65.481, 128.553, 24.966]) / 255.0 + 16.0\n else:\n rlt = np.matmul(img_ , [[65.481, -37.797, 112.0], [128.553, -74.203, -93.786],\n [24.966, 112.0, -18.214]]) / 255.0 + [16, 128, 128]\n if in_img_type == np.uint8:\n rlt = rlt.round()\n else:\n rlt /= 255.\n return rlt.astype(in_img_type)\n\ndef bgr2ycbcr(img, only_y=True, separate=False):\n '''bgr version of matlab rgb2ycbcr\n Python opencv library (cv2) cv2.COLOR_BGR2YCrCb has\n different parameters with MATLAB color convertion.\n only_y: only return Y channel\n separate: if true, will returng the channels as\n separate images\n Input:\n uint8, [0, 255]\n float, [0, 1]\n '''\n in_img_type = img.dtype\n img_ = img.astype(np.float32)\n if in_img_type != np.uint8:\n img_ *= 255.\n # convert\n if only_y:\n rlt = np.dot(img_ , [24.966, 128.553, 65.481]) / 255.0 + 16.0\n else:\n rlt = np.matmul(img_ , [[24.966, 112.0, -18.214], [128.553, -74.203, -93.786],\n [65.481, -37.797, 112.0]]) / 255.0 + [16, 128, 128]\n # to make ycrcb like cv2\n # rlt = rlt[:, :, (0, 2, 1)]\n\n if in_img_type == np.uint8:\n rlt = rlt.round()\n else:\n rlt /= 255.\n\n if separate:\n rlt = rlt.astype(in_img_type)\n # y, cb, cr\n return rlt[:, :, 0], rlt[:, :, 1], rlt[:, :, 2]\n else:\n return rlt.astype(in_img_type)\n\n'''\ndef ycbcr2rgb_(img, only_y=True):\n \"\"\"same as matlab ycbcr2rgb\n (Note: this implementation is the original from BasicSR, but\n appears to be for ycrcb, like cv2)\n Input:\n uint8, [0, 255]\n float, [0, 1]\n \"\"\"\n in_img_type = img.dtype\n img_ = img.astype(np.float32)\n if in_img_type != np.uint8:\n img_ *= 255.\n\n # to make ycrcb like cv2\n # rlt = rlt[:, :, (0, 2, 1)]\n\n # convert\n # original (for ycrcb):\n rlt = np.matmul(img_ , [[0.00456621, 0.00456621, 0.00456621], [0, -0.00153632, 0.00791071],\n [0.00625893, -0.00318811, 0]]) * 255.0 + [-222.921, 135.576, -276.836]\n\n #alternative conversion:\n # xform = np.array([[1, 0, 1.402], [1, -0.34414, -.71414], [1, 1.772, 0]])\n # img_[:, :, [1, 2]] -= 128\n # rlt = img_.dot(xform.T)\n np.putmask(rlt, rlt > 255, 255)\n np.putmask(rlt, rlt < 0, 0)\n\n if in_img_type == np.uint8:\n rlt = rlt.round()\n else:\n rlt /= 255.\n return rlt.astype(in_img_type)\n'''\n\ndef ycbcr2rgb(img, only_y=True):\n '''\n bgr version of matlab ycbcr2rgb\n Python opencv library (cv2) cv2.COLOR_YCrCb2BGR has\n different parameters to MATLAB color convertion.\n\n Input:\n uint8, [0, 255]\n float, [0, 1]\n '''\n in_img_type = img.dtype\n img_ = img.astype(np.float32)\n if in_img_type != np.uint8:\n img_ *= 255.\n\n # to make ycrcb like cv2\n # rlt = rlt[:, :, (0, 2, 1)]\n\n # convert\n mat = np.array([[24.966, 128.553, 65.481],[112, -74.203, -37.797], [-18.214, -93.786, 112.0]])\n mat = np.linalg.inv(mat.T) * 255\n offset = np.array([[[16, 128, 128]]])\n\n rlt = np.dot((img_ - offset), mat)\n rlt = np.clip(rlt, 0, 255)\n ## rlt = np.rint(rlt).astype('uint8')\n\n if in_img_type == np.uint8:\n rlt = rlt.round()\n else:\n rlt /= 255.\n return rlt.astype(in_img_type)\n\n'''\n#TODO: TMP RGB version, to check (PIL)\ndef rgb2ycbcr(img_rgb):\n ## the range of img_rgb should be (0, 1)\n img_y = 0.257 * img_rgb[:, :, 0] + 0.504 * img_rgb[:, :, 1] + 0.098 * img_rgb[:, :, 2] + 16 / 255.0\n img_cb = -0.148 * img_rgb[:, :, 0] - 0.291 * img_rgb[:, :, 1] + 0.439 * img_rgb[:, :, 2] + 128 / 255.0\n img_cr = 0.439 * img_rgb[:, :, 0] - 0.368 * img_rgb[:, :, 1] - 0.071 * img_rgb[:, :, 2] + 128 / 255.0\n return img_y, img_cb, img_cr\n\n#TODO: TMP RGB version, to check (PIL)\ndef ycbcr2rgb(img_ycbcr):\n ## the range of img_ycbcr should be (0, 1)\n img_r = 1.164 * (img_ycbcr[:, :, 0] - 16 / 255.0) + 1.596 * (img_ycbcr[:, :, 2] - 128 / 255.0)\n img_g = 1.164 * (img_ycbcr[:, :, 0] - 16 / 255.0) - 0.392 * (img_ycbcr[:, :, 1] - 128 / 255.0) - 0.813 * (img_ycbcr[:, :, 2] - 128 / 255.0)\n img_b = 1.164 * (img_ycbcr[:, :, 0] - 16 / 255.0) + 2.017 * (img_ycbcr[:, :, 1] - 128 / 255.0)\n img_r = img_r[:, :, np.newaxis]\n img_g = img_g[:, :, np.newaxis]\n img_b = img_b[:, :, np.newaxis]\n img_rgb = np.concatenate((img_r, img_g, img_b), 2)\n return img_rgb\n'''\n\ndef modcrop(img_in, scale):\n # img_in: Numpy, HWC or HW\n img = np.copy(img_in)\n if img.ndim == 2:\n H, W = img.shape\n H_r, W_r = H % scale, W % scale\n img = img[:H - H_r, :W - W_r]\n elif img.ndim == 3:\n H, W, C = img.shape\n H_r, W_r = H % scale, W % scale\n img = img[:H - H_r, :W - W_r, :]\n else:\n raise ValueError('Wrong img ndim: [{:d}].'.format(img.ndim))\n return img\n\n#TODO: this should probably be elsewhere (augmentations.py)\ndef augment(img_list, hflip=True, rot=True):\n # horizontal flip OR rotate\n hflip = hflip and random.random() < 0.5\n vflip = rot and random.random() < 0.5\n rot90 = rot and random.random() < 0.5\n #rot90n = rot and random.random() < 0.5\n\n def _augment(img):\n if hflip: img = np.flip(img, axis=1) #img[:, ::-1, :]\n if vflip: img = np.flip(img, axis=0) #img[::-1, :, :]\n #if rot90: img = img.transpose(1, 0, 2)\n if rot90: img = np.rot90(img, 1) #90 degrees # In PIL: img.transpose(Image.ROTATE_90)\n #if rot90n: img = np.rot90(img, -1) #-90 degrees\n return img\n\n return [_augment(img) for img in img_list]\n\n\n\n####################\n# Normalization functions\n####################\n\n\n#TODO: Could also automatically detect the possible range with min and max, like in def ssim()\ndef denorm(x, min_max=(-1.0, 1.0)):\n '''\n Denormalize from [-1,1] range to [0,1]\n formula: xi' = (xi - mu)/sigma\n Example: \"out = (x + 1.0) / 2.0\" for denorm\n range (-1,1) to (0,1)\n for use with proper act in Generator output (ie. tanh)\n '''\n out = (x - min_max[0]) / (min_max[1] - min_max[0])\n if isinstance(x, torch.Tensor):\n return out.clamp(0, 1)\n elif isinstance(x, np.ndarray):\n return np.clip(out, 0, 1)\n else:\n raise TypeError(\"Got unexpected object type, expected torch.Tensor or \\\n np.ndarray\")\n\ndef norm(x):\n #Normalize (z-norm) from [0,1] range to [-1,1]\n out = (x - 0.5) * 2.0\n if isinstance(x, torch.Tensor):\n return out.clamp(-1, 1)\n elif isinstance(x, np.ndarray):\n return np.clip(out, -1, 1)\n else:\n raise TypeError(\"Got unexpected object type, expected torch.Tensor or \\\n np.ndarray\")\n\n\n####################\n# np and tensor conversions\n####################\n\n\n#2tensor\ndef np2tensor(img, bgr2rgb=True, data_range=1., normalize=False, change_range=True, add_batch=True):\n \"\"\"\n Converts a numpy image array into a Tensor array.\n Parameters:\n img (numpy array): the input image numpy array\n add_batch (bool): choose if new tensor needs batch dimension added\n \"\"\"\n if not isinstance(img, np.ndarray): #images expected to be uint8 -> 255\n raise TypeError(\"Got unexpected object type, expected np.ndarray\")\n #check how many channels the image has, then condition, like in my BasicSR. ie. RGB, RGBA, Gray\n #if bgr2rgb:\n #img = img[:, :, [2, 1, 0]] #BGR to RGB -> in numpy, if using OpenCV, else not needed. Only if image has colors.\n if change_range:\n if np.issubdtype(img.dtype, np.integer):\n info = np.iinfo\n elif np.issubdtype(img.dtype, np.floating):\n info = np.finfo\n img = img*data_range/info(img.dtype).max #uint8 = /255\n img = torch.from_numpy(np.ascontiguousarray(np.transpose(img, (2, 0, 1)))).float() #\"HWC to CHW\" and \"numpy to tensor\"\n if bgr2rgb:\n if img.shape[0] == 3: #RGB\n #BGR to RGB -> in tensor, if using OpenCV, else not needed. Only if image has colors.\n img = bgr_to_rgb(img)\n elif img.shape[0] == 4: #RGBA\n #BGR to RGB -> in tensor, if using OpenCV, else not needed. Only if image has colors.)\n img = bgra_to_rgba(img)\n if add_batch:\n img.unsqueeze_(0) # Add fake batch dimension = 1 . squeeze() will remove the dimensions of size 1\n if normalize:\n img = norm(img)\n return img\n\n#2np\ndef tensor2np(img, rgb2bgr=True, remove_batch=True, data_range=255,\n denormalize=False, change_range=True, imtype=np.uint8):\n \"\"\"\n Converts a Tensor array into a numpy image array.\n Parameters:\n img (tensor): the input image tensor array\n 4D(B,(3/1),H,W), 3D(C,H,W), or 2D(H,W), any range, RGB channel order\n remove_batch (bool): choose if tensor of shape BCHW needs to be squeezed\n denormalize (bool): Used to denormalize from [-1,1] range back to [0,1]\n imtype (type): the desired type of the converted numpy array (np.uint8\n default)\n Output:\n img (np array): 3D(H,W,C) or 2D(H,W), [0,255], np.uint8 (default)\n \"\"\"\n if not isinstance(img, torch.Tensor):\n raise TypeError(\"Got unexpected object type, expected torch.Tensor\")\n n_dim = img.dim()\n\n #TODO: Check: could denormalize here in tensor form instead, but end result is the same\n\n img = img.float().cpu()\n\n if n_dim == 4 or n_dim == 3:\n #if n_dim == 4, has to convert to 3 dimensions, either removing batch or by creating a grid\n if n_dim == 4 and remove_batch:\n if img.shape[0] > 1:\n # leave only the first image in the batch\n img = img[0,...]\n else:\n # remove a fake batch dimension\n img = img.squeeze()\n # squeeze removes batch and channel of grayscale images (dimensions = 1)\n if len(img.shape) < 3:\n #add back the lost channel dimension\n img = img.unsqueeze(dim=0)\n # convert images in batch (BCHW) to a grid of all images (C B*H B*W)\n else:\n n_img = len(img)\n img = make_grid(img, nrow=int(math.sqrt(n_img)), normalize=False)\n\n if img.shape[0] == 3 and rgb2bgr: #RGB\n #RGB to BGR -> in tensor, if using OpenCV, else not needed. Only if image has colors.\n img_np = rgb_to_bgr(img).numpy()\n elif img.shape[0] == 4 and rgb2bgr: #RGBA\n #RGBA to BGRA -> in tensor, if using OpenCV, else not needed. Only if image has colors.\n img_np = rgba_to_bgra(img).numpy()\n else:\n img_np = img.numpy()\n img_np = np.transpose(img_np, (1, 2, 0)) # \"CHW to HWC\" -> # HWC, BGR\n elif n_dim == 2:\n img_np = img.numpy()\n else:\n raise TypeError(\n 'Only support 4D, 3D and 2D tensor. But received with dimension: {:d}'.format(n_dim))\n\n #if rgb2bgr:\n #img_np = img_np[[2, 1, 0], :, :] #RGB to BGR -> in numpy, if using OpenCV, else not needed. Only if image has colors.\n #TODO: Check: could denormalize in the begining in tensor form instead\n if denormalize:\n img_np = denorm(img_np) #denormalize if needed\n if change_range:\n img_np = np.clip(data_range*img_np,0,data_range).round() #clip to the data_range\n # Important. Unlike matlab, numpy.unit8() WILL NOT round by default.\n #has to be in range (0,255) before changing to np.uint8, else np.float32\n return img_np.astype(imtype)\n\n\n\n\n####################\n# Prepare Images\n####################\n# https://github.com/sunreef/BlindSR/blob/master/src/image_utils.py\ndef patchify_tensor(features, patch_size, overlap=10):\n batch_size, channels, height, width = features.size()\n\n effective_patch_size = patch_size - overlap\n n_patches_height = (height // effective_patch_size)\n n_patches_width = (width // effective_patch_size)\n\n if n_patches_height * effective_patch_size < height:\n n_patches_height += 1\n if n_patches_width * effective_patch_size < width:\n n_patches_width += 1\n\n patches = []\n for b in range(batch_size):\n for h in range(n_patches_height):\n for w in range(n_patches_width):\n patch_start_height = min(h * effective_patch_size, height - patch_size)\n patch_start_width = min(w * effective_patch_size, width - patch_size)\n patches.append(features[b:b+1, :,\n patch_start_height: patch_start_height + patch_size,\n patch_start_width: patch_start_width + patch_size])\n return torch.cat(patches, 0)\n\ndef recompose_tensor(patches, full_height, full_width, overlap=10):\n\n batch_size, channels, patch_size, _ = patches.size()\n effective_patch_size = patch_size - overlap\n n_patches_height = (full_height // effective_patch_size)\n n_patches_width = (full_width // effective_patch_size)\n\n if n_patches_height * effective_patch_size < full_height:\n n_patches_height += 1\n if n_patches_width * effective_patch_size < full_width:\n n_patches_width += 1\n\n n_patches = n_patches_height * n_patches_width\n if batch_size % n_patches != 0:\n print(\"Error: The number of patches provided to the recompose function does not match the number of patches in each image.\")\n final_batch_size = batch_size // n_patches\n\n blending_in = torch.linspace(0.1, 1.0, overlap)\n blending_out = torch.linspace(1.0, 0.1, overlap)\n middle_part = torch.ones(patch_size - 2 * overlap)\n blending_profile = torch.cat([blending_in, middle_part, blending_out], 0)\n\n horizontal_blending = blending_profile[None].repeat(patch_size, 1)\n vertical_blending = blending_profile[:, None].repeat(1, patch_size)\n blending_patch = horizontal_blending * vertical_blending\n\n blending_image = torch.zeros(1, channels, full_height, full_width)\n for h in range(n_patches_height):\n for w in range(n_patches_width):\n patch_start_height = min(h * effective_patch_size, full_height - patch_size)\n patch_start_width = min(w * effective_patch_size, full_width - patch_size)\n blending_image[0, :, patch_start_height: patch_start_height + patch_size, patch_start_width: patch_start_width + patch_size] += blending_patch[None]\n\n recomposed_tensor = torch.zeros(final_batch_size, channels, full_height, full_width)\n if patches.is_cuda:\n blending_patch = blending_patch.cuda()\n blending_image = blending_image.cuda()\n recomposed_tensor = recomposed_tensor.cuda()\n patch_index = 0\n for b in range(final_batch_size):\n for h in range(n_patches_height):\n for w in range(n_patches_width):\n patch_start_height = min(h * effective_patch_size, full_height - patch_size)\n patch_start_width = min(w * effective_patch_size, full_width - patch_size)\n recomposed_tensor[b, :, patch_start_height: patch_start_height + patch_size, patch_start_width: patch_start_width + patch_size] += patches[patch_index] * blending_patch\n patch_index += 1\n recomposed_tensor /= blending_image\n\n return recomposed_tensor\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n#TODO: imresize could be an independent file (imresize.py)\n####################\n# Matlab imresize\n####################\n\n\n# These next functions are all interpolation methods. x is the distance from the left pixel center\ndef cubic(x):\n absx = torch.abs(x)\n absx2 = absx**2\n absx3 = absx**3\n return (1.5*absx3 - 2.5*absx2 + 1) * ((absx <= 1).type_as(absx)) + \\\n (-0.5*absx3 + 2.5*absx2 - 4*absx + 2) * (((absx > 1)*(absx <= 2)).type_as(absx))\n\ndef box(x):\n return ((-0.5 <= x) & (x < 0.5)) * 1.0\n\ndef linear(x):\n return (x + 1) * ((-1 <= x) & (x < 0)) + (1 - x) * ((0 <= x) & (x <= 1))\n\ndef lanczos2(x):\n return (((torch.sin(math.pi*x) * torch.sin(math.pi*x/2) + torch.finfo(torch.float32).eps) /\n ((math.pi**2 * x**2 / 2) + torch.finfo(torch.float32).eps))\n * (torch.abs(x) < 2))\n\ndef lanczos3(x):\n return (((torch.sin(math.pi*x) * torch.sin(math.pi*x/3) + torch.finfo(torch.float32).eps) /\n ((math.pi**2 * x**2 / 3) + torch.finfo(torch.float32).eps))\n * (torch.abs(x) < 3))\n\n\ndef calculate_weights_indices(in_length, out_length, scale, kernel, kernel_width, antialiasing):\n if (scale < 1) and (antialiasing):\n # Use a modified kernel to simultaneously interpolate and antialias- larger kernel width\n kernel_width = kernel_width / scale\n\n # Output-space coordinates\n x = torch.linspace(1, out_length, out_length)\n\n # Input-space coordinates. Calculate the inverse mapping such that 0.5\n # in output space maps to 0.5 in input space, and 0.5+scale in output\n # space maps to 1.5 in input space.\n u = x / scale + 0.5 * (1 - 1 / scale)\n\n # What is the left-most pixel that can be involved in the computation?\n left = torch.floor(u - kernel_width / 2)\n\n # What is the maximum number of pixels that can be involved in the\n # computation? Note: it's OK to use an extra pixel here; if the\n # corresponding weights are all zero, it will be eliminated at the end\n # of this function.\n P = math.ceil(kernel_width) + 2\n\n # The indices of the input pixels involved in computing the k-th output\n # pixel are in row k of the indices matrix.\n indices = left.view(out_length, 1).expand(out_length, P) + torch.linspace(0, P - 1, P).view(\n 1, P).expand(out_length, P)\n\n # The weights used to compute the k-th output pixel are in row k of the\n # weights matrix.\n distance_to_center = u.view(out_length, 1).expand(out_length, P) - indices\n # apply kernel\n if (scale < 1) and (antialiasing):\n weights = scale * kernel(distance_to_center * scale)\n else:\n weights = kernel(distance_to_center)\n # Normalize the weights matrix so that each row sums to 1.\n weights_sum = torch.sum(weights, 1).view(out_length, 1)\n weights = weights / weights_sum.expand(out_length, P)\n\n # If a column in weights is all zero, get rid of it. only consider the first and last column.\n weights_zero_tmp = torch.sum((weights == 0), 0)\n if not math.isclose(weights_zero_tmp[0], 0, rel_tol=1e-6):\n indices = indices.narrow(1, 1, P - 2)\n weights = weights.narrow(1, 1, P - 2)\n if not math.isclose(weights_zero_tmp[-1], 0, rel_tol=1e-6):\n indices = indices.narrow(1, 0, P - 2)\n weights = weights.narrow(1, 0, P - 2)\n weights = weights.contiguous()\n indices = indices.contiguous()\n sym_len_s = -indices.min() + 1\n sym_len_e = indices.max() - in_length\n indices = indices + sym_len_s - 1\n return weights, indices, int(sym_len_s), int(sym_len_e)\n\n\ndef imresize(img, scale, antialiasing=True, interpolation=None):\n # The scale should be the same for H and W\n # input: img: CHW RGB [0,1]\n # output: CHW RGB [0,1] w/o round\n\n in_C, in_H, in_W = img.size()\n out_C, out_H, out_W = in_C, math.ceil(in_H * scale), math.ceil(in_W * scale)\n\n # Choose interpolation method, each method has the matching kernel size\n kernel, kernel_width = {\n \"cubic\": (cubic, 4.0),\n \"lanczos2\": (lanczos2, 4.0),\n \"lanczos3\": (lanczos3, 6.0),\n \"box\": (box, 1.0),\n \"linear\": (linear, 2.0),\n None: (cubic, 4.0) # set default interpolation method as cubic\n }.get(interpolation)\n\n # Return the desired dimension order for performing the resize. The\n # strategy is to perform the resize first along the dimension with the\n # smallest scale factor.\n # Now we do not support this.\n\n # get weights and indices\n weights_H, indices_H, sym_len_Hs, sym_len_He = calculate_weights_indices(\n in_H, out_H, scale, kernel, kernel_width, antialiasing)\n weights_W, indices_W, sym_len_Ws, sym_len_We = calculate_weights_indices(\n in_W, out_W, scale, kernel, kernel_width, antialiasing)\n # process H dimension\n # symmetric copying\n img_aug = torch.FloatTensor(in_C, in_H + sym_len_Hs + sym_len_He, in_W)\n img_aug.narrow(1, sym_len_Hs, in_H).copy_(img)\n\n sym_patch = img[:, :sym_len_Hs, :]\n inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long()\n sym_patch_inv = sym_patch.index_select(1, inv_idx)\n img_aug.narrow(1, 0, sym_len_Hs).copy_(sym_patch_inv)\n\n sym_patch = img[:, -sym_len_He:, :]\n inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long()\n sym_patch_inv = sym_patch.index_select(1, inv_idx)\n img_aug.narrow(1, sym_len_Hs + in_H, sym_len_He).copy_(sym_patch_inv)\n\n out_1 = torch.FloatTensor(in_C, out_H, in_W)\n kernel_width = weights_H.size(1)\n for i in range(out_H):\n idx = int(indices_H[i][0])\n out_1[0, i, :] = img_aug[0, idx:idx + kernel_width, :].transpose(0, 1).mv(weights_H[i])\n out_1[1, i, :] = img_aug[1, idx:idx + kernel_width, :].transpose(0, 1).mv(weights_H[i])\n out_1[2, i, :] = img_aug[2, idx:idx + kernel_width, :].transpose(0, 1).mv(weights_H[i])\n\n # process W dimension\n # symmetric copying\n out_1_aug = torch.FloatTensor(in_C, out_H, in_W + sym_len_Ws + sym_len_We)\n out_1_aug.narrow(2, sym_len_Ws, in_W).copy_(out_1)\n\n sym_patch = out_1[:, :, :sym_len_Ws]\n inv_idx = torch.arange(sym_patch.size(2) - 1, -1, -1).long()\n sym_patch_inv = sym_patch.index_select(2, inv_idx)\n out_1_aug.narrow(2, 0, sym_len_Ws).copy_(sym_patch_inv)\n\n sym_patch = out_1[:, :, -sym_len_We:]\n inv_idx = torch.arange(sym_patch.size(2) - 1, -1, -1).long()\n sym_patch_inv = sym_patch.index_select(2, inv_idx)\n out_1_aug.narrow(2, sym_len_Ws + in_W, sym_len_We).copy_(sym_patch_inv)\n\n out_2 = torch.FloatTensor(in_C, out_H, out_W)\n kernel_width = weights_W.size(1)\n for i in range(out_W):\n idx = int(indices_W[i][0])\n out_2[0, :, i] = out_1_aug[0, :, idx:idx + kernel_width].mv(weights_W[i])\n out_2[1, :, i] = out_1_aug[1, :, idx:idx + kernel_width].mv(weights_W[i])\n out_2[2, :, i] = out_1_aug[2, :, idx:idx + kernel_width].mv(weights_W[i])\n\n return out_2\n\n\ndef imresize_np(img, scale, antialiasing=True, interpolation=None):\n # Now the scale should be the same for H and W\n # input: img: Numpy, HWC BGR [0,1]\n # output: HWC BGR [0,1] w/o round\n\n change_range = False\n if img.max() > 1:\n img_type = img.dtype\n if np.issubdtype(img_type, np.integer):\n info = np.iinfo\n elif np.issubdtype(img_type, np.floating):\n info = np.finfo\n img = img/info(img_type).max\n change_range = True\n\n img = torch.from_numpy(img)\n\n in_H, in_W, in_C = img.size()\n out_C, out_H, out_W = in_C, math.ceil(in_H * scale), math.ceil(in_W * scale)\n\n # Choose interpolation method, each method has the matching kernel size\n kernel, kernel_width = {\n \"cubic\": (cubic, 4.0),\n \"lanczos2\": (lanczos2, 4.0),\n \"lanczos3\": (lanczos3, 6.0),\n \"box\": (box, 1.0),\n \"linear\": (linear, 2.0),\n None: (cubic, 4.0) # set default interpolation method as cubic\n }.get(interpolation)\n\n # Return the desired dimension order for performing the resize. The\n # strategy is to perform the resize first along the dimension with the\n # smallest scale factor.\n # Now we do not support this.\n\n # get weights and indices\n weights_H, indices_H, sym_len_Hs, sym_len_He = calculate_weights_indices(\n in_H, out_H, scale, kernel, kernel_width, antialiasing)\n weights_W, indices_W, sym_len_Ws, sym_len_We = calculate_weights_indices(\n in_W, out_W, scale, kernel, kernel_width, antialiasing)\n # process H dimension\n # symmetric copying\n img_aug = torch.FloatTensor(in_H + sym_len_Hs + sym_len_He, in_W, in_C)\n img_aug.narrow(0, sym_len_Hs, in_H).copy_(img)\n\n sym_patch = img[:sym_len_Hs, :, :]\n inv_idx = torch.arange(sym_patch.size(0) - 1, -1, -1).long()\n sym_patch_inv = sym_patch.index_select(0, inv_idx)\n img_aug.narrow(0, 0, sym_len_Hs).copy_(sym_patch_inv)\n\n sym_patch = img[-sym_len_He:, :, :]\n inv_idx = torch.arange(sym_patch.size(0) - 1, -1, -1).long()\n sym_patch_inv = sym_patch.index_select(0, inv_idx)\n img_aug.narrow(0, sym_len_Hs + in_H, sym_len_He).copy_(sym_patch_inv)\n\n out_1 = torch.FloatTensor(out_H, in_W, in_C)\n kernel_width = weights_H.size(1)\n for i in range(out_H):\n idx = int(indices_H[i][0])\n out_1[i, :, 0] = img_aug[idx:idx + kernel_width, :, 0].transpose(0, 1).mv(weights_H[i])\n out_1[i, :, 1] = img_aug[idx:idx + kernel_width, :, 1].transpose(0, 1).mv(weights_H[i])\n out_1[i, :, 2] = img_aug[idx:idx + kernel_width, :, 2].transpose(0, 1).mv(weights_H[i])\n\n # process W dimension\n # symmetric copying\n out_1_aug = torch.FloatTensor(out_H, in_W + sym_len_Ws + sym_len_We, in_C)\n out_1_aug.narrow(1, sym_len_Ws, in_W).copy_(out_1)\n\n sym_patch = out_1[:, :sym_len_Ws, :]\n inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long()\n sym_patch_inv = sym_patch.index_select(1, inv_idx)\n out_1_aug.narrow(1, 0, sym_len_Ws).copy_(sym_patch_inv)\n\n sym_patch = out_1[:, -sym_len_We:, :]\n inv_idx = torch.arange(sym_patch.size(1) - 1, -1, -1).long()\n sym_patch_inv = sym_patch.index_select(1, inv_idx)\n out_1_aug.narrow(1, sym_len_Ws + in_W, sym_len_We).copy_(sym_patch_inv)\n\n out_2 = torch.FloatTensor(out_H, out_W, in_C)\n kernel_width = weights_W.size(1)\n for i in range(out_W):\n idx = int(indices_W[i][0])\n out_2[:, i, 0] = out_1_aug[:, idx:idx + kernel_width, 0].mv(weights_W[i])\n out_2[:, i, 1] = out_1_aug[:, idx:idx + kernel_width, 1].mv(weights_W[i])\n out_2[:, i, 2] = out_1_aug[:, idx:idx + kernel_width, 2].mv(weights_W[i])\n\n out_2 = out_2.numpy().clip(0,1)\n\n if change_range:\n out_2 = out_2*info(img_type).max #uint8 = 255\n out_2 = out_2.astype(img_type)\n\n return out_2\n\n\nif __name__ == '__main__':\n # test imresize function\n # read images\n img = cv2.imread('test.png')\n img = img * 1.0 / 255\n img = torch.from_numpy(np.transpose(img[:, :, [2, 1, 0]], (2, 0, 1))).float()\n # imresize\n scale = 1 / 4\n import time\n total_time = 0\n for i in range(10):\n start_time = time.time()\n rlt = imresize(img, scale, antialiasing=True)\n use_time = time.time() - start_time\n total_time += use_time\n print('average time: {}'.format(total_time / 10))\n\n import torchvision.utils\n torchvision.utils.save_image(\n (rlt * 255).round() / 255, 'rlt.png', nrow=1, padding=0, normalize=False)\n", "#@title one_stage.py (new loss, todo: adding loss functions to ```def generator_loss```)\n\nfrom .vic.loss import CharbonnierLoss, GANLoss, GradientPenaltyLoss, HFENLoss, TVLoss, GradientLoss, ElasticLoss, RelativeL1, L1CosineSim, ClipL1, MaskedL1Loss, MultiscalePixelLoss, FFTloss, OFLoss, L1_regularization, ColorLoss, AverageLoss, GPLoss, CPLoss, SPL_ComputeWithTrace, SPLoss, Contextual_Loss\nfrom .vic.filters import *\nfrom .vic.colors import *\nfrom .vic.discriminators import *\n\nimport os.path as osp\nfrom pathlib import Path\n\nimport mmcv\nimport torch\nfrom mmcv.runner import auto_fp16\nfrom torchvision.utils import save_image\n\nfrom mmedit.core import L1Evaluation, psnr, ssim, tensor2img\nfrom ..base import BaseModel\nfrom ..builder import build_backbone, build_component, build_loss\nfrom ..common import set_requires_grad\nfrom ..registry import MODELS\n\n\[email protected]_module()\nclass OneStageInpaintor(BaseModel):\n \"\"\"Standard one-stage inpaintor with commonly used losses.\n\n An inpaintor must contain an encoder-decoder style generator to\n inpaint masked regions. A discriminator will be adopted when\n adversarial training is needed.\n\n In this class, we provide a common interface for inpaintors.\n For other inpaintors, only some funcs may be modified to fit the\n input style or training schedule.\n\n Args:\n generator (dict): Config for encoder-decoder style generator.\n disc (dict): Config for discriminator.\n loss_gan (dict): Config for adversarial loss.\n loss_gp (dict): Config for gradient penalty loss.\n loss_disc_shift (dict): Config for discriminator shift loss.\n loss_composed_percep (dict): Config for perceptural and style loss with\n composed image as input.\n loss_out_percep (dict): Config for perceptural and style loss with\n direct output as input.\n loss_l1_hole (dict): Config for l1 loss in the hole.\n loss_l1_valid (dict): Config for l1 loss in the valid region.\n loss_tv (dict): Config for total variation loss.\n train_cfg (dict): Configs for training scheduler. `disc_step` must be\n contained for indicates the discriminator updating steps in each\n training step.\n test_cfg (dict): Configs for testing scheduler.\n pretrained (str): Path for pretrained model. Default None.\n \"\"\"\n _eval_metrics = dict(l1=L1Evaluation, psnr=psnr, ssim=ssim)\n\n def __init__(self,\n encdec,\n disc=None,\n loss_gan=None,\n loss_gp=None,\n loss_disc_shift=None,\n loss_composed_percep=None,\n loss_out_percep=False,\n loss_l1_hole=None,\n loss_l1_valid=None,\n loss_tv=None,\n train_cfg=None,\n test_cfg=None,\n pretrained=None):\n super(OneStageInpaintor, self).__init__()\n self.with_l1_hole_loss = loss_l1_hole is not None\n self.with_l1_valid_loss = loss_l1_valid is not None\n self.with_tv_loss = loss_tv is not None\n self.with_composed_percep_loss = loss_composed_percep is not None\n self.with_out_percep_loss = loss_out_percep\n self.with_gan = disc is not None and loss_gan is not None\n self.with_gp_loss = loss_gp is not None\n self.with_disc_shift_loss = loss_disc_shift is not None\n self.is_train = train_cfg is not None\n self.train_cfg = train_cfg\n self.test_cfg = test_cfg\n self.eval_with_metrics = ('metrics' in self.test_cfg) and (\n self.test_cfg['metrics'] is not None)\n\n self.generator = build_backbone(encdec)\n\n # support fp16\n self.fp16_enabled = False\n\n # build loss modules\n if self.with_gan:\n self.disc = build_component(disc)\n self.loss_gan = build_loss(loss_gan)\n\n if self.with_l1_hole_loss:\n self.loss_l1_hole = build_loss(loss_l1_hole)\n\n if self.with_l1_valid_loss:\n self.loss_l1_valid = build_loss(loss_l1_valid)\n\n if self.with_composed_percep_loss:\n self.loss_percep = build_loss(loss_composed_percep)\n\n if self.with_gp_loss:\n self.loss_gp = build_loss(loss_gp)\n\n if self.with_disc_shift_loss:\n self.loss_disc_shift = build_loss(loss_disc_shift)\n\n if self.with_tv_loss:\n self.loss_tv = build_loss(loss_tv)\n\n self.disc_step_count = 0\n self.init_weights(pretrained=pretrained)\n\n # new loss\n\n # #l_hfen_type = CharbonnierLoss() # nn.L1Loss(), nn.MSELoss(), CharbonnierLoss(), ElasticLoss(), RelativeL1(), L1CosineSim()\n l_hfen_type = L1CosineSim()\n self.HFENLoss = HFENLoss(loss_f=l_hfen_type, kernel='log', kernel_size=15, sigma = 2.5, norm = False)\n\n self.ElasticLoss = ElasticLoss(a=0.2, reduction='mean')\n\n self.RelativeL1 = RelativeL1(eps=.01, reduction='mean')\n\n self.L1CosineSim = L1CosineSim(loss_lambda=5, reduction='mean')\n\n self.ClipL1 = ClipL1(clip_min=0.0, clip_max=10.0)\n\n self.FFTloss = FFTloss(loss_f = torch.nn.L1Loss, reduction='mean')\n\n self.OFLoss = OFLoss()\n\n self.GPLoss = GPLoss(trace=False, spl_denorm=False)\n\n self.CPLoss = CPLoss(rgb=True, yuv=True, yuvgrad=True, trace=False, spl_denorm=False, yuv_denorm=False)\n\n layers_weights = {'conv_1_1': 1.0, 'conv_3_2': 1.0}\n self.Contextual_Loss = Contextual_Loss(layers_weights, crop_quarter=False, max_1d_size=100,\n distance_type = 'cosine', b=1.0, band_width=0.5,\n use_vgg = True, net = 'vgg19', calc_type = 'regular')\n\n\n\n\n def init_weights(self, pretrained=None):\n \"\"\"Init weights for models.\n\n Args:\n pretrained (str, optional): Path for pretrained weights. If given\n None, pretrained weights will not be loaded. Defaults to None.\n \"\"\"\n self.generator.init_weights(pretrained=pretrained)\n if self.with_gan:\n self.disc.init_weights(pretrained=pretrained)\n\n @auto_fp16(apply_to=('masked_img', 'mask'))\n def forward(self, masked_img, mask, test_mode=True, **kwargs):\n \"\"\"Forward function.\n\n Args:\n masked_img (torch.Tensor): Image with hole as input.\n mask (torch.Tensor): Mask as input.\n test_mode (bool, optional): Whether use testing mode.\n Defaults to True.\n\n Returns:\n dict: Dict contains output results.\n \"\"\"\n if not test_mode:\n return self.forward_train(masked_img, mask, **kwargs)\n else:\n return self.forward_test(masked_img, mask, **kwargs)\n\n def forward_train(self, *args, **kwargs):\n \"\"\"Forward function for training.\n\n In this version, we do not use this interface.\n \"\"\"\n raise NotImplementedError('This interface should not be used in '\n 'current training schedule. Please use '\n '`train_step` for training.')\n\n def forward_train_d(self, data_batch, is_real, is_disc):\n \"\"\"Forward function in discriminator training step.\n\n In this function, we compute the prediction for each data batch (real\n or fake). Meanwhile, the standard gan loss will be computed with\n several proposed losses fro stable training.\n\n Args:\n data (torch.Tensor): Batch of real data or fake data.\n is_real (bool): If True, the gan loss will regard this batch as\n real data. Otherwise, the gan loss will regard this batch as\n fake data.\n is_disc (bool): If True, this function is called in discriminator\n training step. Otherwise, this function is called in generator\n training step. This will help us to compute different types of\n adversarial loss, like LSGAN.\n\n Returns:\n dict: Contains the loss items computed in this function.\n \"\"\"\n pred = self.disc(data_batch)\n loss_ = self.loss_gan(pred, is_real, is_disc)\n\n loss = dict(real_loss=loss_) if is_real else dict(fake_loss=loss_)\n\n if self.with_disc_shift_loss:\n loss_d_shift = self.loss_disc_shift(loss_)\n # 0.5 for average the fake and real data\n loss.update(loss_disc_shift=loss_d_shift * 0.5)\n\n return loss\n\n def generator_loss(self, fake_res, fake_img, data_batch):\n \"\"\"Forward function in generator training step.\n\n In this function, we mainly compute the loss items for generator with\n the given (fake_res, fake_img). In general, the `fake_res` is the\n direct output of the generator and the `fake_img` is the composition of\n direct output and ground-truth image.\n\n Args:\n fake_res (torch.Tensor): Direct output of the generator.\n fake_img (torch.Tensor): Composition of `fake_res` and\n ground-truth image.\n data_batch (dict): Contain other elements for computing losses.\n\n Returns:\n tuple(dict): Dict contains the results computed within this \\\n function for visualization and dict contains the loss items \\\n computed in this function.\n \"\"\"\n gt = data_batch['gt_img']\n mask = data_batch['mask']\n masked_img = data_batch['masked_img']\n\n loss = dict()\n\n if self.with_gan:\n g_fake_pred = self.disc(fake_img)\n loss_g_fake = self.loss_gan(g_fake_pred, True, is_disc=False)\n loss['loss_g_fake'] = loss_g_fake\n\n if self.with_l1_hole_loss:\n loss_l1_hole = self.loss_l1_hole(fake_res, gt, weight=mask)\n loss['loss_l1_hole'] = loss_l1_hole\n\n if self.with_l1_valid_loss:\n loss_loss_l1_valid = self.loss_l1_valid(\n fake_res, gt, weight=1. - mask)\n loss['loss_l1_valid'] = loss_loss_l1_valid\n\n if self.with_composed_percep_loss:\n loss_pecep, loss_style = self.loss_percep(fake_img, gt)\n if loss_pecep is not None:\n loss['loss_composed_percep'] = loss_pecep\n if loss_style is not None:\n loss['loss_composed_style'] = loss_style\n\n if self.with_out_percep_loss:\n loss_out_percep, loss_out_style = self.loss_percep(fake_res, gt)\n if loss_out_percep is not None:\n loss['loss_out_percep'] = loss_out_percep\n if loss_out_style is not None:\n loss['loss_out_style'] = loss_out_style\n\n if self.with_tv_loss:\n loss_tv = self.loss_tv(fake_img, mask=mask)\n loss['loss_tv'] = loss_tv\n\n res = dict(\n gt_img=gt.cpu(),\n masked_img=masked_img.cpu(),\n fake_res=fake_res.cpu(),\n fake_img=fake_img.cpu())\n\n return res, loss\n\n def forward_test(self,\n masked_img,\n mask,\n save_image=False,\n save_path=None,\n iteration=None,\n **kwargs):\n \"\"\"Forward function for testing.\n\n Args:\n masked_img (torch.Tensor): Tensor with shape of (n, 3, h, w).\n mask (torch.Tensor): Tensor with shape of (n, 1, h, w).\n save_image (bool, optional): If True, results will be saved as\n image. Defaults to False.\n save_path (str, optional): If given a valid str, the reuslts will\n be saved in this path. Defaults to None.\n iteration (int, optional): Iteration number. Defaults to None.\n\n Returns:\n dict: Contain output results and eval metrics (if have).\n \"\"\"\n input_x = torch.cat([masked_img, mask], dim=1)\n fake_res = self.generator(input_x)\n fake_img = fake_res * mask + masked_img * (1. - mask)\n\n output = dict()\n eval_results = {}\n if self.eval_with_metrics:\n gt_img = kwargs['gt_img']\n data_dict = dict(gt_img=gt_img, fake_res=fake_res, mask=mask)\n for metric_name in self.test_cfg['metrics']:\n if metric_name in ['ssim', 'psnr']:\n eval_results[metric_name] = self._eval_metrics[\n metric_name](tensor2img(fake_img, min_max=(-1, 1)),\n tensor2img(gt_img, min_max=(-1, 1)))\n else:\n eval_results[metric_name] = self._eval_metrics[\n metric_name]()(data_dict).item()\n output['eval_results'] = eval_results\n else:\n output['fake_res'] = fake_res\n output['fake_img'] = fake_img\n\n output['meta'] = None if 'meta' not in kwargs else kwargs['meta'][0]\n\n if save_image:\n assert save_image and save_path is not None, (\n 'Save path should been given')\n assert output['meta'] is not None, (\n 'Meta information should be given to save image.')\n\n tmp_filename = output['meta']['gt_img_path']\n filestem = Path(tmp_filename).stem\n if iteration is not None:\n filename = f'{filestem}_{iteration}.png'\n else:\n filename = f'{filestem}.png'\n mmcv.mkdir_or_exist(save_path)\n img_list = [kwargs['gt_img']] if 'gt_img' in kwargs else []\n img_list.extend(\n [masked_img,\n mask.expand_as(masked_img), fake_res, fake_img])\n img = torch.cat(img_list, dim=3).cpu()\n self.save_visualization(img, osp.join(save_path, filename))\n output['save_img_path'] = osp.abspath(\n osp.join(save_path, filename))\n\n return output\n\n def save_visualization(self, img, filename):\n \"\"\"Save visualization results.\n\n Args:\n img (torch.Tensor): Tensor with shape of (n, 3, h, w).\n filename (str): Path to save visualization.\n \"\"\"\n if self.test_cfg.get('img_rerange', True):\n img = (img + 1) / 2\n if self.test_cfg.get('img_bgr2rgb', True):\n img = img[:, [2, 1, 0], ...]\n save_image(img, filename, nrow=1, padding=0)\n\n def train_step(self, data_batch, optimizer):\n \"\"\"Train step function.\n\n In this function, the inpaintor will finish the train step following\n the pipeline:\n\n 1. get fake res/image\n 2. optimize discriminator (if have)\n 3. optimize generator\n\n If `self.train_cfg.disc_step > 1`, the train step will contain multiple\n iterations for optimizing discriminator with different input data and\n only one iteration for optimizing gerator after `disc_step` iterations\n for discriminator.\n\n Args:\n data_batch (torch.Tensor): Batch of data as input.\n optimizer (dict[torch.optim.Optimizer]): Dict with optimizers for\n generator and discriminator (if have).\n\n Returns:\n dict: Dict with loss, information for logger, the number of \\\n samples and results for visualization.\n \"\"\"\n log_vars = {}\n\n gt_img = data_batch['gt_img']\n mask = data_batch['mask']\n masked_img = data_batch['masked_img']\n\n # get common output from encdec\n input_x = torch.cat([masked_img, mask], dim=1)\n fake_res = self.generator(input_x)\n fake_img = gt_img * (1. - mask) + fake_res * mask\n\n # discriminator training step\n if self.train_cfg.disc_step > 0:\n set_requires_grad(self.disc, True)\n disc_losses = self.forward_train_d(\n fake_img.detach(), False, is_disc=True)\n loss_disc, log_vars_d = self.parse_losses(disc_losses)\n log_vars.update(log_vars_d)\n optimizer['disc'].zero_grad()\n loss_disc.backward()\n\n disc_losses = self.forward_train_d(gt_img, True, is_disc=True)\n loss_disc, log_vars_d = self.parse_losses(disc_losses)\n log_vars.update(log_vars_d)\n loss_disc.backward()\n\n if self.with_gp_loss:\n loss_d_gp = self.loss_gp(\n self.disc, gt_img, fake_img, mask=mask)\n loss_disc, log_vars_d = self.parse_losses(\n dict(loss_gp=loss_d_gp))\n log_vars.update(log_vars_d)\n loss_disc.backward()\n\n optimizer['disc'].step()\n\n self.disc_step_count = (self.disc_step_count +\n 1) % self.train_cfg.disc_step\n if self.disc_step_count != 0:\n # results contain the data for visualization\n results = dict(\n gt_img=gt_img.cpu(),\n masked_img=masked_img.cpu(),\n fake_res=fake_res.cpu(),\n fake_img=fake_img.cpu())\n outputs = dict(\n log_vars=log_vars,\n num_samples=len(data_batch['gt_img'].data),\n results=results)\n\n return outputs\n\n # generator (encdec) training step, results contain the data\n # for visualization\n if self.with_gan:\n set_requires_grad(self.disc, False)\n results, g_losses = self.generator_loss(fake_res, fake_img, data_batch)\n loss_g, log_vars_g = self.parse_losses(g_losses)\n log_vars.update(log_vars_g)\n optimizer['generator'].zero_grad()\n loss_g.backward()\n optimizer['generator'].step()\n\n outputs = dict(\n log_vars=log_vars,\n num_samples=len(data_batch['gt_img'].data),\n results=results)\n\n return outputs\n\n def val_step(self, data_batch, **kwargs):\n \"\"\"Forward function for evaluation.\n\n Args:\n data_batch (dict): Contain data for forward.\n\n Returns:\n dict: Contain the results from model.\n \"\"\"\n output = self.forward_test(**data_batch, **kwargs)\n\n return output\n\n def forward_dummy(self, x):\n \"\"\"Forward dummy function for getting flops.\n\n Args:\n x (torch.Tensor): Input tensor with shape of (n, c, h, w).\n\n Returns:\n torch.Tensor: Results tensor with shape of (n, 3, h, w).\n \"\"\"\n res = self.generator(x)\n\n return res\n" ]
[ [ "numpy.dot", "torch.abs", "numpy.expand_dims", "torch.cat", "torch.zeros", "torch.sin", "numpy.issubdtype", "torch.sum", "torch.FloatTensor", "torch.finfo", "torch.ones", "numpy.clip", "numpy.matmul", "torch.from_numpy", "numpy.full", "numpy.frombuffer", "numpy.copy", "numpy.load", "numpy.rot90", "torch.linspace", "torch.floor", "numpy.linalg.inv", "numpy.transpose", "numpy.array", "numpy.flip" ], [ "torch.cat" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
gabriellm1/pandas
[ "020040b3b92516b445ddd8daba3b9818340e82d4", "020040b3b92516b445ddd8daba3b9818340e82d4", "020040b3b92516b445ddd8daba3b9818340e82d4", "020040b3b92516b445ddd8daba3b9818340e82d4", "020040b3b92516b445ddd8daba3b9818340e82d4", "020040b3b92516b445ddd8daba3b9818340e82d4" ]
[ "pandas/core/construction.py", "pandas/tests/reshape/test_melt.py", "pandas/tests/series/methods/test_replace.py", "pandas/tests/arithmetic/test_interval.py", "pandas/tests/window/moments/test_moments_consistency_ewm.py", "pandas/tests/test_sorting.py" ]
[ "\"\"\"\nConstructor functions intended to be shared by pd.array, Series.__init__,\nand Index.__new__.\n\nThese should not depend on core.internals.\n\"\"\"\nfrom __future__ import annotations\n\nfrom collections import abc\nfrom typing import TYPE_CHECKING, Any, Optional, Sequence, Union, cast\n\nimport numpy as np\nimport numpy.ma as ma\n\nfrom pandas._libs import lib\nfrom pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime\nfrom pandas._typing import AnyArrayLike, ArrayLike, Dtype, DtypeObj\n\nfrom pandas.core.dtypes.base import ExtensionDtype, registry\nfrom pandas.core.dtypes.cast import (\n construct_1d_arraylike_from_scalar,\n construct_1d_ndarray_preserving_na,\n construct_1d_object_array_from_listlike,\n infer_dtype_from_scalar,\n maybe_cast_to_datetime,\n maybe_cast_to_integer_array,\n maybe_castable,\n maybe_convert_platform,\n maybe_upcast,\n)\nfrom pandas.core.dtypes.common import (\n is_datetime64_ns_dtype,\n is_extension_array_dtype,\n is_float_dtype,\n is_integer_dtype,\n is_iterator,\n is_list_like,\n is_object_dtype,\n is_sparse,\n is_string_dtype,\n is_timedelta64_ns_dtype,\n)\nfrom pandas.core.dtypes.generic import (\n ABCExtensionArray,\n ABCIndexClass,\n ABCPandasArray,\n ABCSeries,\n)\nfrom pandas.core.dtypes.missing import isna\n\nimport pandas.core.common as com\n\nif TYPE_CHECKING:\n from pandas import ExtensionArray, Index, Series\n\n\ndef array(\n data: Union[Sequence[object], AnyArrayLike],\n dtype: Optional[Dtype] = None,\n copy: bool = True,\n) -> ExtensionArray:\n \"\"\"\n Create an array.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n data : Sequence of objects\n The scalars inside `data` should be instances of the\n scalar type for `dtype`. It's expected that `data`\n represents a 1-dimensional array of data.\n\n When `data` is an Index or Series, the underlying array\n will be extracted from `data`.\n\n dtype : str, np.dtype, or ExtensionDtype, optional\n The dtype to use for the array. This may be a NumPy\n dtype or an extension type registered with pandas using\n :meth:`pandas.api.extensions.register_extension_dtype`.\n\n If not specified, there are two possibilities:\n\n 1. When `data` is a :class:`Series`, :class:`Index`, or\n :class:`ExtensionArray`, the `dtype` will be taken\n from the data.\n 2. Otherwise, pandas will attempt to infer the `dtype`\n from the data.\n\n Note that when `data` is a NumPy array, ``data.dtype`` is\n *not* used for inferring the array type. This is because\n NumPy cannot represent all the types of data that can be\n held in extension arrays.\n\n Currently, pandas will infer an extension dtype for sequences of\n\n ============================== =====================================\n Scalar Type Array Type\n ============================== =====================================\n :class:`pandas.Interval` :class:`pandas.arrays.IntervalArray`\n :class:`pandas.Period` :class:`pandas.arrays.PeriodArray`\n :class:`datetime.datetime` :class:`pandas.arrays.DatetimeArray`\n :class:`datetime.timedelta` :class:`pandas.arrays.TimedeltaArray`\n :class:`int` :class:`pandas.arrays.IntegerArray`\n :class:`float` :class:`pandas.arrays.FloatingArray`\n :class:`str` :class:`pandas.arrays.StringArray`\n :class:`bool` :class:`pandas.arrays.BooleanArray`\n ============================== =====================================\n\n For all other cases, NumPy's usual inference rules will be used.\n\n .. versionchanged:: 1.0.0\n\n Pandas infers nullable-integer dtype for integer data,\n string dtype for string data, and nullable-boolean dtype\n for boolean data.\n\n .. versionchanged:: 1.2.0\n\n Pandas now also infers nullable-floating dtype for float-like\n input data\n\n copy : bool, default True\n Whether to copy the data, even if not necessary. Depending\n on the type of `data`, creating the new array may require\n copying data, even if ``copy=False``.\n\n Returns\n -------\n ExtensionArray\n The newly created array.\n\n Raises\n ------\n ValueError\n When `data` is not 1-dimensional.\n\n See Also\n --------\n numpy.array : Construct a NumPy array.\n Series : Construct a pandas Series.\n Index : Construct a pandas Index.\n arrays.PandasArray : ExtensionArray wrapping a NumPy array.\n Series.array : Extract the array stored within a Series.\n\n Notes\n -----\n Omitting the `dtype` argument means pandas will attempt to infer the\n best array type from the values in the data. As new array types are\n added by pandas and 3rd party libraries, the \"best\" array type may\n change. We recommend specifying `dtype` to ensure that\n\n 1. the correct array type for the data is returned\n 2. the returned array type doesn't change as new extension types\n are added by pandas and third-party libraries\n\n Additionally, if the underlying memory representation of the returned\n array matters, we recommend specifying the `dtype` as a concrete object\n rather than a string alias or allowing it to be inferred. For example,\n a future version of pandas or a 3rd-party library may include a\n dedicated ExtensionArray for string data. In this event, the following\n would no longer return a :class:`arrays.PandasArray` backed by a NumPy\n array.\n\n >>> pd.array(['a', 'b'], dtype=str)\n <PandasArray>\n ['a', 'b']\n Length: 2, dtype: str32\n\n This would instead return the new ExtensionArray dedicated for string\n data. If you really need the new array to be backed by a NumPy array,\n specify that in the dtype.\n\n >>> pd.array(['a', 'b'], dtype=np.dtype(\"<U1\"))\n <PandasArray>\n ['a', 'b']\n Length: 2, dtype: str32\n\n Finally, Pandas has arrays that mostly overlap with NumPy\n\n * :class:`arrays.DatetimeArray`\n * :class:`arrays.TimedeltaArray`\n\n When data with a ``datetime64[ns]`` or ``timedelta64[ns]`` dtype is\n passed, pandas will always return a ``DatetimeArray`` or ``TimedeltaArray``\n rather than a ``PandasArray``. This is for symmetry with the case of\n timezone-aware data, which NumPy does not natively support.\n\n >>> pd.array(['2015', '2016'], dtype='datetime64[ns]')\n <DatetimeArray>\n ['2015-01-01 00:00:00', '2016-01-01 00:00:00']\n Length: 2, dtype: datetime64[ns]\n\n >>> pd.array([\"1H\", \"2H\"], dtype='timedelta64[ns]')\n <TimedeltaArray>\n ['0 days 01:00:00', '0 days 02:00:00']\n Length: 2, dtype: timedelta64[ns]\n\n Examples\n --------\n If a dtype is not specified, pandas will infer the best dtype from the values.\n See the description of `dtype` for the types pandas infers for.\n\n >>> pd.array([1, 2])\n <IntegerArray>\n [1, 2]\n Length: 2, dtype: Int64\n\n >>> pd.array([1, 2, np.nan])\n <IntegerArray>\n [1, 2, <NA>]\n Length: 3, dtype: Int64\n\n >>> pd.array([1.1, 2.2])\n <FloatingArray>\n [1.1, 2.2]\n Length: 2, dtype: Float64\n\n >>> pd.array([\"a\", None, \"c\"])\n <StringArray>\n ['a', <NA>, 'c']\n Length: 3, dtype: string\n\n >>> pd.array([pd.Period('2000', freq=\"D\"), pd.Period(\"2000\", freq=\"D\")])\n <PeriodArray>\n ['2000-01-01', '2000-01-01']\n Length: 2, dtype: period[D]\n\n You can use the string alias for `dtype`\n\n >>> pd.array(['a', 'b', 'a'], dtype='category')\n ['a', 'b', 'a']\n Categories (2, object): ['a', 'b']\n\n Or specify the actual dtype\n\n >>> pd.array(['a', 'b', 'a'],\n ... dtype=pd.CategoricalDtype(['a', 'b', 'c'], ordered=True))\n ['a', 'b', 'a']\n Categories (3, object): ['a' < 'b' < 'c']\n\n If pandas does not infer a dedicated extension type a\n :class:`arrays.PandasArray` is returned.\n\n >>> pd.array([1 + 1j, 3 + 2j])\n <PandasArray>\n [(1+1j), (3+2j)]\n Length: 2, dtype: complex128\n\n As mentioned in the \"Notes\" section, new extension types may be added\n in the future (by pandas or 3rd party libraries), causing the return\n value to no longer be a :class:`arrays.PandasArray`. Specify the `dtype`\n as a NumPy dtype if you need to ensure there's no future change in\n behavior.\n\n >>> pd.array([1, 2], dtype=np.dtype(\"int32\"))\n <PandasArray>\n [1, 2]\n Length: 2, dtype: int32\n\n `data` must be 1-dimensional. A ValueError is raised when the input\n has the wrong dimensionality.\n\n >>> pd.array(1)\n Traceback (most recent call last):\n ...\n ValueError: Cannot pass scalar '1' to 'pandas.array'.\n \"\"\"\n from pandas.core.arrays import (\n BooleanArray,\n DatetimeArray,\n FloatingArray,\n IntegerArray,\n IntervalArray,\n PandasArray,\n StringArray,\n TimedeltaArray,\n period_array,\n )\n\n if lib.is_scalar(data):\n msg = f\"Cannot pass scalar '{data}' to 'pandas.array'.\"\n raise ValueError(msg)\n\n if dtype is None and isinstance(\n data, (ABCSeries, ABCIndexClass, ABCExtensionArray)\n ):\n dtype = data.dtype\n\n data = extract_array(data, extract_numpy=True)\n\n # this returns None for not-found dtypes.\n if isinstance(dtype, str):\n dtype = registry.find(dtype) or dtype\n\n if is_extension_array_dtype(dtype):\n cls = cast(ExtensionDtype, dtype).construct_array_type()\n return cls._from_sequence(data, dtype=dtype, copy=copy)\n\n if dtype is None:\n inferred_dtype = lib.infer_dtype(data, skipna=True)\n if inferred_dtype == \"period\":\n try:\n return period_array(data, copy=copy)\n except IncompatibleFrequency:\n # We may have a mixture of frequencies.\n # We choose to return an ndarray, rather than raising.\n pass\n elif inferred_dtype == \"interval\":\n try:\n return IntervalArray(data, copy=copy)\n except ValueError:\n # We may have a mixture of `closed` here.\n # We choose to return an ndarray, rather than raising.\n pass\n\n elif inferred_dtype.startswith(\"datetime\"):\n # datetime, datetime64\n try:\n return DatetimeArray._from_sequence(data, copy=copy)\n except ValueError:\n # Mixture of timezones, fall back to PandasArray\n pass\n\n elif inferred_dtype.startswith(\"timedelta\"):\n # timedelta, timedelta64\n return TimedeltaArray._from_sequence(data, copy=copy)\n\n elif inferred_dtype == \"string\":\n return StringArray._from_sequence(data, copy=copy)\n\n elif inferred_dtype == \"integer\":\n return IntegerArray._from_sequence(data, copy=copy)\n\n elif inferred_dtype in (\"floating\", \"mixed-integer-float\"):\n return FloatingArray._from_sequence(data, copy=copy)\n\n elif inferred_dtype == \"boolean\":\n return BooleanArray._from_sequence(data, copy=copy)\n\n # Pandas overrides NumPy for\n # 1. datetime64[ns]\n # 2. timedelta64[ns]\n # so that a DatetimeArray is returned.\n if is_datetime64_ns_dtype(dtype):\n return DatetimeArray._from_sequence(data, dtype=dtype, copy=copy)\n elif is_timedelta64_ns_dtype(dtype):\n return TimedeltaArray._from_sequence(data, dtype=dtype, copy=copy)\n\n result = PandasArray._from_sequence(data, dtype=dtype, copy=copy)\n return result\n\n\ndef extract_array(obj: AnyArrayLike, extract_numpy: bool = False) -> ArrayLike:\n \"\"\"\n Extract the ndarray or ExtensionArray from a Series or Index.\n\n For all other types, `obj` is just returned as is.\n\n Parameters\n ----------\n obj : object\n For Series / Index, the underlying ExtensionArray is unboxed.\n For Numpy-backed ExtensionArrays, the ndarray is extracted.\n\n extract_numpy : bool, default False\n Whether to extract the ndarray from a PandasArray\n\n Returns\n -------\n arr : object\n\n Examples\n --------\n >>> extract_array(pd.Series(['a', 'b', 'c'], dtype='category'))\n ['a', 'b', 'c']\n Categories (3, object): ['a', 'b', 'c']\n\n Other objects like lists, arrays, and DataFrames are just passed through.\n\n >>> extract_array([1, 2, 3])\n [1, 2, 3]\n\n For an ndarray-backed Series / Index a PandasArray is returned.\n\n >>> extract_array(pd.Series([1, 2, 3]))\n <PandasArray>\n [1, 2, 3]\n Length: 3, dtype: int64\n\n To extract all the way down to the ndarray, pass ``extract_numpy=True``.\n\n >>> extract_array(pd.Series([1, 2, 3]), extract_numpy=True)\n array([1, 2, 3])\n \"\"\"\n if isinstance(obj, (ABCIndexClass, ABCSeries)):\n obj = obj.array\n\n if extract_numpy and isinstance(obj, ABCPandasArray):\n obj = obj.to_numpy()\n\n # error: Incompatible return value type (got \"Index\", expected \"ExtensionArray\")\n # error: Incompatible return value type (got \"Series\", expected \"ExtensionArray\")\n return obj # type: ignore[return-value]\n\n\ndef sanitize_array(\n data,\n index: Optional[Index],\n dtype: Optional[DtypeObj] = None,\n copy: bool = False,\n raise_cast_failure: bool = False,\n) -> ArrayLike:\n \"\"\"\n Sanitize input data to an ndarray or ExtensionArray, copy if specified,\n coerce to the dtype if specified.\n \"\"\"\n\n if isinstance(data, ma.MaskedArray):\n mask = ma.getmaskarray(data)\n if mask.any():\n data, fill_value = maybe_upcast(data, copy=True)\n data.soften_mask() # set hardmask False if it was True\n data[mask] = fill_value\n else:\n data = data.copy()\n\n # extract ndarray or ExtensionArray, ensure we have no PandasArray\n data = extract_array(data, extract_numpy=True)\n\n # GH#846\n if isinstance(data, np.ndarray):\n\n if dtype is not None and is_float_dtype(data.dtype) and is_integer_dtype(dtype):\n # possibility of nan -> garbage\n try:\n subarr = _try_cast(data, dtype, copy, True)\n except ValueError:\n if copy:\n subarr = data.copy()\n else:\n subarr = np.array(data, copy=False)\n else:\n # we will try to copy be-definition here\n subarr = _try_cast(data, dtype, copy, raise_cast_failure)\n\n elif isinstance(data, ABCExtensionArray):\n # it is already ensured above this is not a PandasArray\n subarr = data\n\n if dtype is not None:\n subarr = subarr.astype(dtype, copy=copy)\n elif copy:\n subarr = subarr.copy()\n return subarr\n\n elif isinstance(data, (list, tuple, abc.Set, abc.ValuesView)) and len(data) > 0:\n if isinstance(data, set):\n # Raise only for unordered sets, e.g., not for dict_keys\n raise TypeError(\"Set type is unordered\")\n data = list(data)\n\n if dtype is not None:\n subarr = _try_cast(data, dtype, copy, raise_cast_failure)\n else:\n subarr = maybe_convert_platform(data)\n\n subarr = maybe_cast_to_datetime(subarr, dtype)\n\n elif isinstance(data, range):\n # GH#16804\n arr = np.arange(data.start, data.stop, data.step, dtype=\"int64\")\n subarr = _try_cast(arr, dtype, copy, raise_cast_failure)\n elif lib.is_scalar(data) and index is not None and dtype is not None:\n data = maybe_cast_to_datetime(data, dtype)\n if not lib.is_scalar(data):\n data = data[0]\n subarr = construct_1d_arraylike_from_scalar(data, len(index), dtype)\n else:\n subarr = _try_cast(data, dtype, copy, raise_cast_failure)\n\n # scalar like, GH\n if getattr(subarr, \"ndim\", 0) == 0:\n if isinstance(data, list): # pragma: no cover\n subarr = np.array(data, dtype=object)\n elif index is not None:\n value = data\n\n # figure out the dtype from the value (upcast if necessary)\n if dtype is None:\n dtype, value = infer_dtype_from_scalar(value, pandas_dtype=True)\n else:\n # need to possibly convert the value here\n value = maybe_cast_to_datetime(value, dtype)\n\n subarr = construct_1d_arraylike_from_scalar(value, len(index), dtype)\n\n else:\n return subarr.item()\n\n # the result that we want\n elif subarr.ndim == 1:\n if index is not None:\n\n # a 1-element ndarray\n if len(subarr) != len(index) and len(subarr) == 1:\n subarr = construct_1d_arraylike_from_scalar(\n subarr[0], len(index), subarr.dtype\n )\n\n elif subarr.ndim > 1:\n if isinstance(data, np.ndarray):\n raise ValueError(\"Data must be 1-dimensional\")\n else:\n subarr = com.asarray_tuplesafe(data, dtype=dtype)\n\n if not (is_extension_array_dtype(subarr.dtype) or is_extension_array_dtype(dtype)):\n # This is to prevent mixed-type Series getting all casted to\n # NumPy string type, e.g. NaN --> '-1#IND'.\n if issubclass(subarr.dtype.type, str):\n # GH#16605\n # If not empty convert the data to dtype\n # GH#19853: If data is a scalar, subarr has already the result\n if not lib.is_scalar(data):\n if not np.all(isna(data)):\n data = np.array(data, dtype=dtype, copy=False)\n subarr = np.array(data, dtype=object, copy=copy)\n\n is_object_or_str_dtype = is_object_dtype(dtype) or is_string_dtype(dtype)\n if is_object_dtype(subarr.dtype) and not is_object_or_str_dtype:\n inferred = lib.infer_dtype(subarr, skipna=False)\n if inferred in {\"interval\", \"period\"}:\n subarr = array(subarr)\n\n return subarr\n\n\ndef _try_cast(arr, dtype: Optional[DtypeObj], copy: bool, raise_cast_failure: bool):\n \"\"\"\n Convert input to numpy ndarray and optionally cast to a given dtype.\n\n Parameters\n ----------\n arr : ndarray, scalar, list, tuple, iterator (catchall)\n Excludes: ExtensionArray, Series, Index.\n dtype : np.dtype, ExtensionDtype or None\n copy : bool\n If False, don't copy the data if not needed.\n raise_cast_failure : bool\n If True, and if a dtype is specified, raise errors during casting.\n Otherwise an object array is returned.\n \"\"\"\n # perf shortcut as this is the most common case\n if isinstance(arr, np.ndarray):\n if maybe_castable(arr) and not copy and dtype is None:\n return arr\n\n if isinstance(dtype, ExtensionDtype) and (dtype.kind != \"M\" or is_sparse(dtype)):\n # create an extension array from its dtype\n # DatetimeTZ case needs to go through maybe_cast_to_datetime but\n # SparseDtype does not\n array_type = dtype.construct_array_type()._from_sequence\n subarr = array_type(arr, dtype=dtype, copy=copy)\n return subarr\n\n try:\n # GH#15832: Check if we are requesting a numeric dtype and\n # that we can convert the data to the requested dtype.\n if is_integer_dtype(dtype):\n # this will raise if we have e.g. floats\n maybe_cast_to_integer_array(arr, dtype)\n subarr = arr\n else:\n subarr = maybe_cast_to_datetime(arr, dtype)\n\n # Take care in creating object arrays (but iterators are not\n # supported):\n if is_object_dtype(dtype) and (\n is_list_like(subarr)\n and not (is_iterator(subarr) or isinstance(subarr, np.ndarray))\n ):\n subarr = construct_1d_object_array_from_listlike(subarr)\n elif not is_extension_array_dtype(subarr):\n subarr = construct_1d_ndarray_preserving_na(subarr, dtype, copy=copy)\n except OutOfBoundsDatetime:\n # in case of out of bound datetime64 -> always raise\n raise\n except (ValueError, TypeError):\n if dtype is not None and raise_cast_failure:\n raise\n else:\n subarr = np.array(arr, dtype=object, copy=copy)\n return subarr\n\n\ndef is_empty_data(data: Any) -> bool:\n \"\"\"\n Utility to check if a Series is instantiated with empty data,\n which does not contain dtype information.\n\n Parameters\n ----------\n data : array-like, Iterable, dict, or scalar value\n Contains data stored in Series.\n\n Returns\n -------\n bool\n \"\"\"\n is_none = data is None\n is_list_like_without_dtype = is_list_like(data) and not hasattr(data, \"dtype\")\n is_simple_empty = is_list_like_without_dtype and not data\n return is_none or is_simple_empty\n\n\ndef create_series_with_explicit_dtype(\n data: Any = None,\n index: Optional[Union[ArrayLike, Index]] = None,\n dtype: Optional[Dtype] = None,\n name: Optional[str] = None,\n copy: bool = False,\n fastpath: bool = False,\n dtype_if_empty: Dtype = object,\n) -> Series:\n \"\"\"\n Helper to pass an explicit dtype when instantiating an empty Series.\n\n This silences a DeprecationWarning described in GitHub-17261.\n\n Parameters\n ----------\n data : Mirrored from Series.__init__\n index : Mirrored from Series.__init__\n dtype : Mirrored from Series.__init__\n name : Mirrored from Series.__init__\n copy : Mirrored from Series.__init__\n fastpath : Mirrored from Series.__init__\n dtype_if_empty : str, numpy.dtype, or ExtensionDtype\n This dtype will be passed explicitly if an empty Series will\n be instantiated.\n\n Returns\n -------\n Series\n \"\"\"\n from pandas.core.series import Series\n\n if is_empty_data(data) and dtype is None:\n dtype = dtype_if_empty\n return Series(\n data=data, index=index, dtype=dtype, name=name, copy=copy, fastpath=fastpath\n )\n", "import numpy as np\nimport pytest\n\nimport pandas as pd\nfrom pandas import DataFrame, lreshape, melt, wide_to_long\nimport pandas._testing as tm\n\n\nclass TestMelt:\n def setup_method(self, method):\n self.df = tm.makeTimeDataFrame()[:10]\n self.df[\"id1\"] = (self.df[\"A\"] > 0).astype(np.int64)\n self.df[\"id2\"] = (self.df[\"B\"] > 0).astype(np.int64)\n\n self.var_name = \"var\"\n self.value_name = \"val\"\n\n self.df1 = pd.DataFrame(\n [\n [1.067683, -1.110463, 0.20867],\n [-1.321405, 0.368915, -1.055342],\n [-0.807333, 0.08298, -0.873361],\n ]\n )\n self.df1.columns = [list(\"ABC\"), list(\"abc\")]\n self.df1.columns.names = [\"CAP\", \"low\"]\n\n def test_top_level_method(self):\n result = melt(self.df)\n assert result.columns.tolist() == [\"variable\", \"value\"]\n\n def test_method_signatures(self):\n tm.assert_frame_equal(self.df.melt(), melt(self.df))\n\n tm.assert_frame_equal(\n self.df.melt(id_vars=[\"id1\", \"id2\"], value_vars=[\"A\", \"B\"]),\n melt(self.df, id_vars=[\"id1\", \"id2\"], value_vars=[\"A\", \"B\"]),\n )\n\n tm.assert_frame_equal(\n self.df.melt(var_name=self.var_name, value_name=self.value_name),\n melt(self.df, var_name=self.var_name, value_name=self.value_name),\n )\n\n tm.assert_frame_equal(self.df1.melt(col_level=0), melt(self.df1, col_level=0))\n\n def test_default_col_names(self):\n result = self.df.melt()\n assert result.columns.tolist() == [\"variable\", \"value\"]\n\n result1 = self.df.melt(id_vars=[\"id1\"])\n assert result1.columns.tolist() == [\"id1\", \"variable\", \"value\"]\n\n result2 = self.df.melt(id_vars=[\"id1\", \"id2\"])\n assert result2.columns.tolist() == [\"id1\", \"id2\", \"variable\", \"value\"]\n\n def test_value_vars(self):\n result3 = self.df.melt(id_vars=[\"id1\", \"id2\"], value_vars=\"A\")\n assert len(result3) == 10\n\n result4 = self.df.melt(id_vars=[\"id1\", \"id2\"], value_vars=[\"A\", \"B\"])\n expected4 = DataFrame(\n {\n \"id1\": self.df[\"id1\"].tolist() * 2,\n \"id2\": self.df[\"id2\"].tolist() * 2,\n \"variable\": [\"A\"] * 10 + [\"B\"] * 10,\n \"value\": (self.df[\"A\"].tolist() + self.df[\"B\"].tolist()),\n },\n columns=[\"id1\", \"id2\", \"variable\", \"value\"],\n )\n tm.assert_frame_equal(result4, expected4)\n\n def test_value_vars_types(self):\n # GH 15348\n expected = DataFrame(\n {\n \"id1\": self.df[\"id1\"].tolist() * 2,\n \"id2\": self.df[\"id2\"].tolist() * 2,\n \"variable\": [\"A\"] * 10 + [\"B\"] * 10,\n \"value\": (self.df[\"A\"].tolist() + self.df[\"B\"].tolist()),\n },\n columns=[\"id1\", \"id2\", \"variable\", \"value\"],\n )\n\n for type_ in (tuple, list, np.array):\n result = self.df.melt(id_vars=[\"id1\", \"id2\"], value_vars=type_((\"A\", \"B\")))\n tm.assert_frame_equal(result, expected)\n\n def test_vars_work_with_multiindex(self):\n expected = DataFrame(\n {\n (\"A\", \"a\"): self.df1[(\"A\", \"a\")],\n \"CAP\": [\"B\"] * len(self.df1),\n \"low\": [\"b\"] * len(self.df1),\n \"value\": self.df1[(\"B\", \"b\")],\n },\n columns=[(\"A\", \"a\"), \"CAP\", \"low\", \"value\"],\n )\n\n result = self.df1.melt(id_vars=[(\"A\", \"a\")], value_vars=[(\"B\", \"b\")])\n tm.assert_frame_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"id_vars, value_vars, col_level, expected\",\n [\n (\n [\"A\"],\n [\"B\"],\n 0,\n DataFrame(\n {\n \"A\": {0: 1.067683, 1: -1.321405, 2: -0.807333},\n \"CAP\": {0: \"B\", 1: \"B\", 2: \"B\"},\n \"value\": {0: -1.110463, 1: 0.368915, 2: 0.08298},\n }\n ),\n ),\n (\n [\"a\"],\n [\"b\"],\n 1,\n DataFrame(\n {\n \"a\": {0: 1.067683, 1: -1.321405, 2: -0.807333},\n \"low\": {0: \"b\", 1: \"b\", 2: \"b\"},\n \"value\": {0: -1.110463, 1: 0.368915, 2: 0.08298},\n }\n ),\n ),\n ],\n )\n def test_single_vars_work_with_multiindex(\n self, id_vars, value_vars, col_level, expected\n ):\n result = self.df1.melt(id_vars, value_vars, col_level=col_level)\n tm.assert_frame_equal(result, expected)\n\n def test_tuple_vars_fail_with_multiindex(self):\n # melt should fail with an informative error message if\n # the columns have a MultiIndex and a tuple is passed\n # for id_vars or value_vars.\n tuple_a = (\"A\", \"a\")\n list_a = [tuple_a]\n tuple_b = (\"B\", \"b\")\n list_b = [tuple_b]\n\n msg = r\"(id|value)_vars must be a list of tuples when columns are a MultiIndex\"\n for id_vars, value_vars in (\n (tuple_a, list_b),\n (list_a, tuple_b),\n (tuple_a, tuple_b),\n ):\n with pytest.raises(ValueError, match=msg):\n self.df1.melt(id_vars=id_vars, value_vars=value_vars)\n\n def test_custom_var_name(self):\n result5 = self.df.melt(var_name=self.var_name)\n assert result5.columns.tolist() == [\"var\", \"value\"]\n\n result6 = self.df.melt(id_vars=[\"id1\"], var_name=self.var_name)\n assert result6.columns.tolist() == [\"id1\", \"var\", \"value\"]\n\n result7 = self.df.melt(id_vars=[\"id1\", \"id2\"], var_name=self.var_name)\n assert result7.columns.tolist() == [\"id1\", \"id2\", \"var\", \"value\"]\n\n result8 = self.df.melt(\n id_vars=[\"id1\", \"id2\"], value_vars=\"A\", var_name=self.var_name\n )\n assert result8.columns.tolist() == [\"id1\", \"id2\", \"var\", \"value\"]\n\n result9 = self.df.melt(\n id_vars=[\"id1\", \"id2\"], value_vars=[\"A\", \"B\"], var_name=self.var_name\n )\n expected9 = DataFrame(\n {\n \"id1\": self.df[\"id1\"].tolist() * 2,\n \"id2\": self.df[\"id2\"].tolist() * 2,\n self.var_name: [\"A\"] * 10 + [\"B\"] * 10,\n \"value\": (self.df[\"A\"].tolist() + self.df[\"B\"].tolist()),\n },\n columns=[\"id1\", \"id2\", self.var_name, \"value\"],\n )\n tm.assert_frame_equal(result9, expected9)\n\n def test_custom_value_name(self):\n result10 = self.df.melt(value_name=self.value_name)\n assert result10.columns.tolist() == [\"variable\", \"val\"]\n\n result11 = self.df.melt(id_vars=[\"id1\"], value_name=self.value_name)\n assert result11.columns.tolist() == [\"id1\", \"variable\", \"val\"]\n\n result12 = self.df.melt(id_vars=[\"id1\", \"id2\"], value_name=self.value_name)\n assert result12.columns.tolist() == [\"id1\", \"id2\", \"variable\", \"val\"]\n\n result13 = self.df.melt(\n id_vars=[\"id1\", \"id2\"], value_vars=\"A\", value_name=self.value_name\n )\n assert result13.columns.tolist() == [\"id1\", \"id2\", \"variable\", \"val\"]\n\n result14 = self.df.melt(\n id_vars=[\"id1\", \"id2\"], value_vars=[\"A\", \"B\"], value_name=self.value_name\n )\n expected14 = DataFrame(\n {\n \"id1\": self.df[\"id1\"].tolist() * 2,\n \"id2\": self.df[\"id2\"].tolist() * 2,\n \"variable\": [\"A\"] * 10 + [\"B\"] * 10,\n self.value_name: (self.df[\"A\"].tolist() + self.df[\"B\"].tolist()),\n },\n columns=[\"id1\", \"id2\", \"variable\", self.value_name],\n )\n tm.assert_frame_equal(result14, expected14)\n\n def test_custom_var_and_value_name(self):\n\n result15 = self.df.melt(var_name=self.var_name, value_name=self.value_name)\n assert result15.columns.tolist() == [\"var\", \"val\"]\n\n result16 = self.df.melt(\n id_vars=[\"id1\"], var_name=self.var_name, value_name=self.value_name\n )\n assert result16.columns.tolist() == [\"id1\", \"var\", \"val\"]\n\n result17 = self.df.melt(\n id_vars=[\"id1\", \"id2\"], var_name=self.var_name, value_name=self.value_name\n )\n assert result17.columns.tolist() == [\"id1\", \"id2\", \"var\", \"val\"]\n\n result18 = self.df.melt(\n id_vars=[\"id1\", \"id2\"],\n value_vars=\"A\",\n var_name=self.var_name,\n value_name=self.value_name,\n )\n assert result18.columns.tolist() == [\"id1\", \"id2\", \"var\", \"val\"]\n\n result19 = self.df.melt(\n id_vars=[\"id1\", \"id2\"],\n value_vars=[\"A\", \"B\"],\n var_name=self.var_name,\n value_name=self.value_name,\n )\n expected19 = DataFrame(\n {\n \"id1\": self.df[\"id1\"].tolist() * 2,\n \"id2\": self.df[\"id2\"].tolist() * 2,\n self.var_name: [\"A\"] * 10 + [\"B\"] * 10,\n self.value_name: (self.df[\"A\"].tolist() + self.df[\"B\"].tolist()),\n },\n columns=[\"id1\", \"id2\", self.var_name, self.value_name],\n )\n tm.assert_frame_equal(result19, expected19)\n\n df20 = self.df.copy()\n df20.columns.name = \"foo\"\n result20 = df20.melt()\n assert result20.columns.tolist() == [\"foo\", \"value\"]\n\n def test_col_level(self):\n res1 = self.df1.melt(col_level=0)\n res2 = self.df1.melt(col_level=\"CAP\")\n assert res1.columns.tolist() == [\"CAP\", \"value\"]\n assert res2.columns.tolist() == [\"CAP\", \"value\"]\n\n def test_multiindex(self):\n res = self.df1.melt()\n assert res.columns.tolist() == [\"CAP\", \"low\", \"value\"]\n\n @pytest.mark.parametrize(\n \"col\",\n [\n pd.Series(pd.date_range(\"2010\", periods=5, tz=\"US/Pacific\")),\n pd.Series([\"a\", \"b\", \"c\", \"a\", \"d\"], dtype=\"category\"),\n pd.Series([0, 1, 0, 0, 0]),\n ],\n )\n def test_pandas_dtypes(self, col):\n # GH 15785\n df = DataFrame(\n {\"klass\": range(5), \"col\": col, \"attr1\": [1, 0, 0, 0, 0], \"attr2\": col}\n )\n expected_value = pd.concat([pd.Series([1, 0, 0, 0, 0]), col], ignore_index=True)\n result = melt(\n df, id_vars=[\"klass\", \"col\"], var_name=\"attribute\", value_name=\"value\"\n )\n expected = DataFrame(\n {\n 0: list(range(5)) * 2,\n 1: pd.concat([col] * 2, ignore_index=True),\n 2: [\"attr1\"] * 5 + [\"attr2\"] * 5,\n 3: expected_value,\n }\n )\n expected.columns = [\"klass\", \"col\", \"attribute\", \"value\"]\n tm.assert_frame_equal(result, expected)\n\n def test_preserve_category(self):\n # GH 15853\n data = DataFrame({\"A\": [1, 2], \"B\": pd.Categorical([\"X\", \"Y\"])})\n result = pd.melt(data, [\"B\"], [\"A\"])\n expected = DataFrame(\n {\"B\": pd.Categorical([\"X\", \"Y\"]), \"variable\": [\"A\", \"A\"], \"value\": [1, 2]}\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_melt_missing_columns_raises(self):\n # GH-23575\n # This test is to ensure that pandas raises an error if melting is\n # attempted with column names absent from the dataframe\n\n # Generate data\n df = pd.DataFrame(np.random.randn(5, 4), columns=list(\"abcd\"))\n\n # Try to melt with missing `value_vars` column name\n msg = \"The following '{Var}' are not present in the DataFrame: {Col}\"\n with pytest.raises(\n KeyError, match=msg.format(Var=\"value_vars\", Col=\"\\\\['C'\\\\]\")\n ):\n df.melt([\"a\", \"b\"], [\"C\", \"d\"])\n\n # Try to melt with missing `id_vars` column name\n with pytest.raises(KeyError, match=msg.format(Var=\"id_vars\", Col=\"\\\\['A'\\\\]\")):\n df.melt([\"A\", \"b\"], [\"c\", \"d\"])\n\n # Multiple missing\n with pytest.raises(\n KeyError,\n match=msg.format(Var=\"id_vars\", Col=\"\\\\['not_here', 'or_there'\\\\]\"),\n ):\n df.melt([\"a\", \"b\", \"not_here\", \"or_there\"], [\"c\", \"d\"])\n\n # Multiindex melt fails if column is missing from multilevel melt\n multi = df.copy()\n multi.columns = [list(\"ABCD\"), list(\"abcd\")]\n with pytest.raises(KeyError, match=msg.format(Var=\"id_vars\", Col=\"\\\\['E'\\\\]\")):\n multi.melt([(\"E\", \"a\")], [(\"B\", \"b\")])\n # Multiindex fails if column is missing from single level melt\n with pytest.raises(\n KeyError, match=msg.format(Var=\"value_vars\", Col=\"\\\\['F'\\\\]\")\n ):\n multi.melt([\"A\"], [\"F\"], col_level=0)\n\n def test_melt_mixed_int_str_id_vars(self):\n # GH 29718\n df = DataFrame({0: [\"foo\"], \"a\": [\"bar\"], \"b\": [1], \"d\": [2]})\n result = melt(df, id_vars=[0, \"a\"], value_vars=[\"b\", \"d\"])\n expected = DataFrame(\n {0: [\"foo\"] * 2, \"a\": [\"bar\"] * 2, \"variable\": list(\"bd\"), \"value\": [1, 2]}\n )\n tm.assert_frame_equal(result, expected)\n\n def test_melt_mixed_int_str_value_vars(self):\n # GH 29718\n df = DataFrame({0: [\"foo\"], \"a\": [\"bar\"]})\n result = melt(df, value_vars=[0, \"a\"])\n expected = DataFrame({\"variable\": [0, \"a\"], \"value\": [\"foo\", \"bar\"]})\n tm.assert_frame_equal(result, expected)\n\n def test_ignore_index(self):\n # GH 17440\n df = DataFrame({\"foo\": [0], \"bar\": [1]}, index=[\"first\"])\n result = melt(df, ignore_index=False)\n expected = DataFrame(\n {\"variable\": [\"foo\", \"bar\"], \"value\": [0, 1]}, index=[\"first\", \"first\"]\n )\n tm.assert_frame_equal(result, expected)\n\n def test_ignore_multiindex(self):\n # GH 17440\n index = pd.MultiIndex.from_tuples(\n [(\"first\", \"second\"), (\"first\", \"third\")], names=[\"baz\", \"foobar\"]\n )\n df = DataFrame({\"foo\": [0, 1], \"bar\": [2, 3]}, index=index)\n result = melt(df, ignore_index=False)\n\n expected_index = pd.MultiIndex.from_tuples(\n [(\"first\", \"second\"), (\"first\", \"third\")] * 2, names=[\"baz\", \"foobar\"]\n )\n expected = DataFrame(\n {\"variable\": [\"foo\"] * 2 + [\"bar\"] * 2, \"value\": [0, 1, 2, 3]},\n index=expected_index,\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_ignore_index_name_and_type(self):\n # GH 17440\n index = pd.Index([\"foo\", \"bar\"], dtype=\"category\", name=\"baz\")\n df = DataFrame({\"x\": [0, 1], \"y\": [2, 3]}, index=index)\n result = melt(df, ignore_index=False)\n\n expected_index = pd.Index([\"foo\", \"bar\"] * 2, dtype=\"category\", name=\"baz\")\n expected = DataFrame(\n {\"variable\": [\"x\", \"x\", \"y\", \"y\"], \"value\": [0, 1, 2, 3]},\n index=expected_index,\n )\n\n tm.assert_frame_equal(result, expected)\n\n\nclass TestLreshape:\n def test_pairs(self):\n data = {\n \"birthdt\": [\n \"08jan2009\",\n \"20dec2008\",\n \"30dec2008\",\n \"21dec2008\",\n \"11jan2009\",\n ],\n \"birthwt\": [1766, 3301, 1454, 3139, 4133],\n \"id\": [101, 102, 103, 104, 105],\n \"sex\": [\"Male\", \"Female\", \"Female\", \"Female\", \"Female\"],\n \"visitdt1\": [\n \"11jan2009\",\n \"22dec2008\",\n \"04jan2009\",\n \"29dec2008\",\n \"20jan2009\",\n ],\n \"visitdt2\": [\"21jan2009\", np.nan, \"22jan2009\", \"31dec2008\", \"03feb2009\"],\n \"visitdt3\": [\"05feb2009\", np.nan, np.nan, \"02jan2009\", \"15feb2009\"],\n \"wt1\": [1823, 3338, 1549, 3298, 4306],\n \"wt2\": [2011.0, np.nan, 1892.0, 3338.0, 4575.0],\n \"wt3\": [2293.0, np.nan, np.nan, 3377.0, 4805.0],\n }\n\n df = DataFrame(data)\n\n spec = {\n \"visitdt\": [f\"visitdt{i:d}\" for i in range(1, 4)],\n \"wt\": [f\"wt{i:d}\" for i in range(1, 4)],\n }\n result = lreshape(df, spec)\n\n exp_data = {\n \"birthdt\": [\n \"08jan2009\",\n \"20dec2008\",\n \"30dec2008\",\n \"21dec2008\",\n \"11jan2009\",\n \"08jan2009\",\n \"30dec2008\",\n \"21dec2008\",\n \"11jan2009\",\n \"08jan2009\",\n \"21dec2008\",\n \"11jan2009\",\n ],\n \"birthwt\": [\n 1766,\n 3301,\n 1454,\n 3139,\n 4133,\n 1766,\n 1454,\n 3139,\n 4133,\n 1766,\n 3139,\n 4133,\n ],\n \"id\": [101, 102, 103, 104, 105, 101, 103, 104, 105, 101, 104, 105],\n \"sex\": [\n \"Male\",\n \"Female\",\n \"Female\",\n \"Female\",\n \"Female\",\n \"Male\",\n \"Female\",\n \"Female\",\n \"Female\",\n \"Male\",\n \"Female\",\n \"Female\",\n ],\n \"visitdt\": [\n \"11jan2009\",\n \"22dec2008\",\n \"04jan2009\",\n \"29dec2008\",\n \"20jan2009\",\n \"21jan2009\",\n \"22jan2009\",\n \"31dec2008\",\n \"03feb2009\",\n \"05feb2009\",\n \"02jan2009\",\n \"15feb2009\",\n ],\n \"wt\": [\n 1823.0,\n 3338.0,\n 1549.0,\n 3298.0,\n 4306.0,\n 2011.0,\n 1892.0,\n 3338.0,\n 4575.0,\n 2293.0,\n 3377.0,\n 4805.0,\n ],\n }\n exp = DataFrame(exp_data, columns=result.columns)\n tm.assert_frame_equal(result, exp)\n\n result = lreshape(df, spec, dropna=False)\n exp_data = {\n \"birthdt\": [\n \"08jan2009\",\n \"20dec2008\",\n \"30dec2008\",\n \"21dec2008\",\n \"11jan2009\",\n \"08jan2009\",\n \"20dec2008\",\n \"30dec2008\",\n \"21dec2008\",\n \"11jan2009\",\n \"08jan2009\",\n \"20dec2008\",\n \"30dec2008\",\n \"21dec2008\",\n \"11jan2009\",\n ],\n \"birthwt\": [\n 1766,\n 3301,\n 1454,\n 3139,\n 4133,\n 1766,\n 3301,\n 1454,\n 3139,\n 4133,\n 1766,\n 3301,\n 1454,\n 3139,\n 4133,\n ],\n \"id\": [\n 101,\n 102,\n 103,\n 104,\n 105,\n 101,\n 102,\n 103,\n 104,\n 105,\n 101,\n 102,\n 103,\n 104,\n 105,\n ],\n \"sex\": [\n \"Male\",\n \"Female\",\n \"Female\",\n \"Female\",\n \"Female\",\n \"Male\",\n \"Female\",\n \"Female\",\n \"Female\",\n \"Female\",\n \"Male\",\n \"Female\",\n \"Female\",\n \"Female\",\n \"Female\",\n ],\n \"visitdt\": [\n \"11jan2009\",\n \"22dec2008\",\n \"04jan2009\",\n \"29dec2008\",\n \"20jan2009\",\n \"21jan2009\",\n np.nan,\n \"22jan2009\",\n \"31dec2008\",\n \"03feb2009\",\n \"05feb2009\",\n np.nan,\n np.nan,\n \"02jan2009\",\n \"15feb2009\",\n ],\n \"wt\": [\n 1823.0,\n 3338.0,\n 1549.0,\n 3298.0,\n 4306.0,\n 2011.0,\n np.nan,\n 1892.0,\n 3338.0,\n 4575.0,\n 2293.0,\n np.nan,\n np.nan,\n 3377.0,\n 4805.0,\n ],\n }\n exp = DataFrame(exp_data, columns=result.columns)\n tm.assert_frame_equal(result, exp)\n\n with tm.assert_produces_warning(FutureWarning):\n result = lreshape(df, spec, dropna=False, label=\"foo\")\n\n spec = {\n \"visitdt\": [f\"visitdt{i:d}\" for i in range(1, 3)],\n \"wt\": [f\"wt{i:d}\" for i in range(1, 4)],\n }\n msg = \"All column lists must be same length\"\n with pytest.raises(ValueError, match=msg):\n lreshape(df, spec)\n\n\nclass TestWideToLong:\n def test_simple(self):\n np.random.seed(123)\n x = np.random.randn(3)\n df = pd.DataFrame(\n {\n \"A1970\": {0: \"a\", 1: \"b\", 2: \"c\"},\n \"A1980\": {0: \"d\", 1: \"e\", 2: \"f\"},\n \"B1970\": {0: 2.5, 1: 1.2, 2: 0.7},\n \"B1980\": {0: 3.2, 1: 1.3, 2: 0.1},\n \"X\": dict(zip(range(3), x)),\n }\n )\n df[\"id\"] = df.index\n exp_data = {\n \"X\": x.tolist() + x.tolist(),\n \"A\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"],\n \"B\": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1],\n \"year\": [1970, 1970, 1970, 1980, 1980, 1980],\n \"id\": [0, 1, 2, 0, 1, 2],\n }\n expected = DataFrame(exp_data)\n expected = expected.set_index([\"id\", \"year\"])[[\"X\", \"A\", \"B\"]]\n result = wide_to_long(df, [\"A\", \"B\"], i=\"id\", j=\"year\")\n tm.assert_frame_equal(result, expected)\n\n def test_stubs(self):\n # GH9204\n df = pd.DataFrame([[0, 1, 2, 3, 8], [4, 5, 6, 7, 9]])\n df.columns = [\"id\", \"inc1\", \"inc2\", \"edu1\", \"edu2\"]\n stubs = [\"inc\", \"edu\"]\n\n # TODO: unused?\n df_long = pd.wide_to_long(df, stubs, i=\"id\", j=\"age\") # noqa\n\n assert stubs == [\"inc\", \"edu\"]\n\n def test_separating_character(self):\n # GH14779\n np.random.seed(123)\n x = np.random.randn(3)\n df = pd.DataFrame(\n {\n \"A.1970\": {0: \"a\", 1: \"b\", 2: \"c\"},\n \"A.1980\": {0: \"d\", 1: \"e\", 2: \"f\"},\n \"B.1970\": {0: 2.5, 1: 1.2, 2: 0.7},\n \"B.1980\": {0: 3.2, 1: 1.3, 2: 0.1},\n \"X\": dict(zip(range(3), x)),\n }\n )\n df[\"id\"] = df.index\n exp_data = {\n \"X\": x.tolist() + x.tolist(),\n \"A\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"],\n \"B\": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1],\n \"year\": [1970, 1970, 1970, 1980, 1980, 1980],\n \"id\": [0, 1, 2, 0, 1, 2],\n }\n expected = DataFrame(exp_data)\n expected = expected.set_index([\"id\", \"year\"])[[\"X\", \"A\", \"B\"]]\n result = wide_to_long(df, [\"A\", \"B\"], i=\"id\", j=\"year\", sep=\".\")\n tm.assert_frame_equal(result, expected)\n\n def test_escapable_characters(self):\n np.random.seed(123)\n x = np.random.randn(3)\n df = pd.DataFrame(\n {\n \"A(quarterly)1970\": {0: \"a\", 1: \"b\", 2: \"c\"},\n \"A(quarterly)1980\": {0: \"d\", 1: \"e\", 2: \"f\"},\n \"B(quarterly)1970\": {0: 2.5, 1: 1.2, 2: 0.7},\n \"B(quarterly)1980\": {0: 3.2, 1: 1.3, 2: 0.1},\n \"X\": dict(zip(range(3), x)),\n }\n )\n df[\"id\"] = df.index\n exp_data = {\n \"X\": x.tolist() + x.tolist(),\n \"A(quarterly)\": [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"],\n \"B(quarterly)\": [2.5, 1.2, 0.7, 3.2, 1.3, 0.1],\n \"year\": [1970, 1970, 1970, 1980, 1980, 1980],\n \"id\": [0, 1, 2, 0, 1, 2],\n }\n expected = DataFrame(exp_data)\n expected = expected.set_index([\"id\", \"year\"])[\n [\"X\", \"A(quarterly)\", \"B(quarterly)\"]\n ]\n result = wide_to_long(df, [\"A(quarterly)\", \"B(quarterly)\"], i=\"id\", j=\"year\")\n tm.assert_frame_equal(result, expected)\n\n def test_unbalanced(self):\n # test that we can have a varying amount of time variables\n df = pd.DataFrame(\n {\n \"A2010\": [1.0, 2.0],\n \"A2011\": [3.0, 4.0],\n \"B2010\": [5.0, 6.0],\n \"X\": [\"X1\", \"X2\"],\n }\n )\n df[\"id\"] = df.index\n exp_data = {\n \"X\": [\"X1\", \"X1\", \"X2\", \"X2\"],\n \"A\": [1.0, 3.0, 2.0, 4.0],\n \"B\": [5.0, np.nan, 6.0, np.nan],\n \"id\": [0, 0, 1, 1],\n \"year\": [2010, 2011, 2010, 2011],\n }\n expected = pd.DataFrame(exp_data)\n expected = expected.set_index([\"id\", \"year\"])[[\"X\", \"A\", \"B\"]]\n result = wide_to_long(df, [\"A\", \"B\"], i=\"id\", j=\"year\")\n tm.assert_frame_equal(result, expected)\n\n def test_character_overlap(self):\n # Test we handle overlapping characters in both id_vars and value_vars\n df = pd.DataFrame(\n {\n \"A11\": [\"a11\", \"a22\", \"a33\"],\n \"A12\": [\"a21\", \"a22\", \"a23\"],\n \"B11\": [\"b11\", \"b12\", \"b13\"],\n \"B12\": [\"b21\", \"b22\", \"b23\"],\n \"BB11\": [1, 2, 3],\n \"BB12\": [4, 5, 6],\n \"BBBX\": [91, 92, 93],\n \"BBBZ\": [91, 92, 93],\n }\n )\n df[\"id\"] = df.index\n expected = pd.DataFrame(\n {\n \"BBBX\": [91, 92, 93, 91, 92, 93],\n \"BBBZ\": [91, 92, 93, 91, 92, 93],\n \"A\": [\"a11\", \"a22\", \"a33\", \"a21\", \"a22\", \"a23\"],\n \"B\": [\"b11\", \"b12\", \"b13\", \"b21\", \"b22\", \"b23\"],\n \"BB\": [1, 2, 3, 4, 5, 6],\n \"id\": [0, 1, 2, 0, 1, 2],\n \"year\": [11, 11, 11, 12, 12, 12],\n }\n )\n expected = expected.set_index([\"id\", \"year\"])[[\"BBBX\", \"BBBZ\", \"A\", \"B\", \"BB\"]]\n result = wide_to_long(df, [\"A\", \"B\", \"BB\"], i=\"id\", j=\"year\")\n tm.assert_frame_equal(result.sort_index(axis=1), expected.sort_index(axis=1))\n\n def test_invalid_separator(self):\n # if an invalid separator is supplied a empty data frame is returned\n sep = \"nope!\"\n df = pd.DataFrame(\n {\n \"A2010\": [1.0, 2.0],\n \"A2011\": [3.0, 4.0],\n \"B2010\": [5.0, 6.0],\n \"X\": [\"X1\", \"X2\"],\n }\n )\n df[\"id\"] = df.index\n exp_data = {\n \"X\": \"\",\n \"A2010\": [],\n \"A2011\": [],\n \"B2010\": [],\n \"id\": [],\n \"year\": [],\n \"A\": [],\n \"B\": [],\n }\n expected = pd.DataFrame(exp_data).astype({\"year\": \"int\"})\n expected = expected.set_index([\"id\", \"year\"])[\n [\"X\", \"A2010\", \"A2011\", \"B2010\", \"A\", \"B\"]\n ]\n expected.index = expected.index.set_levels([0, 1], level=0)\n result = wide_to_long(df, [\"A\", \"B\"], i=\"id\", j=\"year\", sep=sep)\n tm.assert_frame_equal(result.sort_index(axis=1), expected.sort_index(axis=1))\n\n def test_num_string_disambiguation(self):\n # Test that we can disambiguate number value_vars from\n # string value_vars\n df = pd.DataFrame(\n {\n \"A11\": [\"a11\", \"a22\", \"a33\"],\n \"A12\": [\"a21\", \"a22\", \"a23\"],\n \"B11\": [\"b11\", \"b12\", \"b13\"],\n \"B12\": [\"b21\", \"b22\", \"b23\"],\n \"BB11\": [1, 2, 3],\n \"BB12\": [4, 5, 6],\n \"Arating\": [91, 92, 93],\n \"Arating_old\": [91, 92, 93],\n }\n )\n df[\"id\"] = df.index\n expected = pd.DataFrame(\n {\n \"Arating\": [91, 92, 93, 91, 92, 93],\n \"Arating_old\": [91, 92, 93, 91, 92, 93],\n \"A\": [\"a11\", \"a22\", \"a33\", \"a21\", \"a22\", \"a23\"],\n \"B\": [\"b11\", \"b12\", \"b13\", \"b21\", \"b22\", \"b23\"],\n \"BB\": [1, 2, 3, 4, 5, 6],\n \"id\": [0, 1, 2, 0, 1, 2],\n \"year\": [11, 11, 11, 12, 12, 12],\n }\n )\n expected = expected.set_index([\"id\", \"year\"])[\n [\"Arating\", \"Arating_old\", \"A\", \"B\", \"BB\"]\n ]\n result = wide_to_long(df, [\"A\", \"B\", \"BB\"], i=\"id\", j=\"year\")\n tm.assert_frame_equal(result.sort_index(axis=1), expected.sort_index(axis=1))\n\n def test_invalid_suffixtype(self):\n # If all stubs names end with a string, but a numeric suffix is\n # assumed, an empty data frame is returned\n df = pd.DataFrame(\n {\n \"Aone\": [1.0, 2.0],\n \"Atwo\": [3.0, 4.0],\n \"Bone\": [5.0, 6.0],\n \"X\": [\"X1\", \"X2\"],\n }\n )\n df[\"id\"] = df.index\n exp_data = {\n \"X\": \"\",\n \"Aone\": [],\n \"Atwo\": [],\n \"Bone\": [],\n \"id\": [],\n \"year\": [],\n \"A\": [],\n \"B\": [],\n }\n expected = pd.DataFrame(exp_data).astype({\"year\": \"int\"})\n\n expected = expected.set_index([\"id\", \"year\"])\n expected.index = expected.index.set_levels([0, 1], level=0)\n result = wide_to_long(df, [\"A\", \"B\"], i=\"id\", j=\"year\")\n tm.assert_frame_equal(result.sort_index(axis=1), expected.sort_index(axis=1))\n\n def test_multiple_id_columns(self):\n # Taken from http://www.ats.ucla.edu/stat/stata/modules/reshapel.htm\n df = pd.DataFrame(\n {\n \"famid\": [1, 1, 1, 2, 2, 2, 3, 3, 3],\n \"birth\": [1, 2, 3, 1, 2, 3, 1, 2, 3],\n \"ht1\": [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],\n \"ht2\": [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9],\n }\n )\n expected = pd.DataFrame(\n {\n \"ht\": [\n 2.8,\n 3.4,\n 2.9,\n 3.8,\n 2.2,\n 2.9,\n 2.0,\n 3.2,\n 1.8,\n 2.8,\n 1.9,\n 2.4,\n 2.2,\n 3.3,\n 2.3,\n 3.4,\n 2.1,\n 2.9,\n ],\n \"famid\": [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3],\n \"birth\": [1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3, 1, 1, 2, 2, 3, 3],\n \"age\": [1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2],\n }\n )\n expected = expected.set_index([\"famid\", \"birth\", \"age\"])[[\"ht\"]]\n result = wide_to_long(df, \"ht\", i=[\"famid\", \"birth\"], j=\"age\")\n tm.assert_frame_equal(result, expected)\n\n def test_non_unique_idvars(self):\n # GH16382\n # Raise an error message if non unique id vars (i) are passed\n df = pd.DataFrame(\n {\"A_A1\": [1, 2, 3, 4, 5], \"B_B1\": [1, 2, 3, 4, 5], \"x\": [1, 1, 1, 1, 1]}\n )\n msg = \"the id variables need to uniquely identify each row\"\n with pytest.raises(ValueError, match=msg):\n wide_to_long(df, [\"A_A\", \"B_B\"], i=\"x\", j=\"colname\")\n\n def test_cast_j_int(self):\n df = pd.DataFrame(\n {\n \"actor_1\": [\"CCH Pounder\", \"Johnny Depp\", \"Christoph Waltz\"],\n \"actor_2\": [\"Joel David Moore\", \"Orlando Bloom\", \"Rory Kinnear\"],\n \"actor_fb_likes_1\": [1000.0, 40000.0, 11000.0],\n \"actor_fb_likes_2\": [936.0, 5000.0, 393.0],\n \"title\": [\"Avatar\", \"Pirates of the Caribbean\", \"Spectre\"],\n }\n )\n\n expected = pd.DataFrame(\n {\n \"actor\": [\n \"CCH Pounder\",\n \"Johnny Depp\",\n \"Christoph Waltz\",\n \"Joel David Moore\",\n \"Orlando Bloom\",\n \"Rory Kinnear\",\n ],\n \"actor_fb_likes\": [1000.0, 40000.0, 11000.0, 936.0, 5000.0, 393.0],\n \"num\": [1, 1, 1, 2, 2, 2],\n \"title\": [\n \"Avatar\",\n \"Pirates of the Caribbean\",\n \"Spectre\",\n \"Avatar\",\n \"Pirates of the Caribbean\",\n \"Spectre\",\n ],\n }\n ).set_index([\"title\", \"num\"])\n result = wide_to_long(\n df, [\"actor\", \"actor_fb_likes\"], i=\"title\", j=\"num\", sep=\"_\"\n )\n\n tm.assert_frame_equal(result, expected)\n\n def test_identical_stubnames(self):\n df = pd.DataFrame(\n {\n \"A2010\": [1.0, 2.0],\n \"A2011\": [3.0, 4.0],\n \"B2010\": [5.0, 6.0],\n \"A\": [\"X1\", \"X2\"],\n }\n )\n msg = \"stubname can't be identical to a column name\"\n with pytest.raises(ValueError, match=msg):\n wide_to_long(df, [\"A\", \"B\"], i=\"A\", j=\"colname\")\n\n def test_nonnumeric_suffix(self):\n df = pd.DataFrame(\n {\n \"treatment_placebo\": [1.0, 2.0],\n \"treatment_test\": [3.0, 4.0],\n \"result_placebo\": [5.0, 6.0],\n \"A\": [\"X1\", \"X2\"],\n }\n )\n expected = pd.DataFrame(\n {\n \"A\": [\"X1\", \"X1\", \"X2\", \"X2\"],\n \"colname\": [\"placebo\", \"test\", \"placebo\", \"test\"],\n \"result\": [5.0, np.nan, 6.0, np.nan],\n \"treatment\": [1.0, 3.0, 2.0, 4.0],\n }\n )\n expected = expected.set_index([\"A\", \"colname\"])\n result = wide_to_long(\n df, [\"result\", \"treatment\"], i=\"A\", j=\"colname\", suffix=\"[a-z]+\", sep=\"_\"\n )\n tm.assert_frame_equal(result, expected)\n\n def test_mixed_type_suffix(self):\n df = pd.DataFrame(\n {\n \"A\": [\"X1\", \"X2\"],\n \"result_1\": [0, 9],\n \"result_foo\": [5.0, 6.0],\n \"treatment_1\": [1.0, 2.0],\n \"treatment_foo\": [3.0, 4.0],\n }\n )\n expected = pd.DataFrame(\n {\n \"A\": [\"X1\", \"X2\", \"X1\", \"X2\"],\n \"colname\": [\"1\", \"1\", \"foo\", \"foo\"],\n \"result\": [0.0, 9.0, 5.0, 6.0],\n \"treatment\": [1.0, 2.0, 3.0, 4.0],\n }\n ).set_index([\"A\", \"colname\"])\n result = wide_to_long(\n df, [\"result\", \"treatment\"], i=\"A\", j=\"colname\", suffix=\".+\", sep=\"_\"\n )\n tm.assert_frame_equal(result, expected)\n\n def test_float_suffix(self):\n df = pd.DataFrame(\n {\n \"treatment_1.1\": [1.0, 2.0],\n \"treatment_2.1\": [3.0, 4.0],\n \"result_1.2\": [5.0, 6.0],\n \"result_1\": [0, 9],\n \"A\": [\"X1\", \"X2\"],\n }\n )\n expected = pd.DataFrame(\n {\n \"A\": [\"X1\", \"X1\", \"X1\", \"X1\", \"X2\", \"X2\", \"X2\", \"X2\"],\n \"colname\": [1, 1.1, 1.2, 2.1, 1, 1.1, 1.2, 2.1],\n \"result\": [0.0, np.nan, 5.0, np.nan, 9.0, np.nan, 6.0, np.nan],\n \"treatment\": [np.nan, 1.0, np.nan, 3.0, np.nan, 2.0, np.nan, 4.0],\n }\n )\n expected = expected.set_index([\"A\", \"colname\"])\n result = wide_to_long(\n df, [\"result\", \"treatment\"], i=\"A\", j=\"colname\", suffix=\"[0-9.]+\", sep=\"_\"\n )\n tm.assert_frame_equal(result, expected)\n\n def test_col_substring_of_stubname(self):\n # GH22468\n # Don't raise ValueError when a column name is a substring\n # of a stubname that's been passed as a string\n wide_data = {\n \"node_id\": {0: 0, 1: 1, 2: 2, 3: 3, 4: 4},\n \"A\": {0: 0.80, 1: 0.0, 2: 0.25, 3: 1.0, 4: 0.81},\n \"PA0\": {0: 0.74, 1: 0.56, 2: 0.56, 3: 0.98, 4: 0.6},\n \"PA1\": {0: 0.77, 1: 0.64, 2: 0.52, 3: 0.98, 4: 0.67},\n \"PA3\": {0: 0.34, 1: 0.70, 2: 0.52, 3: 0.98, 4: 0.67},\n }\n wide_df = pd.DataFrame.from_dict(wide_data)\n expected = pd.wide_to_long(\n wide_df, stubnames=[\"PA\"], i=[\"node_id\", \"A\"], j=\"time\"\n )\n result = pd.wide_to_long(wide_df, stubnames=\"PA\", i=[\"node_id\", \"A\"], j=\"time\")\n tm.assert_frame_equal(result, expected)\n\n def test_warn_of_column_name_value(self):\n # GH34731\n # raise a warning if the resultant value column name matches\n # a name in the dataframe already (default name is \"value\")\n df = pd.DataFrame({\"col\": list(\"ABC\"), \"value\": range(10, 16, 2)})\n expected = pd.DataFrame(\n [[\"A\", \"col\", \"A\"], [\"B\", \"col\", \"B\"], [\"C\", \"col\", \"C\"]],\n columns=[\"value\", \"variable\", \"value\"],\n )\n\n with tm.assert_produces_warning(FutureWarning):\n result = df.melt(id_vars=\"value\")\n tm.assert_frame_equal(result, expected)\n", "import re\n\nimport numpy as np\nimport pytest\n\nimport pandas as pd\nimport pandas._testing as tm\n\n\nclass TestSeriesReplace:\n def test_replace(self, datetime_series):\n N = 100\n ser = pd.Series(np.random.randn(N))\n ser[0:4] = np.nan\n ser[6:10] = 0\n\n # replace list with a single value\n return_value = ser.replace([np.nan], -1, inplace=True)\n assert return_value is None\n\n exp = ser.fillna(-1)\n tm.assert_series_equal(ser, exp)\n\n rs = ser.replace(0.0, np.nan)\n ser[ser == 0.0] = np.nan\n tm.assert_series_equal(rs, ser)\n\n ser = pd.Series(np.fabs(np.random.randn(N)), tm.makeDateIndex(N), dtype=object)\n ser[:5] = np.nan\n ser[6:10] = \"foo\"\n ser[20:30] = \"bar\"\n\n # replace list with a single value\n rs = ser.replace([np.nan, \"foo\", \"bar\"], -1)\n\n assert (rs[:5] == -1).all()\n assert (rs[6:10] == -1).all()\n assert (rs[20:30] == -1).all()\n assert (pd.isna(ser[:5])).all()\n\n # replace with different values\n rs = ser.replace({np.nan: -1, \"foo\": -2, \"bar\": -3})\n\n assert (rs[:5] == -1).all()\n assert (rs[6:10] == -2).all()\n assert (rs[20:30] == -3).all()\n assert (pd.isna(ser[:5])).all()\n\n # replace with different values with 2 lists\n rs2 = ser.replace([np.nan, \"foo\", \"bar\"], [-1, -2, -3])\n tm.assert_series_equal(rs, rs2)\n\n # replace inplace\n return_value = ser.replace([np.nan, \"foo\", \"bar\"], -1, inplace=True)\n assert return_value is None\n\n assert (ser[:5] == -1).all()\n assert (ser[6:10] == -1).all()\n assert (ser[20:30] == -1).all()\n\n ser = pd.Series([np.nan, 0, np.inf])\n tm.assert_series_equal(ser.replace(np.nan, 0), ser.fillna(0))\n\n ser = pd.Series([np.nan, 0, \"foo\", \"bar\", np.inf, None, pd.NaT])\n tm.assert_series_equal(ser.replace(np.nan, 0), ser.fillna(0))\n filled = ser.copy()\n filled[4] = 0\n tm.assert_series_equal(ser.replace(np.inf, 0), filled)\n\n ser = pd.Series(datetime_series.index)\n tm.assert_series_equal(ser.replace(np.nan, 0), ser.fillna(0))\n\n # malformed\n msg = r\"Replacement lists must match in length\\. Expecting 3 got 2\"\n with pytest.raises(ValueError, match=msg):\n ser.replace([1, 2, 3], [np.nan, 0])\n\n # make sure that we aren't just masking a TypeError because bools don't\n # implement indexing\n with pytest.raises(TypeError, match=\"Cannot compare types .+\"):\n ser.replace([1, 2], [np.nan, 0])\n\n ser = pd.Series([0, 1, 2, 3, 4])\n result = ser.replace([0, 1, 2, 3, 4], [4, 3, 2, 1, 0])\n tm.assert_series_equal(result, pd.Series([4, 3, 2, 1, 0]))\n\n def test_replace_gh5319(self):\n # API change from 0.12?\n # GH 5319\n ser = pd.Series([0, np.nan, 2, 3, 4])\n expected = ser.ffill()\n result = ser.replace([np.nan])\n tm.assert_series_equal(result, expected)\n\n ser = pd.Series([0, np.nan, 2, 3, 4])\n expected = ser.ffill()\n result = ser.replace(np.nan)\n tm.assert_series_equal(result, expected)\n # GH 5797\n ser = pd.Series(pd.date_range(\"20130101\", periods=5))\n expected = ser.copy()\n expected.loc[2] = pd.Timestamp(\"20120101\")\n result = ser.replace({pd.Timestamp(\"20130103\"): pd.Timestamp(\"20120101\")})\n tm.assert_series_equal(result, expected)\n result = ser.replace(pd.Timestamp(\"20130103\"), pd.Timestamp(\"20120101\"))\n tm.assert_series_equal(result, expected)\n\n # GH 11792: Test with replacing NaT in a list with tz data\n ts = pd.Timestamp(\"2015/01/01\", tz=\"UTC\")\n s = pd.Series([pd.NaT, pd.Timestamp(\"2015/01/01\", tz=\"UTC\")])\n result = s.replace([np.nan, pd.NaT], pd.Timestamp.min)\n expected = pd.Series([pd.Timestamp.min, ts], dtype=object)\n tm.assert_series_equal(expected, result)\n\n def test_replace_timedelta_td64(self):\n tdi = pd.timedelta_range(0, periods=5)\n ser = pd.Series(tdi)\n\n # Using a single dict argument means we go through replace_list\n result = ser.replace({ser[1]: ser[3]})\n\n expected = pd.Series([ser[0], ser[3], ser[2], ser[3], ser[4]])\n tm.assert_series_equal(result, expected)\n\n def test_replace_with_single_list(self):\n ser = pd.Series([0, 1, 2, 3, 4])\n result = ser.replace([1, 2, 3])\n tm.assert_series_equal(result, pd.Series([0, 0, 0, 0, 4]))\n\n s = ser.copy()\n return_value = s.replace([1, 2, 3], inplace=True)\n assert return_value is None\n tm.assert_series_equal(s, pd.Series([0, 0, 0, 0, 4]))\n\n # make sure things don't get corrupted when fillna call fails\n s = ser.copy()\n msg = (\n r\"Invalid fill method\\. Expecting pad \\(ffill\\) or backfill \"\n r\"\\(bfill\\)\\. Got crash_cymbal\"\n )\n with pytest.raises(ValueError, match=msg):\n return_value = s.replace([1, 2, 3], inplace=True, method=\"crash_cymbal\")\n assert return_value is None\n tm.assert_series_equal(s, ser)\n\n def test_replace_with_empty_list(self):\n # GH 21977\n s = pd.Series([[1], [2, 3], [], np.nan, [4]])\n expected = s\n result = s.replace([], np.nan)\n tm.assert_series_equal(result, expected)\n\n # GH 19266\n with pytest.raises(ValueError, match=\"cannot assign mismatch\"):\n s.replace({np.nan: []})\n with pytest.raises(ValueError, match=\"cannot assign mismatch\"):\n s.replace({np.nan: [\"dummy\", \"alt\"]})\n\n def test_replace_mixed_types(self):\n s = pd.Series(np.arange(5), dtype=\"int64\")\n\n def check_replace(to_rep, val, expected):\n sc = s.copy()\n r = s.replace(to_rep, val)\n return_value = sc.replace(to_rep, val, inplace=True)\n assert return_value is None\n tm.assert_series_equal(expected, r)\n tm.assert_series_equal(expected, sc)\n\n # MUST upcast to float\n e = pd.Series([0.0, 1.0, 2.0, 3.0, 4.0])\n tr, v = [3], [3.0]\n check_replace(tr, v, e)\n\n # MUST upcast to float\n e = pd.Series([0, 1, 2, 3.5, 4])\n tr, v = [3], [3.5]\n check_replace(tr, v, e)\n\n # casts to object\n e = pd.Series([0, 1, 2, 3.5, \"a\"])\n tr, v = [3, 4], [3.5, \"a\"]\n check_replace(tr, v, e)\n\n # again casts to object\n e = pd.Series([0, 1, 2, 3.5, pd.Timestamp(\"20130101\")])\n tr, v = [3, 4], [3.5, pd.Timestamp(\"20130101\")]\n check_replace(tr, v, e)\n\n # casts to object\n e = pd.Series([0, 1, 2, 3.5, True], dtype=\"object\")\n tr, v = [3, 4], [3.5, True]\n check_replace(tr, v, e)\n\n # test an object with dates + floats + integers + strings\n dr = pd.Series(pd.date_range(\"1/1/2001\", \"1/10/2001\", freq=\"D\"))\n result = dr.astype(object).replace([dr[0], dr[1], dr[2]], [1.0, 2, \"a\"])\n expected = pd.Series([1.0, 2, \"a\"] + dr[3:].tolist(), dtype=object)\n tm.assert_series_equal(result, expected)\n\n def test_replace_bool_with_string_no_op(self):\n s = pd.Series([True, False, True])\n result = s.replace(\"fun\", \"in-the-sun\")\n tm.assert_series_equal(s, result)\n\n def test_replace_bool_with_string(self):\n # nonexistent elements\n s = pd.Series([True, False, True])\n result = s.replace(True, \"2u\")\n expected = pd.Series([\"2u\", False, \"2u\"])\n tm.assert_series_equal(expected, result)\n\n def test_replace_bool_with_bool(self):\n s = pd.Series([True, False, True])\n result = s.replace(True, False)\n expected = pd.Series([False] * len(s))\n tm.assert_series_equal(expected, result)\n\n def test_replace_with_dict_with_bool_keys(self):\n s = pd.Series([True, False, True])\n result = s.replace({\"asdf\": \"asdb\", True: \"yes\"})\n expected = pd.Series([\"yes\", False, \"yes\"])\n tm.assert_series_equal(result, expected)\n\n def test_replace2(self):\n N = 100\n ser = pd.Series(np.fabs(np.random.randn(N)), tm.makeDateIndex(N), dtype=object)\n ser[:5] = np.nan\n ser[6:10] = \"foo\"\n ser[20:30] = \"bar\"\n\n # replace list with a single value\n rs = ser.replace([np.nan, \"foo\", \"bar\"], -1)\n\n assert (rs[:5] == -1).all()\n assert (rs[6:10] == -1).all()\n assert (rs[20:30] == -1).all()\n assert (pd.isna(ser[:5])).all()\n\n # replace with different values\n rs = ser.replace({np.nan: -1, \"foo\": -2, \"bar\": -3})\n\n assert (rs[:5] == -1).all()\n assert (rs[6:10] == -2).all()\n assert (rs[20:30] == -3).all()\n assert (pd.isna(ser[:5])).all()\n\n # replace with different values with 2 lists\n rs2 = ser.replace([np.nan, \"foo\", \"bar\"], [-1, -2, -3])\n tm.assert_series_equal(rs, rs2)\n\n # replace inplace\n return_value = ser.replace([np.nan, \"foo\", \"bar\"], -1, inplace=True)\n assert return_value is None\n assert (ser[:5] == -1).all()\n assert (ser[6:10] == -1).all()\n assert (ser[20:30] == -1).all()\n\n def test_replace_with_dictlike_and_string_dtype(self):\n # GH 32621\n s = pd.Series([\"one\", \"two\", np.nan], dtype=\"string\")\n expected = pd.Series([\"1\", \"2\", np.nan])\n result = s.replace({\"one\": \"1\", \"two\": \"2\"})\n tm.assert_series_equal(expected, result)\n\n def test_replace_with_empty_dictlike(self):\n # GH 15289\n s = pd.Series(list(\"abcd\"))\n tm.assert_series_equal(s, s.replace(dict()))\n\n with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False):\n empty_series = pd.Series([])\n tm.assert_series_equal(s, s.replace(empty_series))\n\n def test_replace_string_with_number(self):\n # GH 15743\n s = pd.Series([1, 2, 3])\n result = s.replace(\"2\", np.nan)\n expected = pd.Series([1, 2, 3])\n tm.assert_series_equal(expected, result)\n\n def test_replace_replacer_equals_replacement(self):\n # GH 20656\n # make sure all replacers are matching against original values\n s = pd.Series([\"a\", \"b\"])\n expected = pd.Series([\"b\", \"a\"])\n result = s.replace({\"a\": \"b\", \"b\": \"a\"})\n tm.assert_series_equal(expected, result)\n\n def test_replace_unicode_with_number(self):\n # GH 15743\n s = pd.Series([1, 2, 3])\n result = s.replace(\"2\", np.nan)\n expected = pd.Series([1, 2, 3])\n tm.assert_series_equal(expected, result)\n\n def test_replace_mixed_types_with_string(self):\n # Testing mixed\n s = pd.Series([1, 2, 3, \"4\", 4, 5])\n result = s.replace([2, \"4\"], np.nan)\n expected = pd.Series([1, np.nan, 3, np.nan, 4, 5])\n tm.assert_series_equal(expected, result)\n\n @pytest.mark.parametrize(\n \"categorical, numeric\",\n [\n (pd.Categorical(\"A\", categories=[\"A\", \"B\"]), [1]),\n (pd.Categorical((\"A\",), categories=[\"A\", \"B\"]), [1]),\n (pd.Categorical((\"A\", \"B\"), categories=[\"A\", \"B\"]), [1, 2]),\n ],\n )\n def test_replace_categorical(self, categorical, numeric):\n # GH 24971\n # Do not check if dtypes are equal due to a known issue that\n # Categorical.replace sometimes coerces to object (GH 23305)\n s = pd.Series(categorical)\n result = s.replace({\"A\": 1, \"B\": 2})\n expected = pd.Series(numeric)\n tm.assert_series_equal(expected, result)\n\n def test_replace_categorical_single(self):\n # GH 26988\n dti = pd.date_range(\"2016-01-01\", periods=3, tz=\"US/Pacific\")\n s = pd.Series(dti)\n c = s.astype(\"category\")\n\n expected = c.copy()\n expected = expected.cat.add_categories(\"foo\")\n expected[2] = \"foo\"\n expected = expected.cat.remove_unused_categories()\n assert c[2] != \"foo\"\n\n result = c.replace(c[2], \"foo\")\n tm.assert_series_equal(expected, result)\n assert c[2] != \"foo\" # ensure non-inplace call does not alter original\n\n return_value = c.replace(c[2], \"foo\", inplace=True)\n assert return_value is None\n tm.assert_series_equal(expected, c)\n\n first_value = c[0]\n return_value = c.replace(c[1], c[0], inplace=True)\n assert return_value is None\n assert c[0] == c[1] == first_value # test replacing with existing value\n\n def test_replace_with_no_overflowerror(self):\n # GH 25616\n # casts to object without Exception from OverflowError\n s = pd.Series([0, 1, 2, 3, 4])\n result = s.replace([3], [\"100000000000000000000\"])\n expected = pd.Series([0, 1, 2, \"100000000000000000000\", 4])\n tm.assert_series_equal(result, expected)\n\n s = pd.Series([0, \"100000000000000000000\", \"100000000000000000001\"])\n result = s.replace([\"100000000000000000000\"], [1])\n expected = pd.Series([0, 1, \"100000000000000000001\"])\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"ser, to_replace, exp\",\n [\n ([1, 2, 3], {1: 2, 2: 3, 3: 4}, [2, 3, 4]),\n ([\"1\", \"2\", \"3\"], {\"1\": \"2\", \"2\": \"3\", \"3\": \"4\"}, [\"2\", \"3\", \"4\"]),\n ],\n )\n def test_replace_commutative(self, ser, to_replace, exp):\n # GH 16051\n # DataFrame.replace() overwrites when values are non-numeric\n\n series = pd.Series(ser)\n\n expected = pd.Series(exp)\n result = series.replace(to_replace)\n\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"ser, exp\", [([1, 2, 3], [1, True, 3]), ([\"x\", 2, 3], [\"x\", True, 3])]\n )\n def test_replace_no_cast(self, ser, exp):\n # GH 9113\n # BUG: replace int64 dtype with bool coerces to int64\n\n series = pd.Series(ser)\n result = series.replace(2, True)\n expected = pd.Series(exp)\n\n tm.assert_series_equal(result, expected)\n\n def test_replace_invalid_to_replace(self):\n # GH 18634\n # API: replace() should raise an exception if invalid argument is given\n series = pd.Series([\"a\", \"b\", \"c \"])\n msg = (\n r\"Expecting 'to_replace' to be either a scalar, array-like, \"\n r\"dict or None, got invalid type.*\"\n )\n with pytest.raises(TypeError, match=msg):\n series.replace(lambda x: x.strip())\n\n @pytest.mark.parametrize(\"frame\", [False, True])\n def test_replace_nonbool_regex(self, frame):\n obj = pd.Series([\"a\", \"b\", \"c \"])\n if frame:\n obj = obj.to_frame()\n\n msg = \"'to_replace' must be 'None' if 'regex' is not a bool\"\n with pytest.raises(ValueError, match=msg):\n obj.replace(to_replace=[\"a\"], regex=\"foo\")\n\n @pytest.mark.parametrize(\"frame\", [False, True])\n def test_replace_empty_copy(self, frame):\n obj = pd.Series([], dtype=np.float64)\n if frame:\n obj = obj.to_frame()\n\n res = obj.replace(4, 5, inplace=True)\n assert res is None\n\n res = obj.replace(4, 5, inplace=False)\n tm.assert_equal(res, obj)\n assert res is not obj\n\n def test_replace_only_one_dictlike_arg(self):\n # GH#33340\n\n ser = pd.Series([1, 2, \"A\", pd.Timestamp.now(), True])\n to_replace = {0: 1, 2: \"A\"}\n value = \"foo\"\n msg = \"Series.replace cannot use dict-like to_replace and non-None value\"\n with pytest.raises(ValueError, match=msg):\n ser.replace(to_replace, value)\n\n to_replace = 1\n value = {0: \"foo\", 2: \"bar\"}\n msg = \"Series.replace cannot use dict-value and non-None to_replace\"\n with pytest.raises(ValueError, match=msg):\n ser.replace(to_replace, value)\n\n def test_replace_extension_other(self):\n # https://github.com/pandas-dev/pandas/issues/34530\n ser = pd.Series(pd.array([1, 2, 3], dtype=\"Int64\"))\n ser.replace(\"\", \"\") # no exception\n\n def test_replace_with_compiled_regex(self):\n # https://github.com/pandas-dev/pandas/issues/35680\n s = pd.Series([\"a\", \"b\", \"c\"])\n regex = re.compile(\"^a$\")\n result = s.replace({regex: \"z\"}, regex=True)\n expected = pd.Series([\"z\", \"b\", \"c\"])\n tm.assert_series_equal(result, expected)\n\n @pytest.mark.parametrize(\"pattern\", [\"^.$\", \".\"])\n def test_str_replace_regex_default_raises_warning(self, pattern):\n # https://github.com/pandas-dev/pandas/pull/24809\n s = pd.Series([\"a\", \"b\", \"c\"])\n msg = r\"The default value of regex will change from True to False\"\n if len(pattern) == 1:\n msg += r\".*single character regular expressions.*not.*literal strings\"\n with tm.assert_produces_warning(FutureWarning, check_stacklevel=False) as w:\n s.str.replace(pattern, \"\")\n assert re.match(msg, str(w[0].message))\n", "import operator\n\nimport numpy as np\nimport pytest\n\nfrom pandas.core.dtypes.common import is_list_like\n\nimport pandas as pd\nfrom pandas import (\n Categorical,\n Index,\n Interval,\n IntervalIndex,\n Period,\n Series,\n Timedelta,\n Timestamp,\n date_range,\n period_range,\n timedelta_range,\n)\nimport pandas._testing as tm\nfrom pandas.core.arrays import IntervalArray\n\n\[email protected](\n params=[\n (Index([0, 2, 4, 4]), Index([1, 3, 5, 8])),\n (Index([0.0, 1.0, 2.0, np.nan]), Index([1.0, 2.0, 3.0, np.nan])),\n (\n timedelta_range(\"0 days\", periods=3).insert(4, pd.NaT),\n timedelta_range(\"1 day\", periods=3).insert(4, pd.NaT),\n ),\n (\n date_range(\"20170101\", periods=3).insert(4, pd.NaT),\n date_range(\"20170102\", periods=3).insert(4, pd.NaT),\n ),\n (\n date_range(\"20170101\", periods=3, tz=\"US/Eastern\").insert(4, pd.NaT),\n date_range(\"20170102\", periods=3, tz=\"US/Eastern\").insert(4, pd.NaT),\n ),\n ],\n ids=lambda x: str(x[0].dtype),\n)\ndef left_right_dtypes(request):\n \"\"\"\n Fixture for building an IntervalArray from various dtypes\n \"\"\"\n return request.param\n\n\[email protected]\ndef array(left_right_dtypes):\n \"\"\"\n Fixture to generate an IntervalArray of various dtypes containing NA if possible\n \"\"\"\n left, right = left_right_dtypes\n return IntervalArray.from_arrays(left, right)\n\n\ndef create_categorical_intervals(left, right, closed=\"right\"):\n return Categorical(IntervalIndex.from_arrays(left, right, closed))\n\n\ndef create_series_intervals(left, right, closed=\"right\"):\n return Series(IntervalArray.from_arrays(left, right, closed))\n\n\ndef create_series_categorical_intervals(left, right, closed=\"right\"):\n return Series(Categorical(IntervalIndex.from_arrays(left, right, closed)))\n\n\nclass TestComparison:\n @pytest.fixture(params=[operator.eq, operator.ne])\n def op(self, request):\n return request.param\n\n @pytest.fixture(\n params=[\n IntervalArray.from_arrays,\n IntervalIndex.from_arrays,\n create_categorical_intervals,\n create_series_intervals,\n create_series_categorical_intervals,\n ],\n ids=[\n \"IntervalArray\",\n \"IntervalIndex\",\n \"Categorical[Interval]\",\n \"Series[Interval]\",\n \"Series[Categorical[Interval]]\",\n ],\n )\n def interval_constructor(self, request):\n \"\"\"\n Fixture for all pandas native interval constructors.\n To be used as the LHS of IntervalArray comparisons.\n \"\"\"\n return request.param\n\n def elementwise_comparison(self, op, array, other):\n \"\"\"\n Helper that performs elementwise comparisons between `array` and `other`\n \"\"\"\n other = other if is_list_like(other) else [other] * len(array)\n expected = np.array([op(x, y) for x, y in zip(array, other)])\n if isinstance(other, Series):\n return Series(expected, index=other.index)\n return expected\n\n def test_compare_scalar_interval(self, op, array):\n # matches first interval\n other = array[0]\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n tm.assert_numpy_array_equal(result, expected)\n\n # matches on a single endpoint but not both\n other = Interval(array.left[0], array.right[1])\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_compare_scalar_interval_mixed_closed(self, op, closed, other_closed):\n array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)\n other = Interval(0, 1, closed=other_closed)\n\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_compare_scalar_na(self, op, array, nulls_fixture, request):\n result = op(array, nulls_fixture)\n expected = self.elementwise_comparison(op, array, nulls_fixture)\n\n if nulls_fixture is pd.NA and array.dtype != pd.IntervalDtype(\"int64\"):\n mark = pytest.mark.xfail(\n reason=\"broken for non-integer IntervalArray; see GH 31882\"\n )\n request.node.add_marker(mark)\n\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"other\",\n [\n 0,\n 1.0,\n True,\n \"foo\",\n Timestamp(\"2017-01-01\"),\n Timestamp(\"2017-01-01\", tz=\"US/Eastern\"),\n Timedelta(\"0 days\"),\n Period(\"2017-01-01\", \"D\"),\n ],\n )\n def test_compare_scalar_other(self, op, array, other):\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_compare_list_like_interval(self, op, array, interval_constructor):\n # same endpoints\n other = interval_constructor(array.left, array.right)\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n tm.assert_equal(result, expected)\n\n # different endpoints\n other = interval_constructor(array.left[::-1], array.right[::-1])\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n tm.assert_equal(result, expected)\n\n # all nan endpoints\n other = interval_constructor([np.nan] * 4, [np.nan] * 4)\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n tm.assert_equal(result, expected)\n\n def test_compare_list_like_interval_mixed_closed(\n self, op, interval_constructor, closed, other_closed\n ):\n array = IntervalArray.from_arrays(range(2), range(1, 3), closed=closed)\n other = interval_constructor(range(2), range(1, 3), closed=other_closed)\n\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n tm.assert_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"other\",\n [\n (\n Interval(0, 1),\n Interval(Timedelta(\"1 day\"), Timedelta(\"2 days\")),\n Interval(4, 5, \"both\"),\n Interval(10, 20, \"neither\"),\n ),\n (0, 1.5, Timestamp(\"20170103\"), np.nan),\n (\n Timestamp(\"20170102\", tz=\"US/Eastern\"),\n Timedelta(\"2 days\"),\n \"baz\",\n pd.NaT,\n ),\n ],\n )\n def test_compare_list_like_object(self, op, array, other):\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_compare_list_like_nan(self, op, array, nulls_fixture, request):\n other = [nulls_fixture] * 4\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n\n if nulls_fixture is pd.NA and array.dtype.subtype != \"i8\":\n reason = \"broken for non-integer IntervalArray; see GH 31882\"\n mark = pytest.mark.xfail(reason=reason)\n request.node.add_marker(mark)\n\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\n \"other\",\n [\n np.arange(4, dtype=\"int64\"),\n np.arange(4, dtype=\"float64\"),\n date_range(\"2017-01-01\", periods=4),\n date_range(\"2017-01-01\", periods=4, tz=\"US/Eastern\"),\n timedelta_range(\"0 days\", periods=4),\n period_range(\"2017-01-01\", periods=4, freq=\"D\"),\n Categorical(list(\"abab\")),\n Categorical(date_range(\"2017-01-01\", periods=4)),\n pd.array(list(\"abcd\")),\n pd.array([\"foo\", 3.14, None, object()]),\n ],\n ids=lambda x: str(x.dtype),\n )\n def test_compare_list_like_other(self, op, array, other):\n result = op(array, other)\n expected = self.elementwise_comparison(op, array, other)\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\"length\", [1, 3, 5])\n @pytest.mark.parametrize(\"other_constructor\", [IntervalArray, list])\n def test_compare_length_mismatch_errors(self, op, other_constructor, length):\n array = IntervalArray.from_arrays(range(4), range(1, 5))\n other = other_constructor([Interval(0, 1)] * length)\n with pytest.raises(ValueError, match=\"Lengths must match to compare\"):\n op(array, other)\n\n @pytest.mark.parametrize(\n \"constructor, expected_type, assert_func\",\n [\n (IntervalIndex, np.array, tm.assert_numpy_array_equal),\n (Series, Series, tm.assert_series_equal),\n ],\n )\n def test_index_series_compat(self, op, constructor, expected_type, assert_func):\n # IntervalIndex/Series that rely on IntervalArray for comparisons\n breaks = range(4)\n index = constructor(IntervalIndex.from_breaks(breaks))\n\n # scalar comparisons\n other = index[0]\n result = op(index, other)\n expected = expected_type(self.elementwise_comparison(op, index, other))\n assert_func(result, expected)\n\n other = breaks[0]\n result = op(index, other)\n expected = expected_type(self.elementwise_comparison(op, index, other))\n assert_func(result, expected)\n\n # list-like comparisons\n other = IntervalArray.from_breaks(breaks)\n result = op(index, other)\n expected = expected_type(self.elementwise_comparison(op, index, other))\n assert_func(result, expected)\n\n other = [index[0], breaks[0], \"foo\"]\n result = op(index, other)\n expected = expected_type(self.elementwise_comparison(op, index, other))\n assert_func(result, expected)\n\n @pytest.mark.parametrize(\"scalars\", [\"a\", False, 1, 1.0, None])\n def test_comparison_operations(self, scalars):\n # GH #28981\n expected = Series([False, False])\n s = pd.Series([pd.Interval(0, 1), pd.Interval(1, 2)], dtype=\"interval\")\n result = s == scalars\n tm.assert_series_equal(result, expected)\n", "import numpy as np\nfrom numpy.random import randn\nimport pytest\n\nfrom pandas import DataFrame, Series, concat\nimport pandas._testing as tm\nfrom pandas.tests.window.common import (\n moments_consistency_cov_data,\n moments_consistency_is_constant,\n moments_consistency_mock_mean,\n moments_consistency_series_data,\n moments_consistency_std_data,\n moments_consistency_var_data,\n moments_consistency_var_debiasing_factors,\n)\n\n\[email protected](\"func\", [\"cov\", \"corr\"])\ndef test_ewm_pairwise_cov_corr(func, frame):\n result = getattr(frame.ewm(span=10, min_periods=5), func)()\n result = result.loc[(slice(None), 1), 5]\n result.index = result.index.droplevel(1)\n expected = getattr(frame[1].ewm(span=10, min_periods=5), func)(frame[5])\n expected.index = expected.index._with_freq(None)\n tm.assert_series_equal(result, expected, check_names=False)\n\n\[email protected](\"name\", [\"cov\", \"corr\"])\ndef test_ewm_corr_cov(name, binary_ew_data):\n A, B = binary_ew_data\n\n result = getattr(A.ewm(com=20, min_periods=5), name)(B)\n assert np.isnan(result.values[:14]).all()\n assert not np.isnan(result.values[14:]).any()\n\n\[email protected](\"name\", [\"cov\", \"corr\"])\ndef test_ewm_corr_cov_min_periods(name, min_periods, binary_ew_data):\n # GH 7898\n A, B = binary_ew_data\n result = getattr(A.ewm(com=20, min_periods=min_periods), name)(B)\n # binary functions (ewmcov, ewmcorr) with bias=False require at\n # least two values\n assert np.isnan(result.values[:11]).all()\n assert not np.isnan(result.values[11:]).any()\n\n # check series of length 0\n empty = Series([], dtype=np.float64)\n result = getattr(empty.ewm(com=50, min_periods=min_periods), name)(empty)\n tm.assert_series_equal(result, empty)\n\n # check series of length 1\n result = getattr(Series([1.0]).ewm(com=50, min_periods=min_periods), name)(\n Series([1.0])\n )\n tm.assert_series_equal(result, Series([np.NaN]))\n\n\[email protected](\"name\", [\"cov\", \"corr\"])\ndef test_different_input_array_raise_exception(name, binary_ew_data):\n\n A, _ = binary_ew_data\n msg = \"Input arrays must be of the same type!\"\n # exception raised is Exception\n with pytest.raises(Exception, match=msg):\n getattr(A.ewm(com=20, min_periods=5), name)(randn(50))\n\n\[email protected]\[email protected](\"min_periods\", [0, 1, 2, 3, 4])\[email protected](\"adjust\", [True, False])\[email protected](\"ignore_na\", [True, False])\ndef test_ewm_consistency(consistency_data, min_periods, adjust, ignore_na):\n def _weights(s, com, adjust, ignore_na):\n if isinstance(s, DataFrame):\n if not len(s.columns):\n return DataFrame(index=s.index, columns=s.columns)\n w = concat(\n [\n _weights(s.iloc[:, i], com=com, adjust=adjust, ignore_na=ignore_na)\n for i, _ in enumerate(s.columns)\n ],\n axis=1,\n )\n w.index = s.index\n w.columns = s.columns\n return w\n\n w = Series(np.nan, index=s.index)\n alpha = 1.0 / (1.0 + com)\n if ignore_na:\n w[s.notna()] = _weights(\n s[s.notna()], com=com, adjust=adjust, ignore_na=False\n )\n elif adjust:\n for i in range(len(s)):\n if s.iat[i] == s.iat[i]:\n w.iat[i] = pow(1.0 / (1.0 - alpha), i)\n else:\n sum_wts = 0.0\n prev_i = -1\n for i in range(len(s)):\n if s.iat[i] == s.iat[i]:\n if prev_i == -1:\n w.iat[i] = 1.0\n else:\n w.iat[i] = alpha * sum_wts / pow(1.0 - alpha, i - prev_i)\n sum_wts += w.iat[i]\n prev_i = i\n return w\n\n def _variance_debiasing_factors(s, com, adjust, ignore_na):\n weights = _weights(s, com=com, adjust=adjust, ignore_na=ignore_na)\n cum_sum = weights.cumsum().fillna(method=\"ffill\")\n cum_sum_sq = (weights * weights).cumsum().fillna(method=\"ffill\")\n numerator = cum_sum * cum_sum\n denominator = numerator - cum_sum_sq\n denominator[denominator <= 0.0] = np.nan\n return numerator / denominator\n\n def _ewma(s, com, min_periods, adjust, ignore_na):\n weights = _weights(s, com=com, adjust=adjust, ignore_na=ignore_na)\n result = (\n s.multiply(weights).cumsum().divide(weights.cumsum()).fillna(method=\"ffill\")\n )\n result[\n s.expanding().count() < (max(min_periods, 1) if min_periods else 1)\n ] = np.nan\n return result\n\n x, is_constant, no_nans = consistency_data\n com = 3.0\n moments_consistency_mock_mean(\n x=x,\n mean=lambda x: x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).mean(),\n mock_mean=lambda x: _ewma(\n x, com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ),\n )\n\n moments_consistency_is_constant(\n x=x,\n is_constant=is_constant,\n min_periods=min_periods,\n count=lambda x: x.expanding().count(),\n mean=lambda x: x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).mean(),\n corr=lambda x, y: x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).corr(y),\n )\n\n moments_consistency_var_debiasing_factors(\n x=x,\n var_unbiased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=False)\n ),\n var_biased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=True)\n ),\n var_debiasing_factors=lambda x: (\n _variance_debiasing_factors(x, com=com, adjust=adjust, ignore_na=ignore_na)\n ),\n )\n\n\[email protected](\"min_periods\", [0, 1, 2, 3, 4])\[email protected](\"adjust\", [True, False])\[email protected](\"ignore_na\", [True, False])\ndef test_ewm_consistency_var(consistency_data, min_periods, adjust, ignore_na):\n x, is_constant, no_nans = consistency_data\n com = 3.0\n moments_consistency_var_data(\n x=x,\n is_constant=is_constant,\n min_periods=min_periods,\n count=lambda x: x.expanding().count(),\n mean=lambda x: x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).mean(),\n var_unbiased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=False)\n ),\n var_biased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=True)\n ),\n )\n\n\[email protected](\"min_periods\", [0, 1, 2, 3, 4])\[email protected](\"adjust\", [True, False])\[email protected](\"ignore_na\", [True, False])\ndef test_ewm_consistency_std(consistency_data, min_periods, adjust, ignore_na):\n x, is_constant, no_nans = consistency_data\n com = 3.0\n moments_consistency_std_data(\n x=x,\n var_unbiased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=False)\n ),\n std_unbiased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).std(bias=False)\n ),\n var_biased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=True)\n ),\n std_biased=lambda x: x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).std(bias=True),\n )\n\n\[email protected](\"min_periods\", [0, 1, 2, 3, 4])\[email protected](\"adjust\", [True, False])\[email protected](\"ignore_na\", [True, False])\ndef test_ewm_consistency_cov(consistency_data, min_periods, adjust, ignore_na):\n x, is_constant, no_nans = consistency_data\n com = 3.0\n moments_consistency_cov_data(\n x=x,\n var_unbiased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=False)\n ),\n cov_unbiased=lambda x, y: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).cov(y, bias=False)\n ),\n var_biased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=True)\n ),\n cov_biased=lambda x, y: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).cov(y, bias=True)\n ),\n )\n\n\[email protected]\[email protected](\"min_periods\", [0, 1, 2, 3, 4])\[email protected](\"adjust\", [True, False])\[email protected](\"ignore_na\", [True, False])\ndef test_ewm_consistency_series_data(consistency_data, min_periods, adjust, ignore_na):\n x, is_constant, no_nans = consistency_data\n com = 3.0\n moments_consistency_series_data(\n x=x,\n mean=lambda x: x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).mean(),\n corr=lambda x, y: x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).corr(y),\n var_unbiased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=False)\n ),\n std_unbiased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).std(bias=False)\n ),\n cov_unbiased=lambda x, y: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).cov(y, bias=False)\n ),\n var_biased=lambda x: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).var(bias=True)\n ),\n std_biased=lambda x: x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).std(bias=True),\n cov_biased=lambda x, y: (\n x.ewm(\n com=com, min_periods=min_periods, adjust=adjust, ignore_na=ignore_na\n ).cov(y, bias=True)\n ),\n )\n", "from collections import defaultdict\nfrom datetime import datetime\nfrom itertools import product\n\nimport numpy as np\nimport pytest\n\nfrom pandas import DataFrame, MultiIndex, Series, array, concat, merge\nimport pandas._testing as tm\nfrom pandas.core.algorithms import safe_sort\nimport pandas.core.common as com\nfrom pandas.core.sorting import (\n decons_group_index,\n get_group_index,\n is_int64_overflow_possible,\n lexsort_indexer,\n nargsort,\n)\n\n\nclass TestSorting:\n @pytest.mark.slow\n def test_int64_overflow(self):\n\n B = np.concatenate((np.arange(1000), np.arange(1000), np.arange(500)))\n A = np.arange(2500)\n df = DataFrame(\n {\n \"A\": A,\n \"B\": B,\n \"C\": A,\n \"D\": B,\n \"E\": A,\n \"F\": B,\n \"G\": A,\n \"H\": B,\n \"values\": np.random.randn(2500),\n }\n )\n\n lg = df.groupby([\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"])\n rg = df.groupby([\"H\", \"G\", \"F\", \"E\", \"D\", \"C\", \"B\", \"A\"])\n\n left = lg.sum()[\"values\"]\n right = rg.sum()[\"values\"]\n\n exp_index, _ = left.index.sortlevel()\n tm.assert_index_equal(left.index, exp_index)\n\n exp_index, _ = right.index.sortlevel(0)\n tm.assert_index_equal(right.index, exp_index)\n\n tups = list(map(tuple, df[[\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"]].values))\n tups = com.asarray_tuplesafe(tups)\n\n expected = df.groupby(tups).sum()[\"values\"]\n\n for k, v in expected.items():\n assert left[k] == right[k[::-1]]\n assert left[k] == v\n assert len(left) == len(right)\n\n @pytest.mark.arm_slow\n def test_int64_overflow_moar(self):\n\n # GH9096\n values = range(55109)\n data = DataFrame.from_dict({\"a\": values, \"b\": values, \"c\": values, \"d\": values})\n grouped = data.groupby([\"a\", \"b\", \"c\", \"d\"])\n assert len(grouped) == len(values)\n\n arr = np.random.randint(-1 << 12, 1 << 12, (1 << 15, 5))\n i = np.random.choice(len(arr), len(arr) * 4)\n arr = np.vstack((arr, arr[i])) # add sume duplicate rows\n\n i = np.random.permutation(len(arr))\n arr = arr[i] # shuffle rows\n\n df = DataFrame(arr, columns=list(\"abcde\"))\n df[\"jim\"], df[\"joe\"] = np.random.randn(2, len(df)) * 10\n gr = df.groupby(list(\"abcde\"))\n\n # verify this is testing what it is supposed to test!\n assert is_int64_overflow_possible(gr.grouper.shape)\n\n # manually compute groupings\n jim, joe = defaultdict(list), defaultdict(list)\n for key, a, b in zip(map(tuple, arr), df[\"jim\"], df[\"joe\"]):\n jim[key].append(a)\n joe[key].append(b)\n\n assert len(gr) == len(jim)\n mi = MultiIndex.from_tuples(jim.keys(), names=list(\"abcde\"))\n\n def aggr(func):\n f = lambda a: np.fromiter(map(func, a), dtype=\"f8\")\n arr = np.vstack((f(jim.values()), f(joe.values()))).T\n res = DataFrame(arr, columns=[\"jim\", \"joe\"], index=mi)\n return res.sort_index()\n\n tm.assert_frame_equal(gr.mean(), aggr(np.mean))\n tm.assert_frame_equal(gr.median(), aggr(np.median))\n\n def test_lexsort_indexer(self):\n keys = [[np.nan] * 5 + list(range(100)) + [np.nan] * 5]\n # orders=True, na_position='last'\n result = lexsort_indexer(keys, orders=True, na_position=\"last\")\n exp = list(range(5, 105)) + list(range(5)) + list(range(105, 110))\n tm.assert_numpy_array_equal(result, np.array(exp, dtype=np.intp))\n\n # orders=True, na_position='first'\n result = lexsort_indexer(keys, orders=True, na_position=\"first\")\n exp = list(range(5)) + list(range(105, 110)) + list(range(5, 105))\n tm.assert_numpy_array_equal(result, np.array(exp, dtype=np.intp))\n\n # orders=False, na_position='last'\n result = lexsort_indexer(keys, orders=False, na_position=\"last\")\n exp = list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110))\n tm.assert_numpy_array_equal(result, np.array(exp, dtype=np.intp))\n\n # orders=False, na_position='first'\n result = lexsort_indexer(keys, orders=False, na_position=\"first\")\n exp = list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1))\n tm.assert_numpy_array_equal(result, np.array(exp, dtype=np.intp))\n\n def test_nargsort(self):\n # np.argsort(items) places NaNs last\n items = [np.nan] * 5 + list(range(100)) + [np.nan] * 5\n # np.argsort(items2) may not place NaNs first\n items2 = np.array(items, dtype=\"O\")\n\n # mergesort is the most difficult to get right because we want it to be\n # stable.\n\n # According to numpy/core/tests/test_multiarray, \"\"\"The number of\n # sorted items must be greater than ~50 to check the actual algorithm\n # because quick and merge sort fall over to insertion sort for small\n # arrays.\"\"\"\n\n # mergesort, ascending=True, na_position='last'\n result = nargsort(items, kind=\"mergesort\", ascending=True, na_position=\"last\")\n exp = list(range(5, 105)) + list(range(5)) + list(range(105, 110))\n tm.assert_numpy_array_equal(result, np.array(exp), check_dtype=False)\n\n # mergesort, ascending=True, na_position='first'\n result = nargsort(items, kind=\"mergesort\", ascending=True, na_position=\"first\")\n exp = list(range(5)) + list(range(105, 110)) + list(range(5, 105))\n tm.assert_numpy_array_equal(result, np.array(exp), check_dtype=False)\n\n # mergesort, ascending=False, na_position='last'\n result = nargsort(items, kind=\"mergesort\", ascending=False, na_position=\"last\")\n exp = list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110))\n tm.assert_numpy_array_equal(result, np.array(exp), check_dtype=False)\n\n # mergesort, ascending=False, na_position='first'\n result = nargsort(items, kind=\"mergesort\", ascending=False, na_position=\"first\")\n exp = list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1))\n tm.assert_numpy_array_equal(result, np.array(exp), check_dtype=False)\n\n # mergesort, ascending=True, na_position='last'\n result = nargsort(items2, kind=\"mergesort\", ascending=True, na_position=\"last\")\n exp = list(range(5, 105)) + list(range(5)) + list(range(105, 110))\n tm.assert_numpy_array_equal(result, np.array(exp), check_dtype=False)\n\n # mergesort, ascending=True, na_position='first'\n result = nargsort(items2, kind=\"mergesort\", ascending=True, na_position=\"first\")\n exp = list(range(5)) + list(range(105, 110)) + list(range(5, 105))\n tm.assert_numpy_array_equal(result, np.array(exp), check_dtype=False)\n\n # mergesort, ascending=False, na_position='last'\n result = nargsort(items2, kind=\"mergesort\", ascending=False, na_position=\"last\")\n exp = list(range(104, 4, -1)) + list(range(5)) + list(range(105, 110))\n tm.assert_numpy_array_equal(result, np.array(exp), check_dtype=False)\n\n # mergesort, ascending=False, na_position='first'\n result = nargsort(\n items2, kind=\"mergesort\", ascending=False, na_position=\"first\"\n )\n exp = list(range(5)) + list(range(105, 110)) + list(range(104, 4, -1))\n tm.assert_numpy_array_equal(result, np.array(exp), check_dtype=False)\n\n\nclass TestMerge:\n @pytest.mark.slow\n def test_int64_overflow_issues(self):\n\n # #2690, combinatorial explosion\n df1 = DataFrame(np.random.randn(1000, 7), columns=list(\"ABCDEF\") + [\"G1\"])\n df2 = DataFrame(np.random.randn(1000, 7), columns=list(\"ABCDEF\") + [\"G2\"])\n\n # it works!\n result = merge(df1, df2, how=\"outer\")\n assert len(result) == 2000\n\n low, high, n = -1 << 10, 1 << 10, 1 << 20\n left = DataFrame(np.random.randint(low, high, (n, 7)), columns=list(\"ABCDEFG\"))\n left[\"left\"] = left.sum(axis=1)\n\n # one-2-one match\n i = np.random.permutation(len(left))\n right = left.iloc[i].copy()\n right.columns = right.columns[:-1].tolist() + [\"right\"]\n right.index = np.arange(len(right))\n right[\"right\"] *= -1\n\n out = merge(left, right, how=\"outer\")\n assert len(out) == len(left)\n tm.assert_series_equal(out[\"left\"], -out[\"right\"], check_names=False)\n result = out.iloc[:, :-2].sum(axis=1)\n tm.assert_series_equal(out[\"left\"], result, check_names=False)\n assert result.name is None\n\n out.sort_values(out.columns.tolist(), inplace=True)\n out.index = np.arange(len(out))\n for how in [\"left\", \"right\", \"outer\", \"inner\"]:\n tm.assert_frame_equal(out, merge(left, right, how=how, sort=True))\n\n # check that left merge w/ sort=False maintains left frame order\n out = merge(left, right, how=\"left\", sort=False)\n tm.assert_frame_equal(left, out[left.columns.tolist()])\n\n out = merge(right, left, how=\"left\", sort=False)\n tm.assert_frame_equal(right, out[right.columns.tolist()])\n\n # one-2-many/none match\n n = 1 << 11\n left = DataFrame(\n np.random.randint(low, high, (n, 7)).astype(\"int64\"),\n columns=list(\"ABCDEFG\"),\n )\n\n # confirm that this is checking what it is supposed to check\n shape = left.apply(Series.nunique).values\n assert is_int64_overflow_possible(shape)\n\n # add duplicates to left frame\n left = concat([left, left], ignore_index=True)\n\n right = DataFrame(\n np.random.randint(low, high, (n // 2, 7)).astype(\"int64\"),\n columns=list(\"ABCDEFG\"),\n )\n\n # add duplicates & overlap with left to the right frame\n i = np.random.choice(len(left), n)\n right = concat([right, right, left.iloc[i]], ignore_index=True)\n\n left[\"left\"] = np.random.randn(len(left))\n right[\"right\"] = np.random.randn(len(right))\n\n # shuffle left & right frames\n i = np.random.permutation(len(left))\n left = left.iloc[i].copy()\n left.index = np.arange(len(left))\n\n i = np.random.permutation(len(right))\n right = right.iloc[i].copy()\n right.index = np.arange(len(right))\n\n # manually compute outer merge\n ldict, rdict = defaultdict(list), defaultdict(list)\n\n for idx, row in left.set_index(list(\"ABCDEFG\")).iterrows():\n ldict[idx].append(row[\"left\"])\n\n for idx, row in right.set_index(list(\"ABCDEFG\")).iterrows():\n rdict[idx].append(row[\"right\"])\n\n vals = []\n for k, lval in ldict.items():\n rval = rdict.get(k, [np.nan])\n for lv, rv in product(lval, rval):\n vals.append(k + tuple([lv, rv]))\n\n for k, rval in rdict.items():\n if k not in ldict:\n for rv in rval:\n vals.append(k + tuple([np.nan, rv]))\n\n def align(df):\n df = df.sort_values(df.columns.tolist())\n df.index = np.arange(len(df))\n return df\n\n def verify_order(df):\n kcols = list(\"ABCDEFG\")\n tm.assert_frame_equal(\n df[kcols].copy(), df[kcols].sort_values(kcols, kind=\"mergesort\")\n )\n\n out = DataFrame(vals, columns=list(\"ABCDEFG\") + [\"left\", \"right\"])\n out = align(out)\n\n jmask = {\n \"left\": out[\"left\"].notna(),\n \"right\": out[\"right\"].notna(),\n \"inner\": out[\"left\"].notna() & out[\"right\"].notna(),\n \"outer\": np.ones(len(out), dtype=\"bool\"),\n }\n\n for how in [\"left\", \"right\", \"outer\", \"inner\"]:\n mask = jmask[how]\n frame = align(out[mask].copy())\n assert mask.all() ^ mask.any() or how == \"outer\"\n\n for sort in [False, True]:\n res = merge(left, right, how=how, sort=sort)\n if sort:\n verify_order(res)\n\n # as in GH9092 dtypes break with outer/right join\n tm.assert_frame_equal(\n frame, align(res), check_dtype=how not in (\"right\", \"outer\")\n )\n\n\ndef test_decons():\n def testit(codes_list, shape):\n group_index = get_group_index(codes_list, shape, sort=True, xnull=True)\n codes_list2 = decons_group_index(group_index, shape)\n\n for a, b in zip(codes_list, codes_list2):\n tm.assert_numpy_array_equal(a, b)\n\n shape = (4, 5, 6)\n codes_list = [\n np.tile([0, 1, 2, 3, 0, 1, 2, 3], 100).astype(np.int64),\n np.tile([0, 2, 4, 3, 0, 1, 2, 3], 100).astype(np.int64),\n np.tile([5, 1, 0, 2, 3, 0, 5, 4], 100).astype(np.int64),\n ]\n testit(codes_list, shape)\n\n shape = (10000, 10000)\n codes_list = [\n np.tile(np.arange(10000, dtype=np.int64), 5),\n np.tile(np.arange(10000, dtype=np.int64), 5),\n ]\n testit(codes_list, shape)\n\n\nclass TestSafeSort:\n def test_basic_sort(self):\n values = [3, 1, 2, 0, 4]\n result = safe_sort(values)\n expected = np.array([0, 1, 2, 3, 4])\n tm.assert_numpy_array_equal(result, expected)\n\n values = list(\"baaacb\")\n result = safe_sort(values)\n expected = np.array(list(\"aaabbc\"), dtype=\"object\")\n tm.assert_numpy_array_equal(result, expected)\n\n values = []\n result = safe_sort(values)\n expected = np.array([])\n tm.assert_numpy_array_equal(result, expected)\n\n @pytest.mark.parametrize(\"verify\", [True, False])\n def test_codes(self, verify):\n values = [3, 1, 2, 0, 4]\n expected = np.array([0, 1, 2, 3, 4])\n\n codes = [0, 1, 1, 2, 3, 0, -1, 4]\n result, result_codes = safe_sort(values, codes, verify=verify)\n expected_codes = np.array([3, 1, 1, 2, 0, 3, -1, 4], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n tm.assert_numpy_array_equal(result_codes, expected_codes)\n\n # na_sentinel\n codes = [0, 1, 1, 2, 3, 0, 99, 4]\n result, result_codes = safe_sort(values, codes, na_sentinel=99, verify=verify)\n expected_codes = np.array([3, 1, 1, 2, 0, 3, 99, 4], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n tm.assert_numpy_array_equal(result_codes, expected_codes)\n\n codes = []\n result, result_codes = safe_sort(values, codes, verify=verify)\n expected_codes = np.array([], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n tm.assert_numpy_array_equal(result_codes, expected_codes)\n\n @pytest.mark.parametrize(\"na_sentinel\", [-1, 99])\n def test_codes_out_of_bound(self, na_sentinel):\n values = [3, 1, 2, 0, 4]\n expected = np.array([0, 1, 2, 3, 4])\n\n # out of bound indices\n codes = [0, 101, 102, 2, 3, 0, 99, 4]\n result, result_codes = safe_sort(values, codes, na_sentinel=na_sentinel)\n expected_codes = np.array(\n [3, na_sentinel, na_sentinel, 2, 0, 3, na_sentinel, 4], dtype=np.intp\n )\n tm.assert_numpy_array_equal(result, expected)\n tm.assert_numpy_array_equal(result_codes, expected_codes)\n\n def test_mixed_integer(self):\n values = np.array([\"b\", 1, 0, \"a\", 0, \"b\"], dtype=object)\n result = safe_sort(values)\n expected = np.array([0, 0, 1, \"a\", \"b\", \"b\"], dtype=object)\n tm.assert_numpy_array_equal(result, expected)\n\n values = np.array([\"b\", 1, 0, \"a\"], dtype=object)\n codes = [0, 1, 2, 3, 0, -1, 1]\n result, result_codes = safe_sort(values, codes)\n expected = np.array([0, 1, \"a\", \"b\"], dtype=object)\n expected_codes = np.array([3, 1, 0, 2, 3, -1, 1], dtype=np.intp)\n tm.assert_numpy_array_equal(result, expected)\n tm.assert_numpy_array_equal(result_codes, expected_codes)\n\n def test_mixed_integer_from_list(self):\n values = [\"b\", 1, 0, \"a\", 0, \"b\"]\n result = safe_sort(values)\n expected = np.array([0, 0, 1, \"a\", \"b\", \"b\"], dtype=object)\n tm.assert_numpy_array_equal(result, expected)\n\n def test_unsortable(self):\n # GH 13714\n arr = np.array([1, 2, datetime.now(), 0, 3], dtype=object)\n msg = (\n \"unorderable types: .* [<>] .*\"\n \"|\" # the above case happens for numpy < 1.14\n \"'[<>]' not supported between instances of .*\"\n )\n with pytest.raises(TypeError, match=msg):\n safe_sort(arr)\n\n def test_exceptions(self):\n with pytest.raises(TypeError, match=\"Only list-like objects are allowed\"):\n safe_sort(values=1)\n\n with pytest.raises(TypeError, match=\"Only list-like objects or None\"):\n safe_sort(values=[0, 1, 2], codes=1)\n\n with pytest.raises(ValueError, match=\"values should be unique\"):\n safe_sort(values=[0, 1, 2, 1], codes=[0, 1])\n\n def test_extension_array(self):\n # a = array([1, 3, np.nan, 2], dtype='Int64')\n a = array([1, 3, 2], dtype=\"Int64\")\n result = safe_sort(a)\n # expected = array([1, 2, 3, np.nan], dtype='Int64')\n expected = array([1, 2, 3], dtype=\"Int64\")\n tm.assert_extension_array_equal(result, expected)\n\n @pytest.mark.parametrize(\"verify\", [True, False])\n @pytest.mark.parametrize(\"na_sentinel\", [-1, 99])\n def test_extension_array_codes(self, verify, na_sentinel):\n a = array([1, 3, 2], dtype=\"Int64\")\n result, codes = safe_sort(\n a, [0, 1, na_sentinel, 2], na_sentinel=na_sentinel, verify=verify\n )\n expected_values = array([1, 2, 3], dtype=\"Int64\")\n expected_codes = np.array([0, 2, na_sentinel, 1], dtype=np.intp)\n tm.assert_extension_array_equal(result, expected_values)\n tm.assert_numpy_array_equal(codes, expected_codes)\n" ]
[ [ "pandas.core.dtypes.common.is_datetime64_ns_dtype", "pandas.core.dtypes.cast.maybe_cast_to_integer_array", "pandas.core.dtypes.common.is_extension_array_dtype", "pandas.core.dtypes.cast.maybe_cast_to_datetime", "pandas._libs.lib.is_scalar", "pandas.core.arrays.FloatingArray._from_sequence", "pandas.core.dtypes.common.is_timedelta64_ns_dtype", "pandas.core.series.Series", "numpy.ma.getmaskarray", "numpy.arange", "pandas.core.dtypes.cast.maybe_convert_platform", "pandas.core.common.asarray_tuplesafe", "pandas.core.dtypes.cast.construct_1d_ndarray_preserving_na", "pandas.core.arrays.StringArray._from_sequence", "pandas.core.dtypes.common.is_iterator", "pandas.core.dtypes.common.is_float_dtype", "pandas.core.dtypes.common.is_string_dtype", "pandas.core.arrays.IntervalArray", "pandas.core.arrays.PandasArray._from_sequence", "pandas.core.dtypes.common.is_integer_dtype", "pandas.core.dtypes.common.is_list_like", "pandas.core.dtypes.cast.maybe_castable", "pandas.core.dtypes.cast.infer_dtype_from_scalar", "pandas.core.dtypes.cast.construct_1d_object_array_from_listlike", "pandas.core.arrays.period_array", "pandas.core.arrays.IntegerArray._from_sequence", "pandas.core.dtypes.common.is_sparse", "numpy.array", "pandas.core.arrays.BooleanArray._from_sequence", "pandas.core.arrays.DatetimeArray._from_sequence", "pandas.core.arrays.TimedeltaArray._from_sequence", "pandas.core.dtypes.common.is_object_dtype", "pandas.core.dtypes.cast.maybe_upcast", "pandas.core.dtypes.missing.isna", "pandas._libs.lib.infer_dtype", "pandas.core.dtypes.base.registry.find" ], [ "pandas._testing.assert_produces_warning", "pandas.concat", "pandas.Series", "numpy.random.seed", "pandas.date_range", "pandas.Categorical", "pandas.wide_to_long", "pandas.Index", "pandas.MultiIndex.from_tuples", "pandas.DataFrame", "pandas.lreshape", "numpy.random.randn", "pandas.DataFrame.from_dict", "pandas._testing.makeTimeDataFrame", "pandas._testing.assert_frame_equal", "pandas.melt" ], [ "pandas.timedelta_range", "pandas._testing.assert_produces_warning", "pandas.Series", "pandas._testing.assert_equal", "numpy.arange", "pandas.Categorical", "pandas.array", "pandas.isna", "numpy.random.randn", "pandas.Timestamp.now", "pandas.date_range", "pandas._testing.makeDateIndex", "pandas._testing.assert_series_equal", "pandas.Timestamp" ], [ "pandas.Series", "pandas.core.arrays.IntervalArray.from_breaks", "pandas.core.arrays.IntervalArray.from_arrays", "pandas.IntervalDtype", "pandas.IntervalIndex.from_arrays", "pandas._testing.assert_numpy_array_equal", "numpy.arange", "pandas.Index", "pandas._testing.assert_series_equal", "pandas.core.dtypes.common.is_list_like", "pandas.Timedelta", "pandas.Interval", "pandas.date_range", "pandas.timedelta_range", "pandas._testing.assert_equal", "pandas.period_range", "pandas.IntervalIndex.from_breaks", "pandas.Period", "pandas.Timestamp" ], [ "pandas.Series", "numpy.isnan", "pandas.DataFrame", "numpy.random.randn", "pandas._testing.assert_series_equal" ], [ "pandas.merge", "pandas.DataFrame", "numpy.random.randn", "pandas.core.sorting.get_group_index", "pandas.core.sorting.is_int64_overflow_possible", "numpy.random.randint", "pandas._testing.assert_numpy_array_equal", "numpy.arange", "pandas.core.common.asarray_tuplesafe", "pandas._testing.assert_extension_array_equal", "pandas._testing.assert_series_equal", "pandas.core.sorting.lexsort_indexer", "pandas._testing.assert_index_equal", "pandas.concat", "pandas.core.algorithms.safe_sort", "pandas.array", "pandas.DataFrame.from_dict", "numpy.array", "pandas.core.sorting.nargsort", "pandas.core.sorting.decons_group_index", "numpy.tile", "numpy.vstack" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "1.4", "1.3", "1.1", "1.0", "1.2" ], "scipy": [], "tensorflow": [] } ]
tangku006/cnn-text-classification-tf-master
[ "510a39d2726a23b0b94a5e6f4fc83014b0e0fa30" ]
[ "test.py" ]
[ "#! /usr/bin/env python\r\n\r\nimport tensorflow as tf\r\nimport numpy as np\r\nimport os\r\nimport time\r\nimport datetime\r\nimport data_helpers\r\nfrom text_cnn import TextCNN\r\nfrom tensorflow.contrib import learn\r\n\r\n# Parameters\r\n# ==================================================\r\n\r\n# Data loading params 语料文件路径定义\r\ntf.flags.DEFINE_float(\"dev_sample_percentage\", .1, \"Percentage of the training data to use for validation\")\r\ntf.flags.DEFINE_string(\"positive_data_file\", \"./data/rt-polaritydata/rt-polarity.pos\", \"Data source for the positive data.\")\r\ntf.flags.DEFINE_string(\"negative_data_file\", \"./data/rt-polaritydata/rt-polarity.neg\", \"Data source for the negative data.\")\r\n\r\n# Model Hyperparameters 定义网络超参数\r\ntf.flags.DEFINE_integer(\"embedding_dim\", 128, \"Dimensionality of character embedding (default: 128)\")\r\ntf.flags.DEFINE_string(\"filter_sizes\", \"3,4,5\", \"Comma-separated filter sizes (default: '3,4,5')\")\r\ntf.flags.DEFINE_integer(\"num_filters\", 128, \"Number of filters per filter size (default: 128)\")\r\ntf.flags.DEFINE_float(\"dropout_keep_prob\", 0.5, \"Dropout keep probability (default: 0.5)\")\r\ntf.flags.DEFINE_float(\"l2_reg_lambda\", 0.0, \"L2 regularization lambda (default: 0.0)\")\r\n\r\n# Training parameters\r\ntf.flags.DEFINE_integer(\"batch_size\", 64, \"Batch Size (default: 64)\")\r\ntf.flags.DEFINE_integer(\"num_epochs\", 200, \"Number of training epochs (default: 200)\")\r\ntf.flags.DEFINE_integer(\"evaluate_every\", 100, \"Evaluate model on dev set after this many steps (default: 100)\")\r\ntf.flags.DEFINE_integer(\"checkpoint_every\", 100, \"Save model after this many steps (default: 100)\")\r\ntf.flags.DEFINE_integer(\"num_checkpoints\", 5, \"Number of checkpoints to store (default: 5)\")\r\n# Misc Parameters\r\ntf.flags.DEFINE_boolean(\"allow_soft_placement\", True, \"Allow device soft device placement\")\r\ntf.flags.DEFINE_boolean(\"log_device_placement\", False, \"Log placement of ops on devices\")\r\n\r\nFLAGS = tf.flags.FLAGS\r\nFLAGS._parse_flags()\r\nprint(\"\\nParameters:\")\r\nfor attr, value in sorted(FLAGS.__flags.items()):\r\n print(\"{}={}\".format(attr.upper(), value))\r\nprint(\"\")\r\n\r\n\r\n# Data Preparation\r\n# ==================================================\r\n\r\n# Load data\r\nprint(\"Loading data...\")\r\nx_text, y = data_helpers.load_data_and_labels(FLAGS.positive_data_file, FLAGS.negative_data_file)\r\n\r\n# Build vocabulary\r\nmax_document_length = max([len(x.split(\" \")) for x in x_text])\r\n# 将词向量填充至max_length的长度\r\nvocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)\r\nx = np.array(list(vocab_processor.fit_transform(x_text)))\r\nprint(x[:10])\r\n\r\n# Randomly shuffle data\r\nnp.random.seed(10)\r\nshuffle_indices = np.random.permutation(np.arange(len(y)))\r\nx_shuffled = x[shuffle_indices]\r\ny_shuffled = y[shuffle_indices]\r\n\r\n\r\ndev_sample_index = -1 * int(FLAGS.dev_sample_percentage * float(len(y)))\r\nx_train, x_dev = x_shuffled[:dev_sample_index], x_shuffled[dev_sample_index:]\r\ny_train, y_dev = y_shuffled[:dev_sample_index], y_shuffled[dev_sample_index:]\r\n\r\ndel x, y, x_shuffled, y_shuffled\r\n\r\nprint(\"Vocabulary: \", vocab_processor.vocabulary_)\r\nprint(\"Vocabulary Size: {:d}\".format(len(vocab_processor.vocabulary_)))\r\nprint(\"Train/Dev split: {:d}/{:d}\".format(len(y_train), len(y_dev)))\r\n\r\nprint(x_train.shape[0], x_train.shape[1])" ]
[ [ "tensorflow.flags.DEFINE_boolean", "numpy.random.seed", "tensorflow.flags.DEFINE_string", "tensorflow.flags.DEFINE_float", "tensorflow.contrib.learn.preprocessing.VocabularyProcessor", "tensorflow.flags.DEFINE_integer" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cdiswine/data-engineering-nanodegree
[ "a5895e3ba2f94128a16b9da6d07327451bacb173" ]
[ "ETL-data-with-postgres/etl.py" ]
[ "import os\nimport glob\nimport psycopg2\nimport pandas as pd\nimport numpy as np\nfrom sql_queries import *\n\n\ndef process_song_file(cur, filepath):\n # open song file\n df = pd.read_json(filepath, lines = True)\n\n # insert song record\n song_data = df[[\"song_id\", \"title\", \"artist_id\", \"year\", \"duration\"]].values[0]\n cur.execute(song_table_insert, song_data)\n \n # insert artist record\n artist_data = df[[\"artist_id\", \"artist_name\", \"artist_location\", \"artist_latitude\", \"artist_longitude\",]].values[0]\n cur.execute(artist_table_insert, artist_data)\n\n\ndef process_log_file(cur, filepath):\n # open log file\n df = pd.read_json(filepath, lines = True)\n\n # filter by NextSong action\n df = df.query(\"page=='NextSong'\")\n\n # convert timestamp column to datetime\n t = pd.to_datetime(df[\"ts\"]/1000, unit = 's')\n \n # insert time data records\n time_data = np.transpose(np.array([df[\"ts\"].values, t.dt.hour.values, t.dt.day.values, t.dt.week.values, \\\n t.dt.month.values, t.dt.year.values, t.dt.weekday.values]))\n column_labels = (\"timestamp\", \"hour\", \"day\", \"week of year\", \"month\", \"year\", \"weekday\")\n time_df = pd.DataFrame(data = time_data, columns = column_labels)\n\n for i, row in time_df.iterrows():\n cur.execute(time_table_insert, list(row))\n\n # load user table\n user_df = df[[\"userId\", \"firstName\", \"lastName\", \"gender\", \"level\"]]\n\n # insert user records\n for i, row in user_df.iterrows():\n cur.execute(user_table_insert, row)\n\n # insert songplay records\n for index, row in df.iterrows():\n \n # get songid and artistid from song and artist tables\n cur.execute(song_select, (row.song, row.artist, row.length))\n results = cur.fetchone()\n \n if results:\n songid, artistid = results\n else:\n songid, artistid = None, None\n\n # insert songplay record\n songplay_data = (row.ts, row.userId, row.level, songid, artistid, row.sessionId, \\\n row.location, row.userAgent)\n cur.execute(songplay_table_insert, songplay_data)\n\n\ndef process_data(cur, conn, filepath, func):\n # get all files matching extension from directory\n all_files = []\n for root, dirs, files in os.walk(filepath):\n files = glob.glob(os.path.join(root,'*.json'))\n for f in files :\n all_files.append(os.path.abspath(f))\n\n # get total number of files found\n num_files = len(all_files)\n print('{} files found in {}'.format(num_files, filepath))\n\n # iterate over files and process\n for i, datafile in enumerate(all_files, 1):\n func(cur, datafile)\n conn.commit()\n print('{}/{} files processed.'.format(i, num_files))\n\n\ndef main():\n conn = psycopg2.connect(\"host=127.0.0.1 dbname=sparkifydb user=student password=student\")\n cur = conn.cursor()\n\n process_data(cur, conn, filepath='data/song_data', func=process_song_file)\n process_data(cur, conn, filepath='data/log_data', func=process_log_file)\n\n conn.close()\n\n\nif __name__ == \"__main__\":\n main()" ]
[ [ "numpy.array", "pandas.to_datetime", "pandas.read_json", "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] } ]
weightan/quaternion_polynomials
[ "50d00bb883c4a4249f13154cffcb459a1319ecb9", "50d00bb883c4a4249f13154cffcb459a1319ecb9" ]
[ "old_stuff/harold/_time_domain.py", "old_stuff/harold/tests/test_static_ctrl_design.py" ]
[ "import numpy as np\nfrom numpy import (reciprocal, einsum, maximum, minimum, zeros_like,\n atleast_1d, squeeze)\nfrom scipy.linalg import eig, eigvals, matrix_balance, norm\nfrom harold._classes import Transfer, transfer_to_state\nfrom harold._discrete_funcs import discretize\nfrom harold._arg_utils import _check_for_state, _check_for_state_or_transfer\n\n__all__ = ['simulate_linear_system', 'simulate_step_response',\n 'simulate_impulse_response']\n\n\ndef simulate_linear_system(sys, u, t=None, x0=None, per_channel=False):\n \"\"\"\n Compute the linear model response to an input array sampled at given time\n instances.\n\n Parameters\n ----------\n sys : {State, Transfer}\n The system model to be simulated\n u : array_like\n The real-valued input sequence to force the model. 1D arrays for single\n input models and 2D arrays that has as many columns as the number of\n inputs are valid inputs.\n t : array_like, optional\n The real-valued sequence to be used for the evolution of the system.\n The values should be equally spaced otherwise an error is raised. For\n discrete time models increments different than the sampling period also\n raises an error. On the other hand for discrete models this can be\n omitted and a time sequence will be generated automatically.\n x0 : array_like, optional\n The initial condition array. If omitted an array of zeros is assumed.\n Note that Transfer models by definition assume zero initial conditions\n and will raise an error.\n per_channel : bool, optional\n If this is set to True and if the system has multiple inputs, the\n response of each input is returned individually. For example, if a\n system has 4 inputs and 3 outputs then the response shape becomes\n (num, p, m) instead of (num, p) where k-th slice (:, :, k) is the\n response from the k-th input channel. For single input systems, this\n keyword has no effect.\n\n Returns\n -------\n yout : ndarray\n The resulting response array. The array is 1D if sys is SISO and\n has p columns if sys has p outputs.\n tout : ndarray\n The time sequence used in the simulation. If the parameter t is not\n None then a copy of t is given.\n\n Notes\n -----\n For Transfer models, first conversion to a state model is performed and\n then the resulting model is used for computations.\n\n \"\"\"\n _check_for_state_or_transfer(sys)\n\n # Quick initial condition checks\n if x0 is not None:\n if sys._isgain:\n raise ValueError('Static system models can\\'t have initial '\n 'conditions set.')\n if isinstance(sys, Transfer):\n raise ValueError('Transfer models can\\'t have initial conditions '\n 'set.')\n x0 = np.asarray(x0, dtype=float).squeeze()\n if x0.ndim > 1:\n raise ValueError('Initial condition can only be a 1D array.')\n else:\n x0 = x0[:, None]\n\n if sys.NumberOfStates != x0.size:\n raise ValueError('The initial condition size does not match the '\n 'number of states of the model.')\n\n # Always works with State Models\n try:\n _check_for_state(sys)\n except ValueError:\n sys = transfer_to_state(sys)\n\n n, m = sys.NumberOfStates, sys.shape[1]\n\n is_discrete = sys.SamplingSet == 'Z'\n u = np.asarray(u, dtype=float).squeeze()\n if u.ndim == 1:\n u = u[:, None]\n\n t = _check_u_and_t_for_simulation(m, sys._dt, u, t, is_discrete)\n # input and time arrays are regular move on\n\n # Static gains are simple matrix multiplications with no x0\n if sys._isgain:\n if sys._isSISO:\n yout = u * sys.d.squeeze()\n else:\n # don't bother for single inputs\n if m == 1:\n per_channel = False\n\n if per_channel:\n yout = np.einsum('ij,jk->ikj', u, sys.d.T)\n else:\n yout = u @ sys.d.T\n\n # Dynamic model\n else:\n # TODO: Add FOH discretization for funky input\n # ZOH discretize the continuous system based on the time increment\n if not is_discrete:\n sys = discretize(sys, t[1]-t[0], method='zoh')\n\n sample_num = len(u)\n a, b, c, d = sys.matrices\n # Bu and Du are constant matrices so get them ready (transposed)\n M_u = np.block([b.T, d.T])\n at = a.T\n\n # Explicitly skip single inputs for per_channel\n if m == 1:\n per_channel = False\n\n # Shape the response as a 3D array\n if per_channel:\n xout = np.empty([sample_num, n, m], dtype=float)\n\n for col in range(m):\n xout[0, :, col] = 0. if x0 is None else x0.T\n Bu = u[:, [col]] @ b.T[[col], :]\n\n # Main loop for xdot eq.\n for row in range(1, sample_num):\n xout[row, :, col] = xout[row-1, :, col] @ at + Bu[row-1]\n\n # Get the output equation for each slice of inputs\n # Cx + Du\n yout = np.einsum('ijk,jl->ilk', xout, c.T) + \\\n np.einsum('ij,jk->ikj', u, d.T)\n # Combined output\n else:\n BDu = u @ M_u\n xout = np.empty([sample_num, n], dtype=float)\n xout[0] = 0. if x0 is None else x0.T\n # Main loop for xdot eq.\n for row in range(1, sample_num):\n xout[row] = (xout[row-1] @ at) + BDu[row-1, :n]\n\n # Now we have all the state evolution get the output equation\n yout = xout @ c.T + BDu[:, n:]\n\n return yout, t\n\n\ndef simulate_step_response(sys, t=None):\n \"\"\"\n Compute the linear model response to an Heaviside function (or all-ones\n array) sampled at given time instances.\n\n If the time array is omitted then a time sequence is generated based on\n the poles of the model.\n\n Parameters\n ----------\n sys : {State, Transfer}\n The system model to be simulated\n t : array_like\n The real-valued sequence to be used for the evolution of the system.\n The values should be equally spaced otherwise an error is raised. For\n discrete time models increments different than the sampling period also\n raises an error. On the other hand for discrete models this can be\n omitted and a time sequence will be generated automatically.\n\n Returns\n -------\n yout : ndarray\n The resulting response array. The array is 1D if sys is SISO and\n has p columns if sys has p outputs. If there are also m inputs the\n array is 3D array with the shape (<num of samples>, p, m)\n tout : ndarray\n The time sequence used in the simulation. If the parameter t is not\n None then a copy of t is given.\n\n \"\"\"\n _check_for_state_or_transfer(sys)\n # Always works with State Models\n try:\n _check_for_state(sys)\n except ValueError:\n sys = transfer_to_state(sys)\n\n if t is None:\n tf, ts = _compute_tfinal_and_dt(sys)\n t = np.arange(0, tf+ts, ts, dtype=float)\n else:\n t, ts = _check_custom_time_input(t)\n\n m = sys.shape[1]\n u = np.ones([len(t), m], dtype=float)\n\n return simulate_linear_system(sys, u=u, t=t, per_channel=1)\n\n\ndef simulate_impulse_response(sys, t=None):\n \"\"\"\n Compute the linear model response to an Dirac delta pulse (or all-zeros\n array except the first sample being 1/dt at each channel) sampled at given\n time instances.\n\n If the time array is omitted then a time sequence is generated based on\n the poles of the model.\n\n Parameters\n ----------\n sys : {State, Transfer}\n The system model to be simulated\n t : array_like\n The real-valued sequence to be used for the evolution of the system.\n The values should be equally spaced otherwise an error is raised. For\n discrete time models increments different than the sampling period also\n raises an error. On the other hand for discrete models this can be\n omitted and a time sequence will be generated automatically.\n\n Returns\n -------\n yout : ndarray\n The resulting response array. The array is 1D if sys is SISO and\n has p columns if sys has p outputs. If there are also m inputs the\n array is 3D array with the shape (<num of samples>, p, m)\n tout : ndarray\n The time sequence used in the simulation. If the parameter t is not\n None then a copy of t is given.\n\n \"\"\"\n _check_for_state_or_transfer(sys)\n # Always works with State Models\n try:\n _check_for_state(sys)\n except ValueError:\n sys = transfer_to_state(sys)\n\n if t is None:\n tf, ts = _compute_tfinal_and_dt(sys, is_step=False)\n t = np.arange(0, tf+ts, ts, dtype=float)\n else:\n t, ts = _check_custom_time_input(t)\n\n m = sys.shape[1]\n u = np.zeros([len(t), m], dtype=float)\n u[0] = 1./ts\n\n return simulate_linear_system(sys, u=u, t=t, per_channel=1)\n\n\ndef _compute_tfinal_and_dt(sys, is_step=True):\n \"\"\"\n Helper function to estimate a final time and a sampling period for\n time domain simulations. It is essentially geared towards impulse response\n but is also used for step responses.\n\n For discrete-time models, obviously dt is inherent and only tfinal is\n computed.\n\n Parameters\n ----------\n sys : {State, Transfer}\n The system to be investigated\n is_step : bool\n Scales the dc value by the magnitude of the nonzero mode since\n integrating the impulse response gives ∫exp(-λt) = -exp(-λt)/λ.\n Default is True.\n\n Returns\n -------\n tfinal : float\n The final time instance for which the simulation will be performed.\n dt : float\n The estimated sampling period for the simulation.\n\n Notes\n -----\n Just by evaluating the fastest mode for dt and slowest for tfinal often\n leads to unnecessary, bloated sampling (e.g., Transfer(1,[1,1001,1000]))\n since dt will be very small and tfinal will be too large though the fast\n mode hardly ever contributes. Similarly, change the numerator to [1, 2, 0]\n and the simulation would be unnecessarily long and the plot is virtually\n an L shape since the decay is so fast.\n\n Instead, a modal decomposition in time domain hence a truncated ZIR and ZSR\n can be used such that only the modes that have significant effect on the\n time response are taken. But the sensitivity of the eigenvalues complicate\n the matter since dλ = <w, dA*v> with <w,v> = 1. Hence we can only work\n with simple poles with this formulation. See Golub, Van Loan Section 7.2.2\n for simple eigenvalue sensitivity about the nonunity of <w,v>. The size of\n the response is dependent on the size of the eigenshapes rather than the\n eigenvalues themselves.\n\n \"\"\"\n sqrt_eps = np.sqrt(np.spacing(1.))\n min_points = 100 # min number of points\n min_points_z = 20 # min number of points\n max_points = 10000 # max number of points\n max_points_z = 75000 # max number of points for discrete models\n default_tfinal = 5 # Default simulation horizon\n total_cycles = 5 # number of cycles for oscillating modes\n pts_per_cycle = 25 # Number of points divide a period of oscillation\n log_decay_percent = np.log(100) # Factor of reduction for real pole decays\n\n # if a static model is given, don't bother with checks\n if sys._isgain:\n if sys._isdiscrete:\n return sys._dt*min_points_z, sys._dt\n else:\n return default_tfinal, default_tfinal / min_points\n\n if sys._isdiscrete:\n # System already has sampling fixed hence we can't fall into the same\n # trap mentioned above. Just get nonintegrating slow modes together\n # with the damping.\n dt = sys._dt\n tfinal = default_tfinal\n p = eigvals(sys.a)\n # Array Masks\n # unstable\n m_u = (np.abs(p) >= 1 + sqrt_eps)\n p_u, p = p[m_u], p[~m_u]\n if p_u.size > 0:\n m_u = (p_u.real < 0) & (np.abs(p_u.imag) < sqrt_eps)\n t_emp = np.max(log_decay_percent / np.abs(np.log(p_u[~m_u])/dt))\n tfinal = max(tfinal, t_emp)\n\n # zero - negligible effect on tfinal\n m_z = np.abs(p) < sqrt_eps\n p = p[~m_z]\n # Negative reals- treated as oscillary mode\n m_nr = (p.real < 0) & (np.abs(p.imag) < sqrt_eps)\n p_nr, p = p[m_nr], p[~m_nr]\n if p_nr.size > 0:\n t_emp = np.max(log_decay_percent / np.abs((np.log(p_nr)/dt).real))\n tfinal = max(tfinal, t_emp)\n # discrete integrators\n m_int = (p.real - 1 < sqrt_eps) & (np.abs(p.imag) < sqrt_eps)\n p_int, p = p[m_int], p[~m_int]\n # pure oscillatory modes\n m_w = (np.abs(np.abs(p) - 1) < sqrt_eps)\n p_w, p = p[m_w], p[~m_w]\n if p_w.size > 0:\n t_emp = total_cycles * 2 * np.pi / np.abs(np.log(p_w)/dt).min()\n tfinal = max(tfinal, t_emp)\n\n if p.size > 0:\n t_emp = log_decay_percent / np.abs((np.log(p)/dt).real).min()\n tfinal = max(tfinal, t_emp)\n\n if p_int.size > 0:\n tfinal = tfinal * 5\n\n # Make tfinal an integer multiple of dt\n num_samples = tfinal // dt\n if num_samples > max_points_z:\n tfinal = dt * max_points_z\n else:\n tfinal = dt * num_samples\n\n return tfinal, dt\n\n # Improve conditioning via balancing and zeroing tiny entries\n # See <w,v> for [[1,2,0], [9,1,0.01], [1,2,10*np.pi]] before/after balance\n b, (sca, perm) = matrix_balance(sys.a, separate=True)\n p, l, r = eig(b, left=True, right=True)\n # Reciprocal of inner product <w,v> for each λ, (bound the ~infs by 1e12)\n # G = Transfer([1], [1,0,1]) gives zero sensitivity (bound by 1e-12)\n eig_sens = reciprocal(maximum(1e-12, einsum('ij,ij->j', l, r).real))\n eig_sens = minimum(1e12, eig_sens)\n # Tolerances\n p[np.abs(p) < np.spacing(eig_sens * norm(b, 1))] = 0.\n # Incorporate balancing to outer factors\n l[perm, :] *= reciprocal(sca)[:, None]\n r[perm, :] *= sca[:, None]\n w, v = sys.c @ r, l.T.conj() @ sys.b\n\n origin = False\n # Computing the \"size\" of the response of each simple mode\n wn = np.abs(p)\n if np.any(wn == 0.):\n origin = True\n\n dc = zeros_like(p, dtype=float)\n # well-conditioned nonzero poles, np.abs just in case\n ok = np.abs(eig_sens) <= 1/sqrt_eps\n # the averaged t→∞ response of each simple λ on each i/o channel\n # See, A = [[-1, k], [0, -2]], response sizes are k-dependent (that is\n # R/L eigenvector dependent)\n dc[ok] = norm(v[ok, :], axis=1)*norm(w[:, ok], axis=0)*eig_sens[ok]\n dc[wn != 0.] /= wn[wn != 0] if is_step else 1.\n dc[wn == 0.] = 0.\n # double the oscillating mode magnitude for the conjugate\n dc[p.imag != 0.] *= 2\n\n # Now get rid of noncontributing integrators and simple modes if any\n relevance = (dc > 0.1*dc.max()) | ~ok\n psub = p[relevance]\n wnsub = wn[relevance]\n\n tfinal, dt = [], []\n ints = wnsub == 0.\n iw = (psub.imag != 0.) & (np.abs(psub.real) <= sqrt_eps)\n\n # Pure imaginary?\n if np.any(iw):\n tfinal += (total_cycles * 2 * np.pi / wnsub[iw]).tolist()\n dt += (2 * np.pi / pts_per_cycle / wnsub[iw]).tolist()\n # The rest ~ts = log(%ss value) / exp(Re(λ)t)\n texp_mode = log_decay_percent / np.abs(psub[~iw & ~ints].real)\n tfinal += texp_mode.tolist()\n dt += minimum(texp_mode / 50,\n (2 * np.pi / pts_per_cycle / wnsub[~iw & ~ints])).tolist()\n\n # All integrators?\n if len(tfinal) == 0:\n return default_tfinal*5, default_tfinal*5/min_points\n\n tfinal = np.max(tfinal)*(5 if origin else 1)\n dt = np.min(dt)\n\n dt = tfinal / max_points if tfinal // dt > max_points else dt\n tfinal = dt * min_points if tfinal // dt < min_points else tfinal\n\n return tfinal, dt\n\n\ndef _check_u_and_t_for_simulation(m, dt, u, t, isdiscrete):\n \"\"\"\n Helper function to validate the input arguments for simulate_linear_system\n \"\"\"\n # Discrete models can omit t array, make one here for convenience\n if t is None:\n if not isdiscrete:\n raise ValueError('Continuous time models need an evenly spaced '\n 'time sequence from which the sampling period '\n 'will be obtained.')\n else:\n u_samples = len(u)\n t = np.linspace(0, (u_samples-1)*dt, num=u_samples)\n else:\n t = np.asarray(t, dtype=float).squeeze()\n if t.ndim != 1:\n raise ValueError('Time array needs to be a 1D array.')\n t_diff = np.diff(t)\n if not np.allclose(t_diff, t_diff[0]) or not t_diff[0] > 0.:\n raise ValueError('Time array should be equally spaced and '\n 'increasing.')\n\n if isdiscrete and not np.isclose(dt, t_diff[0]):\n raise ValueError('Time array increment {} is not equal to the'\n ' model sampling period {}.'.format(t_diff[0],\n dt))\n\n if u.size < 1:\n raise ValueError('The input array should at least have one point.')\n\n # First dimension is always # of samples\n if len(u) != len(t):\n raise ValueError('The input and time arrays should have the same'\n ' length. t: {} vs. u: {}'.format(t.shape,\n u.shape))\n\n if u.shape[1] != m:\n raise ValueError('Number of input columns ({}) don\\'t match the number'\n ' of inputs ({}) of the given model.'\n ''.format(u.shape[1], m))\n return t\n\n\ndef _check_custom_time_input(t):\n \"\"\"\n Helper function for simple and rather expensive checks for sanity\n \"\"\"\n t = atleast_1d(t)\n if t.ndim > 1:\n t = squeeze(t)\n if t.ndim > 1:\n raise ValueError('Time array should be a 1D array but has '\n '{} nontrivial dimensions'.format(t.ndim))\n if t.size < 2:\n raise ValueError('Time array should have at least two data points.')\n dt = t[1] - t[0]\n if dt <= 0.:\n raise ValueError('The time increment dt cannot be negative; '\n 'Difference of the first two samples t1 - t0 = {}'\n ''.format(dt))\n # np.diff is somewhat slower than the diff of the views\n if not np.allclose(t[1:] - t[:-1], dt):\n raise ValueError('Supplied time array is not numerically equally '\n 'spaced (checked via numpy.allclose).')\n\n return t, dt\n", "from numpy import eye, array, sort, empty\nfrom scipy.linalg import block_diag, eigvals\nfrom scipy.signal.filter_design import _cplxpair\nfrom numpy.testing import (assert_almost_equal, assert_array_almost_equal,\n assert_array_equal)\n\nfrom pytest import raises as assert_raises\nfrom harold import lqr, ackermann, State, Transfer, haroldcompanion\nfrom harold._static_ctrl_design import _get_pole_reps\n\n\ndef test_lqr_arguments():\n # First arg is not LTI\n assert_raises(ValueError, lqr, 1, 1)\n # Static Gain\n assert_raises(ValueError, lqr, State(1), 1)\n # Wrong string\n assert_raises(ValueError, lqr, Transfer(1, [1, 1]), 1, weight_on='asdf')\n # scalar matrices\n H = Transfer(1, [1, 1])\n k, x, e = lqr(H, 3)\n assert_almost_equal(array([k[0, 0], x[0, 0], e[0]]), [1, 1, -2+0j])\n\n\ndef test_simple_lqr():\n # Example taken from M. de Oliveira's MAE280B lecture notes\n H = State([[0, 0, 1, 0],\n [0, 0, 0, 1],\n [4.03428022844288e-06, 0, 0, 0.0515652322798669],\n [0, 0, -0.000104315254033883, 0]],\n [[0, 0], [1e-5/3, 0], [0, 0], [0, 0.01]],\n eye(4))\n k, _, _ = lqr(H[:, 1], eye(4))\n H.a = H.a.T\n f, _, _ = lqr(H[:, 0], block_diag(0, 0, 1e-5, 1e-5), 0.1)\n assert_almost_equal(k, array([[1.00554916, -1, 52.52180106, 18.51107167]]))\n assert_almost_equal(f, array([[-577.370350, 173.600463,\n 0.383744946, 0.050228534]]), decimal=5)\n\n\ndef test_simple_lqry():\n # Scalar matrices\n H = State(1, 1, 1, 1)\n k, x, e = lqr(H, Q=3, weight_on='output')\n assert_almost_equal(array([k[0, 0], x[0, 0], e[0]]), [1.5, 3, -0.5+0j])\n # Wrong S shape\n assert_raises(ValueError, lqr, H, Q=3, S=eye(2), weight_on='output')\n\n\ndef test_simple_dlqr():\n # Example taken from M. de Oliveira's MAE280B lecture notes\n H = State([[0, 0, 1, 0],\n [0, 0, 0, 1],\n [4.03428022844288e-06, 0, 0, 0.0515652322798669],\n [0, 0, -0.000104315254033883, 0]],\n [[0, 0], [1e-5/3, 0], [0, 0], [0, 0.01]],\n eye(4), dt=0.1)\n k, _, _ = lqr(H[:, 1], eye(4))\n H.a = H.a.T\n f, _, _ = lqr(H[:, 0], block_diag(0, 0, 1e-5, 1e-5), 0.1)\n assert_almost_equal(k, array([[0, 0, -2.08727337333631e-06, 0]]))\n assert_almost_equal(f, array([[1.71884123e-11, 0, 0, -1.79301359e-15]]))\n\n\ndef test_ackermann_args():\n # Not SIxO system\n G = State(eye(2), eye(2), eye(2))\n assert_raises(ValueError, ackermann, G, [1, 2])\n # Wrong # of poles\n G = State(eye(2), [[1], [0]], [1, 0])\n assert_raises(ValueError, ackermann, G, [1, 2, 3])\n\n\ndef test_ackermann_controllable():\n #\n A = haroldcompanion([1, 6, 5, 1])\n B = eye(3)[:, [-1]]\n p = [-10, -9, -8]\n K = ackermann((A, B), p)\n pa = eigvals(A - B@K)\n assert_array_almost_equal(array(p, dtype=complex), sort(pa))\n\n\ndef test_ackermann_uncontrollable():\n A = block_diag(haroldcompanion([1, 6, 5, 1]), 1)\n B = eye(4)[:, [-2]]\n p = [-10, -9, -8, -7]\n assert_raises(ValueError, ackermann, (A, B), p)\n\n\ndef byersnash_A_B_test_pairs():\n ABs = [\n # Chemical Reactor (Munro 1979)\n (array([[1.38, -0.2077, 6.715, -5.676],\n [-0.5814, -4.29, 0, 0.675],\n [1.067, 4.273, -6.654, 5.893],\n [0.048, 4.273, 1.343, -2.104]]),\n array([[0, 0],\n [5.679, 0],\n [1.136, -3.146],\n [1.136, 0]])),\n # Distillation Column (Klein, Moore 1977)\n (array([[-0.1094, 0.0628, 0, 0, 0],\n [1.306, -2.132, 0.9807, 0, 0],\n [0, 1.595, -3.149, 1.547, 0],\n [0, 0.0355, 2.632, -4.257, 1.855],\n [0, 0.0023, 0, 0.1636, -0.1625]]),\n array([[0, 0],\n [0.638, 0],\n [0.0838, -0.1396],\n [0.1004, -0.206],\n [0.0063, -0.0128]])),\n # Nuclear rocket engine (Davison, Chow 1974)\n (array([[-65.0, 65, -19.5, 19.5],\n [0.1, -0.1, 0, 0],\n [1, 0, -0.5, -1],\n [0, 0, 0.4, 0]]),\n array([[65., 0],\n [0, 0],\n [0, 0],\n [0, 0.4]])),\n # MIMO system (Atkinson, 1985)\n (array([[0, 1, 0],\n [0, 0, 1],\n [-6, -11, -6]]),\n array([[1, 1],\n [0, 1],\n [1, 1]])),\n # Drum boiler (Bengtsson 1973)\n (array([[-0.129, 0, 0.396, 0.25, 0.00191],\n [0.0329, 0, -0.00779, 0.0122, -0.621],\n [0.00718, 0, -0.1, 0.000887, -0.0385],\n [0.00411, 0, 0, -0.0822, 0],\n [0.00351, 0, 0.0035, 0.00426, -0.0743]]),\n array([[0, 0.1390],\n [0, 0.0359],\n [0, -0.0989],\n [0.0249, 0],\n [0, -0.00534]])),\n # Miminis random example #1\n (array([[5.8765, 9.3456, 4.5634, 9.3520],\n [6.6526, 0.5867, 3.5829, 0.6534],\n [0.0000, 9.6738, 7.4876, 4.7654],\n [0.0000, 0.0000, 6.6784, 2.5678]]),\n array([[3.9878, 0.5432],\n [0.0000, 2.7650],\n [0.0000, 0.0000],\n [0.0000, 0.0000]])),\n # Miminis random example #2\n (array([[.5257, .8544, .5596, .5901, .0259, .6213, .7227, .5617],\n [.9931, .0643, .1249, .3096, .5174, .3455, .8977, .4682],\n [.6489, .8279, .7279, .2552, .3917, .7065, .2428, .7795],\n [.9923, .9262, .2678, .6252, .2414, .5211, .4338, .9677],\n [.0000, .5667, .5465, .1157, .5064, .2870, .7901, .9809],\n [.0000, .0000, .8672, .6117, .4236, .6503, .5069, .8187],\n [.0000, .0000, .0000, .0000, .2894, .0881, .5233, .4257],\n [.0000, .0000, .0000, .0000, .0000, .4499, .5597, .2462]]),\n array([[0.9230, 0.3950, 0.8325],\n [0.0000, 0.0366, 0.6105],\n [0.0000, 0.0000, 0.1871],\n [0.0000, 0.0000, 0.0000],\n [0.0000, 0.0000, 0.0000],\n [0.0000, 0.0000, 0.0000],\n [0.0000, 0.0000, 0.0000],\n [0.0000, 0.0000, 0.0000]])),\n # Aircraft control example I (Kautsky and Nichols 1983)\n (array([[0, 1, 0, 0],\n [1.40e-4, -2.04, -1.95, -1.33e-2],\n [-2.51e-4, 1, -1.32, -2.38e-2],\n [-5.61e-1, 0, 0.358, -2.79e-1]]),\n array([[0, 0, 0],\n [-5.33, 6.45e-3, -2.67e-1],\n [-1.60e-1, -1.16e-2, -2.51e-1],\n [0, 1.06e-1, 8.62e-2]])),\n # Aircraft control example II (Kautsky and Nichols 1983)\n (array([[0, 1, 0, 0],\n [5.32e-7, -4.18e-1, -0.12, -2.32e-2],\n [-4.62e-9, 1, -0.752, -2.39e-2],\n [-5.61e-1, 0, 0.3, -1.74e-2]]),\n array([[0, 0],\n [-1.72e-1, 7.45e-6],\n [-2.82e-2, -7.78e-5],\n [0, 3.69e-3]])),\n # Symmetric example (Kautsky and Nichols 1983)\n (array([[-3.624, 4.9567e-2, -2.4564e-1, 1.3853e-2],\n [3.3486e-1, -1.8875, -8.1251e-1, -2.8102e-1],\n [-1.9958e-1, -1.1335, -2.2039, -4.5523e-1],\n [1.3784e-1, -4.7140e-1, -3.3229e-1, -4.0605]]),\n array([[2.3122e-1, 3.0761e-1, 3.6164e-1, 3.3217e-1],\n [8.8339e-1, 2.1460e-1, 5.6642e-1, 5.0153e-1]]).T),\n # Ad-hoc ill-conditioned example (Byers and Nash 1989)\n (array([[0, 0, 0, 0],\n [1, 10, 100, 1000],\n [0, 1, 10, 100],\n [0, 0, 1, 10]]),\n array([[1, 0],\n [0, 1],\n [0, 0],\n [0, 0]]))\n ]\n\n # Return a generator\n return (x for x in ABs)\n\n\ndef _test_get_pole_reps():\n\n # Only complex\n p = array([1.+1j, 1-1j, 2.+1j, 2-1j])\n pr, nc, nr = _get_pole_reps(p)\n for x in range(2):\n assert_array_equal(pr[x], empty((0, 2)))\n assert nc == 4\n assert nr == 0\n\n # Only real\n p = array([1, 2, 3])\n pr, nc, nr = _get_pole_reps(p)\n for x in range(2):\n assert_array_equal(pr[x], empty((0, 2)))\n assert nc == 0\n assert nr == 3\n\n # Mixed, no reps\n p = array([1.+1j, 1-1j, 3])\n pr, nc, nr = _get_pole_reps(p)\n for x in range(2):\n assert_array_equal(pr[x], empty((0, 2)))\n assert nc == 2\n assert nr == 1\n\n # Mixed, complex reps\n p = array([1.+1j, 1-1j, 1.+1j, 1-1j, 3])\n p = _cplxpair(p).conj()\n pr, nc, nr = _get_pole_reps(p)\n assert_array_equal(pr[0], array([[0, 2]]))\n assert_array_equal(pr[1], empty((0, 2)))\n assert nc == 4\n assert nr == 1\n\n # Mixed real reps\n p = array([1.+1j, 1-1j, 1., 1])\n p = _cplxpair(p).conj()\n pr, nc, nr = _get_pole_reps(p)\n assert_array_equal(pr[0], empty((0, 2)))\n assert_array_equal(pr[1], array([[2, 4]]))\n assert nc == 2\n assert nr == 2\n\n # Mixed real reps, real dangling\n p = array([1.+1j, 1-1j, 1., 1, 0.54, 3.8])\n p = _cplxpair(p).conj()\n pr, nc, nr = _get_pole_reps(p)\n assert_array_equal(pr[0], empty((0, 2)))\n assert_array_equal(pr[1], array([[3, 5]]))\n assert nc == 2\n assert nr == 4\n\n # Mixed complex reps, complex dangling\n p = array([1.+1j, 1-1j, 1.+1j, 1-1j, 0.+1j, 0-1j, 0.5, 3.])\n p = _cplxpair(p).conj()\n pr, nc, nr = _get_pole_reps(p)\n assert_array_equal(pr[0], array([[1, 3]]))\n assert_array_equal(pr[1], empty((0, 2)))\n assert nc == 6\n assert nr == 2\n\n # Mixed reps and dangling\n p = array([1.+1j, 1-1j, 1.+1j, 1-1j,\n 2.+1j, 2-1j,\n 3.+1j, 3-1j, 3.+1j, 3-1j, 3.+1j, 3-1j,\n 4.+1j, 4-1j,\n 0,\n 0.5, 0.5,\n 3.,\n 6, 6, 6])\n p = _cplxpair(p).conj()\n pr, nc, nr = _get_pole_reps(p)\n assert_array_equal(pr[0], array([[0, 2],\n [3, 6]]))\n assert_array_equal(pr[1], array([[15, 17],\n [18, 21]]))\n assert nc == 14\n assert nr == 7\n" ]
[ [ "numpy.minimum", "numpy.linspace", "numpy.einsum", "numpy.asarray", "numpy.squeeze", "numpy.max", "numpy.zeros_like", "numpy.any", "numpy.allclose", "numpy.arange", "numpy.atleast_1d", "numpy.block", "numpy.diff", "scipy.linalg.norm", "numpy.reciprocal", "numpy.isclose", "numpy.log", "numpy.spacing", "scipy.linalg.matrix_balance", "numpy.min", "scipy.linalg.eigvals", "scipy.linalg.eig", "numpy.abs", "numpy.empty" ], [ "scipy.linalg.block_diag", "numpy.eye", "numpy.sort", "scipy.linalg.eigvals", "scipy.signal.filter_design._cplxpair", "numpy.array", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "0.13", "0.14", "0.15", "0.12", "0.10" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ananthsub/d2go
[ "8c3618d9e73518d32350ab4e6d0fb6509c9e08b6", "8c3618d9e73518d32350ab4e6d0fb6509c9e08b6" ]
[ "d2go/setup.py", "d2go/evaluation/prediction_count_evaluation.py" ]
[ "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\n\nimport argparse\nimport logging\nimport os\nimport time\n\nimport detectron2.utils.comm as comm\nimport torch\nfrom d2go.config import (\n CfgNode as CN,\n auto_scale_world_size,\n reroute_config_path,\n temp_defrost,\n)\nfrom d2go.distributed import get_local_rank, get_num_processes_per_machine\nfrom d2go.runner import GeneralizedRCNNRunner, create_runner\nfrom d2go.utils.launch_environment import get_launch_environment\nfrom detectron2.utils.collect_env import collect_env_info\nfrom detectron2.utils.logger import setup_logger\nfrom detectron2.utils.serialize import PicklableWrapper\nfrom d2go.utils.helper import run_once\nfrom detectron2.utils.file_io import PathManager\nfrom mobile_cv.common.misc.py import FolderLock, MultiprocessingPdb, post_mortem_if_fail\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef basic_argument_parser(\n distributed=True,\n requires_config_file=True,\n requires_output_dir=True,\n):\n \"\"\" Basic cli tool parser for Detectron2Go binaries \"\"\"\n parser = argparse.ArgumentParser(description=\"PyTorch Object Detection Training\")\n parser.add_argument(\n \"--runner\",\n type=str,\n default=\"d2go.runner.GeneralizedRCNNRunner\",\n help=\"Full class name, i.e. (package.)module.class\",\n )\n parser.add_argument(\n \"--config-file\",\n help=\"path to config file\",\n default=\"\",\n required=requires_config_file,\n metavar=\"FILE\",\n )\n parser.add_argument(\n \"--output-dir\",\n help=\"When given, this will override the OUTPUT_DIR in the config-file\",\n required=requires_output_dir,\n default=None,\n type=str,\n )\n parser.add_argument(\n \"opts\",\n help=\"Modify config options using the command-line\",\n default=None,\n nargs=argparse.REMAINDER,\n )\n\n if distributed:\n parser.add_argument(\n \"--num-processes\", type=int, default=1, help=\"number of gpus per machine\"\n )\n parser.add_argument(\"--num-machines\", type=int, default=1)\n parser.add_argument(\n \"--machine-rank\",\n type=int,\n default=0,\n help=\"the rank of this machine (unique per machine)\",\n )\n parser.add_argument(\n \"--dist-url\", default=\"file:///tmp/d2go_dist_file_{}\".format(time.time())\n )\n parser.add_argument(\"--dist-backend\", type=str, default=\"NCCL\")\n\n if not requires_config_file:\n # NOTE if not passing yaml file, user should explicitly set the\n # following args, and use `opts` for non-common usecase.\n parser.add_argument(\n \"--datasets\",\n type=str,\n nargs=\"+\",\n required=True,\n help=\"cfg.DATASETS.TEST\",\n )\n parser.add_argument(\n \"--min_size\",\n type=int,\n required=True,\n help=\"cfg.INPUT.MIN_SIZE_TEST\",\n )\n parser.add_argument(\n \"--max_size\",\n type=int,\n required=True,\n help=\"cfg.INPUT.MAX_SIZE_TEST\",\n )\n return parser\n\n return parser\n\n\ndef create_cfg_from_cli_args(args, default_cfg):\n \"\"\"\n Instead of loading from defaults.py, this binary only includes necessary\n configs building from scratch, and overrides them from args. There're two\n levels of config:\n _C: the config system used by this binary, which is a sub-set of training\n config, override by configurable_cfg. It can also be override by\n args.opts for convinience.\n configurable_cfg: common configs that user should explicitly specify\n in the args.\n \"\"\"\n\n _C = CN()\n _C.INPUT = default_cfg.INPUT\n _C.DATASETS = default_cfg.DATASETS\n _C.DATALOADER = default_cfg.DATALOADER\n _C.TEST = default_cfg.TEST\n if hasattr(default_cfg, \"D2GO_DATA\"):\n _C.D2GO_DATA = default_cfg.D2GO_DATA\n if hasattr(default_cfg, \"TENSORBOARD\"):\n _C.TENSORBOARD = default_cfg.TENSORBOARD\n\n # NOTE configs below might not be necessary, but must add to make code work\n _C.MODEL = CN()\n _C.MODEL.META_ARCHITECTURE = default_cfg.MODEL.META_ARCHITECTURE\n _C.MODEL.MASK_ON = default_cfg.MODEL.MASK_ON\n _C.MODEL.KEYPOINT_ON = default_cfg.MODEL.KEYPOINT_ON\n _C.MODEL.LOAD_PROPOSALS = default_cfg.MODEL.LOAD_PROPOSALS\n assert _C.MODEL.LOAD_PROPOSALS is False, \"caffe2 model doesn't support\"\n\n _C.OUTPUT_DIR = args.output_dir\n\n configurable_cfg = [\n \"DATASETS.TEST\",\n args.datasets,\n \"INPUT.MIN_SIZE_TEST\",\n args.min_size,\n \"INPUT.MAX_SIZE_TEST\",\n args.max_size,\n ]\n\n cfg = _C.clone()\n cfg.merge_from_list(configurable_cfg)\n cfg.merge_from_list(args.opts)\n\n return cfg\n\n\ndef prepare_for_launch(args):\n \"\"\"\n Load config, figure out working directory, create runner.\n - when args.config_file is empty, returned cfg will be the default one\n - returned output_dir will always be non empty, args.output_dir has higher\n priority than cfg.OUTPUT_DIR.\n \"\"\"\n print(args)\n runner = create_runner(args.runner)\n\n cfg = runner.get_default_cfg()\n if args.config_file:\n with PathManager.open(reroute_config_path(args.config_file), \"r\") as f:\n print(\"Loaded config file {}:\\n{}\".format(args.config_file, f.read()))\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n else:\n cfg = create_cfg_from_cli_args(args, default_cfg=cfg)\n cfg.freeze()\n\n assert args.output_dir or args.config_file\n output_dir = args.output_dir or cfg.OUTPUT_DIR\n return cfg, output_dir, runner\n\n\ndef setup_after_launch(cfg, output_dir, runner):\n \"\"\"\n Set things up after entering DDP, including\n - creating working directory\n - setting up logger\n - logging environment\n - initializing runner\n \"\"\"\n create_dir_on_global_main_process(output_dir)\n comm.synchronize()\n setup_loggers(output_dir)\n cfg.freeze()\n if cfg.OUTPUT_DIR != output_dir:\n with temp_defrost(cfg):\n logger.warning(\n \"Override cfg.OUTPUT_DIR ({}) to be the same as output_dir {}\".format(\n cfg.OUTPUT_DIR, output_dir\n )\n )\n cfg.OUTPUT_DIR = output_dir\n logger.info(\"Initializing runner ...\")\n runner = initialize_runner(runner, cfg)\n\n log_info(cfg, runner)\n dump_cfg(cfg, os.path.join(output_dir, \"config.yaml\"))\n\n auto_scale_world_size(cfg, new_world_size=comm.get_world_size())\n\n\n@run_once()\ndef setup_loggers(output_dir, color=None):\n if not color:\n color = get_launch_environment() == \"local\"\n\n d2_logger = setup_logger(\n output_dir,\n distributed_rank=comm.get_rank(),\n color=color,\n name=\"detectron2\",\n abbrev_name=\"d2\",\n )\n fvcore_logger = setup_logger(\n output_dir,\n distributed_rank=comm.get_rank(),\n color=color,\n name=\"fvcore\",\n )\n d2go_logger = setup_logger(\n output_dir,\n distributed_rank=comm.get_rank(),\n color=color,\n name=\"d2go\",\n abbrev_name=\"d2go\",\n )\n mobile_cv_logger = setup_logger(\n output_dir,\n distributed_rank=comm.get_rank(),\n color=color,\n name=\"mobile_cv\",\n abbrev_name=\"mobile_cv\",\n )\n\n # NOTE: all above loggers have FileHandler pointing to the same file as d2_logger.\n # Those files are opened upon creation, but it seems fine in 'a' mode.\n\n # NOTE: the root logger might has been configured by other applications,\n # since this already sub-top level, just don't propagate to root.\n d2_logger.propagate = False\n fvcore_logger.propagate = False\n d2go_logger.propagate = False\n mobile_cv_logger.propagate = False\n\n\ndef log_info(cfg, runner):\n num_processes = get_num_processes_per_machine()\n logger.info(\n \"Using {} processes per machine. Rank of current process: {}\".format(\n num_processes, comm.get_rank()\n )\n )\n logger.info(\"Environment info:\\n\" + collect_env_info())\n logger.info(\"Running with full config:\\n{}\".format(cfg))\n logger.info(\"Running with runner: {}\".format(runner))\n\n\ndef dump_cfg(cfg, path):\n if comm.is_main_process():\n with PathManager.open(path, \"w\") as f:\n f.write(cfg.dump())\n logger.info(\"Full config saved to {}\".format(path))\n\n\ndef create_dir_on_local_main_process(dir):\n if get_local_rank() == 0 and dir:\n PathManager.mkdirs(dir)\n\n\ndef create_dir_on_global_main_process(dir):\n if comm.get_rank() == 0 and dir:\n PathManager.mkdirs(dir)\n\n\ndef initialize_runner(runner, cfg):\n runner = runner or GeneralizedRCNNRunner()\n runner._initialize(cfg)\n return runner\n\n\ndef caffe2_global_init(logging_print_net_summary=0, num_threads=None):\n if num_threads is None:\n if get_num_processes_per_machine() > 1:\n # by default use single thread when DDP with multiple processes\n num_threads = 1\n else:\n # GlobalInit will clean PyTorch's num_threads and set it to 1,\n # thus keep PyTorch's default value to make it truly default.\n num_threads = torch.get_num_threads()\n\n if not get_local_rank() == 0:\n logging_print_net_summary = 0 # only enable for local main process\n\n from caffe2.python import workspace\n\n workspace.GlobalInit(\n [\n \"caffe2\",\n \"--caffe2_log_level=2\",\n \"--caffe2_logging_print_net_summary={}\".format(logging_print_net_summary),\n \"--caffe2_omp_num_threads={}\".format(num_threads),\n \"--caffe2_mkl_num_threads={}\".format(num_threads),\n ]\n )\n logger.info(\"Using {} threads after GlobalInit\".format(torch.get_num_threads()))\n\n\ndef post_mortem_if_fail_for_main(main_func):\n def new_main_func(cfg, output_dir, *args, **kwargs):\n pdb_ = (\n MultiprocessingPdb(FolderLock(output_dir))\n if comm.get_world_size() > 1\n else None # fallback to use normal pdb for single process\n )\n return post_mortem_if_fail(pdb_)(main_func)(cfg, output_dir, *args, **kwargs)\n\n return PicklableWrapper(new_main_func)\n", "#!/usr/bin/env python3\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\n\nimport logging\nfrom collections import OrderedDict\n\nimport numpy as np\nfrom detectron2.evaluation import DatasetEvaluator\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass PredictionCountEvaluator(DatasetEvaluator):\n \"\"\"\n Custom Detectron2 evaluator class to simply count the number of predictions\n e.g. on a dataset of hard negatives where there are no annotations, and\n summarize results into interpretable metrics.\n\n See class pattern from detectron2.evaluation.evaluator.py, especially\n :func:`inference_on_dataset` to see how this class will be called.\n \"\"\"\n\n def reset(self):\n self.prediction_counts = []\n self.confidence_scores = []\n\n def process(self, inputs, outputs):\n \"\"\"\n Params:\n input: the input that's used to call the model.\n output: the return value of `model(output)`\n \"\"\"\n # outputs format:\n # [{\n # \"instances\": Instances(\n # num_instances=88,\n # fields=[scores = tensor([list of len num_instances])]\n # ), ...\n # },\n # ... other dicts\n # ]\n for output_dict in outputs:\n instances = output_dict[\"instances\"]\n self.prediction_counts.append(len(instances))\n self.confidence_scores.extend(instances.get(\"scores\").tolist())\n\n def evaluate(self):\n \"\"\"\n Returns:\n In detectron2.tools.train_net.py, following format expected:\n dict:\n * key: the name of the task (e.g., bbox)\n * value: a dict of {metric name: score}, e.g.: {\"AP50\": 80}\n \"\"\"\n mpi = np.mean(self.prediction_counts)\n mcp = np.mean(self.confidence_scores)\n output_metrics = OrderedDict(\n {\n \"false_positives\": {\n \"predictions_per_image\": mpi,\n \"confidence_per_prediction\": mcp,\n }\n }\n )\n logger.info(f\"mean predictions per image: {mpi}\")\n logger.info(f\"mean confidence per prediction: {mcp}\")\n return output_metrics\n" ]
[ [ "torch.get_num_threads" ], [ "numpy.mean" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
petersvenningsson/radar-Bayesian-human-motion
[ "728db0f39c107faccf9d711670177aac74456e3f", "728db0f39c107faccf9d711670177aac74456e3f" ]
[ "train.py", "pytrack/simulation.py" ]
[ "import argparse\n\nimport numpy as np\nfrom sklearn.metrics import accuracy_score, jaccard_score, balanced_accuracy_score\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport pandas as pd\n\nimport dataloader\nimport track\nfrom classifiers import ObservationsConditionsClassifier\nfrom classifiers import ClassifierComposition\n\nnp.seterr(all='ignore')\n\nclass_set = 9\nn_pca_components = 20\n\ndef train():\n global parsed_args\n test_sequence = 'Mix'\n measurement_costs = [0.1*i for i in range(0,15)]\n measurement_costs.extend([0.01*i for i in range(1, 15)])\n\n loader = dataloader.DataLoaderSpectrogram()\n features = [f'PC_{i}' for i in range(n_pca_components)]\n\n classifiers = [\n (ObservationsConditionsClassifier(features, discriminant_model='calibrated_Gaussian', n_angle_bins=8), 'Conditioned on $\\phi$', 'Isotonic calibration'),\n (ObservationsConditionsClassifier(features, discriminant_model='Gaussian', n_angle_bins=8), 'Conditioned on $\\phi$','Uncalibrated'),\n (ClassifierComposition(features, discriminant_model='Gaussian'), 'Not conditioned on $\\phi$', 'Uncalibrated'),\n (ClassifierComposition(features, discriminant_model='calibrated_Gaussian'), 'Not conditioned on $\\phi$', 'Isotonic calibration'),\n ]\n\n rows = []\n for cost in measurement_costs:\n for i_model, (classifier, observation_condition, discriminant_model) in enumerate(classifiers):\n\n if parsed_args.rebuild:\n track.state_estimation(load_directory = './data/dataset/RD')\n dataset_path = r'C:\\Users\\peter\\Documents\\pulseON'\n loader = dataloader.DataLoaderSpectrogram()\n loader.build(dataset_path,'PCA')\n else:\n loader.load('./data/dataset_df')\n\n result_df = evaluate_classifier(classifier, loader.df, test_persons = loader.df.person.unique(), test_sequence = test_sequence, measurement_cost = cost)\n\n predictions = result_df.loc[result_df['sequence_type'] == test_sequence]['prediction'].to_numpy()\n lables = result_df.loc[result_df['sequence_type'] == test_sequence]['lable'].to_numpy()\n accuracy = accuracy_score(lables, predictions)\n\n rows.append({\n 'Accuracy': accuracy, 'Balanced accuracy': balanced_accuracy_score(lables, predictions), 'Macro-averaged Jaccard index': jaccard_score(lables, predictions, average='macro'),\n 'Observation conditions': observation_condition, 'Calibration': discriminant_model, 'Cost': cost,\n 'result_df': result_df, 'model_index': i_model,\n })\n \n sns.lineplot(data = pd.DataFrame(rows), x = 'Cost', y = 'Accuracy', style = 'Observation conditions', hue = 'Calibration')\n plt.tight_layout()\n plt.show()\n\n\ndef evaluate_classifier(model, df, test_persons, measurement_cost, test_sequence = 'Mix', prior = [1/class_set for i in range(class_set)], render_seq=False):\n\n df['prediction'] = -6666\n for test_person in test_persons:\n\n training_df = df.loc[df['person'] != test_person]\n test_df = df.loc[(df['person'] == test_person) & (df['sequence_type'] == test_sequence)].copy()\n\n transition_matrix = estimate_transition_matrix(\n training_df.loc[training_df['sequence_type'] == 'Mix']\n )\n\n model.fit(training_df)\n for j, file in enumerate(test_df.file_index.unique()):\n print(f'File {j}/{len(test_df.file_index.unique())}')\n\n seq_df = test_df.loc[test_df['file_index'] == file].copy()\n seq_df = predict_sequence(model, seq_df, transition_matrix, measurement_cost)\n \n if render_seq:\n render.render_classification_sequence(seq_df)\n\n df.loc[seq_df.index, 'belief'] = seq_df['belief']\n df.loc[seq_df.index, 'prediction'] = seq_df['prediction']\n df.loc[seq_df.index, 'Selected'] = seq_df['Selected']\n\n return df\n\n\ndef predict_sequence(model, df, transition_matrix, measurement_cost, prior=[1/class_set for _ in range(class_set)]):\n belief = np.reshape(prior, (class_set, 1))\n\n for time in np.sort(df.time.unique()):\n df_step = df[df['time'] == time].copy()\n\n if measurement_cost:\n selected_sensors = information_selection(df_step, model, belief, measurement_cost)\n else:\n selected_sensors = df_step.index\n df.loc[selected_sensors, 'Selected'] = True\n\n for i, row in df_step.loc[selected_sensors].iterrows():\n row = row.to_frame().transpose()\n prop_likelihood = model.predict_proba(row)\n posterior = prop_likelihood[0, :, np.newaxis] * belief\n posterior = posterior/(posterior.sum())\n belief = posterior\n \n # save prediction\n df['belief'] = np.nan\n df['belief'] = df['belief'].astype(object)\n for index in df_step.index:\n df.loc[index, 'belief'] = [belief]\n df.loc[index ,'prediction'] = belief.argmax() + 1\n\n # Transition step\n belief = transition_matrix @ np.reshape(belief, (class_set,1))\n\n return df\n\n\ndef information_selection(df, model, belief, measurement_cost):\n\n # Calculate information and sort indices by information\n df['information'] = df.apply(lambda row: model.information(belief, [row['predicted_angle']]), axis=1)\n potential_sensors = df.sort_values('information').index.to_list()\n\n selected_sensors = []\n sensor_utility = {0:[]}\n while potential_sensors:\n selected_sensors.append(potential_sensors.pop())\n\n information = model.information(belief, sensors=df.loc[selected_sensors]['predicted_angle'].to_list())\n utility = information - measurement_cost*len(selected_sensors)\n\n sensor_utility[utility] = selected_sensors[:]\n\n return sensor_utility[np.max(list(sensor_utility.keys()))]\n\n\ndef estimate_transition_matrix(df):\n transition_count = np.zeros((class_set,class_set))\n df = df.loc[df['radar'] == df.radar.unique()[0]]\n sequences = df['file_index'].unique()\n for sequence_index in sequences:\n df_seq = df.loc[df['file_index'] == sequence_index].sort_values('time').reset_index(drop=True)\n\n previous_state = None\n for i, row in df_seq.iterrows():\n state = row['lable']\n if not previous_state:\n previous_state = state\n continue\n transition_count[state - 1, previous_state - 1] += 1 \n previous_state = state\n transition_matrix = transition_count/transition_count.sum(axis=0,keepdims=1)\n transition_matrix = transition_matrix/transition_matrix.sum(axis=0,keepdims=1)\n\n return transition_matrix\n\n\ndef load_options():\n global parsed_args\n parser = argparse.ArgumentParser(description='Entry point to fit and evaluate\\\n a Bayesian model of human motion',\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('--rebuild', dest='rebuild', action='store_true')\n parser.add_argument('--no-rebuild', dest='rebuild', action='store_false')\n parser.set_defaults(rebuild=False)\n parsed_args = parser.parse_args()\n\n\nif __name__ == '__main__':\n load_options()\n train()", "import numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom . import processmodels\nfrom . import utils\nfrom . import measmodels\nfrom . import render\nfrom .density import Gaussian\nfrom . import radar_configuration\n\n\ndef simulate_ct_radar():\n time_steps = 50\n process_model = processmodels.CoordinatedTurnModel( T = 0.2, sigma_velocity = 1, sigma_turnrate = 30*np.pi/180)\n\n # Define ground truth movement\n left_turn = utils.generate_ground_truth(process_model, initial_state = np.array([[-2],[0],[1.5],[np.pi/3],[-0.9]]), n_steps=int(time_steps - 20))\n right_turn_initial = left_turn[-1]\n right_turn_initial[-1] = -2\n right_turn = utils.generate_ground_truth(process_model, initial_state = right_turn_initial, n_steps=int(10))\n straight_initial = right_turn[-1]\n straight_initial[-1] = 0\n straight = utils.generate_ground_truth(process_model, initial_state = straight_initial, n_steps=int(10))\n ground_truth = np.vstack((left_turn, right_turn, straight))\n\n sensors = []\n sensor_measurements = []\n\n # Define sensors\n sensor_positions = radar_configuration.pulseON_positions\n\n for position in sensor_positions:\n sensors.append(measmodels.RangeDopplerMeasurmentModel(sensor_bias = position, sigma_position=0.3, sigma_rangerate=0.1, state_space = 'CT'))\n\n for sensor in sensors:\n sensor_measurements.append(utils.measurement_sequence(sensor, ground_truth))\n\n state = Gaussian(mean = np.array([[0],[0],[0],[0],[0]]), covariance = np.diag([50,50,50,2,2]))\n state_history = []\n for t in range(time_steps):\n for sensor, measurements in zip(sensors,sensor_measurements):\n state = Gaussian.update(state, measurements[t], sensor)\n state_history.append({'updated_state': state})\n state = Gaussian.predict(state, process_model)\n\n figure = render.base_figure()\n figure = render.render_ground_truth(figure, ground_truth, process_model)\n figure = render.render_estimate(figure, state_history, render_cov=True)\n figure = render.render_estimates_quiver(figure, state_history, process_model)\n\n for position in sensor_positions:\n plt.plot(position[0], position[1], marker = 'H', color = 'black', figure = figure)\n \n plt.axis('equal')\n plt.show()\n\n\nif __name__ == '__main__':\n simulate_ct_radar()" ]
[ [ "matplotlib.pyplot.tight_layout", "sklearn.metrics.jaccard_score", "numpy.reshape", "sklearn.metrics.balanced_accuracy_score", "pandas.DataFrame", "numpy.seterr", "matplotlib.pyplot.show", "numpy.zeros", "sklearn.metrics.accuracy_score" ], [ "numpy.diag", "numpy.vstack", "matplotlib.pyplot.plot", "matplotlib.pyplot.axis", "numpy.array", "matplotlib.pyplot.show" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
cpiker/condaCDF
[ "58f0c15fa387798f49c0372cc33d3639d997112d" ]
[ "pycdf/__init__.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\ndas developers note:\n\n This a is modification of the original SpacePy pycdf package. All\n refereneces to the greater spacepy package have been removed to create\n a small standalone module.\n \n --cwp 2018-10-18\n \n The libcdf.so location code has been changed to find the version installed\n in anaconda.\n \n --cwp 2020-04-06\n \n\nThis package provides a Python interface to the Common Data Format (CDF)\nlibrary used for many NASA missions, available at http://cdf.gsfc.nasa.gov/.\nIt is targeted at Python 2.6+ and should work without change on either\nPython 2 or Python 3.\n\nThe interface is intended to be 'pythonic' rather than reproducing the\nC interface. To open or close a CDF and access its variables, see the :class:`CDF`\nclass. Accessing data within the variables is via the :class:`Var`\nclass. The :data:`lib` object provides access to some routines\nthat affect the functionality of the library in general. The\n:mod:`~pycdf.const` module contains constants useful for accessing\nthe underlying library.\n\nAuthors: Jon Niehof\n\nInstitution: University of New Hampshire\n\nContact: [email protected]\n\n\nCopyright 2010-2015 Los Alamos National Security, LLC.\n\n\"\"\"\n\n__contact__ = 'Jon Niehof, [email protected]'\n\ntry:\n from collections.abc import MutableMapping, MutableSequence\nexcept ImportError:\n from collections import MutableMapping, MutableSequence\nimport ctypes\nimport ctypes.util\nimport datetime\nimport operator\nimport os\nimport os.path\nimport shutil\nimport sys\nimport tempfile\nimport warnings\nimport weakref\n\nimport numpy\nimport numpy.ma\n\n#Import const AFTER library loaded, so failed load doesn't leave half-imported\n#from . import const\n\ntry:\n str_classes = (str, bytes, unicode)\nexcept NameError:\n str_classes = (str, bytes)\n\n\nclass Library(object):\n \"\"\"\n Abstraction of the base CDF C library and its state.\n\n Not normally intended for end-user use. An instance of this class\n is created at package load time as the :data:`~pycdf.lib` variable, providing\n access to the underlying C library if necessary. The CDF library itself\n is described in section 2.1 of the CDF user's guide, as well as the CDF\n C reference manual.\n\n Calling the C library directly requires knowledge of\n :mod:`ctypes`.\n\n Instantiating this object loads the C library, see :doc:`/pycdf` docs\n for details.\n\n .. autosummary::\n\n ~Library.call\n ~Library.check_status\n ~Library.datetime_to_epoch\n ~Library.datetime_to_epoch16\n ~Library.datetime_to_tt2000\n ~Library.epoch_to_datetime\n ~Library.epoch_to_epoch16\n ~Library.epoch_to_num\n ~Library.epoch_to_tt2000\n ~Library.epoch16_to_datetime\n ~Library.epoch16_to_epoch\n ~Library.epoch16_to_tt2000\n ~Library.set_backward\n supports_int8\n ~Library.tt2000_to_datetime\n ~Library.tt2000_to_epoch\n ~Library.tt2000_to_epoch16\n v_datetime_to_epoch\n v_datetime_to_epoch16\n v_datetime_to_tt2000\n v_epoch_to_datetime\n v_epoch_to_tt2000\n v_epoch16_to_datetime\n v_epoch16_to_tt2000\n v_tt2000_to_datetime\n v_tt2000_to_epoch\n v_tt2000_to_epoch16\n libpath\n version\n\n .. automethod:: call\n .. automethod:: check_status\n .. automethod:: datetime_to_epoch\n .. automethod:: datetime_to_epoch16\n .. automethod:: datetime_to_tt2000\n .. automethod:: epoch_to_datetime\n .. automethod:: epoch_to_epoch16\n .. automethod:: epoch_to_num\n .. automethod:: epoch_to_tt2000\n .. automethod:: epoch16_to_datetime\n .. automethod:: epoch16_to_epoch\n .. automethod:: epoch16_to_tt2000\n .. automethod:: set_backward\n\n .. attribute:: supports_int8\n\n True if this library supports INT8 and TIME_TT2000 types; else False.\n\n .. automethod:: tt2000_to_datetime\n .. automethod:: tt2000_to_epoch\n .. automethod:: tt2000_to_epoch16\n\n .. method:: v_datetime_to_epoch(datetime)\n \n A vectorized version of :meth:`datetime_to_epoch` which takes a\n numpy array of datetimes as input and returns an array of epochs.\n\n .. method:: v_datetime_to_epoch16(datetime)\n \n A vectorized version of :meth:`datetime_to_epoch16` which takes a\n numpy array of datetimes as input and returns an array of epoch16.\n\n .. method:: v_datetime_to_tt2000(datetime)\n \n A vectorized version of :meth:`datetime_to_tt2000` which takes a\n numpy array of datetimes as input and returns an array of TT2000.\n\n .. method:: v_epoch_to_datetime(epoch)\n \n A vectorized version of :meth:`epoch_to_datetime` which takes a\n numpy array of epochs as input and returns an array of datetimes.\n\n .. method:: v_epoch_to_tt2000(epoch)\n \n A vectorized version of :meth:`epoch_to_tt2000` which takes a\n numpy array of epochs as input and returns an array of tt2000s.\n\n .. method:: v_epoch16_to_datetime(epoch0, epoch1)\n \n A vectorized version of :meth:`epoch16_to_datetime` which takes\n a numpy array of epoch16 as input and returns an array of datetimes.\n An epoch16 is a pair of doubles; the input array's last dimension\n must be two (and the returned array will have one fewer dimension).\n\n .. method:: v_epoch16_to_tt2000(epoch16)\n \n A vectorized version of :meth:`epoch16_to_tt2000` which takes\n a numpy array of epoch16 as input and returns an array of tt2000s.\n An epoch16 is a pair of doubles; the input array's last dimension\n must be two (and the returned array will have one fewer dimension).\n\n .. method:: v_tt2000_to_datetime(tt2000)\n \n A vectorized version of :meth:`tt2000_to_datetime` which takes\n a numpy array of tt2000 as input and returns an array of datetimes.\n\n .. method:: v_tt2000_to_epoch(tt2000)\n \n A vectorized version of :meth:`tt2000_to_epoch` which takes\n a numpy array of tt2000 as input and returns an array of epochs.\n\n .. method:: v_tt2000_to_epoch16(tt2000)\n \n A vectorized version of :meth:`tt2000_to_epoch16` which takes\n a numpy array of tt2000 as input and returns an array of epoch16.\n\n .. attribute:: libpath\n\n The path where pycdf found the CDF C library, potentially useful in\n debugging. If this contains just the name of a file (with no path\n information), then the system linker found the library for pycdf.\n On Linux, ``ldconfig -p`` may be useful for displaying the system's\n library resolution.\n\n .. attribute:: version\n\n Version of the CDF library, (version, release, increment, subincrement)\n \"\"\"\n def __init__(self, libpath=None, library=None):\n \"\"\"Load the CDF C library.\n\n Searches for the library in the order:\n 1. Appropriately-named file in CDF_LIB\n 2. Appropriately-named file in CDF_BASE\n 3. Standard library search path\n @raise CDFError: BAD_DATA_TYPE if can't map types properly\n \"\"\"\n\n if not 'CDF_TMP' in os.environ:\n os.environ['CDF_TMP'] = tempfile.gettempdir()\n\n if not library:\n if not libpath:\n self.libpath, self._library = self._find_lib()\n if self._library is None:\n raise Exception((\n 'Cannot load CDF C library; checked {0}. '\n 'Try \\'os.environ[\"CDF_LIB\"] = library_directory\\' '\n 'before import.').format(', '.join(self.libpath)))\n else:\n self._library = ctypes.CDLL(libpath)\n self.libpath = libpath\n else:\n self._library = library\n self.libpath = libpath\n self._library.CDFlib.restype = ctypes.c_long #commonly used, so set it up here\n self._library.EPOCHbreakdown.restype = ctypes.c_long\n self._library.computeEPOCH.restype = ctypes.c_double\n self._library.computeEPOCH.argtypes = [ctypes.c_long] * 7\n self._library.computeEPOCH16.restype = ctypes.c_double\n self._library.computeEPOCH16.argtypes = [ctypes.c_long] * 10 + \\\n [ctypes.POINTER(ctypes.c_double * 2)]\n if hasattr(self._library, 'CDFsetFileBackward'):\n self._library.CDFsetFileBackward.restype = None\n self._library.CDFsetFileBackward.argtypes = [ctypes.c_long]\n #Map old name to the 3.7.1+ name\n if not hasattr(self._library, 'computeTT2000') \\\n and hasattr(self._library, 'CDF_TT2000_from_UTC_parts'):\n self._library.computeTT2000 \\\n = self._library.CDF_TT2000_from_UTC_parts\n if hasattr(self._library, 'computeTT2000'):\n self._library.computeTT2000.restype = ctypes.c_longlong\n self._library.computeTT2000.argtypes = \\\n [ctypes.c_double] *9\n #Map old name to the 3.7.1+ name\n if not hasattr(self._library, 'breakdownTT2000') \\\n and hasattr(self._library, 'CDF_TT2000_to_UTC_parts'):\n self._library.breakdownTT2000 \\\n = self._library.CDF_TT2000_to_UTC_parts\n if hasattr(self._library, 'breakdownTT2000'):\n self._library.breakdownTT2000.restype = None\n self._library.breakdownTT2000.argtypes = \\\n [ctypes.c_longlong] + [ctypes.POINTER(ctypes.c_double)] * 9\n if hasattr(self._library, 'CDF_TT2000_to_UTC_EPOCH'):\n self._library.CDF_TT2000_to_UTC_EPOCH.restype = ctypes.c_double\n self._library.CDF_TT2000_to_UTC_EPOCH.argtypes = [ctypes.c_longlong]\n if hasattr(self._library, 'CDF_TT2000_from_UTC_EPOCH'):\n self._library.CDF_TT2000_from_UTC_EPOCH.restype = ctypes.c_longlong\n self._library.CDF_TT2000_from_UTC_EPOCH.argtypes = [ctypes.c_double]\n if hasattr(self._library, 'CDF_TT2000_to_UTC_EPOCH16'):\n self._library.CDF_TT2000_to_UTC_EPOCH16.restype = ctypes.c_double\n self._library.CDF_TT2000_to_UTC_EPOCH16.argtypes = \\\n [ctypes.c_longlong, ctypes.POINTER(ctypes.c_double * 2)]\n if hasattr(self._library, 'CDF_TT2000_from_UTC_EPOCH16'):\n self._library.CDF_TT2000_from_UTC_EPOCH16.restype = \\\n ctypes.c_longlong\n self._library.CDF_TT2000_from_UTC_EPOCH16.argtypes = \\\n [ctypes.POINTER(ctypes.c_double * 2)]\n\n #Get CDF version information\n ver = ctypes.c_long(0)\n rel = ctypes.c_long(0)\n inc = ctypes.c_long(0)\n sub = ctypes.c_char(b' ')\n self.call(const.GET_, const.LIB_VERSION_, ctypes.byref(ver),\n const.GET_, const.LIB_RELEASE_, ctypes.byref(rel),\n const.GET_, const.LIB_INCREMENT_, ctypes.byref(inc),\n const.GET_, const.LIB_subINCREMENT_, ctypes.byref(sub))\n ver = ver.value\n rel = rel.value\n inc = inc.value\n sub = sub.value\n self.version = (ver, rel, inc, sub)\n self._del_middle_rec_bug = ver < 3 or (ver == 3 and\n (rel < 4 or\n (rel == 4 and inc < 1)))\n self.supports_int8 = (ver > 3 or (ver == 3 and rel >=4))\n\n self.cdftypenames = {const.CDF_BYTE.value: 'CDF_BYTE',\n const.CDF_CHAR.value: 'CDF_CHAR',\n const.CDF_INT1.value: 'CDF_INT1',\n const.CDF_UCHAR.value: 'CDF_UCHAR',\n const.CDF_UINT1.value: 'CDF_UINT1',\n const.CDF_INT2.value: 'CDF_INT2',\n const.CDF_UINT2.value: 'CDF_UINT2',\n const.CDF_INT4.value: 'CDF_INT4',\n const.CDF_UINT4.value: 'CDF_UINT4',\n const.CDF_INT8.value: 'CDF_INT8',\n const.CDF_FLOAT.value: 'CDF_FLOAT',\n const.CDF_REAL4.value: 'CDF_REAL4',\n const.CDF_DOUBLE.value: 'CDF_DOUBLE',\n const.CDF_REAL8.value: 'CDF_REAL8',\n const.CDF_EPOCH.value: 'CDF_EPOCH',\n const.CDF_EPOCH16.value: 'CDF_EPOCH16',\n const.CDF_TIME_TT2000.value: 'CDF_TIME_TT2000',\n }\n self.numpytypedict = {const.CDF_BYTE.value: numpy.int8,\n const.CDF_CHAR.value: numpy.int8,\n const.CDF_INT1.value: numpy.int8,\n const.CDF_UCHAR.value: numpy.uint8,\n const.CDF_UINT1.value: numpy.uint8,\n const.CDF_INT2.value: numpy.int16,\n const.CDF_UINT2.value: numpy.uint16,\n const.CDF_INT4.value: numpy.int32,\n const.CDF_UINT4.value: numpy.uint32,\n const.CDF_INT8.value: numpy.int64,\n const.CDF_FLOAT.value: numpy.float32,\n const.CDF_REAL4.value: numpy.float32,\n const.CDF_DOUBLE.value: numpy.float64,\n const.CDF_REAL8.value: numpy.float64,\n const.CDF_EPOCH.value: numpy.float64,\n const.CDF_EPOCH16.value:\n numpy.dtype((numpy.float64, 2)),\n const.CDF_TIME_TT2000.value: numpy.int64,\n }\n self.timetypes = [const.CDF_EPOCH.value,\n const.CDF_EPOCH16.value,\n const.CDF_TIME_TT2000.value]\n if not self.supports_int8:\n del self.cdftypenames[const.CDF_INT8.value]\n del self.numpytypedict[const.CDF_INT8.value]\n del self.cdftypenames[const.CDF_TIME_TT2000.value]\n del self.numpytypedict[const.CDF_TIME_TT2000.value]\n elif sys.platform.startswith('linux') \\\n and os.uname()[4].startswith('arm') \\\n and hasattr(self._library, 'computeTT2000') \\\n and self._library.computeTT2000(\n 2010, 1, 1, 0, 0, 0, 0, 0, 0) != 315576066184000000:\n #TT2000 call failed, so probably need to type-pun\n #double arguments to variadic functions.\n #Calling convention for non-variadic functions with floats\n #is unique, but convention for ints is same as variadic.\n #So type-pun arguments to integers to force that calling\n #convention.\n if ctypes.sizeof(ctypes.c_longlong) != \\\n ctypes.sizeof(ctypes.c_double):\n warnings.warn('ARM with unknown type sizes; '\n 'TT2000 functions will not work.')\n else:\n self._library.computeTT2000.argtypes = \\\n [ctypes.c_longlong] * 9\n c_ll_p = ctypes.POINTER(ctypes.c_longlong)\n if self._library.computeTT2000(\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n 2010)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n 1)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n 1)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n 0)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n 0)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n 0)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n 0)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n 0)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n 0)), c_ll_p).contents) != 315576066184000000:\n warnings.warn('ARM with unknown calling convention; '\n 'TT2000 functions will not work.')\n self.datetime_to_tt2000 = self._datetime_to_tt2000_typepunned\n\n v_epoch16_to_datetime = numpy.frompyfunc(\n self.epoch16_to_datetime, 2, 1)\n self.v_epoch16_to_datetime = \\\n lambda x: v_epoch16_to_datetime(x[..., 0], x[..., 1])\n self.v_epoch_to_datetime = numpy.frompyfunc(\n self.epoch_to_datetime, 1, 1)\n self.v_tt2000_to_datetime = numpy.frompyfunc(\n self.tt2000_to_datetime, 1, 1)\n self.v_datetime_to_epoch = numpy.vectorize(\n self.datetime_to_epoch, otypes=[numpy.float64])\n v_datetime_to_epoch16 = numpy.frompyfunc(\n self.datetime_to_epoch16, 1, 2)\n #frompyfunc returns a TUPLE of the returned values,\n #implicitly the 0th dimension. We want everything from one\n #call paired, so this rolls the 0th dimension to the last\n #(via the second-to-last)\n def _v_datetime_to_epoch16(x):\n retval = numpy.require(v_datetime_to_epoch16(x),\n dtype=numpy.float64)\n if len(retval.shape) > 1:\n return numpy.rollaxis(\n numpy.rollaxis(retval, 0, -1),\n -1, -2)\n else:\n return retval\n self.v_datetime_to_epoch16 = _v_datetime_to_epoch16\n self.v_datetime_to_tt2000 = numpy.vectorize(\n self.datetime_to_tt2000, otypes=[numpy.int64])\n self.v_epoch_to_tt2000 = numpy.vectorize(\n self.epoch_to_tt2000, otypes=[numpy.int64])\n self.v_tt2000_to_epoch = numpy.vectorize(\n self.tt2000_to_epoch, otypes=[numpy.float64])\n v_epoch16_to_tt2000 = numpy.frompyfunc(\n self.epoch16_to_tt2000, 2, 1)\n self.v_epoch16_to_tt2000 = \\\n lambda x: v_epoch16_to_tt2000(x[..., 0], x[..., 1])\n v_tt2000_to_epoch16 = numpy.frompyfunc(\n self.tt2000_to_epoch16, 1, 2)\n #frompyfunc returns a TUPLE of the returned values,\n #implicitly the 0th dimension. We want everything from one\n #call paired, so this rolls the 0th dimension to the last\n #(via the second-to-last)\n def _v_tt2000_to_epoch16(x):\n retval = numpy.require(v_tt2000_to_epoch16(x),\n dtype=numpy.float64)\n if len(retval.shape) > 1:\n return numpy.rollaxis(\n numpy.rollaxis(retval, 0, -1),\n -1, -2)\n else:\n return retval\n self.v_tt2000_to_epoch16 = _v_tt2000_to_epoch16\n if not self.supports_int8:\n self.datetime_to_tt2000 = self._bad_tt2000\n self.tt2000_to_datetime = self._bad_tt2000\n self.v_datetime_to_tt2000 = self._bad_tt2000\n self.v_tt2000_to_datetime = self._bad_tt2000\n self.epoch_to_tt2000 = self._bad_tt2000\n self.v_epoch_to_tt2000 = self._bad_tt2000\n self.tt2000_to_epoch = self._bad_tt2000\n self.v_tt2000_to_epoch = self._bad_tt2000\n self.epoch_16_to_tt2000 = self._bad_tt2000\n self.v_epoch16_to_tt2000 = self._bad_tt2000\n self.tt2000_to_epoch16 = self._bad_tt2000\n self.v_tt2000_to_epoch16 = self._bad_tt2000\n\n #Default to V2 CDF\n self.set_backward(True)\n\n @staticmethod\n def _find_lib():\n \"\"\"\n Search for the CDF library\n\n Searches in likely locations for CDF libraries and attempts to load\n them. Stops at first successful load and, if fails, reports all\n the files that were tried as libraries.\n\n Returns\n =======\n out : tuple\n This is either (path to library, loaded library)\n or, in the event of failure, (None, list of libraries tried)\n \"\"\"\n failed = []\n for libpath in Library._lib_paths():\n try:\n lib = ctypes.CDLL(libpath)\n except:\n failed.append(libpath)\n else:\n return libpath, lib\n return (failed, None)\n\n @staticmethod\n def _lib_paths():\n \"\"\"Find candidate paths for the CDF library\n\n Does not check that the library is actually in any particular directory,\n just returns a list of possible locations, in priority order.\n\n Returns\n =======\n out : generator of str\n paths that look like the CDF library\n \"\"\"\n #What the library might be named\n names = { 'win32': ['cdf.dll'],\n 'darwin': ['libcdf.dylib', 'cdf.dylib', 'libcdf.so'],\n 'linux2': ['libcdf.so'],\n 'linux': ['libcdf.so'],\n }\n names = names.get(sys.platform, ['libcdf.so'])\n \n #All existing CDF-library-like paths within a directory\n search_dir = lambda x: \\\n [os.path.join(x, fname) for fname in names\n if os.path.exists(os.path.join(x, fname))]\n \n # Only use anaconda locations...\n \n # Defined during builds ...\n if 'PREFIX' in os.environ:\n if sys.platform == 'win32':\n for p in search_dir(os.path.join(os.environ['PREFIX'], 'Library', 'bin')):\n yield p\n else:\n for p in search_dir(os.path.join(os.environ['PREFIX'], 'lib')):\n yield p\n \n # defined when conda is activated ...\n if 'CONDA_PREFIX' in os.environ:\n if sys.platform == 'win32':\n for p in search_dir(os.path.join(os.environ['CONDA_PREFIX'], 'Library', 'bin')):\n yield p\n else:\n for p in search_dir(os.path.join(os.environ['CONDA_PREFIX'], 'lib')):\n yield p\n \n # Special subdirectory for anaconda unix packages on windows\n if 'LIBRARY_BIN' in os.environ:\n for p in search_dir(os.environ['LIBRARY_BIN']):\n yield p\n \n ctypespath = ctypes.util.find_library(\n 'cdf.dll' if sys.platform == 'win32' else 'cdf')\n if ctypespath:\n yield ctypespath\n\n def check_status(self, status, ignore=()):\n \"\"\"\n Raise exception or warning based on return status of CDF call\n\n Parameters\n ==========\n status : int\n status returned by the C library\n\n Other Parameters\n ================\n ignore : sequence of ctypes.c_long\n CDF statuses to ignore. If any of these is returned by CDF library,\n any related warnings or exceptions will *not* be raised.\n (Default none).\n\n Raises\n ======\n CDFError : if status < CDF_WARN, indicating an error\n\n Warns\n =====\n CDFWarning : if CDF_WARN <= status < CDF_OK, indicating a warning.\n\n Returns\n =======\n out : int\n status (unchanged)\n \"\"\"\n if status == const.CDF_OK or status in ignore:\n return status\n if status < const.CDF_WARN:\n raise CDFError(status)\n else:\n warning = CDFWarning(status)\n warning.warn()\n return status\n\n def call(self, *args, **kwargs):\n \"\"\"\n Call the CDF internal interface\n\n Passes all parameters directly through to the CDFlib routine of the\n CDF library's C internal interface. Checks the return value with\n :meth:`check_status`.\n\n Terminal NULL is automatically added to args.\n\n Parameters\n ==========\n args : various, see :mod:`ctypes`\n Passed directly to the CDF library interface. Useful\n constants are defined in the :mod:`~pycdf.const` module.\n\n Other Parameters\n ================\n ignore : sequence of CDF statuses\n sequence of CDF statuses to ignore. If any of these\n is returned by CDF library, any related warnings or\n exceptions will *not* be raised.\n\n Returns\n =======\n out : int\n CDF status from the library\n\n Raises\n ======\n CDFError : if CDF library reports an error\n\n Warns\n =====\n CDFWarning : if CDF library reports a warning\n \"\"\"\n if 'ignore' in kwargs:\n return self.check_status(self._library.CDFlib(\n *(args + (const.NULL_, ))\n ), kwargs['ignore'])\n else:\n return self.check_status(self._library.CDFlib(\n *(args + (const.NULL_, ))\n ))\n\n def set_backward(self, backward=True):\n \"\"\"\n Set backward compatibility mode for new CDFs\n\n Unless backward compatible mode is set, CDF files created by\n the version 3 library can not be read by V2.\n\n Parameters\n ==========\n backward : boolean\n Set backward compatible mode if True; clear it if False.\n\n Raises\n ======\n ValueError : if backward=False and underlying CDF library is V2\n \"\"\"\n if self.version[0] < 3:\n if not backward:\n raise ValueError(\n 'Cannot disable backward-compatible mode for CDF version 2.')\n else:\n return\n self._library.CDFsetFileBackward(const.BACKWARDFILEon if backward\n else const.BACKWARDFILEoff)\n\n def epoch_to_datetime(self, epoch):\n \"\"\"\n Converts a CDF epoch value to a datetime\n\n Parameters\n ==========\n epoch : float\n epoch value from CDF\n\n Returns\n =======\n out : :class:`datetime.datetime`\n date and time corresponding to epoch. Invalid values are set to\n usual epoch invalid value, i.e. last moment of year 9999.\n\n See Also\n ========\n v_epoch_to_datetime\n \"\"\"\n yyyy = ctypes.c_long(0)\n mm = ctypes.c_long(0)\n dd = ctypes.c_long(0)\n hh = ctypes.c_long(0)\n min = ctypes.c_long(0)\n sec = ctypes.c_long(0)\n msec = ctypes.c_long(0)\n self._library.EPOCHbreakdown(ctypes.c_double(epoch),\n ctypes.byref(yyyy), ctypes.byref(mm),\n ctypes.byref(dd),\n ctypes.byref(hh), ctypes.byref(min),\n ctypes.byref(sec), ctypes.byref(msec))\n if yyyy.value <= 0:\n return datetime.datetime(9999, 12, 13, 23, 59, 59, 999000)\n else:\n return datetime.datetime(yyyy.value, mm.value, dd.value,\n hh.value, min.value, sec.value,\n msec.value * 1000)\n\n def datetime_to_epoch(self, dt):\n \"\"\"\n Converts a Python datetime to a CDF Epoch value\n\n Parameters\n ==========\n dt : :class:`datetime.datetime`\n date and time to convert\n\n Returns\n =======\n out : float\n epoch corresponding to dt\n\n See Also\n ========\n v_datetime_to_epoch\n \"\"\"\n if dt.tzinfo != None and dt.utcoffset() != None:\n dt = dt - dt.utcoffset()\n dt.replace(tzinfo=None)\n micro = dt.microsecond % 1000\n if micro >= 500 and dt.year < 9999:\n dt += datetime.timedelta(0, 0, 1000)\n return self._library.computeEPOCH(dt.year, dt.month, dt.day, dt.hour,\n dt.minute, dt.second,\n int(dt.microsecond / 1000))\n\n def epoch16_to_datetime(self, epoch0, epoch1):\n \"\"\"\n Converts a CDF epoch16 value to a datetime\n\n .. note::\n The call signature has changed since SpacePy 0.1.2. Formerly\n this method took a single argument with two values; now it\n requires two arguments (one for each value). To convert existing\n code, replace ``epoch16_to_datetime(epoch)`` with\n ``epoch16_to_datetime(*epoch)``.\n\n Parameters\n ==========\n epoch0 : float\n epoch16 value from CDF, first half\n epoch1 : float\n epoch16 value from CDF, second half\n\n Raises\n ======\n EpochError : if input invalid\n\n Returns\n =======\n out : :class:`datetime.datetime`\n date and time corresponding to epoch. Invalid values are set to\n usual epoch invalid value, i.e. last moment of year 9999.\n\n See Also\n ========\n v_epoch16_to_datetime\n \"\"\"\n yyyy = ctypes.c_long(0)\n mm = ctypes.c_long(0)\n dd = ctypes.c_long(0)\n hh = ctypes.c_long(0)\n min = ctypes.c_long(0)\n sec = ctypes.c_long(0)\n msec = ctypes.c_long(0)\n usec = ctypes.c_long(0)\n nsec = ctypes.c_long(0)\n psec = ctypes.c_long(0)\n self._library.EPOCH16breakdown((ctypes.c_double * 2)(epoch0, epoch1),\n ctypes.byref(yyyy), ctypes.byref(mm),\n ctypes.byref(dd),\n ctypes.byref(hh), ctypes.byref(min),\n ctypes.byref(sec), ctypes.byref(msec),\n ctypes.byref(usec), ctypes.byref(nsec),\n ctypes.byref(psec))\n if yyyy.value <= 0:\n return datetime.datetime(9999, 12, 13, 23, 59, 59, 999999)\n micro = int(float(msec.value) * 1000 + float(usec.value) +\n float(nsec.value) / 1000 + float(psec.value) / 1e6 + 0.5)\n if micro < 1000000:\n return datetime.datetime(yyyy.value, mm.value, dd.value,\n hh.value, min.value, sec.value,\n micro)\n else:\n add_sec = int(micro / 1000000)\n try:\n return datetime.datetime(yyyy.value, mm.value, dd.value,\n hh.value, min.value, sec.value,\n micro - add_sec * 1000000) + \\\n datetime.timedelta(seconds=add_sec)\n except OverflowError:\n return datetime.datetime(datetime.MAXYEAR, 12, 31,\n 23, 59, 59,\n 999999)\n\n def datetime_to_epoch16(self, dt):\n \"\"\"\n Converts a Python datetime to a CDF Epoch16 value\n\n Parameters\n ==========\n dt : :class:`datetime.datetime`\n date and time to convert\n\n Returns\n =======\n out : list of float\n epoch16 corresponding to dt\n\n See Also\n ========\n v_datetime_to_epoch16\n \"\"\"\n if dt.tzinfo != None and dt.utcoffset() != None:\n dt = dt - dt.utcoffset()\n dt.replace(tzinfo=None)\n #Default to \"illegal epoch\"\n epoch16 = (ctypes.c_double * 2)(-1., -1.)\n if self._library.computeEPOCH16(dt.year, dt.month, dt.day, dt.hour,\n dt.minute, dt.second,\n int(dt.microsecond / 1000),\n dt.microsecond % 1000, 0, 0,\n epoch16):\n return (-1., -1.) #Failure, so illegal epoch\n return (epoch16[0], epoch16[1])\n\n def epoch_to_epoch16(self, epoch):\n \"\"\"\n Converts a CDF EPOCH to a CDF EPOCH16 value\n\n Parameters\n ==========\n epoch : double\n EPOCH to convert. Lists and numpy arrays are acceptable.\n\n Returns\n =======\n out : (double, double)\n EPOCH16 corresponding to epoch\n \"\"\"\n e = numpy.require(epoch, numpy.float64)\n s = numpy.trunc(e / 1000.0)\n #ugly numpy stuff, probably a better way....\n res = numpy.hstack((s, (e - s * 1000.0) * 1e9))\n if len(res) <= 2:\n return res\n newshape = list(res.shape[0:-2])\n newshape.append(res.shape[-1] // 2)\n newshape.append(2)\n return numpy.rollaxis(res.reshape(newshape), -1, -2)\n\n def epoch_to_num(self, epoch):\n \"\"\"\n Convert CDF EPOCH to matplotlib number.\n\n Same output as :func:`~matplotlib.dates.date2num` and useful for\n plotting large data sets without converting the times through datetime.\n\n Parameters\n ==========\n epoch : double\n EPOCH to convert. Lists and numpy arrays are acceptable.\n\n Returns\n =======\n out : double\n Floating point number representing days since 0001-01-01.\n \"\"\"\n #date2num day 1 is 1/1/1 00UT\n #epoch 1/1/1 00UT is 31622400000.0 (millisecond)\n return (epoch - 31622400000.0) / (24 * 60 * 60 * 1000.0) + 1.0\n\n def epoch16_to_epoch(self, epoch16):\n \"\"\"\n Converts a CDF EPOCH16 to a CDF EPOCH value\n\n Parameters\n ==========\n epoch16 : (double, double)\n EPOCH16 to convert. Lists and numpy arrays are acceptable.\n LAST dimension should be 2: the two pairs of EPOCH16\n\n Returns\n =======\n out : double\n EPOCH corresponding to epoch16\n \"\"\"\n e = numpy.require(epoch16, numpy.float64)\n return e[..., 0] * 1000.0 + numpy.round(e[..., 1] / 1e9)\n\n def tt2000_to_datetime(self, tt2000):\n \"\"\"\n Converts a CDF TT2000 value to a datetime\n\n .. note::\n Although TT2000 values support leapseconds, Python's datetime\n object does not. Any times after 23:59:59.999999 will\n be truncated to 23:59:59.999999.\n\n\n Parameters\n ==========\n tt2000 : int\n TT2000 value from CDF\n\n Raises\n ======\n EpochError : if input invalid\n\n Returns\n =======\n out : :class:`datetime.datetime`\n date and time corresponding to epoch. Invalid values are set to\n usual epoch invalid value, i.e. last moment of year 9999.\n\n See Also\n ========\n v_tt2000_to_datetime\n \"\"\"\n yyyy = ctypes.c_double(0)\n mm = ctypes.c_double(0)\n dd = ctypes.c_double(0)\n hh = ctypes.c_double(0)\n min = ctypes.c_double(0)\n sec = ctypes.c_double(0)\n msec = ctypes.c_double(0)\n usec = ctypes.c_double(0)\n nsec = ctypes.c_double(0)\n self._library.breakdownTT2000(\n ctypes.c_longlong(tt2000),\n ctypes.byref(yyyy), ctypes.byref(mm), ctypes.byref(dd),\n ctypes.byref(hh), ctypes.byref(min), ctypes.byref(sec),\n ctypes.byref(msec), ctypes.byref(usec), ctypes.byref(nsec))\n if yyyy.value <= 0:\n return datetime.datetime(9999, 12, 13, 23, 59, 59, 999999)\n sec = int(sec.value)\n if sec >= 60:\n return datetime.datetime(\n int(yyyy.value), int(mm.value), int(dd.value),\n int(hh.value), int(min.value), 59, 999999)\n micro = int(msec.value * 1000 + usec.value + nsec.value / 1000 + 0.5)\n if micro < 1000000:\n return datetime.datetime(\n int(yyyy.value), int(mm.value), int(dd.value),\n int(hh.value), int(min.value), sec, micro)\n else:\n add_sec = int(micro / 1000000)\n try:\n return datetime.datetime(\n int(yyyy.value), int(mm.value), int(dd.value),\n int(hh.value), int(min.value), sec,\n micro - add_sec * 1000000) + \\\n datetime.timedelta(seconds=add_sec)\n except OverflowError:\n return datetime.datetime(datetime.MAXYEAR, 12, 31,\n 23, 59, 59, 999999)\n\n def datetime_to_tt2000(self, dt):\n \"\"\"\n Converts a Python datetime to a CDF TT2000 value\n\n Parameters\n ==========\n dt : :class:`datetime.datetime`\n date and time to convert\n\n Returns\n =======\n out : int\n tt2000 corresponding to dt\n\n See Also\n ========\n v_datetime_to_tt2000\n \"\"\"\n if dt.tzinfo != None and dt.utcoffset() != None:\n dt = dt - dt.utcoffset()\n dt = dt.replace(tzinfo=None)\n if dt == datetime.datetime.max:\n return -2**63\n return self._library.computeTT2000(\n dt.year, dt.month, dt.day, dt.hour,\n dt.minute, dt.second,\n int(dt.microsecond / 1000),\n dt.microsecond % 1000, 0)\n\n def _datetime_to_tt2000_typepunned(self, dt):\n \"\"\"\n Converts a Python datetime to a CDF TT2000 value\n\n Typepunned version that passes doubles as longlongs, to get around\n ARM calling convention oddness.\n\n Parameters\n ==========\n dt : :class:`datetime.datetime`\n date and time to convert\n\n Returns\n =======\n out : int\n tt2000 corresponding to dt\n\n See Also\n ========\n v_datetime_to_tt2000\n \"\"\"\n c_ll_p = ctypes.POINTER(ctypes.c_longlong)\n if dt.tzinfo != None and dt.utcoffset() != None:\n dt = dt - dt.utcoffset()\n dt = dt.replace(tzinfo=None)\n if dt == datetime.datetime.max:\n return -2**63\n return self._library.computeTT2000(\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n dt.year)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n dt.month)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n dt.day)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n dt.hour)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n dt.minute)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n dt.second)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n dt.microsecond // 1000)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n dt.microsecond % 1000)), c_ll_p).contents,\n ctypes.cast(ctypes.pointer(ctypes.c_double(\n 0)), c_ll_p).contents)\n\n def epoch_to_tt2000(self, epoch):\n \"\"\"\n Converts a CDF EPOCH to a CDF TT2000 value\n\n Parameters\n ==========\n epoch : double\n EPOCH to convert\n\n Returns\n =======\n out : int\n tt2000 corresponding to epoch\n\n See Also\n ========\n v_epoch_to_tt2000\n \"\"\"\n return self._library.CDF_TT2000_from_UTC_EPOCH(epoch)\n\n def tt2000_to_epoch(self, tt2000):\n \"\"\"\n Converts a CDF TT2000 value to a CDF EPOCH\n\n .. note::\n Although TT2000 values support leapseconds, CDF EPOCH values\n do not. Times during leapseconds are rounded up to beginning\n of the next day.\n\n\n Parameters\n ==========\n tt2000 : int\n TT2000 value from CDF\n\n Raises\n ======\n EpochError : if input invalid\n\n Returns\n =======\n out : double\n EPOCH corresponding to the TT2000 input time\n\n See Also\n ========\n v_tt2000_to_epoch\n \"\"\"\n return self._library.CDF_TT2000_to_UTC_EPOCH(tt2000)\n\n def epoch16_to_tt2000(self, epoch0, epoch1):\n \"\"\"\n Converts a CDF epoch16 value to TT2000\n\n .. note::\n Because TT2000 does not support picoseconds, the picoseconds\n value in epoch is ignored (i.e., truncated.)\n\n Parameters\n ==========\n epoch0 : float\n epoch16 value from CDF, first half\n epoch1 : float\n epoch16 value from CDF, second half\n\n Raises\n ======\n EpochError : if input invalid\n\n Returns\n =======\n out : long\n TT2000 corresponding to epoch.\n\n See Also\n ========\n v_epoch16_to_tt2000\n \"\"\"\n return self._library.CDF_TT2000_from_UTC_EPOCH16(\n (ctypes.c_double * 2)(epoch0, epoch1))\n\n def tt2000_to_epoch16(self, tt2000):\n \"\"\"\n Converts a CDF TT2000 value to a CDF EPOCH16\n\n .. note::\n Although TT2000 values support leapseconds, CDF EPOCH16 values\n do not. Times during leapseconds are rounded up to beginning\n of the next day.\n\n Parameters\n ==========\n tt2000 : int\n TT2000 value from CDF\n\n Raises\n ======\n EpochError : if input invalid\n\n Returns\n =======\n out : double, double\n EPOCH16 corresponding to the TT2000 input time\n\n See Also\n ========\n v_tt2000_to_epoch16\n \"\"\"\n #Default to \"illegal epoch\" if isn't populated\n epoch16 = (ctypes.c_double * 2)(-1., -1.)\n if self._library.CDF_TT2000_to_UTC_EPOCH16(tt2000, epoch16):\n return (-1., -1.) #Failure; illegal epoch\n return (epoch16[0], epoch16[1])\n\n def _bad_tt2000(*args, **kwargs):\n \"\"\"Convenience function for complaining that TT2000 not supported\"\"\"\n raise NotImplementedError(\n 'TT2000 functions require CDF library 3.4.0 or later')\n\n\ndef download_library():\n \"\"\"Download and install the CDF library\"\"\"\n if sys.platform != 'win32':\n raise NotImplementedError(\n 'CDF library install only supported on Windows')\n try:\n import html.parser as HTMLParser\n except ImportError:\n import HTMLParser\n #https://stackoverflow.com/questions/1713038/super-fails-with-error-typeerror-argument-1-must-be-type-not-classobj\n class LinkParser(HTMLParser.HTMLParser, object):\n def __init__(self, *args, **kwargs):\n self.links_found = []\n super(LinkParser, self).__init__(*args, **kwargs)\n def handle_starttag(self, tag, attrs):\n if tag != 'a' or attrs[0][0] != 'href':\n return\n self.links_found.append(attrs[0][1])\n import re\n import subprocess\n try:\n import urllib.request as u\n except ImportError:\n import urllib as u\n\n # Removed reference to spacepy\n #import spacepy\n #if spacepy.config.get('user_agent', None):\n # class AppURLopener(u.FancyURLopener):\n # version = spacepy.config['user_agent']\n # u._urlopener = AppURLopener()\n baseurl = 'https://spdf.sci.gsfc.nasa.gov/pub/software/cdf/dist/'\n url = u.urlopen(baseurl)\n listing = url.read()\n url.close()\n p = LinkParser()\n p.feed(listing)\n cdfdist = [l for l in p.links_found if re.match('^cdf3\\d_\\d(?:_\\d)?/$', l)]\n if not cdfdist:\n raise RuntimeError(\n \"Couldn't find CDF distribution directory to download\")\n cdfdist.sort(key=lambda x: x.rstrip('/').split('_'))\n cdfverbase = cdfdist[-1].rstrip('/')\n instfname = cdfverbase + ('_0' if cdfverbase.count('_') == 1 else '') + \\\n '-setup-{0}.exe'.format(len('%x' % sys.maxsize)*4)\n insturl = baseurl + cdfverbase + '/windows/' + instfname\n tmpdir = tempfile.mkdtemp()\n try:\n fname, status = u.urlretrieve(insturl, os.path.join(tmpdir, instfname))\n subprocess.check_call([fname, '/install', '/q1'], shell=False)\n finally:\n shutil.rmtree(tmpdir)\n\n_libpath, _library = Library._find_lib()\nif _library is None:\n raise Exception(('Cannot load CDF C library; checked {0}. '\n 'Try \\'os.environ[\"CDF_LIB\"] = library_directory\\' '\n 'before import.').format(', '.join(_libpath)))\nfrom . import const\nlib = Library(_libpath, _library)\n\"\"\"Module global library object.\n\nInitalized at module load time so all classes have ready\naccess to the CDF library and a common state. E.g:\n >>> import pycdf\n >>> pycdf.lib.version\n (3, 3, 0, ' ')\n\"\"\"\n\n\nclass CDFException(Exception):\n \"\"\"\n Base class for errors or warnings in the CDF library.\n\n Not normally used directly, but in subclasses :class:`CDFError`\n and :class:`CDFWarning`.\n\n Error messages provided by this class are looked up from the underlying\n C library.\n \"\"\"\n def __init__(self, status):\n \"\"\"\n Create a CDF Exception\n\n Uses CDF C library to look up an appropriate error message.\n\n Parameters\n ==========\n status : ctypes.c_long\n CDF status\n \"\"\"\n self.status = status\n self.string = 'CDF error ' + repr(status) + ', unable to get details.'\n message = ctypes.create_string_buffer(const.CDF_STATUSTEXT_LEN + 1)\n try:\n retval = lib._library.CDFlib(const.SELECT_, const.CDF_STATUS_,\n ctypes.c_long(status),\n const.GET_, const.STATUS_TEXT_, message,\n const.NULL_)\n if retval == const.CDF_OK:\n if isinstance(message.value, str):\n self.string = message.value\n elif isinstance(message.value, bytes):\n self.string = message.value.decode()\n except:\n pass\n\n def __str__(self):\n \"\"\"\n Error string associated with the library error.\n\n Returns\n =======\n out : str\n Error message from the CDF library.\n \"\"\"\n return self.string\n\n\nclass CDFError(CDFException):\n \"\"\"Raised for an error in the CDF library.\"\"\"\n pass\n\n\nclass CDFWarning(CDFException, UserWarning):\n \"\"\"Used for a warning in the CDF library.\"\"\"\n\n def warn(self, level=4):\n \"\"\"\n Issues a warning based on the information stored in my exception\n\n Intended for use in check_status or similar wrapper function.\n\n Other Parameters\n ================\n level : int\n optional (default 3), how far up the stack the warning should\n be reported. Passed directly to :class:`warnings.warn`.\n \"\"\"\n warnings.warn(self, self.__class__, level)\n\n\nclass EpochError(Exception):\n \"\"\"Used for errors in epoch routines\"\"\"\n pass\n\n\ndef _compress(obj, comptype=None, param=None):\n \"\"\"Set or check the compression of a :py:class:`pycdf.CDF` or :py:class:`pycdf.Var`\n\n @param obj: object on which to set or check compression\n @type obj: :py:class:`pycdf.CDF` or :py:class:`pycdf.Var`\n @param comptype: type of compression to change to, see CDF C reference\n manual section 4.10. Constants for this parameter\n are in :py:mod:`pycdf.const`. If not specified, will not change\n compression.\n @type comptype: ctypes.c_long\n @param param: Compression parameter, see CDF CRM 4.10 and :py:mod:`pycdf.const`.\n If not specified, will choose reasonable default (5 for\n gzip; other types have only one possible parameter.)\n @type param: ctypes.c_long\n @return: (comptype, param) currently in effect\n @rtype: tuple\n \"\"\"\n if isinstance(obj, CDF):\n COMPRESSION_ = const.CDF_COMPRESSION_\n elif isinstance(obj, Var):\n COMPRESSION_ = const.zVAR_COMPRESSION_\n else:\n raise ValueError('Must specify a CDF or Var type.')\n\n validparams = {const.NO_COMPRESSION.value: [ctypes.c_long(0)],\n const.RLE_COMPRESSION.value: [const.RLE_OF_ZEROs],\n const.HUFF_COMPRESSION.value:\n [const.OPTIMAL_ENCODING_TREES],\n const.AHUFF_COMPRESSION.value:\n [const.OPTIMAL_ENCODING_TREES],\n const.GZIP_COMPRESSION.value: [ctypes.c_long(5),\n ctypes.c_long(1),\n ctypes.c_long(2),\n ctypes.c_long(3),\n ctypes.c_long(4),\n ctypes.c_long(6),\n ctypes.c_long(7),\n ctypes.c_long(8),\n ctypes.c_long(9),\n ],\n }\n comptypes = [const.NO_COMPRESSION, const.RLE_COMPRESSION,\n const.HUFF_COMPRESSION, const.AHUFF_COMPRESSION,\n const.GZIP_COMPRESSION]\n comptypevalues = [i.value for i in comptypes]\n\n if comptype != None:\n if not hasattr(comptype, 'value'):\n comptype = ctypes.c_long(comptype)\n if param is None:\n if not comptype.value in validparams:\n raise CDFError(const.BAD_COMPRESSION)\n param = validparams[comptype.value][0]\n paramlist = (ctypes.c_long * 1)(param)\n obj._call(const.PUT_, COMPRESSION_,\n comptype, paramlist)\n params = (ctypes.c_long *\n const.CDF_MAX_PARMS)(*([0] * const.CDF_MAX_PARMS))\n comptype = ctypes.c_long(0)\n percent = ctypes.c_long(0)\n obj._call(const.GET_, COMPRESSION_,\n ctypes.byref(comptype), ctypes.byref(params),\n ctypes.byref(percent))\n param = params[0]\n if not comptype.value in comptypevalues:\n raise CDFError(const.BAD_COMPRESSION)\n validparamvalues = [i.value for i in validparams[comptype.value]]\n if not param in validparamvalues:\n raise CDFError(const.BAD_COMPRESSION_PARM)\n comptype = comptypes[comptypevalues.index(comptype.value)]\n if comptype in (const.RLE_COMPRESSION, const.HUFF_COMPRESSION,\n const.AHUFF_COMPRESSION):\n param = validparams[comptype.value][validparamvalues.index(param)]\n return (comptype, param)\n\n\nclass CDF(MutableMapping):\n \"\"\"\n Python object representing a CDF file.\n\n Open or create a CDF file by creating an object of this class.\n\n Parameters\n ==========\n pathname : string\n name of the file to open or create\n masterpath : string\n name of the master CDF file to use in creating\n a new file. If not provided, an existing file is\n opened; if provided but evaluates to ``False``\n (e.g., ``''``), an empty new CDF is created.\n create : bool\n Create a new CDF even if masterpath isn't provided\n readonly : bool\n Open the CDF read-only. Default True if opening an\n existing CDF; False if creating a new one. A readonly\n CDF with many variables may be slow to close. See\n :meth:`readonly`.\n\n Raises\n ======\n CDFError\n if CDF library reports an error\n\n Warns\n =====\n CDFWarning\n if CDF library reports a warning and interpreter\n is set to error on warnings.\n\n Examples\n ========\n Open a CDF by creating a CDF object, e.g.:\n\n >>> cdffile = pycdf.CDF('cdf_filename.cdf')\n\n Be sure to :meth:`close` or :meth:`save` when\n done.\n\n .. note::\n Existing CDF files are opened read-only by default, see\n :meth:`readonly` to change.\n\n CDF supports the `with\n <http://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects>`_\n keyword, like other file objects, so:\n\n >>> with pycdf.CDF('cdf_filename.cdf') as cdffile:\n ... #do brilliant things with the CDF\n\n will open the CDF, execute the indented statements, and close the CDF when\n finished or when an error occurs. The `python docs\n <http://docs.python.org/reference/compound_stmts.html#with>`_ include more\n detail on this 'context manager' ability.\n\n CDF objects behave like a python `dictionary\n <http://docs.python.org/tutorial/datastructures.html#dictionaries>`_,\n where the keys are names of variables in the CDF, and the values,\n :class:`Var` objects. As a dictionary, they are also `iterable\n <http://docs.python.org/tutorial/classes.html#iterators>`_ and it is easy\n to loop over all of the variables in a file. Some examples:\n\n #. List the names of all variables in the open CDF ``cdffile``:\n\n >>> cdffile.keys()\n >>> for k in cdffile: #Alternate\n ... print(k)\n\n #. Get a :class:`Var` object for the variable named ``Epoch``:\n\n >>> epoch = cdffile['Epoch']\n\n #. Determine if a CDF contains a variable named ``B_GSE``:\n\n >>> if 'B_GSE' in cdffile:\n ... print('B_GSE is in the file')\n ... else:\n ... print('B_GSE is not in the file')\n\n #. Find how many variables are in the file:\n\n >>> print(len(cdffile))\n\n #. Delete the variable ``Epoch`` from the open CDF file ``cdffile``:\n\n >>> del cdffile['Epoch']\n\n #. Display a summary of variables and types in open CDF file ``cdffile``:\n\n >>> print(cdffile)\n\n #. Open the CDF named ``cdf_filename.cdf``, read *all* the data from\n all variables into dictionary ``data``, and close it when done or\n if an error occurs:\n\n >>> with pycdf.CDF('cdf_filename.cdf') as cdffile:\n ... data = cdffile.copy()\n\n\n This last example can be very inefficient as it reads the entire CDF.\n Normally it's better to treat the CDF as a dictionary and access only\n the data needed, which will be pulled transparently from disc. See\n :class:`Var` for more subtle examples.\n\n Potentially useful dictionary methods and related functions:\n\n - `in <http://docs.python.org/reference/expressions.html#in>`_\n - `keys <http://docs.python.org/tutorial/datastructures.html#dictionaries>`_\n - :py:func:`len`\n - `list comprehensions\n <http://docs.python.org/tutorial/datastructures.html#list-comprehensions>`_\n - :py:func:`sorted`\n - :py:func:`~spacepy.toolbox.dictree`\n\n The CDF user's guide section 2.2 has more background information on CDF\n files.\n\n The :attr:`~CDF.attrs` Python attribute acts as a dictionary\n referencing CDF attributes (do not confuse the two); all the\n dictionary methods above also work on the attribute dictionary.\n See :class:`gAttrList` for more on the dictionary of global\n attributes.\n\n Creating a new CDF from a master (skeleton) CDF has similar syntax to\n opening one:\n\n >>> cdffile = pycdf.CDF('cdf_filename.cdf', 'master_cdf_filename.cdf')\n\n This creates and opens ``cdf_filename.cdf`` as a copy of\n ``master_cdf_filename.cdf``.\n\n Using a skeleton CDF is recommended over making a CDF entirely from\n scratch, but this is possible by specifying a blank master:\n\n >>> cdffile = pycdf.CDF('cdf_filename.cdf', '')\n\n When CDFs are created in this way, they are opened read-write, see\n :py:meth:`readonly` to change.\n\n By default, new CDFs (without a master) are created in version 2\n (backward-compatible) format. To create a version 3 CDF, use\n :meth:`Library.set_backward`:\n\n >>> pycdf.lib.set_backward(False)\n >>> cdffile = pycdf.CDF('cdf_filename.cdf', '')\n\n Add variables by direct assignment, which will automatically set type\n and dimension based on the data provided:\n\n >>> cdffile['new_variable_name'] = [1, 2, 3, 4]\n\n or, if more control is needed over the type and dimensions, use\n :py:meth:`new`.\n\n Although it is supported to assign Var objects to Python variables\n for convenience, there are some minor pitfalls that can arise when\n changing a CDF that will not affect most users. This is only a\n concern when assigning a zVar object to a Python variable, changing the\n CDF through some other variable, and then trying to use the zVar\n object via the originally assigned variable.\n\n Deleting a variable:\n\n >>> var = cdffile['Var1']\n >>> del cdffile['Var1']\n >>> var[0] #fail, no such variable\n\n Renaming a variable:\n\n >>> var = cdffile['Var1']\n >>> cdffile['Var1'].rename('Var2')\n >>> var[0] #fail, no such variable\n\n Renaming via the same variable works:\n\n >>> var = cdffile['Var1']\n >>> var.rename('Var2')\n >>> var[0] #succeeds, aware of new name\n\n Deleting a variable and then creating another variable with the same name\n may lead to some surprises:\n\n >>> var = cdffile['Var1']\n >>> var[...] = [1, 2, 3, 4]\n >>> del cdffile['Var1']\n >>> cdffile.new('Var1', data=[5, 6, 7, 8]\n >>> var[...]\n [5, 6, 7, 8]\n\n .. autosummary::\n\n ~CDF.attr_num\n ~CDF.attrs\n ~CDF.add_attr_to_cache\n ~CDF.add_to_cache\n ~CDF.backward\n ~CDF.checksum\n ~CDF.clear_attr_from_cache\n ~CDF.clear_from_cache\n ~CDF.clone\n ~CDF.close\n ~CDF.col_major\n ~CDF.compress\n ~CDF.copy\n ~CDF.from_data\n ~CDF.new\n ~CDF.raw_var\n ~CDF.readonly\n ~CDF.save\n ~CDF.var_num\n ~CDF.version\n\n .. attribute:: CDF.attrs\n\n Global attributes for this CDF in a dict-like format.\n See :class:`gAttrList` for details.\n\n .. attribute:: CDF.backward\n\n True if this CDF was created in backward-compatible mode\n (for opening with CDF library before 3.x)\n\n .. automethod:: add_to_cache\n .. automethod:: add_attr_to_cache\n .. automethod:: attr_num\n .. automethod:: checksum\n .. automethod:: clear_from_cache\n .. automethod:: clear_attr_from_cache\n .. automethod:: clone\n .. automethod:: close\n .. automethod:: col_major\n .. automethod:: compress\n .. automethod:: copy\n .. automethod:: from_data\n .. automethod:: new\n .. automethod:: raw_var\n .. automethod:: readonly\n .. automethod:: save\n .. automethod:: var_num\n .. automethod:: version\n\n \"\"\"\n def __init__(self, pathname, masterpath=None, create=None, readonly=None):\n \"\"\"Open or create a CDF file.\n\n Parameters\n ==========\n pathname : string\n name of the file to open or create\n masterpath : string\n name of the master CDF file to use in creating\n a new file. If not provided, an existing file is\n opened; if provided but evaluates to ``False``\n (e.g., ``''``), an empty new CDF is created.\n create : bool\n Create a new CDF even if masterpath isn't provided\n readonly : bool\n Open the CDF read-only. Default True if opening an\n existing CDF; False if creating a new one.\n\n Raises\n ======\n CDFError\n if CDF library reports an error\n CDFWarning\n if CDF library reports a warning and interpreter\n is set to error on warnings.\n\n Examples\n ========\n Open a CDF by creating a CDF object, e.g.:\n >>> cdffile = pycdf.CDF('cdf_filename.cdf')\n Be sure to :py:meth:`pycdf.CDF.close` or :py:meth:`pycdf.CDF.save`\n when done.\n \"\"\"\n if masterpath is not None: #Looks like we want to create\n if create is False:\n raise ValueError('Cannot specify a master CDF without creating a CDF')\n if readonly is True:\n raise ValueError('Cannot create a CDF in readonly mode')\n if create and readonly:\n raise ValueError('Cannot create a CDF in readonly mode')\n try:\n self.pathname = pathname.encode()\n except AttributeError:\n raise ValueError(\n 'pathname must be string-like: {0}'.format(pathname))\n self._handle = ctypes.c_void_p(None)\n self._opened = False\n if masterpath is None and not create:\n self._open(True if readonly is None else readonly)\n elif masterpath:\n self._from_master(masterpath.encode())\n else:\n self._create()\n lib.call(const.SELECT_, const.CDF_zMODE_, ctypes.c_long(2))\n self._attrlistref = weakref.ref(gAttrList(self))\n self.backward = self.version()[0] < 3\n self._var_nums = {}\n \"\"\"Cache of name-to-number mappings for variables in this CDF\"\"\"\n self._attr_info = {}\n \"\"\"Cache of name-to-(number, global) mappings for attributes\n in this CDF\"\"\"\n\n def __del__(self):\n \"\"\"Destructor; called when CDF object is destroyed.\n\n Close CDF file if there is still a valid handle.\n .. note::\n To avoid data loss, explicitly call :py:meth:`pycdf.CDF.close` \n or :py:meth:`pycdf.CDF.save`.\n \"\"\"\n if self._opened:\n self.close()\n\n def __delitem__(self, name):\n \"\"\"Delete a zVariable in this CDF, by name or number\n\n Parameters\n ==========\n name : string or int\n Name or number of the CDF variable\n .. note:\n Variable numbers may change if variables are added or removed.\n\n Examples\n ========\n Delete the variable ``Epoch`` from the open CDF file ``cdffile``.\n >>> del cdffile['Epoch']\n \"\"\"\n self[name]._delete()\n\n def __enter__(self):\n \"\"\"Context manager entrance function.\"\"\"\n return self\n\n def __exit__(self, type, value, traceback):\n \"\"\"Context manager exit function.\n\n Close CDF file.\n \"\"\"\n self.close()\n\n def __getitem__(self, name):\n \"\"\"Gets a zVariable in this CDF, by name or number\n\n The CDF acts like a dict\n\n @param name: Name or number of the CDF variable\n @type name: string or int\n @return: CDF variable named or numbered L{name}\n @rtype: :py:class:`pycdf.Var`\n @raise KeyError: for pretty much any problem in lookup\n @note: variable numbers may change if variables are added or removed.\n \"\"\"\n try:\n return Var(self, name)\n except CDFException as e:\n raise KeyError('{0}: {1}'.format(name, e))\n\n def __setitem__(self, name, data):\n \"\"\"Writes data to a zVariable in this CDF\n\n If the zVariable does not exist, will create one matching\n L{data}. If it does exist, will attempt to write L{data}\n to it without changing the type or dimensions.\n\n @param name: name or number of the variable to write\n @type name: str or int\n @param data: data to write, or a :py:class:`pycdf.Var` to copy\n \"\"\"\n if isinstance(data, Var):\n self.clone(data, name)\n elif name in self:\n self[name][...] = data\n if hasattr(data, 'attrs'):\n self[name].attrs.clone(data.attrs)\n else:\n self.new(name, data)\n\n def __iter__(self, current = 0):\n \"\"\"Iterates over zVars in CDF\n\n Iterators for dicts return keys\n @note: Returned in variable-number order\n \"\"\"\n while current < self.__len__():\n name = self[current].name()\n value = (yield name)\n if value is None:\n current += 1\n else:\n current = self[value]._num()\n current += 1\n\n def __len__(self):\n \"\"\"Implements 'length' of CDF (number of zVars)\n\n @return: number of zVars in the CDF\n @rtype: int\n \"\"\"\n count = ctypes.c_long(0)\n self._call(const.GET_, const.CDF_NUMzVARS_, ctypes.byref(count))\n return count.value\n\n def __contains__(self, key):\n \"\"\"Determines whether a particular variable name is in the CDF\n\n @note: Essentially an efficiency function; L{__iter__} is called\n if this isn't defined\n @param key: key/variable name to check\n @type key: string\n @return: True if L{key} is the name of a variable in CDF, else False\n @rtype: Boolean\n \"\"\"\n try:\n foo = self[key]\n return True\n except KeyError as e:\n expected = str(key) + \\\n \": NO_SUCH_VAR: Named variable not found in this CDF.\"\n if expected in e.args:\n return False\n raise\n\n def __repr__(self):\n \"\"\"Returns representation of CDF\n\n Cannot return anything that can be eval'd to create a copy of the\n CDF, so just wrap the informal representation in angle brackets.\n @return: all the data in this list of attributes\n @rtype: str\n \"\"\"\n return '<CDF:\\n' + str(self) + '\\n>'\n\n def __str__(self):\n \"\"\"Returns a string representation of the CDF\n\n This is an 'informal' representation in that it cannot be evaluated\n directly to create a :py:class:`pycdf.CDF`, just the names, types, and sizes of all\n variables. (Attributes are not listed.)\n\n @return: description of the variables in the CDF\n @rtype: str\n \"\"\"\n if self._opened:\n return '\\n'.join([key + ': ' + str(value)\n for (key, value) in sorted(self.items())])\n #can get away with this sort because second value in tuple isn't\n #compared unless first are different, and variable name is unique.\n else:\n if isinstance(self.pathname, str):\n return 'Closed CDF {0}'.format(self.pathname)\n else:\n return 'Closed CDF {0}'.format(self.pathname.decode('ascii'))\n\n def _open(self, readonly=True):\n \"\"\"Opens the CDF file (called on init)\n\n Will open an existing CDF file read/write.\n\n Raises\n ======\n CDFError : if CDF library reports an error\n CDFWarning : if CDF library reports a warning and interpreter\n is set to error on warnings.\n .. note:\n Not intended for direct call; pass parameters to\n :py:class:`pycdf.CDF` constructor.\n \"\"\"\n\n lib.call(const.OPEN_, const.CDF_, self.pathname, ctypes.byref(self._handle))\n self._opened = True\n if readonly: #Default is RW\n self.readonly(readonly)\n\n def _create(self):\n \"\"\"Creates (and opens) a new CDF file\n\n Created at ``pathname``.\n Assumes zero-dimension r variables\n\n Raises\n ======\n CDFError : if CDF library reports an error\n CDFWarning : if CDF library reports a warning and interpreter\n is set to error on warnings.\n .. note:\n Not intended for direct call; pass parameters to\n :py:class:`pycdf.CDF` constructor.\n \"\"\"\n\n lib.call(const.CREATE_, const.CDF_, self.pathname, ctypes.c_long(0),\n (ctypes.c_long * 1)(0), ctypes.byref(self._handle))\n self._opened = True\n\n def _from_master(self, master_path):\n \"\"\"Creates a new CDF from a master CDF file\n\n ``master_path`` is copied to ``pathname`` and opened.\n\n Parameters\n ==========\n master_path : string\n location of the master CDF file\n\n Raises\n ======\n CDFError : if CDF library reports an error\n CDFWarning : if CDF library reports a warning and interpreter\n is set to error on warnings.\n .. note:\n Not intended for direct call; pass parameters to\n :py:class:`pycdf.CDF` constructor.\n \"\"\"\n\n if os.path.exists(self.pathname):\n raise CDFError(const.CDF_EXISTS)\n shutil.copy2(master_path, self.pathname)\n self._open(False)\n\n\n def _call(self, *args, **kwargs):\n \"\"\"Select this CDF as current and call the CDF internal interface\n\n Adds call to select this CDF to L{args} and passes all parameters\n directly through to the CDFlib routine of the CDF library's C internal\n interface. Checks the return value with L{Library.check_status}.\n\n Parameters\n ==========\n args : various, see :py:mod:`ctypes`.\n Passed directly to the CDF library interface. Useful\n constants are defined in the :doc:`const <pycdf_const>`\n module of this package.\n\n Returns\n =======\n out : ctypes.c_long\n CDF status from the library\n\n .. note:\n Terminal NULL_ is automatically added to ``args``.\n Raises\n ======\n CDFError : if CDF library reports an error\n CDFWarning : if CDF library reports a warning and interpreter\n is set to error on warnings.\n \"\"\"\n return lib.call(const.SELECT_, const.CDF_, self._handle,\n *args, **kwargs)\n\n def clone(self, zVar, name=None, data=True):\n \"\"\"\n Clone a zVariable (from another CDF or this) into this CDF\n\n Parameters\n ==========\n zVar : :py:class:`Var`\n variable to clone\n\n Other Parameters\n ================\n name : str\n Name of the new variable (default: name of the original)\n data : boolean (optional)\n Copy data, or only type, dimensions, variance, attributes?\n (default: True, copy data as well)\n\n Returns\n =======\n out : :py:class:`Var`\n The newly-created zVar in this CDF\n \"\"\"\n if name is None:\n name = zVar.name()\n if name in self:\n del self[name]\n self.new(name, type=zVar.type(), recVary=zVar.rv(),\n dimVarys=zVar.dv(), dims=zVar._dim_sizes(),\n n_elements=zVar._nelems())\n self[name].compress(*zVar.compress())\n self[name].attrs.clone(zVar.attrs)\n if data:\n r = zVar._raw\n zVar._raw = True\n self.raw_var(name)[...] = zVar[...]\n zVar._raw = r\n return zVar\n\n def col_major(self, new_col=None):\n \"\"\"\n Finds the majority of this CDF file\n\n Other Parameters\n ================\n new_col : boolean\n Specify True to change to column-major, False to change to\n row major, or do not specify to check the majority\n rather than changing it.\n (default is check only)\n\n Returns\n =======\n out : boolean\n True if column-major, false if row-major\n \"\"\"\n if new_col != None:\n new_maj = const.COLUMN_MAJOR if new_col else const.ROW_MAJOR\n self._call(const.PUT_, const.CDF_MAJORITY_, new_maj)\n maj = ctypes.c_long(0)\n self._call(const.GET_, const.CDF_MAJORITY_, ctypes.byref(maj))\n if not maj.value in (const.ROW_MAJOR.value, const.COLUMN_MAJOR.value):\n raise CDFError(const.BAD_MAJORITY)\n return maj.value == const.COLUMN_MAJOR.value\n\n def readonly(self, ro=None):\n \"\"\"\n Sets or check the readonly status of this CDF\n\n If the CDF has been changed since opening, setting readonly mode\n will have no effect.\n\n .. note::\n Closing a CDF that has been opened readonly, or setting readonly\n False, may take a substantial amount of time if there are many\n variables in the CDF, as a (potentially large) cache needs to\n be cleared. Consider specifying ``readonly=False`` when opening\n the file if this is an issue. However, this may make some reading\n operations slower.\n\n Other Parameters\n ================\n ro : Boolean\n True to set the CDF readonly, False to set it read/write,\n or leave out to check only.\n\n Returns\n =======\n out : Boolean\n True if CDF is read-only, else False\n\n Raises\n ======\n CDFError : if bad mode is set\n \"\"\"\n if ro == True:\n self._call(const.SELECT_, const.CDF_READONLY_MODE_,\n const.READONLYon)\n elif ro == False:\n self._call(const.SELECT_, const.CDF_READONLY_MODE_,\n const.READONLYoff)\n mode = ctypes.c_long(0)\n self._call(const.CONFIRM_, const.CDF_READONLY_MODE_,\n ctypes.byref(mode))\n if mode.value == const.READONLYon.value:\n return True\n elif mode.value == const.READONLYoff.value:\n return False\n else:\n raise CDFError(const.BAD_READONLY_MODE.value)\n\n def checksum(self, new_val=None):\n \"\"\"\n Set or check the checksum status of this CDF. If checksums\n are enabled, the checksum will be verified every time the file\n is opened.\n\n Other Parameters\n ================\n new_val : boolean\n True to enable checksum, False to disable, or leave out\n to simply check.\n\n Returns\n =======\n out : boolean\n True if the checksum is enabled or False if disabled\n \"\"\"\n if new_val != None:\n self._call(const.PUT_, const.CDF_CHECKSUM_,\n const.MD5_CHECKSUM if new_val else const.NO_CHECKSUM)\n chk = ctypes.c_long(0)\n self._call(const.GET_, const.CDF_CHECKSUM_, ctypes.byref(chk))\n if not chk.value in (const.MD5_CHECKSUM.value,\n const.NO_CHECKSUM.value):\n raise CDFError(const.BAD_CHECKSUM)\n return chk.value == const.MD5_CHECKSUM.value\n\n def close(self):\n \"\"\"\n Closes the CDF file\n\n Although called on object destruction (:meth:`~CDF.__del__`),\n to ensure all data are saved, the user should explicitly call\n :meth:`~CDF.close` or :meth:`~CDF.save`.\n\n Raises\n ======\n CDFError : if CDF library reports an error\n\n Warns\n =====\n CDFWarning : if CDF library reports a warning\n \"\"\"\n\n self._call(const.CLOSE_, const.CDF_)\n self._opened = False\n\n def compress(self, comptype=None, param=None):\n \"\"\"\n Set or check the compression of this CDF\n\n Sets compression on entire *file*, not per-variable.\n\n See section 2.6 of the CDF user's guide for more information on\n compression.\n\n Other Parameters\n ================\n comptype : ctypes.c_long\n type of compression to change to, see CDF C reference manual\n section 4.10. Constants for this parameter are in\n :mod:`~pycdf.const`. If not specified, will not change\n compression.\n param : ctypes.c_long\n Compression parameter, see CDF CRM 4.10 and\n :mod:`~pycdf.const`.\n If not specified, will choose reasonable default (5 for gzip;\n other types have only one possible parameter.)\n\n Returns\n =======\n out : tuple\n (comptype, param) currently in effect\n\n See Also\n ========\n :meth:`Var.compress`\n\n Examples\n ========\n Set file ``cdffile`` to gzip compression, compression level 9:\n >>> cdffile.compress(pycdf.const.GZIP_COMPRESSION, 9)\n \"\"\"\n return _compress(self, comptype, param)\n\n def new(self, name, data=None, type=None, recVary=True, dimVarys=None,\n dims=None, n_elements=None, compress=None, compress_param=None):\n \"\"\"\n Create a new zVariable in this CDF\n\n .. note::\n Either ``data`` or ``type`` must be specified. If type is not\n specified, it is guessed from ``data``.\n\n Parameters\n ==========\n name : str\n name of the new variable\n\n Other Parameters\n ================\n data\n data to store in the new variable. If this has a an ``attrs``\n attribute (e.g., :class:`~spacepy.datamodel.dmarray`), it\n will be used to populate attributes of the new variable.\n type : ctypes.c_long\n CDF type of the variable, from :mod:`~pycdf.const`.\n See section 2.5 of the CDF user's guide for more information on\n CDF data types.\n recVary : boolean\n record variance of the variable (default True)\n dimVarys : list of boolean\n dimension variance of each dimension, default True for all\n dimensions.\n dims : list of int\n size of each dimension of this variable, default zero-dimensional.\n Note this is the dimensionality as defined by CDF, i.e., for\n record-varying variables it excludes the leading record dimension.\n See :py:class:`Var`.\n n_elements : int\n number of elements, should be 1 except for CDF_CHAR,\n for which it's the length of the string.\n compress : ctypes.c_long\n Compression to apply to this variable, default None.\n See :py:meth:`Var.compress`.\n compress_param : ctypes.c_long\n Compression parameter if compression used; reasonable default\n is chosen. See :py:meth:`Var.compress`.\n\n Returns\n =======\n out : :py:class:`Var`\n the newly-created zVariable\n\n Raises\n ======\n ValueError : if neither data nor sufficient typing information\n is provided.\n\n Notes\n =====\n Any given data may be representable by a range of CDF types; if\n the type is not specified, pycdf will guess which\n the CDF types which can represent this data. This breaks down to:\n\n #. If input data is a numpy array, match the type of that array\n #. Proper kind (numerical, string, time)\n #. Proper range (stores highest and lowest number provided)\n #. Sufficient resolution (EPOCH16 required if datetime has\n microseconds or below.)\n\n If more than one value satisfies the requirements, types are returned\n in preferred order:\n\n #. Type that matches precision of data first, then\n #. integer type before float type, then\n #. Smallest type first, then\n #. signed type first, then\n #. specifically-named (CDF_BYTE) vs. generically named (CDF_INT1)\n\n So for example, EPOCH_16 is preferred over EPOCH if ``data`` specifies\n below the millisecond level (rule 1), but otherwise EPOCH is preferred\n (rule 2).\n\n For floats, four-byte is preferred unless eight-byte is required:\n\n #. absolute values between 0 and 3e-39\n #. absolute values greater than 1.7e38\n\n This will switch to an eight-byte double in some cases where four bytes\n would be sufficient for IEEE 754 encoding, but where DEC formats would\n require eight.\n \"\"\"\n if type in (const.CDF_EPOCH16, const.CDF_INT8, const.CDF_TIME_TT2000) \\\n and self.backward:\n raise ValueError('Cannot use EPOCH16, INT8, or TIME_TT2000 '\n 'in backward-compatible CDF')\n if not lib.supports_int8 and \\\n type in (const.CDF_INT8, const.CDF_TIME_TT2000):\n raise ValueError('INT8 and TIME_TT2000 require CDF library 3.4.0')\n if data is None:\n if type is None:\n raise ValueError('Must provide either data or a CDF type.')\n if dims is None:\n dims = []\n if n_elements is None:\n n_elements = 1\n else:\n (guess_dims, guess_types, guess_elements) = _Hyperslice.types(data)\n if dims is None:\n if recVary:\n if guess_dims == ():\n raise ValueError(\n 'Record-varying data cannot be scalar. '\n 'Specify NRV with CDF.new() or put data in array.')\n dims = guess_dims[1:]\n else:\n dims = guess_dims\n if type is None:\n type = guess_types[0]\n if type == const.CDF_EPOCH16.value and self.backward:\n type = const.CDF_EPOCH\n if n_elements is None:\n n_elements = guess_elements\n if dimVarys is None:\n dimVarys = [True for i in dims]\n recVary = const.VARY if recVary else const.NOVARY\n dimVarys = [const.VARY if dimVary else const.NOVARY\n for dimVary in dimVarys]\n if not hasattr(type, 'value'):\n type = ctypes.c_long(type)\n if type.value == const.CDF_INT8.value and not lib.supports_int8:\n raise ValueError(\n '64-bit integer support require CDF library 3.4.0')\n if type.value in (const.CDF_EPOCH16.value, const.CDF_INT8.value,\n const.CDF_TIME_TT2000.value) \\\n and self.backward:\n raise ValueError('Data requires EPOCH16, INT8, or TIME_TT2000; '\n 'incompatible with backward-compatible CDF')\n new_var = Var(self, name, type, n_elements, dims, recVary, dimVarys)\n if compress != None:\n new_var.compress(compress, compress_param)\n if data is not None:\n new_var[...] = data\n if hasattr(data, 'attrs'):\n new_var.attrs.clone(data.attrs)\n return new_var\n\n def raw_var(self, name):\n \"\"\"\n Get a \"raw\" :class:`Var` object.\n\n Normally a :class:`Var` will perform translation of values for\n certain types (to/from Unicode for CHAR variables on Py3k,\n and to/from datetime for all time types). A \"raw\" object\n does not perform this translation, on read or write.\n\n This does *not* affect the data on disk, and in fact it\n is possible to maintain multiple Python objects with access\n to the same zVariable.\n\n Parameters\n ==========\n name : str\n name or number of the zVariable\n \"\"\"\n v = self[name]\n v._raw = True\n return v\n\n def save(self):\n \"\"\"\n Saves the CDF file but leaves it open.\n\n If closing the CDF, :meth:`close` is sufficient;\n there is no need to call\n :meth:`save` before :meth:`close`.\n\n .. note::\n Relies on an undocumented call of the CDF C library, which is\n also used in the Java interface.\n\n Raises\n ======\n CDFError : if CDF library reports an error\n\n Warns\n =====\n CDFWarning : if CDF library reports a warning\n \"\"\"\n\n self._call(const.SAVE_, const.CDF_)\n\n def copy(self):\n \"\"\"\n Make a copy of all data and attributes in this CDF\n\n Returns\n =======\n out : :py:class:`CDFCopy`\n :class:`~spacepy.datamodel.SpaceData`-like object of all data\n \"\"\"\n return CDFCopy(self)\n\n def version(self):\n \"\"\"\n Get version of library that created this CDF\n\n Returns\n =======\n out : tuple\n version of CDF library, in form (version, release, increment)\n \"\"\"\n ver = ctypes.c_long(0)\n rel = ctypes.c_long(0)\n inc = ctypes.c_long(0)\n self._call(const.GET_, const.CDF_VERSION_, ctypes.byref(ver),\n const.GET_, const.CDF_RELEASE_, ctypes.byref(rel),\n const.GET_, const.CDF_INCREMENT_, ctypes.byref(inc))\n return (ver.value, rel.value, inc.value)\n\n def _get_attrs(self):\n \"\"\"Get attribute list\n\n Provide access to the CDF's attribute list without holding a\n strong reference, as the attribute list has a (strong)\n back-reference to its parent.\n\n Either deref a weak reference (to try and keep the object the same),\n or make a new AttrList instance and assign it to the weak reference\n for next time.\n \"\"\"\n al = self._attrlistref()\n if al is None:\n al = gAttrList(self)\n self._attrlistref = weakref.ref(al)\n return al\n\n def _set_attrs(self, value):\n \"\"\"Assign to the attribute list\n\n Clears all elements of the attribute list and copies from value\n \"\"\"\n self.attrs.clone(value)\n\n attrs = property(\n _get_attrs, _set_attrs, None,\n \"\"\"Global attributes for this CDF in a dict-like format.\n See :class:`gAttrList` for details.\n \"\"\")\n\n def var_num(self, varname):\n \"\"\"Get the variable number of a particular variable name\n\n This maintains a cache of name-to-number mappings for zVariables\n to keep from having to query the CDF library constantly. It's mostly\n an internal function.\n\n Parameters\n ==========\n varname : bytes\n name of the zVariable. Not this is NOT a string in Python 3!\n\n Raises\n ======\n CDFError : if variable is not found\n\n Returns\n =======\n out : int\n Variable number of this zvariable.\n \"\"\"\n num = self._var_nums.get(varname, None)\n if num is None: #Copied from Var._get, which can hopefully be thinned\n varNum = ctypes.c_long(0)\n self._call(const.GET_, const.zVAR_NUMBER_, varname,\n ctypes.byref(varNum))\n num = varNum.value\n self._var_nums[varname] = num\n return num\n\n def attr_num(self, attrname):\n \"\"\"Get the attribute number and scope by attribute name\n\n This maintains a cache of name-to-number mappings for attributes\n to keep from having to query the CDF library constantly. It's mostly\n an internal function.\n\n Parameters\n ==========\n attrname : bytes\n name of the zVariable. Not this is NOT a string in Python 3!\n\n Raises\n ======\n CDFError : if variable is not found\n\n Returns\n =======\n out : tuple\n attribute number, scope (True for global) of this attribute\n \"\"\"\n res = self._attr_info.get(attrname, None)\n if res is None: #Copied from Var._get, which can hopefully be thinned\n attrNum = ctypes.c_long(0)\n self._call(const.GET_, const.ATTR_NUMBER_, attrname,\n ctypes.byref(attrNum))\n scope = ctypes.c_long(0)\n self._call(const.SELECT_, const.ATTR_, attrNum,\n const.GET_, const.ATTR_SCOPE_, ctypes.byref(scope))\n if scope.value == const.GLOBAL_SCOPE.value:\n scope = True\n elif scope.value == const.VARIABLE_SCOPE.value:\n scope = False\n else:\n raise CDFError(const.BAD_SCOPE)\n res = (attrNum.value, scope)\n self._attr_info[attrname] = res\n return res\n\n def clear_attr_from_cache(self, attrname):\n \"\"\"Mark an attribute deleted in the name-to-number cache\n\n Will remove an attribute, and all attributes with higher numbers,\n from the attribute cache.\n\n Does NOT delete the variable!\n\n This maintains a cache of name-to-number mappings for attributes\n to keep from having to query the CDF library constantly. It's mostly\n an internal function.\n\n Parameters\n ==========\n attrname : bytes\n name of the attribute. Not this is NOT a string in Python 3!\n \"\"\"\n num, scope = self.attr_num(attrname)\n #All numbers higher than this are renumbered\n for a, n in list(self._attr_info.items()):\n if n[0] >= num:\n del self._attr_info[a]\n\n def clear_from_cache(self, varname):\n \"\"\"Mark a variable deleted in the name-to-number cache\n\n Will remove a variable, and all variables with higher numbers,\n from the variable cache.\n\n Does NOT delete the variable!\n\n This maintains a cache of name-to-number mappings for zVariables\n to keep from having to query the CDF library constantly. It's mostly\n an internal function.\n\n Parameters\n ==========\n varname : bytes\n name of the zVariable. Not this is NOT a string in Python 3!\n \"\"\"\n num = self.var_num(varname)\n #All numbers higher than this are renumbered\n for v, n in list(self._var_nums.items()):\n if n >= num:\n del self._var_nums[v]\n\n def add_attr_to_cache(self, attrname, num, scope):\n \"\"\"Add an attribute to the name-to-number cache\n\n This maintains a cache of name-to-number mappings for attributes\n to keep from having to query the CDF library constantly. It's mostly\n an internal function.\n\n Parameters\n ==========\n varname : bytes\n name of the zVariable. Not this is NOT a string in Python 3!\n num : int\n number of the variable\n scope : bool\n True if global scope; False if variable scope.\n \"\"\"\n self._attr_info[attrname] = (num, scope)\n\n def add_to_cache(self, varname, num):\n \"\"\"Add a variable to the name-to-number cache\n\n This maintains a cache of name-to-number mappings for zVariables\n to keep from having to query the CDF library constantly. It's mostly\n an internal function.\n\n Parameters\n ==========\n varname : bytes\n name of the zVariable. Not this is NOT a string in Python 3!\n num : int\n number of the variable\n \"\"\"\n self._var_nums[varname] = num\n\n #Note there is no function for delete, currently handled in Var.rename\n #and Attr.rename by just deleting from the dict directly. Maybe this\n #should be differen (maybe should be possible to follow a variable across\n #a rename...)\n\n\nclass Var(MutableSequence):\n \"\"\"\n A CDF variable.\n\n This object does not directly store the data from the CDF; rather,\n it provides access to the data in a format that much like a Python\n list or numpy :class:`~numpy.ndarray`.\n General list information is available in the python docs:\n `1 <http://docs.python.org/tutorial/introduction.html#lists>`_,\n `2 <http://docs.python.org/tutorial/datastructures.html#more-on-lists>`_,\n `3 <http://docs.python.org/library/stdtypes.html#typesseq>`_.\n\n The CDF user's guide, section 2.3, provides background on variables.\n\n .. note::\n Not intended to be created directly; use methods of :class:`CDF` to gain access to a variable.\n\n A record-varying variable's data are viewed as a hypercube of dimensions\n n_dims+1 (the extra dimension is the record number). They are indexed in\n row-major fashion, i.e. the last index changes most frequently / is\n contiguous in memory. If the CDF is column-major, the data are\n transformed to row-major before return.\n\n Non record-varying variables are similar, but do not have the extra\n dimension of record number.\n\n Variables can be subscripted by a multidimensional index to return the\n data. Indices are in row-major order with the first dimension\n representing the record number. If the CDF is column major,\n the data are reordered to row major. Each dimension is specified\n by standard Python\n `slice <http://docs.python.org/tutorial/introduction.html#strings>`_\n notation, with dimensions separated by commas. The ellipsis fills in\n any missing dimensions with full slices. The returned data are\n lists; Python represents multidimensional arrays as nested lists.\n The innermost set of lists represents contiguous data.\n\n .. note::\n numpy 'fancy indexing' is *not* supported.\n\n Degenerate dimensions are 'collapsed', i.e. no list of only one\n element will be returned if a single subscript is specified\n instead of a range. (To avoid this, specify a slice like 1:2,\n which starts with 1 and ends before 2).\n\n Two special cases:\n \n 1. requesting a single-dimension slice for a\n record-varying variable will return all data for that\n record number (or those record numbers) for that variable.\n 2. Requests for multi-dimensional variables may skip the record-number\n dimension and simply specify the slice on the array itself. In that\n case, the slice of the array will be returned for all records.\n\n In the event of ambiguity (e.g., single-dimension slice on a one-dimensional\n variable), case 1 takes priority.\n Otherwise, mismatch between the number of dimensions specified in\n the slice and the number of dimensions in the variable will cause\n an :exc:`~exceptions.IndexError` to be thrown.\n\n This all sounds very complicated but it is essentially attempting\n to do the 'right thing' for a range of slices.\n\n An unusual case is scalar (zero-dimensional) non-record-varying variables.\n Clearly they cannot be subscripted normally. In this case, use the\n ``[...]`` syntax meaning 'access all data.':\n\n >>> import pycdf\n >>> testcdf = pycdf.CDF('test.cdf', '')\n >>> variable = testcdf.new('variable', recVary=False,\n ... type=pycdf.const.CDF_INT4)\n >>> variable[...] = 10\n >>> variable\n <Var:\n CDF_INT4 [] NRV\n >\n >>> variable[...]\n 10\n\n Reading any empty non-record-varying variable will return an empty\n with the same *number* of dimensions, but all dimensions will be\n of zero length. The scalar is, again, a special case: due to the\n inability to have a numpy array which is both zero-dimensional and empty,\n reading an NRV scalar variable with no data will return an empty\n one-dimensional array. This is really not recommended.\n\n As a list type, variables are also `iterable\n <http://docs.python.org/tutorial/classes.html#iterators>`_; iterating\n over a variable returns a single complete record at a time.\n\n This is all clearer with examples. Consider a variable ``B_GSM``, with\n three elements per record (x, y, z components) and fifty records in\n the CDF. Then:\n \n 1. ``B_GSM[0, 1]`` is the y component of the first record.\n 2. ``B_GSM[10, :]`` is a three-element list, containing x, y, and z\n components of the 11th record. As a shortcut, if only one dimension\n is specified, it is assumed to be the record number, so this\n could also be written ``B_GSM[10]``.\n 3. ``B_GSM[...]`` reads all data for ``B_GSM`` and returns it as a\n fifty-element list, each element itself being a three-element\n list of x, y, z components.\n\n Multidimensional example: consider fluxes stored as a function of\n pitch angle and energy. Such a variable may be called Flux and\n stored as a two-dimensional array, with the first dimension\n representing (say) ten energy steps and the second, eighteen\n pitch angle bins (ten degrees wide, centered from 5 to 175 degrees).\n Assume 100 records stored in the CDF (i.e. 100 different times).\n \n 1. ``Flux[4]`` is a list of ten elements, one per energy step,\n each element being a list of 18 fluxes, one per pitch bin.\n All are taken from the fifth record in the CDF.\n 2. ``Flux[4, :, 0:4]`` is the same record, all energies, but\n only the first four pitch bins (roughly, field-aligned).\n 3. ``Flux[..., 0:4]`` is a 100-element list (one per record),\n each element being a ten-element list (one per energy step),\n each containing fluxes for the first four pitch bins.\n\n This slicing notation is very flexible and allows reading\n specifically the desired data from the CDF.\n\n All data are, on read, converted to appropriate Python data\n types; EPOCH, EPOCH16, and TIME_TT2000 types are converted to\n :class:`~datetime.datetime`. Data are returned in numpy arrays.\n\n .. note::\n Although pycdf supports TIME_TT2000 variables, the Python\n :class:`~datetime.datetime` object does not support leap\n seconds. Thus, on read, any seconds past 59 are truncated\n to 59.999999 (59 seconds, 999 milliseconds, 999 microseconds).\n\n Potentially useful list methods and related functions:\n - `count <http://docs.python.org/tutorial/datastructures.html#more-on-lists>`_\n - `in <http://docs.python.org/reference/expressions.html#in>`_\n - `index <http://docs.python.org/tutorial/datastructures.html#more-on-lists>`_\n - `len <http://docs.python.org/library/functions.html#len>`_\n - `list comprehensions\n <http://docs.python.org/tutorial/datastructures.html#list-comprehensions>`_\n - `sorted <http://docs.python.org/library/functions.html#sorted>`_\n\n The topic of array majority can be very confusing; good background material\n is available at `IDL Array Storage and Indexing\n <http://www.idlcoyote.com/misc_tips/colrow_major.html>`_. In brief,\n *regardless of the majority stored in the CDF*, pycdf will always present\n the data in the native Python majority, row-major order, also known as\n C order. This is the default order in `NumPy\n <http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html\n #internal-memory-layout-of-an-ndarray>`_.\n However, packages that render image data may expect it in column-major\n order. If the axes seem 'swapped' this is likely the reason.\n\n The :attr:`~Var.attrs` Python attribute acts as a dictionary referencing\n zAttributes (do not confuse the two); all the dictionary methods above\n also work on the attribute dictionary. See :class:`zAttrList` for more on\n the dictionary of attributes.\n\n With writing, as with reading, every attempt has been made to match the\n behavior of Python lists. You can write one record, many records, or even\n certain elements of all records. There is one restriction: only the record\n dimension (i.e. dimension 0) can be resized by write, as all records\n in a variable must have the same dimensions. Similarly, only whole\n records can be deleted.\n\n .. note::\n Unusual error messages on writing data usually mean that pycdf is\n unable to interpret the data as a regular array of a single type\n matching the type and shape of the variable being written.\n A 5x4 array is supported; an irregular array where one row has\n five columns and a different row has six columns is not. Error messages\n of this type include:\n\n - ``Data must be well-formed, regular array of number, string, or datetime``\n - ``setting an array element with a sequence.``\n - ``shape mismatch: objects cannot be broadcast to a\n single shape``\n\n For these examples, assume Flux has 100 records and dimensions [2, 3].\n \n Rewrite the first record without changing the rest:\n \n >>> Flux[0] = [[1, 2, 3], [4, 5, 6]]\n \n Writes a new first record and delete all the rest:\n\n >>> Flux[...] = [[1, 2, 3], [4, 5, 6]]\n \n Write a new record in the last position and add a new record after:\n\n >>> Flux[99:] = [[[1, 2, 3], [4, 5, 6]],\n ... [[11, 12, 13], [14, 15, 16]]]\n \n Insert two new records between the current number 5 and 6:\n \n >>> Flux[5:6] = [[[1, 2, 3], [4, 5, 6]], [[11, 12, 13],\n ... [14, 15, 16]]]\n\n This operation can be quite slow, as it requires reading and\n rewriting the entire variable. (CDF does not directly support\n record insertion.)\n \n Change the first element of the first two records but leave other\n elements alone:\n\n >>> Flux[0:2, 0, 0] = [1, 2]\n\n Remove the first record:\n\n >>> del Flux[0]\n\n Removes record 5 (the sixth):\n\n >>> del Flux[5]\n\n Due to the need to work around a bug in the CDF library, this operation\n can be quite slow.\n \n Delete *all data* from ``Flux``, but leave the variable definition intact:\n\n >>> del Flux[...]\n\n .. note::\n Although this interface only directly supports zVariables, zMode is\n set on opening the CDF so rVars appear as zVars. See p.24 of the\n CDF user's guide; pyCDF uses zMode 2.\n\n\n .. autosummary::\n\n ~Var.attrs\n ~Var.compress\n ~Var.copy\n ~Var.dtype\n ~Var.dv\n ~Var.insert\n ~Var.name\n ~Var.rename\n ~Var.rv\n ~Var.shape\n ~Var.type\n .. attribute:: Var.attrs\n\n zAttributes for this zVariable in a dict-like format.\n See :class:`zAttrList` for details.\n .. automethod:: compress\n .. automethod:: copy\n .. autoattribute:: dtype\n .. automethod:: dv\n .. automethod:: insert\n .. automethod:: name\n .. automethod:: rename\n .. automethod:: rv\n .. autoattribute:: shape\n .. automethod:: type\n \"\"\"\n def __init__(self, cdf_file, var_name, *args):\n \"\"\"Create or locate a variable\n\n Parameters\n ==========\n cdf_file : :py:class:`pycdf.CDF`\n CDF file containing this variable\n var_name : string\n name of this variable\n\n Other Parameters\n ================\n args\n additional arguments passed to :py:meth:`_create`. If none,\n opens an existing variable. If provided, creates a\n new one.\n\n Raises\n ======\n CDFError\n if CDF library reports an error\n\n Warns\n =====\n CDFWarning\n if CDF library reports a warning\n \"\"\"\n self.cdf_file = cdf_file\n #This is the definitive \"identify\" of variable\n self._name = None\n self._type = None #CDF type (long)\n self._raw = False #Raw access (skip all conversions)\n if len(args) == 0:\n self._get(var_name)\n else:\n self._create(var_name, *args)\n #Weak reference to attribute list (use attrs instead)\n #This avoids a reference loop\n self._attrlistref = weakref.ref(zAttrList(self))\n\n def __getitem__(self, key):\n \"\"\"Returns a slice from the data array. Details under :py:class:`pycdf.Var`.\n\n @return: The data from this variable\n @rtype: list-of-lists of appropriate type.\n @raise IndexError: if L{key} is out of range, mismatches dimensions,\n or simply unparseable.\n @raise CDFError: for errors from the CDF library\n \"\"\"\n hslice = _Hyperslice(self, key)\n #Hyperslice mostly catches this sort of thing, but\n #an empty variable is a special case, since we might want to\n #WRITE to 0th record (which Hyperslice also supports) but\n #can't READ from it, and iterating over tries to read from it.\n if hslice.rv:\n if hslice.dimsizes[0] == 0 and hslice.degen[0] and \\\n hslice.starts[0] == 0:\n raise IndexError('record index out of range')\n #For NRV, again hslice will assume 0th record exists since we might\n #want to write. So ANY degenerate dim other than the glued-on 0th\n #suggests an explicit index that should fail. None degenerate suggests\n #make an empty array.\n #Note this is pulling a lot of hyperslice stuff into getitem!\n elif hslice.dimsizes[0] == 0:\n if len(hslice.degen) > 1 and max(hslice.degen[1:]):\n raise IndexError('record index out of range')\n else:\n #The zero-length dimension is degenerate so it gets chopped,\n #and you can't have a zero-length numpy array that still\n #maintains the size of all other dimensions. So just force\n #a zero-dim array and the rest will follow\n hslice.counts[...] = 0\n #If this is a scalar, need to make a single non-degenerate\n #dimension so it can be empty.\n if len(hslice.counts) == 1:\n hslice.degen[0] = False\n result = hslice.create_array()\n if hslice.counts[0] != 0:\n hslice.select()\n lib.call(const.GET_, const.zVAR_HYPERDATA_,\n result.ctypes.data_as(ctypes.c_void_p))\n return hslice.convert_input_array(result)\n\n def __delitem__(self, key):\n \"\"\"Removes a record (or set of records) from the CDF\n\n Only whole records can be deleted, so the del call must either specify\n only one dimension or it must specify all elements of the non-record\n dimensions. This is *not* a way to resize a variable!\n\n Deleting records from the middle of a variable may be very slow in\n some circumstances. To work around a bug in CDF library versions\n 3.4.0 and before, all the data must be read in, the requested deletions\n done, and then all written back out.\n\n @param key: index or slice to delete\n @type key: int or slice\n @raise TypeError: if an attempt is made to delete from a non\n record-varying variable, or to delete below\n the record level\n \"\"\"\n if not self.rv():\n raise TypeError('Cannot delete records from non-record-varying '\n 'variable.')\n hslice = _Hyperslice(self, key)\n if hslice.dims > 1 and (hslice.counts[1:] != hslice.dimsizes[1:]).any():\n raise TypeError('Can only delete entire records.')\n if hslice.counts[0] == 0:\n return\n start = hslice.starts[0]\n count = hslice.counts[0]\n interval = hslice.intervals[0]\n dimsize = hslice.dimsizes[0]\n\n self._call()\n dangerous_delete = False\n if lib._del_middle_rec_bug and \\\n (interval != 1 or (start != 0 and start + count < dimsize)):\n #delete from middle is dangerous if only have one index entry\n entries = ctypes.c_long(0)\n lib.call(const.GET_, const.zVAR_nINDEXENTRIES_,\n ctypes.byref(entries))\n dangerous_delete = (entries.value == 1)\n\n if dangerous_delete:\n data = self[...]\n data = numpy.delete(\n data,\n numpy.arange(start, start + count * interval, interval),\n 0)\n self[0:dimsize - count] = data\n first_rec = dimsize - count\n last_rec = dimsize - 1\n lib.call(const.DELETE_, const.zVAR_RECORDS_,\n ctypes.c_long(first_rec), ctypes.c_long(last_rec))\n elif interval == 1:\n first_rec = ctypes.c_long(start)\n last_rec = ctypes.c_long(start + count - 1)\n lib.call(const.DELETE_, const.zVAR_RECORDS_,\n first_rec, last_rec)\n else:\n self._call()\n #delete from end to avoid renumbering of records\n for recno in range(start + (count - 1) * interval,\n start - 1, -1 * interval):\n lib.call(const.DELETE_, const.zVAR_RECORDS_,\n ctypes.c_long(recno), ctypes.c_long(recno))\n\n def __setitem__(self, key, data):\n \"\"\"Puts a slice into the data array. Details under :py:class:`pycdf.Var`.\n\n @param key: index or slice to store\n @type key: int or slice\n @param data: data to store\n @type data: numpy.array\n @raise IndexError: if L{key} is out of range, mismatches dimensions,\n or simply unparseable. IndexError will\n @raise CDFError: for errors from the CDF library\n \"\"\"\n hslice = _Hyperslice(self, key)\n n_recs = hslice.counts[0]\n hslice.expand(data)\n cdf_type = self.type()\n if cdf_type == const.CDF_EPOCH16.value:\n if not self._raw:\n try:\n data = lib.v_datetime_to_epoch16(data)\n except AttributeError:\n pass\n data = numpy.require(data, requirements=('C', 'A', 'W'),\n dtype=numpy.float64)\n elif cdf_type == const.CDF_EPOCH.value:\n if not self._raw:\n try:\n data = lib.v_datetime_to_epoch(data)\n except AttributeError:\n pass\n data = numpy.require(data, requirements=('C', 'A', 'W'),\n dtype=numpy.float64)\n elif cdf_type == const.CDF_TIME_TT2000.value:\n if not self._raw:\n try:\n data = lib.v_datetime_to_tt2000(data)\n except AttributeError:\n pass\n data = numpy.require(data, requirements=('C', 'A', 'W'),\n dtype=numpy.int64)\n else:\n data = numpy.require(data, requirements=('C', 'A', 'W'),\n dtype=self._np_type())\n if cdf_type == const.CDF_EPOCH16.value:\n datashape = data.shape[:-1]\n else:\n datashape = data.shape\n #Check data sizes\n if datashape != tuple(hslice.expected_dims()):\n raise ValueError('attempt to assign data of dimensions ' +\n str(datashape) + ' to slice of dimensions ' +\n str(tuple(hslice.expected_dims())))\n #Flip majority and reversed dimensions, see convert_input_array\n data = hslice.convert_output_array(data)\n #Handle insertions and similar weirdness\n if hslice.counts[0] > n_recs and \\\n hslice.starts[0] + n_recs < hslice.dimsizes[0]:\n #Specified slice ends before last record, so insert in middle\n saved_data = self[hslice.starts[0] + n_recs:]\n if hslice.counts[0] > 0:\n hslice.select()\n lib.call(const.PUT_, const.zVAR_HYPERDATA_,\n data.ctypes.data_as(ctypes.c_void_p))\n if hslice.counts[0] < n_recs:\n first_rec = hslice.starts[0] + hslice.counts[0]\n last_rec = hslice.dimsizes[0] - 1\n lib.call(const.DELETE_, const.zVAR_RECORDS_,\n ctypes.c_long(first_rec), ctypes.c_long(last_rec))\n elif hslice.counts[0] > n_recs and \\\n hslice.starts[0] + n_recs < hslice.dimsizes[0]:\n #Put saved data in after inserted data\n self[hslice.starts[0] + hslice.counts[0]:] = saved_data\n\n def extend(self, data):\n \"\"\"\n Append multiple values to the end of this variable\n\n This is an efficiency function which overrides the base implementation\n in MutableSequence.\n\n Parameters\n ----------\n data :\n the data to append\n \"\"\"\n self[len(self):] = data\n\n def insert(self, index, data):\n \"\"\"\n Inserts a *single* record before an index\n\n Parameters\n ----------\n index : int\n index before which to insert the new record\n data :\n the record to insert\n \"\"\"\n self[index:index] = [data]\n\n def _create(self, var_name, datatype, n_elements = 1, dims = (),\n recVary = const.VARY, dimVarys = None):\n \"\"\"Creates a new zVariable\n\n @param var_name: name of this variable\n @type var_name: string\n @param datatype: CDF data type\n @type datatype: ctypes.c_long\n @param n_elements: number of elements (should be 1 except for\n CDF_CHAR variables).\n @type n_elements: long\n @param dims: size of each dimension for multi-dimensional variable,\n or empty for a zero-dimensional\n @type dims: sequence of long\n @param recVary: record variance for this variable (VARY/NOVARY)\n @type recVary: long\n @param dimVarys: array of VARY or NOVARY, variance for each dimension\n @type dimVarys: sequence of long\n @return: new variable with this name\n @rtype: :py:class:`pycdf.Var`\n @raise CDFError: if CDF library reports an error\n @raise CDFWarning: if CDF library reports a warning and interpreter\n is set to error on warnings.\n @note: Not intended to be used directly; use L{CDF.new}.\n \"\"\"\n\n dim_array = (ctypes.c_long * len(dims))(*dims)\n enc_name = var_name.encode('ascii')\n if dimVarys is None:\n dim_vary_array = (ctypes.c_long * (len(dims) if len(dims) > 0 else 1))(const.VARY)\n else:\n dim_vary_array = (ctypes.c_long * len(dims))(*dimVarys)\n varNum = ctypes.c_long(0)\n self.cdf_file._call(const.CREATE_, const.zVAR_, enc_name, datatype,\n ctypes.c_long(n_elements), ctypes.c_long(len(dims)), dim_array,\n recVary, dim_vary_array, ctypes.byref(varNum))\n self._name = enc_name\n self.cdf_file.add_to_cache(enc_name, varNum.value)\n\n def _delete(self):\n \"\"\"Removes this zVariable from the CDF\n\n @raise CDFError: if CDF library reports an error\n @raise CDFWarning: if CDF library reports a warning and interpreter\n is set to error on warnings.\n \"\"\"\n self._call(const.DELETE_, const.zVAR_)\n self.cdf_file.clear_from_cache(self._name)\n self._name = None\n\n def _get(self, var_name):\n \"\"\"Gets an existing zVariable\n\n @param var_name: name of this variable\n @type var_name: string\n @return: variable with this name\n @rtype: :py:class:`pycdf.Var`\n @raise CDFError: if CDF library reports an error\n @raise CDFWarning: if CDF library reports a warning and interpreter\n is set to error on warnings.\n @note: Not intended to be used directly; use L{CDF.__getitem__}.\n \"\"\"\n\n if isinstance(var_name, str_classes):\n try:\n enc_name = var_name.encode('ascii').rstrip()\n except AttributeError:\n enc_name = var_name.rstrip() #already in ASCII\n #'touch' CDF to cause an error if the name isn't there; get number\n varNum = ctypes.c_long(0)\n self.cdf_file._call(const.GET_, const.zVAR_NUMBER_, enc_name, ctypes.byref(varNum))\n self._name = enc_name\n self.cdf_file.add_to_cache(enc_name, varNum.value)\n else: #Looking up by number\n name = ctypes.create_string_buffer(const.CDF_VAR_NAME_LEN256+1)\n self.cdf_file._call(const.SELECT_, const.zVAR_, ctypes.c_long(var_name),\n const.GET_, const.zVAR_NAME_, name)\n self._name = name.value.rstrip()\n self.cdf_file.add_to_cache(self._name, var_name)\n\n def _num(self):\n \"\"\"Returns the zVar number for this variable\n\n @return: number of this zVar\n @rtype: int\n \"\"\"\n return self.cdf_file.var_num(self._name)\n\n def __len__(self):\n \"\"\"Get number of records for this variable in this file\n\n @return: Number of records\n @rtype: long\n @raise CDFError: if CDF library reports an error\n @raise CDFWarning: if CDF library reports a warning and interpreter\n is set to error on warnings.\n \"\"\"\n count = ctypes.c_long(0)\n self._call(const.GET_, const.zVAR_MAXREC_, ctypes.byref(count))\n return (count.value + 1)\n\n def __repr__(self):\n \"\"\"Returns representation of the variable\n\n Cannot return anything that can be eval'd to create a copy,\n so just wrap the informal representation in angle brackets.\n @return: info on this zVar\n @rtype: str\n \"\"\"\n return '<Var:\\n' + str(self) + '\\n>'\n\n def __str__(self):\n \"\"\"Returns a string representation of the variable\n\n This is an 'informal' representation in that it cannot be evaluated\n directly to create a :py:class:`pycdf.Var`.\n\n @return: info on this zVar, CDFTYPE [dimensions] NRV\n (if not record-varying)\n @rtype: str\n \"\"\"\n if self.cdf_file._opened:\n cdftype = self.type()\n chartypes = (const.CDF_CHAR.value, const.CDF_UCHAR.value)\n rv = self.rv()\n typestr = lib.cdftypenames[cdftype] + \\\n ('*' + str(self._nelems()) if cdftype in chartypes else '' )\n if rv:\n sizestr = str([len(self)] + self._dim_sizes())\n else:\n sizestr = str(self._dim_sizes())\n return typestr + ' ' + sizestr + ('' if rv else ' NRV')\n else:\n if isinstance(self._name, str):\n return 'zVar \"{0}\" in closed CDF {1}'.format(\n self._name, self.cdf_file.pathname)\n else:\n return 'zVar \"{0}\" in closed CDF {1}'.format(\n self._name.decode('ascii'),\n self.cdf_file.pathname.decode('ascii'))\n\n def _n_dims(self):\n \"\"\"Get number of dimensions for this variable\n\n @return: the number of dimensions\n @rtype: long\n \"\"\"\n n_dims = ctypes.c_long(0)\n self._call(const.GET_, const.zVAR_NUMDIMS_, ctypes.byref(n_dims))\n return n_dims.value\n\n def _dim_sizes(self):\n \"\"\"Get the dimension sizes for this variable\n\n @return: sequence of sizes\n @rtype: sequence of long\n @note: This will always be in Python order (i.e. row major, last index\n iterates most quickly), *regardless* of the majority of the CDF.\n \"\"\"\n sizes = (ctypes.c_long * const.CDF_MAX_DIMS)(0)\n self._call(const.GET_, const.zVAR_DIMSIZES_, sizes)\n sizes = sizes[0:self._n_dims()]\n return sizes\n\n def rv(self, new_rv=None):\n \"\"\"\n Gets or sets whether this variable has record variance\n\n If the variance is unknown, True is assumed\n (this replicates the apparent behavior of the CDF library on\n variable creation).\n\n Other Parameters\n ================\n new_rv : boolean\n True to change to record variance, False to change to NRV,\n unspecified to simply check variance.\n\n Returns\n =======\n out : Boolean\n True if record varying, False if NRV\n \"\"\"\n if new_rv != None:\n self._call(const.PUT_, const.zVAR_RECVARY_,\n const.VARY if new_rv else const.NOVARY)\n vary = ctypes.c_long(0)\n self._call(const.GET_, const.zVAR_RECVARY_, ctypes.byref(vary))\n return vary.value != const.NOVARY.value\n\n def dv(self, new_dv=None):\n \"\"\"\n Gets or sets dimension variance of each dimension of variable.\n\n If the variance is unknown, True is assumed\n (this replicates the apparent behavior of the\n CDF library on variable creation).\n\n Parameters\n ==========\n new_dv : list of boolean\n Each element True to change that dimension to dimension\n variance, False to change to not dimension variance.\n (Unspecified to simply check variance.)\n\n Returns\n =======\n out : list of boolean\n True if that dimension has variance, else false.\n \"\"\"\n ndims = self._n_dims()\n if new_dv != None:\n if len(new_dv) != ndims:\n raise ValueError('Must specify variance for ' +\n str(ndims) + 'dimensions.')\n varies = (ctypes.c_long * ndims)(\n *[const.VARY if dv else const.NOVARY for dv in new_dv])\n self._call(const.PUT_, const.zVAR_DIMVARYS_,\n varies)\n if ndims == 0:\n return []\n varies = (ctypes.c_long * const.CDF_MAX_DIMS)()\n self._call(const.GET_, const.zVAR_DIMVARYS_, varies)\n return [dv != const.NOVARY.value for dv in varies[0:ndims]]\n\n def _call(self, *args, **kwargs):\n \"\"\"Select this CDF and variable and call the CDF internal interface\n\n Adds call to select this CDF to L{args} and passes all parameters\n directly through to the CDFlib routine of the CDF library's C internal\n interface. Checks the return value with L{Library.check_status}.\n\n @param args: Passed directly to the CDF library interface. Useful\n constants are defined in the :py:mod:`pycdf.const` module of this package.\n @type args: various, see :py:mod:`ctypes`.\n @return: CDF status from the library\n @rtype: ctypes.c_long\n @note: Terminal NULL_ is automatically added to L{args}.\n @raise CDFError: if CDF library reports an error\n @raise CDFWarning: if CDF library reports a warning and interpreter\n is set to error on warnings.\n \"\"\"\n return self.cdf_file._call(\n const.SELECT_, const.zVAR_,\n ctypes.c_long(self.cdf_file.var_num(self._name)), *args, **kwargs)\n\n def _np_type(self):\n \"\"\"Returns the numpy type of this variable\n\n This is the numpy type that will come directly out of the CDF;\n see :meth:`dtype` for the representation post-conversion.\n\n Raises\n ======\n CDFError : for library-reported error or failure to find numpy type\n\n Returns\n =======\n out : dtype\n numpy dtype that will hold value from this variable\n \n \"\"\"\n cdftype = self.type()\n if cdftype == const.CDF_CHAR.value or cdftype == const.CDF_UCHAR.value:\n return numpy.dtype('S' + str(self._nelems()))\n try:\n return lib.numpytypedict[cdftype]\n except KeyError:\n raise CDFError(const.BAD_DATA_TYPE)\n\n def type(self, new_type=None):\n \"\"\"\n Returns or sets the CDF type of this variable\n\n Parameters\n ==========\n new_type : ctypes.c_long\n the new type from :mod:`~pycdf.const`\n\n Returns\n =======\n out : int\n CDF type\n \"\"\"\n if new_type != None:\n if not hasattr(new_type, 'value'):\n new_type = ctypes.c_long(new_type)\n n_elements = ctypes.c_long(self._nelems())\n self._call(const.PUT_, const.zVAR_DATASPEC_,\n new_type, n_elements)\n self._type = None\n if self._type is None:\n cdftype = ctypes.c_long(0)\n self._call(const.GET_, const.zVAR_DATATYPE_,\n ctypes.byref(cdftype))\n self._type = cdftype.value\n return self._type\n\n def _nelems(self):\n \"\"\"Number of elements for each value in this variable\n\n This is the length of strings for CHAR and UCHAR,\n should be 1 otherwise.\n @return: length of strings\n @rtype: int\n \"\"\"\n nelems = ctypes.c_long(0)\n self._call(const.GET_, const.zVAR_NUMELEMS_, ctypes.byref(nelems))\n return nelems.value\n\n def name(self):\n \"\"\"\n Returns the name of this variable\n\n Returns\n =======\n out : str\n variable's name\n \"\"\"\n if isinstance(self._name, str):\n return self._name\n elif isinstance(self._name, bytes):\n return self._name.decode()\n\n def compress(self, comptype=None, param=None):\n \"\"\"\n Set or check the compression of this variable\n\n Compression may not be changeable on variables with data already\n written; even deleting the data may not permit the change.\n\n See section 2.6 of the CDF user's guide for more information on\n compression.\n\n Other Parameters\n ================\n comptype : ctypes.c_long\n type of compression to change to, see CDF C reference\n manual section 4.10. Constants for this parameter\n are in :mod:`~pycdf.const`. If not specified, will not\n change compression.\n param : ctypes.c_long\n Compression parameter, see CDF CRM 4.10 and\n :mod:`~pycdf.const`.\n If not specified, will choose reasonable default (5 for\n gzip; other types have only one possible parameter.)\n\n Returns\n =======\n out : tuple\n the (comptype, param) currently in effect\n \"\"\"\n return _compress(self, comptype, param)\n\n def copy(self):\n \"\"\"\n Copies all data and attributes from this variable\n\n Returns\n =======\n out : :class:`VarCopy`\n list of all data in record order\n \"\"\"\n return VarCopy(self)\n\n def rename(self, new_name):\n \"\"\"\n Renames this variable\n\n Parameters\n ==========\n new_name : str\n the new name for this variable\n \"\"\"\n try:\n enc_name = new_name.encode('ascii')\n except AttributeError:\n enc_name = new_name\n if len(enc_name) > const.CDF_VAR_NAME_LEN256:\n raise CDFError(const.BAD_VAR_NAME)\n self._call(const.PUT_, const.zVAR_NAME_, enc_name)\n self.cdf_file.add_to_cache(\n enc_name,\n self.cdf_file.var_num(self._name)) #Still in cache\n del self.cdf_file._var_nums[self._name]\n self._name = enc_name\n\n @property\n def shape(self):\n \"\"\"\n Provides the numpy array-like shape of this variable.\n\n Returns a tuple; first element is number of records (RV variable\n only) And the rest provide the dimensionality of the variable.\n\n .. note::\n Assigning to this attribute will not change the shape.\n \"\"\"\n if self.rv():\n return tuple([len(self)] + self._dim_sizes())\n else:\n return tuple(self._dim_sizes())\n\n @property\n def dtype(self):\n \"\"\"\n Provide the numpy dtype equivalent to the CDF type of this variable.\n\n Data from this variable will be returned in numpy arrays of this type.\n\n See Also\n --------\n type\n \"\"\"\n cdftype = self.type()\n if cdftype in (const.CDF_CHAR.value, const.CDF_UCHAR.value) and \\\n str is not bytes and not self._raw:\n return numpy.dtype('U' + str(self._nelems()))\n if cdftype in (const.CDF_EPOCH.value, const.CDF_EPOCH16.value,\n const.CDF_TIME_TT2000.value) and not self._raw:\n return numpy.dtype('O')\n return self._np_type()\n\n def _get_attrs(self):\n \"\"\"Get attribute list\n\n Provide access to the zVar's attribute list without holding a\n strong reference, as the attribute list has a (strong)\n back-reference to its parent.\n\n Either deref a weak reference (to try and keep the object the same),\n or make a new AttrList instance and assign it to the weak reference\n for next time.\n \"\"\"\n al = self._attrlistref()\n if al is None:\n al = zAttrList(self)\n self._attrlistref = weakref.ref(al)\n return al\n\n def _set_attrs(self, value):\n \"\"\"Assign to the attribute list\n\n Clears all elements of the attribute list and copies from value\n \"\"\"\n self.attrs.clone(value)\n\n attrs = property(\n _get_attrs, _set_attrs, None,\n \"\"\"zAttributes for this zVariable in a dict-like format.\n See :class:`zAttrList` for details.\n \"\"\")\n\n\n\nclass _Hyperslice(object):\n \"\"\"Represents a CDF 'slice' used for the hyper CDF functions\n\n For internal module use only.\n\n @ivar dims: number of dimensions to this slice, usually\n number of dimensions to the variable plus one\n for the record, which represents the 0th\n (least rapidly varying) dimension.\n @type dims: int\n @ivar dimsizes: size of each dimension (0th is number of records)\n @type dimsizes: list of int\n @ivar starts: index of the start value for each dimension\n ('dimension indices' in CDF speak)\n @type starts: list of int\n @ivar counts: number of values to get from each dimension.\n Final result will be the product of everything\n in counts.\n ('dimension counts' in CDF speak)\n @type counts: numpy.array\n @ivar intervals: interval between successive indices\n to use for each dimension.\n ('dimension invervals' in CDF speak)\n @type intervals: list of int\n @ivar degen: is this dimension degenerate, i.e. should be\n removed in the returned dataset. A 3D array\n with one dimension degenerate will be returned\n as a 2D array (i.e. list-of-lists.)\n @type degen: numpy.array\n @ivar rev: should this dimension be returned in reverse order?\n @type rev: numpy.array\n @ivar column: is this slice in column-major mode (if false, row-major)\n @type column: boolean\n @ivar zvar: what CDF variable this object slices on\n @type zvar: :py:class:`pycdf.Var`\n @ivar expanded_key: fully-expanded version of the key passed to the\n constructor (all dimensions filled in)\n @type expanded_key: tuple\n @note: All dimension-related variables are stored row-major\n (Python order)\n \"\"\"\n\n def __init__(self, zvar, key):\n \"\"\"Create a Hyperslice\n\n @param zvar: zVariable that this slices\n @type zvar: :py:class:`pycdf.Var`\n @param key: Python multi-dimensional slice as passed to\n __getitem__\n @type key: tuple of slice and/or int\n @raise IndexError: if slice is out of range, mismatches dimensions, or\n otherwise unparsable.\n @raise ValueError: if slice has invalid values\n \"\"\"\n\n self.zvar = zvar\n self.rv = self.zvar.rv()\n #dim of records, + 1 record dim (NRV always is record 0)\n self.dims = zvar._n_dims() + 1\n self.dimsizes = [len(zvar)] + \\\n zvar._dim_sizes()\n self.starts = [0] * self.dims\n self.counts = numpy.empty((self.dims,), dtype=numpy.int32)\n self.counts.fill(1)\n self.intervals = [1] * self.dims\n self.degen = numpy.zeros(self.dims, dtype=numpy.bool)\n self.rev = numpy.zeros(self.dims, dtype=numpy.bool)\n #key is:\n #1. a single value (integer or slice object) if called 1D\n #2. a tuple (of integers and/or slice objects) if called nD\n #3. Each item is either a single value (degenerate dim)\n # or a slice object.\n\n if not hasattr(key, '__len__'): #Not a container object, pack in tuple\n key = (key, )\n if not self.rv:\n key = (0, ) + key #NRV, so always get 0th record (degenerate)\n key = self.expand_ellipsis(key, self.dims)\n if self.rv: #special-cases for RV variables\n if len(key) == 1: #get all data for this record(s)\n key = self.expand_ellipsis(key + (Ellipsis, ), self.dims)\n elif len(key) == self.dims - 1: #get same slice from each record\n key = (slice(None, None, None), ) + key\n if len(key) == self.dims:\n self.expanded_key = key\n for i in range(self.dims):\n idx = key[i]\n if hasattr(idx, 'start'): #slice\n (self.starts[i], self.counts[i],\n self.intervals[i], self.rev[i]) = \\\n self.convert_range(idx.start, idx.stop,\n idx.step, self.dimsizes[i])\n else: #Single degenerate value\n if idx < 0:\n idx += self.dimsizes[i]\n if idx != 0 and (idx >= self.dimsizes[i] or idx < 0):\n raise IndexError('list index out of range')\n self.starts[i] = idx\n self.degen[i] = True\n else:\n raise IndexError('Slice does not match dimensions for zVar ' +\n str(zvar._name))\n\n self.column = zvar.cdf_file.col_major()\n\n def expected_dims(self, data=None):\n \"\"\"Calculate size of non-degenerate dimensions\n\n Figures out size, in each dimension, of expected input data\n\n @return: size of each dimension for this slice, excluding degenerate\n @rtype: list of int\n \"\"\"\n return [self.counts[i] for i in range(self.dims) if not self.degen[i]]\n\n def expand(self, data):\n \"\"\"Expands the record dimension of this slice to hold a set of data\n\n If the length of data (outermost dimension) is larger than the record\n count (counts[0]) for this slice, expand the slice to hold all the data.\n This requires that the record dimension of the slice not be degenerate,\n and also that it not have been completely specified when the hyperslice\n was created (i.e. record dimension either ellipsis or no specified\n stop.)\n\n Does *not* expand any other dimension, since that's Very Hard in CDF.\n\n @param data: the data which are intended to be stored in this slice\n @type data: list\n \"\"\"\n rec_slice = self.expanded_key[0]\n if not self.rv or isinstance(data, str_classes) or self.degen[0] or \\\n not hasattr(rec_slice, 'stop'):\n return\n if len(data) < self.counts[0]: #Truncate to fit data\n if rec_slice.stop is None and rec_slice.step in (None, 1):\n self.counts[0] = len(data)\n elif len(data) > self.counts[0]: #Expand to fit data\n if rec_slice.step in (None, 1):\n self.counts[0] = len(data)\n\n def create_array(self):\n \"\"\"Creates a numpy array to hold the data from this slice\n\n Returns\n =======\n out : numpy.array\n array sized, typed, and dimensioned to hold data from\n this slice\n \"\"\"\n counts = self.counts\n degen = self.degen\n if self.column:\n counts = self.reorder(counts)\n degen = self.reorder(degen)\n #TODO: Forcing C order for now, revert to using self.column later\n array = numpy.empty(\n [counts[i] for i in range(len(counts)) if not degen[i]],\n self.zvar._np_type(), order='C')\n return numpy.require(array, requirements=('C', 'A', 'W'))\n \n def convert_input_array(self, buffer):\n \"\"\"Converts a buffer of raw data from this slice\n\n EPOCH(16) variables always need to be converted.\n CHAR need converted to Unicode if py3k\n\n Parameters\n ==========\n buffer : numpy.array\n data as read from the CDF file\n\n Returns\n =======\n out : numpy.array\n converted data\n \"\"\"\n result = self._flip_array(buffer)\n\n #Convert to derived types\n cdftype = self.zvar.type()\n if not self.zvar._raw:\n if cdftype in (const.CDF_CHAR.value, const.CDF_UCHAR.value) and \\\n str != bytes:\n dt = numpy.dtype('U{0}'.format(result.dtype.itemsize))\n result = numpy.require(numpy.char.array(result).decode(),\n dtype=dt)\n elif cdftype == const.CDF_EPOCH.value:\n result = lib.v_epoch_to_datetime(result)\n elif cdftype == const.CDF_EPOCH16.value:\n result = lib.v_epoch16_to_datetime(result)\n elif cdftype == const.CDF_TIME_TT2000.value:\n result = lib.v_tt2000_to_datetime(result)\n return result\n\n def convert_output_array(self, buffer):\n \"\"\"Convert a buffer of data that will go into this slice\n \n Parameters\n ==========\n buffer : numpy.array\n data to go into the CDF file\n\n Returns\n =======\n out : numpy.array\n input with majority flipped and dimensions reversed to be\n suitable to pass directly to CDF library.\n \"\"\"\n buffer = self._flip_array(buffer)\n return numpy.require(buffer, requirements=('C', 'A', 'W'))\n\n def _flip_array(self, data):\n \"\"\"\n Operations for majority, etc. common between convert_input and _output\n \"\"\"\n cdftype = self.zvar.type()\n #Flip majority if any non-degenerate dimensions exist\n if self.column and not min(self.degen):\n #Record-number dim degen, swap whole thing\n if self.degen[0]:\n if cdftype == const.CDF_EPOCH16.value:\n #Maintain last dimension\n data = data.transpose(\n list(range(len(data.shape) - 2, 0, -1)) +\n [len(data.shape) - 1]\n )\n else:\n data = data.transpose()\n #Record-number dimension is not degenerate, so keep it first\n else:\n if cdftype == const.CDF_EPOCH16.value:\n data = data.transpose(\n [0] + list(range(len(data.shape) - 2, 0, -1)) +\n [len(data.shape) - 1]\n )\n else:\n data = data.transpose(\n [0] + list(range(len(data.shape) - 1, 0, -1)))\n #Reverse non-degenerate dimensions in rev\n #Remember that the degenerate indices are already gone!\n if self.rev.any():\n sliced = [(slice(None, None, -1) if self.rev[i] else slice(None))\n for i in range(self.dims) if not self.degen[i]]\n if cdftype == const.CDF_EPOCH16.value: #don't reverse last dim\n sliced.extend(slice(None))\n data = operator.getitem(data, tuple(sliced))\n return data\n\n def select(self):\n \"\"\"Selects this hyperslice in the CDF\n\n Calls the CDF library to select the CDF, variable, records, and\n array elements corresponding to this slice.\n \"\"\"\n args = (const.SELECT_, const.zVAR_RECNUMBER_, ctypes.c_long(self.starts[0]),\n const.SELECT_, const.zVAR_RECCOUNT_, ctypes.c_long(self.counts[0]),\n const.SELECT_, const.zVAR_RECINTERVAL_,\n ctypes.c_long(self.intervals[0]))\n if self.dims > 1:\n dims = self.dims - 1\n args += (const.SELECT_, const.zVAR_DIMINDICES_,\n (ctypes.c_long * dims)(*self.starts[1:]),\n const.SELECT_, const.zVAR_DIMCOUNTS_,\n (ctypes.c_long * dims)(*self.counts[1:]),\n const.SELECT_, const.zVAR_DIMINTERVALS_,\n (ctypes.c_long * dims)(*self.intervals[1:]))\n self.zvar._call(*args)\n\n @staticmethod\n def expand_ellipsis(slices, n_dims):\n \"\"\"Expands any ellipses into correct number of full-size slices\n\n @param slices: tuple of slices, integers, or ellipse objects\n @type slices: tuple\n @param n_dims: number of dimensions this slice is over\n @type n_dims: int\n @return: L{slices} with ellipses replaced by appropriate number of\n full-dimension slices\n @rtype: tuple\n @raise IndexError: if ellipses specified when already have enough\n dimensions\n \"\"\"\n if slices is Ellipsis:\n return tuple([slice(None, None, None)\n for i in range(n_dims)])\n #Elements might be numpy arrays, so can't use in/index\n idx = [i for i, v in enumerate(slices) if v is Ellipsis]\n if not idx: #no ellipsis\n return slices\n if len(idx) > 1: #multiples!\n raise IndexError('Ellipses can only be used once per slice.')\n idx = idx[0]\n\n #how many dims to expand ellipsis to\n #remember the ellipsis is in len(slices) and must be replaced!\n extra = n_dims - len(slices) + 1\n if extra < 0:\n raise IndexError('too many indices')\n result = slices[0:idx] + (slice(None), ) * extra + slices[idx+1:]\n return result\n\n @staticmethod\n def check_well_formed(data):\n \"\"\"Checks if input data is well-formed, regular array\"\"\"\n d = numpy.asanyarray(data)\n if d.dtype == numpy.object: #this is probably going to be bad\n try:\n len(d.flat[0])\n except TypeError: #at least it's not a list\n pass\n else:\n raise ValueError(\n 'Data must be well-formed, regular array of number, '\n 'string, or datetime')\n\n @staticmethod\n def dimensions(data):\n \"\"\"Finds the dimensions of a nested list-of-lists\n\n @param data: data of which dimensions are desired\n @type data: list (of lists)\n @return: dimensions of L{data}, in order outside-in\n @rtype: list of int\n @raise ValueError: if L{data} has irregular dimensions\n \"\"\"\n d = numpy.asanyarray(data)\n _Hyperslice.check_well_formed(d)\n return d.shape\n\n @staticmethod\n def types(data, backward=False):\n \"\"\"Find dimensions and valid types of a nested list-of-lists\n\n Any given data may be representable by a range of CDF types; infer\n the CDF types which can represent this data. This breaks down to:\n 1. Proper kind (numerical, string, time)\n 2. Proper range (stores highest and lowest number)\n 3. Sufficient resolution (EPOCH16 required if datetime has\n microseconds or below.)\n\n If more than one value satisfies the requirements, types are returned\n in preferred order:\n 1. Type that matches precision of data first, then\n 2. integer type before float type, then\n 3. Smallest type first, then\n 4. signed type first, then\n 5. specifically-named (CDF_BYTE) vs. generically named (CDF_INT1)\n So for example, EPOCH_16 is preferred over EPOCH if L{data} specifies\n below the millisecond level (rule 1), but otherwise EPOCH is preferred\n (rule 2).\n\n For floats, four-byte is preferred unless eight-byte is required:\n 1. absolute values between 0 and 3e-39\n 2. absolute values greater than 1.7e38\n This will switch to an eight-byte double in some cases where four bytes\n would be sufficient for IEEE 754 encoding, but where DEC formats would\n require eight.\n\n @param data: data for which dimensions and CDF types are desired\n @type data: list (of lists)\n @param backward: limit to pre-CDF3 types\n @type backward: bool\n @return: dimensions of L{data}, in order outside-in;\n CDF types which can represent this data;\n number of elements required (i.e. length of longest string)\n @rtype: 3-tuple of lists ([int], [ctypes.c_long], [int])\n @raise ValueError: if L{data} has irregular dimensions\n \"\"\"\n d = numpy.asanyarray(data)\n dims = d.shape\n elements = 1\n types = []\n\n _Hyperslice.check_well_formed(d)\n if d.dtype.kind in ('S', 'U'): #it's a string\n types = [const.CDF_CHAR, const.CDF_UCHAR]\n elements = d.dtype.itemsize\n if d.dtype.kind == 'U': #UTF-8 uses 4 bytes per\n elements //= 4\n elif d.size and hasattr(numpy.ma.getdata(d).flat[0], 'microsecond'):\n if max((dt.microsecond % 1000 for dt in d.flat)) > 0:\n types = [const.CDF_EPOCH16, const.CDF_EPOCH,\n const.CDF_TIME_TT2000]\n else:\n types = [const.CDF_EPOCH, const.CDF_EPOCH16,\n const.CDF_TIME_TT2000]\n if backward:\n del types[types.index(const.CDF_EPOCH16)]\n del types[-1]\n elif not lib.supports_int8:\n del types[-1]\n elif d is data or isinstance(data, numpy.generic):\n #numpy array came in, use its type (or byte-swapped)\n types = [k for k in lib.numpytypedict\n if (lib.numpytypedict[k] == d.dtype\n or lib.numpytypedict[k] == d.dtype.newbyteorder())\n and not k in lib.timetypes]\n if (not lib.supports_int8 or backward) \\\n and const.CDF_INT8.value in types:\n del types[types.index(const.CDF_INT8.value)]\n #Maintain priority to match the ordered lists below:\n #float/double (44, 45) before real (21/22), and\n #byte (41) before int (1) before char (51). So hack.\n #Consider making typedict an ordered dict once 2.6 is dead.\n types.sort(key=lambda x: x % 50, reverse=True)\n\n if not types: #not a numpy array, or can't parse its type\n if d.dtype.kind == 'O': #Object. Try to make it numeric\n #Can't do safe casting from Object, so try and compare\n #Basically try most restrictive to least restrictive\n trytypes = (numpy.uint64, numpy.int64, numpy.float64)\n for t in trytypes:\n try:\n newd = d.astype(dtype=t)\n except: #Failure to cast, try next type\n continue\n if (newd == d).all(): #Values preserved, use this type\n d = newd\n #Continue with normal guessing, as if a list\n break\n else:\n #fell through without a match\n raise ValueError(\n 'Cannot convert generic objects to CDF type.')\n if d.dtype.kind in ('i', 'u'): #integer\n minval = numpy.min(d)\n maxval = numpy.max(d)\n if minval < 0:\n types = [const.CDF_BYTE, const.CDF_INT1,\n const.CDF_INT2, const.CDF_INT4, const.CDF_INT8,\n const.CDF_FLOAT, const.CDF_REAL4,\n const.CDF_DOUBLE, const.CDF_REAL8]\n cutoffs = [2 ** 7, 2 ** 7, 2 ** 15, 2 ** 31, 2 ** 63,\n 1.7e38, 1.7e38, 8e307, 8e307]\n else:\n types = [const.CDF_BYTE, const.CDF_INT1, const.CDF_UINT1,\n const.CDF_INT2, const.CDF_UINT2,\n const.CDF_INT4, const.CDF_UINT4,\n const.CDF_INT8,\n const.CDF_FLOAT, const.CDF_REAL4,\n const.CDF_DOUBLE, const.CDF_REAL8]\n cutoffs = [2 ** 7, 2 ** 7, 2 ** 8,\n 2 ** 15, 2 ** 16, 2 ** 31, 2 ** 32, 2 ** 63,\n 1.7e38, 1.7e38, 8e307, 8e307]\n types = [t for (t, c) in zip(types, cutoffs) if c > maxval\n and (minval >= 0 or minval >= -c)]\n if (not lib.supports_int8 or backward) \\\n and const.CDF_INT8 in types:\n del types[types.index(const.CDF_INT8)]\n else: #float\n if dims is ():\n if d != 0 and (abs(d) > 1.7e38 or abs(d) < 3e-39):\n types = [const.CDF_DOUBLE, const.CDF_REAL8]\n else:\n types = [const.CDF_FLOAT, const.CDF_REAL4,\n const.CDF_DOUBLE, const.CDF_REAL8]\n else:\n absolutes = numpy.abs(d[d != 0])\n if len(absolutes) > 0 and \\\n (numpy.max(absolutes) > 1.7e38 or\n numpy.min(absolutes) < 3e-39):\n types = [const.CDF_DOUBLE, const.CDF_REAL8]\n else:\n types = [const.CDF_FLOAT, const.CDF_REAL4,\n const.CDF_DOUBLE, const.CDF_REAL8]\n types = [t.value if hasattr(t, 'value') else t for t in types]\n return (dims, types, elements)\n\n @staticmethod\n def reorder(seq):\n \"\"\"Reorders seq to switch array majority\n\n Used to take an array of subscripts between row\n and column majority. First element is not touched,\n being the record number.\n\n @param seq: a sequence of *subscripts*\n @type seq: sequence of integers\n @return: seq with all but element 0 reversed in order\n @rtype: sequence of integers\n \"\"\"\n return numpy.concatenate((seq[0:1],\n numpy.flipud(seq)[:-1]))\n\n @staticmethod\n def convert_range(start, stop, step, size):\n \"\"\"Converts a start/stop/step range to start/count/interval\n\n (i.e. changes from Python-style slice to CDF-style)\n @param start: index to start a slice at, may be none or negative\n @type start: int\n @param stop: index at end of slice (one-past, standard Python),\n may be none or negative\n @type stop: int\n @param step: interval for stepping through stlice\n @type step: int\n @param size: size of list to slice\n @type size: int\n @return: (start, count, interval, rev) where:\n 1. start is the start index, normalized to be within\n the size of the list and negatives handled\n 2. count is the number of records in the slice,\n guaranteed to stop before the end\n 3. interval is the skip between records\n 4. rev indicates whether the sequence should be reversed\n @rtype: (int, int, int, boolean)\n \"\"\"\n (start, stop, step) = slice(start, stop, step).indices(size)\n if step < 0:\n step *= -1\n count = int((start - stop + step - 1) / step)\n start = start - (count - 1) * step\n rev = True\n else:\n count = int((stop - start + step - 1) / step)\n rev = False\n if count < 0:\n count = 0\n start = 0\n return (start, count, step, rev)\n\n\nclass Attr(MutableSequence):\n \"\"\"An attribute, g or z, for a CDF\n\n .. warning::\n This class should not be used directly, but only in its\n subclasses, :class:`gAttr` and :class:`zAttr`. The methods\n listed here are safe to use in the subclasses.\n\n Represents a CDF attribute, providing access to the Entries in a format\n that looks like a Python\n list. General list information is available in the python docs:\n `1 <http://docs.python.org/tutorial/introduction.html#lists>`_,\n `2 <http://docs.python.org/tutorial/datastructures.html#more-on-lists>`_,\n `3 <http://docs.python.org/library/stdtypes.html#typesseq>`_.\n\n An introduction to CDF attributes can be found in section 2.4 of\n the CDF user's guide.\n\n Each element of the list is a single Entry of the appropriate type.\n The index to the elements is the Entry number.\n\n Multi-dimensional slicing is *not* supported; an Entry with multiple\n elements will have all elements returned (and can thus be sliced itself).\n Example:\n\n >>> first_three = attribute[5, 0:3] #will fail\n >>> first_three = attribute[5][0:3] #first three elements of 5th Entry\n\n .. autosummary::\n\n ~Attr.append\n ~Attr.has_entry\n ~Attr.insert\n ~Attr.max_idx\n ~Attr.new\n ~Attr.number\n ~Attr.rename\n ~Attr.type\n\n .. automethod:: append\n .. automethod:: has_entry\n .. automethod:: insert\n .. automethod:: max_idx\n .. automethod:: new\n .. automethod:: number\n .. automethod:: rename\n .. automethod:: type\n \"\"\"\n\n def __init__(self, cdf_file, attr_name, create=False):\n \"\"\"Initialize this attribute\n\n @param cdf_file: CDF file containing this attribute\n @type cdf_file: :py:class:`pycdf.CDF`\n @param attr_name: Name of this attribute\n @type attr_name: str\n @param create: True to create attribute, False to look up existing.\n @type create: bool\n \"\"\"\n self._cdf_file = cdf_file\n self._raw = False\n if isinstance(attr_name, str_classes):\n try:\n self._name = attr_name.encode('ascii')\n except AttributeError:\n self._name = attr_name\n attrno = ctypes.c_long()\n if create:\n self._cdf_file._call(const.CREATE_, const.ATTR_,\n self._name, self.SCOPE,\n ctypes.byref(attrno))\n self._cdf_file.add_attr_to_cache(\n self._name, attrno.value, self.SCOPE == const.GLOBAL_SCOPE)\n else: #Ensure exists, and populate cache. See scope note below\n attrno, scope = self._cdf_file.attr_num(self._name)\n else:\n name = ctypes.create_string_buffer(const.CDF_ATTR_NAME_LEN256 + 1)\n scope = ctypes.c_long(0)\n self._cdf_file._call(const.SELECT_, const.ATTR_,\n ctypes.c_long(attr_name))\n #Because it's possible to create a gAttr Python objecting\n #referencing an Attribute with variable scope, and vice-versa,\n #do NOT assume the scope matches\n #(Higher level code checks for that being a bad thing.)\n self._cdf_file._call(\n const.GET_, const.ATTR_NAME_, name,\n const.GET_, const.ATTR_SCOPE_, ctypes.byref(scope))\n self._name = name.value.rstrip()\n if scope.value == const.GLOBAL_SCOPE.value:\n scope = True\n elif scope.value == const.VARIABLE_SCOPE.value:\n scope = False\n else:\n raise CDFError(const.BAD_SCOPE)\n self._cdf_file.add_attr_to_cache(self._name, attr_name, scope)\n\n def __getitem__(self, key):\n \"\"\"Return a slice of Entries.\n\n Because Attributes may be sparse, a multi-element slice will return\n None for those elements which do not have associated Entries.\n\n @param key: index or range of Entry number to return\n @type key: slice or int\n @return: a list of entries, appropriate type.\n @raise IndexError: if L{key} is an int and that Entry number does not\n exist.\n \"\"\"\n if key is Ellipsis:\n key = slice(None, None, None)\n if hasattr(key, 'indices'):\n idx = range(*key.indices(self.max_idx() + 1))\n return [self._get_entry(i) if self.has_entry(i) else None\n for i in idx]\n else:\n if self.has_entry(key):\n return self._get_entry(key)\n else:\n raise IndexError('list index ' + str(key) + ' out of range.')\n\n def _check_other_entries(self, types):\n \"\"\"Try to get the type of this entry from others in the Attribute\n\n For zAttrs, checks if all other Entries are the same type, and at\n least one doesn't match its zVar, i.e. Entry type dominates (otherwise\n assumption is the Var type dominates).\n\n For gAttrs, checks all other Entries, and gives priority to the\n one that's earliest in the possible type list and exists in other\n Entries.\n\n This is only one component of Entry type guessing!\n\n :param list types: CDF types that are candidates (match the data)\n :return: The type discerned from other Entries, or None\n \"\"\"\n if self.ENTRY_ == const.zENTRY_:\n #If everything else is the same entry type,\n #and one is not the same as its var, probably\n #all entries should be of that type\n cand_et = None #The Entry type that might work\n one_var_diff = False #One Var has a type different from Entry\n for num in range(self.max_idx() + 1):\n if not self.has_entry(num):\n continue\n vartype = self._cdf_file[num].type()\n entrytype = self.type(num)\n if vartype != entrytype:\n one_var_diff = True\n if cand_et is None:\n if not entrytype in types:\n return None #One var has Entry with \"impossible\" type\n cand_et = entrytype\n elif cand_et != entrytype:\n return None #Two vars have Entries with different types\n if one_var_diff and cand_et is not None:\n return cand_et\n else:\n # Of those types which exist in other entries,\n # find the one which is earliest\n # in types, i.e. the preferred type\n entrytypes = [self.type(num) for num in\n range(self.max_idx() + 1)\n if self.has_entry(num)]\n entrytypes = [et for et in entrytypes if et in types]\n if entrytypes:\n return types[\n min([types.index(et) for et in entrytypes])]\n return None\n\n def __setitem__(self, key, data):\n \"\"\"Set a slice of Entries.\n\n @param key: index or range of Entry numbers to set\n @type key: slice or int\n @param data: the data to set these entries to. Normally each entry should\n be a sequence; if a scalar is provided, it is treated\n as a single-element list.\n @type data: scalar or list\n @raise ValueError: if size of {data} does not match size of L{key}\n @note: Attributes do not 'grow' or 'shrink' as entries are added\n or removed. Indexes of entries never change and there is no\n way to 'insert'.\n \"\"\"\n if key is Ellipsis:\n key = slice(None, None, None)\n if not hasattr(key, 'indices'):\n #Single value, promote everything a dimension\n idx = (key, key + 1, 1)\n data = [data]\n else:\n idx = key.indices(self.max_idx() + 1)\n if key.step is None or key.step > 0:\n #Iterating forward, extend slice to match data\n if len(data) > len(range(*idx)):\n idx = (idx[0], idx[0] + idx[2] * len(data), idx[2])\n\n #get, and check, types and sizes for all data\n #checks first so don't have error after changing half the Entries\n data_idx = -1\n typelist = []\n for i in range(*idx):\n data_idx += 1\n if data_idx >= len(data):\n continue\n datum = data[data_idx]\n if datum is None:\n typelist[i] = (None, None, None)\n continue\n (dims, types, elements) = _Hyperslice.types(\n datum, backward=self._cdf_file.backward)\n if len(types) <= 0:\n raise ValueError('Cannot find a matching CDF type.')\n if len(dims) > 1:\n raise ValueError('Entries must be scalar or 1D.')\n elif len(dims) == 1 and isinstance(datum[0], str_classes):\n raise ValueError('Entry strings must be scalar.')\n entry_type = None\n if self.has_entry(i): #If the entry already exists, match its type\n entry_type = self.type(i)\n if not entry_type in types:\n entry_type = None\n if entry_type is None: #Check other entries for this attribute\n entry_type = self._check_other_entries(types)\n if entry_type is None and self.ENTRY_ == const.zENTRY_:\n #Fall back to zVar type\n vartype = self._cdf_file[i].type()\n if vartype in types:\n entry_type = vartype\n else:\n entry_type = types[0]\n elif entry_type is None:\n entry_type = types[0]\n if not entry_type in lib.numpytypedict:\n raise ValueError('Cannot find a matching numpy type.')\n typelist.append((dims, entry_type, elements))\n\n data_idx = -1\n for i in range(*idx):\n data_idx += 1\n if data_idx >= len(data) or data[data_idx] is None:\n if self.has_entry(i):\n del self[i]\n continue\n datum = data[data_idx]\n (dims, entry_type, elements) = typelist[data_idx]\n self._write_entry(i, datum, entry_type, dims, elements)\n\n def __delitem__(self, key):\n \"\"\"Delete a slice of Entries.\n\n @param key: index or range of Entry numbers to delete\n @type key: slice or int\n @note: Attributes do not 'grow' or 'shrink' as entries are added\n or removed. Indexes of entries never change and there is no\n way to 'insert'.\n \"\"\"\n if key is Ellipsis:\n key = slice(None, None, None)\n if not hasattr(key, 'indices'):\n idx = (key, key + 1, 1)\n else:\n idx = key.indices(self.max_idx() + 1)\n for i in range(*idx):\n self._call(const.SELECT_, self.ENTRY_, ctypes.c_long(i),\n const.DELETE_, self.ENTRY_)\n\n def __iter__(self, current=0):\n \"\"\"Iterates over all entries in this Attribute\n\n Returns data from one entry at a time until reaches the end.\n @note: Returned in entry-number order.\n \"\"\"\n while current <= self.max_idx():\n if self.has_entry(current):\n value = yield(self._get_entry(current))\n if value != None:\n current = value\n current += 1\n\n def __reversed__(self, current=None):\n \"\"\"Iterates over all entries in this Attribute\n\n Returns data from one entry at a time, starting at end and going\n to beginning.\n @note: Returned in entry-number order.\n \"\"\"\n if current is None:\n current = self.max_idx()\n while current >= 0:\n if self.has_entry(current):\n value = yield(self._get_entry(current))\n if value != None:\n current = value\n current -= 1\n\n def __len__(self):\n \"\"\"Number of Entries for this Attr. NOT same as max Entry number.\n\n @return: Number of Entries\n @rtype: int\n \"\"\"\n count = ctypes.c_long(0)\n self._call(const.GET_, self.ATTR_NUMENTRIES_, ctypes.byref(count))\n return count.value\n\n def __repr__(self):\n \"\"\"Returns representation of an attribute\n\n Cannot return anything that can be eval'd to create a copy of the\n attribtute, so just wrap the informal representation in angle brackets.\n @return: all the data in this attribute\n @rtype: str\n \"\"\"\n return '<\\n' + str(self) + '\\n>'\n\n def __str__(self):\n \"\"\"Returns a string representation of the attribute\n\n This is an 'informal' representation in that it cannot be evaluated\n directly to create an L{Attr}.\n\n @return: all the data in this attribute\n @rtype: str\n \"\"\"\n if self._cdf_file._opened:\n return '\\n'.join([str(item) for item in self])\n else:\n if isinstance(self._name, str):\n return 'Attribute \"{0}\" in closed CDF {1}'.format(\n self._name, self._cdf_file.pathname)\n else:\n return 'Attribute \"{0}\" in closed CDF {1}'.format(\n self._name.decode('ascii'),\n self._cdf_file.pathname.decode('ascii'))\n\n def insert(self, index, data):\n \"\"\"Insert an entry at a particular number\n\n Inserts entry at particular number while moving all subsequent\n entries to one entry number later. Does not close gaps.\n\n Parameters\n ==========\n index : int\n index where to put the new entry\n data : \n data for the new entry\n \"\"\"\n max_entry = self.max_idx()\n if index > max_entry: #Easy case\n self[index] = data\n return\n for i in range(max_entry, index - 1, -1):\n if self.has_entry(i+1):\n self.__delitem__(i+1)\n if self.has_entry(i):\n self.new(self.__getitem__(i), type=self.type(i), number=i+1)\n self[index] = data\n\n def append(self, data):\n \"\"\"Add an entry to end of attribute\n\n Puts entry after last defined entry (does not fill gaps)\n\n Parameters\n ==========\n data : \n data for the new entry\n \"\"\"\n self[self.max_idx() + 1] = data\n\n def _call(self, *args, **kwargs):\n \"\"\"Select this CDF and Attr and call the CDF internal interface\n\n @param args: Passed directly to the CDF library interface.\n @type args: various, see :py:mod:`ctypes`.\n @return: CDF status from the library\n @rtype: ctypes.c_long\n @note: Terminal NULL_ is automatically added to L{args}.\n @raise CDFError: if CDF library reports an error\n @raise CDFWarning: if CDF library reports a warning and interpreter\n is set to error on warnings.\n \"\"\"\n return self._cdf_file._call(\n const.SELECT_, const.ATTR_,\n ctypes.c_long(self._cdf_file.attr_num(self._name)[0]),\n *args, **kwargs)\n\n def _entry_len(self, number):\n \"\"\"Number of elements in an Entry\n\n @param number: number of Entry\n @type number: int\n @return: number of elements\n @rtype: int\n \"\"\"\n if not self.has_entry(number):\n raise IndexError('list index ' + str(number) + ' out of range.')\n count = ctypes.c_long(0)\n self._call(\n const.SELECT_, self.ENTRY_, ctypes.c_long(number),\n const.GET_, self.ENTRY_NUMELEMS_, ctypes.byref(count))\n return count.value\n\n def type(self, number, new_type=None):\n \"\"\"Find or change the CDF type of a particular Entry number\n\n Parameters\n ==========\n number : int\n number of Entry to check or change\n\n Other Parameters\n ================\n new_type\n type to change this Entry to, from :mod:`~pycdf.const`.\n Omit to only check type.\n\n Returns\n =======\n out : int\n CDF variable type, see :mod:`~pycdf.const`\n\n Notes\n =====\n If changing types, old and new must be equivalent, see CDF\n User's Guide section 2.5.5 pg. 57\n \"\"\"\n if new_type != None:\n if not hasattr(new_type, 'value'):\n new_type = ctypes.c_long(new_type)\n size = ctypes.c_long(self._entry_len(number))\n status = self._call(const.SELECT_, self.ENTRY_, ctypes.c_long(number),\n const.PUT_, self.ENTRY_DATASPEC_, new_type, size,\n ignore=(const.NO_SUCH_ENTRY,))\n if status == const.NO_SUCH_ENTRY:\n raise IndexError('list index ' + str(number) + ' out of range.')\n cdftype = ctypes.c_long(0)\n status = self._call(const.SELECT_, self.ENTRY_, ctypes.c_long(number),\n const.GET_, self.ENTRY_DATATYPE_, ctypes.byref(cdftype),\n ignore=(const.NO_SUCH_ENTRY,))\n if status == const.NO_SUCH_ENTRY:\n raise IndexError('list index ' + str(number) + ' out of range.')\n return cdftype.value\n\n def has_entry(self, number):\n \"\"\"Check if this attribute has a particular Entry number\n\n Parameters\n ==========\n number : int\n number of Entry to check or change\n\n Returns\n =======\n out : bool\n True if ``number`` is a valid entry number; False if not\n \"\"\"\n status = self._call(const.CONFIRM_, self.ENTRY_EXISTENCE_,\n ctypes.c_long(number),\n ignore=(const.NO_SUCH_ENTRY, ))\n return not status == const.NO_SUCH_ENTRY\n\n def max_idx(self):\n \"\"\"Maximum index of Entries for this Attr\n\n Returns\n =======\n out : int\n maximum Entry number\n \"\"\"\n count = ctypes.c_long(0)\n self._call(const.GET_, self.ATTR_MAXENTRY_, ctypes.byref(count))\n return count.value\n\n def new(self, data, type=None, number=None):\n \"\"\"Create a new Entry in this Attribute\n\n .. note:: If ``number`` is provided and an Entry with that number\n already exists, it will be overwritten.\n\n Parameters\n ==========\n data\n data to put in the Entry\n\n Other Parameters\n ================\n type : int\n type of the new Entry, from :mod:`~pycdf.const`\n (otherwise guessed from ``data``)\n number : int\n Entry number to write, default is lowest available number.\n \"\"\"\n if number is None:\n number = 0\n while self.has_entry(number):\n number += 1\n (dims, types, elements) = _Hyperslice.types(\n data, backward=self._cdf_file.backward)\n if type is None:\n #Guess based on other entries\n type = self._check_other_entries(types)\n if type is None and self.ENTRY_ == const.zENTRY_:\n #Try to match variable type\n vartype = self._cdf_file[number].type()\n if vartype in types:\n type = vartype\n if type is None:\n type = types[0]\n elif hasattr(type, 'value'):\n type = type.value\n self._write_entry(number, data, type, dims, elements)\n\n def number(self):\n \"\"\"Find the attribute number for this attribute\n\n Returns\n =======\n out : int\n attribute number\n \"\"\"\n no = ctypes.c_long(0)\n self._cdf_file._call(const.GET_, const.ATTR_NUMBER_,\n self._name, ctypes.byref(no))\n return no.value\n\n def global_scope(self):\n \"\"\"Determine scope of this attribute.\n\n Returns\n =======\n out : bool\n True if global (i.e. gAttr), False if zAttr\n \"\"\"\n return self._cdf_file.attr_num(self._name)[1]\n\n def rename(self, new_name):\n \"\"\"Rename this attribute\n\n Renaming a zAttribute renames it for *all* zVariables in this CDF!\n\n Parameters\n ==========\n new_name : str\n the new name of the attribute\n \"\"\"\n try:\n enc_name = new_name.encode('ascii')\n except AttributeError:\n enc_name = new_name\n if len(enc_name) > const.CDF_ATTR_NAME_LEN256:\n raise CDFError(const.BAD_ATTR_NAME)\n self._call(const.PUT_, const.ATTR_NAME_, enc_name)\n self._cdf_file.add_attr_to_cache(\n enc_name,\n *self._cdf_file.attr_num(self._name)) #still in cache\n del self._cdf_file._attr_info[self._name]\n self._name = enc_name\n\n def _get_entry(self, number):\n \"\"\"Read an Entry associated with this L{Attr}\n\n @param number: number of Entry to return\n @type number: int\n @return: data from entry numbered L{number}\n @rtype: list or str\n \"\"\"\n if not self.has_entry(number):\n raise IndexError('list index ' + str(number) + ' out of range.')\n #Make a big enough buffer\n length = self._entry_len(number)\n cdftype = self.type(number)\n if cdftype in (const.CDF_CHAR.value, const.CDF_UCHAR.value):\n buff = numpy.empty((), 'S{0}'.format(length), order='C')\n else:\n if not cdftype in lib.numpytypedict:\n raise CDFError(const.BAD_DATA_TYPE)\n buff = numpy.empty((length,), lib.numpytypedict[cdftype],\n order='C')\n buff = numpy.require(buff, requirements=('C', 'A', 'W'))\n self._call(const.SELECT_, self.ENTRY_, ctypes.c_long(number),\n const.GET_, self.ENTRY_DATA_,\n buff.ctypes.data_as(ctypes.c_void_p))\n\n #decode\n if cdftype in (const.CDF_CHAR.value, const.CDF_UCHAR.value):\n if str == bytes or self._raw: #Py2k, leave as bytes\n result = bytes(buff)\n else: #Py3k, make unicode\n result = str(numpy.char.array(buff).decode())\n else:\n if not self._raw:\n if cdftype == const.CDF_EPOCH.value:\n result = lib.v_epoch_to_datetime(buff)\n elif cdftype == const.CDF_EPOCH16.value:\n result = lib.v_epoch16_to_datetime(buff)\n elif cdftype == const.CDF_TIME_TT2000.value:\n result = lib.v_tt2000_to_datetime(buff)\n else:\n result = buff\n else:\n result = buff\n if length == 1:\n result = result[0]\n\n return result\n\n def _write_entry(self, number, data, cdf_type, dims, elements):\n \"\"\"Write an Entry to this Attr.\n\n @param number: number of Entry to write\n @type number: int\n @param data: data to write\n @param cdf_type: the CDF type to write, from :py:mod:`pycdf.const`\n @param dims: dimensions of L{data}\n @type dims: list\n @param elements: number of elements in L{data}, 1 unless it is a string\n @type elements: int\n \"\"\"\n if len(dims) == 0:\n n_write = 1\n else:\n n_write = dims[0]\n if cdf_type in (const.CDF_CHAR.value, const.CDF_UCHAR.value):\n data = numpy.require(data, requirements=('C', 'A', 'W'),\n dtype=numpy.dtype('S' + str(elements)))\n n_write = elements\n elif cdf_type == const.CDF_EPOCH16.value:\n if not self._raw:\n try:\n data = lib.v_datetime_to_epoch16(data)\n except AttributeError:\n pass\n data = numpy.require(data, requirements=('C', 'A', 'W'),\n dtype=numpy.float64)\n elif cdf_type == const.CDF_EPOCH.value:\n if not self._raw:\n try:\n data = lib.v_datetime_to_epoch(data),\n except AttributeError:\n pass\n data = numpy.require(data, requirements=('C', 'A', 'W'),\n dtype=numpy.float64)\n elif cdf_type == const.CDF_TIME_TT2000.value:\n if not self._raw:\n try:\n data = lib.v_datetime_to_tt2000(data)\n except AttributeError:\n pass\n data = numpy.require(data, requirements=('C', 'A', 'W'),\n dtype=numpy.int64)\n elif cdf_type in lib.numpytypedict:\n data = numpy.require(data, requirements=('C', 'A', 'W'),\n dtype=lib.numpytypedict[cdf_type])\n else:\n raise CDFError(const.BAD_DATA_TYPE)\n self._call(const.SELECT_, self.ENTRY_, ctypes.c_long(number),\n const.PUT_, self.ENTRY_DATA_, ctypes.c_long(cdf_type),\n ctypes.c_long(n_write),\n data.ctypes.data_as(ctypes.c_void_p))\n\n def _delete(self):\n \"\"\"Delete this Attribute\n\n Also deletes all Entries associated with it.\n \"\"\"\n self._call(const.DELETE_, const.ATTR_)\n self._cdf_file.clear_attr_from_cache(self._name)\n self._name = None\n\n\nclass zAttr(Attr):\n \"\"\"zAttribute for zVariables within a CDF.\n\n .. warning::\n Because zAttributes are shared across all variables in a CDF,\n directly manipulating them may have unexpected consequences.\n It is safest to operate on zEntries via :class:`zAttrList`.\n\n .. note::\n When accessing a zAttr, pyCDF exposes only the zEntry corresponding\n to the associated zVariable.\n\n See Also\n ========\n :class:`Attr`\n \"\"\"\n ENTRY_ = const.zENTRY_\n ENTRY_DATA_ = const.zENTRY_DATA_\n SCOPE = const.VARIABLE_SCOPE\n ENTRY_EXISTENCE_ = const.zENTRY_EXISTENCE_\n ATTR_NUMENTRIES_ = const.ATTR_NUMzENTRIES_\n ATTR_MAXENTRY_ = const.ATTR_MAXzENTRY_\n ENTRY_NUMELEMS_ = const.zENTRY_NUMELEMS_\n ENTRY_DATATYPE_ = const.zENTRY_DATATYPE_\n ENTRY_DATASPEC_ = const.zENTRY_DATASPEC_\n\n def insert(self, index, data):\n \"\"\"Insert entry at particular index number\n\n Since there can only be one zEntry per zAttr, this cannot be\n implemented.\n\n Raises\n ======\n NotImplementedError : always\n \"\"\"\n raise NotImplementedError\n\n def append(self, index, data):\n \"\"\"Add entry to end of attribute list\n\n Since there can only be one zEntry per zAttr, this cannot be\n implemented.\n\n Raises\n ======\n NotImplementedError : always\n \"\"\"\n raise NotImplementedError\n\n\nclass gAttr(Attr):\n \"\"\"Global Attribute for a CDF\n\n Represents a CDF attribute, providing access to the gEntries in a format\n that looks like a Python list. General list information is available in\n the python docs:\n `1 <http://docs.python.org/tutorial/introduction.html#lists>`_,\n `2 <http://docs.python.org/tutorial/datastructures.html#more-on-lists>`_,\n `3 <http://docs.python.org/library/stdtypes.html#typesseq>`_.\n\n Normally accessed by providing a key to a :class:`gAttrList`:\n\n >>> attribute = cdffile.attrs['attribute_name']\n >>> first_gentry = attribute[0]\n\n Each element of the list is a single gEntry of the appropriate type.\n The index to the elements is the gEntry number.\n\n A gEntry may be either a single string or a 1D array of numerical type.\n Entries of numerical type (everything but CDF_CHAR and CDF_UCHAR)\n with a single element are returned as scalars; multiple-element entries\n are returned as a list. No provision is made for accessing below\n the entry level; the whole list is returned at once (but Python's\n slicing syntax can be used to extract individual items from that list.)\n\n Multi-dimensional slicing is *not* supported; an entry with multiple\n elements will have all elements returned (and can thus be sliced itself).\n Example:\n\n >>> first_three = attribute[5, 0:3] #will fail\n >>> first_three = attribute[5][0:3] #first three elements of 5th Entry\n\n gEntries are *not* necessarily contiguous; a gAttribute may have an\n entry 0 and entry 2 without an entry 1. :meth:`~Attr.len` will return the\n *number* of gEntries; use :meth:`~Attr.max_idx` to find the highest defined\n gEntry number and :meth:`~Attr.has_entry` to determine if a particular\n gEntry number exists. Iterating over all entries is also supported::\n\n >>> entrylist = [entry for entry in attribute]\n\n Deleting gEntries will leave a \"hole\":\n\n >>> attribute[0:3] = [1, 2, 3]\n >>> del attribute[1]\n >>> attribute.has_entry(1)\n False\n >>> attribute.has_entry(2)\n True\n >>> print attribute[0:3]\n [1, None, 3]\n\n Multi-element slices over nonexistent gEntries will return ``None`` where\n no entry exists. Single-element indices for nonexistent gEntries will\n raise ``IndexError``. Assigning ``None`` to a gEntry will delete it.\n\n When assigning to a gEntry, the type is chosen to match the data;\n subject to that constraint, it will try to match\n (in order):\n\n #. existing gEntry of the same number in this gAttribute\n #. other gEntries in this gAttribute\n #. data-matching constraints described in :meth:`CDF.new`.\n\n See Also\n ========\n :class:`Attr`\n \"\"\"\n ENTRY_ = const.gENTRY_\n ENTRY_DATA_ = const.gENTRY_DATA_\n SCOPE = const.GLOBAL_SCOPE\n ENTRY_EXISTENCE_ = const.gENTRY_EXISTENCE_\n ATTR_NUMENTRIES_ = const.ATTR_NUMgENTRIES_\n ATTR_MAXENTRY_ = const.ATTR_MAXgENTRY_\n ENTRY_NUMELEMS_ = const.gENTRY_NUMELEMS_\n ENTRY_DATATYPE_ = const.gENTRY_DATATYPE_\n ENTRY_DATASPEC_ = const.gENTRY_DATASPEC_\n\n\nclass AttrList(MutableMapping):\n \"\"\"Object representing a list of attributes.\n\n .. warning::\n This class should not be used directly, but only via its\n subclasses, :class:`gAttrList` and :class:`zAttrList`.\n Methods listed here are safe to use from the subclasses.\n\n .. autosummary::\n\n ~AttrList.clone\n ~AttrList.copy\n ~AttrList.from_dict\n ~AttrList.new\n ~AttrList.rename\n \n .. automethod:: clone\n .. automethod:: copy\n .. automethod:: from_dict\n .. automethod:: new\n .. automethod:: rename\n \"\"\"\n\n def __init__(self, cdf_file, special_entry=None):\n \"\"\"Initialize the attribute collection\n\n @param cdf_file: CDF these attributes are in\n @type cdf_file: :py:class:`pycdf.CDF`\n @param special_entry: callable which returns a \"special\" entry number,\n used to limit results for zAttrs to those which match the zVar\n (i.e. the var number)\n @type special_entry: callable\n \"\"\"\n self._cdf_file = cdf_file\n self.special_entry = special_entry\n\n def __getitem__(self, name):\n \"\"\"Find an Attribute by name\n\n @param name: name of the Attribute to return\n @type name: str\n @return: attribute named L{name}\n @rtype: L{Attr}\n @raise KeyError: if there is no attribute named L{name}\n @raise CDFError: other errors in CDF library\n \"\"\"\n try:\n attrib = self.AttrType(self._cdf_file, name)\n except CDFError:\n (t, v, tb) = sys.exc_info()\n if v.status == const.NO_SUCH_ATTR:\n raise KeyError(name + ': ' + str(v))\n else:\n raise\n if attrib.global_scope() != self.global_scope:\n raise KeyError(name + ': no ' + self.attr_name + ' by that name.')\n return attrib\n\n def __setitem__(self, name, data):\n \"\"\"Create an Attribute or change its entries\n\n @param name: name of Attribute to change\n @type name: str\n @param data: Entries to populate this Attribute with.\n Any existing Entries will be deleted!\n Another C{Attr} may be specified, in which\n case all its entries are copied.\n @type data: scalar, list, or L{Attr}\n \"\"\"\n if isinstance(data, AttrList):\n if name in self:\n del self[name]\n attr = self._get_or_create(name)\n for entryno in range(data.max_idx()):\n if data.has_entry(entryno):\n attr.new(data[entryno], data.type(entryno), entryno)\n else:\n attr = self._get_or_create(name)\n if isinstance(data, str_classes):\n data = [data]\n else:\n try:\n junk = len(data)\n except TypeError:\n data = [data]\n attr[:] = data\n del attr[len(data):]\n\n def __delitem__(self, name):\n \"\"\"Delete an Attribute (and all its entries)\n\n @param name: name of Attribute to delete\n @type name: str\n \"\"\"\n try:\n attr = self.AttrType(self._cdf_file, name)\n except CDFError:\n (t, v, tb) = sys.exc_info()\n if v.status == const.NO_SUCH_ATTR:\n raise KeyError(name + ': ' + str(v))\n else:\n raise\n if attr.global_scope() != self.global_scope:\n raise KeyError(name + ': not ' + self.attr_name)\n attr._delete()\n\n def __iter__(self, current=0):\n \"\"\"Iterates over all Attr in this CDF or variable\n\n Returns name of one L{Attr} at a time until reaches the end.\n @note: Returned in number order.\n \"\"\"\n count = ctypes.c_long(0)\n self._cdf_file._call(const.GET_, const.CDF_NUMATTRS_,\n ctypes.byref(count))\n while current < count.value:\n candidate = self.AttrType(self._cdf_file, current)\n if candidate.global_scope() == self.global_scope:\n if self.special_entry is None or \\\n candidate.has_entry(self.special_entry()):\n if str == bytes:\n value = yield(candidate._name)\n else:\n value = yield(candidate._name.decode())\n if value != None:\n current = self[value].number()\n current += 1\n\n def __repr__(self):\n \"\"\"Returns representation of attribute list\n\n Cannot return anything that can be eval'd to create a copy of the\n list, so just wrap the informal representation in angle brackets.\n @return: all the data in this list of attributes\n @rtype: str\n \"\"\"\n return '<' + self.__class__.__name__ + ':\\n' + str(self) + '\\n>'\n\n def __str__(self):\n \"\"\"Returns a string representation of the attribute list\n\n This is an 'informal' representation in that it cannot be evaluated\n directly to create an L{AttrList}.\n\n @return: all the data in this list of attributes\n @rtype: str\n \"\"\"\n if self._cdf_file._opened:\n return '\\n'.join([key + ': ' + (\n ('\\n' + ' ' * (len(key) + 2)).join(\n [str(value[i]) + ' [' + lib.cdftypenames[value.type(i)] + ']'\n for i in range(value.max_idx() + 1) if value.has_entry(i)])\n if isinstance(value, Attr)\n else str(value) +\n ' [' + lib.cdftypenames[self.type(key)] + ']'\n )\n for (key, value) in sorted(self.items())])\n else:\n if isinstance(self._cdf_file.pathname, str):\n return 'Attribute list in closed CDF {0}'.format(\n self._cdf_file.pathname)\n else:\n return 'Attribute list in closed CDF {0}'.format(\n self._cdf_file.pathname.decode('ascii'))\n\n def clone(self, master, name=None, new_name=None):\n \"\"\"\n Clones another attribute list, or one attribute from it, into this\n list.\n\n Parameters\n ==========\n master : AttrList\n the attribute list to copy from. This can be any dict-like object.\n\n Other Parameters\n ================\n name : str (optional)\n name of attribute to clone (default: clone entire list)\n new_name : str (optional)\n name of the new attribute, default ``name``\n \"\"\"\n if name is None:\n self._clone_list(master)\n else:\n self._clone_attr(master, name, new_name)\n\n def copy(self):\n \"\"\"\n Create a copy of this attribute list\n\n Returns\n =======\n out : dict\n copy of the entries for all attributes in this list\n \"\"\"\n return dict((key, value[:] if isinstance(value, Attr) else value)\n for (key, value) in self.items())\n\n def new(self, name, data=None, type=None):\n \"\"\"\n Create a new Attr in this AttrList\n\n Parameters\n ==========\n name : str\n name of the new Attribute\n\n Other Parameters\n ================\n data\n data to put into the first entry in the new Attribute\n type\n CDF type of the first entry from :mod:`~pycdf.const`.\n Only used if data are specified.\n\n Raises\n ======\n KeyError : if the name already exists in this list\n \"\"\"\n if name in self:\n raise KeyError(name + ' already exists.')\n #A zAttr without an Entry in this zVar will be a \"get\" not \"create\"\n attr = self._get_or_create(name)\n if data is not None:\n if self.special_entry is None:\n attr.new(data, type)\n else:\n attr.new(data, type, self.special_entry())\n\n def rename(self, old_name, new_name):\n \"\"\"\n Rename an attribute in this list\n\n Renaming a zAttribute renames it for *all* zVariables in this CDF!\n\n Parameters\n ==========\n old_name : str\n the current name of the attribute\n new_name : str\n the new name of the attribute\n \"\"\"\n AttrList.__getitem__(self, old_name).rename(new_name)\n\n def from_dict(self, in_dict):\n \"\"\"\n Fill this list of attributes from a dictionary\n\n .. deprecated:: 0.1.5\n Use :meth:`~pycdf.AttrList.clone` instead; it supports\n cloning from dictionaries.\n\n Parameters\n ==========\n in_dict : dict\n Attribute list is populated entirely from this dictionary;\n all existing attributes are deleted.\n \"\"\"\n warnings.warn(\"from_dict is deprecated and will be removed. Use clone.\",\n DeprecationWarning)\n for k in in_dict:\n self[k] = in_dict[k]\n for k in list(self):\n if not k in in_dict:\n del self[k]\n\n def _clone_attr(self, master, name, new_name=None):\n \"\"\"Clones a single attribute from one in this list or another\n\n Copies data and types from the master attribute to the new one\n\n @param master: attribute list to copy attribute from\n @type master: L{AttrList}\n @param name: name of attribute to copy\n @type name: str\n @param new_name: name of the new attribute, default L{name}\n @type new_name: str\n \"\"\"\n if new_name is None:\n new_name = name\n self[new_name] = master[name]\n\n def _clone_list(self, master):\n \"\"\"Clones this attribute list from another\n\n @param master: the attribute list to copy from\n @type master: L{AttrList}\n \"\"\"\n for name in master:\n self._clone_attr(master, name)\n for name in list(self): #Can't iterate over a list we're changing\n if not name in master:\n del self[name]\n\n def _get_or_create(self, name):\n \"\"\"Retrieve L{Attr} or create it if it doesn't exist\n\n @param name: name of the attribute to look up or create\n @type name: str\n @return: attribute with this name\n @rtype: L{Attr}\n \"\"\"\n attr = None\n try:\n attr = self.AttrType(self._cdf_file, name)\n except CDFError:\n (t, v, tb) = sys.exc_info()\n if v.status != const.NO_SUCH_ATTR:\n raise\n if attr is None:\n attr = self.AttrType(self._cdf_file, name, True)\n elif attr.global_scope() != self.global_scope:\n raise KeyError(name + ': not ' + self.attr_name)\n return attr\n\n\nclass gAttrList(AttrList):\n \"\"\"\n Object representing *all* the gAttributes in a CDF.\n\n Normally accessed as an attribute of an open :class:`CDF`:\n\n >>> global_attribs = cdffile.attrs\n\n Appears as a dictionary: keys are attribute names; each value is an\n attribute represented by a :class:`gAttr` object. To access the global\n attribute TEXT:\n\n >>> text_attr = cdffile.attrs['TEXT']\n\n See Also\n ========\n :class:`AttrList`\n \"\"\"\n AttrType = gAttr\n attr_name = 'gAttribute'\n global_scope = True\n\n def __len__(self):\n \"\"\"\n Number of gAttributes in this CDF\n\n Returns\n =======\n out : int\n number of gAttributes in the CDF\n \"\"\"\n count = ctypes.c_long(0)\n self._cdf_file._call(const.GET_, const.CDF_NUMgATTRS_,\n ctypes.byref(count))\n return count.value\n\n\nclass zAttrList(AttrList):\n \"\"\"Object representing *all* the zAttributes in a zVariable.\n\n Normally accessed as an attribute of a :class:`Var` in an open\n CDF:\n \n >>> epoch_attribs = cdffile['Epoch'].attrs\n\n Appears as a dictionary: keys are attribute names, values are\n the value of the zEntry associated with the appropriate zVariable.\n Each vAttribute in a CDF may only have a *single* entry associated\n with each variable. The entry may be a string, a single numerical value,\n or a series of numerical values. Entries with multiple values are returned\n as an entire list; direct access to the individual elements is not\n possible.\n\n Example: finding the first dependency of (ISTP-compliant) variable\n ``Flux``:\n\n >>> print cdffile['Flux'].attrs['DEPEND_0']\n\n zAttributes are shared among zVariables, one zEntry allowed per zVariable.\n (pyCDF hides this detail.) Deleting the last zEntry for a zAttribute will\n delete the underlying zAttribute.\n\n zEntries are created and destroyed by the usual dict methods on the\n zAttrlist:\n \n >>> epoch_attribs['new_entry'] = [1, 2, 4] #assign a list to new zEntry\n >>> del epoch_attribs['new_entry'] #delete the zEntry\n\n The type of the zEntry is guessed from data provided. The type is chosen to\n match the data; subject to that constraint, it will try to match\n (in order):\n\n #. existing zEntry corresponding to this zVar\n #. other zEntries in this zAttribute\n #. the type of this zVar\n #. data-matching constraints described in :py:meth:`CDF.new`\n\n See Also\n ========\n :class:`AttrList`\n\n \"\"\"\n AttrType = zAttr\n attr_name = 'zAttribute'\n global_scope = False\n\n def __init__(self, zvar):\n \"\"\"Initialize the attribute collection\n\n @param zvar: zVariable these attributes are in\n @param zvar: :py:class:`pycdf.Var`\n \"\"\"\n super(zAttrList, self).__init__(zvar.cdf_file, zvar._num)\n self._zvar = zvar\n\n def __getitem__(self, name):\n \"\"\"Find an zEntry by name\n\n @param name: name of the zAttribute to return\n @type name: str\n @return: attribute named L{name}\n @rtype: L{zAttr}\n @raise KeyError: if there is no attribute named L{name} associated\n with this zVariable\n @raise CDFError: other errors in CDF library\n \"\"\"\n attrib = super(zAttrList, self).__getitem__(name)\n zvar_num = self._zvar._num()\n if attrib.has_entry(zvar_num):\n attrib._raw = self._zvar._raw\n return attrib[zvar_num]\n else:\n raise KeyError(name + ': no such attribute for variable ' +\n self._zvar.name())\n\n def __delitem__(self, name):\n \"\"\"Delete an zEntry by name\n\n @param name: name of the zEntry to delete\n @type name: str\n @raise KeyError: if there is no attribute named L{name} associated\n with this zVariable\n @raise CDFError: other errors in CDF library\n @note: If this is the only remaining entry, the Attribute will be\n deleted.\n \"\"\"\n attrib = super(zAttrList, self).__getitem__(name)\n zvar_num = self._zvar._num()\n if not attrib.has_entry(zvar_num):\n raise KeyError(str(name) + ': no such attribute for variable ' +\n str(self._zvar._name))\n del attrib[zvar_num]\n if len(attrib) == 0:\n attrib._delete()\n\n def __setitem__(self, name, data):\n \"\"\"Sets a zEntry by name\n\n The type of the zEntry is guessed from L{data}. The type is chosen to\n match the data; subject to that constraint, it will try to match\n (in order):\n 1. existing zEntry corresponding to this zVar\n 2. other zEntries in this zAttribute\n 3. the type of this zVar\n 4. data-matching constraints described in L{_Hyperslice.types}\n\n @param name: name of zAttribute; zEntry for this zVariable will be set\n in zAttribute by this name\n @type name: str\n @raise CDFError: errors in CDF library\n @raise ValueError: if unable to find a valid CDF type matching L{data},\n or if L{data} is the wrong dimensions.\n \"\"\"\n try:\n attr = super(zAttrList, self).__getitem__(name)\n except KeyError:\n attr = zAttr(self._cdf_file, name, True)\n attr._raw = self._zvar._raw\n attr[self._zvar._num()] = data\n\n def __len__(self):\n \"\"\"Number of zAttributes in this variable\n\n @return: number of zAttributes in the CDF\n which have entries for this variable.\n @rtype: int\n \"\"\"\n length = 0\n count = ctypes.c_long(0)\n self._cdf_file._call(const.GET_, const.CDF_NUMATTRS_,\n ctypes.byref(count))\n current = 0\n while current < count.value:\n candidate = zAttr(self._cdf_file, current)\n if not candidate.global_scope():\n if candidate.has_entry(self._zvar._num()):\n length += 1\n current += 1\n return length\n\n def type(self, name, new_type=None):\n \"\"\"Find or change the CDF type of a zEntry in this zVar\n\n @param name: name of the zAttr to check or change\n @type name: str\n @param new_type: type to change it to, see :py:mod:`pycdf.const`\n @type new_type: ctypes.c_long\n @return: CDF variable type, see :py:mod:`pycdf.const`\n @rtype: int\n @note: If changing types, old and new must be equivalent, see CDF\n User's Guide section 2.5.5 pg. 57\n \"\"\"\n attrib = super(zAttrList, self).__getitem__(name)\n zvar_num = self._zvar._num()\n if not attrib.has_entry(zvar_num):\n raise KeyError(name + ': no such attribute for variable ' +\n self._zvar.name())\n return attrib.type(zvar_num, new_type)\n\n def _clone_attr(self, master, name, new_name=None):\n \"\"\"Clones a single attribute from one in this list or another\n\n Copies data and types from the master attribute to the new one\n\n @param master: attribute list to copy attribute from\n @type master: L{zAttrList}\n @param name: name of attribute to copy\n @type name: str\n @param new_name: name of the new attribute, default L{name}\n @type new_name: str\n \"\"\"\n if new_name is None:\n new_name = name\n if new_name in self:\n del self[new_name]\n self.new(new_name, master[name],\n master.type(name) if hasattr(master, 'type') else None)\n" ]
[ [ "numpy.rollaxis", "numpy.hstack", "numpy.trunc", "numpy.abs", "numpy.min", "numpy.arange", "numpy.ma.getdata", "numpy.flipud", "numpy.frompyfunc", "numpy.dtype", "numpy.round", "numpy.max", "numpy.char.array", "numpy.vectorize", "numpy.asanyarray", "numpy.require", "numpy.zeros", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
juancruzsosa/torchero
[ "d1440b7a9c3ab2c1d3abbb282abb9ee1ea240797", "d1440b7a9c3ab2c1d3abbb282abb9ee1ea240797" ]
[ "torchero/utils/defaults.py", "torchero/meters/confusion_matrix.py" ]
[ "from collections import Iterable\n\nfrom torch import nn\nfrom torch import optim\n\nfrom torchero import meters\nfrom functools import partial\n\nINVALID_MODE_INFERENCE_MESSAGE = (\n \"Could not infer mode from meter {meter}\"\n)\n\ndef get_default_mode(meter):\n if hasattr(meter.__class__, 'DEFAULT_MODE'):\n return getattr(meter.__class__, 'DEFAULT_MODE')\n else:\n raise Exception(INVALID_MODE_INFERENCE_MESSAGE\n .format(meter=getattr(meter, 'name', meter.__class__.__name__)))\n\n\n\noptimizers = {\n 'asgd': optim.ASGD,\n 'adadelta': optim.Adadelta,\n 'adagrad': optim.Adagrad,\n 'adam': optim.Adam,\n 'adamax': optim.Adamax,\n 'lbfgs': optim.LBFGS,\n 'rmsprop': optim.RMSprop,\n 'rprop': optim.Rprop,\n 'sgd': lambda params: optim.SGD(params, lr=1e-2),\n 'sparseadam': optim.SparseAdam\n}\n\n\ndef get_optimizer_by_name(name, model):\n if name not in optimizers:\n raise KeyError(\"Optimizer {} not found. \"\n \"Optimizer availables: {}\"\n .format(repr(name),\n ', '.join(map(repr, optimizers.keys()))))\n return optimizers[name](model.parameters())\n\n\nlosses = {\n 'l1': nn.L1Loss,\n 'mse': nn.MSELoss,\n 'cross_entropy': nn.CrossEntropyLoss,\n 'nll': nn.NLLLoss,\n 'poisson_nll': nn.PoissonNLLLoss,\n 'kl_div': nn.KLDivLoss,\n 'binary_cross_entropy': nn.BCELoss,\n 'binary_cross_entropy_wl': nn.BCEWithLogitsLoss,\n 'margin_ranking': nn.MarginRankingLoss,\n 'hinge': nn.HingeEmbeddingLoss,\n 'multi_label_hinge': nn.MultiLabelMarginLoss,\n 'smooth': nn.SmoothL1Loss,\n 'soft_margin': nn.SoftMarginLoss,\n 'multilabel_soft_margin': nn.MultiLabelSoftMarginLoss,\n 'cosine': nn.CosineEmbeddingLoss,\n 'multi_hinge': nn.MultiMarginLoss,\n 'triplet_margin': nn.TripletMarginLoss\n}\n\n\ndef get_loss_by_name(name):\n if name not in losses:\n raise KeyError(\"Loss {} not found. Losses available: {}\"\n .format(repr(name),\n ', '.join(map(repr, losses.keys()))))\n return losses[name]()\n\n\nmeters_by_name = {\n 'mse': meters.MSE,\n 'rmse': meters.RMSE,\n 'msle': meters.MSLE,\n 'rmsle': meters.RMSLE,\n 'categorical_accuracy': meters.CategoricalAccuracy,\n 'categorical_accuracy_percentage': lambda: meters.CategoricalAccuracy() * 100.0,\n 'binary_accuracy': meters.BinaryAccuracy,\n 'binary_accuracy_percentage': lambda: meters.BinaryAccuracy() * 100,\n 'binary_accuracy_wl': meters.BinaryWithLogitsAccuracy,\n 'binary_accuracy_wl_percentage': lambda: meters.BinaryWithLogitsAccuracy() * 100,\n 'confusion_matrix': meters.ConfusionMatrix,\n 'confusion_matrix_percentage': lambda: meters.ConfusionMatrix() * 100,\n 'balanced_accuracy': meters.BalancedAccuracy,\n}\n\nfor name, metric in (('recall', meters.Recall),\n ('precision', meters.Precision),\n ('npv', meters.NPV),\n ('specificity', meters.Specificity),\n ('f1', meters.F1Score),\n ('f2', meters.F2Score)):\n meters_by_name.update({\n name: metric,\n name + '_wl': partial(metric, with_logits=True)\n })\n for agg_name in ('micro', 'macro', 'weighted'):\n meters_by_name.update({\n agg_name + '_' + name: partial(metric, with_logits=False, agg=agg_name),\n agg_name + '_' + name + '_wl': partial(metric, with_logits=True, agg=agg_name)\n })\n\nfor name, speed_metric, pace_metric in (('batches', meters.BatchSpeed, meters.BatchPace),\n ('it', meters.IterSpeed, meters.IterPace)):\n for unit_abbr, unit in (('sec', 'second'),\n ('min', 'minute')):\n meters_by_name.update({name + '/' + unit_abbr: partial(speed_metric, time_unit=unit),\n unit_abbr + '/' + name.replace('batches', 'batch'): partial(pace_metric, time_unit=unit)})\n\n\ndef get_meters_by_name(name):\n if name not in meters_by_name:\n raise KeyError(\"Meter {} not found. Meters available: {}\"\n .format(repr(name),\n ', '.join(map(repr, meters_by_name.keys()))))\n return meters_by_name[name]()\n\n\ndef parse_meters(meters):\n def to_small_case(obj):\n if hasattr(obj, 'name'):\n s = str(obj.name)\n else:\n name = obj.__class__.__name__\n s = ''\n for i in range(len(name)-1):\n s += name[i].lower()\n if name[i].islower() and not name[i+1].islower():\n s += '_'\n s += name[-1].lower()\n return s\n\n def parse(obj):\n if isinstance(obj, str):\n return get_meters_by_name(obj)\n else:\n return obj\n\n def parse_name(obj):\n if isinstance(obj, str):\n obj = get_meters_by_name(obj)\n return to_small_case(obj)\n\n if isinstance(meters, dict):\n return {k: parse(v) for k, v in meters.items()}\n elif isinstance(meters, Iterable):\n return {parse_name(v): parse(v) for v in meters}\n else:\n raise Exception(\"Expected iterable meters\")\n\ntime_units = {'hour': 60*60,\n 'hours': 60*60,\n 'minute': 60,\n 'minutes': 60,\n 'second': 1,\n 'seconds': 1}\n\ndef parse_time_unit(time_unit):\n if isinstance(time_unit, (int, float)):\n return time_unit\n elif isinstance(time_unit, str) and time_unit in time_units:\n return time_units[time_unit]\n elif isinstance(time_unit, str):\n raise ValueError(\"Invalid time_unit reference!\")\n else:\n raise TypeError(\"Invalid type for time_unit\")\n", "from abc import ABCMeta, abstractmethod\n\nimport torch\n\nfrom torchero.meters.base import BaseMeter\n\n\nclass ConfusionMatrixController(object, metaclass=ABCMeta):\n def __init__(self, normalize=False):\n self.normalize = normalize\n self.reset()\n\n @property\n @abstractmethod\n def matrix(self):\n pass\n\n @abstractmethod\n def reset(self):\n pass\n\n def increment(self, a, b):\n for i, j in zip(a, b):\n self.matrix[i][j] += 1\n\n @property\n def num_classes(self):\n return self.matrix.shape[0]\n\n def plot(self, ax=None, fig=None, classes=None, xlabel=\"Predicted label\", ylabel=\"True label\", title=\"Confusion Matrix\", cmap=\"Blues\", colorbar=False):\n try:\n from matplotlib import pyplot as plt\n except ImportError:\n raise ImportError(\n \"Matplotlib is required in order to plot confusion matrix\"\n )\n if (classes is not None) and (len(classes) != self.num_classes):\n raise ValueError(\"number of classes is: {} but {} were passed!\".format(self.num_classes, len(classes)))\n\n if ax is None:\n ax = plt.gca()\n if fig is None:\n fig = plt.gcf()\n matrix = self.matrix\n normalized_matrix = matrix / matrix.sum(dim=0)\n cmap = plt.get_cmap(cmap)\n im=ax.imshow(normalized_matrix, cmap=cmap, vmin=0, vmax=1)\n ax.set_xticks(range(self.num_classes))\n ax.set_yticks(range(self.num_classes))\n\n ax.xaxis.set_ticks_position('top')\n ax.xaxis.set_label_position('top')\n\n for i in range(matrix.shape[0]):\n for j in range(matrix.shape[1]):\n value = matrix[i, j].item()\n normalized_value = normalized_matrix[i, j].item()\n if self.normalize:\n value = '{:.2f}'.format(value)\n else:\n value = '{}'.format(int(value))\n if i == j:\n value += \" \" + \"({:.0f}%)\".format(normalized_value * 100)\n r, g, b, _ = cmap(normalized_value)\n text_color = 'white' if r * g * b < 0.5 else 'black'\n text = ax.text(j, i, value,\n ha=\"center\", va=\"center\", color=text_color)\n\n if xlabel is not None:\n ax.set_xlabel(xlabel)\n\n if ylabel is not None:\n ax.set_ylabel(ylabel)\n\n if title is not None:\n ax.set_title(title)\n\n if classes is not None:\n ax.set_xticklabels(classes)\n ax.set_yticklabels(classes)\n\n if colorbar:\n fig.colorbar(im, ax=ax)\n\n\nclass FixedConfusionMatrixController(ConfusionMatrixController):\n def __init__(self, nr_classes, normalize=False):\n if not isinstance(nr_classes, int) or nr_classes == 0:\n raise Exception(ConfusionMatrix.INVALID_NR_OF_CLASSES_MESSAGE\n .format(nr_classes=nr_classes))\n self._nr_classes = nr_classes\n super(FixedConfusionMatrixController, self).__init__(normalize=normalize)\n\n @property\n def matrix(self):\n if self.normalize:\n return self._matrix / self._matrix.sum(dim=0)\n else:\n return self._matrix\n\n def reset(self):\n self._matrix = torch.zeros(self._nr_classes, self._nr_classes)\n\n def check_inputs(self, xs):\n if not ((0 <= xs) & (xs < self._matrix.shape[0])).all():\n raise Exception(ConfusionMatrix.INVALID_LABELS_MESSAGE)\n\n def increment(self, a, b):\n self.check_inputs(torch.cat([a, b]))\n super(FixedConfusionMatrixController, self).increment(a, b)\n\n\nclass ResizableConfusionMatrixController(ConfusionMatrixController):\n @property\n def matrix(self):\n if self.normalize:\n return self._matrix / self._matrix.sum(dim=0)\n else:\n return self._matrix\n\n def reset(self):\n self._matrix = torch.zeros(1, 1)\n\n def expand(self, n):\n total_rows = n + self._matrix.shape[0]\n total_cols = n + self._matrix.shape[1]\n\n old_matrix, self._matrix = self._matrix, torch.zeros(total_rows,\n total_cols)\n self._matrix[:old_matrix.shape[0], :old_matrix.shape[1]] = old_matrix\n\n def increment(self, a, b):\n max_class_nr = max(torch.max(a), torch.max(b))\n\n if max_class_nr >= self._matrix.shape[0]:\n n = max_class_nr - self._matrix.shape[0] + 1\n self.expand(n)\n\n super(ResizableConfusionMatrixController, self).increment(a, b)\n\nclass ConfusionMatrix(BaseMeter):\n INVALID_NR_OF_CLASSES_MESSAGE = (\n 'Expected number of classes to be greater than one. Got {nr_classes}'\n )\n INVALID_INPUT_TYPE_MESSAGE = (\n 'Expected input tensors of type LongTensor. Got {type_}'\n )\n INVALID_BATCH_DIMENSION_MESSAGE = (\n 'Expected input tensors of 1-dimention. Got {dims}'\n )\n INVALID_LENGTHS_MESSAGE = (\n 'Expected input and targets of same lengths'\n )\n INVALID_LABELS_MESSAGE = (\n 'Expected labels between 0 and number of classes'\n )\n\n def __init__(self, nr_classes='auto', normalize=False):\n \"\"\" Constructor\n\n Arguments:\n nr_classes (int or str): If 'auto' is passed the confusion matrix will readjust\n to the observed ranges. If a number is passed this will reserve the confusion matrix\n for that size. Default 'auto'\n normalize (bool): IF passed the confusion matrix will hold percentages\n \"\"\"\n if isinstance(nr_classes, str) and nr_classes == 'auto':\n self.matrix_controller = ResizableConfusionMatrixController(normalize=normalize)\n elif isinstance(nr_classes, int) and nr_classes > 0:\n self.matrix_controller = FixedConfusionMatrixController(nr_classes, normalize=normalize)\n else:\n raise ValueError(self.INVALID_NR_OF_CLASSES_MESSAGE\n .format(nr_classes=nr_classes))\n self.reset()\n\n def reset(self):\n self.matrix_controller.reset()\n\n def check_tensor(self, a):\n if (isinstance(a, torch.FloatTensor) or\n isinstance(a, torch.cuda.FloatTensor)):\n raise Exception(self.INVALID_INPUT_TYPE_MESSAGE\n .format(type_=a.type()))\n\n if a.dim() > 1:\n raise Exception(self.INVALID_BATCH_DIMENSION_MESSAGE\n .format(dims=a.dim()))\n\n def measure(self, a, b):\n if a.dim() == 2:\n a = a.topk(k=1, dim=1)[1].squeeze(1)\n if b.dim() == 2:\n b = b.topk(k=1, dim=1)[1].squeeze(1)\n\n self.check_tensor(a)\n self.check_tensor(b)\n\n if len(a) != len(b):\n raise Exception(self.INVALID_LENGTHS_MESSAGE)\n\n self.matrix_controller.increment(a, b)\n\n def value(self):\n return self.matrix_controller\n" ]
[ [ "torch.optim.SGD" ], [ "matplotlib.pyplot.gca", "torch.max", "torch.cat", "torch.zeros", "matplotlib.pyplot.get_cmap", "matplotlib.pyplot.gcf" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
filipeaguiarrod/Formacao-Cientista-de-Dados-com-Python-e-R
[ "c9b72f93b2a6ead49641d765fe2a0f23ffb4b1bf" ]
[ "Python/grafico_3d.py" ]
[ "import pandas as pd\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import axes3d\n\nbase = pd.read_csv('orchard.csv')\n\nfigura = plt.figure()\neixo = figura.add_subplot(1, 1, 1, projection = '3d')\neixo.scatter(base.decrease, base.rowpos, base.colpos)\neixo.set_xlabel('decrease')\neixo.set_ylabel('rowpos')\neixo.set_zlabel('colpos')\n\n# cores\n# https://pythonspot.com/3d-scatterplot/" ]
[ [ "pandas.read_csv", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
xli94/simpeg
[ "a0078301f7dfd54431d6b51abcf092079ad0e5a3" ]
[ "SimPEG/electromagnetics/natural_source/survey.py" ]
[ "import sys\nimport numpy as np\nfrom numpy.lib import recfunctions as recFunc\n\nfrom ..frequency_domain.survey import Survey\nfrom ...data import Data as BaseData\nfrom ...utils import mkvc\nfrom .sources import Planewave_xy_1Dprimary, Planewave_xy_1DhomotD\nfrom .receivers import Point3DImpedance, Point3DTipper\nfrom .utils.plot_utils import DataNSEMPlotMethods\n#########\n# Survey\n#########\n\n\n# class Survey(BaseSurvey):\n# \"\"\"\n# Survey class for NSEM.\n\n# **Requried**\n# :param list srcList: List of sources associated with the survey\n\n\n# **Optional**\n# \"\"\"\n# srcPair = BaseNSEMSrc\n\n# def __init__(self, srcList, **kwargs):\n# # Sort these by frequency\n# self.source_list = srcList\n# BaseSurvey.__init__(self, **kwargs)\n\n# _freqDict = {}\n# for src in srcList:\n# if src.freq not in _freqDict:\n# _freqDict[src.freq] = []\n# _freqDict[src.freq] += [src]\n\n# self._freqDict = _freqDict\n# self._freqs = sorted([f for f in self._freqDict])\n\n# @property\n# def freqs(self):\n# \"\"\"Frequencies\"\"\"\n# return self._freqs\n\n# @property\n# def nFreq(self):\n# \"\"\"Number of frequencies\"\"\"\n# return len(self._freqDict)\n\n# def getSrcByFreq(self, freq):\n# \"\"\"Returns the sources associated with a specific frequency.\"\"\"\n# assert freq in self._freqDict, \"The requested frequency is not in this survey.\"\n# return self._freqDict[freq]\n\n# def eval(self, f):\n# \"\"\"\n# Evalute and return Data given calculated fields\n\n# :param SimPEG.electromagnetics.frequency_domain.fields.FieldsFDEM f: A NSEM fileds object to evaluate data from\n# :retype: SimPEG.EM.NSEM.Data\n# :return: NSEM Data object\n# \"\"\"\n# data = Data(self)\n# for src in self.source_list:\n# sys.stdout.flush()\n# for rx in src.receiver_list:\n# data[src, rx] = rx.eval(src, self.mesh, f)\n# return data\n\n# def evalDeriv(self, f):\n# raise Exception('Use Sources to project fields deriv.')\n\n#########\n# Data\n#########\n\n\nclass Data(BaseData, DataNSEMPlotMethods):\n \"\"\"\n Data class for NSEMdata. Stores the data vector indexed by the survey.\n \"\"\"\n\n def __init__(self, survey, dobs=None, relative_error=None, noise_floor=None):\n BaseData.__init__(self, survey, dobs, relative_error, noise_floor)\n\n def toRecArray(self, returnType=\"RealImag\"):\n \"\"\"\n Returns a numpy.recarray for a SimpegNSEM impedance data object.\n\n :param returnType: Switches between returning a rec array where the impedance is split to real and imaginary ('RealImag') or is a complex ('Complex')\n :type returnType: str, optional\n :rtype: numpy.recarray\n :return: Record array with data, with indexed columns\n \"\"\"\n\n # Define the record fields\n dtRI = [\n (\"freq\", float),\n (\"x\", float),\n (\"y\", float),\n (\"z\", float),\n (\"zxxr\", float),\n (\"zxxi\", float),\n (\"zxyr\", float),\n (\"zxyi\", float),\n (\"zyxr\", float),\n (\"zyxi\", float),\n (\"zyyr\", float),\n (\"zyyi\", float),\n (\"tzxr\", float),\n (\"tzxi\", float),\n (\"tzyr\", float),\n (\"tzyi\", float),\n ]\n dtCP = [\n (\"freq\", float),\n (\"x\", float),\n (\"y\", float),\n (\"z\", float),\n (\"zxx\", complex),\n (\"zxy\", complex),\n (\"zyx\", complex),\n (\"zyy\", complex),\n (\"tzx\", complex),\n (\"tzy\", complex),\n ]\n\n for src in self.survey.source_list:\n # Temp array for all the receivers of the source.\n # Note: needs to be written more generally,\n # using diffterent rxTypes and not all the data at the locations\n # Assume the same locs for all RX\n locs = src.receiver_list[0].locations\n if locs.shape[1] == 1:\n locs = np.hstack((np.array([[0.0, 0.0]]), locs))\n elif locs.shape[1] == 2:\n locs = np.hstack((np.array([[0.0]]), locs))\n tArrRec = np.concatenate(\n (\n src.freq * np.ones((locs.shape[0], 1)),\n locs,\n np.nan * np.ones((locs.shape[0], 12)),\n ),\n axis=1,\n ).view(dtRI)\n # Get the type and the value for the DataNSEM object as a list\n typeList = [\n [rx.orientation, rx.component, self[src, rx]]\n for rx in src.receiver_list\n ]\n # Insert the values to the temp array\n for nr, (k, c, val) in enumerate(typeList):\n zt_type = \"t\" if \"z\" in k else \"z\"\n key = zt_type + k + c[0]\n tArrRec[key] = mkvc(val, 2)\n # Masked array\n\n try:\n outTemp = recFunc.stack_arrays((outTemp, tArrRec))\n except NameError:\n outTemp = tArrRec.copy()\n\n if \"RealImag\" in returnType:\n outArr = outTemp.copy()\n elif \"Complex\" in returnType:\n # Add the real and imaginary to a complex number\n outArr = np.empty(outTemp.shape, dtype=dtCP)\n for comp in [\"freq\", \"x\", \"y\", \"z\"]:\n outArr[comp] = outTemp[comp].copy()\n for comp in [\"zxx\", \"zxy\", \"zyx\", \"zyy\", \"tzx\", \"tzy\"]:\n outArr[comp] = (\n outTemp[comp + \"r\"].copy() + 1j * outTemp[comp + \"i\"].copy()\n )\n else:\n raise NotImplementedError(\n \"{:s} is not implemented, as to be RealImag or Complex.\"\n )\n\n # Return\n return outArr\n\n @classmethod\n def fromRecArray(cls, recArray, srcType=\"primary\"):\n \"\"\"\n Class method that reads in a numpy record array to NSEMdata object.\n\n :param recArray: Record array with the data. Has to have ('freq','x','y','z') columns and some ('zxx','zxy','zyx','zyy','tzx','tzy')\n :type recArray: numpy.recarray\n\n :param srcType: The type of SimPEG.EM.NSEM.SrcNSEM to be used\n :type srcType: str, optional\n\n \"\"\"\n if srcType == \"primary\":\n src = Planewave_xy_1Dprimary\n elif srcType == \"total\":\n src = Planewave_xy_1DhomotD\n else:\n raise NotImplementedError(\"{:s} is not a valid source type for NSEMdata\")\n\n # Find all the frequencies in recArray\n uniFreq = np.unique(recArray[\"freq\"].copy())\n srcList = []\n dataList = []\n for freq in uniFreq:\n # Initiate rxList\n rxList = []\n # Find that data for freq\n dFreq = recArray[recArray[\"freq\"] == freq].copy()\n # Find the impedance rxTypes in the recArray.\n rxTypes = [\n comp\n for comp in recArray.dtype.names\n if (len(comp) == 4 or len(comp) == 3) and \"z\" in comp\n ]\n for rxType in rxTypes:\n # Find index of not nan values in rxType\n notNaNind = ~np.isnan(dFreq[rxType].copy())\n if np.any(notNaNind): # Make sure that there is any data to add.\n locs = _rec_to_ndarr(dFreq[[\"x\", \"y\", \"z\"]][notNaNind].copy())\n if dFreq[rxType].dtype.name in \"complex128\":\n if \"t\" in rxType:\n rxList.append(Point3DTipper(locs, rxType[1:3], \"real\"))\n dataList.append(dFreq[rxType][notNaNind].real.copy())\n rxList.append(Point3DTipper(locs, rxType[1:3], \"imag\"))\n dataList.append(dFreq[rxType][notNaNind].imag.copy())\n elif \"z\" in rxType:\n rxList.append(Point3DImpedance(locs, rxType[1:3], \"real\"))\n dataList.append(dFreq[rxType][notNaNind].real.copy())\n rxList.append(Point3DImpedance(locs, rxType[1:3], \"imag\"))\n dataList.append(dFreq[rxType][notNaNind].imag.copy())\n else:\n component = \"real\" if \"r\" in rxType else \"imag\"\n if \"z\" in rxType:\n rxList.append(\n Point3DImpedance(locs, rxType[1:3], component)\n )\n dataList.append(dFreq[rxType][notNaNind].copy())\n if \"t\" in rxType:\n rxList.append(Point3DTipper(locs, rxType[1:3], component))\n dataList.append(dFreq[rxType][notNaNind].copy())\n\n srcList.append(src(rxList, freq))\n\n # Make a survey\n survey = Survey(srcList)\n dataVec = np.hstack(dataList)\n return cls(survey, dataVec)\n\n\ndef _rec_to_ndarr(rec_arr, data_type=float):\n \"\"\"\n Function to transform a numpy record array to a nd array.\n dupe of SimPEG.electromagnetics.natural_source.utils.rec_to_ndarr to avoid circular import\n \"\"\"\n # fix for numpy >= 1.16.0\n # https://numpy.org/devdocs/release/1.16.0-notes.html#multi-field-views-return-a-view-instead-of-a-copy\n return np.array(recFunc.structured_to_unstructured(recFunc.repack_fields(rec_arr[list(rec_arr.dtype.names)])),\n dtype=data_type)\n" ]
[ [ "numpy.hstack", "numpy.lib.recfunctions.stack_arrays", "numpy.ones", "numpy.any", "numpy.array", "numpy.empty" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
daniel98789/bullet3
[ "b57aa900293e21f7808ea2697a5b64b494867492" ]
[ "python_part/trees.py" ]
[ "import PyBulletEnv\nimport Obj\nfrom numpy import random\n\nif __name__ == \"__main__\":\n env = PyBulletEnv.PyBulletEnv()\n env.setup()\n tree = Obj.Obj(\"data/tree/Tree.obj\")\n \n\n forest = []\n for _ in range(2):\n x = random.uniform(0, 20)\n y = random.uniform(0, 20)\n forest.append(tree.createObjectObj([x, y , 3.7], 1.0))\n\n env.analyze(tree, forest)\n \n env.run()\n\n\n" ]
[ [ "numpy.random.uniform" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
QSD-for-WaSH/sanitation
[ "cbcbdd7ead382a6e66b51b5193852494ab3f081b", "cbcbdd7ead382a6e66b51b5193852494ab3f081b", "cbcbdd7ead382a6e66b51b5193852494ab3f081b" ]
[ "qsdsan/sanunits/_suspended_growth_bioreactor.py", "qsdsan/_lca.py", "qsdsan/_transportation.py" ]
[ "# -*- coding: utf-8 -*-\n'''\nQSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems\n\nThis module is developed by:\n Joy Zhang <[email protected]>\n\nThis module is under the University of Illinois/NCSA Open Source License.\nPlease refer to https://github.com/QSD-Group/QSDsan/blob/main/LICENSE.txt\nfor license details.\n'''\n\nfrom .. import SanUnit, WasteStream, Process, Processes, CompiledProcesses\nfrom ._clarifier import _settling_flux\nfrom sympy import symbols, lambdify, Matrix\nfrom scipy.integrate import solve_ivp\nfrom warnings import warn\nfrom math import floor, ceil\nimport numpy as np\nimport pandas as pd\nfrom numba import njit\n\n__all__ = ('CSTR',\n 'SBR',\n # 'PFR',\n )\n\ndef _add_aeration_to_growth_model(aer, model):\n if isinstance(aer, Process):\n processes = Processes(model.tuple)\n processes.append(aer)\n processes.compile()\n else:\n processes = model\n processes.compile()\n return processes\n\n# %%\n\n@njit(cache=True)\ndef dydt_cstr_no_rxn_fixed_aer(QC_ins, dQC_ins, V_arr, Q_e_arr, _dstate, Cs):\n Q_ins = QC_ins[:, -1]\n C_ins = QC_ins[:, :-1]\n flow_in = Q_ins @ C_ins / V_arr\n Q_e_arr[:] = Q_ins.sum(axis=0)\n _dstate[-1] = dQC_ins[:, -1].sum(axis=0)\n flow_out = Q_e_arr * Cs / V_arr\n _dstate[:-1] = flow_in - flow_out\n\n@njit(cache=True)\ndef dydt_cstr_no_rxn_controlled_aer(QC_ins, dQC_ins, V_arr, Q_e_arr, _dstate, Cs):\n Q_ins = QC_ins[:, -1]\n C_ins = QC_ins[:, :-1]\n flow_in = Q_ins @ C_ins / V_arr\n Q_e_arr[:] = Q_ins.sum(axis=0)\n _dstate[-1] = dQC_ins[:, -1].sum(axis=0)\n flow_out = Q_e_arr * Cs / V_arr\n _dstate[:-1] = flow_in - flow_out\n\n#%%\nclass CSTR(SanUnit):\n '''\n A single continuous stirred tank reactor.\n\n Parameters\n ----------\n ID : str\n ID for the reactor.\n ins : :class:`WasteStream`\n Influents to the reactor. Can be an array of up to 3 WasteStream objects by\n default, typically wastewater to be treated, recycled effluent, recycled\n activated sludge.\n outs : :class:`WasteStream`\n Treated effluent.\n split : iterable of float\n Volumetric splits of effluent flows if there are more than one effluent.\n The default is None.\n V_max : float\n Designed volume, in [m^3]. The default is 1000.\n aeration : float or :class:`Process`, optional\n Aeration setting. Either specify a targeted dissolved oxygen concentration\n in [mg O2/L] or provide a :class:`Process` object to represent aeration,\n or None for no aeration. The default is 2.0.\n DO_ID : str, optional\n The :class:`Component` ID for dissolved oxygen, only relevant when the\n reactor is aerated. The default is 'S_O2'.\n suspended_growth_model : :class:`Processes`, optional\n The suspended growth biokinetic model. The default is None.\n '''\n\n _N_ins = 3\n _N_outs = 1\n _ins_size_is_fixed = False\n _outs_size_is_fixed = False\n\n def __init__(self, ID='', ins=None, outs=(), split=None, thermo=None,\n init_with='WasteStream', V_max=1000, aeration=2.0,\n DO_ID='S_O2', suspended_growth_model=None,\n isdynamic=True, **kwargs):\n SanUnit.__init__(self, ID, ins, outs, thermo, init_with, isdynamic=isdynamic)\n self._V_max = V_max\n self._aeration = aeration\n self._DO_ID = DO_ID\n self._model = suspended_growth_model\n self._concs = None\n self._mixed = WasteStream()\n self.split = split\n for attr, value in kwargs.items():\n setattr(self, attr, value)\n\n @property\n def V_max(self):\n '''[float] The designed maximum liquid volume, not accounting for increased volume due to aeration, in m^3.'''\n return self._V_max\n\n @V_max.setter\n def V_max(self, Vm):\n self._V_max = Vm\n\n @property\n def aeration(self):\n '''[:class:`Process` or float or NoneType] Aeration model.'''\n return self._aeration\n\n @aeration.setter\n def aeration(self, ae):\n if ae is None or isinstance(ae, Process): self._aeration = ae\n elif isinstance(ae, (float, int)):\n if ae < 0:\n raise ValueError('targeted dissolved oxygen concentration for aeration must be non-negative.')\n else:\n if ae > 14:\n warn(f'targeted dissolved oxygen concentration for {self.ID} might exceed the saturated level.')\n self._aeration = ae\n else:\n raise TypeError(f'aeration must be one of the following types: float, '\n f'int, Process, NoneType. Not {type(ae)}')\n\n @property\n def suspended_growth_model(self):\n '''[:class:`CompiledProcesses` or NoneType] Suspended growth model.'''\n return self._model\n\n @suspended_growth_model.setter\n def suspended_growth_model(self, model):\n if isinstance(model, CompiledProcesses) or model is None: self._model = model\n else: raise TypeError(f'suspended_growth_model must be one of the following '\n f'types: CompiledProesses, NoneType. Not {type(model)}')\n\n @property\n def DO_ID(self):\n '''[str] The `Component` ID for dissolved oxygen used in the suspended growth model and the aeration model.'''\n return self._DO_ID\n\n @DO_ID.setter\n def DO_ID(self, doid):\n if doid not in self.components.IDs:\n raise ValueError(f'DO_ID must be in the set of `CompiledComponents` used to set thermo, '\n f'i.e., one of {self.components.IDs}.')\n self._DO_ID = doid\n\n @property\n def split(self):\n '''[numpy.1darray or NoneType] The volumetric split of outs.'''\n return self._split\n\n @split.setter\n def split(self, split):\n if split is None: self._split = split\n else:\n if len(split) != len(self._outs):\n raise ValueError('split and outs must have the same size')\n self._split = np.array(split)/sum(split)\n\n @property\n def state(self):\n '''The state of the CSTR, including component concentrations [mg/L] and flow rate [m^3/d].'''\n if self._state is None: return None\n else:\n return dict(zip(list(self.components.IDs) + ['Q'], self._state))\n\n @state.setter\n def state(self, QCs):\n QCs = np.asarray(QCs)\n if QCs.shape != (len(self.components)+1, ):\n raise ValueError(f'state must be a 1D array of length {len(self.components) + 1},'\n 'indicating component concentrations [mg/L] and total flow rate [m^3/d]')\n self._state = QCs\n\n def set_init_conc(self, **kwargs):\n '''set the initial concentrations [mg/L] of the CSTR.'''\n Cs = np.zeros(len(self.components))\n cmpx = self.components.index\n for k, v in kwargs.items(): Cs[cmpx(k)] = v\n self._concs = Cs\n\n def _init_state(self):\n mixed = self._mixed\n Q = mixed.get_total_flow('m3/d')\n if self._concs is not None: Cs = self._concs\n else: Cs = mixed.conc\n self._state = np.append(Cs, Q).astype('float64')\n self._dstate = self._state * 0.\n\n def _update_state(self):\n arr = self._state\n if self.split is None: self._outs[0].state = arr\n else:\n for ws, spl in zip(self._outs, self.split):\n y = arr.copy()\n y[-1] *= spl\n ws.state = y\n\n def _update_dstate(self):\n arr = self._dstate\n if self.split is None: self._outs[0].dstate = arr\n else:\n for ws, spl in zip(self._outs, self.split):\n y = arr.copy()\n y[-1] *= spl\n ws.dstate = y\n\n def _run(self):\n '''Only to converge volumetric flows.'''\n mixed = self._mixed # avoid creating multiple new streams\n mixed.mix_from(self.ins)\n Q = mixed.F_vol # m3/hr\n if self.split is None: self.outs[0].copy_like(mixed)\n else:\n for ws, spl in zip(self._outs, self.split):\n ws.copy_like(mixed)\n ws.set_total_flow(Q*spl, 'm3/hr')\n\n def get_retained_mass(self, biomass_IDs):\n cmps = self.components\n mass = cmps.i_mass * self._state[:-1]\n return self._V_max * mass[cmps.indices(biomass_IDs)].sum()\n\n @property\n def ODE(self):\n if self._ODE is None:\n self._compile_ODE()\n return self._ODE\n\n def _compile_ODE(self):\n isa = isinstance\n C = list(symbols(self.components.IDs))\n m = len(C)\n if self._model is None:\n warn(f'{self.ID} was initialized without a suspended growth model, '\n f'and thus run as a non-reactive unit')\n r = lambda *args: np.zeros(m)\n else:\n processes = _add_aeration_to_growth_model(self._aeration, self._model)\n r_eqs = list(processes.production_rates.rate_of_production)\n r = lambdify(C, r_eqs, 'numpy')\n\n _dstate = self._dstate\n _update_dstate = self._update_dstate\n V_arr = np.full(m, self._V_max)\n Q_e_arr = np.zeros(m)\n\n if isa(self._aeration, (float, int)):\n i = self.components.index(self._DO_ID)\n fixed_DO = self._aeration\n def dy_dt(t, QC_ins, QC, dQC_ins):\n Cs = QC[:-1]\n Cs[i] = fixed_DO\n dydt_cstr_no_rxn_controlled_aer(QC_ins, dQC_ins, V_arr, Q_e_arr, _dstate, Cs)\n _dstate[:-1] += r(*Cs)\n _dstate[i] = 0\n _update_dstate()\n else:\n def dy_dt(t, QC_ins, QC, dQC_ins):\n Cs = QC[:-1]\n dydt_cstr_no_rxn_fixed_aer(QC_ins, dQC_ins, V_arr, Q_e_arr, _dstate, Cs)\n _dstate[:-1] += r(*Cs)\n _update_dstate()\n\n self._ODE = dy_dt\n\n def _design(self):\n pass\n\n\nclass SBR(SanUnit):\n '''\n Sequential batch reactors operated in parallel. The number of reactors is\n determined by operation cycle and influent flowrate. [1]_\n\n Parameters\n ----------\n ID : str\n ID for the reactors. The default is ''.\n ins : :class:`WasteStream`\n Influent to the reactor. Expected number of influent is 1.\n outs : :class:`WasteStream`\n Treated effluent and wasted sludge.\n surface_area : float, optional\n Surface area of the reactor bottom, in [m^2]. The reactor is assumed\n to be cylinder. The default is 1500.\n height : float, optional\n Height of the reactor, in [m]. The default is 4.\n operation_cycle : iterable of float, optional\n Operation cycle of the SBR, time for each stage specified in [h]. There\n are 7 stages: 1 - fill, 2 - fill, 3 - mix, 4 - mix, 5 - settle, 6 - decant,\n 7 - desludge. The first 4 stages are modeled as a biological reactor.\n The 5th stage is modeled as a 1D N-layer settler. The last 2 stages are\n assumed inactive. The default is (0.5, 1.5, 2.0, 0, 1.0, 0.5, 0.1).\n aeration : iterable of float and/or :class:`Process`, optional\n Aeration settings for the first 4 stages of the operation cycle. Either\n specify a targeted dissolved oxygen concentration in [mg O2/L] or provide\n a :class:`Process` object to represent aeration, or None for no aeration.\n The default is (None, None, None, 2.0).\n DO_ID : str, optional\n The :class:`Component` ID for dissolved oxygen, only relevant when the\n reactor is aerated. The default is 'S_O2'.\n suspended_growth_model : :class:`Processes`, optional\n The suspended growth biokinetic model. The default is None.\n N_layer : int, optional\n The number of layers to model settling. The default is 10.\n pumped_flow : float, optional\n Designed effluent flowrate, in [m^3/d]. The default is None.\n underflow : float, optional\n Designed wasted activated sludge flowrate, in [m^3/d]. The default is None.\n X_threshold : float, optional\n Threshold suspended solid concentration, in [g/m^3]. The default is 3000.\n v_max : float, optional\n Maximum theoretical (i.e. Vesilind) settling velocity, in [m/d]. The\n default is 474.\n v_max_practical : float, optional\n Maximum practical settling velocity, in [m/d]. The default is 250.\n rh : float, optional\n Hindered zone settling parameter in the double-exponential settling velocity\n function, in [m^3/g]. The default is 5.76e-4.\n rp : float, optional\n Flocculant zone settling parameter in the double-exponential settling velocity\n function, in [m^3/g]. The default is 2.86e-3.\n fns : float, optional\n Non-settleable fraction of the suspended solids, dimensionless. Must be within\n [0, 1]. The default is 2.28e-3.\n cache_state : bool, optional\n Whether to store volume and composition of retained sludge in the tank from\n most recent run. The default is True.\n\n References\n ----------\n .. [1] Takács, I.; Patry, G. G.; Nolasco, D. A Dynamic Model of the Clarification\n -Thickening Process. Water Res. 1991, 25 (10), 1263–1271.\n https://doi.org/10.1016/0043-1354(91)90066-Y.\n\n '''\n\n _N_ins = 1\n _N_outs = 2\n\n def __init__(self, ID='', ins=None, outs=(), thermo=None, init_with='WasteStream',\n surface_area=1500, height=4,\n operation_cycle=(0.5, 1.5, 2.0, 0, 1.0, 0.5, 0.1),\n aeration=(None, None, None, 2.0), DO_ID='S_O2',\n suspended_growth_model=None, N_layer=10,\n pumped_flow=None, underflow=None,\n X_threshold=3000, v_max=474, v_max_practical=250,\n rh=5.76e-4, rp=2.86e-3, fns=2.28e-3,\n cache_state=True, **kwargs):\n SanUnit.__init__(self, ID, ins, outs, thermo, init_with)\n\n self._V = surface_area * height\n self._A = surface_area\n self._h = height\n self._operation_cycle = operation_cycle\n self._aeration = aeration\n self._DO_ID = DO_ID\n self._model = suspended_growth_model\n self._N_layer = N_layer\n self._Q_e = pumped_flow\n self._Q_WAS = underflow\n self._X_t = X_threshold\n self._v_max = v_max\n self._v_max_p = v_max_practical\n self._rh = rh\n self._rp = rp\n self._fns = fns\n self._cache_state = cache_state\n\n for attr, value in kwargs.items():\n setattr(self, attr, value)\n self._init_Vas = None\n self._init_Cas = None\n self._dynamic_composition = None\n\n\n @property\n def operation_cycle(self):\n return dict(zip(('fill_1', 'fill_2', 'mix_1', 'mix_2', 'settle', 'decant', 'desludge'),\n self._operation_cycle))\n @property\n def total_cycle_time(self):\n return sum(self._operation_cycle)\n\n @property\n def aeration(self):\n return dict(zip(('fill_1', 'fill_2', 'mix_1', 'mix_2'),\n self._aeration[:4]))\n\n @property\n def C_t(self):\n if self._dynamic_composition:\n return pd.DataFrame(self._dynamic_composition,\n columns = ['Time[d]'] + list(self.components.IDs))\n else: return None\n\n def _run(self, cache_state=True):\n if self._model is None:\n raise RuntimeError(f'{self.ID} was initialized without a suspended growth model.')\n else:\n isa = isinstance\n inf = self.ins[0]\n Q_in = inf.get_total_flow('m3/d')\n eff, sludge = self.outs\n eff.copy_like(inf)\n sludge.copy_like(inf)\n C_in = inf.mass / inf.F_vol * 1e3 # concentrations in g/m3\n cmps = self.components\n C = list(symbols(cmps.IDs))\n if self._init_Vas is not None:\n V_0 = self._init_Vas\n C_0 = self._init_Cas\n else:\n V_0 = 0\n C_0 = C_in\n n = self._N_layer\n if self._aeration.count(None) == len(self._aeration):\n Vmax = self._V\n hj = self._h/n\n else:\n Vmax = self._V*0.75\n hj = self._h*0.75/n\n\n # ********fill and mix/aerate stages***********\n T_fill = (Vmax - V_0)/Q_in # maximum total fill time in day\n T = [t/24 for t in self._operation_cycle] # operation cycle in day\n if T_fill <= T[0]:\n schedule = [T_fill, T[0]-T_fill] + T[1:4]\n aer = [self._aeration[0], self._aeration[0]] + list(self._aeration[1:4])\n fill = [True] + [False]*4\n V_total = Vmax\n elif T_fill <= T[0]+T[1]:\n schedule = [T[0], T_fill-T[0], T[0]+T[1]-T_fill] + T[2:4]\n aer = list(self._aeration[:2]) + [self._aeration[1]] + list(self._aeration[2:4])\n fill = [True]*2 + [False]*3\n V_total = Vmax\n else:\n schedule = T[:4]\n aer = list(self._aeration[:4])\n fill = [True]*2 + [False]*2\n V_total = Q_in*(T[0]+T[1])+V_0\n hj = V_total/self._V*self._h/n\n\n for i in range(1, len(schedule)):\n if fill[-i] == fill[-i-1] and aer[-i] == aer[-i-1]:\n schedule[-i-1] += schedule[-i]\n schedule[-i] = 0\n\n t_arr = np.array([])\n y_mat = np.ndarray([])\n for i in range(len(schedule)):\n if schedule[i] > 0:\n dC_dt, J_func = self._compile_dC_dt(V_0, Q_in, C_in, C, fill[i], aer[i])\n if isa(aer[i], (float, int)): C_0[cmps.index(self._DO_ID)] = aer[i]\n sol = solve_ivp(dC_dt, (0, schedule[i]), C_0, method='BDF', jac=J_func)\n C_0 = sol.y.transpose()[-1]\n V_0 += Q_in * schedule[i] * fill[i]\n t_arr = np.concatenate((t_arr, sol.t + t_arr[-1]))\n y_mat = np.hstack((y_mat, sol.y))\n self._dynamic_composition = np.vstack((t_arr, y_mat)).transpose()\n\n # *********settle, decant, desludge**********\n eff.set_flow(C_0*eff.F_vol, 'g/hr', self.components.IDs)\n X_0 = eff.get_TSS()\n X_min = X_0 * self._fns\n T_settle = T[4]\n def dX_dt(t, X):\n VX = [_settling_flux(x, self._v_max, self._v_max_p, X_min, self._rh, self._rp) for x in X]\n J = [VX[j] if X[j+1] <= self._X_t else min(VX[j], VX[j+1]) for j in range(n-1)]\n settle_out = np.array(J + [0])\n settle_in = np.array([0] + J)\n dXdt = (settle_in - settle_out)/hj\n return dXdt\n sol = solve_ivp(dX_dt, (0, T_settle), np.ones(n)*X_0)\n X = sol.y.transpose()[-1]\n\n V_eff = min(T[5]*self._Q_e, V_total*(n-1)/n)\n n_eff = V_eff/V_total\n w_eff = np.array([1]*floor(n_eff)+[n_eff-floor(n_eff)])\n X_eff = np.average(X[:ceil(n_eff)], weights=w_eff)\n eff_mass_flow = (X_eff/X_0*cmps.x + (1-cmps.x))*C_0*V_eff/T[5]\n eff.set_flow(eff_mass_flow, 'g/d', cmps.IDs)\n\n V_was = min(T[6]*self._Q_WAS, V_total-V_eff)\n X_as = (V_total*X_0 - V_eff*X_eff) / (V_total-V_eff)\n C_as = (X_as/X_0*cmps.x + (1-cmps.x))*C_0\n was_mass_flow = C_as*V_was/T[6]\n sludge.set_flow(was_mass_flow, 'g/d', cmps.IDs)\n\n if self._cache_state:\n self._init_Vas = V_total - V_eff - V_was\n self._init_Cas = C_as\n\n\n def _design(self):\n pass\n\n def _compile_dC_dt(self, V0, Qin, Cin, C, fill, aer):\n isa = isinstance\n processes = _add_aeration_to_growth_model(aer, self._model)\n if fill:\n t = symbols('t')\n mass_balance_terms = list(zip(Cin, C, processes.production_rates.rate_of_production))\n C_dot_eqs = [(cin-c)/(t+V0/Qin) + r for cin, c, r in mass_balance_terms]\n if isa(aer, (float, int)): C_dot_eqs[self.components.index(self._DO_ID)] = 0\n def dC_dt(t, y):\n C_dot = lambdify([t]+C, C_dot_eqs)\n return C_dot(t, *y)\n J = Matrix(dC_dt(t, C)).jacobian(C)\n else:\n C_dot_eqs = processes.production_rates.rate_of_production\n if isa(aer, (float, int)): C_dot_eqs[self.components.index(self._DO_ID)] = 0\n def dC_dt(t, y):\n C_dot = lambdify(C, C_dot_eqs)\n return C_dot(*y)\n J = Matrix(dC_dt(None, C)).jacobian(C)\n def J_func(t, y):\n J_func = lambdify(C, J)\n return J_func(*y)\n return (dC_dt, J_func)\n\n# class PFR(SanUnit):\n\n# _N_ins = 1\n# _N_outs = 2\n\n# def __init__(self, ID='', ins=None, outs=(), **kwargs):\n# SanUnit.__init__(self, ID, ins, outs)\n\n# def _run(self, steady_state=True):\n# pass\n\n# def _design(self):\n# pass", "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\nQSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems\n\nThis module is developed by:\n Yalin Li <[email protected]>\n\nThis module is under the University of Illinois/NCSA Open Source License.\nPlease refer to https://github.com/QSD-Group/QSDsan/blob/main/LICENSE.txt\nfor license details.\n'''\n\n\n# %%\n\nimport sys\nimport numpy as np\nimport pandas as pd\nfrom math import ceil\nfrom collections.abc import Iterable\nfrom warnings import warn\nfrom . import ImpactIndicator, ImpactItem, Stream, SanStream, SanUnit\nfrom .utils import (\n auom,\n format_number as f_num\n )\n\n__all__ = ('LCA',)\n\n\nclass LCA:\n '''\n For life cycle assessment (LCA) of a System.\n\n Parameters\n ----------\n system : :class:`biosteam.System`\n System for which this LCA is conducted for.\n lifetime : int\n Lifetime of the LCA.\n lifetime_unit : str\n Unit of lifetime.\n indicators : Iterable(obj)\n `ImpactIndicator` objects or their IDs/aliases.\n uptime_ratio : float\n Fraction of time that the system is operating.\n annualize_construction : bool\n Used in the case that the lifetime of this LCA (e.g., 10 years)\n is not divisible by the lifetime of certain equipment (e.g., 8 years).\n If True, then the impacts from construction will be annualized using\n the lifetime of the equipment;\n if False, then the total number of the equipment needed throughout this\n LCA will be calculated using `ceil(LCA lifetime/equipment lifetime`.\n item_quantities : kwargs, :class:`ImpactItem` or str = float/callable or (float/callable, unit)\n Other :class:`ImpactItem` objects (e.g., electricity) and their quantities.\n Note that callable functions are used so that quantity of items can be updated.\n\n\n Examples\n --------\n A system should be constructed prior to LCA, here we import a pre-constructed one.\n\n >>> import qsdsan as qs\n >>> from qsdsan.utils import load_example_cmps, load_example_sys\n >>> cmps = load_example_cmps()\n >>> sys = load_example_sys(cmps)\n >>> sys.diagram() # doctest: +SKIP\n >>> sys.simulate()\n >>> sys.show()\n System: sys\n ins...\n [0] salt_water\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (kmol/hr): H2O 111\n NaCl 0.856\n [1] methanol\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (kmol/hr): Methanol 0.624\n [2] ethanol\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (kmol/hr): Ethanol 0.217\n outs...\n [0] alcohols\n phase: 'l', T: 298.15 K, P: 101325 Pa\n flow (kmol/hr): Methanol 0.624\n Ethanol 0.217\n [1] waste_brine\n phase: 'l', T: 350 K, P: 101325 Pa\n flow (kmol/hr): H2O 88.8\n NaCl 0.684\n\n And we also need to specify the impact indicators that we are interested in.\n\n >>> GWP = qs.ImpactIndicator('GlobalWarming', alias='GWP', unit='kg CO2-eq')\n >>> FEC = qs.ImpactIndicator('FossilEnergyConsumption', alias='FEC', unit='MJ')\n\n There are four different types of impacts in `QSDsan`:\n construction, transportation, stream, and others.\n\n Note that it is best to add the impact items when developing the unit module,\n (i.e., typically in the `_design` function, but can also in `_run` or `_cost`)\n but for illustrative purpose, we add it after the system is constructed.\n\n Construction is mainly used for impacts that only occur once per lifetime\n of the equipment or the unit.\n\n For example, assume we want to consider the amount of stainless steel\n and concrete used in constructing the MixTank M1.\n\n >>> # Make the impact item, numbers are made up\n >>> SS = qs.ImpactItem('SS', functional_unit='kg', GWP=3, FEC=50)\n >>> Concrete = qs.ImpactItem('Concrete', functional_unit='kg', GWP=4, FEC=30)\n >>> # Specify the amount of stainless steel and concrete used in the unit\n >>> SS_constr_M1 = qs.Construction(item=SS, quantity=100)\n >>> Concrete_constr_M1 = qs.Construction(item=Concrete, quantity=50)\n >>> # Retrieve the unit from the registry\n >>> flowsheet = qs.Flowsheet.flowsheet.default\n >>> M1 = flowsheet.unit.M1\n >>> # Add the construction activity\n >>> M1.construction = (SS_constr_M1, Concrete_constr_M1)\n\n Transportation activity can be added in a similar manner, assuming that\n stainless steel and concrete are delivered by truck from 500 km away.\n\n The interval set below is assuming a system lifetime of 10 year\n and this delivery is only needed once for the entire lifetime.\n\n >>> lifetime = 10\n >>> Trucking = qs.ImpactItem('Trucking', functional_unit='kg*km',\n ... GWP=0.5, FEC=1.5)\n >>> total_quantity = SS_constr_M1.quantity + Concrete_constr_M1.quantity\n >>> Trans_M1 = qs.Transportation(item=Trucking, load_type='mass',\n ... load=total_quantity, distance=500,\n ... interval=lifetime, interval_unit='yr')\n >>> M1.transportation = Trans_M1\n\n We can als consider the impacts associated with chemicals and emissions.\n For example, assume the acquisition of methanol, ethanol and disposal of\n the waste brine all have impacts, but the generated alcohols can be treated\n as a product therefore have credits with\n\n >>> # Retrieve streams\n >>> methanol = flowsheet.stream.methanol\n >>> ethanol = flowsheet.stream.ethanol\n >>> alcohols = flowsheet.stream.alcohols\n >>> waste_brine = flowsheet.stream.waste_brine\n >>> # Create `StreamImpactItem` and link to the streams\n >>> methanol_item = qs.StreamImpactItem(linked_stream=methanol, GWP=2, FEC=13)\n >>> ethanol_item = qs.StreamImpactItem(linked_stream=ethanol, GWP=2.1, FEC=25)\n >>> alcohols_item = qs.StreamImpactItem(linked_stream=alcohols, GWP=-0.2, FEC=-5)\n >>> brine_item = qs.StreamImpactItem(linked_stream=waste_brine, GWP=2, FEC=3)\n\n Finally, there might be other impacts we want to include in the LCA,\n for example, the electricity needed to operate the system.\n\n We can use add those additional items when creating the `LCA` object.\n\n >>> # Get the electricity usage of the system throughout the lifetime,\n >>> # note that the default power utility unit is hr\n >>> total_power = sys.power_utility.rate*24*365*lifetime\n >>> # Create an impact item for the electricity\n >>> e_item = qs.ImpactItem('e_item', 'kWh', GWP=1.1, FEC=24)\n >>> # Create the LCA object\n >>> lca = qs.LCA(system=sys, lifetime=10, e_item=total_power)\n\n Now we can look at the total impacts associate with this system.\n\n >>> lca.show() # doctest: +ELLIPSIS\n LCA: sys (lifetime 10 yr)\n ...\n >>> # Retrieve impacts associated with a specific indicator\n >>> lca.get_total_impacts()[GWP.ID] # doctest: +ELLIPSIS\n 349737807.9765445...\n >>> # Or breakdowns of the different category\n >>> lca.get_impact_table('Construction') # doctest: +SKIP\n >>> # Below is for testing purpose, you do not need it\n >>> lca.get_impact_table('Construction').to_dict() # doctest: +ELLIPSIS\n {'Quantity': ...\n >>> lca.get_impact_table('Transportation').to_dict() # doctest: +ELLIPSIS\n {'Quantity': ...\n >>> lca.get_impact_table('Stream').to_dict() # doctest: +ELLIPSIS\n {'Mass [kg]': ...\n >>> lca.get_impact_table('Construction').to_dict() # doctest: +ELLIPSIS\n {'Quantity': ...\n\n You can also allocate the impact based on mass, energy, value, or a ratio you like\n\n >>> lca.get_allocated_impacts(sys.products, allocate_by='mass')['waste_brine']['FossilEnergyConsumption'] # doctest: +ELLIPSIS\n 46018518.870...\n >>> lca.get_allocated_impacts(sys.products, allocate_by='energy')['alcohols']['GlobalWarming'] # doctest: +ELLIPSIS\n 11063009.556...\n >>> alcohols.price = 5\n >>> waste_brine.price = 1\n >>> GWP_alcohols = lca.get_allocated_impacts(sys.products, allocate_by='value')['alcohols']['GlobalWarming']\n >>> GWP_brine = lca.get_allocated_impacts(sys.products, allocate_by='value')['waste_brine']['GlobalWarming']\n >>> GWP_alcohols + GWP_brine # doctest: +ELLIPSIS\n 5469807.9765...\n >>> lca.get_total_impacts(exclude=sys.products)['GlobalWarming'] # doctest: +ELLIPSIS\n 5469807.9765...\n\n See Also\n --------\n `SanUnit and System <https://qsdsan.readthedocs.io/en/latest/tutorials/SanUnit_and_System.html>`_\n\n `TEA and LCA <https://qsdsan.readthedocs.io/en/latest/tutorials/TEA_and_LCA.html>`_\n '''\n\n __slots__ = ('_system', '_lifetime', '_uptime_ratio',\n '_construction_units', '_transportation_units',\n '_lca_streams', '_indicators',\n '_other_items', '_other_items_f', 'annualize_construction')\n\n\n def __init__(self, system, lifetime, lifetime_unit='yr',\n indicators=(), uptime_ratio=1, annualize_construction=False,\n **item_quantities):\n system.simulate()\n self._construction_units = set()\n self._transportation_units = set()\n self._lca_streams = set()\n self._update_system(system)\n self._update_lifetime(lifetime, lifetime_unit)\n self.indicators = indicators\n self.uptime_ratio = uptime_ratio\n self.annualize_construction = annualize_construction\n self._other_items = {}\n self._other_items_f = {}\n for item, val in item_quantities.items():\n try:\n f_quantity, unit = val # unit provided for the quantity\n except Exception as e:\n if 'unpack' in str(sys.exc_info()[1]):\n f_quantity = val\n unit = ''\n else:\n raise e\n self.add_other_item(item, f_quantity, unit)\n\n\n def _update_system(self, system):\n for u in system.units:\n if not isinstance (u, SanUnit):\n continue\n if u.construction:\n self._construction_units.add(u)\n if u.transportation:\n self._transportation_units.add(u)\n self._construction_units = sorted(self._construction_units,\n key=lambda u: u.ID)\n self._transportation_units = sorted(self._transportation_units,\n key=lambda u: u.ID)\n for s in (i for i in system.feeds+system.products):\n if not hasattr(s, 'stream_impact_item'):\n continue\n if s.stream_impact_item:\n self._lca_streams.add(s)\n self._lca_streams = sorted(self._lca_streams, key=lambda s: s.ID)\n self._system = system\n try: # for older versions of biosteam without the `_LCA` attribute\n system._LCA = self\n except AttributeError:\n pass\n\n\n def _update_lifetime(self, lifetime=0., unit='yr'):\n if not unit or unit == 'yr':\n self._lifetime = int(lifetime)\n else:\n converted = auom(unit).convert(int(lifetime), 'yr')\n self._lifetime = converted\n\n\n def add_other_item(self, item, f_quantity, unit=''):\n '''Add other :class:`ImpactItem` in LCA.'''\n if isinstance(item, str):\n item = ImpactItem.get_item(item)\n fu = item.functional_unit\n if not callable(f_quantity):\n f = lambda: f_quantity\n else:\n f = f_quantity\n quantity = f()\n if unit and unit != fu:\n try:\n quantity = auom(unit).convert(quantity, fu)\n except:\n raise ValueError(f'Conversion of the given unit {unit} to '\n f'item functional unit {fu} is not supported.')\n self._other_items_f[item.ID] = {'item':item, 'f_quantity':f, 'unit':unit}\n self.other_items[item.ID] = {'item':item, 'quantity':quantity}\n\n\n def refresh_other_items(self):\n '''Refresh quantities of other items using the given functions.'''\n for item_ID, record in self._other_items_f.items():\n item, f_quantity, unit = record.values()\n self.other_items[item_ID]['quantity'] = f_quantity()\n\n\n def __repr__(self):\n return f'<LCA: {self.system}>'\n\n def show(self, lifetime_unit='yr'):\n '''Show basic information of this :class:`LCA` object.'''\n lifetime = auom('yr').convert(self.lifetime, lifetime_unit)\n info = f'LCA: {self.system} (lifetime {f_num(lifetime)} {lifetime_unit})'\n info += '\\nImpacts:'\n print(info)\n if len(self.indicators) == 0:\n print(' None')\n else:\n index = pd.Index((i.ID+' ('+i.unit+')' for i in self.indicators))\n df = pd.DataFrame({\n 'Construction': tuple(self.total_construction_impacts.values()),\n 'Transportation': tuple(self.total_transportation_impacts.values()),\n 'Stream': tuple(self.total_stream_impacts.values()),\n 'Others': tuple(self.total_other_impacts.values()),\n 'Total': tuple(self.total_impacts.values())\n },\n index=index)\n # print(' '*9+df.to_string().replace('\\n', '\\n'+' '*9))\n print(df.to_string())\n\n _ipython_display_ = show\n\n\n def get_construction_impacts(self, units=None, time=None, time_unit='hr'):\n '''\n Return all construction-related impacts for the given unit,\n normalized to a certain time frame.\n '''\n units = self.construction_units if units is None else units\n annualize = self.annualize_construction\n if not isinstance(units, Iterable) or isinstance(units, str):\n units = (units,)\n if time is None:\n time = self.lifetime_hr\n else:\n time = auom(time_unit).convert(float(time), 'hr')\n impacts = dict.fromkeys((i.ID for i in self.indicators), 0.)\n for i in units:\n if not isinstance(i, SanUnit):\n continue\n for j in i.construction:\n impact = j.impacts\n if j.lifetime is not None: # this equipment has a lifetime\n constr_lifetime = auom('yr').convert(j.lifetime, 'hr')\n ratio = ceil(time/constr_lifetime) if not annualize else time/constr_lifetime\n else: # equipment doesn't have a lifetime\n if i.lifetime and not isinstance(i.lifetime, dict): # unit has a uniform lifetime\n constr_lifetime = auom('yr').convert(i.lifetime, 'hr')\n ratio = ceil(time/constr_lifetime) if not annualize else time/constr_lifetime\n else: # no lifetime, assume just need one\n ratio = 1.\n for m, n in impact.items():\n if m not in impacts.keys():\n continue\n impacts[m] += n*ratio\n return impacts\n\n def get_transportation_impacts(self, units=None, time=None, time_unit='hr'):\n '''\n Return all transportation-related impacts for the given unit,\n normalized to a certain time frame.\n '''\n units = self.transportation_units if units is None else units\n if not isinstance(units, Iterable):\n units = (units,)\n if not time:\n time = self.lifetime_hr\n else:\n time = auom(time_unit).convert(float(time), 'hr')\n impacts = dict.fromkeys((i.ID for i in self.indicators), 0.)\n for i in units:\n if not isinstance(i, SanUnit):\n continue\n for j in i.transportation:\n impact = j.impacts\n for m, n in impact.items():\n if m not in impacts.keys():\n continue\n impacts[m] += n*time/j.interval\n return impacts\n\n\n def get_stream_impacts(self, stream_items=None, exclude=None,\n kind='all', time=None, time_unit='hr'):\n '''\n Return all stream-related impacts for the given streams,\n normalized to a certain time frame.\n '''\n isa = isinstance\n if stream_items == None:\n stream_items = self.stream_inventory\n if not isa(stream_items, Iterable):\n stream_items = (stream_items,)\n if not isa(exclude, Iterable):\n exclude = (exclude,)\n impacts = dict.fromkeys((i.ID for i in self.indicators), 0.)\n if not time:\n time = self.lifetime_hr\n else:\n time = auom(time_unit).convert(float(time), 'hr')\n for j in stream_items:\n # In case that ws instead of the item is given\n if isa(j, Stream):\n if not isa(j, SanStream):\n continue\n ws = j\n if j.stream_impact_item:\n j = ws.stream_impact_item\n else: continue\n else:\n ws = j.linked_stream\n\n if ws in exclude: continue\n\n for m, n in j.CFs.items():\n if kind in ('all', 'total', 'net'):\n pass\n elif kind in ('direct', 'direct_emission'):\n n = max(n, 0)\n elif kind == 'offset':\n n = min(n, 0)\n else:\n raise ValueError('kind can only be \"all\", \"direct_emission\", or \"offset\", '\n f'not \"{kind}\".')\n if m not in impacts.keys():\n continue\n impacts[m] += n*time*ws.F_mass\n return impacts\n\n def get_other_impacts(self, time=None, time_unit='hr'):\n '''\n Return all additional impacts from \"other\" :class:`ImpactItems` objects,\n based on defined quantity.\n '''\n self.refresh_other_items()\n impacts = dict.fromkeys((i.ID for i in self.indicators), 0.)\n other_dct = self.other_items\n if not time:\n time = self.lifetime_hr\n else:\n time = auom(time_unit).convert(float(time), 'hr')\n factor = time / self.lifetime_hr\n for i in other_dct.keys():\n item = ImpactItem.get_item(i)\n for m, n in item.CFs.items():\n if m not in impacts.keys():\n continue\n impacts[m] += n*other_dct[i]['quantity']*factor\n return impacts\n\n def get_total_impacts(self, exclude=None, time=None, time_unit='hr'):\n '''Return total impacts, normalized to a certain time frame.'''\n impacts = dict.fromkeys((i.ID for i in self.indicators), 0.)\n constr = self.get_construction_impacts(self.construction_units, time=time, time_unit=time_unit)\n trans = self.get_transportation_impacts(self.transportation_units, time=time, time_unit=time_unit)\n ws_impacts = self.get_stream_impacts(stream_items=self.stream_inventory,\n exclude=exclude, time=time, time_unit=time_unit)\n other = self.get_other_impacts(time=time, time_unit=time_unit)\n\n for i in (constr, trans, ws_impacts, other):\n for m, n in i.items():\n if m not in impacts.keys():\n continue\n impacts[m] += n\n return impacts\n\n def get_allocated_impacts(self, streams=(), allocate_by='mass'):\n '''\n Allocate total impacts to one or multiple streams.\n\n Note that original impacts assigned to the streams will be excluded,\n i.e., the total impact for allocation will be calculated using\n `LCA.get_total_impacts(exclude=streams)`.\n\n Parameters\n ----------\n streams : Iterable(obj)\n One or a Iterable of streams. Note that impacts of these streams will be\n excluded in calculating the total impacts.\n allocate_by : str, Iterable, or function to generate an Iterable\n If provided as a str, can be \"mass\" (`F_mass`), \"energy\" (`HHV`),\n or 'value' (`F_mass`*`price`) to allocate the impacts accordingly.\n If provided as an Iterable (no need to normalize so that sum of the Iterable is 1),\n will allocate impacts according to the Iterable.\n If provided as a function, will call the function to generate an\n Iterable to allocate the impacts accordingly.\n\n .. note::\n\n Energy of the stream will be calculated as the sum of HHVs of all components\n in the stream.\n\n '''\n if not isinstance(streams, Iterable):\n streams = (streams,)\n impact_dct = self.get_total_impacts(exclude=streams)\n impact_vals = np.array([i for i in impact_dct.values()])\n allocated = {}\n if len(streams) == 1:\n if not isinstance(streams[0], SanStream):\n return None\n return impact_dct\n if allocate_by == 'mass':\n ratios = np.array([i.F_mass for i in streams])\n elif allocate_by == 'energy':\n ratios = np.array([i.HHV for i in streams])\n elif allocate_by == 'value':\n ratios = np.array([i.F_mass*i.price for i in streams])\n elif iter(allocate_by):\n ratios = allocate_by\n elif callable(allocate_by):\n ratios = allocate_by()\n else:\n raise ValueError('allocate_by can only be \"mass\", \"energy\", \"value\", '\n 'an Iterable (with the same length as `streams`), '\n 'or a function to generate an Iterable.')\n if ratios.sum() == 0:\n raise ValueError('Calculated allocation ratios are all zero, cannot allocate.')\n ratios = ratios/ratios.sum()\n for n, s in enumerate(streams):\n if not isinstance(s, SanStream):\n continue\n if not s in self.system.streams:\n raise ValueError(f'`WasteStream` {s} not in the system.')\n allocated[s.ID] = dict(zip(impact_dct.keys(), ratios[n]*impact_vals))\n return allocated\n\n\n def get_unit_impacts(self, units, time=None, time_unit='hr',\n exclude=None):\n '''Return total impacts with certain units, normalized to a certain time frame. '''\n if not isinstance(units, Iterable):\n units = (units,)\n constr = self.get_construction_impacts(units, time, time_unit)\n trans = self.get_transportation_impacts(units, time, time_unit)\n stream_items = set(i for i in\n sum((tuple(unit.ins+unit.outs) for unit in units), ())\n if i.impact_item)\n\n s = self.get_stream_impacts(stream_items=stream_items, exclude=exclude,\n time=time, time_unit=time_unit)\n other = self.get_other_impacts()\n tot = constr.copy()\n for m in tot.keys():\n tot[m] += trans[m] + s[m] + other[m]\n return tot\n\n def _append_cat_sum(self, cat_table, cat, tot):\n num = len(cat_table)\n cat_table.loc[num] = '' # initiate a blank spot for value to be added later\n\n for i in self.indicators:\n cat_table[f'{i.ID} [{i.unit}]'][num] = tot[i.ID]\n cat_table[f'Category {i.ID} Ratio'][num] = 1\n\n if cat in ('construction', 'transportation'):\n cat_table.rename(index={num: ('Sum', 'All')}, inplace=True)\n cat_table.index = \\\n pd.MultiIndex.from_tuples(cat_table.index,\n names=[cat.capitalize(), 'SanUnit'])\n else:\n cat_table.rename(index={num: 'Sum'}, inplace=True)\n\n return cat_table\n\n def get_impact_table(self, category, time=None, time_unit='hr'):\n '''\n Return a :class:`pandas.DataFrame` table for the given impact category,\n normalized to a certain time frame.\n '''\n if not time:\n time = self.lifetime_hr\n else:\n time = auom(time_unit).convert(float(time), 'hr')\n\n cat = category.lower()\n tot_f = getattr(self, f'get_{cat}_impacts')\n kwargs = {'time': time, 'time_unit': time_unit} if cat != 'other' else {}\n tot = tot_f(**kwargs)\n time_ratio = time/self.lifetime_hr\n\n if cat in ('construction', 'transportation'):\n units = sorted(getattr(self, f'_{cat}_units'),\n key=(lambda su: su.ID))\n items = sorted(set(i.item for i in getattr(self, f'{cat}_inventory')),\n key=(lambda item: item.ID))\n if len(items) == 0:\n return f'No {cat}-related impacts.'\n\n # Note that item_dct = dict.fromkeys([item.ID for item in items], []) won't work\n item_dct = dict.fromkeys([item.ID for item in items])\n for item_ID in item_dct.keys():\n item_dct[item_ID] = dict(SanUnit=[], Quantity=[])\n for su in units:\n if not isinstance(su, SanUnit):\n continue\n for i in getattr(su, cat):\n item_dct[i.item.ID]['SanUnit'].append(su.ID)\n if cat == 'transportation':\n item_dct[i.item.ID]['Quantity'].append(i.quantity*time/i.interval)\n else: # construction\n lifetime = i.lifetime or su.lifetime or self.lifetime\n if isinstance(lifetime, dict): # in the case the the equipment is not in the unit lifetime dict\n lifetime = lifetime.get(i.item.ID) or self.lifetime\n constr_ratio = self.lifetime/lifetime if self.annualize_construction else ceil(self.lifetime/lifetime)\n item_dct[i.item.ID]['Quantity'].append(i.quantity*constr_ratio)\n\n dfs = []\n for item in items:\n dct = item_dct[item.ID]\n dct['SanUnit'].append('Total')\n dct['Quantity'] = np.append(dct['Quantity'], sum(dct['Quantity']))\n dct['Item Ratio'] = dct['Quantity']/dct['Quantity'].sum()*2\n for i in self.indicators:\n if i.ID in item.CFs:\n dct[f'{i.ID} [{i.unit}]'] = impact = dct['Quantity']*item.CFs[i.ID]\n dct[f'Category {i.ID} Ratio'] = impact/(tot[i.ID]*time_ratio)\n else:\n dct[f'{i.ID} [{i.unit}]'] = dct[f'Category {i.ID} Ratio'] = 0\n df = pd.DataFrame.from_dict(dct)\n index0 = f'{item.ID} [{item.functional_unit}]'\n df.set_index([pd.MultiIndex.from_arrays(\n [(index0,)*len(dct['SanUnit'])], names=(category,)),\n 'SanUnit'],\n inplace=True)\n dfs.append(df)\n\n table = pd.concat(dfs)\n return self._append_cat_sum(table, cat, tot)\n\n ind_head = sum(([f'{i.ID} [{i.unit}]',\n f'Category {i.ID} Ratio'] for i in self.indicators), [])\n\n if cat in ('stream', 'streams'):\n headings = ['Stream', 'Mass [kg]', *ind_head]\n item_dct = dict.fromkeys(headings)\n for key in item_dct.keys():\n item_dct[key] = []\n for ws_item in self.stream_inventory:\n ws = ws_item.linked_stream\n item_dct['Stream'].append(ws.ID)\n mass = ws.F_mass * time\n item_dct['Mass [kg]'].append(mass)\n for ind in self.indicators:\n if ind.ID in ws_item.CFs.keys():\n impact = ws_item.CFs[ind.ID]*mass\n item_dct[f'{ind.ID} [{ind.unit}]'].append(impact)\n item_dct[f'Category {ind.ID} Ratio'].append(impact/(tot[ind.ID]*time_ratio))\n else:\n item_dct[f'{ind.ID} [{ind.unit}]'].append(0)\n item_dct[f'Category {ind.ID} Ratio'].append(0)\n table = pd.DataFrame.from_dict(item_dct)\n table.set_index(['Stream'], inplace=True)\n return self._append_cat_sum(table, cat, tot)\n\n elif cat == 'other':\n headings = ['Other', 'Quantity', *ind_head]\n item_dct = dict.fromkeys(headings)\n for key in item_dct.keys():\n item_dct[key] = []\n for other_ID in self.other_items.keys():\n other = self.other_items[other_ID]['item']\n item_dct['Other'].append(f'{other_ID} [{other.functional_unit}]')\n quantity = self.other_items[other_ID]['quantity'] * time_ratio\n item_dct['Quantity'].append(quantity)\n for ind in self.indicators:\n if ind.ID in other.CFs.keys():\n impact = other.CFs[ind.ID]*quantity\n item_dct[f'{ind.ID} [{ind.unit}]'].append(impact)\n item_dct[f'Category {ind.ID} Ratio'].append(impact/(tot[ind.ID]*time_ratio))\n else:\n item_dct[f'{ind.ID} [{ind.unit}]'].append(0)\n item_dct[f'Category {ind.ID} Ratio'].append(0)\n\n table = pd.DataFrame.from_dict(item_dct)\n table.set_index(['Other'], inplace=True)\n return self._append_cat_sum(table, cat, tot)\n\n raise ValueError(\n 'category can only be \"Construction\", \"Transportation\", \"Stream\", or \"Other\", ' \\\n f'not \"{category}\".')\n\n\n def save_report(self, file=None, sheet_name='LCA',\n time=None, time_unit='hr',\n n_row=0, row_space=2):\n '''Save all LCA tables as an Excel file.'''\n if not file:\n file = f'{self.system.ID}_lca.xlsx'\n tables = [self.get_impact_table(cat, time, time_unit)\n for cat in ('Construction', 'Transportation',\n 'Stream', 'Other')]\n with pd.ExcelWriter(file) as writer:\n for table in tables:\n table.to_excel(writer, sheet_name=sheet_name, startrow=n_row)\n n_row += table.shape[0] + row_space + len(table.columns.names) # extra lines for the heading\n\n\n @property\n def system(self):\n '''[biosteam.System] The system linked to this LCA.'''\n return self._system\n @system.setter\n def system(self, i):\n self._update_system(i)\n\n @property\n def lifetime(self):\n '''[int] Lifetime of the system, [yr].'''\n return self._lifetime\n @lifetime.setter\n def lifetime(self, lifetime, unit='yr'):\n self._update_lifetime(lifetime, unit)\n\n @property\n def lifetime_hr(self):\n '''[float] Lifetime of the system in hours, [hr].'''\n return self._lifetime*365*24*self.uptime_ratio\n\n @property\n def uptime_ratio(self):\n '''[float] Fraction of time that the system is operating.'''\n return self._uptime_ratio\n @uptime_ratio.setter\n def uptime_ratio(self, i):\n if 0 <=i<= 1:\n self._uptime_ratio = float(i)\n else:\n raise ValueError('uptime_ratio must be in [0,1].')\n\n @property\n def indicators(self):\n '''\n [list] All impact indicators associated with this LCA object.\n If not `ImpactIndicator` has been added, then will be defaulted to\n sum of the `ImpactIndicator` objects added to the system associated\n with this LCA (e.g., associated with construction, streams, etc.\n\n '''\n if self._indicators:\n return self._indicators\n\n if not self.construction_inventory:\n constr = set()\n else:\n constr = set(sum((i.indicators for i in self.construction_inventory\n if i is not None), ()))\n if not self.transportation_inventory:\n trans = set()\n else:\n trans = set(sum((i.indicators for i in self.transportation_inventory\n if i is not None), ()))\n if not self.stream_inventory:\n ws = set()\n else:\n ws = set(sum((i.indicators for i in self.stream_inventory\n if i is not None), ()))\n if not self.other_items:\n other = set()\n else:\n other = set(sum((ImpactItem.get_item(i).indicators\n for i in self.other_items.keys()), ()))\n tot = constr.union(trans, ws, other)\n if len(tot) == 0:\n warn('No `ImpactIndicator` has been added.')\n return list(tot)\n @indicators.setter\n def indicators(self, i):\n if not (isinstance(i, Iterable) and not isinstance(i, str)):\n i = (i,)\n inds = []\n for ind in i:\n if isinstance(ind, str):\n ind = ImpactIndicator.get_indicator(ind)\n if not isinstance(ind, ImpactIndicator):\n raise TypeError(f'{ind} is not an `ImpactIndicator` or ID/alias of an `ImpactIndicator`.')\n inds.append(ind)\n self._indicators = inds\n\n @property\n def construction_units(self):\n '''[set] All units in the linked system with construction activity.'''\n return self._construction_units\n\n @property\n def construction_inventory(self):\n '''[tuple] All construction activities.'''\n return sum((i.construction for i in self.construction_units), ())\n\n @property\n def total_construction_impacts(self):\n '''[dict] Total impacts associated with construction activities.'''\n return self.get_construction_impacts(self.construction_units)\n\n @property\n def transportation_units(self):\n '''[set] All units in the linked system with transportation activity.'''\n return self._transportation_units\n\n @property\n def transportation_inventory(self):\n '''[tuple] All transportation activities.'''\n return sum((i.transportation for i in self.transportation_units), ())\n\n @property\n def total_transportation_impacts(self):\n '''[dict] Total impacts associated with transportation activities.'''\n return self.get_transportation_impacts(self.transportation_units)\n\n @property\n def lca_streams(self):\n '''[set] All streams in the linked system with impacts.'''\n return self._lca_streams\n\n @property\n def stream_inventory(self):\n '''[tuple] All chemical inputs, fugitive gases, waste emissions, and products.'''\n return tuple(i.stream_impact_item for i in self.lca_streams)\n\n @property\n def total_stream_impacts(self):\n '''[dict] Total impacts associated with `WasteStreams` (e.g., chemicals, emissions).'''\n return self.get_stream_impacts(stream_items=self.stream_inventory)\n\n @property\n def other_items (self):\n '''[dict] Other impact items (e.g., electricity) and their quantities.'''\n return self._other_items\n @other_items.setter\n def other_items(self, item, f_quantity, unit=''):\n self.add_other_item(item, f_quantity, unit)\n\n @property\n def total_other_impacts(self):\n '''[dict] Total impacts associated with other ImpactItems (e.g., electricity).'''\n return self.get_other_impacts()\n\n @property\n def total_impacts(self):\n '''[dict] Total impacts of the entire system (construction, transportation, and wastestream).'''\n return self.get_total_impacts()", "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n'''\nQSDsan: Quantitative Sustainable Design for sanitation and resource recovery systems\n\nThis module is developed by:\n Yalin Li <[email protected]>\n\nThis module is under the University of Illinois/NCSA Open Source License.\nPlease refer to https://github.com/QSD-Group/QSDsan/blob/main/LICENSE.txt\nfor license details.\n'''\n\n\n# %%\n\nimport pandas as pd\nfrom thermosteam.utils import registered\nfrom . import currency, ImpactItem\nfrom .utils import (\n auom, copy_attr,\n format_number as f_num,\n register_with_prefix,\n )\n\n__all__ = ('Transportation',)\n\n\n@registered(ticket_name='Trans')\nclass Transportation:\n '''\n Transportation activity for cost and environmental impact calculations.\n\n Parameters\n ----------\n ID : str\n ID of this transportation activity,\n a default ID will be given if not provided.\n If this transportation activity is linked to a unit,\n then the actual ID will be {unit.ID}_{ID}.\n linked_unit : obj\n Unit that this transportation activity is linked to, can be left as None.\n item : :class:`ImpactItem`\n Impact item associated with this transportation activity.\n load_type : str\n Can be either 'mass' or 'volume'.\n load : float\n Quantity of the load per trip.\n load_unit : str\n Unit of the load.\n distance : float\n Distance per trip.\n distance_unit : str\n Unit of the distance.\n interval : float\n Distance per trip.\n interval_unit : str\n Unit of the transportation interval.\n\n Examples\n --------\n >>> import qsdsan as qs\n >>> # Make impact indicator\n >>> GWP = qs.ImpactIndicator('GlobalWarming', alias='GWP', unit='kg CO2-eq')\n >>> FEC = qs.ImpactIndicator('FossilEnergyConsumption', alias='FEC', unit='MJ')\n >>> # Assuming transporting 1 kg of goods for 1 km emits 10 kg CO2-eq\n >>> Trucking = qs.ImpactItem('Trucking', 'kg*km', GWP=10, FEC=5)\n >>> # Make a transportation activity for transporting 1000 kg goods for 1 mile every day\n >>> shipping = qs.Transportation('shipping', item=Trucking,\n ... load_type='mass', load=1, load_unit='tonne',\n ... distance='1', distance_unit='mile',\n ... interval='1', interval_unit='day')\n >>> shipping.show()\n Transportation: shipping\n Impact item : Trucking [per trip]\n Load : 1000 kg\n Distance : 1.61 km\n Interval : 24 hr\n Total cost : None USD\n Total impacts :\n Impacts\n GlobalWarming (kg CO2-eq) 1.61e+04\n FossilEnergyConsumption (MJ) 8.05e+03\n >>> # Registry management (transportation activities will be auto-registered)\n >>> shipping.deregister()\n The transportation activity \"shipping\" has been removed from the registry.\n >>> shipping.register()\n The transportation activity \"shipping\" has been added to the registry.\n >>> Transportation.clear_registry()\n All transportation activities have been removed from registry.\n '''\n\n __slots__ = ('_ID', '_linked_unit', '_item', '_load_type', '_load', '_distance', '_interval',\n 'default_units')\n\n def __init__(self, ID='', linked_unit=None, item=None,\n load_type='mass', load=1., load_unit='kg',\n distance=1., distance_unit='km',\n interval=1., interval_unit='hr'):\n self._linked_unit = linked_unit\n prefix = self.linked_unit.ID if self.linked_unit else ''\n register_with_prefix(self, prefix, ID)\n self.item = item\n self.default_units = {\n 'distance': 'km',\n 'interval': 'hr',\n }\n\n self._load_type = load_type\n if load_type == 'mass':\n self.default_units['load'] = 'kg'\n self.default_units['quantity'] = 'kg*km'\n elif load_type == 'volume':\n self.default_units['load'] = 'm3'\n self.default_units['quantity'] = 'm3*km'\n else:\n raise ValueError(\"load_type can only be 'mass' or 'volume', \"\n f'not {load_type}.')\n\n self._update_value('load', load, load_unit)\n self._update_value('distance', distance, distance_unit)\n self._update_value('interval', interval, interval_unit)\n\n if item:\n try:\n auom(str(load_unit)+'*'+str(distance_unit)).convert(1, self.item.functional_unit)\n except:\n raise ValueError(f'Units of `load` {load_unit} and `distance` {distance_unit} '\n f'do not match the item `functional_unit` {self.item.functional_unit}.')\n\n\n def _update_value(self, var, value, unit=''):\n default_unit = self.default_units[var]\n if not unit or unit == default_unit:\n setattr(self, '_'+var, value)\n else:\n converted = auom(unit).convert(float(value), default_unit)\n setattr(self, '_'+var, converted)\n\n def __repr__(self):\n return f'<Transportation: {self.ID}>'\n\n def show(self):\n item = self.item\n impacts = self.impacts\n du = self.default_units\n info = f'Transportation: {self.ID}'\n info += f'\\nImpact item : {item.ID} [per trip]'\n info += f\"\\nLoad : {f_num(self.load)} {du['load']}\"\n info += f\"\\nDistance : {f_num(self.distance)} {du['distance']}\"\n info += f\"\\nInterval : {f_num(self.interval)} {du['interval']}\"\n info += f'\\nTotal cost : {f_num(self.cost)} {currency}'\n info += '\\nTotal impacts :'\n print(info)\n if len(impacts) == 0:\n print(' None')\n else:\n index = pd.Index((i.ID+' ('+i.unit+')' for i in self.indicators))\n df = pd.DataFrame({\n 'Impacts': tuple(self.impacts.values())\n },\n index=index)\n # print(' '*16+df.to_string().replace('\\n', '\\n'+' '*16))\n print(df.to_string())\n\n _ipython_display_ = show # funny that `_ipython_display_` and `_ipython_display` behave differently\n\n def copy(self, new_ID='', skip_item=True, **kwargs):\n new = Transportation.__new__(Transportation)\n new.__init__(new_ID, **kwargs)\n if skip_item:\n new = copy_attr(new, self, skip=('_ID', '_item'))\n new.item = self.item\n else:\n new = copy_attr(new, self, skip=('_ID',))\n return new\n\n __copy__ = copy\n\n\n def register(self, print_msg=True):\n '''Add this transportation activity to the registry.'''\n self.registry.register_safely(self.ID, self)\n if print_msg:\n print(f'The transportation activity \"{self.ID}\" has been added to the registry.')\n\n def deregister(self, print_msg=True):\n '''Remove this transportation activity to the registry.'''\n self.registry.discard(self.ID)\n if print_msg:\n print(f'The transportation activity \"{self.ID}\" has been removed from the registry.')\n\n @classmethod\n def clear_registry(cls, print_msg=True):\n '''Remove all existing transportation activities from the registry.'''\n cls.registry.clear()\n if print_msg:\n print('All transportation activities have been removed from registry.')\n\n\n @property\n def linked_unit(self):\n '''\n :class:`~.SanUnit` The unit that this transportation activity belongs to.\n\n .. note::\n\n This property will be updated upon initialization of the unit.\n '''\n return self._linked_unit\n\n @property\n def item(self):\n '''[:class:`ImpactItem`] Item associated with this transportation activity.'''\n return self._item\n @item.setter\n def item(self, i):\n if not i:\n i = None\n elif isinstance(i, str):\n i = ImpactItem.get_item(i) or ImpactItem(i) # add a filler to enable simulation without LCA\n elif not isinstance(i, ImpactItem):\n raise TypeError('Only `ImpactItem` or the ID of `ImpactItem` can be set, '\n f'not {type(i).__name__}.')\n self._item = i\n\n @property\n def load_type(self):\n '''[str] Either \"mass\" or \"volume\".'''\n return self._load_type\n @load_type.setter\n def load_type(self, i):\n if i == 'mass':\n self.default_units['load'] = 'kg'\n self.default_units['quantity'] = 'kg*km'\n elif i == 'volume':\n self.default_units['load'] = 'm3'\n self.default_units['quantity'] = 'm3*km'\n else:\n raise ValueError('load_type can only be \"mass\" or \"volume\", '\n f'not {i}.')\n self._load_type = i\n\n @property\n def indicators(self):\n ''' [tuple] Impact indicators associated with the transportation item.'''\n return self.item.indicators\n\n @property\n def load(self):\n '''\n [float] Transportation load each trip.\n\n .. note::\n\n Set this to 1 and let the load_unit match the functional unit of the item\n if load does not affect price and impacts.\n\n '''\n return self._load\n @load.setter\n def load(self, load, unit=''):\n self._update_value('load', load, unit)\n\n @property\n def distance(self):\n '''\n [float] Transportation distance each trip.\n\n .. note::\n\n Set this to 1 and let the `distance_unit` match the functional unit of the item\n if distance does not affect price and impacts.\n\n '''\n return self._distance\n @distance.setter\n def distance(self, distance, unit=''):\n self._update_value('distance', distance, unit)\n\n @property\n def quantity(self):\n '''[float] Quantity of item functional unit.'''\n quantity = auom(self.default_units['quantity']). \\\n convert(self.load*self.distance, self.item.functional_unit)\n return quantity\n\n @property\n def interval(self):\n '''[float] Time between trips.'''\n return self._interval\n @interval.setter\n def interval(self, interval, unit=''):\n self._update_value('interval', interval, unit)\n\n @property\n def price(self):\n '''[float] Unit price of the item.'''\n return self.item.price\n\n @property\n def cost(self):\n '''[float] Total cost per trip.'''\n return self.price*self.quantity\n\n @property\n def impacts(self):\n '''[dict] Total impacts of this transportation item.'''\n impacts = {}\n for indicator, CF in self.item.CFs.items():\n impacts[indicator] = self.quantity*CF\n return impacts" ]
[ [ "numpy.hstack", "numpy.asarray", "scipy.integrate.solve_ivp", "numpy.ndarray", "numpy.full", "numpy.concatenate", "numpy.ones", "numpy.append", "numpy.array", "numpy.zeros", "numpy.vstack" ], [ "pandas.concat", "pandas.Index", "pandas.ExcelWriter", "pandas.DataFrame.from_dict", "numpy.array" ], [ "pandas.Index" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [ "1.6", "1.10", "1.4", "1.9", "1.5", "1.2", "1.7", "1.0", "1.3", "1.8" ], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "1.3", "0.19", "1.1", "1.5", "0.24", "0.20", "1.0", "0.25", "1.2" ], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
Maruja/Maruja-ILAS-Python
[ "af304bfa2767fb30982e88d4b2138113237ba99d" ]
[ "Assignment/Environmental_Project/part_A.py" ]
[ "from pandas import read_csv\nfrom IPython.display import display\nimport numpy as np\nimport sys\nimport math\n\n###############################\n ####Maria Eugenia Lopez ##### \n###############################\n\n\ndef fully_grown_depuration(number_to_remove=0.50):\n\t return plants.loc[plants.height_m > number_to_remove]\n\ndef convert_GPS_lat_long(df):\n\tfor index, row in df.iterrows():\n\t\tlat_viejo = row[\"GPS_lat\"]\n\t\tlatVal = (40008000*row[\"GPS_lat\"])/360\n\t\t#res= div*0.001#to convert to Klm\n\t\tdf.loc[index,\"GPS_lat\"] = latVal\n\n\t\tlat_radians = math.radians(lat_viejo)\n\t\tlonVal = (40075160*row[\"GPS_lon\"])/360\n\t\tlonVal = lonVal*math.cos(lat_radians)\n\t\t#res = res*0.001\n\t\tdf.loc[index,\"GPS_lon\"] = lonVal \n\n##----------------------------------------\n##Part A Assembling a Data Set\n##----------------------------------------\n\n##----------------------------------------\n##Input and Output: Data Frames\n\nplants = read_csv('environmental_survey/plants2017.csv',\n\tindex_col=0)\n\nplants.reset_index(level=0,inplace=True)\n\nplants.drop(plants.index[plants.Plant == 'tree'], inplace=True)\n#display(plants.head(n=50))\n\nplants.reset_index(drop=True,inplace=True)\n\n##----------------------------------------\n##Functions\nconvert_GPS_lat_long(\tplants)\nplants.rename(columns={'GPS_lon':'Meters_lon',\n\t\t\t\t\t\t'GPS_lat':'Meters_lat'}, inplace=True)\n\n\n##----------------------------------------\n##Functions and Data Structures: Boolean Indexing\nheiht_set_by_user = float(input(\"Set the height that you want: \") or \"0.5\")\nplants = fully_grown_depuration(float(heiht_set_by_user))\n\n#reseting the index after the depuration \nplants.reset_index(drop=True,inplace=True)\n\ndisplay(plants)\n" ]
[ [ "pandas.read_csv" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "2.0", "1.4", "1.1", "1.5", "1.2", "1.3" ], "scipy": [], "tensorflow": [] } ]
RodolfoFerro/iris-api
[ "3034a1629d28feb215be2fdbf24edbd1176ff0d6" ]
[ "app.py" ]
[ "# -*- coding: utf-8 -*-\n\n# ===============================================================\n# Author: Rodolfo Ferro\n# Email: [email protected]\n# Twitter: @FerroRodolfo\n#\n# ABOUT COPYING OR USING PARTIAL INFORMATION:\n# This script was originally created by Rodolfo Ferro, for\n# his workshop in HackSureste 2019 at Universidad Modelo\n# in Mérida. Any explicit usage of this script or its\n# contents is granted according to the license provided and\n# its conditions.\n# ===============================================================\n\n\nfrom flask import Flask, jsonify, request, render_template\nfrom iris import iris_classifier\nfrom pprint import pprint\nimport numpy as np\nimport requests\nimport json\n\n# Main app:\napp = Flask(__name__)\n\n# Global:\nversion = 'v0.0'\nclassifier = iris_classifier()\nspecies = {\n '0': 'I. setosa',\n '1': 'I. versicolor',\n '2': 'I. virginica'\n}\n\n\n# Static website:\[email protected]('/')\ndef index():\n return render_template(\"index.html\")\n\n\n# API MAIN STRUCTURE:\[email protected]('/api/' + version, methods=['GET'])\ndef test():\n \"\"\"\n GET method to test the API.\n \"\"\"\n\n # Output message:\n message = {\n \"response\": [\n {\n \"text\": \"Hello world!\"\n }\n ]\n }\n return jsonify(message)\n\n\[email protected]('/api/' + version + '/predict', methods=['POST'])\ndef predict():\n \"\"\"\n POST method to predict with our classification model.\n \"\"\"\n\n # Get data from JSON object in POST method:\n req_data = request.get_json()\n\n # Parse data from JSON:\n sl = req_data['sepal_length']\n sw = req_data['sepal_width']\n pl = req_data['petal_length']\n pw = req_data['petal_width']\n\n # Predict with model:\n input_data = np.array([[sl, sw, pl, pw]])\n prediction = classifier.predict(input_data)\n print(prediction)\n\n # Output message:\n message = {\"response\": [\n {\"input\": {\n 'sepal_length': sl,\n 'sepal_width': sw,\n 'petal_length': pl,\n 'petal_width': pw\n }},\n {\"prediction\": int(prediction[0])},\n {\"species\": species[str(prediction[0])]}]}\n return jsonify(message)\n\n\[email protected](404)\ndef not_found(error=None):\n message = {\n 'status': 404,\n 'message': 'Not Found: ' + request.url,\n }\n response = jsonify(message)\n response.status_code = 404\n\n return response\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=5000)\n" ]
[ [ "numpy.array" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
DuttaAbhigyan/robust-adaptive-lqr
[ "89d5ff606806a389a1ec4026bc5c17fb51573ae6" ]
[ "python/sls.py" ]
[ "\"\"\"sls.py\n\nAn implementation of the robust adaptive controller.\nBoth FIR SLS version with CVXPY and the common \nLyapunov relaxation.\n\n\n\"\"\"\n\nimport numpy as np\nimport cvxpy as cvx\nimport utils\nimport logging\nimport math\nimport scipy.linalg\n\nfrom abc import ABC, abstractmethod\nfrom adaptive import AdaptiveMethod\n\n\nclass SLSInfeasibleException(Exception):\n def __init__(self, msg=None):\n super().__init__(msg)\n\ndef make_state_space_controller(Phi_x, Phi_u, n, p):\n \"\"\"\n Converts FIR transfer functions to a state\n space realization of the dynamic controller,\n mapping states to inputs.\n\n \"\"\"\n assert len(Phi_x.shape) == 2\n assert len(Phi_u.shape) == 2\n\n assert Phi_x.shape[1] == n\n assert Phi_u.shape[1] == n\n\n nT, _ = Phi_x.shape\n pT, _ = Phi_u.shape\n\n assert (nT % n) == 0\n assert (pT % p) == 0\n\n T = nT // n\n assert T == (pT // p)\n\n # See Theorem 2 of:\n # https://nikolaimatni.github.io/papers/sls_state_space.pdf\n\n Z = np.diag(np.ones(n*(T-2)), k=-n)\n assert Z.shape == ((T-1)*n, (T-1)*n)\n\n calI = np.zeros((n*(T-1), n))\n calI[:n, :] = np.eye(n)\n\n Rhat = np.hstack([Phi_x[n*k:n*(k+1), :] for k in range(1, T)])\n Mhat = np.hstack([Phi_u[p*k:p*(k+1), :] for k in range(1, T)])\n\n M1 = Phi_u[:p, :]\n R1 = Phi_x[:n, :]\n\n A = Z - calI.dot(Rhat)\n B = -calI\n C = M1.dot(Rhat) - Mhat\n D = M1\n\n return (A, B, C, D)\n\n\ndef h2_squared_norm(A, B, Phi_x, Phi_u, Q, R, sigma_w):\n \"\"\"\n Gets the squared infinite horizon LQR cost for system\n (A,B) in feedback with the controller defined by Phi_x\n and Phi_u. \n\n \"\"\"\n\n n, p = B.shape\n\n A_k, B_k, C_k, D_k = make_state_space_controller(Phi_x, Phi_u, n, p)\n\n A_cl = np.block([\n [A + B.dot(D_k), B.dot(C_k)],\n [B_k, A_k]\n ])\n\n Q_sqrt = utils.psd_sqrt(Q)\n R_sqrt = utils.psd_sqrt(R)\n\n C_cl = np.block([\n [Q_sqrt, np.zeros((n, A_k.shape[0]))],\n [R_sqrt.dot(D_k), R_sqrt.dot(C_k)]\n ])\n\n B_cl = np.vstack((np.eye(n), np.zeros((A_k.shape[0], n))))\n\n P = utils.solve_discrete_lyapunov(A_cl.T, B_cl.dot(B_cl.T))\n\n return (sigma_w ** 2) * np.trace(C_cl.dot(P).dot(C_cl.T))\n\n\ndef _assert_AB_consistent(A, B):\n assert len(A.shape) == 2 and A.shape[0] == A.shape[1]\n assert len(B.shape) == 2\n assert A.shape[0] == B.shape[0]\n\n\ndef _assert_ABCD_consistent(A, B, C, D):\n _assert_AB_consistent(A, B)\n\n assert len(C.shape) == 2\n assert len(D.shape) == 2\n\n assert C.shape[1] == A.shape[0]\n assert C.shape[0] == D.shape[0]\n assert D.shape[1] == B.shape[1]\n\n\ndef roll_forward(A, B, K, x0, psi0, sigma_w, horizon, rng=None):\n \"\"\"Apply an LTI controller K = (A_k,B_k,C_k,D_k)\n\n Roll the true system (A, B) forward with the SS realization of the LTI\n controller given. horizon is the length of the trajectory, and\n sigma_w is the stddev of the Gaussian process noise.\n\n \"\"\"\n\n if rng is None:\n rng = np.random\n\n _assert_AB_consistent(A, B)\n\n A_k, B_k, C_k, D_k = K\n _assert_ABCD_consistent(A_k, B_k, C_k, D_k)\n\n state_dim, input_dim = B.shape\n psi_dim = A_k.shape[0]\n\n assert C_k.shape[0] == input_dim\n assert B_k.shape[1] == state_dim\n\n if x0 is None:\n x0 = np.zeros((state_dim,))\n if psi0 is None:\n psi0 = np.zeros((psi_dim,))\n\n assert x0.shape == (state_dim,)\n assert psi0.shape == (psi_dim,)\n\n process = sigma_w*rng.normal(size=(horizon, state_dim))\n xt = np.array(x0)\n psit = np.array(psi0)\n\n states = np.zeros((horizon+1, state_dim))\n inputs = np.zeros((horizon, input_dim))\n controller_states = np.zeros((horizon+1, psi_dim))\n\n states[0, :] = x0\n controller_states[0, :] = psi0\n\n for t in range(horizon):\n psitp1 = A_k.dot(psit) + B_k.dot(xt)\n ut = C_k.dot(psit) + D_k.dot(xt)\n xtp1 = A.dot(xt) + B.dot(ut) + process[t]\n inputs[t, :] = ut\n states[t+1, :] = xtp1\n controller_states[t+1, :] = psitp1\n xt = xtp1\n psit = psitp1\n\n return states, inputs, controller_states\n\n\ndef sls_synth(Q, R, Ahat, Bhat, eps_A, eps_B, T, gamma, alpha, logger=None):\n \"\"\"\n Solves the SLS synthesis problem for length T FIR filters\n using CVXPY\n\n \"\"\"\n\n assert len(Q.shape) == 2 and Q.shape[0] == Q.shape[1]\n assert len(R.shape) == 2 and R.shape[0] == R.shape[1]\n assert len(Ahat.shape) == 2 and Ahat.shape[0] == Ahat.shape[1]\n assert len(Bhat.shape) == 2 and Bhat.shape[0] == Ahat.shape[0]\n assert Q.shape[0] == Ahat.shape[0]\n assert R.shape[0] == Bhat.shape[1]\n assert eps_A >= 0\n assert eps_B >= 0\n assert T >= 1\n assert gamma > 0 and gamma < 1\n assert alpha > 0 and alpha < 1\n\n if logger is None:\n logger = logging.getLogger(__name__)\n\n n, p = Bhat.shape\n\n Q_sqrt = utils.psd_sqrt(Q)\n R_sqrt = utils.psd_sqrt(R)\n\n # Phi_x = \\sum_{k=1}^{T} Phi_x[k] z^{-k}\n Phi_x = cvx.Variable(T*n, n, name=\"Phi_x\")\n\n # Phi_u = \\sum_{k=1}^{T} Phi_u[k] z^{-k}\n Phi_u = cvx.Variable(T*p, n, name=\"Phi_u\")\n\n # htwo_cost\n htwo_cost = cvx.Variable(name=\"htwo_cost\")\n\n # subspace constraint:\n # [zI - Ah, -Bh] * [Phi_x; Phi_u] = I\n #\n # Note that:\n # z Phi_x = \\sum_{k=0}^{T-1} Phi_x[k+1] z^{-k}\n #\n # This means that:\n # 1) Phi_x[1] = I\n # 2) Phi_x[k+1] = Ah*Phi_x[k] + Bh*Phi_u[k] for k=1, ..., T-1\n # 3) Ah*Phi_x[T] + Bh*Phi_u[T] = 0\n\n constr = []\n\n constr.append(Phi_x[:n, :] == np.eye(n))\n for k in range(T-1):\n constr.append(Phi_x[n*(k+1):n*(k+1+1), :] == Ahat*Phi_x[n*k:n*(k+1), :] + Bhat*Phi_u[p*k:p*(k+1), :])\n constr.append(Ahat*Phi_x[n*(T-1):, :] + Bhat*Phi_u[p*(T-1):, :] == 0)\n\n # H2 constraint:\n # By Parseval's identity, this is equal (up to constants) to\n #\n # frobenius_norm(\n # [ Q_sqrt*Phi_x[1] ;\n # ...\n # Q_sqrt*Phi_x[T] ;\n # R_sqrt*Phi_u[1] ;\n # ...\n # R_sqrt*Phi_u[T]\n # ]\n # ) <= htwo_cost\n # TODO: what is the best way to implement this in cvxpy?\n constr.append(\n cvx.norm(\n cvx.bmat(\n [[Q_sqrt*Phi_x[n*k:n*(k+1), :]] for k in range(T)] +\n [[R_sqrt*Phi_u[p*k:p*(k+1), :]] for k in range(T)]),\n 'fro') <= htwo_cost)\n\n # H-infinity constraint\n #\n # We want to enforce ||H(z)||_inf <= gamma, where\n #\n # H(z) = \\sum_{k=1}^{T} [ mult_x * Phi_x[k] ; mult_u * Phi_u[k] ] z^{-k}.\n #\n # Here, each of the FIR coefficients has size (n+p) x n. Since n+p>n, we enforce\n # the constraint on the transpose system H^T(z). The LMI constraint\n # for this comes from Theorem 5.8 of\n # Positive trigonometric polynomials and signal processing applications (2007) by\n # B. Dumitrescu.\n #\n # Here is a table to map the variable names in the text to this program\n #\n # Text Program Comment\n # -------------------------------------------------------------\n # p n Output dim\n # m n+p Input dim\n # n T FIR horizon\n # p(n+1) n(T+1) SDP variable size\n # p(n+1) x m n(T+1) x (n+p)\n\n mult_x = eps_A/np.sqrt(alpha)\n mult_u = eps_B/np.sqrt(1-alpha)\n\n # Hbar has size (T+1)*n x (n+p)\n Hbar = cvx.bmat(\n [[np.zeros((n, n)), np.zeros((n, p))]] +\n [[mult_x*Phi_x[n*k:n*(k+1), :].T, mult_u*Phi_u[p*k:p*(k+1), :].T] for k in range(T)])\n\n Q = cvx.Semidef(n*(T+1), name=\"Q\")\n\n # Constraint (5.44)\n\n # Case k==0: the block diag of Q has to sum to gamma^2 * eye(n)\n gamma_sq = gamma ** 2\n constr.append(\n sum([Q[n*t:n*(t+1), n*t:n*(t+1)] for t in range(T+1)]) == gamma_sq*np.eye(n))\n\n # Case k>0: the block off-diag of Q has to sum to zero\n for k in range(1, T+1):\n constr.append(\n sum([Q[n*t:n*(t+1), n*(t+k):n*(t+1+k)] for t in range(T+1-k)]) == np.zeros((n, n)))\n\n # Constraint (5.45)\n constr.append(\n cvx.bmat([\n [Q, Hbar],\n [Hbar.T, np.eye(n+p)]]) == cvx.Semidef(n*(T+1) + (n+p)))\n\n prob = cvx.Problem(cvx.Minimize(htwo_cost), constr)\n prob.solve(solver=cvx.SCS)\n\n if prob.status == cvx.OPTIMAL:\n logging.debug(\"successfully solved!\")\n Phi_x = np.array(Phi_x.value)\n Phi_u = np.array(Phi_u.value)\n return (True, prob.value, Phi_x, Phi_u)\n else:\n logging.debug(\"could not solve: {}\".format(prob.status))\n return (False, None, None, None)\n\n\ndef sls_common_lyapunov(A, B, Q, R, eps_A, eps_B, tau, logger=None):\n \"\"\"\n Solves the common Lyapunov relaxation to the robust \n synthesis problem.\n\n Taken from\n lstd-lqr/blob/master/code/policy_iteration.ipynb\n learning-lqr/experiments/matlab/sls_synth_yalmip/common_lyap_synth_var2_alpha.m\n\n \"\"\"\n\n if logger is None:\n logger = logging.getLogger(__name__)\n\n d, p = B.shape\n X = cvx.Symmetric(d) # inverse Lyapunov function\n Z = cvx.Variable(p, d) # -K*X\n W_11 = cvx.Symmetric(d)\n W_12 = cvx.Variable(d, p)\n W_22 = cvx.Symmetric(p)\n alph = cvx.Variable() # scalar for tuning the H_inf constraint\n\n constraints = []\n\n # H2 cost: trace(W)=H2 cost\n mat1 = cvx.bmat([\n [X, X, Z.T],\n [X, W_11, W_12],\n [Z, W_12.T, W_22]])\n constraints.append(mat1 == cvx.Semidef(2*d + p))\n\n # H_infinity constraint\n mat2 = cvx.bmat([\n [X-np.eye(d), (A*X+B*Z), np.zeros((d, d)), np.zeros((d, p))],\n [(X*A.T+Z.T*B.T), X, eps_A*X, eps_B*Z.T],\n [np.zeros((d, d)), eps_A*X, alph*(tau**2)*np.eye(d), np.zeros((d, p))],\n [np.zeros((p, d)), eps_B*Z, np.zeros((p, d)), (1-alph)*(tau**2)*np.eye(p)]])\n constraints.append(mat2 == cvx.Semidef(3*d + p))\n\n # constrain alpha to be in [0,1]:\n constraints.append(alph >= 0)\n constraints.append(alph <= 1)\n\n # Solve!\n objective = cvx.Minimize(cvx.trace(Q*W_11) + cvx.trace(R*W_22))\n prob = cvx.Problem(objective, constraints)\n try:\n obj = prob.solve(solver=cvx.MOSEK)\n except cvx.SolverError:\n logger.warn(\"SolverError encountered\")\n return (False, None, None, None)\n\n if prob.status == cvx.OPTIMAL:\n logging.debug(\"common_lyapunov: found optimal solution\")\n\n X_value = np.array(X.value)\n P_value = scipy.linalg.solve(X_value, np.eye(d), sym_pos=True)\n\n # NOTE: the K returned here is meant to be used\n # as A + BK **NOT** A - BK\n K_value = np.array(Z.value).dot(P_value)\n\n return (True, obj, P_value, K_value)\n\n else:\n logging.debug(\"common_lyapunov: could not solve (status={})\".format(prob.status))\n\n return (False, None, None, None)\n\nclass SLS_Implementation(ABC):\n\n @abstractmethod\n def open(self):\n \"\"\"\n\n \"\"\"\n\n pass\n\n @abstractmethod\n def synth(self, Q, R, Ahat, Bhat, eps_A, eps_B, truncation_length, gamma, alpha, logger):\n \"\"\"\n\n \"\"\"\n\n pass\n\nclass SLS_CVXPY(SLS_Implementation):\n\n def open(self):\n pass\n\n def synth(self, Q, R, Ahat, Bhat, eps_A, eps_B, truncation_length, gamma, alpha, logger):\n return sls_synth(Q, R, Ahat, Bhat, eps_A, eps_B, truncation_length, gamma, alpha, logger)\n\nclass SLS_FIRStrategy(AdaptiveMethod):\n \"\"\"Adaptive control based on FIR truncated SLS\n\n \"\"\"\n\n def __init__(self, Q, R, A_star, B_star, sigma_w, rls_lam,\n sigma_explore, reg, epoch_multiplier,\n truncation_length, actual_error_multiplier,\n use_gamma=0.98, sls_impl=None):\n super().__init__(Q, R, A_star, B_star, sigma_w, rls_lam)\n self._sigma_explore = sigma_explore\n self._reg = reg\n self._epoch_multiplier = epoch_multiplier\n # TODO(stephentu):\n # the truncation length should grow with time, but for now\n # we keep it constant\n # Additionally, gamma should be searched over as an optimization\n # variable. For how, we fix the value.\n # Finally, the optimization problem should be modified\n # to involve the variable V as in https://arxiv.org/abs/1805.09388\n self._truncation_length = truncation_length\n self._actual_error_multiplier = actual_error_multiplier\n self._sls_impl = sls_impl if sls_impl is not None else SLS_CVXPY()\n self._logger = logging.getLogger(__name__)\n self._use_gamma = use_gamma\n self._controller_state = None\n\n def _get_logger(self):\n return self._logger\n\n def reset(self, rng):\n super().reset(rng)\n self._sls_impl.open()\n self._midway_infeasible = 0\n\n def _design_controller(self, states, inputs, transitions, rng):\n\n logger = self._get_logger()\n\n Anom, Bnom, _ = utils.solve_least_squares(states, inputs, transitions, reg=self._reg)\n eps_A = np.linalg.norm(Anom - self._A_star, ord=2)\n eps_B = np.linalg.norm(Bnom - self._B_star, ord=2)\n\n effective_eps_A = self._actual_error_multiplier * eps_A\n effective_eps_B = self._actual_error_multiplier * eps_B\n\n epoch_id = self._epoch_idx + 1 if self._has_primed else 0\n\n logger.info(\"_design_controller(epoch={}): effective_eps_A={}, effective_eps_B={}\".format(epoch_id, effective_eps_A, effective_eps_B))\n\n # if SLS is not feasible, we fallback to the current\n # control policy if it exists, otherwise we throw an SLSInfeasibleException\n if self._use_gamma is None:\n # bisect for gamma\n logger.info(\"_design_controller(epoch={}): bisecting for gamma\".format(epoch_id))\n\n INF = 1e12\n\n def fn(gamma):\n is_feasible, obj, _, _ = self._sls_impl.synth(self._Q, self._R, Anom, Bnom,\n effective_eps_A, effective_eps_B, self._truncation_length,\n gamma=gamma, alpha=0.5, logger=logger)\n if not is_feasible:\n return INF\n else:\n return 1/(1-gamma) * obj\n\n disp_lvl = 3 if logger.isEnabledFor(logging.DEBUG) else 0\n gamma_star, _, error_flag, _ = scipy.optimize.fminbound(fn, 0, 1 - 1e-5, xtol=1e-2, maxfun=20, full_output=True, disp=disp_lvl)\n if error_flag:\n logger.warn(\"_design_controller(epoch={}): maxfun exceeded during bisection, gamma_star={}\".format(epoch_id, gamma_star))\n logger.info(\"_design_controller(epoch={}): using gamma_star={}\".format(epoch_id, gamma_star))\n is_feasible, _, Phi_x, Phi_u = self._sls_impl.synth(self._Q, self._R, Anom, Bnom,\n effective_eps_A, effective_eps_B, self._truncation_length,\n gamma=gamma_star, alpha=0.5, logger=logger)\n\n else:\n assert self._use_gamma > 0 and self._use_gamma < 1\n logger.info(\"_design_controller(epoch={}): using fixed gamma={}\".format(epoch_id, self._use_gamma))\n is_feasible, _, Phi_x, Phi_u = self._sls_impl.synth(self._Q, self._R, Anom, Bnom,\n effective_eps_A, effective_eps_B, self._truncation_length,\n gamma=self._use_gamma, alpha=0.5, logger=logger)\n\n if not is_feasible:\n logger.info(\"_design_controller(epoch={}): SLS was not feasible...\".format(epoch_id))\n\n try:\n self._current_K\n # keep current controller\n assert self._current_K is not None\n logger.warn(\"_design_controller(epoch={}): SLS not feasible: keeping current controller\".format(epoch_id))\n self._midway_infeasible += 1\n except AttributeError:\n logger.warn(\"_design_controller(epoch={}): SLS not feasible: no existing controller to fallback on, effective_eps_A={}, effective_eps_B={}\".format(epoch_id, effective_eps_A, effective_eps_B))\n raise SLSInfeasibleException()\n\n else:\n logger.info(\"_design_controller(epoch={}): SLS was feasible. updating controller\".format(epoch_id))\n self._Phi_x = Phi_x\n self._Phi_u = Phi_u\n self._current_K = make_state_space_controller(Phi_x, Phi_u, self._n, self._p)\n\n # compute the infinite horizon cost of this controller\n Jnom = h2_squared_norm(self._A_star,\n self._B_star,\n self._Phi_x,\n self._Phi_u,\n self._Q,\n self._R,\n self._sigma_w)\n\n return Anom, Bnom, Jnom\n\n def _should_terminate_epoch(self):\n\n if (self._iteration_within_epoch_idx >=\n self._epoch_multiplier * (self._epoch_idx + 1)):\n logger = self._get_logger()\n logger.debug(\"terminating epoch... exploration noise will now have stddev {}\".format(\n self._sigma_explore * 1/math.pow(self._epoch_idx + 2, 1/3)))\n return True\n else:\n return False\n\n def _get_input(self, state, rng):\n\n rng = self._get_rng(rng)\n\n A_k, B_k, C_k, D_k = self._current_K\n psit = self._controller_state\n if psit is None:\n psit = np.zeros((A_k.shape[0],))\n psitp1 = A_k.dot(psit) + B_k.dot(state)\n ctrl_input = C_k.dot(psit) + D_k.dot(state)\n self._controller_state = psitp1\n\n sigma_explore_decay = 1/math.pow(self._epoch_idx + 1, 1/3)\n explore_input = self._sigma_explore * sigma_explore_decay * rng.normal(size=(self._p,))\n return ctrl_input + explore_input\n\n\nclass SLS_CommonLyapunovStrategy(AdaptiveMethod):\n \"\"\"\n Adaptive control based on common Lyapunov relaxation\n of robust control problem\n\n \"\"\"\n\n def __init__(self, Q, R, A_star, B_star, sigma_w, rls_lam,\n sigma_explore, reg, epoch_multiplier, actual_error_multiplier):\n super().__init__(Q, R, A_star, B_star, sigma_w, rls_lam)\n self._sigma_explore = sigma_explore\n self._reg = reg\n self._epoch_multiplier = epoch_multiplier\n self._actual_error_multiplier = actual_error_multiplier\n self._logger = logging.getLogger(__name__)\n self._midway_infeasible = 0\n\n def reset(self, rng):\n super().reset(rng)\n self._midway_infeasible = 0\n\n def _get_logger(self):\n return self._logger\n\n def _design_controller(self, states, inputs, transitions, rng):\n logger = self._get_logger()\n\n Anom, Bnom, _ = utils.solve_least_squares(states, inputs, transitions, reg=self._reg)\n eps_A = np.linalg.norm(Anom - self._A_star, ord=2)\n eps_B = np.linalg.norm(Bnom - self._B_star, ord=2)\n\n effective_eps_A = self._actual_error_multiplier * eps_A\n effective_eps_B = self._actual_error_multiplier * eps_B\n\n epoch_id = self._epoch_idx + 1 if self._has_primed else 0\n\n logger.info(\"_design_controller(epoch={}): effective_eps_A={}, effective_eps_B={}\".format(epoch_id, effective_eps_A, effective_eps_B))\n\n is_feasible, _, _, K = sls_common_lyapunov(\n Anom, Bnom, self._Q, self._R,\n effective_eps_A, effective_eps_B, tau=0.999, logger=logger)\n\n if not is_feasible:\n\n try:\n self._current_K\n # keep current controller\n assert self._current_K is not None\n logger.warn(\"_design_controller(epoch={}): SLS not feasible: keeping current controller\".format(epoch_id))\n self._midway_infeasible += 1\n except AttributeError:\n logger.warn(\"_design_controller(epoch={}): SLS not feasible: no existing controller to fallback on, effective_eps_A={}, effective_eps_B={}\".format(epoch_id, effective_eps_A, effective_eps_B))\n raise SLSInfeasibleException()\n\n else:\n logger.info(\"_design_controller(epoch={}): SLS was feasible. updating controller\".format(epoch_id))\n self._current_K = K\n\n # compute the infinite horizon cost of this controller\n Jnom = utils.LQR_cost(self._A_star, self._B_star, self._current_K, self._Q, self._R, self._sigma_w)\n\n return Anom, Bnom, Jnom\n\n def _should_terminate_epoch(self):\n\n if (self._iteration_within_epoch_idx >=\n self._epoch_multiplier * (self._epoch_idx + 1)):\n logger = self._get_logger()\n logger.debug(\"terminating epoch... exploration noise will now have stddev {}\".format(\n self._sigma_explore * 1/math.pow(self._epoch_idx + 2, 1/3)))\n return True\n else:\n return False\n\n def _get_input(self, state, rng):\n\n rng = self._get_rng(rng)\n ctrl_input = self._current_K.dot(state)\n sigma_explore_decay = 1/math.pow(self._epoch_idx + 1, 1/3)\n explore_input = self._sigma_explore * sigma_explore_decay * rng.normal(size=(self._p,))\n return ctrl_input + explore_input\n\ndef _main():\n import examples\n A_star, B_star = examples.unstable_laplacian_dynamics()\n\n # define costs\n Q = 1e-3 * np.eye(3)\n R = np.eye(3)\n\n # initial controller\n _, K_init = utils.dlqr(A_star, B_star, 1e-3*np.eye(3), np.eye(3))\n\n rng = np.random\n\n env = SLS_FIRStrategy(Q=Q,\n R=R,\n A_star=A_star,\n B_star=B_star,\n sigma_w=1,\n sigma_explore=0.1,\n reg=1e-5,\n epoch_multiplier=10,\n truncation_length=12,\n actual_error_multiplier=1, \n rls_lam=None)\n\n env.reset(rng)\n env.prime(250, K_init, 0.5, rng)\n for idx in range(500):\n env.step(rng)\n\n env = SLS_CommonLyapunovStrategy(Q=Q,\n R=R,\n A_star=A_star,\n B_star=B_star,\n sigma_w=1,\n sigma_explore=0.1,\n reg=1e-5,\n epoch_multiplier=10,\n actual_error_multiplier=1, \n rls_lam=None)\n\n env.reset(rng)\n env.prime(250, K_init, 0.5, rng)\n for idx in range(500):\n env.step(rng)\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.DEBUG)\n np.set_printoptions(linewidth=200)\n _main()\n\n" ]
[ [ "numpy.sqrt", "numpy.eye", "numpy.set_printoptions", "numpy.linalg.norm", "numpy.ones", "numpy.array", "numpy.zeros" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
christabella/GPflow
[ "30824d289f8ee3f58d4249238c8b7267e6a0b2fc", "30824d289f8ee3f58d4249238c8b7267e6a0b2fc", "30824d289f8ee3f58d4249238c8b7267e6a0b2fc", "30824d289f8ee3f58d4249238c8b7267e6a0b2fc" ]
[ "doc/source/notebooks/understanding/models.pct.py", "doc/source/notebooks/theory/Sanity_check.pct.py", "doc/source/notebooks/basics/GPLVM.pct.py", "tests/integration/test_method_equivalence.py" ]
[ "# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,.pct.py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.3.3\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown]\n# # Manipulating GPflow models\n#\n# One of the key ingredients in GPflow is the model class, which enables you to carefully control parameters. This notebook shows how some of these parameter control features work, and how to build your own model with GPflow. First we'll look at:\n#\n# - how to view models and parameters\n# - how to set parameter values\n# - how to constrain parameters (for example, variance > 0)\n# - how to fix model parameters\n# - how to apply priors to parameters\n# - how to optimize models\n#\n# Then we'll show how to build a simple logistic regression model, demonstrating the ease of the parameter framework.\n#\n# GPy users should feel right at home, but there are some small differences.\n#\n# First, let's deal with the usual notebook boilerplate and make a simple GP regression model. See [Basic (Gaussian likelihood) GP regression model](../basics/regression.ipynb) for specifics of the model; we just want some parameters to play with.\n\n# %%\nimport numpy as np\nimport gpflow\nimport tensorflow_probability as tfp\nfrom gpflow.utilities import print_summary, set_trainable, to_default_float\n\n# %% [markdown]\n# We begin by creating a very simple GP regression model:\n\n# %%\n# generate toy data\nnp.random.seed(1)\nX = np.random.rand(20, 1)\nY = np.sin(12 * X) + 0.66 * np.cos(25 * X) + np.random.randn(20, 1) * 0.01\n\nm = gpflow.models.GPR((X, Y), kernel=gpflow.kernels.Matern32() + gpflow.kernels.Linear())\n\n# %% [markdown]\n# ## Viewing, getting, and setting parameters\n# You can display the state of the model in a terminal by using `print_summary(m)`. You can change the display format using the `fmt` keyword argument, e.g. `'html'`. In a notebook, you can also use `fmt='notebook'` or set the default printing format as `notebook`:\n\n# %%\nprint_summary(m, fmt=\"notebook\")\n\n# %%\ngpflow.config.set_default_summary_fmt(\"notebook\")\n\n# %% [markdown]\n# This model has four parameters. The kernel is made of the sum of two parts. The first (counting from zero) is a Matern32 kernel that has a variance parameter and a lengthscales parameter; the second is a linear kernel that has only a variance parameter. There is also a parameter that controls the variance of the noise, as part of the likelihood.\n#\n# All the model variables have been initialized at `1.0`. You can access individual parameters in the same way that you display the state of the model in a terminal; for example, to see all the parameters that are part of the likelihood, run:\n\n# %%\nprint_summary(m.likelihood)\n\n# %% [markdown]\n# This gets more useful with more complex models!\n\n# %% [markdown]\n# To set the value of a parameter, just use `assign()`:\n\n# %%\nm.kernel.kernels[0].lengthscales.assign(0.5)\nm.likelihood.variance.assign(0.01)\nprint_summary(m, fmt=\"notebook\")\n\n# %% [markdown]\n# ## Constraints and trainable variables\n#\n# GPflow helpfully creates an unconstrained representation of all the variables. In the previous example, all the variables are constrained positively (see the **transform** column in the table); the unconstrained representation is given by $\\alpha = \\log(\\exp(\\theta)-1)$. The `trainable_parameters` property returns the constrained values:\n\n# %%\nm.trainable_parameters\n\n# %% [markdown]\n# Each parameter has an `unconstrained_variable` attribute that enables you to access the unconstrained value as a TensorFlow `Variable`.\n\n# %%\np = m.kernel.kernels[0].lengthscales\np.unconstrained_variable\n\n# %% [markdown]\n# You can also check the unconstrained value as follows:\n\n# %%\np.transform.inverse(p)\n\n# %% [markdown]\n# Constraints are handled by the Bijector classes from the `tensorflow_probability` package. You might prefer to use the constraint $\\alpha = \\log(\\theta)$; this is easily done by replacing the parameter with one that has a different `transform` attribute (here we make sure to copy all other attributes across from the old parameter; this is not necessary when there is no `prior` and the `trainable` state is still the default of `True`):\n\n# %%\nold_parameter = m.kernel.kernels[0].lengthscales\nnew_parameter = gpflow.Parameter(\n old_parameter,\n trainable=old_parameter.trainable,\n prior=old_parameter.prior,\n name=old_parameter.name.split(\":\")[0], # tensorflow is weird and adds ':0' to the name\n transform=tfp.bijectors.Exp(),\n)\nm.kernel.kernels[0].lengthscales = new_parameter\n\n# %% [markdown]\n# Though the lengthscale itself remains the same, the unconstrained lengthscale has changed:\n\n# %%\np.transform.inverse(p)\n\n# %% [markdown]\n# You can also change the `transform` attribute in place:\n\n# %%\nm.kernel.kernels[0].variance.transform = tfp.bijectors.Exp()\n\n# %%\nprint_summary(m, fmt=\"notebook\")\n\n# %% [markdown]\n# ## Changing whether a parameter will be trained in optimization\n#\n# Another helpful feature is the ability to fix parameters. To do this, simply set the `trainable` attribute to `False`; this is shown in the **trainable** column of the representation, and the corresponding variable is removed from the free state.\n\n# %%\nset_trainable(m.kernel.kernels[1].variance, False)\nprint_summary(m)\n\n# %%\nm.trainable_parameters\n\n# %% [markdown]\n# To unfix a parameter, just set the `trainable` attribute to `True` again.\n\n# %%\nset_trainable(m.kernel.kernels[1].variance, True)\nprint_summary(m)\n\n# %% [markdown]\n# **NOTE:** If you want to recursively change the `trainable` status of an object that *contains* parameters, you **must** use the `set_trainable()` utility function.\n#\n# A module (e.g. a model, kernel, likelihood, ... instance) does not have a `trainable` attribute:\n\n# %%\ntry:\n m.kernel.trainable\nexcept AttributeError:\n print(f\"{m.kernel.__class__.__name__} does not have a trainable attribute\")\n\n# %%\nset_trainable(m.kernel, False)\nprint_summary(m)\n\n# %% [markdown]\n# ## Priors\n#\n# You can set priors in the same way as transforms and trainability, by using `tensorflow_probability` distribution objects. Let's set a Gamma prior on the variance of the Matern32 kernel.\n\n# %%\nk = gpflow.kernels.Matern32()\nk.variance.prior = tfp.distributions.Gamma(to_default_float(2), to_default_float(3))\n\nprint_summary(k)\n\n# %%\nm.kernel.kernels[0].variance.prior = tfp.distributions.Gamma(\n to_default_float(2), to_default_float(3)\n)\nprint_summary(m)\n\n\n# %% [markdown]\n# ## Optimization\n#\n# To optimize your model, first create an instance of an optimizer (in this case, `gpflow.optimizers.Scipy`), which has optional arguments that are passed to `scipy.optimize.minimize` (we minimize the negative log likelihood). Then, call the `minimize` method of that optimizer, with your model as the optimization target. Variables that have priors are maximum a priori (MAP) estimated, that is, we add the log prior to the log likelihood, and otherwise use Maximum Likelihood.\n\n# %%\ndef closure():\n return -m.log_marginal_likelihood()\n\n\nopt = gpflow.optimizers.Scipy()\nopt.minimize(closure, variables=m.trainable_variables)\n\n# %% [markdown]\n# ## Building new models\n#\n# To build new models, you'll need to inherit from `gpflow.models.BayesianModel`. Parameters are instantiated with `gpflow.Parameter`. You might also be interested in `tf.Module`, which acts as a 'container' for `Parameter`s (for example, kernels are `tf.Module`s).\n#\n# In this very simple demo, we'll implement linear multiclass classification.\n#\n# There are two parameters: a weight matrix and a bias (offset). The key thing to implement the `log_likelihood` method, which returns a TensorFlow scalar that represents the (log) likelihood. You can use parameter objects inside `log_likelihood`.\n#\n\n# %%\nimport tensorflow as tf\n\n\nclass LinearMulticlass(gpflow.models.BayesianModel):\n def __init__(self, X, Y, name=None):\n super().__init__(name=name) # always call the parent constructor\n\n self.X = X.copy() # X is a NumPy array of inputs\n self.Y = Y.copy() # Y is a 1-of-k (one-hot) representation of the labels\n\n self.num_data, self.input_dim = X.shape\n _, self.num_classes = Y.shape\n\n # make some parameters\n self.W = gpflow.Parameter(np.random.randn(self.input_dim, self.num_classes))\n self.b = gpflow.Parameter(np.random.randn(self.num_classes))\n\n # ^^ You must make the parameters attributes of the class for\n # them to be picked up by the model. i.e. this won't work:\n #\n # W = gpflow.Param(... <-- must be self.W\n\n def log_likelihood(self): # takes no arguments\n p = tf.nn.softmax(\n tf.matmul(self.X, self.W) + self.b\n ) # Param variables are used as tensorflow arrays.\n return tf.reduce_sum(tf.math.log(p) * self.Y) # be sure to return a scalar\n\n\n# %% [markdown]\n# ...and that's it. Let's build a really simple demo to show that it works.\n\n# %%\nnp.random.seed(123)\nX = np.vstack(\n [\n np.random.randn(10, 2) + [2, 2],\n np.random.randn(10, 2) + [-2, 2],\n np.random.randn(10, 2) + [2, -2],\n ]\n)\nY = np.repeat(np.eye(3), 10, 0)\n\nfrom matplotlib import pyplot as plt\n\nplt.style.use(\"ggplot\")\n# %matplotlib inline\nimport matplotlib\n\nmatplotlib.rcParams[\"figure.figsize\"] = (12, 6)\n_ = plt.scatter(X[:, 0], X[:, 1], 100, np.argmax(Y, 1), lw=2, cmap=plt.cm.viridis)\n\n# %%\nm = LinearMulticlass(X, Y)\nm\n\n\n# %%\ndef closure():\n return -m.log_marginal_likelihood()\n\n\nopt = gpflow.optimizers.Scipy()\nopt.minimize(closure, variables=m.trainable_variables)\n\n# %%\nxx, yy = np.mgrid[-4:4:200j, -4:4:200j]\nX_test = np.vstack([xx.flatten(), yy.flatten()]).T\nf_test = np.dot(X_test, m.W.read_value()) + m.b.read_value()\np_test = np.exp(f_test)\np_test /= p_test.sum(1)[:, None]\n\n# %%\nplt.figure(figsize=(12, 6))\nfor i in range(3):\n plt.contour(xx, yy, p_test[:, i].reshape(200, 200), [0.5], colors=\"k\", linewidths=1)\n_ = plt.scatter(X[:, 0], X[:, 1], 100, np.argmax(Y, 1), lw=2, cmap=plt.cm.viridis)\n\n# %% [markdown]\n# That concludes the new model example and this notebook. You might want to see for yourself that the `LinearMulticlass` model and its parameters have all the functionality demonstrated here. You could also add some priors and run Hamiltonian Monte Carlo using the HMC optimizer `gpflow.train.HMC` and its `sample` method. See [Markov Chain Monte Carlo (MCMC)](../advanced/mcmc.ipynb) for more information on running the sampler.\n", "# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,.pct.py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.3.3\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown]\n# ## Sanity checking when model behaviours should overlap\n#\n# Many of the model classes in GPflow have overlapping behaviour in special cases. In this notebook, we fit some approximations to a model with a Gaussian likelihood, and make sure they're all the same.\n#\n# The models are:\n# - `GPR`: Full Gaussian process regression.\n#\n# - `VGP`: A Gaussian approximation with Variational Bayes.\n# Approximating a Gaussian posterior with a Gaussian should be exact.\n#\n# - `SVGP`: a sparse GP, with a Gaussian approximation. The inducing points are set to be at the data points, so again, should be exact.\n#\n# - `SVGP` (with whitened representation): As above, but with a rotation applied to whiten the representation of the process.\n#\n# - `SGPR`: A sparse GP with a *collapsed* posterior (Titsias 2009). Again, the inducing points are fixed to the data points.\n#\n# - `GPRFITC`: The FITC approximation. Again, the inducing points are fixed to the data points.\n#\n# In all cases the parameters are estimated by the method of maximum likelihood (or approximate maximum likelihood, as appropriate). The parameter estimates should all be the same.\n\n# %%\nimport gpflow\nimport numpy as np\nimport tensorflow as tf\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom gpflow import set_trainable\nfrom gpflow.config import default_float\nfrom gpflow.ci_utils import ci_niter\n\n# %matplotlib inline\nmatplotlib.rcParams[\"figure.figsize\"] = (12, 6)\n\n# %%\nnp.random.seed(0)\nX = np.random.rand(20, 1) * 10\nY = np.sin(X) + 0.9 * np.cos(X * 1.6) + np.random.randn(*X.shape) * 0.4\nXtest = np.random.rand(10, 1) * 10\n_ = plt.plot(X, Y, \"kx\", mew=2)\n\n# %%\ndata = (\n tf.convert_to_tensor(X, dtype=default_float()),\n tf.convert_to_tensor(Y, dtype=default_float()),\n)\ninducing_variable = tf.convert_to_tensor(X, dtype=default_float())\n\nm1 = gpflow.models.GPR(data, kernel=gpflow.kernels.SquaredExponential())\nm2 = gpflow.models.VGP(\n data, kernel=gpflow.kernels.SquaredExponential(), likelihood=gpflow.likelihoods.Gaussian()\n)\nm3 = gpflow.models.SVGP(\n gpflow.kernels.SquaredExponential(),\n gpflow.likelihoods.Gaussian(),\n inducing_variable,\n q_diag=False,\n)\nset_trainable(m3.inducing_variable, False)\n\nm4 = gpflow.models.SVGP(\n gpflow.kernels.SquaredExponential(),\n gpflow.likelihoods.Gaussian(),\n inducing_variable,\n q_diag=False,\n whiten=True,\n)\nset_trainable(m4.inducing_variable, False)\n\nm5 = gpflow.models.SGPR(\n data, kernel=gpflow.kernels.SquaredExponential(), inducing_variable=inducing_variable\n)\nset_trainable(m5.inducing_variable, False)\n\nm6 = gpflow.models.GPRFITC(\n data, kernel=gpflow.kernels.SquaredExponential(), inducing_variable=inducing_variable\n)\nset_trainable(m6.inducing_variable, False)\n\nmodels = [m1, m2, m3, m4, m5, m6]\n\n# %% [markdown]\n# Now, we optimize the models. For `GPR`, `SVGP`, and `GPRFITC`, this simply optimizes the hyperparameters (since the inducing points are fixed). For the variational models, this jointly maximises the lower bound to the marginal likelihood (Evidence Lower Bound, ELBO) with respect to the variational parameters and the kernel and likelihood hyperparameters.\n\n# %%\nfor m in models:\n opt = gpflow.optimizers.Scipy()\n if isinstance(m, gpflow.models.SVGP):\n loss_fn = lambda: -m.log_marginal_likelihood(data)\n else:\n loss_fn = lambda: -m.log_marginal_likelihood()\n loss_fn = tf.function(loss_fn)\n\n opt.minimize(loss_fn, variables=m.trainable_variables, options=dict(maxiter=ci_niter(1000)))\n\n\n# %% [markdown]\n# If everything worked as planned, the models should have the same:\n#\n# - prediction functions\n# - log (marginal) likelihood\n# - kernel parameters\n#\n# For the variational models, where we use a ELBO in place of the likelihood, the ELBO should be tight to the likelihood in the cases studied here.\n\n# %%\ndef plot(m, color, ax):\n xx = np.linspace(-1, 11, 100)[:, None]\n mu, var = m.predict_y(xx)\n ax.plot(xx, mu, color, lw=2)\n ax.fill_between(\n xx[:, 0],\n mu[:, 0] - 2 * np.sqrt(var[:, 0]),\n mu[:, 0] + 2 * np.sqrt(var[:, 0]),\n color=color,\n alpha=0.2,\n )\n ax.plot(X, Y, \"kx\", mew=2)\n ax.set_xlim(-1, 11)\n\n\nf, ax = plt.subplots(3, 2, sharex=True, sharey=True, figsize=(12, 9))\nplot(m1, \"C0\", ax[0, 0])\nplot(m2, \"C1\", ax[1, 0])\nplot(m3, \"C2\", ax[0, 1])\nplot(m4, \"C3\", ax[1, 1])\nplot(m5, \"C4\", ax[2, 0])\nplot(m6, \"C5\", ax[2, 1])\n\n# %% [markdown]\n# Here are the kernels and likelihoods, which show the fitted kernel parameters and noise variance:\n\n# %%\nfor m in models:\n print(m.__class__.__name__)\n print(f\" kernel lengthscale = {m.kernel.lengthscales.numpy():.5g}\")\n print(f\" kernel variance = {m.kernel.variance.numpy():.5}\")\n print(f\" likelihood variance = {m.likelihood.variance.numpy():.5}\")\n\n# %% [markdown]\n# Here are the likelihoods (or ELBOs):\n\n# %%\nfor m in models:\n if isinstance(m, gpflow.models.SVGP):\n print(f\"{m.__class__.__name__:30} {m.log_likelihood(data)}\")\n else:\n print(f\"{m.__class__.__name__:30} {m.log_likelihood()}\")\n", "# ---\n# jupyter:\n# jupytext:\n# formats: ipynb,.pct.py:percent\n# text_representation:\n# extension: .py\n# format_name: percent\n# format_version: '1.3'\n# jupytext_version: 1.3.3\n# kernelspec:\n# display_name: Python 3\n# language: python\n# name: python3\n# ---\n\n# %% [markdown]\n# # Bayesian Gaussian process latent variable model (Bayesian GPLVM)\n# This notebook shows how to use the Bayesian GPLVM model. This is an unsupervised learning method usually used for dimensionality reduction. For an in-depth overview of GPLVMs,see **[1, 2]**.\n\n# %%\nimport gpflow\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n\nimport gpflow\nfrom gpflow.utilities import ops, print_summary\nfrom gpflow.config import set_default_float, default_float, set_default_summary_fmt\nfrom gpflow.ci_utils import ci_niter\n\nset_default_float(np.float64)\nset_default_summary_fmt(\"notebook\")\n\n# %matplotlib inline\n\n# %% [markdown]\n# ## Data\n# We are using the \"three phase oil flow\" dataset used initially for demonstrating the Generative Topographic mapping from **[3]**.\n\n# %%\ndata = np.load(\"./data/three_phase_oil_flow.npz\")\n\n# %% [markdown]\n# Following the GPflow notation we assume this dataset has a shape of `[num_data, output_dim]`\n\n# %%\nY = tf.convert_to_tensor(data[\"Y\"], dtype=default_float())\n\n# %% [markdown]\n# Integer in $[0, 2]$ indicating to which class the data point belongs (shape `[num_data,]`). Not used for model fitting, only for plotting afterwards.\n\n# %%\nlabels = tf.convert_to_tensor(data[\"labels\"])\n\n# %%\nprint(\"Number of points: {} and Number of dimensions: {}\".format(Y.shape[0], Y.shape[1]))\n\n# %% [markdown]\n# ## Model construction\n#\n# We start by initializing the required variables:\n\n# %%\nlatent_dim = 2 # number of latent dimensions\nnum_inducing = 20 # number of inducing pts\nnum_data = Y.shape[0] # number of data points\n\n# %% [markdown]\n# Initialize via PCA:\n\n# %%\nX_mean_init = ops.pca_reduce(Y, latent_dim)\nX_var_init = tf.ones((num_data, latent_dim), dtype=default_float())\n\n# %% [markdown]\n# Pick inducing inputs randomly from dataset initialization:\n\n# %%\nnp.random.seed(1) # for reproducibility\ninducing_variable = tf.convert_to_tensor(\n np.random.permutation(X_mean_init.numpy())[:num_inducing], dtype=default_float()\n)\n\n# %% [markdown]\n# We construct a Squared Exponential (SE) kernel operating on the two-dimensional latent space.\n# The `ARD` parameter stands for Automatic Relevance Determination, which in practice means that\n# we learn a different lengthscale for each of the input dimensions. See [Manipulating kernels](../advanced/kernels.ipynb) for more information.\n\n# %%\nlengthscales = tf.convert_to_tensor([1.0] * latent_dim, dtype=default_float())\nkernel = gpflow.kernels.RBF(lengthscales=lengthscales)\n\n# %% [markdown]\n# We have all the necessary ingredients to construct the model. GPflow contains an implementation of the Bayesian GPLVM:\n\n# %%\ngplvm = gpflow.models.BayesianGPLVM(\n Y,\n X_data_mean=X_mean_init,\n X_data_var=X_var_init,\n kernel=kernel,\n inducing_variable=inducing_variable,\n)\n# Instead of passing an inducing_variable directly, we can also set the num_inducing_variables argument to an integer, which will randomly pick from the data.\n\n# %% [markdown]\n# We change the default likelihood variance, which is 1, to 0.01.\n\n# %%\ngplvm.likelihood.variance.assign(0.01)\n\n# %% [markdown]\n# Next we optimize the created model. Given that this model has a deterministic evidence lower bound (ELBO), we can use SciPy's L-BFGS-B optimizer.\n\n# %%\nopt = gpflow.optimizers.Scipy()\nmaxiter = ci_niter(1000)\n\n\[email protected]\ndef optimization_step():\n return -gplvm.log_marginal_likelihood()\n\n\n_ = opt.minimize(\n optimization_step,\n method=\"bfgs\",\n variables=gplvm.trainable_variables,\n options=dict(maxiter=maxiter),\n)\n\n# %% [markdown]\n# ## Model analysis\n# GPflow allows you to inspect the learned model hyperparameters.\n\n# %%\nprint_summary(gplvm)\n\n# %% [markdown]\n# ## Plotting vs. Principle Component Analysis (PCA)\n# The reduction of the dimensionality of the dataset to two dimensions allows us to visualize the learned manifold.\n# We compare the Bayesian GPLVM's latent space to the deterministic PCA's one.\n\n# %%\nX_pca = ops.pca_reduce(Y, latent_dim).numpy()\ngplvm_X_mean = gplvm.X_data_mean.numpy()\n\nf, ax = plt.subplots(1, 2, figsize=(10, 6))\n\nfor i in np.unique(labels):\n ax[0].scatter(X_pca[labels == i, 0], X_pca[labels == i, 1], label=i)\n ax[1].scatter(gplvm_X_mean[labels == i, 0], gplvm_X_mean[labels == i, 1], label=i)\n ax[0].set_title(\"PCA\")\n ax[1].set_title(\"Bayesian GPLVM\")\n\n# %%\n\n# %% [markdown]\n# ## References\n# \\[1\\] Lawrence, Neil D. 'Gaussian process latent variable models for visualization of high dimensional data'. *Advances in Neural Information Processing Systems*. 2004.\n#\n# \\[2\\] Titsias, Michalis, and Neil D. Lawrence. 'Bayesian Gaussian process latent variable model'. *Proceedings of the Thirteenth International Conference on Artificial Intelligence and Statistics*. 2010.\n#\n# \\[3\\] Bishop, Christopher M., and Gwilym D. James. 'Analysis of multiphase flows using dual-energy gamma densitometry and neural networks'. *Nuclear Instruments and Methods in Physics Research Section A: Accelerators, Spectrometers, Detectors and Associated Equipment* 327.2-3 (1993): 580-593.\n", "# Copyright 2019 the GPflow authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\nfrom numpy.testing import assert_allclose\n\nimport gpflow\nfrom gpflow.config import default_jitter\nfrom gpflow.mean_functions import Constant\n\nrng = np.random.RandomState(0)\n\n\nclass Datum:\n X = rng.rand(20, 1) * 10\n Y = np.sin(X) + 0.9 * np.cos(X * 1.6) + rng.randn(*X.shape) * 0.8\n Y = np.tile(Y, 2) # two identical columns\n Xtest = rng.rand(10, 1) * 10\n data = (X, Y)\n\n\nclass DatumVGP:\n N, Ns, DX, DY = 100, 10, 2, 2\n np.random.seed(1)\n X = np.random.randn(N, DX)\n Xs = np.random.randn(Ns, DX)\n Y = np.random.randn(N, DY)\n q_mu = np.random.randn(N, DY)\n q_sqrt = np.random.randn(DY, N, N)\n q_alpha = np.random.randn(N, DX)\n q_lambda = np.random.randn(N, DX) ** 2\n data = (X, Y)\n\n\nclass DatumUpper:\n X = np.random.rand(100, 1)\n Y = np.sin(1.5 * 2 * np.pi * X) + np.random.randn(*X.shape) * 0.1\n data = (X, Y)\n\n\ndef _create_full_gp_model():\n \"\"\"\n GP Regression\n \"\"\"\n full_gp_model = gpflow.models.GPR(\n (Datum.X, Datum.Y),\n kernel=gpflow.kernels.SquaredExponential(),\n mean_function=gpflow.mean_functions.Constant(),\n )\n\n opt = gpflow.optimizers.Scipy()\n\n @tf.function\n def full_gp_model_closure():\n return -full_gp_model.log_marginal_likelihood()\n\n opt.minimize(\n full_gp_model_closure,\n variables=full_gp_model.trainable_variables,\n options=dict(maxiter=300),\n )\n return full_gp_model\n\n\ndef _create_approximate_models():\n \"\"\"\n 1) Variational GP (with the likelihood set to Gaussian)\n 2) Sparse variational GP (likelihood is Gaussian, inducing points\n at the data)\n 3) Sparse variational GP (as above, but with the whitening rotation\n of the inducing variables)\n 4) Sparse variational GP Regression (as above, but there the inducing\n variables are 'collapsed' out, as in Titsias 2009)\n 5) FITC Sparse GP Regression\n \"\"\"\n model_1 = gpflow.models.VGP(\n (Datum.X, Datum.Y),\n gpflow.kernels.SquaredExponential(),\n likelihood=gpflow.likelihoods.Gaussian(),\n mean_function=gpflow.mean_functions.Constant(),\n )\n model_2 = gpflow.models.SVGP(\n gpflow.kernels.SquaredExponential(),\n gpflow.likelihoods.Gaussian(),\n inducing_variable=Datum.X.copy(),\n q_diag=False,\n mean_function=gpflow.mean_functions.Constant(),\n num_latent_gps=Datum.Y.shape[1],\n )\n gpflow.set_trainable(model_2.inducing_variable, False)\n model_3 = gpflow.models.SVGP(\n kernel=gpflow.kernels.SquaredExponential(),\n likelihood=gpflow.likelihoods.Gaussian(),\n inducing_variable=Datum.X.copy(),\n q_diag=False,\n whiten=True,\n mean_function=gpflow.mean_functions.Constant(),\n num_latent_gps=Datum.Y.shape[1],\n )\n gpflow.set_trainable(model_3.inducing_variable, False)\n model_4 = gpflow.models.GPRFITC(\n (Datum.X, Datum.Y),\n kernel=gpflow.kernels.SquaredExponential(),\n inducing_variable=Datum.X.copy(),\n mean_function=Constant(),\n )\n gpflow.set_trainable(model_4.inducing_variable, False)\n model_5 = gpflow.models.SGPR(\n (Datum.X, Datum.Y),\n gpflow.kernels.SquaredExponential(),\n inducing_variable=Datum.X.copy(),\n mean_function=Constant(),\n )\n gpflow.set_trainable(model_5.inducing_variable, False)\n\n # Train models\n\n opt = gpflow.optimizers.Scipy()\n\n @tf.function\n def model_1_closure():\n return -model_1.log_marginal_likelihood()\n\n @tf.function\n def model_2_closure():\n return -model_2.elbo(Datum.data)\n\n @tf.function\n def model_3_closure():\n return -model_3.elbo(Datum.data)\n\n @tf.function\n def model_4_closure():\n return -model_4.log_marginal_likelihood()\n\n @tf.function\n def model_5_closure():\n return -model_5.log_marginal_likelihood()\n\n opt.minimize(\n model_1_closure, variables=model_1.trainable_variables, options=dict(maxiter=300),\n )\n opt.minimize(\n model_2_closure, variables=model_2.trainable_variables, options=dict(maxiter=300),\n )\n opt.minimize(\n model_3_closure, variables=model_3.trainable_variables, options=dict(maxiter=300),\n )\n opt.minimize(\n model_4_closure, variables=model_4.trainable_variables, options=dict(maxiter=300),\n )\n opt.minimize(\n model_5_closure, variables=model_5.trainable_variables, options=dict(maxiter=300),\n )\n\n return model_1, model_2, model_3, model_4, model_5\n\n\ndef _create_vgp_model(kernel, likelihood, q_mu=None, q_sqrt=None):\n model_vgp = gpflow.models.VGP((DatumVGP.X, DatumVGP.Y), kernel, likelihood)\n if q_mu is not None and q_sqrt is not None:\n model_vgp.q_mu.assign(q_mu)\n model_vgp.q_sqrt.assign(q_sqrt)\n return model_vgp\n\n\ndef _create_vgpao_model(kernel, likelihood, q_alpha, q_lambda):\n model_vgpoa = gpflow.models.VGPOpperArchambeau(\n (DatumVGP.X, DatumVGP.Y), kernel, likelihood, num_latent_gps=DatumVGP.DY\n )\n model_vgpoa.q_alpha.assign(q_alpha)\n model_vgpoa.q_lambda.assign(q_lambda)\n return model_vgpoa\n\n\ndef _create_svgp_model(kernel, likelihood, q_mu, q_sqrt, whiten):\n model_svgp = gpflow.models.SVGP(\n kernel,\n likelihood,\n DatumVGP.X.copy(),\n whiten=whiten,\n q_diag=False,\n num_latent_gps=DatumVGP.DY,\n )\n model_svgp.q_mu.assign(q_mu)\n model_svgp.q_sqrt.assign(q_sqrt)\n return model_svgp\n\n\[email protected](\"approximate_model\", _create_approximate_models())\ndef test_equivalence(approximate_model):\n \"\"\"\n With a Gaussian likelihood, and inducing points (where appropriate)\n positioned at the data, many of the gpflow methods are equivalent (perhaps\n subject to some optimization).\n \"\"\"\n gpr_model = _create_full_gp_model()\n gpr_likelihood = -gpr_model.log_likelihood()\n if isinstance(approximate_model, gpflow.models.SVGP):\n approximate_likelihood = -approximate_model.log_likelihood(Datum.data)\n else:\n approximate_likelihood = -approximate_model.log_likelihood()\n\n assert_allclose(gpr_likelihood, approximate_likelihood, rtol=1e-6)\n\n gpr_kernel_ls = gpr_model.kernel.lengthscales.read_value()\n gpr_kernel_var = gpr_model.kernel.variance.read_value()\n\n approximate_kernel_ls = approximate_model.kernel.lengthscales.read_value()\n approximate_kernel_var = approximate_model.kernel.variance.read_value()\n\n assert_allclose(gpr_kernel_ls, approximate_kernel_ls, 1e-4)\n assert_allclose(gpr_kernel_var, approximate_kernel_var, 1e-3)\n\n gpr_mu, gpr_var = gpr_model.predict_y(Datum.Xtest)\n approximate_mu, approximate_var = approximate_model.predict_y(Datum.Xtest)\n\n assert_allclose(gpr_mu, approximate_mu, 1e-3)\n assert_allclose(gpr_var, approximate_var, 1e-4)\n\n\ndef test_equivalence_vgp_and_svgp():\n kernel = gpflow.kernels.Matern52()\n likelihood = gpflow.likelihoods.StudentT()\n\n svgp_model = _create_svgp_model(kernel, likelihood, DatumVGP.q_mu, DatumVGP.q_sqrt, whiten=True)\n vgp_model = _create_vgp_model(kernel, likelihood, DatumVGP.q_mu, DatumVGP.q_sqrt)\n\n likelihood_svgp = svgp_model.log_likelihood(DatumVGP.data)\n likelihood_vgp = vgp_model.log_likelihood()\n assert_allclose(likelihood_svgp, likelihood_vgp, rtol=1e-2)\n\n svgp_mu, svgp_var = svgp_model.predict_f(DatumVGP.Xs)\n vgp_mu, vgp_var = vgp_model.predict_f(DatumVGP.Xs)\n\n assert_allclose(svgp_mu, vgp_mu)\n assert_allclose(svgp_var, vgp_var)\n\n\ndef test_equivalence_vgp_and_opper_archambeau():\n kernel = gpflow.kernels.Matern52()\n likelihood = gpflow.likelihoods.StudentT()\n\n vgp_oa_model = _create_vgpao_model(kernel, likelihood, DatumVGP.q_alpha, DatumVGP.q_lambda)\n\n K = kernel(DatumVGP.X) + np.eye(DatumVGP.N) * default_jitter()\n L = np.linalg.cholesky(K)\n L_inv = np.linalg.inv(L)\n K_inv = np.linalg.inv(K)\n\n mean = K @ DatumVGP.q_alpha\n\n prec_dnn = K_inv[None, :, :] + np.array([np.diag(l ** 2) for l in DatumVGP.q_lambda.T])\n var_dnn = np.linalg.inv(prec_dnn)\n\n svgp_model_unwhitened = _create_svgp_model(\n kernel, likelihood, mean, np.linalg.cholesky(var_dnn), whiten=False\n )\n\n mean_white_nd = L_inv.dot(mean)\n var_white_dnn = np.einsum(\"nN,dNM,mM->dnm\", L_inv, var_dnn, L_inv)\n q_sqrt_nnd = np.linalg.cholesky(var_white_dnn)\n\n vgp_model = _create_vgp_model(kernel, likelihood, mean_white_nd, q_sqrt_nnd)\n\n likelihood_vgp = vgp_model.log_likelihood()\n likelihood_vgp_oa = vgp_oa_model.log_likelihood()\n likelihood_svgp_unwhitened = svgp_model_unwhitened.log_likelihood(DatumVGP.data)\n\n assert_allclose(likelihood_vgp, likelihood_vgp_oa, rtol=1e-2)\n assert_allclose(likelihood_vgp, likelihood_svgp_unwhitened, rtol=1e-2)\n\n vgp_oa_mu, vgp_oa_var = vgp_oa_model.predict_f(DatumVGP.Xs)\n svgp_unwhitened_mu, svgp_unwhitened_var = svgp_model_unwhitened.predict_f(DatumVGP.Xs)\n vgp_mu, vgp_var = vgp_model.predict_f(DatumVGP.Xs)\n\n assert_allclose(vgp_oa_mu, vgp_mu)\n assert_allclose(vgp_oa_var, vgp_var, rtol=1e-4) # jitter?\n assert_allclose(svgp_unwhitened_mu, vgp_mu)\n assert_allclose(svgp_unwhitened_var, vgp_var, rtol=1e-4)\n\n\ndef test_upper_bound_few_inducing_points():\n \"\"\"\n Test for upper bound for regression marginal likelihood\n \"\"\"\n model_vfe = gpflow.models.SGPR(\n (DatumUpper.X, DatumUpper.Y),\n gpflow.kernels.SquaredExponential(),\n inducing_variable=DatumUpper.X[:10, :].copy(),\n mean_function=Constant(),\n )\n opt = gpflow.optimizers.Scipy()\n\n @tf.function\n def model_vfe_closure():\n return -model_vfe.log_marginal_likelihood()\n\n opt.minimize(\n model_vfe_closure, variables=model_vfe.trainable_variables, options=dict(maxiter=500),\n )\n\n full_gp = gpflow.models.GPR(\n (DatumUpper.X, DatumUpper.Y),\n kernel=gpflow.kernels.SquaredExponential(),\n mean_function=Constant(),\n )\n full_gp.kernel.lengthscales.assign(model_vfe.kernel.lengthscales)\n full_gp.kernel.variance.assign(model_vfe.kernel.variance)\n full_gp.likelihood.variance.assign(model_vfe.likelihood.variance)\n full_gp.mean_function.c.assign(model_vfe.mean_function.c)\n\n lml_upper = model_vfe.upper_bound()\n lml_vfe = model_vfe.log_marginal_likelihood()\n lml_full_gp = full_gp.log_marginal_likelihood()\n\n assert lml_vfe < lml_full_gp\n assert lml_full_gp < lml_upper\n" ]
[ [ "tensorflow.matmul", "numpy.random.seed", "numpy.eye", "numpy.cos", "numpy.sin", "tensorflow.math.log", "numpy.argmax", "numpy.random.randn", "numpy.random.rand", "numpy.exp", "matplotlib.pyplot.style.use", "matplotlib.pyplot.figure" ], [ "numpy.sqrt", "numpy.random.seed", "numpy.linspace", "matplotlib.pyplot.subplots", "numpy.cos", "numpy.sin", "matplotlib.pyplot.plot", "tensorflow.function", "numpy.random.randn", "numpy.random.rand" ], [ "tensorflow.convert_to_tensor", "numpy.random.seed", "numpy.unique", "matplotlib.pyplot.subplots", "numpy.load" ], [ "numpy.diag", "numpy.linalg.cholesky", "numpy.random.seed", "numpy.einsum", "numpy.linalg.inv", "numpy.eye", "numpy.tile", "numpy.cos", "numpy.sin", "numpy.random.randn", "numpy.random.rand", "numpy.testing.assert_allclose", "numpy.random.RandomState" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "2.7", "2.6", "2.2", "2.3", "2.4", "2.9", "2.5", "2.8", "2.10" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [ "1.10", "1.12", "1.4", "1.13", "1.5", "1.7", "0.12", "1.0", "1.2" ] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
autt/gathering-leto
[ "37894d8d8ad0381a2aacbb38593325a882b030f5" ]
[ "src/data/data/__init__.py" ]
[ "import github\nimport pandas as pd\n\n\ndef get_issues(repo_addr):\n g = github.Github()\n repo = g.get_repo(repo_addr)\n return repo.get_issues()\n\n\ndef fetch_issue_activity(repo_addr):\n g = github.Github()\n issues = g.get_repo(repo_addr).get_issues(state=\"all\")\n\n events = []\n for issue in issues:\n if issue.pull_request is not None:\n continue\n\n events.append((issue.created_at, 1))\n if issue.state == \"closed\":\n events.append((issue.closed_at, -1))\n\n df = pd.DataFrame(events, columns=[\"date\", \"action\"])\n\n df.sort_values(\"date\", inplace=True)\n df[\"open\"] = df[\"action\"].cumsum()\n df[\"total_events\"] = abs(df[\"action\"]).cumsum()\n df[\"closed\"] = (df[\"total_events\"] - df[\"open\"]) // 2\n\n return df\n" ]
[ [ "pandas.DataFrame" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [ "0.23", "0.21", "2.0", "1.4", "0.19", "1.1", "1.5", "1.2", "0.24", "0.20", "1.0", "0.25", "1.3" ], "scipy": [], "tensorflow": [] } ]
gasteigerjo/gdc
[ "996bc47acffd86bc9bb1df3293c87a3c7573744f" ]
[ "data.py" ]
[ "__author__ = \"Stefan Weißenberger and Johannes Gasteiger\"\r\n__license__ = \"MIT\"\r\n\r\nimport os\r\n\r\nimport numpy as np\r\nfrom scipy.linalg import expm\r\n\r\nimport torch\r\nfrom torch_geometric.data import Data, InMemoryDataset\r\nfrom torch_geometric.datasets import Planetoid, Amazon, Coauthor\r\n\r\nfrom seeds import development_seed\r\n\r\n\r\nDATA_PATH = 'data'\r\n\r\n\r\ndef get_dataset(name: str, use_lcc: bool = True) -> InMemoryDataset:\r\n path = os.path.join(DATA_PATH, name)\r\n if name in ['Cora', 'Citeseer', 'Pubmed']:\r\n dataset = Planetoid(path, name)\r\n elif name in ['Computers', 'Photo']:\r\n dataset = Amazon(path, name)\r\n elif name == 'CoauthorCS':\r\n dataset = Coauthor(path, 'CS')\r\n else:\r\n raise Exception('Unknown dataset.')\r\n\r\n if use_lcc:\r\n lcc = get_largest_connected_component(dataset)\r\n\r\n x_new = dataset.data.x[lcc]\r\n y_new = dataset.data.y[lcc]\r\n\r\n row, col = dataset.data.edge_index.numpy()\r\n edges = [[i, j] for i, j in zip(row, col) if i in lcc and j in lcc]\r\n edges = remap_edges(edges, get_node_mapper(lcc))\r\n \r\n data = Data(\r\n x=x_new,\r\n edge_index=torch.LongTensor(edges),\r\n y=y_new,\r\n train_mask=torch.zeros(y_new.size()[0], dtype=torch.bool),\r\n test_mask=torch.zeros(y_new.size()[0], dtype=torch.bool),\r\n val_mask=torch.zeros(y_new.size()[0], dtype=torch.bool)\r\n )\r\n dataset.data = data\r\n\r\n return dataset\r\n\r\n\r\ndef get_component(dataset: InMemoryDataset, start: int = 0) -> set:\r\n visited_nodes = set()\r\n queued_nodes = set([start])\r\n row, col = dataset.data.edge_index.numpy()\r\n while queued_nodes:\r\n current_node = queued_nodes.pop()\r\n visited_nodes.update([current_node])\r\n neighbors = col[np.where(row == current_node)[0]]\r\n neighbors = [n for n in neighbors if n not in visited_nodes and n not in queued_nodes]\r\n queued_nodes.update(neighbors)\r\n return visited_nodes\r\n\r\n\r\ndef get_largest_connected_component(dataset: InMemoryDataset) -> np.ndarray:\r\n remaining_nodes = set(range(dataset.data.x.shape[0]))\r\n comps = []\r\n while remaining_nodes:\r\n start = min(remaining_nodes)\r\n comp = get_component(dataset, start)\r\n comps.append(comp)\r\n remaining_nodes = remaining_nodes.difference(comp)\r\n return np.array(list(comps[np.argmax(list(map(len, comps)))]))\r\n\r\n\r\ndef get_node_mapper(lcc: np.ndarray) -> dict:\r\n mapper = {}\r\n counter = 0\r\n for node in lcc:\r\n mapper[node] = counter\r\n counter += 1\r\n return mapper\r\n\r\n\r\ndef remap_edges(edges: list, mapper: dict) -> list:\r\n row = [e[0] for e in edges]\r\n col = [e[1] for e in edges]\r\n row = list(map(lambda x: mapper[x], row))\r\n col = list(map(lambda x: mapper[x], col))\r\n return [row, col]\r\n\r\n\r\ndef get_adj_matrix(dataset: InMemoryDataset) -> np.ndarray:\r\n num_nodes = dataset.data.x.shape[0]\r\n adj_matrix = np.zeros(shape=(num_nodes, num_nodes))\r\n for i, j in zip(dataset.data.edge_index[0], dataset.data.edge_index[1]):\r\n adj_matrix[i, j] = 1.\r\n return adj_matrix\r\n\r\n\r\ndef get_ppr_matrix(\r\n adj_matrix: np.ndarray,\r\n alpha: float = 0.1) -> np.ndarray:\r\n num_nodes = adj_matrix.shape[0]\r\n A_tilde = adj_matrix + np.eye(num_nodes)\r\n D_tilde = np.diag(1/np.sqrt(A_tilde.sum(axis=1)))\r\n H = D_tilde @ A_tilde @ D_tilde\r\n return alpha * np.linalg.inv(np.eye(num_nodes) - (1 - alpha) * H)\r\n\r\n\r\ndef get_heat_matrix(\r\n adj_matrix: np.ndarray,\r\n t: float = 5.0) -> np.ndarray:\r\n num_nodes = adj_matrix.shape[0]\r\n A_tilde = adj_matrix + np.eye(num_nodes)\r\n D_tilde = np.diag(1/np.sqrt(A_tilde.sum(axis=1)))\r\n H = D_tilde @ A_tilde @ D_tilde\r\n return expm(-t * (np.eye(num_nodes) - H))\r\n\r\n\r\ndef get_top_k_matrix(A: np.ndarray, k: int = 128) -> np.ndarray:\r\n num_nodes = A.shape[0]\r\n row_idx = np.arange(num_nodes)\r\n A[A.argsort(axis=0)[:num_nodes - k], row_idx] = 0.\r\n norm = A.sum(axis=0)\r\n norm[norm <= 0] = 1 # avoid dividing by zero\r\n return A/norm\r\n\r\n\r\ndef get_clipped_matrix(A: np.ndarray, eps: float = 0.01) -> np.ndarray:\r\n num_nodes = A.shape[0]\r\n A[A < eps] = 0.\r\n norm = A.sum(axis=0)\r\n norm[norm <= 0] = 1 # avoid dividing by zero\r\n return A/norm\r\n\r\n\r\ndef set_train_val_test_split(\r\n seed: int,\r\n data: Data,\r\n num_development: int = 1500,\r\n num_per_class: int = 20) -> Data:\r\n rnd_state = np.random.RandomState(development_seed)\r\n num_nodes = data.y.shape[0]\r\n development_idx = rnd_state.choice(num_nodes, num_development, replace=False)\r\n test_idx = [i for i in np.arange(num_nodes) if i not in development_idx]\r\n\r\n train_idx = []\r\n rnd_state = np.random.RandomState(seed)\r\n for c in range(data.y.max() + 1):\r\n class_idx = development_idx[np.where(data.y[development_idx].cpu() == c)[0]]\r\n train_idx.extend(rnd_state.choice(class_idx, num_per_class, replace=False))\r\n\r\n val_idx = [i for i in development_idx if i not in train_idx]\r\n\r\n def get_mask(idx):\r\n mask = torch.zeros(num_nodes, dtype=torch.bool)\r\n mask[idx] = 1\r\n return mask\r\n\r\n data.train_mask = get_mask(train_idx)\r\n data.val_mask = get_mask(val_idx)\r\n data.test_mask = get_mask(test_idx)\r\n\r\n return data\r\n\r\n\r\nclass PPRDataset(InMemoryDataset):\r\n \"\"\"\r\n Dataset preprocessed with GDC using PPR diffusion.\r\n Note that this implementations is not scalable\r\n since we directly invert the adjacency matrix.\r\n \"\"\"\r\n def __init__(self,\r\n name: str = 'Cora',\r\n use_lcc: bool = True,\r\n alpha: float = 0.1,\r\n k: int = 16,\r\n eps: float = None):\r\n self.name = name\r\n self.use_lcc = use_lcc\r\n self.alpha = alpha\r\n self.k = k\r\n self.eps = eps\r\n\r\n super(PPRDataset, self).__init__(DATA_PATH)\r\n self.data, self.slices = torch.load(self.processed_paths[0])\r\n\r\n @property\r\n def raw_file_names(self) -> list:\r\n return []\r\n\r\n @property\r\n def processed_file_names(self) -> list:\r\n return [str(self) + '.pt']\r\n\r\n def download(self):\r\n pass\r\n\r\n def process(self):\r\n base = get_dataset(name=self.name, use_lcc=self.use_lcc)\r\n # generate adjacency matrix from sparse representation\r\n adj_matrix = get_adj_matrix(base)\r\n # obtain exact PPR matrix\r\n ppr_matrix = get_ppr_matrix(adj_matrix,\r\n alpha=self.alpha)\r\n\r\n if self.k:\r\n print(f'Selecting top {self.k} edges per node.')\r\n ppr_matrix = get_top_k_matrix(ppr_matrix, k=self.k)\r\n elif self.eps:\r\n print(f'Selecting edges with weight greater than {self.eps}.')\r\n ppr_matrix = get_clipped_matrix(ppr_matrix, eps=self.eps)\r\n else:\r\n raise ValueError\r\n\r\n # create PyG Data object\r\n edges_i = []\r\n edges_j = []\r\n edge_attr = []\r\n for i, row in enumerate(ppr_matrix):\r\n for j in np.where(row > 0)[0]:\r\n edges_i.append(i)\r\n edges_j.append(j)\r\n edge_attr.append(ppr_matrix[i, j])\r\n edge_index = [edges_i, edges_j]\r\n\r\n data = Data(\r\n x=base.data.x,\r\n edge_index=torch.LongTensor(edge_index),\r\n edge_attr=torch.FloatTensor(edge_attr),\r\n y=base.data.y,\r\n train_mask=torch.zeros(base.data.train_mask.size()[0], dtype=torch.bool),\r\n test_mask=torch.zeros(base.data.test_mask.size()[0], dtype=torch.bool),\r\n val_mask=torch.zeros(base.data.val_mask.size()[0], dtype=torch.bool)\r\n )\r\n\r\n data, slices = self.collate([data])\r\n torch.save((data, slices), self.processed_paths[0])\r\n\r\n def __str__(self) -> str:\r\n return f'{self.name}_ppr_alpha={self.alpha}_k={self.k}_eps={self.eps}_lcc={self.use_lcc}'\r\n\r\n\r\nclass HeatDataset(InMemoryDataset):\r\n \"\"\"\r\n Dataset preprocessed with GDC using heat kernel diffusion.\r\n Note that this implementations is not scalable\r\n since we directly calculate the matrix exponential\r\n of the adjacency matrix.\r\n \"\"\"\r\n def __init__(self,\r\n name: str = 'Cora',\r\n use_lcc: bool = True,\r\n t: float = 5.0,\r\n k: int = 16,\r\n eps: float = None):\r\n self.name = name\r\n self.use_lcc = use_lcc\r\n self.t = t\r\n self.k = k\r\n self.eps = eps\r\n\r\n super(HeatDataset, self).__init__(DATA_PATH)\r\n self.data, self.slices = torch.load(self.processed_paths[0])\r\n\r\n @property\r\n def raw_file_names(self) -> list:\r\n return []\r\n\r\n @property\r\n def processed_file_names(self) -> list:\r\n return [str(self) + '.pt']\r\n\r\n def download(self):\r\n pass\r\n\r\n def process(self):\r\n base = get_dataset(name=self.name, use_lcc=self.use_lcc)\r\n # generate adjacency matrix from sparse representation\r\n adj_matrix = get_adj_matrix(base)\r\n # get heat matrix as described in Berberidis et al., 2019\r\n heat_matrix = get_heat_matrix(adj_matrix,\r\n t=self.t)\r\n if self.k:\r\n print(f'Selecting top {self.k} edges per node.')\r\n heat_matrix = get_top_k_matrix(heat_matrix, k=self.k)\r\n elif self.eps:\r\n print(f'Selecting edges with weight greater than {self.eps}.')\r\n heat_matrix = get_clipped_matrix(heat_matrix, eps=self.eps)\r\n else:\r\n raise ValueError\r\n\r\n # create PyG Data object\r\n edges_i = []\r\n edges_j = []\r\n edge_attr = []\r\n for i, row in enumerate(heat_matrix):\r\n for j in np.where(row > 0)[0]:\r\n edges_i.append(i)\r\n edges_j.append(j)\r\n edge_attr.append(heat_matrix[i, j])\r\n edge_index = [edges_i, edges_j]\r\n\r\n data = Data(\r\n x=base.data.x,\r\n edge_index=torch.LongTensor(edge_index),\r\n edge_attr=torch.FloatTensor(edge_attr),\r\n y=base.data.y,\r\n train_mask=torch.zeros(base.data.train_mask.size()[0], dtype=torch.bool),\r\n test_mask=torch.zeros(base.data.test_mask.size()[0], dtype=torch.bool),\r\n val_mask=torch.zeros(base.data.val_mask.size()[0], dtype=torch.bool)\r\n )\r\n\r\n data, slices = self.collate([data])\r\n torch.save((data, slices), self.processed_paths[0])\r\n\r\n def __str__(self) -> str:\r\n return f'{self.name}_heat_t={self.t}_k={self.k}_eps={self.eps}_lcc={self.use_lcc}'\r\n" ]
[ [ "torch.LongTensor", "torch.zeros", "torch.load", "numpy.arange", "numpy.eye", "torch.FloatTensor", "numpy.random.RandomState", "numpy.zeros", "numpy.where", "torch.save" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
showerhhh/ComplexNetwork
[ "344fadee4e85924f45263a43d2110dae2a9394fe" ]
[ "homework_3/main.py" ]
[ "import functools\nimport os\nimport random\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n\ndef make_graph(path):\n G = nx.DiGraph()\n\n with open(path, 'r') as f:\n lines = f.readlines()\n # random.seed(0)\n sample_nums = int(len(lines) * 0.00006)\n lines = random.sample(lines, sample_nums)\n lines = [line.strip() for line in lines]\n for line in lines:\n edge_node = line.split('\t')\n source = int(edge_node[0])\n target = int(edge_node[1])\n G.add_edge(source, target)\n return G\n\n\ndef degree_centrality(G):\n # 节点的度中心性\n if len(G) <= 1:\n return {n: 1 for n in G}\n\n s = 1.0 / (len(G) - 1.0)\n centrality = {n: d * s for n, d in G.degree()}\n return centrality\n\n\ndef closeness_centrality(G, u=None, distance=None, wf_improved=True):\n # 节点的接近中心性\n if G.is_directed():\n G = G.reverse()\n\n if distance is not None:\n path_length = functools.partial(\n nx.single_source_dijkstra_path_length, weight=distance\n )\n else:\n path_length = nx.single_source_shortest_path_length\n\n if u is None:\n nodes = G.nodes\n else:\n nodes = [u]\n closeness_centrality = {}\n for n in nodes:\n sp = path_length(G, n)\n totsp = sum(sp.values())\n len_G = len(G)\n _closeness_centrality = 0.0\n if totsp > 0.0 and len_G > 1:\n _closeness_centrality = (len(sp) - 1.0) / totsp\n if wf_improved:\n s = (len(sp) - 1.0) / (len_G - 1)\n _closeness_centrality *= s\n closeness_centrality[n] = _closeness_centrality\n if u is not None:\n return closeness_centrality[u]\n else:\n return closeness_centrality\n\n\ndef core_number(G):\n # 节点的核数\n degrees = dict(G.degree())\n nodes = sorted(degrees, key=degrees.get)\n bin_boundaries = [0]\n curr_degree = 0\n for i, v in enumerate(nodes):\n if degrees[v] > curr_degree:\n bin_boundaries.extend([i] * (degrees[v] - curr_degree))\n curr_degree = degrees[v]\n node_pos = {v: pos for pos, v in enumerate(nodes)}\n core = degrees\n nbrs = {v: list(nx.all_neighbors(G, v)) for v in G}\n for v in nodes:\n for u in nbrs[v]:\n if core[u] > core[v]:\n nbrs[u].remove(v)\n pos = node_pos[u]\n bin_start = bin_boundaries[core[u]]\n node_pos[u] = bin_start\n node_pos[nodes[bin_start]] = pos\n nodes[bin_start], nodes[pos] = nodes[pos], nodes[bin_start]\n bin_boundaries[core[u]] += 1\n core[u] -= 1\n return core\n\n\ndef pagerank(G, alpha=0.85, personalization=None, max_iter=100, tol=1.0e-6, nstart=None, weight=\"weight\",\n dangling=None):\n # 节点的pagerank值\n if len(G) == 0:\n return {}\n\n if not G.is_directed():\n D = G.to_directed()\n else:\n D = G\n\n W = nx.stochastic_graph(D, weight=weight)\n N = W.number_of_nodes()\n\n if nstart is None:\n x = dict.fromkeys(W, 1.0 / N)\n else:\n s = float(sum(nstart.values()))\n x = {k: v / s for k, v in nstart.items()}\n\n if personalization is None:\n p = dict.fromkeys(W, 1.0 / N)\n else:\n s = float(sum(personalization.values()))\n p = {k: v / s for k, v in personalization.items()}\n\n if dangling is None:\n dangling_weights = p\n else:\n s = float(sum(dangling.values()))\n dangling_weights = {k: v / s for k, v in dangling.items()}\n dangling_nodes = [n for n in W if W.out_degree(n, weight=weight) == 0.0]\n\n for _ in range(max_iter):\n xlast = x\n x = dict.fromkeys(xlast.keys(), 0)\n danglesum = alpha * sum(xlast[n] for n in dangling_nodes)\n for n in x:\n for nbr in W[n]:\n x[nbr] += alpha * xlast[n] * W[n][nbr][weight]\n x[n] += danglesum * dangling_weights.get(n, 0) + (1.0 - alpha) * p.get(n, 0)\n err = sum([abs(x[n] - xlast[n]) for n in x])\n if err < N * tol:\n return x\n raise nx.PowerIterationFailedConvergence(max_iter)\n\n\ndef hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True):\n # 节点的hub值和authority值\n if len(G) == 0:\n return {}, {}\n if nstart is None:\n h = dict.fromkeys(G, 1.0 / G.number_of_nodes())\n else:\n h = nstart\n s = 1.0 / sum(h.values())\n for k in h:\n h[k] *= s\n for _ in range(max_iter):\n hlast = h\n h = dict.fromkeys(hlast.keys(), 0)\n a = dict.fromkeys(hlast.keys(), 0)\n for n in h:\n for nbr in G[n]:\n a[nbr] += hlast[n] * G[n][nbr].get(\"weight\", 1)\n for n in h:\n for nbr in G[n]:\n h[n] += a[nbr] * G[n][nbr].get(\"weight\", 1)\n s = 1.0 / max(h.values())\n for n in h:\n h[n] *= s\n s = 1.0 / max(a.values())\n for n in a:\n a[n] *= s\n err = sum([abs(h[n] - hlast[n]) for n in h])\n if err < tol:\n break\n else:\n raise nx.PowerIterationFailedConvergence(max_iter)\n if normalized:\n s = 1.0 / sum(a.values())\n for n in a:\n a[n] *= s\n s = 1.0 / sum(h.values())\n for n in h:\n h[n] *= s\n return h, a\n\n\ndef metrics_fuse(G):\n degree = degree_centrality(G)\n closeness = closeness_centrality(G)\n betweenness = nx.betweenness_centrality(G) # 节点的介数中心性\n core = core_number(G)\n pageranks = pagerank(G)\n hubs, authorities = hits(G)\n\n fused = dict()\n for node in G.nodes:\n deg = degree[node]\n cl = closeness[node]\n bet = betweenness[node]\n co = core[node]\n pr = pageranks[node]\n auth = authorities[node]\n M = 0.05 * deg + 0.15 * cl + 0.1 * bet + 0.3 * co + 0.25 * pr + 0.15 * auth\n fused[node] = M\n\n pageranks = sorted(pageranks.items(), key=lambda x: x[1], reverse=True)\n print(\"使用PageRank算法,影响力前10的节点为:\")\n for i in range(10):\n print(\"节点 {}\".format(pageranks[i][0]))\n pos = nx.random_layout(G)\n top_nodes = [k for k, v in pageranks[:10]]\n other_nodes = [k for k, v in pageranks[10:]]\n nx.draw_networkx_nodes(G, pos, top_nodes, node_size=200, node_color='Red', alpha=0.6)\n nx.draw_networkx_nodes(G, pos, other_nodes, node_size=200, node_color='Green', alpha=0.6)\n nx.draw_networkx_edges(G, pos)\n labels = dict()\n for k, v in pageranks[:10]:\n labels[k] = k\n nx.draw_networkx_labels(G, pos, labels=labels)\n plt.savefig(\"./pagerank_result.png\")\n plt.show()\n print(\"---------------------------------------------\")\n\n authorities = sorted(authorities.items(), key=lambda x: x[1], reverse=True)\n print(\"使用HITS算法,影响力前10的节点为:\")\n for i in range(10):\n print(\"节点 {}\".format(authorities[i][0]))\n pos = nx.random_layout(G)\n top_nodes = [k for k, v in authorities[:10]]\n other_nodes = [k for k, v in authorities[10:]]\n nx.draw_networkx_nodes(G, pos, top_nodes, node_size=200, node_color='Red', alpha=0.6)\n nx.draw_networkx_nodes(G, pos, other_nodes, node_size=200, node_color='Green', alpha=0.6)\n nx.draw_networkx_edges(G, pos)\n labels = dict()\n for k, v in authorities[:10]:\n labels[k] = k\n nx.draw_networkx_labels(G, pos, labels=labels)\n plt.savefig(\"./hits_result.png\")\n plt.show()\n print(\"---------------------------------------------\")\n\n fused = sorted(fused.items(), key=lambda x: x[1], reverse=True)\n print(\"使用混合算法,影响力前10的节点为:\")\n for i in range(10):\n print(\"节点 {}\".format(fused[i][0]))\n pos = nx.random_layout(G)\n top_nodes = [k for k, v in fused[:10]]\n other_nodes = [k for k, v in fused[10:]]\n nx.draw_networkx_nodes(G, pos, top_nodes, node_size=200, node_color='Red', alpha=0.6)\n nx.draw_networkx_nodes(G, pos, other_nodes, node_size=200, node_color='Green', alpha=0.6)\n nx.draw_networkx_edges(G, pos)\n labels = dict()\n for k, v in fused[:10]:\n labels[k] = k\n nx.draw_networkx_labels(G, pos, labels=labels)\n plt.savefig(\"./fused_result.png\")\n plt.show()\n print(\"---------------------------------------------\")\n\n return fused\n\n\nif __name__ == '__main__':\n path = './课程设计数据集.txt'\n if not os.path.exists(path):\n print('未找到数据集')\n exit(1)\n G = make_graph(path)\n metrics_fuse(G)\n" ]
[ [ "matplotlib.pyplot.show", "matplotlib.pyplot.savefig" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
comeCU/coding-python
[ "3a35e67f5a92c32734b93b5503e5b08bc63b06bd" ]
[ "funnyPython/test_wordcloud.py" ]
[ "#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n\n# 生成词云\n'''\nReference:\n https://amueller.github.io/word_cloud/\n \thttps://github.com/amueller/word_cloud\n'''\n\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\n\n\nfilename = \"***.txt\"\t# 文本\nwith open(filename) as f:\n\tmytext = f.read()\n\n# print(mytext)\n\nwordcloud = WordCloud().generate(mytext)\n\nplt.imshow(wordcloud, interpolation='bilinear')\nplt.axis(\"off\") # 隐藏坐标\nplt.show()\n\n" ]
[ [ "matplotlib.pyplot.imshow", "matplotlib.pyplot.show", "matplotlib.pyplot.axis" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
yuko29/tflite_custom_op
[ "66df2c5ade62b04b920034e7721c4b6afc60e942" ]
[ "tensorflow_zero_out/python/ops/convert_to_tflite.py" ]
[ "import tensorflow as tf\nimport tensorflow_zero_out \nimport numpy as np\nimport os\n\n# Create a model using low-level tf.* APIs\nclass ZeroOut(tf.Module):\n @tf.function(input_signature=[tf.TensorSpec(shape=[None], dtype=tf.int32)])\n def __call__(self, x):\n return tensorflow_zero_out.zero_out(x)\nmodel = ZeroOut()\n# (ro run your model) result = Squared(5.0) # This prints \"25.0\"\n# (to generate a SavedModel) tf.saved_model.save(model, \"saved_model_tf_dir\")\nconcrete_func = model.__call__.get_concrete_function()\n\n# Convert the model.\n# Notes that for the versions earlier than TensorFlow 2.7, the\n# from_concrete_functions API is able to work when there is only the first\n# argument given:\n# > converter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func])\nconverter = tf.lite.TFLiteConverter.from_concrete_functions([concrete_func],\n )\ntflite_model = converter.convert()\n\n# Save the model.\nwith open('model.tflite', 'wb') as f:\n f.write(tflite_model)" ]
[ [ "tensorflow.TensorSpec", "tensorflow.lite.TFLiteConverter.from_concrete_functions" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
jeongwhanchoi/graph-neural-pde
[ "4323db3bb3badbcfc3c569635b7f8f072946528d" ]
[ "test/test_attention.py" ]
[ "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nTest attention\n\"\"\"\nimport unittest\nimport torch\nfrom torch import tensor\nfrom torch import nn\nfrom function_GAT_attention import SpGraphAttentionLayer, ODEFuncAtt\nfrom torch_geometric.utils import softmax, to_dense_adj\nfrom data import get_dataset\n\n\nclass AttentionTests(unittest.TestCase):\n def setUp(self):\n self.edge = tensor([[0, 2, 2, 1], [1, 0, 1, 2]])\n self.x = tensor([[1., 2.], [3., 2.], [4., 5.]], dtype=torch.float)\n self.W = tensor([[2, 1], [3, 2]], dtype=torch.float)\n self.alpha = tensor([[1, 2, 3, 4]], dtype=torch.float)\n self.edge1 = tensor([[0, 0, 1, 1, 2, 2], [1, 2, 0, 2, 0, 1]])\n self.x1 = torch.ones((3, 2), dtype=torch.float)\n\n self.leakyrelu = nn.LeakyReLU(0.2)\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n self.opt = {'dataset': 'Cora', 'self_loop_weight': 1, 'leaky_relu_slope': 0.2, 'beta_dim': 'vc', 'heads': 2,\n 'K': 10,\n 'attention_norm_idx': 0, 'add_source': False, 'max_nfe': 1000, 'mix_features': False,\n 'attention_dim': 32,\n 'mixed_block': False, 'rewiring': None, 'no_alpha_sigmoid': False, 'reweight_attention': False,\n 'kinetic_energy': None, 'jacobian_norm2': None, 'total_deriv': None, 'directional_penalty': None}\n\n def tearDown(self) -> None:\n pass\n\n def test(self):\n h = torch.mm(self.x, self.W)\n edge_h = torch.cat((h[self.edge[0, :], :], h[self.edge[1, :], :]), dim=1)\n self.assertTrue(edge_h.shape == torch.Size([self.edge.shape[1], 2 * 2]))\n ah = self.alpha.mm(edge_h.t()).t()\n self.assertTrue(ah.shape == torch.Size([self.edge.shape[1], 1]))\n edge_e = self.leakyrelu(ah)\n attention = softmax(edge_e, self.edge[1])\n print(attention)\n\n def test_function(self):\n in_features = self.x.shape[1]\n out_features = self.x.shape[1]\n\n def get_round_sum(tens, n_digits=3):\n val = torch.sum(tens, dim=int(not self.opt['attention_norm_idx']))\n return (val * 10 ** n_digits).round() / (10 ** n_digits)\n\n att_layer = SpGraphAttentionLayer(in_features, out_features, self.opt, self.device, concat=True)\n attention, _ = att_layer(self.x, self.edge) # should be n_edges x n_heads\n self.assertTrue(attention.shape == (self.edge.shape[1], self.opt['heads']))\n dense_attention1 = to_dense_adj(self.edge, edge_attr=attention[:, 0]).squeeze()\n dense_attention2 = to_dense_adj(self.edge, edge_attr=attention[:, 1]).squeeze()\n\n self.assertTrue(torch.all(torch.eq(get_round_sum(dense_attention1), 1.)))\n self.assertTrue(torch.all(torch.eq(get_round_sum(dense_attention2), 1.)))\n\n self.assertTrue(torch.all(attention > 0.))\n self.assertTrue(torch.all(attention <= 1.))\n\n dataset = get_dataset(self.opt, '../data', False)\n data = dataset.data\n in_features = data.x.shape[1]\n out_features = data.x.shape[1]\n\n att_layer = SpGraphAttentionLayer(in_features, out_features, self.opt, self.device, concat=True)\n attention, _ = att_layer(data.x, data.edge_index) # should be n_edges x n_heads\n\n self.assertTrue(attention.shape == (data.edge_index.shape[1], self.opt['heads']))\n dense_attention1 = to_dense_adj(data.edge_index, edge_attr=attention[:, 0]).squeeze()\n dense_attention2 = to_dense_adj(data.edge_index, edge_attr=attention[:, 1]).squeeze()\n self.assertTrue(torch.all(torch.eq(get_round_sum(dense_attention1), 1.)))\n self.assertTrue(torch.all(torch.eq(get_round_sum(dense_attention2), 1.)))\n self.assertTrue(torch.all(attention > 0.))\n self.assertTrue(torch.all(attention <= 1.))\n\n def test_symetric_attention(self):\n in_features = self.x1.shape[1]\n out_features = self.x1.shape[1]\n att_layer = SpGraphAttentionLayer(in_features, out_features, self.opt, self.device, concat=True)\n attention, _ = att_layer(self.x1, self.edge1) # should be n_edges x n_heads\n\n self.assertTrue(torch.all(torch.eq(attention, 0.5 * torch.ones((self.edge1.shape[1], self.x1.shape[1])))))\n\n def test_module(self):\n dataset = get_dataset(self.opt, '../data', False)\n t = 1\n out_dim = 6\n func = ODEFuncAtt(dataset.data.num_features, out_dim, self.opt, dataset.data, self.device)\n out = func(t, dataset.data.x)\n print(out.shape)\n self.assertTrue(out.shape == (dataset.data.num_nodes, dataset.num_features))\n" ]
[ [ "torch.all", "torch.Size", "torch.mm", "torch.ones", "torch.cat", "torch.tensor", "torch.nn.LeakyReLU", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
bshapiroalbert/PsrSigSim
[ "74bb40814295fb6ef84aa932a0de2f684162b8c4" ]
[ "tests/test_simulate.py" ]
[ "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pytest\nimport os\nimport numpy as np\nimport glob\n\nfrom psrsigsim.signal.fb_signal import FilterBankSignal\nfrom psrsigsim.pulsar.pulsar import Pulsar\nfrom psrsigsim.pulsar.portraits import DataPortrait\nfrom psrsigsim.pulsar.profiles import DataProfile\nfrom psrsigsim.ism.ism import ISM\nfrom psrsigsim.telescope.telescope import Telescope\nfrom psrsigsim.telescope.receiver import Receiver\nfrom psrsigsim.telescope.backend import Backend\nfrom psrsigsim.io.psrfits import PSRFITS\nfrom psrsigsim.utils.utils import make_quant\nfrom psrsigsim.io.txtfile import TxtFile\nfrom psrsigsim.simulate.simulate import Simulation\n\n\[email protected]\ndef j1713_profile():\n \"\"\"\n Numpy array of J1713+0747 profile.\n \"\"\"\n path = 'psrsigsim/data/J1713+0747_profile.npy'\n return np.load(path)\n\[email protected]\ndef PSRfits():\n \"\"\"\n Fixture psrfits class\n \"\"\"\n fitspath = \"data/test.fits\"\n tempfits = \"data/B1855+09.L-wide.PUPPI.11y.x.sum.sm\"\n return PSRFITS(path=fitspath, template=tempfits, fits_mode='copy')\n\[email protected]\ndef param_dict():\n \"\"\"\n Fixture parameter dictionary.\n \"\"\"\n pdict = {'fcent' : 430,\n 'bandwidth' : 100,\n 'sample_rate' : 1.5625,\n 'dtype' : np.float32,\n 'Npols' : 1,\n 'Nchan' : 64,\n 'sublen' : 2.0,\n 'fold' : True,\n 'period' : 1.0,\n 'Smean' : 1.0,\n 'profiles' : [0.5, 0.5, 1.0], # Gaussian\n 'tobs' : 4.0,\n 'name' : 'J0000+0000',\n 'dm' : 10.0,\n 'tau_d' : 50e-9,\n 'tau_d_ref_f' : 1500.0,\n 'aperture' : 100.0,\n 'area' : 5500.0,\n 'Tsys' : 35.0,\n 'tscope_name' : \"TestScope\",\n 'system_name' : \"TestSys\",\n 'rcvr_fcent' : 430,\n 'rcvr_bw' : 100,\n 'rcvr_name' : \"TestRCVR\",\n 'backend_samprate' : 1.5625,\n 'backend_name' : \"TestBack\",\n 'tempfile' : None,\n 'parfile' : None,\n }\n return pdict\n\[email protected]\ndef simulation():\n \"\"\"\n Fixture Simulation class. Cannot be the only simulation tested.\n \"\"\"\n sim = Simulation(fcent = 430,\n bandwidth = 100,\n sample_rate = 1.0*2048*10**-6,\n dtype = np.float32,\n Npols = 1,\n Nchan = 64,\n sublen = 2.0,\n fold = True,\n period = 1.0,\n Smean = 1.0,\n profiles = None,\n tobs = 4.0,\n name = 'J0000+0000',\n dm = 10.0,\n tau_d = 50e-9,\n tau_d_ref_f = 1500.0,\n aperture = 100.0,\n area = 5500.0,\n Tsys = 35.0,\n tscope_name = \"TestScope\",\n system_name = \"TestSys\",\n rcvr_fcent = 430,\n rcvr_bw = 100,\n rcvr_name =\"TestRCVR\",\n backend_samprate = 1.5625,\n backend_name = \"TestBack\",\n tempfile = \"data/B1855+09.L-wide.PUPPI.11y.x.sum.sm\",\n parfile = None,\n psrdict = None)\n return sim\n\ndef test_initsim(param_dict):\n \"\"\"\n Test initializing the simulation from dictionary, parfile\n \"\"\"\n sim = Simulation(psrdict = param_dict)\n with pytest.raises(NotImplementedError):\n sim2 = Simulation(parfile = \"testpar.par\")\n\ndef test_initsig(simulation):\n \"\"\"\n Test init_signal function.\n \"\"\"\n # Test from input params\n simulation.init_signal()\n # Test from template file\n simulation.init_signal(from_template = True)\n\ndef test_initprof(simulation, j1713_profile):\n \"\"\"\n Test init_profile function.\n \"\"\"\n # Test no input\n simulation.init_profile()\n # Test function input\n with pytest.raises(NotImplementedError):\n def gprof(x, p0):\n return p0[0]* np.exp(-0.5*((x-p0[1])/(p0[2]))**2)\n simulation._profiles = gprof\n simulation.init_profile()\n # Test Gaussian as input\n simulation._profiles = [0.5, 0.5, 1.0]\n simulation.init_profile()\n # Test data array as input\n simulation._profiles = j1713_profile\n simulation.init_profile()\n # Test array that's not long enough\n with pytest.raises(RuntimeError):\n simulation._profiles = [0.5, 0.5]\n simulation.init_profile()\n # Test profile class as input\n pr = DataProfile(j1713_profile,phases=None)\n print(type(pr), pr)\n simulation._profiles = pr\n simulation.init_profile()\n \ndef test_initpsr(simulation):\n \"\"\"\n Test init_pulsar function.\n \"\"\"\n simulation.init_pulsar()\n\ndef test_initism(simulation):\n \"\"\"\n Test init_ism function.\n \"\"\"\n simulation.init_ism()\n\ndef test_inittscope(simulation):\n \"\"\"\n Test init_telescope function.\n \"\"\"\n # Test init GBT\n simulation._tscope_name = \"GBT\"\n simulation.init_telescope()\n # Test init Arecibo\n simulation._tscope_name = \"Arecibo\"\n simulation.init_telescope()\n # Test input telescope\n simulation._tscope_name = \"TestScope\"\n simulation.init_telescope()\n # Test list of systems for telescope\n simulation._system_name = [\"Sys1\", \"Sys2\"]\n simulation._rcvr_fcent = [430, 800]\n simulation._rcvr_bw = [100, 200]\n simulation._rcvr_name = [\"R1\", \"R2\"]\n simulation._backend_samprate = [1.5625, 12.5]\n simulation._backend_name = [\"B1\", \"B2\"]\n simulation.init_telescope()\n # And the catch with multiple systems\n with pytest.raises(RuntimeError):\n simulation._backend_name = [\"B1\", \"B2\", \"B3\"]\n simulation.init_telescope()\n\ndef test_simulate(simulation):\n \"\"\"\n Test simulate function.\n \"\"\"\n simulation.simulate()\n\[email protected]('ignore::fitsio.FITSRuntimeWarning')\ndef test_savesim(simulation, PSRfits):\n \"\"\"\n Test save simulation function.\n \"\"\"\n simulation._Nchan = 1\n simulation._tobs = 2.0\n #S = PSRfits.make_signal_from_psrfits()\n #simulation._tobs = PSRfits.tsubint.value*PSRfits.nsubint\n simulation.simulate(from_template = True)\n # Try pdv format\n simulation.save_simulation(out_format = \"pdv\")\n # Try psrfits format\n simulation.save_simulation(out_format = \"psrfits\", phaseconnect = False)\n os.remove(\"sim_fits.fits\")\n # Try psrfits format with phaseconnect = True\n #parfile = \"data/test_parfile.par\"\n #simulation._parfile = parfile\n #simulation.save_simulation(out_format = \"psrfits\", phaseconnect = True)\n #os.remove(\"sim_fits.fits\")\n dfs = glob.glob(\"simfits*\")\n for df in dfs:\n os.remove(df)\n # Try psrfits with runtime error\n # Try wrong output file type\n with pytest.raises(RuntimeError):\n simulation.save_simulation(out_format = \"wrong_fmt\")\n simulation._tempfile = None\n simulation.save_simulation(out_format = \"psrfits\")\n\n" ]
[ [ "numpy.load", "numpy.exp" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
johny-c/noge
[ "88e68ba8c51ff0d63577991e233e9110cb76e228" ]
[ "scripts/train_dqn.py" ]
[ "import copy\nimport torch\nimport logging\nimport numpy as np\nfrom sacred import Experiment\n\nfrom noge.data_loaders import get_datasets, get_test_loader, get_train_generator\nfrom noge.factory import make_env, make_memory\nfrom noge.network import make_network\nfrom noge.agent import Actor, main_loop, loop_ing\nfrom noge.trainers import DQNTrainer, Replay\nfrom noge.policies import LinearSchedule, GraphDQNPolicy\nfrom noge.preprocessors import Preprocessor\nfrom noge.evaluation import Evaluator, eval_ing\nfrom noge.constants import CONFIGS_DIR, EVAL_DIR\nfrom xlog.utils import get_logger\nfrom xlog.mlflow_observer import MlflowObserver\n\nex = Experiment(name='NOGE_DQN', ingredients=[eval_ing, loop_ing])\nex.add_config(str(CONFIGS_DIR / 'dqn.yaml'))\nex.logger = get_logger(__name__, level=logging.INFO)\nex.observers = [MlflowObserver(tracking_uri=str(EVAL_DIR.absolute()))]\n\n\[email protected]\ndef train(dataset, test_size, max_episode_steps, reward_type, input_meas_type, meas_transform,\n target_transform, node_history, gamma, target_update_freq,\n cat_features, feature_range, replay_capacity, min_horizon, epsilon_start, epsilon_end,\n exploration_frac, n_train_steps, train_freq, loss, batch_size, lr, n_test_episodes, init_eval,\n n_eval_artifacts, test_freq, log_freq, device, seed, data_seed, save_model, _log, _run, _config):\n np.set_printoptions(precision=2, suppress=True)\n\n if device.startswith('cuda'):\n assert torch.cuda.is_available()\n\n logger = _log\n device = torch.device(device)\n\n # data source\n train_set, test_set = get_datasets(dataset, seed=data_seed, test_size=test_size)\n max_nodes = max(train_set.max_nodes, test_set.max_nodes)\n max_edges = 2 * max(train_set.max_edges, test_set.max_edges) # for undirected graphs, consider both directions\n\n test_loader = get_test_loader(test_set, seed=seed, num_samples=n_test_episodes)\n train_gen = get_train_generator(train_set, seed=seed)\n\n preprocessor = Preprocessor(input_meas_type=input_meas_type,\n output_meas_type=input_meas_type,\n feature_range=feature_range,\n meas_transform=meas_transform,\n target_transform=target_transform,\n temporal_offsets=[1.],\n max_nodes=max_nodes,\n device=device)\n\n # environment\n train_env_config = dict(\n max_episode_steps=max_episode_steps,\n reward_type=reward_type,\n max_nodes=max_nodes,\n max_edges=max_edges,\n nn_feat='N' in cat_features,\n )\n\n train_env = make_env(**train_env_config, data_generator=train_gen, seed=seed)\n test_env_config = copy.deepcopy(train_env_config)\n test_env_config.update(sample_goals=False, data_generator=None)\n test_env = make_env(**test_env_config, seed=seed)\n\n # graph memory + graph preprocessing\n neg_label, pos_label = feature_range\n mem_features = dict(cat=cat_features)\n graph_mem_config = dict(\n max_episode_steps=max_episode_steps,\n max_nodes=max_nodes,\n max_edges=max_edges,\n history=node_history,\n memory_type='cat',\n features=mem_features,\n neg_label=neg_label,\n pos_label=pos_label\n )\n\n eval_memory = make_memory(online=True, **graph_mem_config)\n acting_memory = make_memory(online=True, **graph_mem_config)\n\n # model\n model_config = dict(\n dim_node=eval_memory.dim_node,\n dim_meas=preprocessor.dim_input_meas,\n dim_goal=1,\n max_edges=max_edges,\n **_config['model']\n )\n\n network = make_network(**model_config).to(device)\n\n # evaluation\n eval_policy = GraphDQNPolicy(network, eval_memory, preprocessor=preprocessor, device=device)\n evaluator = Evaluator(test_loader, test_env, eval_policy)\n\n # experience collecting policy\n exploration_steps = int(exploration_frac * n_train_steps)\n exploration_schedule = LinearSchedule(epsilon_start, epsilon_end, exploration_steps)\n acting_policy = GraphDQNPolicy(network,\n graph_memory=acting_memory,\n preprocessor=preprocessor,\n exploration_schedule=exploration_schedule,\n device=device)\n\n # replay buffer\n replay_buffer = Replay(capacity=replay_capacity,\n ob_space=train_env.observation_space,\n graph_mem_config=graph_mem_config,\n min_horizon=min_horizon)\n\n # actor: runs the simulation forward and stores to the replay buffer\n actor = Actor(train_env, acting_policy, replay_buffer)\n\n # trainer\n optimizer = torch.optim.Adam(network.parameters(), lr=lr)\n\n if loss == 'mse':\n criterion = torch.nn.MSELoss()\n else:\n raise ValueError(f\"Unsupported loss: {loss}\")\n\n trainer = DQNTrainer(gamma=gamma,\n target_update_freq=target_update_freq,\n replay_buffer=replay_buffer,\n batch_size=batch_size,\n network=network,\n preprocessor=preprocessor,\n criterion=criterion,\n optimizer=optimizer,\n device=device)\n\n # fill up the replay buffer\n network.eval()\n logger.info(f\"Filling up the replay buffer...\")\n actor.step(n=replay_capacity, use_tqdm=True)\n logger.info(f\"Replay buffer filled: [{len(replay_buffer)} / {replay_capacity}]\")\n\n # fit the preprocessor with buffer data\n preprocessor.fit(replay_buffer._measurements)\n\n best_perf = main_loop(actor, trainer, evaluator, network, exploration_schedule,\n init_eval, n_eval_artifacts, n_train_steps, train_freq, log_freq, test_freq, save_model)\n\n train_env.close()\n evaluator.close()\n\n return best_perf\n" ]
[ [ "torch.device", "numpy.set_printoptions", "torch.nn.MSELoss", "torch.cuda.is_available" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
ziqi123/AutoParking
[ "bc2c86fe93892c0502cc7cf689d8ec072d2974d1", "bc2c86fe93892c0502cc7cf689d8ec072d2974d1", "bc2c86fe93892c0502cc7cf689d8ec072d2974d1", "bc2c86fe93892c0502cc7cf689d8ec072d2974d1" ]
[ "preprocessing/make_dataset_new.py", "hourglass_four/dataloader/dataloader_four.py", "stackedHourglass/dataloader/dataset_stackedHourglass.py", "models/hourglass.py" ]
[ "import numpy as np\nimport os\nimport cv2\nfrom PIL import Image\nimport numpy as np\nimport random\nimport itertools\nimport matplotlib.pyplot as plt # plt 用于显示图片\nfrom tqdm import tqdm\n\n# 标注文件数据处理\n\n\ndef read_pslot(annt_file):\n # print(annt_file)\n with open(annt_file, \"r\") as f:\n annt = f.readlines()\n # print(\"annt\", annt)\n l = []\n l_ign = []\n for line in annt:\n line_annt = line.strip('\\n').split(' ')\n # print(line_annt)\n\n if len(line_annt) != 13 or line_annt[0] != 'line' or line_annt[-4] == '3':\n continue\n\n if line_annt[-4] in ['0', '1']:\n l.append(np.array([int(line_annt[i + 1]) for i in range(8)]))\n # continue\n\n # if line_annt[-4] in ['1', '5']:\n # l_ign.append(np.array([int(line_annt[i + 1]) for i in range(8)]))\n # continue\n return l, l_ign\n\n# 标点\n\n\ndef colorize(points_list, img, save_path, item, line, point_color):\n save_path = os.path.join(save_path, str(\n item.strip('.jpg'))+\"_\"+str(line)+\".jpg\")\n img2 = img.copy()\n # print(save_path)\n # points_list = 384 * np.abs(np.array(outputs[0], dtype=np.float))\n point_size = 1\n thickness = 4 # 可以为 0、4、8\n for i in range(4):\n cv2.circle(img2, (int(points_list[i][0]), int(points_list[i][1])),\n point_size, point_color, thickness)\n # print(save_path)\n cv2.imwrite(save_path, img2)\n\n # 画线\n\n\ndef paint_line(img, dst, cropimg_path, num):\n img2 = img.copy()\n\n cv2.line(img2, (int(dst[0][0]), int(dst[0][1])), (int(\n dst[1][0]), int(dst[1][1])), (255, 0, 0), 5)\n cv2.line(img2, (int(dst[1][0]), int(dst[1][1])), (int(\n dst[2][0]), int(dst[2][1])), (255, 0, 0), 5)\n cv2.line(img2, (int(dst[2][0]), int(dst[2][1])), (int(\n dst[3][0]), int(dst[3][1])), (255, 0, 0), 5)\n cv2.line(img2, (int(dst[3][0]), int(dst[3][1])), (int(\n dst[0][0]), int(dst[0][1])), (255, 0, 0), 5)\n\n cropimg_path1 = os.path.join(\n cropimg_path, i.strip('.jpg')+'_'+str(num)+'.jpg')\n cv2.imwrite(cropimg_path1, img2)\n\n\ndef Crop_pic(ps, img_path, cropimg_path, perspective_path, txt_file, i, trans_path, save_path1, save_path2):\n # single pic\n img = cv2.imread(img_path)\n\n perspective3 = np.float32([[0, 0], [383, 0], [383, 383], [0, 383]])\n perspective3_ = np.float32([[0, 0], [383, 0], [383, 383]])\n num = 0\n for line in ps:\n num = num + 1\n # 随机生成4个坐标\n arr0 = random.randint(80, 120)\n arr1 = random.randint(80, 120)\n\n arr2 = random.randint(263, 303)\n arr3 = random.randint(80, 120)\n\n arr4 = random.randint(263, 303)\n arr5 = random.randint(263, 303)\n\n arr6 = random.randint(80, 120)\n arr7 = random.randint(263, 303)\n\n perspective0 = np.float32([[line[0], line[1]], [line[2], line[3]], [\n line[4], line[5]], [line[6], line[7]]])\n perspective0_ = np.float32([[line[0], line[1]], [line[2], line[3]], [\n line[4], line[5]]])\n\n colorize(perspective0, img, save_path1, i, num, (0, 255, 0))\n\n perspective1 = np.float32(\n [[arr0, arr1], [arr2, arr3], [arr4, arr5], [arr6, arr7]])\n perspective1_ = np.float32(\n [[arr0, arr1], [arr2, arr3], [arr4, arr5]])\n\n # 求逆变换矩阵\n # trans_inv = cv2.getPerspectiveTransform(perspective1, perspective0)\n trans_inv = cv2.getAffineTransform(perspective1_, perspective0_)\n\n # 求逆投影变换后的点坐标\n dst = []\n # mat = np.array(\n # [[[0, 0], [383, 0], [383, 383], [0, 383]]], dtype=np.float32)\n mat = np.array(\n [[0, 0, 1], [383, 0, 1], [383, 383, 1], [0, 383, 1]], dtype=np.float32)\n mat = mat.transpose()\n # dst = cv2.perspectiveTransform(mat, trans_inv)\n dst = np.dot(trans_inv, mat)\n dst = dst.transpose()\n\n # 画线\n paint_line(img, dst, cropimg_path, num)\n\n # 将停车位投影变换后得到在384*384分辨率下的停车位图像\n\n # perspective2 = np.float32([[dst[0][0][0], dst[0][0][1]], [dst[0][1][0], dst[0][1][1]], [\n # dst[0][2][0], dst[0][2][1]], [dst[0][3][0], dst[0][3][1]]])\n perspective2_ = np.float32([[dst[0][0], dst[0][1]], [dst[1][0], dst[1][1]], [\n dst[2][0], dst[2][1]]])\n\n # trans = cv2.getPerspectiveTransform(perspective2, perspective3)\n # dst2 = cv2.warpPerspective(img, trans, (384, 384))\n\n trans = cv2.getAffineTransform(perspective2_, perspective3_)\n dst2 = cv2.warpAffine(img, trans, (384, 384))\n\n # 保存原图四个内角点在384*384图片上的坐标\n # mat2 = np.array([[[line[0], line[1]], [line[2], line[3]], [\n # line[4], line[5]], [line[6], line[7]]]], dtype=np.float32)\n mat2 = np.array([[line[0], line[1], 1], [line[2], line[3], 1], [\n line[4], line[5], 1], [line[6], line[7], 1]], dtype=np.float32)\n\n mat2 = mat2.transpose()\n point = np.dot(trans, mat2)\n point = point.transpose()\n\n # point = cv2.perspectiveTransform(mat2, trans)\n # point = np.dot(mat2, trans)\n\n perspective_path1 = os.path.join(\n perspective_path, i.strip('.jpg')+'_'+str(num)+'.jpg')\n # print(perspective_path)\n cv2.imwrite(perspective_path1, dst2)\n colorize(point, dst2, save_path2, i, num, (0, 255, 0))\n\n # 把四个坐标点记录下来\n txt_file1 = os.path.join(\n txt_file, i.strip('.jpg')+'_'+str(num)+'_OA.txt')\n with open(txt_file1, \"w\") as f:\n for j in range(4):\n f.write(str(point[j][0]))\n f.write(' ')\n f.write(str(point[j][1]))\n f.write('\\n')\n\n # 把转换矩阵记录下来\n trans_path1 = os.path.join(\n trans_path, i.strip('.jpg')+'_'+str(num)+'.txt')\n with open(trans_path1, \"w\") as ff:\n for j in range(2):\n for k in range(3):\n ff.write(str(trans_inv[j][k]))\n ff.write(\" \")\n\n# 计算四个点的预测点与真值点之间的误差\n\n\ndef get_acc(y, y_hat, dis):\n total = 0\n total = 0\n for i in range(4):\n total += ((y[i][0]-y_hat[i][0])**2 + (y[i][1]-y_hat[i][1])**2)**0.5\n total /= 4\n\n if total < dis:\n return 1\n else:\n return 0\n\n\ndef output_pic(img_path, output_path, trans_path, fina_path, ps2, pix, point_path):\n img_pred = cv2.imread(img_path)\n point_pred = []\n trans_inv = []\n point_pred = np.loadtxt(output_path)\n\n point_pred = 384*np.expand_dims(point_pred, axis=0)\n trans_inv = np.loadtxt(trans_path)\n\n trans_inv = trans_inv.reshape(3, 3)\n trans_inv = np.mat(trans_inv)\n\n point_ground = np.loadtxt(point_path)\n point_ground = np.expand_dims(point_ground, axis=0)\n point_ground2 = cv2.perspectiveTransform(point_ground, trans_inv)\n point_size = 1\n thickness = 4\n for i in range(4):\n cv2.circle(img_pred, (int(point_ground2[0][i][0]), int(point_ground2[0][i][1])),\n point_size, (0, 255, 0), thickness)\n\n cv2.imwrite(fina_path, img_pred)\n\n point_pred2 = cv2.perspectiveTransform(point_pred, trans_inv)\n\n # 红色\n point_color = (0, 0, 255)\n point_color2 = (0, 255, 0)\n\n for i in range(4):\n cv2.circle(img_pred, (int(point_pred2[0][i][0]), int(point_pred2[0][i][1])),\n point_size, point_color, thickness)\n\n cv2.imwrite(fina_path, img_pred)\n\n point_pred3 = point_pred2[0]\n\n ps2 = ps2[0].reshape(4, 2)\n\n tmp = get_acc(point_pred3, point_ground2[0], pix)\n return tmp\n\n# 精度\n\n\ndef output(pix):\n accuracy = 0\n for i in os.listdir(test_dir):\n output_path = os.path.join(\n \"/media/alpha4TB/ziqi/Parking/CNN/output\", i.strip('.jpg')+'.txt')\n img_path = os.path.join(\n \"/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/img\", i)\n trans_inv = os.path.join(\n \"/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/trans_inv\", i.strip('.jpg')+'.txt')\n fina_path = os.path.join(\n \"/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/fina\", i)\n annt_path2 = os.path.join(\n './Ps_locate_dataset/annt', i.strip('.jpg')+'_OA.txt')\n point_path = os.path.join(\n \"/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/point\", i.strip('.jpg')+'_OA.txt')\n # print(fina_path)\n ps2, _ = read_pslot(annt_path2)\n tmp = output_pic(img_path, output_path,\n trans_inv, fina_path, ps2, pix, point_path)\n accuracy += tmp\n return accuracy\n\n\nif __name__ == \"__main__\":\n data_dir = '/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/pic'\n label_dir = '/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/annotation'\n crop_dir = '/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/crop_img'\n perspective_dir = '/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/perspective_img'\n txt_dir = '/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/point'\n cnt = 0\n f1 = open(\n \"/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/train_list.txt\", \"w\")\n # f2 = open(\"./Ps_locate_dataset/val_list.txt\", \"w\")\n test_dir = \"/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/test_img\"\n trans_path = \"/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/trans_inv\"\n save_path1 = \"/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/src_img\"\n save_path2 = \"/media/home_bak/ziqi/park/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/perspective2_img\"\n\n pbar = tqdm(total=len(os.listdir(data_dir)))\n\n for i in os.listdir(data_dir):\n # print(i)\n annt_file = os.path.join(label_dir, i.strip('.jpg')+'_OA.txt')\n img_path = os.path.join(data_dir, i)\n\n ps, _ = read_pslot(annt_file)\n Crop_pic(ps, img_path, crop_dir,\n perspective_dir, txt_dir, i, trans_path, save_path1, save_path2)\n pbar.update(1)\n\n pbar.close()\n\n # acc = []\n # for k in range(31):\n # print(\"k\", k)\n # x1 = output(k)\n # x1 = 100 * x1 / 743\n # acc.append(x1)\n\n # x1 = round(x1, 3)\n # print(acc)\n # print(len(acc))\n\n # # 设置画布大小\n # plt.figure(figsize=(30, 15))\n\n # # 标题\n # plt.title(\"accruracy distribution\")\n\n # # 数据\n # plt.bar(range(len(acc)), acc)\n\n # # 横坐标描述\n # plt.xlabel('pixel')\n\n # # 纵坐标描述\n # plt.ylabel('accuracy')\n # # # 设置数字标签\n # # for a, b in zip(x, acc):\n # # plt.text(a, b, b, ha='center', va='bottom', fontsize=10)\n\n # plt.savefig(\n # \"/media/alpha4TB/ziqi/Parking/Ps_locate_dataset/PLD_BirdView_TrainingDaraSet_All/accuracy.png\")\n\n # 保存训练数据的文件名\n filenames = os.listdir(perspective_dir)\n filenames.sort()\n print(filenames[0])\n\n for i in os.listdir(perspective_dir):\n perspective_path = os.path.join(perspective_dir, i)\n f1.write(perspective_path)\n f1.write('\\n')\n\n f1.close()\n", "import os\nimport torch\nfrom torchvision import transforms\nfrom torch.utils.data import DataLoader, Dataset\n\nfrom dataloader.dataset_four import heatmap_dataset\n\n\ndef heatmap_Dataloader(params):\n norm_factor = params['data_normalize_factor']\n ds_dir = params['dataset_dir']\n rgb2gray = params['rgb2gray'] if 'rgb2gray' in params else False\n dataset = params['dataset']\n num_worker = 8\n resize = params['resize'] if 'resize' in params else False\n sigma = params['sigma']\n image_datasets = {}\n dataloaders = {}\n dataset_sizes = {}\n\n ###### Training Set ######\n\n image_datasets['train'] = heatmap_dataset(ds_dir, sigma, setname='train',\n transform=None, norm_factor=norm_factor,\n rgb2gray=rgb2gray, resize=resize)\n\n dataloaders['train'] = DataLoader(image_datasets['train'], shuffle=True, batch_size=params['train_batch_sz'],\n num_workers=num_worker)\n dataset_sizes['train'] = {len(image_datasets['train'])}\n\n ##### Validation Set ######\n\n image_datasets['val'] = heatmap_dataset(ds_dir, sigma, setname='val', transform=None,\n norm_factor=norm_factor,\n rgb2gray=rgb2gray, resize=resize)\n dataloaders['val'] = DataLoader(image_datasets['val'], shuffle=False, batch_size=params['val_batch_sz'],\n num_workers=num_worker)\n dataset_sizes['val'] = {len(image_datasets['val'])}\n\n # print(dataset_sizes)\n\n return dataloaders, dataset_sizes\n", "import copy\nfrom PIL import Image\nfrom PIL import ImageEnhance\nfrom torch.utils.data import DataLoader, Dataset\nimport torch\nimport numpy as np\nimport glob\nimport torchvision\nimport matplotlib.pyplot as plt\nimport random\nimport cv2\nfrom heatmappy import Heatmapper\nnp.seterr(divide='ignore', invalid='ignore')\n\n\nclass heatmap_dataset(Dataset):\n def __init__(self, ds_dir, sigma, setname='train', transform=None, norm_factor=256, rgb2gray=False, resize=True):\n\n self.ds_dir = ds_dir\n self.setname = setname\n self.transform = transform\n self.norm_factor = norm_factor\n self.rgb2gray = rgb2gray\n self.__sigma = sigma\n\n self.resize = resize\n self.c = 0\n self.s = 0\n self.r = 0\n\n if setname == 'train':\n data = []\n gt = []\n train_list = '/media/home_bak/ziqi/park/stackedHourglass/dataset/train_list.txt'\n f = open(train_list)\n for line in f:\n line_data = line.strip('\\n')\n line_gt = line_data.replace(\n 'match_img_t', 'match_img_point_t').replace('.jpg', '_OA.txt')\n data.append(line_data)\n gt.append(line_gt)\n self.data = data\n self.gt = gt\n\n if setname == 'val':\n data = []\n gt = []\n test_list = '/media/home_bak/ziqi/park/stackedHourglass/dataset/val.txt'\n f = open(test_list)\n for line in f:\n line_data = line.strip('\\n')\n line_gt = line_data.replace(\n 'match_img', 'match_img_point').replace('.jpg', '_OA.txt')\n data.append(line_data)\n gt.append(line_gt)\n self.data = data\n self.gt = gt\n\n def __len__(self):\n return len(self.data)\n\n def get_affine_transform(self, center, scale, rot, output_size, shift=np.array([0, 0], dtype=np.float32), inv=0):\n if not isinstance(scale, np.ndarray) and not isinstance(scale, list):\n print(scale)\n scale = np.array([scale, scale])\n\n scale_tmp = scale * 200\n # print('scale_tmp',scale_tmp)\n # print(\"scale_tmp: {}\".format(scale_tmp))\n\n # print(\"output_size: {}\".format(output_size)) # W H\n src_w = scale_tmp[0]\n dst_w = output_size[0]\n dst_h = output_size[1]\n\n rot_rad = np.pi * rot / 180\n src_dir = self.get_dir([0, src_w * -0.5], rot_rad)\n dst_dir = np.array([0, dst_w * -0.5], np.float32)\n # print(\"src_dir: {}\".format(src_dir))\n # print(\"dst_dir: {}\".format(dst_dir))\n\n src = np.zeros((3, 2), dtype=np.float32)\n dst = np.zeros((3, 2), dtype=np.float32)\n # print(\"center: {}\".format(center))\n src[0, :] = center + scale_tmp * shift\n # print(\"src[0, :]: {}\".format(src[0, :]))\n\n # print(\"src_dir: {}\".format(src_dir))\n src[1, :] = center + src_dir + scale_tmp * shift\n\n # print(\"src[1, :]: {}\".format(src[1, :]))\n dst[0, :] = [dst_w * 0.5, dst_h * 0.5]\n dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir\n\n src[2:, :] = self.get_3rd_point(src[0, :], src[1, :])\n # print(\"src[2:, :]: {}\".format(src[2:, :]))\n dst[2:, :] = self.get_3rd_point(dst[0, :], dst[1, :])\n # print('src', src,dst)\n # print(\"src:\\n{}\".format(src))\n # print(\"dst:\\n{}\".format(dst))\n\n if inv:\n trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))\n else:\n trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))\n # exit(1)\n\n return trans\n\n def get_dir(self, src_point, rot_rad):\n sn, cs = np.sin(rot_rad), np.cos(rot_rad)\n\n src_result = [0, 0]\n src_result[0] = src_point[0] * cs - src_point[1] * sn\n src_result[1] = src_point[0] * sn + src_point[1] * cs\n\n return src_result\n\n def get_3rd_point(self, a, b):\n direct = a - b\n return b + np.array([-direct[1], direct[0]], dtype=np.float32)\n\n def _box2cs(self, size, aspect_ratio=None, scale_factor=None):\n x, y, w, h = 0, 0, size[0], size[1]\n return self._xywh2cs(x, y, w, h,\n aspect_ratio,\n scale_factor)\n\n def _xywh2cs(self, x, y, w, h, aspect_ratio, scale_factor):\n center = np.zeros((2), dtype=np.float32)\n center[0] = x + w * 0.5\n center[1] = y + h * 0.5\n\n if w > aspect_ratio * h:\n h = w * 1.0 / aspect_ratio\n elif w < aspect_ratio * h:\n w = h * aspect_ratio\n scale = np.array(\n [w * 1.0 / 200, h * 1.0 / 200],\n dtype=np.float32)\n\n return center, scale\n\n def __getitem__(self, item):\n if item < 0 or item >= self.__len__():\n return None\n\n # Read images\n # data = Image.open(str(self.data[item]))\n data = cv2.imread(str(self.data[item]))\n imgPath = str(self.data[item])\n\n gt = [[0, 0], [0, 0], [0, 0], [0, 0]]\n\n # gt = np.loadtxt(str(self.data[item]))\n with open(str(self.gt[item]), \"r\") as f:\n lines = f.readlines() # 把全部数据文件读到一个列表lines中\n\n # 表示矩阵的行,从0行开始\n row = 0\n # 把lines中的数据逐行读取出来\n for line in lines:\n # 处理逐行数据:strip表示把头尾的'\\n'去掉,split表示以空格来分割行数据,然后把处理后的行数据返回到list列表中\n list = line.strip('\\n').split(' ')\n gt[row][0] = float(list[0])\n gt[row][1] = float(list[1])\n # print(\"point:\", list[0], list[1])\n # 然后方阵A的下一行接着读\n row = row + 1\n\n # gt.sort(key=takeSecond)\n # print(\"file\", imgPath)\n\n H, W = 192, 192\n\n # 数据增强\n # data = self.randomBlur(data)\n # data = self.RandomBrightness(data)\n # data = self.RandomHue(data)\n # data = self.RandomSaturation(data)\n # # data = self.randomColor(data)\n # data = self.randomGaussian(data, mean=0.2, sigma=0.3)\n if self.setname == 'train':\n # data = self.randomBlur(data)\n data = self.RandomBrightness(data)\n data = self.RandomHue(data)\n data = self.RandomSaturation(data)\n # data = self.randomColor(data)\n data = self.randomGaussian(data, mean=0.2, sigma=0.3)\n\n data = 255 * np.array(data).astype('uint8')\n data = cv2.cvtColor(np.array(data), cv2.COLOR_RGB2BGR) # PIL转cv2\n\n # data = self.random_rotate(data)\n\n if self.rgb2gray:\n t = torchvision.transforms.Grayscale(1)\n data = t(data)\n\n # Convert to numpy\n data = np.array(data, dtype=np.float32) / self.norm_factor\n # gt = np.array(gt, dtype=np.float32) / 384\n gt = np.array(gt, dtype=np.float32)\n\n size = [192, 192]\n mask = np.zeros((size[0], size[1]), dtype=np.float)\n\n # heatmaps = self._putGaussianMaps(gt, H, W, 1, self.__sigma)\n generateHeatmap = GenerateHeatmap(48, 4)\n gt2=gt/192*48\n heatmaps = generateHeatmap(gt2)\n\n heatmaps = heatmaps.astype(np.float32)\n\n c, s = self._box2cs(size, aspect_ratio=1)\n r = 0\n # print(r)\n trans = self.get_affine_transform(c, s, r, size)\n data = cv2.warpAffine(\n data, trans, (size[0], size[1]), flags=cv2.INTER_LINEAR)\n mask = cv2.warpAffine(\n mask, trans, (size[0], size[1]), flags=cv2.INTER_LINEAR, borderValue=255)\n\n # Expand dims into Pytorch format\n data = np.transpose(data, (2, 0, 1))\n mask = np.expand_dims(mask, 0)\n\n # Convert to Pytorch Tensors\n data = torch.tensor(data, dtype=torch.float)\n gt = torch.tensor(gt, dtype=torch.float32)\n # print(\"gt,imgPath:\", gt, imgPath)\n mask = torch.tensor(mask, dtype=torch.float)\n\n return data, gt, mask, item, imgPath, heatmaps\n\n def randomColor(image):\n \"\"\"\n 对图像进行颜色抖动\n :param image: PIL的图像image\n :return: 有颜色色差的图像image\n \"\"\"\n random_factor = np.random.randint(0, 31) / 10. # 随机因子\n color_image = ImageEnhance.Color(\n image).enhance(random_factor) # 调整图像的饱和度\n random_factor = np.random.randint(10, 21) / 10. # 随机因子\n brightness_image = ImageEnhance.Brightness(\n color_image).enhance(random_factor) # 调整图像的亮度\n random_factor = np.random.randint(10, 21) / 10. # 随机因子\n contrast_image = ImageEnhance.Contrast(\n brightness_image).enhance(random_factor) # 调整图像对比度\n random_factor = np.random.randint(0, 31) / 10. # 随机因子\n # 调整图像锐度\n return ImageEnhance.Sharpness(contrast_image).enhance(random_factor)\n\n def random_blur(self, image, sigma):\n _sigma = random.randint(0, sigma)\n\n return cv2.GaussianBlur(image, (11, 11), _sigma)\n\n def randomGaussian(self, image, mean, sigma):\n \"\"\"\n 对图像进行高斯噪声处理\n :param image:\n :return:\n \"\"\"\n def gaussianNoisy(im, mean, sigma):\n \"\"\"\n 对图像做高斯噪音处理\n :param im: 单通道图像\n :param mean: 偏移量\n :param sigma: 标准差\n :return:\n \"\"\"\n for _i in range(len(im)):\n im[_i] += random.gauss(mean, sigma)\n return im\n # 将图像转化成数组\n img = np.asarray(image)\n img.flags.writeable = True # 将数组改为读写模式\n width, height = img.shape[:2]\n img_r = gaussianNoisy(img[:, :, 0].flatten(), mean, sigma)\n img_g = gaussianNoisy(img[:, :, 1].flatten(), mean, sigma)\n img_b = gaussianNoisy(img[:, :, 2].flatten(), mean, sigma)\n img[:, :, 0] = img_r.reshape([width, height])\n img[:, :, 1] = img_g.reshape([width, height])\n img[:, :, 2] = img_b.reshape([width, height])\n return Image.fromarray(np.uint8(img))\n\n def RandomBrightness(self, bgr):\n if random.random() < 0.5:\n hsv = self.BGR2HSV(bgr)\n h, s, v = cv2.split(hsv)\n adjust = random.choice([0.5, 1.5])\n v = v*adjust\n v = np.clip(v, 0, 255).astype(hsv.dtype)\n hsv = cv2.merge((h, s, v))\n bgr = self.HSV2BGR(hsv)\n return bgr\n\n def RandomSaturation(self, bgr):\n if random.random() < 0.5:\n hsv = self.BGR2HSV(bgr)\n h, s, v = cv2.split(hsv)\n adjust = random.choice([0.5, 1.5])\n s = s*adjust\n s = np.clip(s, 0, 255).astype(hsv.dtype)\n hsv = cv2.merge((h, s, v))\n bgr = self.HSV2BGR(hsv)\n return bgr\n\n def RandomHue(self, bgr):\n if random.random() < 0.5:\n hsv = self.BGR2HSV(bgr)\n h, s, v = cv2.split(hsv)\n adjust = random.choice([0.5, 1.5])\n h = h*adjust\n h = np.clip(h, 0, 255).astype(hsv.dtype)\n hsv = cv2.merge((h, s, v))\n bgr = self.HSV2BGR(hsv)\n return bgr\n\n def randomShift(self, bgr, boxes, labels):\n # 平移变换\n center = (boxes[:, 2:]+boxes[:, :2])/2\n if random.random() < 0.5:\n height, width, c = bgr.shape\n after_shfit_image = np.zeros((height, width, c), dtype=bgr.dtype)\n after_shfit_image[:, :, :] = (104, 117, 123) # bgr\n shift_x = random.uniform(-width*0.2, width*0.2)\n shift_y = random.uniform(-height*0.2, height*0.2)\n # 原图像的平移\n if shift_x >= 0 and shift_y >= 0:\n after_shfit_image[int(shift_y):, int(\n shift_x):, :] = bgr[:height-int(shift_y), :width-int(shift_x), :]\n elif shift_x >= 0 and shift_y < 0:\n after_shfit_image[:height+int(shift_y), int(shift_x) :, :] = bgr[-int(shift_y):, : width-int(shift_x), :]\n elif shift_x < 0 and shift_y >= 0:\n after_shfit_image[int(shift_y):, : width+int(shift_x),\n :] = bgr[: height-int(shift_y), -int(shift_x):, :]\n elif shift_x < 0 and shift_y < 0:\n after_shfit_image[: height+int(shift_y), : width+int(\n shift_x), :] = bgr[-int(shift_y):, -int(shift_x):, :]\n\n shift_xy = torch.FloatTensor(\n [[int(shift_x), int(shift_y)]]).expand_as(center)\n center = center + shift_xy\n mask1 = (center[:, 0] > 0) & (center[:, 0] < width)\n mask2 = (center[:, 1] > 0) & (center[:, 1] < height)\n mask = (mask1 & mask2).view(-1, 1)\n boxes_in = boxes[mask.expand_as(boxes)].view(-1, 4)\n if len(boxes_in) == 0:\n return bgr, boxes, labels\n box_shift = torch.FloatTensor(\n [[int(shift_x), int(shift_y), int(shift_x), int(shift_y)]]).expand_as(boxes_in)\n boxes_in = boxes_in+box_shift\n labels_in = labels[mask.view(-1)]\n return after_shfit_image, boxes_in, labels_in\n return bgr, boxes, labels\n\n def BGR2RGB(self, img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n def BGR2HSV(self, img):\n return cv2.cvtColor(img, cv2.COLOR_BGR2HSV)\n\n def HSV2BGR(self, img):\n return cv2.cvtColor(img, cv2.COLOR_HSV2BGR)\n\n def randomScale(self, bgr, boxes):\n # 固定住高度,以0.8-1.2伸缩宽度,做图像形变\n if random.random() < 0.5:\n scale = random.uniform(0.8, 1.2)\n height, width, c = bgr.shape\n bgr = cv2.resize(bgr, (int(width*scale), height))\n scale_tensor = torch.FloatTensor(\n [[scale, 1, scale, 1]]).expand_as(boxes)\n boxes = boxes * scale_tensor\n return bgr, boxes\n return bgr, boxes\n\n def randomCrop(self, bgr, boxes, labels):\n if random.random() < 0.5:\n center = (boxes[:, 2:]+boxes[:, :2])/2\n height, width, c = bgr.shape\n h = random.uniform(0.6*height, height)\n w = random.uniform(0.6*width, width)\n x = random.uniform(0, width-w)\n y = random.uniform(0, height-h)\n x, y, h, w = int(x), int(y), int(h), int(w)\n\n center = center - torch.FloatTensor([[x, y]]).expand_as(center)\n mask1 = (center[:, 0] > 0) & (center[:, 0] < w)\n mask2 = (center[:, 1] > 0) & (center[:, 1] < h)\n mask = (mask1 & mask2).view(-1, 1)\n\n boxes_in = boxes[mask.expand_as(boxes)].view(-1, 4)\n if(len(boxes_in) == 0):\n return bgr, boxes, labels\n box_shift = torch.FloatTensor([[x, y, x, y]]).expand_as(boxes_in)\n\n boxes_in = boxes_in - box_shift\n boxes_in[:, 0] = boxes_in[:, 0].clamp_(min=0, max=w)\n boxes_in[:, 2] = boxes_in[:, 2].clamp_(min=0, max=w)\n boxes_in[:, 1] = boxes_in[:, 1].clamp_(min=0, max=h)\n boxes_in[:, 3] = boxes_in[:, 3].clamp_(min=0, max=h)\n\n labels_in = labels[mask.view(-1)]\n img_croped = bgr[y:y+h, x:x+w, :]\n return img_croped, boxes_in, labels_in\n return bgr, boxes, labels\n\n def subMean(self, bgr, mean):\n mean = np.array(mean, dtype=np.float32)\n bgr = bgr - mean\n return bgr\n\n def random_bright(self, im, delta=16):\n alpha = random.random()\n if alpha > 0.3:\n im = im * alpha + random.randrange(-delta, delta)\n im = im.clip(min=0, max=255).astype(np.uint8)\n return im\n\n def _putGaussianMap(self, center, crop_size_y, crop_size_x, stride, sigma):\n \"\"\"\n 根据一个中心点,生成一个heatmap\n :param center:\n :return:\n \"\"\"\n grid_y = crop_size_y / stride\n grid_x = crop_size_x / stride\n start = stride / 2.0 - 0.5\n y_range = [i for i in range(int(grid_y))]\n x_range = [i for i in range(int(grid_x))]\n xx, yy = np.meshgrid(x_range, y_range)\n xx = xx * stride + start\n yy = yy * stride + start\n d2 = (xx - center[0]) ** 2 + (yy - center[1]) ** 2\n exponent = d2 / 2.0 / sigma / sigma\n heatmap = np.exp(-exponent)\n return heatmap\n\n def _putGaussianMaps(self, keypoints, crop_size_y, crop_size_x, stride, sigma):\n \"\"\"\n\n :param keypoints: (15,2)\n :param crop_size_y: int\n :param crop_size_x: int\n :param stride: int\n :param sigma: float\n :return:\n \"\"\"\n all_keypoints = keypoints\n point_num = all_keypoints.shape[0]\n heatmaps_this_img = []\n for k in range(point_num):\n heatmap = self._putGaussianMap(\n all_keypoints[k], crop_size_y, crop_size_x, stride, sigma)\n heatmap = heatmap[np.newaxis, ...]\n heatmaps_this_img.append(heatmap)\n # (num_joint,crop_size_y/stride,crop_size_x/stride)\n heatmaps_this_img = np.concatenate(heatmaps_this_img, axis=0)\n return heatmaps_this_img\n\n def random_rotate(self, image, angle=5.):\n angle = np.random.uniform(-angle, angle)\n\n h, w, _ = image.shape\n m = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1)\n image = cv2.warpAffine(\n image, m, (w, h), borderMode=cv2.BORDER_REFLECT101)\n\n return image\n\n def random_distort(self, image, hue, saturation, exposure):\n # determine scale factors\n dhue = np.random.uniform(-hue, hue)\n dsat = np.random.uniform(1. / saturation, saturation)\n dexp = np.random.uniform(1. / exposure, exposure)\n\n image = 255 * np.array(image).astype('uint8')\n # convert RGB space to HSV space\n image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV).astype('float')\n\n # change satuation and exposure\n image[:, :, 1] *= dsat\n image[:, :, 2] *= dexp\n\n # change hue\n image[:, :, 0] += dhue\n\n image[:, :, 0] = np.clip(image[:, :, 0], 0., 179.)\n image[:, :, 1] = np.clip(image[:, :, 1], 0., 255.)\n image[:, :, 2] = np.clip(image[:, :, 2], 0., 255.)\n\n # convert back to RGB from HSV\n return cv2.cvtColor(image.astype('uint8'), cv2.COLOR_HSV2RGB)\n\n def random_add_smu(self, image):\n _smu = cv2.imread(\n '/media/home_bak/ziqi/park/Hourglass_nocrop/noise/smu.jpg')\n if random.randint(0, 1):\n rows = random.randint(0, _smu.shape[0] - image.shape[0])\n cols = random.randint(0, _smu.shape[1] - image.shape[1])\n add_smu = _smu[rows:rows + image.shape[0],\n cols:cols + image.shape[1]]\n image = cv2.bitwise_not(image)\n image = cv2.bitwise_and(add_smu, image)\n image = cv2.bitwise_not(image)\n return image\n\n\nclass GenerateHeatmap():\n def __init__(self, output_res, num_parts):\n self.output_res = output_res\n self.num_parts = num_parts\n sigma = self.output_res / 48\n self.sigma = sigma\n size = 6 * sigma + 3\n x = np.arange(0, size, 1, float)\n y = x[:, np.newaxis]\n x0, y0 = 3 * sigma + 1, 3 * sigma + 1\n self.g = np.exp(- ((x - x0) ** 2 + (y - y0) ** 2) / (2 * sigma ** 2))\n\n def __call__(self, keypoints):\n hms = np.zeros(shape=(self.num_parts, self.output_res,\n self.output_res), dtype=np.float32)\n sigma = self.sigma\n for idx, pt in enumerate(keypoints):\n if pt[0] > 0:\n x, y = int(pt[0]), int(pt[1])\n if x < 0 or y < 0 or x >= self.output_res or y >= self.output_res:\n continue\n ul = int(x - 3 * sigma - 1), int(y - 3 * sigma - 1)\n br = int(x + 3 * sigma + 2), int(y + 3 * sigma + 2)\n\n c, d = max(0, -ul[0]), min(br[0], self.output_res) - ul[0]\n a, b = max(0, -ul[1]), min(br[1], self.output_res) - ul[1]\n\n cc, dd = max(0, ul[0]), min(br[0], self.output_res)\n aa, bb = max(0, ul[1]), min(br[1], self.output_res)\n hms[idx, aa:bb, cc:dd] = np.maximum(\n hms[idx, aa:bb, cc:dd], self.g[a:b, c:d])\n return hms\n", "import torch.nn as nn\nfrom torch.nn import Upsample\n\n\nclass HourGlass(nn.Module):\n \"\"\"不改变特征图的高宽\"\"\"\n\n def __init__(self, n=5, f=128):\n \"\"\"\n :param n: hourglass模块的层级数目\n :param f: hourglass模块中的特征图数量\n :return:\n \"\"\"\n super(HourGlass, self).__init__()\n self._n = n\n self._f = f\n self._init_layers(self._n, self._f)\n\n def _init_layers(self, n, f):\n # 上分支\n setattr(self, 'res'+str(n)+'_1', Residual(f, f))\n # 下分支\n setattr(self, 'pool'+str(n)+'_1', nn.MaxPool2d(2, 2))\n setattr(self, 'res'+str(n)+'_2', Residual(f, f))\n if n > 1:\n self._init_layers(n-1, f)\n else:\n self.res_center = Residual(f, f)\n setattr(self, 'res'+str(n)+'_3', Residual(f, f))\n setattr(self, 'unsample'+str(n), Upsample(scale_factor=2))\n\n def _forward(self, x, n, f):\n # 上分支\n up1 = x\n up1 = eval('self.res'+str(n)+'_1')(up1)\n # 下分支\n low1 = eval('self.pool'+str(n)+'_1')(x)\n low1 = eval('self.res'+str(n)+'_2')(low1)\n if n > 1:\n low2 = self._forward(low1, n-1, f)\n else:\n low2 = self.res_center(low1)\n low3 = low2\n low3 = eval('self.'+'res'+str(n)+'_3')(low3)\n up2 = eval('self.'+'unsample'+str(n)).forward(low3)\n\n return up1+up2\n\n def forward(self, x):\n return self._forward(x, self._n, self._f)\n\n\nclass Residual(nn.Module):\n \"\"\"\n 残差模块,并不改变特征图的宽高\n \"\"\"\n\n def __init__(self, ins, outs):\n super(Residual, self).__init__()\n # 卷积模块\n self.convBlock = nn.Sequential(\n nn.BatchNorm2d(ins),\n nn.ReLU(inplace=True),\n nn.Conv2d(ins, outs//2, 1),\n nn.BatchNorm2d(outs//2),\n nn.ReLU(inplace=True),\n nn.Conv2d(outs//2, outs//2, 3, 1, 1),\n nn.BatchNorm2d(outs//2),\n nn.ReLU(inplace=True),\n nn.Conv2d(outs//2, outs, 1)\n )\n # 跳层\n if ins != outs:\n self.skipConv = nn.Conv2d(ins, outs, 1)\n self.ins = ins\n self.outs = outs\n\n def forward(self, x):\n residual = x\n x = self.convBlock(x)\n if self.ins != self.outs:\n residual = self.skipConv(residual)\n x += residual\n return x\n\n\nclass Lin(nn.Module):\n def __init__(self, numIn=128, numout=2):\n super(Lin, self).__init__()\n self.conv = nn.Conv2d(numIn, numout, 1)\n self.bn = nn.BatchNorm2d(numout)\n self.relu = nn.ReLU(inplace=True)\n\n def forward(self, x):\n return self.relu(self.bn(self.conv(x)))\n\n\nclass KFSGNet(nn.Module):\n\n def __init__(self):\n super(KFSGNet, self).__init__()\n self.__conv1 = nn.Conv2d(3, 64, 1)\n self.__relu1 = nn.ReLU(inplace=True)\n self.__conv2 = nn.Conv2d(64, 128, 1)\n self.__relu2 = nn.ReLU(inplace=True)\n self.__hg = HourGlass()\n self.__lin = Lin()\n\n def forward(self, x):\n x = self.__relu1(self.__conv1(x))\n x = self.__relu2(self.__conv2(x))\n x = self.__hg(x)\n x = self.__lin(x)\n return x\n" ]
[ [ "numpy.dot", "numpy.expand_dims", "numpy.float32", "numpy.array", "numpy.mat", "numpy.loadtxt" ], [ "torch.utils.data.DataLoader" ], [ "numpy.expand_dims", "numpy.asarray", "numpy.concatenate", "numpy.seterr", "torch.FloatTensor", "numpy.exp", "numpy.random.randint", "numpy.clip", "numpy.arange", "numpy.uint8", "torch.tensor", "numpy.sin", "numpy.float32", "numpy.zeros", "numpy.transpose", "numpy.meshgrid", "numpy.array", "numpy.maximum", "numpy.cos", "numpy.random.uniform" ], [ "torch.nn.Conv2d", "torch.nn.MaxPool2d", "torch.nn.Upsample", "torch.nn.BatchNorm2d", "torch.nn.ReLU" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
vlievin/booster-pytorch
[ "a8f447160c30224112731a25f90f6f97126a34b2" ]
[ "booster/logging/logger.py" ]
[ "import logging\nimport os\nimport sys\nimport warnings\nfrom collections import namedtuple\nfrom typing import *\n\nimport matplotlib.image\nimport matplotlib.pyplot as plt\nfrom torch import Tensor\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom booster import Diagnostic\nfrom .datatracker import DataTracker\n\nBestScore = namedtuple('BestScore', ['step', 'epoch', 'value', 'summary'])\n\n\nclass BaseLogger():\n def __init__(self, key, logdir):\n self.key = key\n self.logdir = logdir\n\n def log_diagnostic(self, global_step: int, epoch: int, summary: Diagnostic, **kwargs):\n raise NotImplementedError\n\n def log_image(self, key: str, global_step: int, epoch: int, img_tensor: Tensor):\n raise NotImplementedError\n\n\nclass TensorboardLogger(BaseLogger):\n def __init__(self, *args, **kwargs):\n super().__init__(*args)\n\n self.writer = SummaryWriter(os.path.join(self.logdir, self.key))\n\n def log_diagnostic(self, global_step: int, epoch: int, summary: Diagnostic, **kwargs):\n summary.log(self.writer, global_step)\n\n def log_image(self, key: str, global_step: int, epoch: int, img_tensor: Tensor):\n self.writer.add_image(key, img_tensor, global_step=global_step)\n\n\nclass LoggingLogger(BaseLogger):\n def __init__(self, *args, diagnostic_keys=['loss'], **kwargs):\n super().__init__(*args)\n\n self.logger = logging.getLogger(self.key)\n\n # logFormatter = logging.Formatter('%(asctime)s %(name)-4s %(levelname)-4s %(message)s')\n #\n # fileHandler = logging.FileHandler(os.path.join(self.logdir, 'run.log'))\n # fileHandler.setFormatter(logFormatter)\n # self.logger.addHandler(fileHandler)\n #\n # consoleHandler = logging.StreamHandler(sys.stdout)\n # consoleHandler.setFormatter(logFormatter)\n # self.logger.addHandler(consoleHandler)\n\n self.logger.setLevel(logging.INFO)\n\n self.diagnostic_keys = diagnostic_keys\n\n def log_diagnostic(self, global_step: int, epoch: int, summary: Diagnostic, best_score: Optional[BestScore] = None,\n **kwargs):\n for stats_key in self.diagnostic_keys:\n if not stats_key in summary.keys():\n self.logger.warning('key ' + str(stats_key) + ' not in summary.')\n else:\n message = f'[{global_step} / {epoch}] '\n message += ''.join([f'{k} {v:6.2f} ' for k, v in summary.get(stats_key).items()])\n if \"info\" in summary.keys() and \"elapsed-time\" in summary[\"info\"].keys():\n message += f'({summary[\"info\"][\"elapsed-time\"]:.2f}s /iter)'\n else:\n warnings.warn(\n f\"Summary does not contain the key info/elapsed-time. The elapsed time won't be displayed.\")\n if best_score is not None:\n message += f' (best: {best_score.value:6.2f} [{best_score.step} | {best_score.epoch}])'\n\n self.logger.info(message)\n\n def log_image(self, key: str, global_step: int, epoch: int, img_tensor: Tensor):\n pass\n\n\nclass PlotLogger(BaseLogger):\n def __init__(self, *args, diagnostic_keys=['loss'], **kwargs):\n super().__init__(*args)\n self.diagnostic_keys = diagnostic_keys\n self.tracker = DataTracker(label=self.key)\n\n def log_diagnostic(self, global_step: int, epoch: int, summary: Diagnostic, **kwargs):\n for key in self.diagnostic_keys:\n self.tracker.append(global_step, summary[key])\n\n def plot(self, *args, **kwargs):\n self.tracker.plot(*args, **kwargs)\n\n def log_image(self, key: str, global_step: int, epoch: int, img_tensor: Tensor):\n img = img_tensor.data.permute(1, 2, 0).cpu().numpy()\n matplotlib.image.imsave(os.path.join(self.logdir, f\"{key}.png\"), img)\n\n\nclass PlotHandler(List):\n def __init__(self, logdir, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.path = os.path.join(logdir, \"curves.png\")\n\n def plot(self):\n\n if len(self):\n logger = self[0]\n keys = logger.tracker.data.keys()\n\n plt.figure(figsize=(4 * len(keys), 3))\n for i, key in enumerate(keys):\n plt.subplot(1, len(keys), i + 1)\n plt.title(key)\n for logger in self:\n logger.plot(key)\n plt.legend()\n\n plt.savefig(self.path)\n\n\nclass Logger(BaseLogger):\n def __init__(self, key, logdir, tensorboard=True, logging=True, plot=True, **kwargs):\n super().__init__(key, logdir)\n\n self.loggers = []\n\n if tensorboard:\n self.loggers += [TensorboardLogger(key, logdir, **kwargs)]\n\n if logging:\n self.loggers += [LoggingLogger(key, logdir, **kwargs)]\n\n if plot:\n self.loggers += [PlotLogger(key, logdir, **kwargs)]\n\n def log_diagnostic(self, *args, **kwargs):\n for logger in self.loggers:\n logger.log_diagnostic(*args, **kwargs)\n\n def log_image(self, *args, **kwargs):\n for logger in self.loggers:\n logger.log_image(*args, **kwargs)\n\n\nclass LoggerManager():\n\n def __init__(self, logdir, **kwargs):\n self.logdir = logdir\n self.kwargs = kwargs\n\n self.loggers = {}\n\n self.plot_handler = PlotHandler(self.logdir)\n\n def init_logger(self, key):\n self.loggers[key] = Logger(key, self.logdir, **self.kwargs)\n\n # mappend PlotLogger to PlotHandler\n for logger in self.loggers[key].loggers:\n if isinstance(logger, PlotLogger):\n self.plot_handler.append(logger)\n\n def log_diagnostic(self, key, step, epoch, summary, **kwargs):\n if key not in self.loggers:\n self.init_logger(key)\n\n self.loggers[key].log_diagnostic(step, epoch, summary, **kwargs)\n\n self.plot_handler.plot()\n\n def log_image(self, key, image_key, step, epoch, img_tensor, **kwargs):\n if key not in self.loggers:\n self.init_logger(key)\n\n self.loggers[key].log_image(image_key, step, epoch, img_tensor, **kwargs)\n" ]
[ [ "matplotlib.pyplot.legend", "matplotlib.pyplot.title", "matplotlib.pyplot.savefig" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
thunlp/AMNRE
[ "16970d9887561c75886123828960943b7efc9c62" ]
[ "CNN/src/models.py" ]
[ "from __future__ import print_function\nimport torch\nfrom torch import nn\nimport numpy as np\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom constant import *\nfrom torch.nn.utils.rnn import pack_padded_sequence\n\nclass EncoderGRU(nn.Module):\n def __init__(self,\n vocab_size,emb_dim,emb,\n hidden_dim,\n nlayers,\n pad_token,\n bidir=False):\n #emb---np wordVec vocab_size=len(emb)\n super(EncoderGRU,self).__init__()\n #self.word_emb=nn.Embedding(vocab_size,emb_dim,pad_token)\n #self.word_emb.weight.data.copy_(torch.from_numpy(emb))\n #self.pos1_emb=nn.Embedding(MaxPos,dimWPE)\n #self.pos2_emb=nn.Embedding(MaxPos,dimWPE)\n self.hidden_dim=hidden_dim\n self.emb_dim=emb_dim+dimWPE*2\n self.nlayers=nlayers\n self.bidir=bidir\n #using gru\n self.gru=nn.GRU(\n self.emb_dim//2 if bidir else self.emb_dim,\n self.hidden_dim,\n self.nlayers,\n bidirectional=bidir,\n batch_first=True\n )\n def forward(self,input_,pos1,pos2):\n embd=self.word_emb(input_)\n pos1=self.pos1_emb(pos1)\n pos2=self.pos2_emb(pos2)\n embd=torch.cat((embd,pos1,pos2),2)\n #using gru\n _,h_t_=self.encoder(embed)\n h_t=torch.cat((h_t_[-1],h_t_[-2]),1)if self.bidir else h_t_[-1]\n return h_t\nclass EncoderCNN(nn.Module):\n def __init__(self,\n vocab_size,emb,emb_dim=dimWE,\n hidden_dim=dimC,lang=0):\n #emb---np wordVec vocab_size=len(emb)\n super(EncoderCNN,self).__init__()\n self.lang=lang\n self.word_emb=nn.Embedding(vocab_size,emb_dim)\n self.word_emb.weight.data.copy_(torch.from_numpy(emb))\n self.pos1_emb=nn.Embedding(MaxPos,dimWPE)\n self.pos2_emb=nn.Embedding(MaxPos,dimWPE)\n self.maxPooling=nn.MaxPool1d(SenLen[self.lang]-2)\n self.emb_dim=emb_dim+dimWPE*2\n self.hidden_dim=hidden_dim\n #using CNN\n self.tanh=nn.Tanh()\n self.conv=nn.Conv1d(self.emb_dim,hidden_dim,filter_size)\n self.dropout=nn.Dropout(p=CNNDropout)\n def forward(self,inp,pos1,pos2):\n Len=inp.size(0)\n embd=self.word_emb(inp)\n pos1=self.pos1_emb(pos1)\n pos2=self.pos2_emb(pos2)\n embd=torch.cat((embd,pos1,pos2),2).transpose(1,2)\n conved=self.conv(embd)\n pooled=self.maxPooling(conved).view(Len,dimC)\n out=self.tanh(pooled)\n return self.dropout(out)\nclass CNNEncoder(nn.Module):\n def __init__(self,vocab_en,emb_en,vocab_zh,emb_zh):\n super(CNNEncoder,self).__init__()\n self.encoder_en=EncoderCNN(vocab_en,emb_en,dimWE,dimC,0)\n self.encoder_zh=EncoderCNN(vocab_zh,emb_zh,dimWE,dimC,1)\n def forward(self,wordsEn,pos1En,pos2En,wordsZh,pos1Zh,pos2Zh):\n return self.encoder_en(wordsEn,pos1En,pos2En),self.encoder_zh(wordsZh,pos1Zh,pos2Zh)\nclass Discriminator(nn.Module):\n def __init__(self,\n dis_input_dim=Encodered_dim,\n nlayers=dis_layers,\n hidden_dim=dis_hidden_dim,\n input_dropout=dis_input_dropout,\n dropout=dis_dropout):\n super(Discriminator,self).__init__()\n self.dis_input=dis_input_dim\n layers=[nn.Dropout(input_dropout)]\n for i in range(0,nlayers+1):\n input_dim=self.dis_input if i==0 else hidden_dim\n output_dim=1 if i==nlayers else hidden_dim\n layers.append(nn.Linear(input_dim,output_dim))\n if i<nlayers:\n layers.append(nn.LeakyReLU(0.2))\n layers.append(nn.Dropout(dropout))\n layers.append(nn.Sigmoid())\n self.layers=nn.Sequential(*layers)\n def forward(self,inp):\n assert inp.dim()==2 and inp.size(1)==self.dis_input\n return self.layers(inp).view(-1)\nclass MultiRE(nn.Module):\n def __init__(self):\n super(MultiRE,self).__init__()\n self.relation_emb=nn.Embedding(dimR,Encodered_dim)\n self.dropout=nn.Dropout(p=Att_dropout)\n #self.softmax=nn.Softmax()\n #self.logsoftmax=nn.LogSoftmax()\n self.M=nn.Linear(Encodered_dim,dimR)\n def forward(self,inp_en,r_en,l_en,inp_zh,r_zh,l_zh,re_mask):\n NumRe=r_en.size(0)\n NumIn=l_zh.size(0)\n relation_en=self.relation_emb(r_en)\n relation_zh=self.relation_emb(r_zh)\n attn_en=torch.sum(relation_en*inp_en,2)\n attn_zh=torch.sum(relation_zh*inp_zh,2)\n p=Variable(torch.cuda.FloatTensor(NumIn,NumRe).fill_(0.0))\n L_en=0\n L_zh=0\n R_vec=Variable(torch.cuda.FloatTensor(NumIn,NumRe,Encodered_dim).fill_(0.0))\n S=Variable(torch.cuda.FloatTensor(NumIn,NumRe,Encodered_dim).fill_(0.0))\n for i in range(0,NumIn):\n R_en=L_en+l_en[i].data[0]\n R_zh=L_zh+l_zh[i].data[0]\n if R_en>L_en and R_zh>L_zh:\n Att=F.softmax(torch.cat((attn_en[:,L_en:R_en],attn_zh[:,L_zh:R_zh]),1),1)\n S[i]=self.dropout(torch.matmul(Att,torch.cat((inp_en[L_en:R_en],inp_zh[L_zh:R_zh]),0)))\n R_vec[i]=relation_en[:,L_en,:]\n elif R_en>L_en:\n Att=F.softmax(attn_en[:,L_en:R_en],1)\n S[i]=self.dropout(torch.matmul(Att,inp_en[L_en:R_en]))\n R_vec[i]=relation_en[:,L_en,:]\n elif R_zh>L_zh:\n Att=F.softmax(attn_zh[:,L_zh:R_zh],1)\n S[i]=self.dropout(torch.matmul(Att,inp_zh[L_zh:R_zh]))\n R_vec[i]=relation_zh[:,L_zh,:]\n else:\n print(\"ERR NO sentences\")\n exit()\n L_en=R_en\n L_zh=R_zh\n p_n=F.log_softmax(self.M(S)+torch.sum(R_vec*S,2).view(NumIn,NumRe,1),2).view(NumIn,NumRe,dimR)\n return p_n[re_mask].view(NumIn,NumRe)\nclass MonoRE(nn.Module):\n def __init__(self):\n super(MonoRE,self).__init__()\n self.relation_emb=nn.Embedding(dimR,Encodered_dim)\n self.dropout=nn.Dropout(p=Att_dropout)\n #self.softmax=nn.Softmax()\n #self.logsoftmax=nn.LogSoftmax()\n self.M=nn.Linear(Encodered_dim,dimR)\n def forward(self,inp,r,l,re_mask):\n NumRe=r.size(0)\n NumIn=l.size(0)\n relation=self.relation_emb(r)\n attn=torch.sum(relation*inp,2)\n p=Variable(torch.cuda.FloatTensor(NumIn,NumRe).fill_(0.0))\n L=0\n R_vec=Variable(torch.cuda.FloatTensor(NumIn,NumRe,Encodered_dim).fill_(0.0))\n S=Variable(torch.cuda.FloatTensor(NumIn,NumRe,Encodered_dim).fill_(0.0))\n for i in range(0,NumIn):\n R=L+l[i].data[0]\n if R>L:\n Att=F.softmax(attn[:,L:R],1)\n S[i]=self.dropout(torch.matmul(Att,inp[L:R]))\n R_vec[i]=relation[:,L,:]\n L=R\n p_n=F.log_softmax((self.M(S)+torch.sum(R_vec*S,2).view(NumIn,NumRe,1)),2).view(NumIn,NumRe,dimR)\n return p_n[re_mask].view(NumIn,NumRe)\n\nclass AMRE(nn.Module):\n def __init__(self,emb_en,emb_zh):\n super(AMRE,self).__init__()\n self.encoder=CNNEncoder(len(emb_en),emb_en,len(emb_zh),emb_zh).cuda()\n self.enRE=MonoRE().cuda()\n self.zhRE=MonoRE().cuda()\n def forward(self,wordsEn,pos1En,pos2En,rEn,lEn,wordsZh,pos1Zh,pos2Zh,rZh,lZh,re_mask):\n inp_en,inp_zh=self.encoder(wordsEn,pos1En,pos2En,wordsZh,pos1Zh,pos2Zh)\n return self.enRE(inp_en,rEn,lEn,re_mask)+self.zhRE(inp_zh,rZh,lZh,re_mask)\nclass MARE(nn.Module):\n def __init__(self,emb_en,emb_zh):\n super(MARE,self).__init__()\n self.D=Discriminator().cuda()\n self.share_encoder=CNNEncoder(len(emb_en),emb_en,len(emb_zh),emb_zh).cuda()\n self.multiRE=MultiRE().cuda()\n self.monoRE=AMRE(emb_en,emb_zh)\n def Orth_con(self,wordsEn,pos1En,pos2En,wordsZh,pos1Zh,pos2Zh):\n share_en,share_zh=self.share_encoder(wordsEn,pos1En,pos2En,wordsZh,pos1Zh,pos2Zh)\n mono_en,mono_zh=self.monoRE.encoder(wordsEn,pos1En,pos2En,wordsZh,pos1Zh,pos2Zh)\n share=torch.cat((share_en,share_zh),0)\n mono=torch.cat((mono_en,mono_zh),0)\n share-=torch.mean(share,0)\n mono-=torch.mean(mono,0)\n share=F.normalize(share,2,1)\n mono=F.normalize(mono,2,1)\n correlation_mat=torch.matmul(share.transpose(0,1),mono)\n cost=torch.mean(correlation_mat*correlation_mat)\n return cost\n def forward(self,wordsEn,pos1En,pos2En,rEn,lEn,wordsZh,pos1Zh,pos2Zh,rZh,lZh,re_mask):\n share_en,share_zh=self.share_encoder(wordsEn,pos1En,pos2En,wordsZh,pos1Zh,pos2Zh)\n return self.monoRE(wordsEn,pos1En,pos2En,rEn,lEn,wordsZh,pos1Zh,pos2Zh,rZh,lZh,re_mask)+self.multiRE(share_en,rEn,lEn,share_zh,rZh,lZh,re_mask)\n" ]
[ [ "torch.nn.functional.normalize", "torch.nn.Sequential", "torch.nn.Dropout", "torch.mean", "torch.nn.functional.softmax", "torch.cat", "torch.nn.GRU", "torch.sum", "torch.from_numpy", "torch.nn.Embedding", "torch.nn.Tanh", "torch.nn.Sigmoid", "torch.nn.MaxPool1d", "torch.nn.Linear", "torch.cuda.FloatTensor", "torch.matmul", "torch.nn.LeakyReLU", "torch.nn.Conv1d" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
Lan-Jing/Courses
[ "540db9499b8725ca5b82a2c4e7a3da09f73c0efa", "540db9499b8725ca5b82a2c4e7a3da09f73c0efa", "540db9499b8725ca5b82a2c4e7a3da09f73c0efa" ]
[ "DCS311 Artificial Intelligence/KNN/lab1_code/M3/dist.py", "DCS311 Artificial Intelligence/CNN/main.py", "DCS311 Artificial Intelligence/RNN/nn.py" ]
[ "# module for distance computation;\nimport numpy as np\n\ndef dist(arraya, arrayb, mode):\n if mode == 0:\n dis = np.sum(np.abs(np.subtract(arraya, arrayb)))\n elif mode == 1:\n dis = np.sqrt(np.sum(np.power(np.subtract(arraya, arrayb), 2)))\n else:\n dis = 1 - np.dot(arraya, arrayb) / np.sqrt(np.sum(np.power(arraya, 2)) * np.sum(np.power(arrayb, 2)))\n return dis\n\n\ndef corr(arraya, arrayb, show):\n a = np.subtract(arraya, np.mean(arraya))\n b = np.subtract(arrayb, np.mean(arrayb))\n corr = np.sum(np.multiply(a, b)) / np.sqrt(np.multiply(np.sum(np.power(a, 2)), np.sum(np.power(b, 2)))) \n return corr", "#%%\nimport data\nimport helper as hp\nimport cnn\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\ntransform = 'default'\n\nlearnRate = 0.001\nmomentum = 0.9\nepoch = 10\n\ncriterion = nn.CrossEntropyLoss()\n\nnum_device = 2\ndevice = torch.device(\"cuda:{}\".format(num_device) if torch.cuda.is_available() else \"cpu\")\ntofile = 1\n\ndef main():\n cifar = data.cifar10Dataset(path='../data', transform=transform, train=True)\n trainLoader, validLoader = data.data_split(cifar, batch_size=4, shuffle=True)\n\n # output sample graphs\n hp.print_sample(trainLoader, transform != 'default')\n\n # define network and optimizer\n net = cnn.VGG3_final().float().to(device)\n optimizer = optim.SGD(net.parameters(), learnRate, momentum)\n\n # training\n accList, lossList = cnn.train(net, optimizer, criterion, trainLoader, validLoader, epoch, device)\n # plot training and validation loss\n hp.plot_curve(lossList, \"Train and Validation Loss\", [\"train\", \"validation\"], tofile)\n hp.plot_curve(accList, \"Train and Validation Accuracy\", [\"train\", \"validation\"], tofile)\n # testing\n cnn.test(net, validLoader, device)\n\nif __name__ == \"__main__\":\n main()\n# %%\n", "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.nn.utils.rnn as rnn\nimport torch.optim as optim\n\nclass LSTM(nn.Module):\n def __init__(self, vec_dim, hidden_dim, out_dim):\n super(LSTM, self).__init__()\n self.lstm = nn.LSTM(vec_dim, hidden_dim, batch_first = True)\n self.fc1 = nn.Linear(hidden_dim, 128)\n self.fc2 = nn.Linear(128, out_dim)\n self.dropout = nn.Dropout(0.5)\n \n def forward(self, x):\n x, _ = self.lstm(x)\n x, _ = rnn.pad_packed_sequence(x, batch_first=True)\n\n x = self.dropout(x)\n x = self.fc1(F.relu(x))\n x = self.dropout(x)\n x = self.fc2(F.relu(x))\n \n return x\n \n# pack padded data returned from loaders\ndef pack_data(data, labels, data_len, device):\n data = rnn.pack_padded_sequence(data, data_len, batch_first=True)\n labels = rnn.pack_padded_sequence(labels, data_len, batch_first=True)[0]\n return data.to(device), labels.to(device)\n \ndef train(net, optimizer, criterion, trainLoader, validLoader, epoch, device):\n accList = [[], []]\n lossList = [[], []]\n\n for i in range(epoch):\n loss = 0\n for data, labels, data_len in trainLoader:\n data, labels = pack_data(data, labels, data_len, device)\n \n optimizer.zero_grad()\n output = net(data)\n output = rnn.pack_padded_sequence(output, data_len, batch_first=True)[0]\n batchLoss = criterion(output, labels)\n batchLoss.backward()\n optimizer.step()\n loss += batchLoss.item()\n lossList[0].append(loss / len(trainLoader))\n accList[0].append(test(net, trainLoader, device))\n\n loss = 0\n for data, labels, data_len in validLoader:\n data, labels = pack_data(data, labels, data_len, device)\n \n with torch.no_grad():\n output = net(data)\n output = rnn.pack_padded_sequence(output, data_len, batch_first=True)[0]\n batchLoss = criterion(output, labels)\n loss += batchLoss.item()\n \n lossList[1].append(loss / len(validLoader))\n accList[1].append(test(net, validLoader, device))\n print('epoch:{}, trainLoss:{}, validLoss:{}'.format(i+1, lossList[0][-1], lossList[1][-1]))\n print('epoch:{}, TrainAcc:{}, validAcc:{}'.format(i+1, accList[0][-1], accList[1][-1]))\n return accList, lossList\n\ndef test(net, testLoader, device):\n total = 0\n accuracy = 0\n with torch.no_grad():\n for data, labels, data_len in testLoader:\n data, labels = pack_data(data, labels, data_len, device)\n \n output = net(data)\n output = rnn.pack_padded_sequence(output, data_len, batch_first=True)[0]\n _, predicted = torch.max(output, dim=-1)\n\n ptr = 0\n for l in data_len:\n now_predict = predicted[ptr:ptr+l]\n now_label = labels[ptr:ptr+l]\n\n accuracy += torch.equal(now_predict, now_label)\n total += 1\n ptr += l\n return accuracy / total * 100\n " ]
[ [ "numpy.dot", "numpy.multiply", "numpy.power", "numpy.subtract", "numpy.mean" ], [ "torch.nn.CrossEntropyLoss", "torch.cuda.is_available" ], [ "torch.nn.Dropout", "torch.max", "torch.nn.LSTM", "torch.nn.utils.rnn.pack_padded_sequence", "torch.equal", "torch.nn.Linear", "torch.nn.utils.rnn.pad_packed_sequence", "torch.nn.functional.relu", "torch.no_grad" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]
czuo0303/Python
[ "4866b1330bc7c77c0ed0e050e6b99efdeb026448", "c906ba82f3772173a7e90bd0918c846530439a8b" ]
[ "digital_image_processing/filters/gaussian_filter.py", "machine_learning/logistic_regression.py" ]
[ "\"\"\"\nImplementation of gaussian filter algorithm\n\"\"\"\nfrom cv2 import imread, cvtColor, COLOR_BGR2GRAY, imshow, waitKey\nfrom numpy import pi, mgrid, exp, square, zeros, ravel, dot, uint8\nfrom itertools import product\n\n\ndef gen_gaussian_kernel(k_size, sigma):\n center = k_size // 2\n x, y = mgrid[0 - center : k_size - center, 0 - center : k_size - center]\n g = 1 / (2 * pi * sigma) * exp(-(square(x) + square(y)) / (2 * square(sigma)))\n return g\n\n\ndef gaussian_filter(image, k_size, sigma):\n height, width = image.shape[0], image.shape[1]\n # dst image height and width\n dst_height = height - k_size + 1\n dst_width = width - k_size + 1\n\n # im2col, turn the k_size*k_size pixels into a row and np.vstack all rows\n image_array = zeros((dst_height * dst_width, k_size * k_size))\n row = 0\n for i, j in product(range(dst_height), range(dst_width)):\n window = ravel(image[i : i + k_size, j : j + k_size])\n image_array[row, :] = window\n row += 1\n\n # turn the kernel into shape(k*k, 1)\n gaussian_kernel = gen_gaussian_kernel(k_size, sigma)\n filter_array = ravel(gaussian_kernel)\n\n # reshape and get the dst image\n dst = dot(image_array, filter_array).reshape(dst_height, dst_width).astype(uint8)\n\n return dst\n\n\nif __name__ == \"__main__\":\n # read original image\n img = imread(r\"../image_data/lena.jpg\")\n # turn image in gray scale value\n gray = cvtColor(img, COLOR_BGR2GRAY)\n\n # get values with two different mask size\n gaussian3x3 = gaussian_filter(gray, 3, sigma=1)\n gaussian5x5 = gaussian_filter(gray, 5, sigma=0.8)\n\n # show result images\n imshow(\"gaussian filter with 3x3 mask\", gaussian3x3)\n imshow(\"gaussian filter with 5x5 mask\", gaussian5x5)\n waitKey()\n", "#!/usr/bin/python\n\n# Logistic Regression from scratch\n\n# In[62]:\n\n# In[63]:\n\n# importing all the required libraries\n\n\"\"\"\nImplementing logistic regression for classification problem\nHelpful resources:\nCoursera ML course\nhttps://medium.com/@martinpella/logistic-regression-from-scratch-in-python-124c5636b8ac\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# get_ipython().run_line_magic('matplotlib', 'inline')\n\nfrom sklearn import datasets\n\n\n# In[67]:\n\n# sigmoid function or logistic function is used as a hypothesis function in\n# classification problems\n\n\ndef sigmoid_function(z):\n return 1 / (1 + np.exp(-z))\n\n\ndef cost_function(h, y):\n return (-y * np.log(h) - (1 - y) * np.log(1 - h)).mean()\n\n\ndef log_likelihood(X, Y, weights):\n scores = np.dot(X, weights)\n return np.sum(Y * scores - np.log(1 + np.exp(scores)))\n\n\n# here alpha is the learning rate, X is the feature matrix,y is the target matrix\ndef logistic_reg(alpha, X, y, max_iterations=70000):\n theta = np.zeros(X.shape[1])\n\n for iterations in range(max_iterations):\n z = np.dot(X, theta)\n h = sigmoid_function(z)\n gradient = np.dot(X.T, h - y) / y.size\n theta = theta - alpha * gradient # updating the weights\n z = np.dot(X, theta)\n h = sigmoid_function(z)\n J = cost_function(h, y)\n if iterations % 100 == 0:\n print(f\"loss: {J} \\t\") # printing the loss after every 100 iterations\n return theta\n\n\n# In[68]:\n\nif __name__ == \"__main__\":\n iris = datasets.load_iris()\n X = iris.data[:, :2]\n y = (iris.target != 0) * 1\n\n alpha = 0.1\n theta = logistic_reg(alpha, X, y, max_iterations=70000)\n print(\"theta: \", theta) # printing the theta i.e our weights vector\n\n def predict_prob(X):\n return sigmoid_function(\n np.dot(X, theta)\n ) # predicting the value of probability from the logistic regression algorithm\n\n plt.figure(figsize=(10, 6))\n plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color=\"b\", label=\"0\")\n plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color=\"r\", label=\"1\")\n (x1_min, x1_max) = (X[:, 0].min(), X[:, 0].max())\n (x2_min, x2_max) = (X[:, 1].min(), X[:, 1].max())\n (xx1, xx2) = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))\n grid = np.c_[xx1.ravel(), xx2.ravel()]\n probs = predict_prob(grid).reshape(xx1.shape)\n plt.contour(xx1, xx2, probs, [0.5], linewidths=1, colors=\"black\")\n\n plt.legend()\n plt.show()\n" ]
[ [ "numpy.square", "numpy.ravel", "numpy.dot", "numpy.zeros" ], [ "numpy.dot", "matplotlib.pyplot.legend", "numpy.log", "matplotlib.pyplot.scatter", "numpy.linspace", "sklearn.datasets.load_iris", "matplotlib.pyplot.contour", "numpy.exp", "matplotlib.pyplot.show", "numpy.zeros", "matplotlib.pyplot.figure" ] ]
[ { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] }, { "matplotlib": [], "numpy": [], "pandas": [], "scipy": [], "tensorflow": [] } ]