code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import unittest import numpy as np from revgraph.core.values.variable import Variable class VariableTestCase(unittest.TestCase): def test_variable_is_mutable(self): a = Variable(np.zeros((3,3))) a.data += 1 self.assertTrue((a.data == np.ones((3,3))).all())
[ "numpy.zeros", "numpy.ones" ]
[((194, 210), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {}), '((3, 3))\n', (202, 210), True, 'import numpy as np\n'), ((266, 281), 'numpy.ones', 'np.ones', (['(3, 3)'], {}), '((3, 3))\n', (273, 281), True, 'import numpy as np\n')]
import os import torch import numpy as np import cv2 from models.net_rfb import RFB from models.retinaface import RetinaFace from data import cfg_rfb, cfg_mnet, cfg_slim def check_keys(model, pretrained_state_dict): ckpt_keys = set(pretrained_state_dict.keys()) model_keys = set(model.state_dict().keys()) used_pretrained_keys = model_keys & ckpt_keys unused_pretrained_keys = ckpt_keys - model_keys missing_keys = model_keys - ckpt_keys print('Missing keys:{}'.format(len(missing_keys))) print('Unused checkpoint keys:{}'.format(len(unused_pretrained_keys))) print('Used keys:{}'.format(len(used_pretrained_keys))) assert len(used_pretrained_keys) > 0, 'load NONE from pretrained checkpoint' return True def remove_prefix(state_dict, prefix): ''' Old style model is stored with all names of parameters sharing common prefix 'module.' ''' print('remove prefix \'{}\''.format(prefix)) f = lambda x: x.split(prefix, 1)[-1] if x.startswith(prefix) else x return {f(key): value for key, value in state_dict.items()} def load_model(model, pretrained_path, load_to_cpu): print('Loading model from {}'.format(pretrained_path)) if load_to_cpu: pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc: storage) else: device = torch.cuda.current_device() pretrained_dict = torch.load(pretrained_path, map_location=lambda storage, loc:storage.cuda(device)) if "state_dict" in pretrained_dict.keys(): pretrained_dict = remove_prefix(pretrained_dict['state_dict'], 'module.') else: pretrained_dict = remove_prefix(pretrained_dict, 'module.') check_keys(model, pretrained_dict) model.load_state_dict(pretrained_dict, strict=False) return model def load_graph(frozen_graph_filename): with tf.gfile.GFile(frozen_graph_filename, "rb") as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) with tf.Graph().as_default() as graph: tf.import_graph_def(graph_def,input_map = None,return_elements = None,name = "",op_dict = None,producer_op_list = None) return graph if __name__ == '__main__': torch.set_grad_enabled(False) cfg = cfg_mnet net = RetinaFace(cfg=cfg, phase='test') net = load_model(net, "./converted_models/mobilenet/mobilenet0.25_Final.pth", True) net.eval() print('Finish loading model!') #print(net) #cudnn.benchmark = True device = torch.device("cpu") net = net.to(device) img_raw = cv2.imread("./Face_Detector_ncnn/sample.jpg") #img = np.ones((3,240,320), dtype=np.float32) img = np.float32(img_raw) long_side = 320 im_shape = img.shape im_size_min = np.min(im_shape[0:2]) im_size_max = np.max(im_shape[0:2]) resize = float(long_side) / float(im_size_min) if np.round(resize * im_size_max) > long_side: resize = float(long_side) / float(im_size_max) if resize != 1: img = cv2.resize(img, None, None, fx=resize, fy=resize, interpolation=cv2.INTER_LINEAR) img -= (104, 117, 123) img = img.transpose(2,0,1) img = torch.from_numpy(img).unsqueeze(0) img = img.to(device) loc, conf, landms = net(img) _, n, _ = loc.shape loc_np = loc.data.cpu().numpy() conf_np = conf.data.cpu().numpy() landms_np = landms.data.cpu().numpy() with open("pytorch_result.txt", 'w') as fd: for j in range(n): fd.write(str(conf_np[0,j,1]) + ' '+str(loc_np[0, j, 0]) + ' ' + str(loc_np[0, j, 1]) + ' ' + str(loc_np[0, j, 2]) + ' ' + str(loc_np[0, j, 3]) + '\n') #fd.write(str(landms_np[0,j,0]) + ' ' + str(landms_np[0,j,1]) + ' ' + str(landms[0,j,2]) + ' ' + str(landms_np[0,j,3]) + ' ' + str(landms_np[0,j,4) + ' ' + str(landms_np[0,j,5]) + ' ' + str(landms_np[0,j,6]) + ' ' + str(landms_np[0,j,7]) + ' ' + str(landms_np[0,j,8]) + ' ' + str(landms_np[0,j,9]) + '\n') #fd.write(str(landms_np[0,j,0]) + ' ' + str(landms_np[0,j,1]) + str(landms_np[0,j,2]) + ' ' + str(landms_np[0,j,3]) + '\n') print(loc.shape) print(loc) print(conf) print(landms)
[ "numpy.float32", "torch.set_grad_enabled", "torch.load", "numpy.round", "cv2.imread", "numpy.min", "numpy.max", "torch.device", "torch.cuda.current_device", "models.retinaface.RetinaFace", "cv2.resize", "torch.from_numpy" ]
[((2185, 2214), 'torch.set_grad_enabled', 'torch.set_grad_enabled', (['(False)'], {}), '(False)\n', (2207, 2214), False, 'import torch\n'), ((2245, 2278), 'models.retinaface.RetinaFace', 'RetinaFace', ([], {'cfg': 'cfg', 'phase': '"""test"""'}), "(cfg=cfg, phase='test')\n", (2255, 2278), False, 'from models.retinaface import RetinaFace\n'), ((2475, 2494), 'torch.device', 'torch.device', (['"""cpu"""'], {}), "('cpu')\n", (2487, 2494), False, 'import torch\n'), ((2535, 2580), 'cv2.imread', 'cv2.imread', (['"""./Face_Detector_ncnn/sample.jpg"""'], {}), "('./Face_Detector_ncnn/sample.jpg')\n", (2545, 2580), False, 'import cv2\n'), ((2641, 2660), 'numpy.float32', 'np.float32', (['img_raw'], {}), '(img_raw)\n', (2651, 2660), True, 'import numpy as np\n'), ((2724, 2745), 'numpy.min', 'np.min', (['im_shape[0:2]'], {}), '(im_shape[0:2])\n', (2730, 2745), True, 'import numpy as np\n'), ((2764, 2785), 'numpy.max', 'np.max', (['im_shape[0:2]'], {}), '(im_shape[0:2])\n', (2770, 2785), True, 'import numpy as np\n'), ((1231, 1301), 'torch.load', 'torch.load', (['pretrained_path'], {'map_location': '(lambda storage, loc: storage)'}), '(pretrained_path, map_location=lambda storage, loc: storage)\n', (1241, 1301), False, 'import torch\n'), ((1329, 1356), 'torch.cuda.current_device', 'torch.cuda.current_device', ([], {}), '()\n', (1354, 1356), False, 'import torch\n'), ((2844, 2874), 'numpy.round', 'np.round', (['(resize * im_size_max)'], {}), '(resize * im_size_max)\n', (2852, 2874), True, 'import numpy as np\n'), ((2978, 3064), 'cv2.resize', 'cv2.resize', (['img', 'None', 'None'], {'fx': 'resize', 'fy': 'resize', 'interpolation': 'cv2.INTER_LINEAR'}), '(img, None, None, fx=resize, fy=resize, interpolation=cv2.\n INTER_LINEAR)\n', (2988, 3064), False, 'import cv2\n'), ((3129, 3150), 'torch.from_numpy', 'torch.from_numpy', (['img'], {}), '(img)\n', (3145, 3150), False, 'import torch\n')]
from typing import Union, Any, Callable, Dict, Iterable, List from pathlib import Path import pickle import time from functools import wraps from urllib.request import urlopen import sys from concurrent.futures import as_completed, ThreadPoolExecutor import pandas as pd import json import numpy as np import PIL from IPython.display import display def new_save(out_path: Path, data, file_format: str = "pickle"): """ (Over)write data to new pickle/json file. """ out_path.parent.mkdir(parents=True, exist_ok=True) if file_format == "pickle": with open(out_path, "wb") as f: pickle.dump(data, f) elif file_format == "json": with open(out_path, "w") as f: json.dump(data, f, indent=4) print(f"Writing new {file_format} file... {out_path.name}") def load_saved(in_path: Path, file_format: str = "pickle"): """ Load saved pickle/json file. """ if file_format == "pickle": with open(in_path, "rb") as f: data = pickle.load(f) elif file_format == "json": with open(in_path, "r") as f: data = json.load(f) print(f"Loading from {file_format} file... {in_path.name}") return data def load_or_new_save( path: Path, default_data: Union[Callable, Any], callable_args: Dict = None, file_format: str = "pickle", ) -> Any: """ Write data to new pickle/json file or load pickle/json if that file already exists. Example: df = cgeo.other.load_or_new_save(path=Path('output/preprocessed_marker_small.pkl'), default_data=preprocess_vector, callable_args={'inpath': fp_fields, 'meta': meta}) Args: path: in/output pickle/json file path. file_format: Either 'pickle' or 'json'. default_data: Data that is written to a pickle/json file if the pickle/json does not already exist. When giving a function, do not call the function, only give the function object name. Function arguments can be provided via callable_args. callable_args: args for additional function arguments when default_data is a callable function. Returns: Contents of the loaded or newly created pickle/json file. """ try: if file_format in ["pickle", "json"]: data = load_saved(path, file_format=file_format) except (FileNotFoundError, OSError, IOError, EOFError): if not callable(default_data): data = default_data else: if callable_args is None: data = default_data() else: data = default_data(**callable_args) if file_format in ["pickle", "json"]: new_save(out_path=path, data=data, file_format=file_format) return data def lprun(func): """ Line profile decorator. Put @lprun on the function you want to profile. From pavelpatrin: https://gist.github.com/pavelpatrin/5a28311061bf7ac55cdd """ @wraps(func) def wrapper(*args, **kwargs): from line_profiler import LineProfiler prof = LineProfiler() try: return prof(func)(*args, **kwargs) finally: prof.print_stats() return wrapper def printfull(df): """ Displays full dataframe (deactivates rows/columns wrapper). Prints if not in Notebook. """ with pd.option_context("display.max_rows", None, "display.max_columns", None): display(df) def sizeof_memvariables(locals): """ Prints size of all variables in memory in human readable output. By <NAME>, after https://stackoverflow.com/a/1094933/1870254 """ def sizeof_fmt(num, suffix="B"): for unit in ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"]: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num, "Yi", suffix) for name, size in sorted( ((name, sys.getsizeof(value)) for name, value in locals().items()), key=lambda x: -x[1], )[:10]: print("{:>30}: {:>8}".format(name, sizeof_fmt(size))) def download_url(url, out_path): """ Download file from URL. Example: download_file("url", 'data.tif') """ print("downloading {} to {}".format(url, out_path)) with open(out_path, "wb") as local_file: local_file.write(urlopen(url).read()) def print_file_tree(dir: Path = None): """ Print file tree of the selected directory. Taken from https://realpython.com/python-pathlib/ Args: dir: The directory to print the file tree for. Defaults to current working directory. """ if dir is None: dir = Path.cwd() print(f"+ {dir}") for path in sorted(dir.rglob("*")): depth = len(path.relative_to(dir).parts) spacer = " " * depth print(f"{spacer}+ {path.name}") def track_time(task): """ Track time start/end of running function. """ start_time = time.time() state = task.status()["state"] print("RUNNING...") while state in ["READY", "RUNNING"]: time.sleep(3) state = task.status()["state"] elapsed_time = time.time() - start_time print("Done in", elapsed_time, "s") print(task.status()) def get_bands_in_folder(indir: Union[Path, str], sensor="s2") -> pd.DataFrame: """ Collects Sentinel-2 or Landsat-8 band file information in input directory to a pandas dataframe. Expects SAFE format filenames, but arbitrary (sub)folder structure. Works with both tiff or jp2 format. Args: indir: input directory. Arbitrary (sub)folder structure. sensor: Satellite sensor, sentinel-2 's2' or landsat-8 'l8' Returns: pandas dataframe. The columns time and tile are multi-index. Examples usages of results dataframe: - df.reset_index() # Dissolves multi-index (every row has every value) - for date, new_df in df.groupby(level=0): # loop over dates, return "subdataframe" per date. - dates_list = df_layers_all.index.get_level_values(0).unique() """ band_names_s2 = { "B01": "coastal", "B02": "blue", "B03": "green", "B04": "red", "B05": "rededge_1", "B06": "rededge_2", "B07": "rededge_3", "B08": "nir", "B8A": "watervapour", "B10": "cirrus", "B11": "swir_1", "B12": "swir_2", "SLC": "slc", } band_names_l8 = {} band_names_fmask = { "clear_land_pixel": 0, "clear_water_pixel": 1, "cloud_shadow": 2, "snow": 3, "cloud": 4, "no_observation": 255, } paths = Path(indir).rglob("*.[jt][pi][2f]") # Drop non-relevant bands e.g. quality bands and other resolutions. paths = [ path for path in paths if any(f"_{x}_10m" in str(path) for x in band_names_s2) ] stems = [path.stem for path in paths] time_tile_sid_band = [ ( stem.split("_")[2].split("T")[0], # 20171020 stem.split("_")[1][1:], # 32ULB stem.split("_")[3], # B07 ) for stem in stems ] df_layers = pd.DataFrame(time_tile_sid_band, columns=["time", "tile", "band"]) df_layers["time"] = pd.to_datetime(df_layers.time) df_layers["band_name"] = [band_names_s2[band] for band in df_layers.band] df_layers["file"] = [str(path) for path in paths] df_layers = df_layers.set_index(["time", "tile", "band", "band_name"]) return df_layers def multithread_iterable( func: Callable, iterable: Iterable, func_kwargs: Dict = None, max_workers: int = 2 ): """Wrapper for simplified multithreading of iterable. Uses concurrent.futures.ThreadPoolExecutor instead of manually spinning up threads via the threading module. Args: func: callable function. iterable: list, generator etc. that should be iterated over via one thread per iteration. If the iterable yields a tuple, func_kwargs: additional function arguments. max_workers: number of threads. Returns: The function return value in a list. Example: def task(i, iter, add=2): # i and iter are required arguments! print("Processing {}".format(i)) return iter*iter + add print(multithreading(func=task, iterable=[2,3,4], func_kwargs={'add':10}, max_workers=2)) """ with ThreadPoolExecutor(max_workers=max_workers) as executor: if not isinstance(iterable, tuple): futures = [ executor.submit(func, i, iter, **func_kwargs) for i, iter in enumerate(iterable) ] else: futures = [ executor.submit(func, i, *iter, **func_kwargs) for i, iter in enumerate(iterable) ] return [fut.result() for fut in as_completed(futures)] def roman_numbers_to_arrays( text_list: List[str], fontsize: int = 12, display=True ) -> List[np.array]: """ Create binary arrays displaying Roman numbers. Inspired by https://stackoverflow.com/questions/36384353/generate-pixel-matrices- from-characters-in-string Args: text_list: List of Roman numbers as string. Defaults to I-X. fontsize: Should be at least 12, otherwise deformations display: In addition to returning the arrays plot them. Returns: List of binary numpy arrays, all with the same dimensions. Example: roman_arrays = roman_to_pixels(['I', 'II'], 22, display=False) """ font = PIL.ImageFont.truetype("arialbd.ttf", fontsize) if not text_list: roman = { 1: "I", 2: "II", 3: "III", 4: "IV", 5: "V", 6: "VI", 7: "VII", 8: "VIII", 9: "IX", 10: "X", } text_list = list(roman.values()) if fontsize < 12: raise ValueError( "fontsize needs to be at least 12, smaller will cause font deformations." ) widths = [] for text in text_list: w, h = font.getsize(text) # calc the size of text in pixels h *= 2 widths.append(w) w, h = max(widths), h arrays = [] for text in text_list: image = PIL.Image.new("L", (w, h), 1) draw = PIL.ImageDraw.Draw(image) draw.text((0, 0), text, font=font) arr = np.asarray(image) arr = np.where(arr, 0, 1) arr = arr[(arr != 0).any(axis=1)] arrays.append(arr) if display is True: result = np.where(arr, "#", " ") print("shape", arr.shape) print("\n".join(["".join(row) for row in result])) return arrays
[ "PIL.Image.new", "pickle.dump", "pandas.option_context", "pathlib.Path", "pickle.load", "sys.getsizeof", "pandas.DataFrame", "urllib.request.urlopen", "IPython.display.display", "PIL.ImageDraw.Draw", "concurrent.futures.ThreadPoolExecutor", "json.dump", "numpy.asarray", "time.sleep", "pa...
[((3054, 3065), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (3059, 3065), False, 'from functools import wraps\n'), ((5092, 5103), 'time.time', 'time.time', ([], {}), '()\n', (5101, 5103), False, 'import time\n'), ((7321, 7387), 'pandas.DataFrame', 'pd.DataFrame', (['time_tile_sid_band'], {'columns': "['time', 'tile', 'band']"}), "(time_tile_sid_band, columns=['time', 'tile', 'band'])\n", (7333, 7387), True, 'import pandas as pd\n'), ((7412, 7442), 'pandas.to_datetime', 'pd.to_datetime', (['df_layers.time'], {}), '(df_layers.time)\n', (7426, 7442), True, 'import pandas as pd\n'), ((9750, 9797), 'PIL.ImageFont.truetype', 'PIL.ImageFont.truetype', (['"""arialbd.ttf"""', 'fontsize'], {}), "('arialbd.ttf', fontsize)\n", (9772, 9797), False, 'import PIL\n'), ((3163, 3177), 'line_profiler.LineProfiler', 'LineProfiler', ([], {}), '()\n', (3175, 3177), False, 'from line_profiler import LineProfiler\n'), ((3447, 3519), 'pandas.option_context', 'pd.option_context', (['"""display.max_rows"""', 'None', '"""display.max_columns"""', 'None'], {}), "('display.max_rows', None, 'display.max_columns', None)\n", (3464, 3519), True, 'import pandas as pd\n'), ((3529, 3540), 'IPython.display.display', 'display', (['df'], {}), '(df)\n', (3536, 3540), False, 'from IPython.display import display\n'), ((4795, 4805), 'pathlib.Path.cwd', 'Path.cwd', ([], {}), '()\n', (4803, 4805), False, 'from pathlib import Path\n'), ((5212, 5225), 'time.sleep', 'time.sleep', (['(3)'], {}), '(3)\n', (5222, 5225), False, 'import time\n'), ((5284, 5295), 'time.time', 'time.time', ([], {}), '()\n', (5293, 5295), False, 'import time\n'), ((8597, 8640), 'concurrent.futures.ThreadPoolExecutor', 'ThreadPoolExecutor', ([], {'max_workers': 'max_workers'}), '(max_workers=max_workers)\n', (8615, 8640), False, 'from concurrent.futures import as_completed, ThreadPoolExecutor\n'), ((10485, 10514), 'PIL.Image.new', 'PIL.Image.new', (['"""L"""', '(w, h)', '(1)'], {}), "('L', (w, h), 1)\n", (10498, 10514), False, 'import PIL\n'), ((10530, 10555), 'PIL.ImageDraw.Draw', 'PIL.ImageDraw.Draw', (['image'], {}), '(image)\n', (10548, 10555), False, 'import PIL\n'), ((10613, 10630), 'numpy.asarray', 'np.asarray', (['image'], {}), '(image)\n', (10623, 10630), True, 'import numpy as np\n'), ((10645, 10664), 'numpy.where', 'np.where', (['arr', '(0)', '(1)'], {}), '(arr, 0, 1)\n', (10653, 10664), True, 'import numpy as np\n'), ((618, 638), 'pickle.dump', 'pickle.dump', (['data', 'f'], {}), '(data, f)\n', (629, 638), False, 'import pickle\n'), ((1017, 1031), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1028, 1031), False, 'import pickle\n'), ((6809, 6820), 'pathlib.Path', 'Path', (['indir'], {}), '(indir)\n', (6813, 6820), False, 'from pathlib import Path\n'), ((10784, 10807), 'numpy.where', 'np.where', (['arr', '"""#"""', '""" """'], {}), "(arr, '#', ' ')\n", (10792, 10807), True, 'import numpy as np\n'), ((722, 750), 'json.dump', 'json.dump', (['data', 'f'], {'indent': '(4)'}), '(data, f, indent=4)\n', (731, 750), False, 'import json\n'), ((1121, 1133), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1130, 1133), False, 'import json\n'), ((9056, 9077), 'concurrent.futures.as_completed', 'as_completed', (['futures'], {}), '(futures)\n', (9068, 9077), False, 'from concurrent.futures import as_completed, ThreadPoolExecutor\n'), ((4049, 4069), 'sys.getsizeof', 'sys.getsizeof', (['value'], {}), '(value)\n', (4062, 4069), False, 'import sys\n'), ((4464, 4476), 'urllib.request.urlopen', 'urlopen', (['url'], {}), '(url)\n', (4471, 4476), False, 'from urllib.request import urlopen\n')]
import sys import sqlite3 import numpy as np from utils.colmap.bases import * IS_PYTHON3 = sys.version_info[0] >= 3 MAX_IMAGE_ID = 2**31 - 1 def extract_pair_pts(pair_id, key_points, matches): """Get point correspondences of a pair Args: pair_id: tuple (im1_id, im2_id) key_points: dict {image_id: keypoints} matches: dict {image_pair_id: (key_pt_ids1, key_pt_ids2)} Return: pts: contains pixel locations of all correspondences, stored as Nx4 numpy array. Four columns are x1, y1, x2, y2. If there's no correspondences detected for this pair, None is returned, invalid: set to 0 if there exists no correspondences for this pair, otherwise 1. """ invalid = 0 (im1, im2) = pair_id kpts1 = key_points[im1] kpts2 = key_points[im2] if (im1, im2) not in matches: invalid = 1 return None, invalid key_ids = matches[(im1, im2)] num_pts = key_ids.shape[0] pts = np.zeros((num_pts, 4)) for j in range(num_pts): k1, k2 = key_ids[j,:] x1, y1 = kpts1[k1][0:2] x2, y2 = kpts2[k2][0:2] pts[j, :] = [x1, y1, x2, y2] return pts, invalid def extract_all_pair_pts(pair_ids, key_points, matches): '''Get pixel location of correspondence''' corrd_dict = {} invalid = [] for i, (i1, i2) in enumerate(pair_ids): feat1 = key_points[i1] feat2 = key_points[i2] if (i1, i2) in matches: fmatch = matches[(i1, i2)] else: invalid.append(i) corrds = None continue Nf = fmatch.shape[0] corrds = np.zeros((Nf, 4)) for j in range(Nf): # Get pixel location k1, k2 = fmatch[j,:] x1, y1 = feat1[k1][0:2] x2, y2 = feat2[k2][0:2] corrds[j, :] = [x1, y1, x2, y2] corrd_dict[(i1, i2)] = corrds return corrd_dict, invalid def image_ids_to_pair_id(image_id1, image_id2): if image_id1 > image_id2: image_id1, image_id2 = image_id2, image_id1 return image_id1 * MAX_IMAGE_ID + image_id2 def pair_id_to_image_ids(pair_id): image_id2 = pair_id % MAX_IMAGE_ID image_id1 = (pair_id - image_id2) / MAX_IMAGE_ID return int(image_id1), int(image_id2) def array_to_blob(array): if IS_PYTHON3: return array.tostring() else: return np.getbuffer(array) def blob_to_array(blob, dtype, shape=(-1,)): if IS_PYTHON3: return np.fromstring(blob, dtype=dtype).reshape(*shape) else: return np.frombuffer(blob, dtype=dtype).reshape(*shape) class COLMAPDataLoader: def __init__(self, database_path): super(COLMAPDataLoader, self).__init__() self.db = sqlite3.connect(database_path) self.cameras = None self.images_name_based = None self.images_id_based = None self.keypoints = None self.matches = None self.descriptors = None def load_images(self, name_based=False): if not self.images_id_based or not self.images_name_based: images_name_based = {} images_id_based = {} for image_id, name, camera_id in self.db.execute("SELECT image_id, name, camera_id FROM images"): images_name_based[name] = (image_id, camera_id) images_id_based[image_id] = (name, camera_id) self.images_name_based = images_name_based self.images_id_based = images_id_based print('Load images to dataloader') return self.images_name_based if name_based else self.images_id_based def load_cameras(self,): if not self.cameras: cameras = {} for row in self.db.execute("SELECT * FROM cameras"): camera_id, model_id, width, height, params, prior = row model_name = CAMERA_MODEL_IDS[model_id].model_name #num_params = CAMERA_MODEL_IDS[model_id].num_params params = blob_to_array(params, np.float64) CameraParam = CAMERA_PARAMS[model_name] cameras[camera_id] = Camera(id=camera_id, model=model_name, width=width, height=height, params=CameraParam._make(params)) self.cameras = cameras print('Load cameras to dataloader') return self.cameras def load_descriptors(self): if not self.descriptors: descriptors = dict( (image_id, blob_to_array(data, np.uint8, (-1, 128))) for image_id, data in self.db.execute( "SELECT image_id, data FROM descriptors")) self.descriptors = descriptors print('Load descriptors to dataloader') return self.descriptors def load_keypoints(self, key_len=6): """ Note that COLMAP supports: - 2D keypoints: (x, y) - 4D keypoints: (x, y, scale, orientation) - 6D affine keypoints: (x, y, a_11, a_12, a_21, a_22) Return: keypoints: dict {image_id: keypoints} """ if not self.keypoints: keypoints = dict( (image_id, blob_to_array(data, np.float32, (-1, key_len))) for image_id, data in self.db.execute( "SELECT image_id, data FROM keypoints")) self.keypoints = keypoints print('Load keypoints to dataloader') return self.keypoints def load_matches(self): """Load all matches. Notice this will take lots of time if there are lots of images Return: matches: dict {image_pair_id: matches} """ if not self.matches: matches = {} for pair_id, data in self.db.execute("SELECT pair_id, data FROM matches"): if data is not None: im_pair_id = pair_id_to_image_ids(pair_id) matches[im_pair_id] = blob_to_array(data, np.uint32, (-1, 2)) self.matches = matches print('Load matches to dataloader') return self.matches def load_pair_matches(self, im_pair_ids): '''Load specified matches Arg: im_pair_ids: list of tuple (im1_id, im2_id) Return: matches: dict {image_pair_id: matches} ''' if not self.matches: matches = {} for im_pair_id in im_pair_ids: im1, im2= im_pair_id pair_id = image_ids_to_pair_id(im1, im2) data = self.db.execute("SELECT data FROM matches where pair_id={}".format(pair_id)).fetchall()[0][0] if data is not None: match_val = blob_to_array(data, np.uint32, (-1, 2)) if im1 > im2: match_val = match_val[:,::-1] # swap the indices matches[(im1, im2)] = match_val self.matches = matches print('Load matches to dataloader') return self.matches def get_intrinsics(self, im_name): self.load_images(name_based=True) self.load_cameras() cid = self.images_name_based[train_im][1] camera = self.cameras[cid] param = camera.params ox, oy = param.ox, param.oy if 'f' in param: fx, fy = param.f, param.f else: fx, fy = param.fx, param.fy return (fx, fy, ox, oy) def load_two_view_geometry(self): raise NotImplementedError
[ "numpy.frombuffer", "numpy.zeros", "sqlite3.connect", "numpy.fromstring", "numpy.getbuffer" ]
[((996, 1018), 'numpy.zeros', 'np.zeros', (['(num_pts, 4)'], {}), '((num_pts, 4))\n', (1004, 1018), True, 'import numpy as np\n'), ((1660, 1677), 'numpy.zeros', 'np.zeros', (['(Nf, 4)'], {}), '((Nf, 4))\n', (1668, 1677), True, 'import numpy as np\n'), ((2409, 2428), 'numpy.getbuffer', 'np.getbuffer', (['array'], {}), '(array)\n', (2421, 2428), True, 'import numpy as np\n'), ((2776, 2806), 'sqlite3.connect', 'sqlite3.connect', (['database_path'], {}), '(database_path)\n', (2791, 2806), False, 'import sqlite3\n'), ((2509, 2541), 'numpy.fromstring', 'np.fromstring', (['blob'], {'dtype': 'dtype'}), '(blob, dtype=dtype)\n', (2522, 2541), True, 'import numpy as np\n'), ((2583, 2615), 'numpy.frombuffer', 'np.frombuffer', (['blob'], {'dtype': 'dtype'}), '(blob, dtype=dtype)\n', (2596, 2615), True, 'import numpy as np\n')]
import numpy as np import random def get_block_covariance(img, k): vec = [] size = img.shape[:2] num_vecs = [size[0] // k, size[1] // k] r_list = random.sample(list(range(num_vecs[0])), 3 * k ** 2) c_list = random.sample(list(range(num_vecs[1])), 3 * k ** 2) for row in r_list: for col in c_list: vec.append(np.ravel(img[row*k:(row+1)*k, col*k:(col+1)*k, :])) cov_mat = np.ravel(np.cov(vec)) return np.ravel(cov_mat)
[ "numpy.cov", "numpy.ravel" ]
[((453, 470), 'numpy.ravel', 'np.ravel', (['cov_mat'], {}), '(cov_mat)\n', (461, 470), True, 'import numpy as np\n'), ((429, 440), 'numpy.cov', 'np.cov', (['vec'], {}), '(vec)\n', (435, 440), True, 'import numpy as np\n'), ((354, 416), 'numpy.ravel', 'np.ravel', (['img[row * k:(row + 1) * k, col * k:(col + 1) * k, :]'], {}), '(img[row * k:(row + 1) * k, col * k:(col + 1) * k, :])\n', (362, 416), True, 'import numpy as np\n')]
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import matplotlib.animation as animation import matplotlib.colors as clr from matplotlib import cm from matplotlib.gridspec import GridSpec from matplotlib.colors import LinearSegmentedColormap import numpy.random as rnd import scipy.special as spc import scipy.stats as sts import scipy.sparse as spr import pandas as pd import pandas.plotting as pdplt from sklearn.neighbors import NearestNeighbors as knn from rpy2.robjects import numpy2ri from rpy2.robjects.packages import importr import rpy2.robjects as rob import time #import sys #import os #import glob import warnings #from tqdm import tqdm warnings.filterwarnings("ignore", message="using a non-tuple sequence for multidimensional indexing is deprecated") numpy2ri.activate() r_mat_package = importr('Matrix', on_conflict = 'warn') #%% class MixtureModel(object): '''Generic class for handling multiple GMMs of spike features''' def __init__(self, dimensions, num_comp, verbose = False): '''Initialize the most general model parameters. dimensions (int or list of int): the number of data dimensions num_comp (int or list of int): the number of mixture components''' if type(dimensions) is int: dimensions = [dimensions] num_comp = [num_comp] if len(dimensions) != len(num_comp): raise ValueError('dimensions and num_comp must be the same length') self.dim_obs = dimensions self.num_comp = num_comp self.num_dset = len(self.dim_obs) self.verbose = verbose # Nested list to store model parameters self.params = [[] for _ in range(self.num_dset)] #%% fitting def fit_model( self, data, max_iter = 200, n_runs = 10, init_method = 'prior', use_spatial = False, num_spatial_bins = 5, bin_method = 'evenly', spatial_variable = None, p_remove = 0.1, skip_datasets = [], make_plots = True): ''' Fit the mixture model using the standard EM algorithm. Automatically removes outlier points. Args: data (list of (n_obs, dim_obs) nparray): list of datasets max_iter (int): maximum number of iterations in each run n_runs (int): number of times to run the algorithm init_method ('prior' or 'randkm'): initialisation method use_spatial (bool): fit the SVGMM? num_spatial_bins (int): how many spatial bins along each dimension bin_method ('evenly'): how to space the edges of each spatial bin spatial_variable (list of (n_obs,dim_spat) nparrays): the variable to use for the SVGMM p_remove (0-1): proportion of outliers to remove skip_datasets (list of int): list of any dataset indices to skip make_plots (bool): whether to show the log-likelihood plots ''' if use_spatial and spatial_variable is None: raise ValueError('You need to provide a spatial variable if use_spatial is True!') num_dsets = len(data) - len(skip_datasets) # Fit each dataset t0 = time.time() dset = -1 for dset, dat in enumerate(data): if dset in skip_datasets: continue num_clu = self.num_comp[dset] if self.verbose: print('%.1f: Fitting model %d/%d' \ % (time.time() - t0, dset+1, num_dsets)) # remove outlier points nonoutlier = self.remove_outliers(dat, q = p_remove) dat = dat[nonoutlier,:] if spatial_variable is not None: SV = spatial_variable[dset][nonoutlier,:] N, d = dat.shape # number of data points # initialise mu_prior = dat.mean(0)[:,np.newaxis] sig_prior = (dat.T.dot(dat)[:,:,np.newaxis]/(N - 1)) pi_prior = (np.ones((num_clu, N))/num_clu) # run the EM elbo = np.zeros((n_runs, max_iter)) # pies = np.zeros((num_clu, N, max_iter+1)) # mus = np.zeros((dat.shape[1], num_clu, max_iter+1)) # sigs = np.zeros((dat.shape[1], dat.shape[1], num_clu, max_iter+1)) # dubs = np.zeros((N, num_clu, max_iter+1)) maxlik = -np.inf for r in range(n_runs): self.initialise_model(dset, dat, [mu_prior, sig_prior, pi_prior], how = init_method, s = 0.1) # should I save initial conditions? # pies[:,:,0] = pi # mus[:,:,0] = mu # sigs[:,:,:,0] = sig # dubs[:,:,0] = z_init mu, sig, pi, _ = self.params[dset] for n in range(max_iter): # E step self.E_Step(dset, dat) # M step if use_spatial: self.M_Step_SV(dset,dat,SV,num_spatial_bins, bin_method) else: self.M_Step(dset,dat) # likelihood probs = self.pdf(dset,dat)[0] loglik = np.sum(np.log(probs.sum(0))) elbo[r,n] = loglik # nparam = use_svgmm*nbin*4 + K*(X.shape[1] + X.shape[1]**2)/2 maxlik = np.max([maxlik, loglik]) if loglik == maxlik: # hold on to the best model Mu, Sig, _, W = self.params[dset] Pi = (np.squeeze(W.sum(0)/N).T)[:,np.newaxis] if self.verbose: print('%.1f: Model %d/%d, run %d/%d' \ % (time.time() - t0, dset+1, num_dsets, r+1, n_runs)) self.params[dset] = [Mu, Sig, Pi, W] if make_plots: dis = np.argmax(elbo[:,-1]) plt.figure() plt.plot(elbo.T, c = [0.5,0.5,0.5],linewidth = 1) plt.plot(elbo[dis,:].T,'k-',linewidth = 2) plt.ylabel('log-likelihood') plt.title('Fits for dataset %d' % (dset + 1)) if self.verbose: print('done') def E_Step(self, whichDset, dat): ''' Does the E step in the EM algorithm. Updates the class assignments. ''' means, covs, pi, _ = self.params[whichDset] log_w = np.array([sts.multivariate_normal.logpdf(dat,means[:,k],covs[:,:,k]) \ for k in range(self.num_comp[whichDset])]) log_w += np.log(pi + 1e-16) c = log_w.max(0) log_norm = c + np.log(np.sum(np.exp(log_w - c), axis = 0)) log_w -= log_norm w_ik = np.exp(log_w).T self.params[whichDset][-1] = w_ik def M_Step(self, whichDset, dat): ''' Does the M step in the standard EM algorithm. ''' def my_cov(X, **kwargs): ''' wrapper for covariance computation which rounds to nearest positive definite matrix ''' sig_temp = np.cov(X, **kwargs) sig_r = r_mat_package.nearPD(sig_temp, eig_tol = 1e-6) sig_out = np.array(rob.r['as.matrix'](sig_r[0])) return sig_out # fudge = np.eye(self.dim_obs[whichDset])[:,:,np.newaxis]*1e-5 # load class assignments and make them nice for broadcasting w_ik = self.params[whichDset][-1][:,np.newaxis,:] N = dat.shape[0] pi = np.tile(np.squeeze(w_ik.sum(0)/N),(N,1)).T mu = np.array([np.average(dat, axis = 0, weights = w_ik[:,0,k] + 1e-16) \ for k in range(self.num_comp[whichDset])]).T sig = np.array([my_cov(dat.T, aweights = w_ik[:,0,k] + 1e-16) \ for k in range(self.num_comp[whichDset])]) sig = np.transpose(sig,(1,2,0)) self.params[whichDset][0:-1] = [mu, sig, pi] def M_Step_SV(self, whichDset, dat, SV, nbin = 5, method = 'evenly'): ''' Does the M step in the SVGMM EM algorithm. ''' def my_cov(X, **kwargs): ''' wrapper for covariance computation which rounds to nearest positive definite matrix ''' sig_temp = np.cov(X, **kwargs) sig_r = r_mat_package.nearPD(sig_temp, eig_tol = 1e-6) sig_out = np.array(rob.r['as.matrix'](sig_r[0])) return sig_out # load class assignments w_ik = self.params[whichDset][-1] pi = np.array( [self.neighbour_func(SV, w_ik[:,k], nbin = nbin, how = method)[0] \ for k in range(self.num_comp[whichDset])]) mu = np.array([np.average(dat, axis = 0, weights = w_ik[:,k] + 1e-16) \ for k in range(self.num_comp[whichDset])]).T sig = np.array([my_cov(dat.T, aweights = w_ik[:,k] + 1e-16) \ for k in range(self.num_comp[whichDset])]) sig = np.transpose(sig,(1,2,0)) self.params[whichDset][0:-1] = [mu, sig, pi] def initialise_model(self, whichDset, dat, priors = None, how = 'randkm', s = 0.2): ''' initialise_model(data, priors = None, how = 'randkm', s = 0.2) Initialise the model for one dataset. Args: whichDset (int): index of the dataset being initialised data ((n_obs,dim_obs) nparray): the data priors (list): [means, covariances, proportions] how ('prior' or 'randkm'): what method to use s (0-1): how much to perturb ''' def my_cov(X, **kwargs): ''' wrapper for covariance computation which rounds to nearest positive definite matrix ''' sig_temp = np.cov(X, **kwargs) sig_r = r_mat_package.nearPD(sig_temp, eig_tol = 1e-6) sig_out = np.array(rob.r['as.matrix'](sig_r[0])) return sig_out if how is 'prior' and priors is None: raise ValueError('Must provide initial conditions for `prior` initialisation') n_obs, n_dim = dat.shape K = self.num_comp[whichDset] # Initialise parameters if n_dim != self.dim_obs[whichDset]: raise ValueError('Dimension of dataset doesn\'t match dim_obs') if how == 'prior': # perturbation from prior mu, sig, pi = priors mu_init = mu*(1 - s + 2*s*rnd.rand(1,K)) sig_init = sig*(1 - s + 2*s*rnd.rand(1,1,K)) pi_init = pi*(1 - s + 2*s*rnd.rand(K, 1)) pi_init /= pi_init.sum(0)[:,np.newaxis].T distX = np.linalg.norm(dat[:,:,np.newaxis] \ - mu_init[np.newaxis,:,:],axis = 1) z_init = np.zeros((n_obs,K)) z_init[np.arange(n_obs), np.argmin(distX, axis = 1)] = 1 elif how == 'randkm': # sort of k-means thing # if n_dim >= K: d = rnd.permutation(np.arange(n_dim)) # else: # d = np.append(rnd.permutation(np.arange(n_dim)), # rnd.choice(n_dim, K-n_dim)) whichdims = [d[0+n::K]\ for n in np.arange(K)] q = np.quantile(dat, [k*(1./K) \ for k in range(K+1)], axis = 0) mean_qk = np.zeros((n_dim, K)) for k in range(1,K+1): # get quantile means in_qk = [(dat[:,d] < q[k,d]) & (dat[:,d] >= q[k-1,d]) \ for d in range(n_dim)] mean_qk[:,k-1] = [dat[in_qk[d],d].mean(0) \ for d in range(n_dim)] mu_init = np.zeros((n_dim, K)) for k in range(K): # select class means trailing = [whichdims[dd] \ for dd in rnd.permutation(np.setdiff1d(range(K),k))] nt = len(trailing) mu_init[whichdims[k],k] = mean_qk[whichdims[k],-1] for kk in range(nt): mu_init[trailing[kk],k] = mean_qk[trailing[kk],-(kk+2)] mu_init *= (1 - s + 2*s*rnd.rand(1,K)) distX = np.linalg.norm(dat[:,:,np.newaxis] - mu_init[np.newaxis,:,:],axis = 1) z_init = np.zeros((n_obs,K)) z_init[np.arange(n_obs),np.argmin(distX, axis = 1)] = 1 pi_init = np.tile(z_init.sum(0)/n_obs, (n_obs,1)).T sig_init = np.array([my_cov(dat.T, aweights = z_init[:,k] + 1e-16) \ for k in range(K)]).T pi_init = pi_init.astype(np.float32) mu_init = mu_init.astype(np.float32) sig_init = sig_init.astype(np.float32) self.params[whichDset] = [mu_init, sig_init, pi_init, z_init] def neighbour_func(self,S, w_i, nb_func = np.mean, nbin = 5, how = 'evenly'): ''' compute a function of w_i for each point in S within a binned neighbourhood wrapper for 'scipy.stats.binned_statistic_dd' function Args: S (N, dim_s): the spatial variable w_i (N,): the soft cluster assignment of each neuron nb_func (callable; 1d --> scalars), default is np.mean: the function to compute nbin (int), default 5: number of spatial bins in each dimension how ({'evenly', 'quantiles'}), default 'evenly': make the bin edges evenly spaced or spaced as quantiles ''' dim_s = S.shape[1] if how == 'evenly': bins = tuple([np.linspace(S[:,d].min(),S[:,d].max(),nbin+1) \ for d in range(dim_s)]) elif how == 'quantiles': bins = tuple([np.quantile(S[:,d],np.arange(nbin+1)/nbin) \ for d in range(dim_s)]) stat ,_, which_nb = sts.binned_statistic_dd( S, w_i, statistic = nb_func, bins = bins) if dim_s != 1: which_nb -= (nbin+3) # need to correct for silly indexing for b in range(nbin): deez = np.isin(which_nb,[range(b*(nbin+2),(b+1)*(nbin+2))]) which_nb[deez] -= b*2 else: which_nb -= 1 pi_i = stat.flatten()[which_nb] return pi_i, which_nb def remove_outliers(self, X, k = 20, q = 0.1): nneigh = knn(k + 1) nneigh.fit(X) dist = nneigh.kneighbors(X,return_distance = True)[0][:,1:] dens = 1/np.mean(dist,axis = 1) keepers = (dens >= np.quantile(dens, q)) return keepers #%% plotting def scatterplot(self, whichDset, dat, pdf_plot = 'contour', c = None, cmap_scat = 'hsv', cmap_pdf = 'cool', alpha = 0.5, conf = 1./3.): ''' Plot a dataset in a scatterplot matrix, along with the fit. ''' self.E_Step(whichDset, dat) this_mu, this_sig, this_pi, this_w = self.params[whichDset] if c is not None: col = c else: col = self.soft_colormap(this_w, cmap_scat) df = pd.DataFrame(dat, columns = ('Trode1','Trode2','Trode3','Trode4')) axs = pdplt.scatter_matrix(df, s = 5, c = col, alpha = alpha, zorder = 2) plt.set_cmap(cmap_scat) for ii in range(self.dim_obs[whichDset]): for jj in range(self.dim_obs[whichDset]): if ii == jj: continue if pdf_plot is 'density': lims = np.array([axs[jj,ii].get_xlim(),axs[jj,ii].get_ylim()]) C = this_sig[[ii,jj],:,:][:,[ii,jj]] m = this_mu[[ii,jj],:] pdf, Q = self.plot_2d_density(lims, m, C, this_pi) axs[jj,ii].pcolormesh(Q[:,:,0],Q[:,:,1], pdf, cmap = cmap_pdf, zorder = 1) elif pdf_plot is 'contour': for k in range(self.num_comp[whichDset]): C = this_sig[[ii,jj],:,k][:,[ii,jj]] m = this_mu[[ii,jj],k] ellipse_x, ellipse_y = self.cov_ellipse(C,m, conf = conf) axs[jj,ii].plot(ellipse_x,ellipse_y, 'k-', linewidth = 1) axs[jj,ii].scatter(this_mu[ii,:],this_mu[jj,:], c = 'k', marker = 'd') return axs def plot_2d_density(self,lims, mus, covs, pies, num = 100): ''' mus (n_dim,K) covs (n_dim,n_dim,K) pies (1,K) ''' K = mus.shape[1] Q = np.array(np.meshgrid( np.linspace(lims[0,0],lims[0,1],num), np.linspace(lims[1,0],lims[1,1],num))).T probs = np.array([pies[k]*sts.multivariate_normal.pdf(Q,mus[:,k],covs[:,:,k]) \ for k in range(K)]) probs = probs.sum(0) return (probs, Q) def cov_ellipse(self,C, m, conf = 0.95): ''' get ellipse of covariance C ''' cf = sts.chi2.ppf(conf,2) L, V = np.linalg.eigh(C) order = L.argsort()[::-1] L, V = L[order], V[:, order] a = 2*np.sqrt(cf*L[0]) b = 2*np.sqrt(cf*L[1]) t = np.linspace(0,2*np.pi,100) tht = np.arctan2(V[1,0],V[0,0]) x = m[0] + a*np.cos(t)*np.cos(tht) - b*np.sin(t)*np.sin(tht) y = m[1] + b*np.sin(t)*np.cos(tht) + a*np.cos(t)*np.sin(tht) return x, y def soft_colormap(self, class_probs, cmap_name = 'jet', nbin = 200): ''' Make a colormap which reflects soft cluster assignments. The hue says which cluster a point is in, and saturation is the 'confidence' (0 when the maximum class_prob is 1/K, 1 when maximum class_prob is 1). ''' N, K = class_probs.shape vals = np.argmax(class_probs, axis = 1) foo = cm.ScalarMappable(cmap = cmap_name) hsv = clr.rgb_to_hsv(foo.to_rgba(vals*(255/K))[:,:3]) hsv[:,1] = (class_probs[range(N),vals] - (1/K))/(1 - (1/K)) cols = clr.hsv_to_rgb(hsv) return cols #%% using def pdf(self, whichDset, values, use_log = False): ''' Compute PDF of the specified mixture models. Args: whichDset (int): which models to use values (nparray or list of nparray): values to evaluate models on ''' if type(whichDset) is int: whichDset = [whichDset] elif type(values) is list and len(whichDset) is not len(values): raise ValueError('Length of "values" is not the same as "whichDset"') # we can evaluate the same dataset under multiple models if type(values) is not list: values = [values for _ in range(len(whichDset))] probs = [] for dset, vals in zip(whichDset, values): this_mu, this_sig, this_pi, this_w = self.params[dset] if use_log: p = np.array([this_pi[k]*sts.multivariate_normal.logpdf( vals, this_mu[:,k], this_sig[:,:,k]) \ for k in range(self.num_comp[dset])]) else: p = np.array([this_pi[k]*sts.multivariate_normal.pdf( vals, this_mu[:,k], this_sig[:,:,k]) \ for k in range(self.num_comp[dset])]) probs.append(p) return probs def logpdf(self, whichDset, values): ''' Wrapper for pdf ''' return self.pdf(whichDset, values, use_log = True) def compute_mark_probs(self, whichDset, marks, indices, final_shape): ''' Makes the giant array with the probability of whichDset (list of int): which models to compute with marks (list): mark values for each multiunit channel (nparray) or empty list for single unit channels indices (list): bin edges used to bin the spikes final_shape (tuple): shape of the desired array, usually is (num_trials, num_time_pts, -1, dim_obs) TODO: be less terrible ''' N = len(whichDset) num_t = final_shape[0]*final_shape[1] w = [[[] for _ in range(N)] for _ in range(num_t)] for n in whichDset: if marks[n] is not None: M = marks[n] inds = indices[n] pi_tet = self.params[n][2].T probs = self.logpdf([n],M)[0].T for t in range(num_t): if marks[n] is None: w[t][n] = np.array([1]) else: Nt = np.sum(inds == t) these_spks = probs[inds == t, :] if Nt > 0: # renormalise for each spike these_spks += np.log(pi_tet + 1e-16) w_ik = np.sum(these_spks.T, axis = 1) c = w_ik.max() log_norm = c + np.log(np.sum(np.exp(w_ik - c))) w_ik -= log_norm w_ik = np.exp(w_ik) w_ik[w_ik < 1e-12] = 0 w[t][n] = w_ik else: w[t][n] = np.squeeze(pi_tet) weight_array = np.array([self.build_weight_matrix(w[tt]) \ for tt in range(num_t)]) weight_array = np.reshape(weight_array,final_shape) return weight_array def build_weight_matrix(self,probs): ''' probs (list) ''' n = len(probs) weight_mat = np.zeros((0,n)) for tet in range(n): tmp = np.zeros((probs[tet].shape[0], n)) tmp[:,tet] = probs[tet] weight_mat = np.append(weight_mat,tmp, axis = 0) return weight_mat #%% simulating # def generate_mixtures(self, whichDset): # ''' # # ''' # # if type(whichDset) is int: # whichDset = [whichDset] # # for dset in whichDset: # params = [] # for tet in range(N_tet): # pi = rnd.dirichlet(np.ones(K[tet])*20) # mu= 200*np.array([rnd.rand(K[tet]) for _ in range(dim)]) + 50 # # sig = np.zeros((dim,dim,K[tet])) # for k in range(K[tet]): # sig[:,:,k] = 20*sts.wishart.rvs(7,np.eye(dim)) # params.append([mu, sig, pi]) # # return params
[ "matplotlib.pyplot.title", "numpy.arctan2", "numpy.sum", "numpy.argmax", "numpy.ones", "numpy.argmin", "matplotlib.pyplot.figure", "numpy.mean", "numpy.linalg.norm", "numpy.exp", "numpy.sin", "numpy.arange", "scipy.stats.multivariate_normal.logpdf", "pandas.DataFrame", "rpy2.robjects.pac...
[((678, 798), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {'message': '"""using a non-tuple sequence for multidimensional indexing is deprecated"""'}), "('ignore', message=\n 'using a non-tuple sequence for multidimensional indexing is deprecated')\n", (701, 798), False, 'import warnings\n'), ((820, 839), 'rpy2.robjects.numpy2ri.activate', 'numpy2ri.activate', ([], {}), '()\n', (837, 839), False, 'from rpy2.robjects import numpy2ri\n'), ((856, 893), 'rpy2.robjects.packages.importr', 'importr', (['"""Matrix"""'], {'on_conflict': '"""warn"""'}), "('Matrix', on_conflict='warn')\n", (863, 893), False, 'from rpy2.robjects.packages import importr\n'), ((3325, 3336), 'time.time', 'time.time', ([], {}), '()\n', (3334, 3336), False, 'import time\n'), ((6975, 6993), 'numpy.log', 'np.log', (['(pi + 1e-16)'], {}), '(pi + 1e-16)\n', (6981, 6993), True, 'import numpy as np\n'), ((8313, 8341), 'numpy.transpose', 'np.transpose', (['sig', '(1, 2, 0)'], {}), '(sig, (1, 2, 0))\n', (8325, 8341), True, 'import numpy as np\n'), ((9512, 9540), 'numpy.transpose', 'np.transpose', (['sig', '(1, 2, 0)'], {}), '(sig, (1, 2, 0))\n', (9524, 9540), True, 'import numpy as np\n'), ((14617, 14678), 'scipy.stats.binned_statistic_dd', 'sts.binned_statistic_dd', (['S', 'w_i'], {'statistic': 'nb_func', 'bins': 'bins'}), '(S, w_i, statistic=nb_func, bins=bins)\n', (14640, 14678), True, 'import scipy.stats as sts\n'), ((15164, 15174), 'sklearn.neighbors.NearestNeighbors', 'knn', (['(k + 1)'], {}), '(k + 1)\n', (15167, 15174), True, 'from sklearn.neighbors import NearestNeighbors as knn\n'), ((15950, 16017), 'pandas.DataFrame', 'pd.DataFrame', (['dat'], {'columns': "('Trode1', 'Trode2', 'Trode3', 'Trode4')"}), "(dat, columns=('Trode1', 'Trode2', 'Trode3', 'Trode4'))\n", (15962, 16017), True, 'import pandas as pd\n'), ((16031, 16090), 'pandas.plotting.scatter_matrix', 'pdplt.scatter_matrix', (['df'], {'s': '(5)', 'c': 'col', 'alpha': 'alpha', 'zorder': '(2)'}), '(df, s=5, c=col, alpha=alpha, zorder=2)\n', (16051, 16090), True, 'import pandas.plotting as pdplt\n'), ((16107, 16130), 'matplotlib.pyplot.set_cmap', 'plt.set_cmap', (['cmap_scat'], {}), '(cmap_scat)\n', (16119, 16130), True, 'import matplotlib.pyplot as plt\n'), ((17989, 18010), 'scipy.stats.chi2.ppf', 'sts.chi2.ppf', (['conf', '(2)'], {}), '(conf, 2)\n', (18001, 18010), True, 'import scipy.stats as sts\n'), ((18030, 18047), 'numpy.linalg.eigh', 'np.linalg.eigh', (['C'], {}), '(C)\n', (18044, 18047), True, 'import numpy as np\n'), ((18211, 18241), 'numpy.linspace', 'np.linspace', (['(0)', '(2 * np.pi)', '(100)'], {}), '(0, 2 * np.pi, 100)\n', (18222, 18241), True, 'import numpy as np\n'), ((18252, 18280), 'numpy.arctan2', 'np.arctan2', (['V[1, 0]', 'V[0, 0]'], {}), '(V[1, 0], V[0, 0])\n', (18262, 18280), True, 'import numpy as np\n'), ((18848, 18878), 'numpy.argmax', 'np.argmax', (['class_probs'], {'axis': '(1)'}), '(class_probs, axis=1)\n', (18857, 18878), True, 'import numpy as np\n'), ((18895, 18928), 'matplotlib.cm.ScalarMappable', 'cm.ScalarMappable', ([], {'cmap': 'cmap_name'}), '(cmap=cmap_name)\n', (18912, 18928), False, 'from matplotlib import cm\n'), ((19081, 19100), 'matplotlib.colors.hsv_to_rgb', 'clr.hsv_to_rgb', (['hsv'], {}), '(hsv)\n', (19095, 19100), True, 'import matplotlib.colors as clr\n'), ((22587, 22624), 'numpy.reshape', 'np.reshape', (['weight_array', 'final_shape'], {}), '(weight_array, final_shape)\n', (22597, 22624), True, 'import numpy as np\n'), ((22797, 22813), 'numpy.zeros', 'np.zeros', (['(0, n)'], {}), '((0, n))\n', (22805, 22813), True, 'import numpy as np\n'), ((4263, 4291), 'numpy.zeros', 'np.zeros', (['(n_runs, max_iter)'], {}), '((n_runs, max_iter))\n', (4271, 4291), True, 'import numpy as np\n'), ((7127, 7140), 'numpy.exp', 'np.exp', (['log_w'], {}), '(log_w)\n', (7133, 7140), True, 'import numpy as np\n'), ((7521, 7540), 'numpy.cov', 'np.cov', (['X'], {}), '(X, **kwargs)\n', (7527, 7540), True, 'import numpy as np\n'), ((8765, 8784), 'numpy.cov', 'np.cov', (['X'], {}), '(X, **kwargs)\n', (8771, 8784), True, 'import numpy as np\n'), ((10382, 10401), 'numpy.cov', 'np.cov', (['X'], {}), '(X, **kwargs)\n', (10388, 10401), True, 'import numpy as np\n'), ((11304, 11377), 'numpy.linalg.norm', 'np.linalg.norm', (['(dat[:, :, np.newaxis] - mu_init[np.newaxis, :, :])'], {'axis': '(1)'}), '(dat[:, :, np.newaxis] - mu_init[np.newaxis, :, :], axis=1)\n', (11318, 11377), True, 'import numpy as np\n'), ((11433, 11453), 'numpy.zeros', 'np.zeros', (['(n_obs, K)'], {}), '((n_obs, K))\n', (11441, 11453), True, 'import numpy as np\n'), ((15282, 15303), 'numpy.mean', 'np.mean', (['dist'], {'axis': '(1)'}), '(dist, axis=1)\n', (15289, 15303), True, 'import numpy as np\n'), ((15341, 15361), 'numpy.quantile', 'np.quantile', (['dens', 'q'], {}), '(dens, q)\n', (15352, 15361), True, 'import numpy as np\n'), ((18142, 18160), 'numpy.sqrt', 'np.sqrt', (['(cf * L[0])'], {}), '(cf * L[0])\n', (18149, 18160), True, 'import numpy as np\n'), ((18173, 18191), 'numpy.sqrt', 'np.sqrt', (['(cf * L[1])'], {}), '(cf * L[1])\n', (18180, 18191), True, 'import numpy as np\n'), ((22860, 22894), 'numpy.zeros', 'np.zeros', (['(probs[tet].shape[0], n)'], {}), '((probs[tet].shape[0], n))\n', (22868, 22894), True, 'import numpy as np\n'), ((22956, 22990), 'numpy.append', 'np.append', (['weight_mat', 'tmp'], {'axis': '(0)'}), '(weight_mat, tmp, axis=0)\n', (22965, 22990), True, 'import numpy as np\n'), ((4175, 4196), 'numpy.ones', 'np.ones', (['(num_clu, N)'], {}), '((num_clu, N))\n', (4182, 4196), True, 'import numpy as np\n'), ((5715, 5739), 'numpy.max', 'np.max', (['[maxlik, loglik]'], {}), '([maxlik, loglik])\n', (5721, 5739), True, 'import numpy as np\n'), ((6242, 6264), 'numpy.argmax', 'np.argmax', (['elbo[:, -1]'], {}), '(elbo[:, -1])\n', (6251, 6264), True, 'import numpy as np\n'), ((6280, 6292), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6290, 6292), True, 'import matplotlib.pyplot as plt\n'), ((6309, 6357), 'matplotlib.pyplot.plot', 'plt.plot', (['elbo.T'], {'c': '[0.5, 0.5, 0.5]', 'linewidth': '(1)'}), '(elbo.T, c=[0.5, 0.5, 0.5], linewidth=1)\n', (6317, 6357), True, 'import matplotlib.pyplot as plt\n'), ((6375, 6418), 'matplotlib.pyplot.plot', 'plt.plot', (['elbo[dis, :].T', '"""k-"""'], {'linewidth': '(2)'}), "(elbo[dis, :].T, 'k-', linewidth=2)\n", (6383, 6418), True, 'import matplotlib.pyplot as plt\n'), ((6434, 6462), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""log-likelihood"""'], {}), "('log-likelihood')\n", (6444, 6462), True, 'import matplotlib.pyplot as plt\n'), ((6479, 6524), 'matplotlib.pyplot.title', 'plt.title', (["('Fits for dataset %d' % (dset + 1))"], {}), "('Fits for dataset %d' % (dset + 1))\n", (6488, 6524), True, 'import matplotlib.pyplot as plt\n'), ((6828, 6891), 'scipy.stats.multivariate_normal.logpdf', 'sts.multivariate_normal.logpdf', (['dat', 'means[:, k]', 'covs[:, :, k]'], {}), '(dat, means[:, k], covs[:, :, k])\n', (6858, 6891), True, 'import scipy.stats as sts\n'), ((12034, 12054), 'numpy.zeros', 'np.zeros', (['(n_dim, K)'], {}), '((n_dim, K))\n', (12042, 12054), True, 'import numpy as np\n'), ((12390, 12410), 'numpy.zeros', 'np.zeros', (['(n_dim, K)'], {}), '((n_dim, K))\n', (12398, 12410), True, 'import numpy as np\n'), ((12887, 12960), 'numpy.linalg.norm', 'np.linalg.norm', (['(dat[:, :, np.newaxis] - mu_init[np.newaxis, :, :])'], {'axis': '(1)'}), '(dat[:, :, np.newaxis] - mu_init[np.newaxis, :, :], axis=1)\n', (12901, 12960), True, 'import numpy as np\n'), ((12979, 12999), 'numpy.zeros', 'np.zeros', (['(n_obs, K)'], {}), '((n_obs, K))\n', (12987, 12999), True, 'import numpy as np\n'), ((18344, 18355), 'numpy.sin', 'np.sin', (['tht'], {}), '(tht)\n', (18350, 18355), True, 'import numpy as np\n'), ((18413, 18424), 'numpy.sin', 'np.sin', (['tht'], {}), '(tht)\n', (18419, 18424), True, 'import numpy as np\n'), ((7056, 7073), 'numpy.exp', 'np.exp', (['(log_w - c)'], {}), '(log_w - c)\n', (7062, 7073), True, 'import numpy as np\n'), ((8033, 8087), 'numpy.average', 'np.average', (['dat'], {'axis': '(0)', 'weights': '(w_ik[:, 0, k] + 1e-16)'}), '(dat, axis=0, weights=w_ik[:, 0, k] + 1e-16)\n', (8043, 8087), True, 'import numpy as np\n'), ((9236, 9287), 'numpy.average', 'np.average', (['dat'], {'axis': '(0)', 'weights': '(w_ik[:, k] + 1e-16)'}), '(dat, axis=0, weights=w_ik[:, k] + 1e-16)\n', (9246, 9287), True, 'import numpy as np\n'), ((11472, 11488), 'numpy.arange', 'np.arange', (['n_obs'], {}), '(n_obs)\n', (11481, 11488), True, 'import numpy as np\n'), ((11490, 11514), 'numpy.argmin', 'np.argmin', (['distX'], {'axis': '(1)'}), '(distX, axis=1)\n', (11499, 11514), True, 'import numpy as np\n'), ((11650, 11666), 'numpy.arange', 'np.arange', (['n_dim'], {}), '(n_dim)\n', (11659, 11666), True, 'import numpy as np\n'), ((17564, 17604), 'numpy.linspace', 'np.linspace', (['lims[0, 0]', 'lims[0, 1]', 'num'], {}), '(lims[0, 0], lims[0, 1], num)\n', (17575, 17604), True, 'import numpy as np\n'), ((17618, 17658), 'numpy.linspace', 'np.linspace', (['lims[1, 0]', 'lims[1, 1]', 'num'], {}), '(lims[1, 0], lims[1, 1], num)\n', (17629, 17658), True, 'import numpy as np\n'), ((17702, 17758), 'scipy.stats.multivariate_normal.pdf', 'sts.multivariate_normal.pdf', (['Q', 'mus[:, k]', 'covs[:, :, k]'], {}), '(Q, mus[:, k], covs[:, :, k])\n', (17729, 17758), True, 'import scipy.stats as sts\n'), ((18318, 18329), 'numpy.cos', 'np.cos', (['tht'], {}), '(tht)\n', (18324, 18329), True, 'import numpy as np\n'), ((18334, 18343), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (18340, 18343), True, 'import numpy as np\n'), ((18387, 18398), 'numpy.cos', 'np.cos', (['tht'], {}), '(tht)\n', (18393, 18398), True, 'import numpy as np\n'), ((18403, 18412), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (18409, 18412), True, 'import numpy as np\n'), ((21754, 21767), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (21762, 21767), True, 'import numpy as np\n'), ((21815, 21832), 'numpy.sum', 'np.sum', (['(inds == t)'], {}), '(inds == t)\n', (21821, 21832), True, 'import numpy as np\n'), ((11090, 11104), 'numpy.random.rand', 'rnd.rand', (['(1)', 'K'], {}), '(1, K)\n', (11098, 11104), True, 'import numpy.random as rnd\n'), ((11145, 11162), 'numpy.random.rand', 'rnd.rand', (['(1)', '(1)', 'K'], {}), '(1, 1, K)\n', (11153, 11162), True, 'import numpy.random as rnd\n'), ((11201, 11215), 'numpy.random.rand', 'rnd.rand', (['K', '(1)'], {}), '(K, 1)\n', (11209, 11215), True, 'import numpy.random as rnd\n'), ((11882, 11894), 'numpy.arange', 'np.arange', (['K'], {}), '(K)\n', (11891, 11894), True, 'import numpy as np\n'), ((12839, 12853), 'numpy.random.rand', 'rnd.rand', (['(1)', 'K'], {}), '(1, K)\n', (12847, 12853), True, 'import numpy.random as rnd\n'), ((13018, 13034), 'numpy.arange', 'np.arange', (['n_obs'], {}), '(n_obs)\n', (13027, 13034), True, 'import numpy as np\n'), ((13035, 13059), 'numpy.argmin', 'np.argmin', (['distX'], {'axis': '(1)'}), '(distX, axis=1)\n', (13044, 13059), True, 'import numpy as np\n'), ((18308, 18317), 'numpy.cos', 'np.cos', (['t'], {}), '(t)\n', (18314, 18317), True, 'import numpy as np\n'), ((18377, 18386), 'numpy.sin', 'np.sin', (['t'], {}), '(t)\n', (18383, 18386), True, 'import numpy as np\n'), ((21984, 22006), 'numpy.log', 'np.log', (['(pi_tet + 1e-16)'], {}), '(pi_tet + 1e-16)\n', (21990, 22006), True, 'import numpy as np\n'), ((22038, 22066), 'numpy.sum', 'np.sum', (['these_spks.T'], {'axis': '(1)'}), '(these_spks.T, axis=1)\n', (22044, 22066), True, 'import numpy as np\n'), ((22252, 22264), 'numpy.exp', 'np.exp', (['w_ik'], {}), '(w_ik)\n', (22258, 22264), True, 'import numpy as np\n'), ((22411, 22429), 'numpy.squeeze', 'np.squeeze', (['pi_tet'], {}), '(pi_tet)\n', (22421, 22429), True, 'import numpy as np\n'), ((20071, 20141), 'scipy.stats.multivariate_normal.logpdf', 'sts.multivariate_normal.logpdf', (['vals', 'this_mu[:, k]', 'this_sig[:, :, k]'], {}), '(vals, this_mu[:, k], this_sig[:, :, k])\n', (20101, 20141), True, 'import scipy.stats as sts\n'), ((20287, 20354), 'scipy.stats.multivariate_normal.pdf', 'sts.multivariate_normal.pdf', (['vals', 'this_mu[:, k]', 'this_sig[:, :, k]'], {}), '(vals, this_mu[:, k], this_sig[:, :, k])\n', (20314, 20354), True, 'import scipy.stats as sts\n'), ((3638, 3649), 'time.time', 'time.time', ([], {}), '()\n', (3647, 3649), False, 'import time\n'), ((14500, 14519), 'numpy.arange', 'np.arange', (['(nbin + 1)'], {}), '(nbin + 1)\n', (14509, 14519), True, 'import numpy as np\n'), ((6063, 6074), 'time.time', 'time.time', ([], {}), '()\n', (6072, 6074), False, 'import time\n'), ((22161, 22177), 'numpy.exp', 'np.exp', (['(w_ik - c)'], {}), '(w_ik - c)\n', (22167, 22177), True, 'import numpy as np\n')]
import numpy as np import math import torch import torch.nn as nn import torch.nn.functional as F from GraphLayers import GraphLayer # Graph Neural Networks device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') class MLP(nn.Module): def __init__(self, input_size, hidden_size, output_size): super(MLP, self).__init__() self.fc1 = nn.Linear(input_size, hidden_size) self.fc2 = nn.Linear(hidden_size, hidden_size) self.fc3 = nn.Linear(hidden_size, output_size) self.ReLU = nn.LeakyReLU() def forward(self, x): x = self.ReLU(self.fc1(x)) x = self.ReLU(self.fc2(x)) x = self.ReLU(self.fc3(x)) return x # need revision class GATConv(nn.Module): def __init__(self, in_features, out_features, num_head, slope_alpha=0.2, bias=True): super(GATConv, self).__init__() #self.dropout = dropout self.in_features = in_features self.out_features = out_features self.slope_alpha = slope_alpha self.num_head = num_head self.weight = nn.Parameter(torch.FloatTensor(in_features, out_features)) self.a = nn.Parameter(torch.zeros(size=(2 * out_features, 1))) self.LeakyReLU = nn.LeakyReLU(self.slope_alpha) if bias: self.bias = nn.Parameter(torch.FloatTensor(out_features)) else: self.register_parameter('bias', None) self.reset_parameters() def reset_parameters(self): nn.init.xavier_uniform_(self.weight.data, gain=1.414) if self.bias is not None: self.bias.data.fill_(0) nn.init.xavier_uniform_(self.a.data, gain=1.414) def forward(self, x, adj): # x refers to selected features ls = [] for i in range(adj.shape[0]): index = np.ndarray.item(np.array(np.nonzero(adj[i, :]))) ls.append(x[index, :]) select_feature = torch.stack(ls, dim=0) # select self and neighboring agents' features # suppose K neighbors and features size L, select_feature should have dimension of (K+1)*L out = [] for i in range(self.num_head): neighbor_dim = select_feature.shape[0] select_feature = F.dropout(select_feature, self.dropout, training=self.training) # Is it necessary? h = torch.matmul(select_feature, self.weight) # is it necessary after MLP dimension shrink? coef_nomi = torch.zeros(neighbor_dim - 1) for j in range(1, neighbor_dim): hij = torch.cat((h[0, :], h[j, :]), dim=1) coef_nomi[j - 1] = torch.exp(self.LeakyReLU(torch.matmul(hij, self.a))) coef_deno = torch.sum(coef_nomi) att = torch.zeros(neighbor_dim - 1) for j in range(1, neighbor_dim): alpha = torch.div(coef_nomi[j - 1], coef_deno) att[j - 1] = torch.matmul(alpha, h[j, :]) h_prime = torch.sum(att) # do we need nonlinear operator/activation function? # in the last layer we need average pooling operation and where to put it??? if self.bias is not None: h_prime = h_prime + self.bias out.append(h_prime) out = torch.cat(out, dim=1) return out # dimension 1 * (self.num_head * out_features) ##################################### #Transition Block will be as same as the graph convolution layer# #how to constrain the number of feature maps# ##################################### class BottleneckLayer(nn.Module): def __init__(self, in_channels, out_channels): super(BottleneckLayer, self).__init__() self.conv1 = nn.Conv1d(in_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=False) self.relu = nn.LeakyReLU(inplace=True) self.bn = nn.BatchNorm1d(in_channels) #Is bn and relu really necessary in this case? def forward(self, x): out = self.conv1(self.relu(self.bn(x))) return torch.cat([x, out], 1) # Not sure if this is necessary and needs revision ############ # bottleneck layer should come with avg pooling layer class GDB(nn.Module): def __init__(self, num_layers, input_size, growth_rate, block, dropRate=0.0): super(GDB, self).__init__() # self.MLP = MLP() # need revision #self.gc = GATConv() # need revision self.layer = self._make_layer(block, input_size, growth_rate, num_layers, dropRate) #self.dropout = dropout #self.ReLU = nn.LeakyReLU() def _make_layer(self, block, in_planes, growth_rate, nb_layers, dropRate): layers = [] for i in range(nb_layers): layers.append(block(in_planes + i * growth_rate, growth_rate, dropRate)) return nn.Sequential(*layers) def forward(self, x): return self.layer(x) # channel dimension? class GraphDensenet(nn.Module): def __init__(self, input_size, hidden_size, output_size, depth, growth_rate, reduction, bottleneck=True, dropRate=0.0, num_head=3, slope_alpha=0.2, bias=True): super(GraphDensenet, self).__init__() self.MLP = MLP(input_size, hidden_size, output_size) in_channels = 2 * growth_rate n = (depth - 4) / 3 # need revision if bottleneck == True: n = n/2 block = BottleneckLayer else: block = GATConv n = int(n) # 1st block self.block1 = GDB(n, in_channels, growth_rate, block, dropRate) in_channels = int(in_channels + n*growth_rate) # 1st transition block out_channels = int(math.floor(in_channels*reduction)) self.trans1 = GATConv(in_channels, out_channels, num_head, slope_alpha, bias) in_channels = int(math.floor(in_channels*reduction)) # 2nd block self.block2 = GDB(n, in_channels, growth_rate, block, dropRate) in_channels = int(in_channels + n*growth_rate) # 2nd transition block out_channels = int(math.floor(in_channels*reduction)) self.trans2 = GATConv(in_channels, out_channels, num_head, slope_alpha, bias) in_channels = int(math.floor(in_channels*reduction)) # 3rd block self.block3 = GDB(n, in_channels, growth_rate, block, dropRate) in_channels = int(in_channels + n*growth_rate) #global normalization self.bn1 = nn.BatchNorm2d(in_channels) self.relu = nn.ReLU(inplace=True) self.in_channels = in_channels for m in self.modules(): if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): m.bias.data.zero_() def forward(self, x): out = self.MLP(x) out = self.trans1(self.block1(out)) out = self.trans2(self.block2(out)) out = self.block3(out) # out = self.relu(self.bn1(out)) # is avg_pooling necessary? return out # out is the output latent input state fed into DDPG network
[ "torch.nn.functional.dropout", "torch.cat", "torch.nn.Conv1d", "torch.FloatTensor", "torch.nn.Linear", "torch.zeros", "torch.matmul", "math.sqrt", "torch.nn.init.xavier_uniform_", "torch.nn.BatchNorm1d", "torch.nn.BatchNorm2d", "torch.cuda.is_available", "torch.nn.LeakyReLU", "torch.sum", ...
[((189, 214), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (212, 214), False, 'import torch\n'), ((368, 402), 'torch.nn.Linear', 'nn.Linear', (['input_size', 'hidden_size'], {}), '(input_size, hidden_size)\n', (377, 402), True, 'import torch.nn as nn\n'), ((422, 457), 'torch.nn.Linear', 'nn.Linear', (['hidden_size', 'hidden_size'], {}), '(hidden_size, hidden_size)\n', (431, 457), True, 'import torch.nn as nn\n'), ((477, 512), 'torch.nn.Linear', 'nn.Linear', (['hidden_size', 'output_size'], {}), '(hidden_size, output_size)\n', (486, 512), True, 'import torch.nn as nn\n'), ((533, 547), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {}), '()\n', (545, 547), True, 'import torch.nn as nn\n'), ((1232, 1262), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', (['self.slope_alpha'], {}), '(self.slope_alpha)\n', (1244, 1262), True, 'import torch.nn as nn\n'), ((1487, 1540), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['self.weight.data'], {'gain': '(1.414)'}), '(self.weight.data, gain=1.414)\n', (1510, 1540), True, 'import torch.nn as nn\n'), ((1619, 1667), 'torch.nn.init.xavier_uniform_', 'nn.init.xavier_uniform_', (['self.a.data'], {'gain': '(1.414)'}), '(self.a.data, gain=1.414)\n', (1642, 1667), True, 'import torch.nn as nn\n'), ((1915, 1937), 'torch.stack', 'torch.stack', (['ls'], {'dim': '(0)'}), '(ls, dim=0)\n', (1926, 1937), False, 'import torch\n'), ((3225, 3246), 'torch.cat', 'torch.cat', (['out'], {'dim': '(1)'}), '(out, dim=1)\n', (3234, 3246), False, 'import torch\n'), ((3660, 3748), 'torch.nn.Conv1d', 'nn.Conv1d', (['in_channels', 'out_channels'], {'kernel_size': '(1)', 'stride': '(1)', 'padding': '(0)', 'bias': '(False)'}), '(in_channels, out_channels, kernel_size=1, stride=1, padding=0,\n bias=False)\n', (3669, 3748), True, 'import torch.nn as nn\n'), ((3765, 3791), 'torch.nn.LeakyReLU', 'nn.LeakyReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (3777, 3791), True, 'import torch.nn as nn\n'), ((3810, 3837), 'torch.nn.BatchNorm1d', 'nn.BatchNorm1d', (['in_channels'], {}), '(in_channels)\n', (3824, 3837), True, 'import torch.nn as nn\n'), ((3983, 4005), 'torch.cat', 'torch.cat', (['[x, out]', '(1)'], {}), '([x, out], 1)\n', (3992, 4005), False, 'import torch\n'), ((4753, 4775), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (4766, 4775), True, 'import torch.nn as nn\n'), ((6379, 6406), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['in_channels'], {}), '(in_channels)\n', (6393, 6406), True, 'import torch.nn as nn\n'), ((6427, 6448), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (6434, 6448), True, 'import torch.nn as nn\n'), ((1090, 1134), 'torch.FloatTensor', 'torch.FloatTensor', (['in_features', 'out_features'], {}), '(in_features, out_features)\n', (1107, 1134), False, 'import torch\n'), ((1166, 1205), 'torch.zeros', 'torch.zeros', ([], {'size': '(2 * out_features, 1)'}), '(size=(2 * out_features, 1))\n', (1177, 1205), False, 'import torch\n'), ((2222, 2285), 'torch.nn.functional.dropout', 'F.dropout', (['select_feature', 'self.dropout'], {'training': 'self.training'}), '(select_feature, self.dropout, training=self.training)\n', (2231, 2285), True, 'import torch.nn.functional as F\n'), ((2322, 2363), 'torch.matmul', 'torch.matmul', (['select_feature', 'self.weight'], {}), '(select_feature, self.weight)\n', (2334, 2363), False, 'import torch\n'), ((2435, 2464), 'torch.zeros', 'torch.zeros', (['(neighbor_dim - 1)'], {}), '(neighbor_dim - 1)\n', (2446, 2464), False, 'import torch\n'), ((2681, 2701), 'torch.sum', 'torch.sum', (['coef_nomi'], {}), '(coef_nomi)\n', (2690, 2701), False, 'import torch\n'), ((2720, 2749), 'torch.zeros', 'torch.zeros', (['(neighbor_dim - 1)'], {}), '(neighbor_dim - 1)\n', (2731, 2749), False, 'import torch\n'), ((2938, 2952), 'torch.sum', 'torch.sum', (['att'], {}), '(att)\n', (2947, 2952), False, 'import torch\n'), ((5611, 5646), 'math.floor', 'math.floor', (['(in_channels * reduction)'], {}), '(in_channels * reduction)\n', (5621, 5646), False, 'import math\n'), ((5758, 5793), 'math.floor', 'math.floor', (['(in_channels * reduction)'], {}), '(in_channels * reduction)\n', (5768, 5793), False, 'import math\n'), ((5999, 6034), 'math.floor', 'math.floor', (['(in_channels * reduction)'], {}), '(in_channels * reduction)\n', (6009, 6034), False, 'import math\n'), ((6146, 6181), 'math.floor', 'math.floor', (['(in_channels * reduction)'], {}), '(in_channels * reduction)\n', (6156, 6181), False, 'import math\n'), ((1317, 1348), 'torch.FloatTensor', 'torch.FloatTensor', (['out_features'], {}), '(out_features)\n', (1334, 1348), False, 'import torch\n'), ((2532, 2568), 'torch.cat', 'torch.cat', (['(h[0, :], h[j, :])'], {'dim': '(1)'}), '((h[0, :], h[j, :]), dim=1)\n', (2541, 2568), False, 'import torch\n'), ((2819, 2857), 'torch.div', 'torch.div', (['coef_nomi[j - 1]', 'coef_deno'], {}), '(coef_nomi[j - 1], coef_deno)\n', (2828, 2857), False, 'import torch\n'), ((2887, 2915), 'torch.matmul', 'torch.matmul', (['alpha', 'h[j, :]'], {}), '(alpha, h[j, :])\n', (2899, 2915), False, 'import torch\n'), ((1831, 1852), 'numpy.nonzero', 'np.nonzero', (['adj[i, :]'], {}), '(adj[i, :])\n', (1841, 1852), True, 'import numpy as np\n'), ((6679, 6697), 'math.sqrt', 'math.sqrt', (['(2.0 / n)'], {}), '(2.0 / n)\n', (6688, 6697), False, 'import math\n'), ((2629, 2654), 'torch.matmul', 'torch.matmul', (['hij', 'self.a'], {}), '(hij, self.a)\n', (2641, 2654), False, 'import torch\n')]
from argo.core.hooks.AbstractWavHook import AbstractWavHook from argo.core.utils.WavSaver import WavSaver from datasets.Dataset import check_dataset_keys_not_loop, VALIDATION, TRAIN, TEST from argo.core.argoLogging import get_logger from .wavenet.utils import mu_law_numpy from .wavenet.AnomalyDetector import AnomalyDetector import numpy as np import os tf_logging = get_logger() class WavReconstructHook(AbstractWavHook): def __init__(self, model, period, time_reference, dirName, sample_indices_by_dataset={ VALIDATION: []}, hop_legth_cqt=128, dataset_keys=[TRAIN, VALIDATION], save_wav=False, reconstruct_from_mean=True, batch_size=20, _plot=True, spider_plot_time_splits=None, anomaly_detection_params=None, compute_reconstruction_metrics=True ): super().__init__(model, period, time_reference, dataset_keys=dataset_keys, hop_legth_cqt=hop_legth_cqt, dirName=dirName) self._plot = _plot self.reconstruct_from_mean = reconstruct_from_mean self.save_wav = save_wav self.batch_size = batch_size self.spider_plot_time_splits = spider_plot_time_splits self._sample_indices_by_dataset = sample_indices_by_dataset self.compute_reconstruction_metrics = compute_reconstruction_metrics self.anomaly_detection_params = anomaly_detection_params if compute_reconstruction_metrics: self.reconstr_metrics_file_names = { TRAIN: dirName + '/reconstr_metrics_tf_train.txt', VALIDATION: dirName + '/reconstr_metrics_tf_validation.txt', TEST: dirName + '/reconstr_metrics_tf_test.txt', } check_dataset_keys_not_loop(list(sample_indices_by_dataset.keys())) tf_logging.info("Create WavReconstructHook for: \n" + \ "\n".join([ds_key + ": " + ", ".join(map(str, idxs or ['all'])) \ for ds_key, idxs in sample_indices_by_dataset.items()])) def before_training(self, session): tf_logging.info("WavReconstructHook, writing originals: " + str(self.save_wav)) if self.save_wav: self._write_origanals() if self.compute_reconstruction_metrics: self.write_headers_to_reconstruction_files() def do_when_triggered(self, run_context, run_values): tf_logging.info("trigger for WavReconstructHook") anomaly_detector = None if self.anomaly_detection_params is not None: anomaly_detector = AnomalyDetector(self.anomaly_detection_params, self.dir_name_anomaly_detection, '{}{}'.format(self._time_ref_shortstr, self._time_ref)) for ds_key in self._samples: indices, samples = self._samples[ds_key] _, labels = self._labels[ds_key] original_indices = indices samples = samples[indices] labels = labels[indices] indices = np.arange(0, samples.shape[0]) encode_tuple = self._model.encode(samples, sess=run_context.session) if len(encode_tuple) == 2: zs, x_shifted = encode_tuple hs = None covariance = None elif len(encode_tuple) == 6: zs, hs, covariance, prior_mean, prior_cov, x_shifted = encode_tuple else: raise ValueError("This tuple should not be this length: {}".format(len(encode_tuple))) # compute quantized and feed below... x_target_quantized = mu_law_numpy(samples) + 128 x_target_quantized = np.squeeze(x_target_quantized, axis=-1) reconstructed_samples, reconstr_loss_per_sample = self._model.decode_tf(zs, x_shifted, x_target_quantized=x_target_quantized, sess=run_context.session, batch_size=self.batch_size) if self.compute_reconstruction_metrics: self.log_reconstr_metrics(self._time_ref, samples, reconstructed_samples, reconstr_loss_per_sample, labels, self.reconstr_metrics_file_names[ds_key]) if anomaly_detector is not None: anomaly_detector.set_data(ds_key, samples, reconstructed_samples, labels, reconstr_loss_per_sample) if self._plot: if hs is not None and covariance is not None and self.reconstruct_from_mean: # if mean/covariance are not none -> VAE reconstructed_samples_mean, reconstr_loss_mean = self._model.decode_tf(hs, x_shifted, sess=run_context.session, x_target_quantized=x_target_quantized, batch_size=self.batch_size) self.multi_plot_and_save(ds_key, original_indices, reconstructed_samples_mean[indices], reconstructed_samples[indices], samples[indices], labels[indices], self._time_ref, self._time_ref_shortstr, zs[indices], hs[indices], covariance[indices], prior_mean, prior_cov, prefix='multiplot_tf_', save_enc=False, save_wav=self.save_wav, plot_mean_separately=True, plot_rainbowgram=False) elif hs is None and covariance is None: # AE self.plot_and_save(ds_key, original_indices, reconstructed_samples[original_indices], samples[original_indices], labels[original_indices], self._time_ref, self._time_ref_shortstr, zs[original_indices], prefix="reconstruction_tf_", suffix="sample", save_enc=False, save_wav=self.save_wav) tf_logging.info("finished with %s" % ds_key) if anomaly_detector is not None: anomaly_detector.detect_anomalies(self._model.dataset.sample_rate, 'tf')
[ "numpy.squeeze", "argo.core.argoLogging.get_logger", "numpy.arange" ]
[((369, 381), 'argo.core.argoLogging.get_logger', 'get_logger', ([], {}), '()\n', (379, 381), False, 'from argo.core.argoLogging import get_logger\n'), ((3227, 3257), 'numpy.arange', 'np.arange', (['(0)', 'samples.shape[0]'], {}), '(0, samples.shape[0])\n', (3236, 3257), True, 'import numpy as np\n'), ((3876, 3915), 'numpy.squeeze', 'np.squeeze', (['x_target_quantized'], {'axis': '(-1)'}), '(x_target_quantized, axis=-1)\n', (3886, 3915), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Apr 7 @author: MOTEorg """ import numpy as np import cv2 as cv import matplotlib.pyplot as plt from optparse import OptionParser #Parser of execution options usage = "Usage: \n\t%prog -i INPUT_IMAGE -d DEBUG" parser = OptionParser(usage=usage) parser.add_option("-i", "--input", dest="inFile", default='image.jpg', help="Name of the image file.", metavar="INPUT_IMAGE") parser.add_option("-d", "--debug", dest="debug", default='0', help="debugging messages", metavar="DEBUG") (options, args) = parser.parse_args() # If not input parameter , then set the default if not options.inFile: print("Not input file!\n") #1. Load image original_image=cv.imread(options.inFile) #2. Convert to grayscale gray_image=cv.cvtColor(original_image,cv.COLOR_BGR2GRAY) #3. Enhance brightness gamma=0.7 lookUpTable = np.empty((1,256), np.uint8) for i in range(256): lookUpTable[0,i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255) bright_image = cv.LUT(gray_image, lookUpTable) #4. Trheshold image threshold=76 ret,thresh_image = cv.threshold(bright_image,threshold,255,cv.THRESH_TOZERO) #5. Extract Edges minVal=64 maxVal=108 edges_image = cv.Canny(thresh_image,minVal,maxVal) #5.1 Edges to black edges_inv_image=255*np.ones((np.shape(edges_image)))-edges_image #6. Morph image kernel_h = np.ones((3,1),np.uint8) kernel_v = np.ones((1,3),np.uint8) kernel = np.ones((4,2),np.uint8) dilation = cv.dilate(edges_image,kernel,iterations = 2) erosion_h = cv.erode(dilation,kernel_h,iterations = 1) erosion = cv.erode(dilation,kernel_v,iterations = 1) #7. Color channel mask #b_image=cv.merge([original_image[:,:,0],np.zeros((np.shape(edges_image)),np.uint8),np.zeros((np.shape(edges_image)),np.uint8)]) #g_image=cv.merge([np.zeros((np.shape(edges_image)),np.uint8),original_image[:,:,0],np.zeros((np.shape(edges_image)),np.uint8)]) r_image=cv.merge([np.zeros((np.shape(edges_image)),np.uint8),original_image[:,:,0],np.zeros((np.shape(edges_image)),np.uint8)]) #8. Blur bilateral filters kernel_size=15 final_image_aux=cv.bilateralFilter(original_image,kernel_size,50,50) final_image_r=cv.bilateralFilter(r_image,kernel_size,25,25) #9. Brightness and contrast modification gamma1=1.05 alpha=1.9 beta=0.8 lookUpTable_add = np.empty((1,256), np.uint8) for i in range(256): lookUpTable_add[0,i] = np.clip(pow(i*alpha / 255.0, gamma1) * 255.0*beta, 0, 255) final_image_0=cv.LUT(cv.subtract(final_image_aux[:,:,0],erosion), lookUpTable_add) final_image_1=cv.LUT(cv.subtract(final_image_r[:,:,1],erosion), lookUpTable_add) final_image_2=cv.LUT(cv.subtract(final_image_aux[:,:,2],erosion), lookUpTable_add) #8. Add color channels in a single image and apply a smooth Gaussian filter final_image=cv.GaussianBlur(cv.merge([final_image_0,final_image_1,final_image_2]),(kernel_size,kernel_size),0) #TODO: Shadows and magazine style #Show edges and final filtered image plt.figure() plt.subplot(1,2,1) plt.imshow(erosion,interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.subplot(1,2,2) plt.imshow(final_image,interpolation = 'bicubic') plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis plt.show() #Save filename_split=(options.inFile).split('.') cv.imwrite(filename_split[0]+'_filtered.jpg',final_image)
[ "optparse.OptionParser", "numpy.empty", "numpy.ones", "cv2.bilateralFilter", "numpy.shape", "matplotlib.pyplot.figure", "cv2.erode", "cv2.subtract", "cv2.dilate", "cv2.cvtColor", "matplotlib.pyplot.imshow", "cv2.imwrite", "matplotlib.pyplot.yticks", "cv2.LUT", "matplotlib.pyplot.xticks",...
[((287, 312), 'optparse.OptionParser', 'OptionParser', ([], {'usage': 'usage'}), '(usage=usage)\n', (299, 312), False, 'from optparse import OptionParser\n'), ((754, 779), 'cv2.imread', 'cv.imread', (['options.inFile'], {}), '(options.inFile)\n', (763, 779), True, 'import cv2 as cv\n'), ((816, 862), 'cv2.cvtColor', 'cv.cvtColor', (['original_image', 'cv.COLOR_BGR2GRAY'], {}), '(original_image, cv.COLOR_BGR2GRAY)\n', (827, 862), True, 'import cv2 as cv\n'), ((909, 937), 'numpy.empty', 'np.empty', (['(1, 256)', 'np.uint8'], {}), '((1, 256), np.uint8)\n', (917, 937), True, 'import numpy as np\n'), ((1043, 1074), 'cv2.LUT', 'cv.LUT', (['gray_image', 'lookUpTable'], {}), '(gray_image, lookUpTable)\n', (1049, 1074), True, 'import cv2 as cv\n'), ((1127, 1187), 'cv2.threshold', 'cv.threshold', (['bright_image', 'threshold', '(255)', 'cv.THRESH_TOZERO'], {}), '(bright_image, threshold, 255, cv.THRESH_TOZERO)\n', (1139, 1187), True, 'import cv2 as cv\n'), ((1238, 1276), 'cv2.Canny', 'cv.Canny', (['thresh_image', 'minVal', 'maxVal'], {}), '(thresh_image, minVal, maxVal)\n', (1246, 1276), True, 'import cv2 as cv\n'), ((1387, 1412), 'numpy.ones', 'np.ones', (['(3, 1)', 'np.uint8'], {}), '((3, 1), np.uint8)\n', (1394, 1412), True, 'import numpy as np\n'), ((1422, 1447), 'numpy.ones', 'np.ones', (['(1, 3)', 'np.uint8'], {}), '((1, 3), np.uint8)\n', (1429, 1447), True, 'import numpy as np\n'), ((1455, 1480), 'numpy.ones', 'np.ones', (['(4, 2)', 'np.uint8'], {}), '((4, 2), np.uint8)\n', (1462, 1480), True, 'import numpy as np\n'), ((1490, 1534), 'cv2.dilate', 'cv.dilate', (['edges_image', 'kernel'], {'iterations': '(2)'}), '(edges_image, kernel, iterations=2)\n', (1499, 1534), True, 'import cv2 as cv\n'), ((1547, 1589), 'cv2.erode', 'cv.erode', (['dilation', 'kernel_h'], {'iterations': '(1)'}), '(dilation, kernel_h, iterations=1)\n', (1555, 1589), True, 'import cv2 as cv\n'), ((1600, 1642), 'cv2.erode', 'cv.erode', (['dilation', 'kernel_v'], {'iterations': '(1)'}), '(dilation, kernel_v, iterations=1)\n', (1608, 1642), True, 'import cv2 as cv\n'), ((2113, 2168), 'cv2.bilateralFilter', 'cv.bilateralFilter', (['original_image', 'kernel_size', '(50)', '(50)'], {}), '(original_image, kernel_size, 50, 50)\n', (2131, 2168), True, 'import cv2 as cv\n'), ((2180, 2228), 'cv2.bilateralFilter', 'cv.bilateralFilter', (['r_image', 'kernel_size', '(25)', '(25)'], {}), '(r_image, kernel_size, 25, 25)\n', (2198, 2228), True, 'import cv2 as cv\n'), ((2317, 2345), 'numpy.empty', 'np.empty', (['(1, 256)', 'np.uint8'], {}), '((1, 256), np.uint8)\n', (2325, 2345), True, 'import numpy as np\n'), ((2961, 2973), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2971, 2973), True, 'import matplotlib.pyplot as plt\n'), ((2974, 2994), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(1)'], {}), '(1, 2, 1)\n', (2985, 2994), True, 'import matplotlib.pyplot as plt\n'), ((2993, 3037), 'matplotlib.pyplot.imshow', 'plt.imshow', (['erosion'], {'interpolation': '"""bicubic"""'}), "(erosion, interpolation='bicubic')\n", (3003, 3037), True, 'import matplotlib.pyplot as plt\n'), ((3109, 3129), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(2)', '(2)'], {}), '(1, 2, 2)\n', (3120, 3129), True, 'import matplotlib.pyplot as plt\n'), ((3128, 3176), 'matplotlib.pyplot.imshow', 'plt.imshow', (['final_image'], {'interpolation': '"""bicubic"""'}), "(final_image, interpolation='bicubic')\n", (3138, 3176), True, 'import matplotlib.pyplot as plt\n'), ((3248, 3258), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3256, 3258), True, 'import matplotlib.pyplot as plt\n'), ((3309, 3369), 'cv2.imwrite', 'cv.imwrite', (["(filename_split[0] + '_filtered.jpg')", 'final_image'], {}), "(filename_split[0] + '_filtered.jpg', final_image)\n", (3319, 3369), True, 'import cv2 as cv\n'), ((2474, 2520), 'cv2.subtract', 'cv.subtract', (['final_image_aux[:, :, 0]', 'erosion'], {}), '(final_image_aux[:, :, 0], erosion)\n', (2485, 2520), True, 'import cv2 as cv\n'), ((2557, 2601), 'cv2.subtract', 'cv.subtract', (['final_image_r[:, :, 1]', 'erosion'], {}), '(final_image_r[:, :, 1], erosion)\n', (2568, 2601), True, 'import cv2 as cv\n'), ((2638, 2684), 'cv2.subtract', 'cv.subtract', (['final_image_aux[:, :, 2]', 'erosion'], {}), '(final_image_aux[:, :, 2], erosion)\n', (2649, 2684), True, 'import cv2 as cv\n'), ((2805, 2860), 'cv2.merge', 'cv.merge', (['[final_image_0, final_image_1, final_image_2]'], {}), '([final_image_0, final_image_1, final_image_2])\n', (2813, 2860), True, 'import cv2 as cv\n'), ((3039, 3053), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (3049, 3053), True, 'import matplotlib.pyplot as plt\n'), ((3055, 3069), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (3065, 3069), True, 'import matplotlib.pyplot as plt\n'), ((3178, 3192), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (3188, 3192), True, 'import matplotlib.pyplot as plt\n'), ((3194, 3208), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (3204, 3208), True, 'import matplotlib.pyplot as plt\n'), ((1324, 1345), 'numpy.shape', 'np.shape', (['edges_image'], {}), '(edges_image)\n', (1332, 1345), True, 'import numpy as np\n'), ((1954, 1975), 'numpy.shape', 'np.shape', (['edges_image'], {}), '(edges_image)\n', (1962, 1975), True, 'import numpy as np\n'), ((2019, 2040), 'numpy.shape', 'np.shape', (['edges_image'], {}), '(edges_image)\n', (2027, 2040), True, 'import numpy as np\n')]
################################################################################# # Copyright (c) 2018-2021, Texas Instruments Incorporated - http://www.ti.com # All Rights Reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ################################################################################# # Some parts of the code are borrowed from: https://github.com/pytorch/vision # with the following license: # # BSD 3-Clause License # # Copyright (c) <NAME> 2016, # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ################################################################################# import numpy as np import cv2 import torch import types import PIL class Compose(object): """ Composes several co_transforms together. For example: >>> co_transforms.Compose([ >>> co_transforms.CenterCrop(10), >>> co_transforms.ToTensor(), >>> ]) """ def __init__(self, t): self.co_transforms = t def extend(self, t): self.co_transforms.extend(t) def insert(self, index, t): self.co_transforms.insert(index, t) def write_img(self, img=[], ch_num=-1, name='', en=False): if en == False: return #name = './data/checkpoints/tiad_interest_pt_descriptor/debug/{:02d}.jpg'.format(aug_idx) scale_range = 255.0 / np.max(img) img = np.clip(img * scale_range, 0.0, 255.0) img = np.asarray(img, 'uint8') non_zero_el = cv2.countNonZero(img) print("non zero element: {}".format(non_zero_el)) cv2.imwrite('{}_nz{}.jpg'.format(name, non_zero_el), img) def __call__(self, input, target): if self.co_transforms: for aug_idx, t in enumerate(self.co_transforms): if t: input,target = t(input,target) return input,target class Bypass(object): def __init__(self): pass def __call__(self, images, targets): return images,targets class Lambda(object): """Applies a lambda as a transform""" def __init__(self, lambd): assert isinstance(lambd, types.LambdaType) self.lambd = lambd def __call__(self, input,target): return self.lambd(input,target) class ImageTransformUtils(object): @staticmethod def apply_to_list(func, inputs, *args, **kwargs): for img_idx in range(len(inputs)): inputs[img_idx] = func(inputs[img_idx], img_idx, *args, **kwargs) return inputs @staticmethod def apply_to_lists(func, images, targets, *args, **kwargs): for img_idx in range(len(images)): images[img_idx], targets[img_idx] = func(images[img_idx], targets[img_idx], img_idx, *args, **kwargs) return images, targets @staticmethod def crop(img, r, c, h, w): img = img[r:(r+h), c:(c+w),...] if (len(img.shape)>2) else img[r:(r+h), c:(c+w)] return img @staticmethod def resize_fast(img, output_size_rc, interpolation=-1): in_h, in_w = img.shape[:2] out_h, out_w = output_size_rc if interpolation<0: interpolation = cv2.INTER_AREA if ((out_h<in_h) or (out_w<in_w)) else cv2.INTER_LINEAR img = cv2.resize(img, (out_w,out_h), interpolation=interpolation) #opencv expects size in (w,h) format img = img[...,np.newaxis] if len(img.shape) < 3 else img return img @staticmethod def resize_img(img, size, interpolation=-1, is_flow=False): #if (len(img.shape) == 3) and (img.shape[2] == 1 or img.shape[2] == 3): # return __class__.resize_fast(img, size, interpolation) in_h, in_w = img.shape[:2] out_h, out_w = size if interpolation is None or interpolation < 0: interpolation = cv2.INTER_AREA if ((out_h<in_h) or (out_w<in_w)) else cv2.INTER_LINEAR # opencv handles planar, 1 or 3 channel images img = img[...,np.newaxis] if len(img.shape) < 3 else img num_chans = img.shape[2] img = np.concatenate([img]+[img[...,0:1]]*(3-num_chans), axis=2) if num_chans<3 else img img = cv2.resize(img, (out_w, out_h), interpolation=interpolation) img = img[...,:num_chans] if is_flow: ratio_h = out_h / in_h ratio_w = out_w / in_w img = ImageTransformUtils.scale_flow(img, ratio_w, ratio_h) return img @staticmethod def resize_and_crop(img, r, c, h, w, size, interpolation=-1, is_flow=False, resize_in_yv12=False): if resize_in_yv12: yv12 = cv2.cvtColor(img, cv2.COLOR_RGB2YUV_YV12) yv12 = ImageTransformUtils.resize_img_yv12(yv12, size, interpolation, is_flow) img = cv2.cvtColor(yv12, cv2.COLOR_YUV2RGB_YV12) else: img = ImageTransformUtils.resize_img(img, size, interpolation, is_flow) # img = ImageTransformUtils.crop(img, r, c, h, w) return img @staticmethod def crop_and_resize(img, r, c, h, w, size, interpolation=-1, is_flow=False, resize_in_yv12=False): img = ImageTransformUtils.crop(img, r, c, h, w) if resize_in_yv12: yv12 = cv2.cvtColor(img, cv2.COLOR_RGB2YUV_YV12) yv12 = ImageTransformUtils.resize_img_yv12(yv12, size, interpolation, is_flow) img = cv2.cvtColor(yv12, cv2.COLOR_YUV2RGB_YV12) else: img = ImageTransformUtils.resize_img(img, size, interpolation, is_flow) # return img @staticmethod def rotate_img(img, angle, interpolation=-1): h, w = img.shape[:2] rmat2x3 = cv2.getRotationMatrix2D(center=(w//2,h//2), angle=angle, scale=1.0) interpolation = cv2.INTER_NEAREST if interpolation < 0 else interpolation img = cv2.warpAffine(img, rmat2x3, (w,h), flags=interpolation) return img @staticmethod def reverse_channels(img): if isinstance(img, np.ndarray): return img[:,:,::-1] elif isinstance(img, PIL.Image): return PIL.Image.fromarray(np.array(img)[:,:,::-1]) else: assert False, 'unrecognized image type' @staticmethod def array_to_tensor(array): """Converts a numpy.ndarray (H x W x C) to a torch.FloatTensor of shape (C x H x W).""" assert(isinstance(array, np.ndarray)) # put it from HWC to CHW format array = np.transpose(array, (2, 0, 1)) if len(array.shape) < 3: array = array[np.newaxis, ...] # tensor = torch.from_numpy(array) return tensor.float() @staticmethod def scale_flow(flow, ratio_x, ratio_y): flow = flow.astype(np.float32) flow[...,0] *= ratio_x flow[...,1] *= ratio_y return flow @staticmethod def scale_flows(inputs, ratio_x, ratio_y, is_flow): for img_idx in range(len(inputs)): if is_flow and is_flow[img_idx]: inputs[img_idx] = inputs[img_idx].astype(np.float32) inputs[img_idx][...,0] *= ratio_x inputs[img_idx][...,1] *= ratio_y # return inputs ############################################################# # functions for nv12 @staticmethod def resize_img_yv12(img, size, interpolation=-1, is_flow=False): #if (len(img.shape) == 3) and (img.shape[2] == 1 or img.shape[2] == 3): # return __class__.resize_fast(img, size, interpolation) debug_print = False in_w = img.shape[1] in_h = (img.shape[0] * 2) // 3 y_h = in_h uv_h = in_h // 4 u_w = in_w // 2 Y = img[0:in_h, 0:in_w] V = img[y_h:y_h + uv_h, 0:in_w] #print(V[0:2,0:8]) #print(V[0:2, u_w:u_w+8]) V = V.reshape(V.shape[0]*2, -1) #print(V[0:2, 0:8]) #print(V[0:2, u_w:u_w + 8]) U = img[y_h + uv_h:y_h + 2 * uv_h, 0:in_w] U = U.reshape(U.shape[0] * 2, -1) out_h, out_w = size if interpolation < 0: interpolation = cv2.INTER_AREA if ((out_h < in_h) or (out_w < in_w)) else cv2.INTER_LINEAR Y = cv2.resize(Y, (out_w, out_h), interpolation=interpolation) U = cv2.resize(U, (out_w//2, out_h//2), interpolation=interpolation) V = cv2.resize(V, (out_w//2, out_h//2), interpolation=interpolation) img = np.zeros((out_h*3//2, out_w), dtype='uint8') op_uv_h = out_h // 4 img[0:out_h, 0:out_w] = Y[:, :] #print(V[0:2,0:8]) V = V.reshape(V.shape[0] // 2, -1) #print(V[0:1,0:8]) #print(V[0:1, op_u_w:op_u_w+8]) img[out_h:out_h + op_uv_h, 0:out_w] = V U = U.reshape(U.shape[0] // 2, -1) img[out_h + op_uv_h:out_h + 2 * op_uv_h, 0:out_w] = U if debug_print: h = img.shape[0] * 2 // 3 w = img.shape[1] print("-" * 32, "Resize in YV12") print("Y") print(img[0:5, 0:5]) print("V Odd Lines") print(img[h:h + 5, 0:5]) print("V Even Lines") print(img[h:h + 5, w // 2:w // 2 + 5]) print("U Odd Lines") print(img[h + h // 4:h + h // 4 + 5, 0:5]) print("U Even Lines") print(img[h + h // 4:h + h // 4 + 5, w // 2:w // 2 + 5]) print("-" * 32) if is_flow: ratio_h = out_h / in_h ratio_w = out_w / in_w img = ImageTransformUtils.scale_flow(img, ratio_w, ratio_h) return img # @staticmethod # def resize_and_crop_yv12(img, r, c, h, w, size, interpolation=-1, is_flow=False): # yv12 = cv2.cvtColor(img, cv2.COLOR_RGB2YUV_YV12) # yv12 = ImageTransformUtils.resize_img_yv12(yv12, size, interpolation, is_flow) # img = cv2.cvtColor(yv12, cv2.COLOR_YUV2RGb_YV12) # img = ImageTransformUtils.crop(img, r, c, h, w) # return img # # @staticmethod # def crop_and_resize_yv12(img, r, c, h, w, size, interpolation=-1, is_flow=False): # img = ImageTransformUtils.crop(img, r, c, h, w) # yv12 = cv2.cvtColor(img, cv2.COLOR_RGB2YUV_YV12) # yv12 = ImageTransformUtils.resize_img_yv12(img, size, interpolation, is_flow) # img = cv2.cvtColor(yv12, cv2.COLOR_YUV2RGB_YV12) # return img
[ "numpy.concatenate", "cv2.countNonZero", "cv2.cvtColor", "numpy.asarray", "numpy.transpose", "numpy.zeros", "numpy.clip", "cv2.warpAffine", "numpy.max", "numpy.array", "cv2.getRotationMatrix2D", "cv2.resize", "torch.from_numpy" ]
[((4246, 4284), 'numpy.clip', 'np.clip', (['(img * scale_range)', '(0.0)', '(255.0)'], {}), '(img * scale_range, 0.0, 255.0)\n', (4253, 4284), True, 'import numpy as np\n'), ((4299, 4323), 'numpy.asarray', 'np.asarray', (['img', '"""uint8"""'], {}), "(img, 'uint8')\n", (4309, 4323), True, 'import numpy as np\n'), ((4347, 4368), 'cv2.countNonZero', 'cv2.countNonZero', (['img'], {}), '(img)\n', (4363, 4368), False, 'import cv2\n'), ((6094, 6154), 'cv2.resize', 'cv2.resize', (['img', '(out_w, out_h)'], {'interpolation': 'interpolation'}), '(img, (out_w, out_h), interpolation=interpolation)\n', (6104, 6154), False, 'import cv2\n'), ((6989, 7049), 'cv2.resize', 'cv2.resize', (['img', '(out_w, out_h)'], {'interpolation': 'interpolation'}), '(img, (out_w, out_h), interpolation=interpolation)\n', (6999, 7049), False, 'import cv2\n'), ((8473, 8545), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', ([], {'center': '(w // 2, h // 2)', 'angle': 'angle', 'scale': '(1.0)'}), '(center=(w // 2, h // 2), angle=angle, scale=1.0)\n', (8496, 8545), False, 'import cv2\n'), ((8637, 8694), 'cv2.warpAffine', 'cv2.warpAffine', (['img', 'rmat2x3', '(w, h)'], {'flags': 'interpolation'}), '(img, rmat2x3, (w, h), flags=interpolation)\n', (8651, 8694), False, 'import cv2\n'), ((9256, 9286), 'numpy.transpose', 'np.transpose', (['array', '(2, 0, 1)'], {}), '(array, (2, 0, 1))\n', (9268, 9286), True, 'import numpy as np\n'), ((9390, 9413), 'torch.from_numpy', 'torch.from_numpy', (['array'], {}), '(array)\n', (9406, 9413), False, 'import torch\n'), ((10990, 11048), 'cv2.resize', 'cv2.resize', (['Y', '(out_w, out_h)'], {'interpolation': 'interpolation'}), '(Y, (out_w, out_h), interpolation=interpolation)\n', (11000, 11048), False, 'import cv2\n'), ((11061, 11129), 'cv2.resize', 'cv2.resize', (['U', '(out_w // 2, out_h // 2)'], {'interpolation': 'interpolation'}), '(U, (out_w // 2, out_h // 2), interpolation=interpolation)\n', (11071, 11129), False, 'import cv2\n'), ((11138, 11206), 'cv2.resize', 'cv2.resize', (['V', '(out_w // 2, out_h // 2)'], {'interpolation': 'interpolation'}), '(V, (out_w // 2, out_h // 2), interpolation=interpolation)\n', (11148, 11206), False, 'import cv2\n'), ((11218, 11266), 'numpy.zeros', 'np.zeros', (['(out_h * 3 // 2, out_w)'], {'dtype': '"""uint8"""'}), "((out_h * 3 // 2, out_w), dtype='uint8')\n", (11226, 11266), True, 'import numpy as np\n'), ((4220, 4231), 'numpy.max', 'np.max', (['img'], {}), '(img)\n', (4226, 4231), True, 'import numpy as np\n'), ((6892, 6957), 'numpy.concatenate', 'np.concatenate', (['([img] + [img[..., 0:1]] * (3 - num_chans))'], {'axis': '(2)'}), '([img] + [img[..., 0:1]] * (3 - num_chans), axis=2)\n', (6906, 6957), True, 'import numpy as np\n'), ((7435, 7476), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2YUV_YV12'], {}), '(img, cv2.COLOR_RGB2YUV_YV12)\n', (7447, 7476), False, 'import cv2\n'), ((7586, 7628), 'cv2.cvtColor', 'cv2.cvtColor', (['yv12', 'cv2.COLOR_YUV2RGB_YV12'], {}), '(yv12, cv2.COLOR_YUV2RGB_YV12)\n', (7598, 7628), False, 'import cv2\n'), ((8036, 8077), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_RGB2YUV_YV12'], {}), '(img, cv2.COLOR_RGB2YUV_YV12)\n', (8048, 8077), False, 'import cv2\n'), ((8187, 8229), 'cv2.cvtColor', 'cv2.cvtColor', (['yv12', 'cv2.COLOR_YUV2RGB_YV12'], {}), '(yv12, cv2.COLOR_YUV2RGB_YV12)\n', (8199, 8229), False, 'import cv2\n'), ((8916, 8929), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (8924, 8929), True, 'import numpy as np\n')]
# Copyright (C) 2002-2021 S[&]T, The Netherlands. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. """ VISAN command line functions and procedures """ __all__ = ['histogramplot', 'plot', 'wplot', 'executescript', 'browseproduct', 'version'] import os import sys import numpy import harp from .harpplot import PlotDataForProduct, WorldPlotDataForProduct def histogramplot(data, bins, *args, **kwargs): """ Draw a histogram plot. This is a convenience function that creates a histogram in a plot window. >>> histogramplot(data, bins) will create a histogramplot where 'data' is the output of the histogram() function and 'bins' is the bins parameter that was used to create the histogram. Both 'data' and 'bins' should be rank-1 arrays and the array length of 'data' should be one less than the length of 'bins'. For customizing the plot you can use the same additional options as are available for the plot() function. """ data = numpy.asarray(data) bins = numpy.asarray(bins) x = numpy.transpose(numpy.reshape(numpy.concatenate([bins[:-1], bins[1:]]), (2, len(bins) - 1))).ravel() y = numpy.transpose(numpy.reshape(numpy.concatenate([data, data]), (2, len(data)))).ravel() plot(x, y, *args, **kwargs) def plot(*args, **kwargs): """ Display a 2-dimensional plot of a dataset. The plot() function has several different usage modes, and can take a large number of optional keywords. For a full reference guide, please consult the VISAN documentation at: <http://www.stcorp.nl/beat/> Basic usage: >>> plot(ydata) where 'ydata' is a one-dimensional Python list or numpy array, will plot the 'ydata' values on the vertical axis against an index array [0..len(data)] on the horizontal axis, in a single plot frame. >>> plot(xdata, ydata) where 'xdata' and 'ydata' are both one-dimensional, will plot the 'ydata' values on the vertical axis against the corresponding 'xdata' values on the horizontal axis. If 'ydata', or 'xdata' and 'ydata' are two-dimensional n x m arrays, a sequence of n plot frames will be created. Each frame f will show a plot of the ydata[f,:] values against the xdata[f,:] values. Initially, only the first frame is shown. The user can start an animation sequence which will cycle through the successive frames in the plot window. >>> plot(harpproduct) where 'harpproduct' is an object of type harp.Product (see also the documentation for the HARP python interface), will display a specific 2D plot associated with the type of data contained in 'harpproduct'. >>> plot(harpproduct, value='variablename') will create a 2D plot for the specified variable of the HARP product. >>> w = plot(data1) >>> plot(data2, window=w) will plot data2 in the same window 'w' as used for data1, instead of opening a separate window. In addition to the 'window' keyword, the plot() function also accepts a number of other, comma-separated optional properties of the form 'property=value'. Their order is arbitrary, but they must always appear after any data arguments to the plot() function. Available plot() properties are: window, windowtitle, size, pos, title, xrange, yrange, xmin, xmax, ymin, ymax, xlog, ylog, xbase, ybase, xlabel, ylabel, xnumticks, ynumticks, numticks, showanimationtoolbar, showpropertypanel, value, name, lines, linewidth, stipplepattern, points, pointsize, color, opacity. """ import wx from . import windowhandler as WindowHandler from visan.plot import PlotFrame # validate all arguments defaultProperties = dict() dataSetAttributes = dict() dataSetLocation = [] xdata = None ydata = None value = None try: value = kwargs["value"] except KeyError: pass if len(args) > 0: if isinstance(args[0], harp.Product): if len(args) != 1: raise ValueError("plot() does not allow additional data arguments when the first argument " "is a HARP product") xdata, ydata, dataSetAttributes, dataSetLocation, defaultProperties = PlotDataForProduct(args[0], value) else: if value is not None: raise ValueError("parameter 'value' (%s) is only allowed when plotting a HARP product" % value) if len(args) > 2: raise ValueError("plot() takes at most two data arguments (%d given)" % len(args)) elif len(args) > 1: xdata = args[0] if isinstance(xdata, harp.Variable): xdata = xdata.data ydata = args[1] if isinstance(ydata, harp.Variable): ydata = ydata.data else: ydata = args[0] if isinstance(ydata, harp.Variable): ydata = ydata.data elif value is not None: raise ValueError("parameter 'value' (%s) is only allowed when plotting a HARP product" % value) knownproperties = ["value", "window", "windowtitle", "size", "pos", "title", "xrange", "yrange", "xmin", "xmax", "ymin", "ymax", "xlog", "ylog", "xbase", "ybase", "xlabel", "ylabel", "xnumticks", "ynumticks", "numticks", "showanimationtoolbar", "showpropertypanel", "name", "lines", "linewidth", "stipplepattern", "points", "pointsize", "color", "opacity"] unknowns = [k for k in list(kwargs.keys()) if k not in knownproperties] if len(unknowns) == 1: raise TypeError("Invalid keyword: %s\n(Supported keywords are: %s)" % (unknowns[0], ', '.join(knownproperties))) elif len(unknowns) > 1: raise TypeError("Invalid keywords: %s\n(Supported keywords are: %s)" % (', '.join(unknowns), ', '.join(knownproperties))) # window window = kwargs.get("window") if window is not None: if not isinstance(window, PlotFrame): raise ValueError("parameter 'window' (%s) does not refer to a plot window" % window) if not window: raise ValueError("parameter 'window' refers to a window that no longer exists") # windowtitle windowtitle = kwargs.get("windowtitle") if windowtitle is not None: try: windowtitle = str(windowtitle) except TypeError: raise ValueError("parameter 'windowtitle' should be a string") # size size = kwargs.get("size") if size is not None: try: size = tuple(size) except TypeError: raise TypeError("parameter 'size' should be a 2-element sequence of numbers (was: '%s')" % str(size)) try: x = float(size[0]) y = float(size[1]) except TypeError: raise TypeError("parameter 'size' should be a 2-element sequence of numbers (was: '%s')" % str(size)) if x <= 0 or y <= 0: raise ValueError("parameter 'size' must contain positive numbers (was: '%s')" % str(size)) xmax = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_X) if x > xmax: raise ValueError("x component of 'size' parameter must not exceed maximum screen width ('%g' > '%g')" % (x, xmax)) ymax = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y) if y > ymax: raise ValueError("y component of 'size' parameter must not exceed maximum screen heigth ('%g' > '%g')" % (y, ymax)) # pos pos = kwargs.get("pos") if pos is not None: try: pos = tuple(pos) except TypeError: raise TypeError("parameter 'pos' should be a 2-element sequence of numbers (was: '%s')" % str(pos)) try: x = float(pos[0]) y = float(pos[1]) except TypeError: raise TypeError("parameter 'pos' should be a 2-element sequence of numbers (was: '%s')" % str(pos)) if x < 0 or y < 0: raise ValueError("parameter 'pos' must contain positive numbers (was: '%s')" % str(pos)) xmax = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_X) if x > xmax: raise ValueError("x component of 'pos' parameter must not exceed maximum screen width ('%g' > '%g')" % (x, xmax)) ymax = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y) if y > ymax: raise ValueError("y component of 'pos' parameter must not exceed maximum screen heigth ('%g' > '%g')" % (y, ymax)) # check mutual exclusive parameters if kwargs.get("xmin") is not None and kwargs.get("xrange") is not None: raise ValueError("it is not allowed to specify both 'xrange' and 'xmin' in a single call") if kwargs.get("xmax") is not None and kwargs.get("xrange") is not None: raise ValueError("it is not allowed to specify both 'xrange' and 'xmax' in a single call") if kwargs.get("ymin") is not None and kwargs.get("yrange") is not None: raise ValueError("it is not allowed to specify both 'yrange' and 'ymin' in a single call") if kwargs.get("ymax") is not None and kwargs.get("yrange") is not None: raise ValueError("it is not allowed to specify both 'yrange' and 'ymax' in a single call") if kwargs.get("numticks") is not None and kwargs.get("xnumticks") is not None: raise ValueError("it is not allowed to specify both 'numticks' and 'xnumticks' in a single call") if kwargs.get("numticks") is not None and kwargs.get("ynumticks") is not None: raise ValueError("it is not allowed to specify both 'numticks' and 'ynumticks' in a single call") # process arguments if window is None: if size is None: size = WindowHandler.GetDefaultSize() if pos is None: pos = WindowHandler.GetNextPosition(size) plot = PlotFrame(size=size, pos=pos) else: plot = window if size is not None: plot.SetSize(size) if pos is not None: plot.Move(pos) # prevent intermediate repaints of the plotwindow until we have set all properties plot.Freeze() try: # add data set (if data was given) dataSetId = None if len(args) > 0: dataSetId = plot.AddDataSet(xdata, ydata) for attr in dataSetAttributes: plot.AddDataSetAttribute(dataSetId, attr, dataSetAttributes[attr]) if len(dataSetLocation) == 2: # TODO: make this work for animated plots plot.AddDataSetLocation(dataSetId, dataSetLocation[0], dataSetLocation[1]) # set generic plot properties if windowtitle is not None: plot.SetTitle(windowtitle) if kwargs.get("title") is not None: plot.SetPlotTitle(kwargs.get("title")) elif "title" in defaultProperties: plot.SetPlotTitle(defaultProperties["title"]) if kwargs.get("xrange") is not None: plot.SetXAxisRange(kwargs.get("xrange")) if kwargs.get("yrange") is not None: plot.SetYAxisRange(kwargs.get("yrange")) if kwargs.get("xmin") is not None: if kwargs.get("xmax") is not None: plot.SetXAxisRange([kwargs.get("xmin"), kwargs.get("xmax")]) else: plot.SetXAxisRange([kwargs.get("xmin"), plot.GetXAxisRange()[1]]) if kwargs.get("xmax") is not None: plot.SetXAxisRange([plot.GetXAxisRange()[0], kwargs.get("xmax")]) if kwargs.get("ymin") is not None: if kwargs.get("ymax") is not None: plot.SetYAxisRange([kwargs.get("ymin"), kwargs.get("ymax")]) else: plot.SetYAxisRange([kwargs.get("ymin"), plot.GetYAxisRange()[1]]) if kwargs.get("ymax") is not None: plot.SetYAxisRange([plot.GetYAxisRange()[0], kwargs.get("ymax")]) if kwargs.get("xlog") is not None: plot.SetXLogAxis(kwargs.get("xlog")) elif "xlog" in defaultProperties: plot.SetXLogAxis(defaultProperties["xlog"]) if kwargs.get("ylog") is not None: plot.SetYLogAxis(kwargs.get("ylog")) elif "ylog" in defaultProperties: plot.SetYLogAxis(defaultProperties["ylog"]) if kwargs.get("xbase") is not None: plot.SetXAxisBase(kwargs.get("xbase")) elif "xbase" in defaultProperties: plot.SetXAxisBase(defaultProperties["xbase"]) if kwargs.get("ybase") is not None: plot.SetYAxisBase(kwargs.get("ybase")) elif "ybase" in defaultProperties: plot.SetYAxisBase(defaultProperties["ybase"]) if kwargs.get("xlabel") is not None: plot.SetXAxisTitle(kwargs.get("xlabel")) elif "xlabel" in defaultProperties: plot.SetXAxisTitle(defaultProperties["xlabel"]) if kwargs.get("ylabel") is not None: plot.SetYAxisTitle(kwargs.get("ylabel")) elif "ylabel" in defaultProperties: plot.SetYAxisTitle(defaultProperties["ylabel"]) if kwargs.get("numticks") is not None: plot.SetXNumAxisLabels(kwargs.get("numticks")) plot.SetYNumAxisLabels(kwargs.get("numticks")) if kwargs.get("xnumticks") is not None: plot.SetXNumAxisLabels(kwargs.get("xnumticks")) if kwargs.get("ynumticks") is not None: plot.SetYNumAxisLabels(kwargs.get("ynumticks")) if kwargs.get("showanimationtoolbar") is not None: plot.ShowAnimationToolbar(kwargs.get("showanimationtoolbar")) elif "showanimationtoolbar" in defaultProperties: plot.ShowAnimationToolbar(defaultProperties["showanimationtoolbar"]) if kwargs.get("showpropertypanel") is not None: plot.ShowPropertyPanel(kwargs.get("showpropertypanel")) elif "showpropertypanel" in defaultProperties: plot.ShowPropertyPanel(defaultProperties["showpropertypanel"]) # set data set properties if dataSetId is not None: if kwargs.get("name") is not None: plot.SetDataSetLabel(dataSetId, kwargs.get("name")) elif "name" in defaultProperties: plot.SetDataSetLabel(dataSetId, defaultProperties["name"]) if kwargs.get("lines") is not None: plot.SetPlotLines(dataSetId, kwargs.get("lines")) if kwargs.get("linewidth") is not None: plot.SetLineWidth(dataSetId, kwargs.get("linewidth")) if kwargs.get("stipplepattern") is not None: plot.SetLineStipplePattern(dataSetId, kwargs.get("stipplepattern")) if kwargs.get("points") is not None: plot.SetPlotPoints(dataSetId, kwargs.get("points")) if kwargs.get("pointsize") is not None: plot.SetPointSize(dataSetId, kwargs.get("pointsize")) if kwargs.get("color") is not None: plot.SetPlotColor(dataSetId, kwargs.get("color")) if kwargs.get("opacity") is not None: plot.SetOpacity(dataSetId, kwargs.get("opacity")) else: # use our own VISAN specific opacity setting plot.SetOpacity(dataSetId, 0.6) except Exception: if window is None: # only destroy the window if we created it ourselves plot.Destroy() raise plot.Thaw() return plot def wplot(*args, **kwargs): """ Display a dataset plotted onto an Earth world map. The wplot() function accepts dataset parameters similar to the plot() function. It can plot basic longitude vs. latitude data as well as HARP products containing latitude/longitude information. All datasets are plotted onto a 2D or 3D Earth world map. For a full reference guide, please consult the VISAN documentation at: <http://www.stcorp.nl/beat/> Basic usage: >>> wplot(latitude, longitude) will plot the locations using the information from the 'latitude' and 'longitude' arrays and project these onto a world map, in a single plot frame. The type of projection can be chosen by supplying a value for the 'projection' keyword. The latitude/longitude arrays may contain either points or corner coordinates. >>> wplot(latitude, longitude, data) will plot the locations using 'data' as color information. If 'data' is one-dimensional, then the data will be plotted as points or swaths. It will be plotted as points if the latitude/longitude arrays are one-dimensional, and as swaths if latitude/longitude arrays are two-dimensional (in which case the second dimension should capture the corners of the swath) If 'data' has more than one dimension, then 'data' will be plotted as a grid using the latitude and longitude as axis. Latitude should match the last dimension of 'data' and longitude the second-last dimension. If 'data' is three dimensional, then an animation plot is created with the first dimension being used as time dimension. >>> plot(harpproduct) where 'harpproduct' is an object of type harp.Product (see also the documentation for the HARP python interface), will display a specific worldmap plot associated with the type of data contained in 'harpproduct'. >>> plot(harpproduct, value='variablename') will create a worldmap plot for the specified variable of the HARP product. The wplot() function also accepts a number of comma-separated optional properties of the form 'property=value'. Their order is arbitrary, but they must always appear after any data arguments to the wplot() function. Available wplot() properties are: window, windowtitle, size, pos, title, centerlat, centerlon, zoom, projection, projectionlat, projectionlon, showanimationtoolbar, showpropertypanel, showcolorbar, value, colortable, colorrange, colorbartitle, numcolorlabels, opacity, linewidth, pointsize, drawpath, drawlocation, heightfactor, minheightvalue, maxheightvalue, deltaradius. """ import wx from . import windowhandler as WindowHandler from visan.plot import WorldPlotFrame kPointData = 0 kSwathData = 1 kGridData = 2 # validate all arguments defaultProperties = dict() dataSetAttributes = dict() latitude = None longitude = None data = None value = None datatype = kPointData plotPoints = False plotLines = False try: value = kwargs["value"] except KeyError: pass if kwargs.get("drawpath") is not None: plotLines = bool(kwargs["drawpath"]) if kwargs.get("drawlocation") is not None: plotPoints = bool(kwargs["drawlocation"]) if len(args) > 0: if isinstance(args[0], harp.Product): if len(args) != 1: raise ValueError("wplot() does not allow additional data arguments when the first argument is a " "HARP product") datatype, data, latitude, longitude, dataSetAttributes, defaultProperties = \ WorldPlotDataForProduct(args[0], plotPoints or plotLines, value) else: if value is not None: raise ValueError("parameter 'value' (%s) is only allowed when plotting a HARP product" % value) if len(args) == 3: data = args[2] if isinstance(data, harp.Variable): data = data.data elif len(args) != 2: raise ValueError("wplot() takes either two or three data arguments if the first argument is not a " "HARP product (%d given)" % len(args)) latitude = args[0] if isinstance(latitude, harp.Variable): latitude = latitude.data if not isinstance(latitude, numpy.ndarray): try: latitude = numpy.asarray(args[0]) except TypeError: raise TypeError("latitude data argument cannot be converted to numpy array. %s" % str(latitude)) longitude = args[1] if isinstance(longitude, harp.Variable): longitude = longitude.data if not isinstance(longitude, numpy.ndarray): try: longitude = numpy.asarray(args[1]) except TypeError: raise TypeError("longitude data argument cannot be converted to numpy array. %s" % str(longitude)) if data is not None: try: data = numpy.asarray(data) except TypeError: raise TypeError("data argument cannot be converted to numpy array. %s" % str(data)) if data.ndim > 1: datatype = kGridData if datatype == kPointData and latitude.ndim == 2 and longitude.ndim == 2: datatype = kSwathData elif value is not None: raise ValueError("parameter 'value' (%s) is only allowed when plotting a HARP product" % value) knownproperties = ["window", "windowtitle", "size", "pos", "title", "centerlat", "centerlon", "zoom", "projection", "projectionlat", "projectionlon", "showanimationtoolbar", "showpropertypanel", "showcolorbar", "value", "colortable", "colorrange", "colorbartitle", "numcolorlabels", "opacity", "linewidth", "pointsize", "drawpath", "drawlocation", "heightfactor", "minheightvalue", "maxheightvalue", "deltaradius"] unknowns = [k for k in list(kwargs.keys()) if k not in knownproperties] if len(unknowns) == 1: raise TypeError("Invalid keyword: %s\n(Supported keywords are: %s)" % (unknowns[0], ', '.join(knownproperties))) elif len(unknowns) > 1: raise TypeError("Invalid keywords: %s\n(Supported keywords are: %s)" % (', '.join(unknowns), ', '.join(knownproperties))) # window window = kwargs.get("window") if window is not None: if not isinstance(window, WorldPlotFrame): raise ValueError("parameter 'window' (%s) does not refer to a wplot window" % window) if not window: raise ValueError("parameter 'window' refers to a window that no longer exists") # windowtitle windowtitle = kwargs.get("windowtitle") if windowtitle is not None: try: windowtitle = str(windowtitle) except TypeError: raise ValueError("parameter 'windowtitle' should be a string") # size size = kwargs.get("size") if size is not None: try: size = tuple(size) except TypeError: raise TypeError("parameter 'size' should be a 2-element sequence of numbers (was: '%s')" % str(size)) try: x = float(size[0]) y = float(size[1]) except TypeError: raise TypeError("parameter 'size' should be a 2-element sequence of numbers (was: '%s')" % str(size)) if x <= 0 or y <= 0: raise ValueError("parameter 'size' must contain positive numbers (was: '%s')" % str(size)) xmax = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_X) if x > xmax: raise ValueError("x component of 'size' parameter must not exceed maximum screen width ('%g' > '%g')" % (x, xmax)) ymax = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y) if y > ymax: raise ValueError("y component of 'size' parameter must not exceed maximum screen heigth ('%g' > '%g')" % (y, ymax)) # pos pos = kwargs.get("pos") if pos is not None: try: pos = tuple(pos) except TypeError: raise TypeError("parameter 'pos' should be a 2-element sequence of numbers (was: '%s')" % str(pos)) try: x = float(pos[0]) y = float(pos[1]) except TypeError: raise TypeError("parameter 'pos' should be a 2-element sequence of numbers (was: '%s')" % str(pos)) if x < 0 or y < 0: raise ValueError("parameter 'pos' must contain positive numbers (was: '%s')" % str(pos)) xmax = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_X) if x > xmax: raise ValueError("x component of 'pos' parameter must not exceed maximum screen width ('%g' > '%g')" % (x, xmax)) ymax = wx.SystemSettings_GetMetric(wx.SYS_SCREEN_Y) if y > ymax: raise ValueError("y component of 'pos' parameter must not exceed maximum screen heigth ('%g' > '%g')" % (y, ymax)) # process arguments if window is None: if size is None: size = WindowHandler.GetDefaultSize() if pos is None: pos = WindowHandler.GetNextPosition(size) plot = WorldPlotFrame(size=size, pos=pos) else: plot = window if size is not None: plot.SetSize(size) if pos is not None: plot.Move(pos) # prevent intermediate repaints of the plotwindow until we have set all properties plot.Freeze() try: # add data set (if data was given) dataSetId = None if len(args) > 0: if datatype == kPointData: if plotLines: dataSetId = plot.AddLineData(latitude, longitude) else: dataSetId = plot.AddPointData(latitude, longitude, data) elif datatype == kSwathData: dataSetId = plot.AddSwathData(latitude, longitude, data) elif datatype == kGridData: dataSetId = plot.AddGridData(latitude, longitude, data) else: raise AssertionError("invalid datatype (%d) for plotdata" % datatype) for attr in dataSetAttributes: plot.AddDataSetAttribute(dataSetId, attr, dataSetAttributes[attr]) # set generic plot properties if windowtitle is not None: plot.SetTitle(windowtitle) if kwargs.get("title") is not None: plot.SetPlotTitle(kwargs.get("title")) elif "title" in defaultProperties: plot.SetPlotTitle(defaultProperties["title"]) if kwargs.get("showanimationtoolbar") is not None: plot.ShowAnimationToolbar(kwargs.get("showanimationtoolbar")) elif "showanimationtoolbar" in defaultProperties: plot.ShowAnimationToolbar(defaultProperties["showanimationtoolbar"]) if kwargs.get("showpropertypanel") is not None: plot.ShowPropertyPanel(kwargs.get("showpropertypanel")) elif "showpropertypanel" in defaultProperties: plot.ShowPropertyPanel(defaultProperties["showpropertypanel"]) if kwargs.get("showcolorbar") is not None: plot.ShowColorBar(kwargs.get("showcolorbar")) elif "showcolorbar" in defaultProperties: plot.ShowColorBar(defaultProperties["showcolorbar"]) if kwargs.get("projection") is not None: plot.SetProjection(kwargs.get("projection")) if kwargs.get("projectionlat") is not None: plot.SetProjectionCenterLatitude(kwargs.get("projectionlat")) if kwargs.get("projectionlon") is not None: plot.SetProjectionCenterLongitude(kwargs.get("projectionlon")) if kwargs.get("centerlat") is not None: plot.SetViewCenterLatitude(kwargs.get("centerlat")) if kwargs.get("centerlon") is not None: plot.SetViewCenterLongitude(kwargs.get("centerlon")) if kwargs.get("zoom") is not None: plot.SetViewZoom(kwargs.get("zoom")) else: if window is None: # if we are creating the plot, set the initial zoom level (if 1.0 is not appropriate) if kwargs.get("projection") is None or kwargs.get("projection").lower() == "3d": plot.SetViewZoom(2.5) elif kwargs.get("projection").lower() == "lambert cylindrical" or \ kwargs.get("projection").lower() == "plate caree" or \ kwargs.get("projection").lower() == "mollweide" or \ kwargs.get("projection").lower() == "robinson": plot.SetViewZoom(1.6) # set data set properties if dataSetId is not None: if kwargs.get("name") is not None: plot.SetDataSetLabel(dataSetId, kwargs.get("name")) elif "name" in defaultProperties: plot.SetDataSetLabel(dataSetId, defaultProperties["name"]) if kwargs.get("colortable") is not None: try: plot.GetColorTable(dataSetId).SetColorTableByName(kwargs.get("colortable")) except Exception: plot.GetColorTable(dataSetId).Import(kwargs.get("colortable")) elif "colortable" in defaultProperties: plot.GetColorTable(dataSetId).SetColorTableByName(defaultProperties["colortable"]) if kwargs.get("colorrange") is not None: plot.SetColorRange(dataSetId, kwargs.get("colorrange")) elif "colorrange" in defaultProperties: plot.SetColorRange(dataSetId, defaultProperties["colorrange"]) if kwargs.get("colorbartitle") is not None: plot.SetColorBarTitle(dataSetId, kwargs.get("colorbartitle")) elif "colorbartitle" in defaultProperties: plot.SetColorBarTitle(dataSetId, defaultProperties["colorbartitle"]) if kwargs.get("numcolorlabels") is not None: plot.SetNumColorBarLabels(dataSetId, kwargs.get("numcolorlabels")) if kwargs.get("opacity") is not None: plot.SetOpacity(dataSetId, kwargs.get("opacity")) elif "opacity" in defaultProperties: plot.SetOpacity(dataSetId, defaultProperties["opacity"]) if kwargs.get("linewidth") is not None: plot.SetLineWidth(dataSetId, kwargs.get("linewidth")) if kwargs.get("pointsize") is not None: plot.SetPointSize(dataSetId, kwargs.get("pointsize")) if kwargs.get("heightfactor") is not None: plot.SetHeightFactor(dataSetId, kwargs.get("heightfactor")) if kwargs.get("minheightvalue") is not None: plot.SetMinHeightValue(dataSetId, kwargs.get("minheightvalue")) if kwargs.get("maxheightvalue") is not None: plot.SetMinHeightValue(dataSetId, kwargs.get("maxheightvalue")) if kwargs.get("deltaradius") is not None: try: deltaradius = float(kwargs.get("deltaradius")) except TypeError: raise TypeError("deltaradius property should be a float (was: '%s')" % str(kwargs.get("deltaradius"))) plot.SetReferenceHeight(dataSetId, 1.0 + deltaradius) except Exception: if window is None: # only destroy the window if we created it ourselves plot.Destroy() raise plot.Thaw() # TODO: Is this still applicable? # The Yield and Refresh are needed to make sure that colortable changes are shown. # Somehow the plot is not rendered using the new colortable after the Thaw. # We have to let the current Refresh result in a Render (using wx.Yield()) # and then ask for a new render using Refresh() wx.Yield() plot.Refresh() return plot def executescript(filename, globals=None, mainargs=None): """ Execute a script. This routine runs an external python script. >>> executescript(filename) runs the script file located at the path indicated by 'filename' and returns to the prompt when the script is finished. If the system is unable to locate the file indicated by 'filename' an execption will be thrown. When you run a script, VISAN will automatically add the location of your script to the module searchpath (sys.path). This means that if your script uses modules that are located in the same directory as the script file then these modules will automatically be found. When the script is finished VISAN will change the module searchpath back to its original value. If you want the script to have access to variables that you have already set or if you want to have access to variables that are going to be set by the script, just pass 'globals()' as second parameter: >>> executescript(filename, globals()) If the script needs to be run as a 'main' script (i.e. as if it was run as an argument to the python executable) and/or requires command line arguments you can use the 'mainargs' keyword. The 'mainargs' keyword should contain a list of command line options (which may be an empty list). For instance, to run a setup.py script to install an external module you could use: >>> executescript('/home/user/package/setup.py', mainargs = ['install']) This will have the result the script is called with the '__name__ variable set to '__main__' and sys.argv will have been set to ['/home/user/package/setup.py', 'install']. The current working directory for the script will also be set to the directory of the script (e.g. '/home/user/package'). Note that if a 'mainargs' keyword parameter is provided, the 'globals' parameter to executescript() (if present) will be ignored. """ if os.path.exists(filename): if os.path.isfile(filename): print(("Executing VISAN/Python script '%s':\n" % filename)) oldcwd = os.getcwd() scriptdir = os.path.dirname(filename) sys.path.insert(0, scriptdir) oldargv = sys.argv try: if mainargs is None: if globals is None: exec(compile(open(filename).read(), filename, 'exec')) else: exec(compile(open(filename).read(), filename, 'exec'), globals) else: sys.argv = [filename] + mainargs os.chdir(scriptdir) exec(compile(open(filename).read(), filename, 'exec'), {'__name__': '__main__'}) finally: del sys.path[0] sys.argv = oldargv os.chdir(oldcwd) else: raise IOError("Error executing VISAN/Python script, the path '%s' does not point to a file\n" % filename) else: raise IOError("Error executing VISAN/Python script, the file '%s' does not exist\n" % filename) def browseproduct(filename): """ Open the Product Browser with a specific product. This routine opens a new Product Browser window with the give product file. >>> browseproduct(filename) If the system is unable to locate the file indicated by 'filename' an execption will be thrown. """ if os.path.exists(filename): if os.path.isfile(filename): import wx wx.GetApp().BrowseProduct(filename) else: raise IOError("Error opening product file, the path '%s' does not point to a file\n" % filename) else: raise IOError("Error opening product file, the file '%s' does not exist\n" % filename) def version(): """ Get version number of VISAN. >>> v = version() returns the version number of the current VISAN release. """ from . import VERSION return VERSION
[ "os.getcwd", "numpy.asarray", "visan.plot.PlotFrame", "os.path.exists", "os.path.dirname", "sys.path.insert", "visan.plot.WorldPlotFrame", "os.path.isfile", "wx.GetApp", "wx.Yield", "os.chdir", "numpy.concatenate", "wx.SystemSettings_GetMetric" ]
[((2438, 2457), 'numpy.asarray', 'numpy.asarray', (['data'], {}), '(data)\n', (2451, 2457), False, 'import numpy\n'), ((2469, 2488), 'numpy.asarray', 'numpy.asarray', (['bins'], {}), '(bins)\n', (2482, 2488), False, 'import numpy\n'), ((33357, 33367), 'wx.Yield', 'wx.Yield', ([], {}), '()\n', (33365, 33367), False, 'import wx\n'), ((35388, 35412), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (35402, 35412), False, 'import os\n'), ((36874, 36898), 'os.path.exists', 'os.path.exists', (['filename'], {}), '(filename)\n', (36888, 36898), False, 'import os\n'), ((8663, 8707), 'wx.SystemSettings_GetMetric', 'wx.SystemSettings_GetMetric', (['wx.SYS_SCREEN_X'], {}), '(wx.SYS_SCREEN_X)\n', (8690, 8707), False, 'import wx\n'), ((8900, 8944), 'wx.SystemSettings_GetMetric', 'wx.SystemSettings_GetMetric', (['wx.SYS_SCREEN_Y'], {}), '(wx.SYS_SCREEN_Y)\n', (8927, 8944), False, 'import wx\n'), ((9720, 9764), 'wx.SystemSettings_GetMetric', 'wx.SystemSettings_GetMetric', (['wx.SYS_SCREEN_X'], {}), '(wx.SYS_SCREEN_X)\n', (9747, 9764), False, 'import wx\n'), ((9956, 10000), 'wx.SystemSettings_GetMetric', 'wx.SystemSettings_GetMetric', (['wx.SYS_SCREEN_Y'], {}), '(wx.SYS_SCREEN_Y)\n', (9983, 10000), False, 'import wx\n'), ((11514, 11543), 'visan.plot.PlotFrame', 'PlotFrame', ([], {'size': 'size', 'pos': 'pos'}), '(size=size, pos=pos)\n', (11523, 11543), False, 'from visan.plot import PlotFrame\n'), ((24946, 24990), 'wx.SystemSettings_GetMetric', 'wx.SystemSettings_GetMetric', (['wx.SYS_SCREEN_X'], {}), '(wx.SYS_SCREEN_X)\n', (24973, 24990), False, 'import wx\n'), ((25183, 25227), 'wx.SystemSettings_GetMetric', 'wx.SystemSettings_GetMetric', (['wx.SYS_SCREEN_Y'], {}), '(wx.SYS_SCREEN_Y)\n', (25210, 25227), False, 'import wx\n'), ((26003, 26047), 'wx.SystemSettings_GetMetric', 'wx.SystemSettings_GetMetric', (['wx.SYS_SCREEN_X'], {}), '(wx.SYS_SCREEN_X)\n', (26030, 26047), False, 'import wx\n'), ((26239, 26283), 'wx.SystemSettings_GetMetric', 'wx.SystemSettings_GetMetric', (['wx.SYS_SCREEN_Y'], {}), '(wx.SYS_SCREEN_Y)\n', (26266, 26283), False, 'import wx\n'), ((26678, 26712), 'visan.plot.WorldPlotFrame', 'WorldPlotFrame', ([], {'size': 'size', 'pos': 'pos'}), '(size=size, pos=pos)\n', (26692, 26712), False, 'from visan.plot import WorldPlotFrame\n'), ((35425, 35449), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (35439, 35449), False, 'import os\n'), ((36911, 36935), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (36925, 36935), False, 'import os\n'), ((35545, 35556), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (35554, 35556), False, 'import os\n'), ((35581, 35606), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (35596, 35606), False, 'import os\n'), ((35619, 35648), 'sys.path.insert', 'sys.path.insert', (['(0)', 'scriptdir'], {}), '(0, scriptdir)\n', (35634, 35648), False, 'import sys\n'), ((36287, 36303), 'os.chdir', 'os.chdir', (['oldcwd'], {}), '(oldcwd)\n', (36295, 36303), False, 'import os\n'), ((2527, 2567), 'numpy.concatenate', 'numpy.concatenate', (['[bins[:-1], bins[1:]]'], {}), '([bins[:-1], bins[1:]])\n', (2544, 2567), False, 'import numpy\n'), ((2636, 2667), 'numpy.concatenate', 'numpy.concatenate', (['[data, data]'], {}), '([data, data])\n', (2653, 2667), False, 'import numpy\n'), ((21661, 21683), 'numpy.asarray', 'numpy.asarray', (['args[0]'], {}), '(args[0])\n', (21674, 21683), False, 'import numpy\n'), ((22073, 22095), 'numpy.asarray', 'numpy.asarray', (['args[1]'], {}), '(args[1])\n', (22086, 22095), False, 'import numpy\n'), ((22331, 22350), 'numpy.asarray', 'numpy.asarray', (['data'], {}), '(data)\n', (22344, 22350), False, 'import numpy\n'), ((36062, 36081), 'os.chdir', 'os.chdir', (['scriptdir'], {}), '(scriptdir)\n', (36070, 36081), False, 'import os\n'), ((36971, 36982), 'wx.GetApp', 'wx.GetApp', ([], {}), '()\n', (36980, 36982), False, 'import wx\n')]
# AUTOGENERATED! DO NOT EDIT! File to edit: 10_FE.ipynb (unless otherwise specified). __all__ = ['FE'] # Cell from pyDOE import lhs import numpy as np from scipy.stats.distributions import norm from scipy.stats import uniform import yaml from qd.cae.dyna import KeyFile import os import pandas as pd from diversipy.hycusampling import maximin_reconstruction as maxmin from pathlib import PurePath class FE(): """ This Class contains set of methods which performs reading of the .yaml file and replaces values of the input parameters with newly generated sample data sets. And then, new key files are generated for simulation. ----------- INPUTS ----------- settigs : Input file for FE simulations to get the user input """ def __init__(self, settings): self.settings = settings self.folders_count=0 self._read_user_input() def _read_user_input(self): """ gets the user input details from the settings.yaml file. Returns ------- fin_dir : Final path of the created directory self.Run : Number of runs self.para_list : A .yaml file containing the parameters/ features/ variables for sampling with appropriate values as subkeys in the same file. self.key : .key file containg the initial simulation details. """ """ gets the user input details from the settings.yaml file. Returns ------- fin_dir : Final path of the created directory self.Run : Number of runs self.para_list : A .yaml file containing the parameters/ features/ variables for sampling with appropriate values as subkeys in the same file. self.key : .key file containg the initial simulation details. """ with open(self.settings,'r') as file: inp = yaml.load(file, Loader=yaml.FullLoader) inp_vals=[*inp.values()] inp_keys=[*inp.keys()] req=['baseline_directory','simulations'] for names in req: if names not in inp_keys: raise Exception(names +" not in dynakit_FE.yaml file") if inp[names] == None: raise Exception(names +" value not in dynakit_FE.yaml file") if isinstance(inp['simulations'], int) == True: self.Run=inp['simulations'] self.int='yes' self.Flag=1 elif isinstance(inp['simulations'], str) == True: self.DOE=pd.read_csv(inp['simulations']) self.int='no' self.Run=len(self.DOE) self.Flag=1 else: print('Enter either a Integer or a .csv Input') self.cwd=os.getcwd() base_dir=PurePath(inp['baseline_directory']) self.basepath=os.path.abspath(base_dir) self.fin_dir=os.path.dirname(self.basepath) self.basename=base_dir.name self.dyna_dir = os.path.join(self.fin_dir,'.dynakit') self.para_list='FE_parameters.yaml' self.key=inp['main_key'] self.fol_name=self.basename.split('_')[0] if os.path.exists(self.dyna_dir): if [name for name in os.listdir(self.dyna_dir) if name.endswith(".csv")] == []: os.rmdir(self.dyna_dir) try: os.mkdir(self.dyna_dir) except OSError as err: print('Adding new samples to the existing directory') self.Flag=0 return self.fin_dir , self.Run , self.key , self.para_list def read_parameters(self): """ converts the .yaml file to a dictionary Parameters ---------- self.para_list : the config.yaml file with the user inputs Returns ------- z : the .yaml file in dictionary format """ os.chdir(self.fin_dir) with open(self.para_list,'r') as file: parameter_list = yaml.load(file, Loader=yaml.FullLoader) dynParams = {k: v for k, v in parameter_list['parameters'].items() if parameter_list['parameters'][k]['type'] == 'dynaParameter'} self.dynaParameters = pd.DataFrame.from_dict(dynParams) onparams = {k: v for k, v in dynParams.items() if dynParams[k]['status'] == True } self.new_par=pd.DataFrame.from_dict(onparams) on=self.new_par.loc['parameter'] self.on_params=on.to_list() return self.dynaParameters def get_samples(self): """ samples the data based on the .yaml file using normal / uniform distribution and lhs library Parameters ---------- vars : values assigned to the sub keys in the .yaml file self.Run : Number of samples required Returns ------- Data : samples matrix in a list """ os.chdir(self.dyna_dir) if self.int=='yes': self.col_names=self.dynaParameters.loc['parameter'] elif self.int=='no': self.col_names=self.DOE.columns if self.int =='yes': DOE_s = lhs(len(self.new_par.loc['parameter']),samples = self.Run) j=0 self.DOE=np.zeros((self.Run,len(self.dynaParameters.loc['parameter']))) for i in range(0,len(self.dynaParameters.loc['parameter'])): if self.dynaParameters.loc['parameter'][i] in self.on_params: self.DOE[:,i]=DOE_s[:,j] j+=1 else: self.DOE[:,i]=1 save_file=pd.DataFrame(self.DOE) os.chdir(self.dyna_dir) save_file.to_csv('DOE.csv', index=False) minimum_val = self.dynaParameters.loc['min'] maximum_val = self.dynaParameters.loc['max'] for j in range(0,len(self.dynaParameters.loc['parameter'])): if self.dynaParameters.loc['parameter'][j] in self.on_params: if self.dynaParameters.loc['distribution'][j]=='Uniform': self.DOE[:,j]=uniform(self.dynaParameters.loc['min'][j], self.dynaParameters.loc['max'][j] - self.dynaParameters.loc['min'][j]).ppf(self.DOE[:, j]) elif self.dynaParameters.loc['distribution'][j]=='Normal': self.DOE[:, j] = norm(loc=self.dynaParameters.loc['mean'][j], scale=self.dynaParameters.loc['SD'][j]).ppf(self.DOE[:, j]) else: self.DOE[:,j]=self.dynaParameters.loc['default'][j] elif self.int=='no': os.chdir(self.dyna_dir) df=self.DOE df.to_csv('DOE.csv', index=False) self.DOE=np.array(self.DOE) return self.DOE def add_samples(self): """ adds samples of the data based on the .yaml file using normal / uniform distribution and lhs library Parameters ---------- vars : values assigned to the sub keys in the .yaml file self.Run : Number of samples required self.fin_dir : final path of the created directory Returns ------- Data : samples matrix in a list """ os.chdir(self.cwd) os.chdir(self.fin_dir) self.folders_count =len([name for name in os.listdir(os.getcwd()) if name.startswith(self.fol_name)])-1 os.chdir(self.dyna_dir) if os.path.isfile('DOE.csv'): old_DOE_s=pd.read_csv('DOE.csv') else: print('No preexisting DOE found!') if self.int=='yes': self.col_names=self.dynaParameters.loc['parameter'] elif self.int=='no': self.col_names=self.DOE.columns if self.int=='yes': old_DOE=np.zeros((self.folders_count,len(self.new_par.loc['parameter']))) old=old_DOE_s.values j=0 for i in range(0,len(self.dynaParameters.loc['parameter'])): if self.dynaParameters.loc['parameter'][i] in self.on_params: old_DOE[:,j]=old[:,i] j+=1 data_add=lhs(len(self.new_par.loc['parameter']),samples = self.Run) DOE_new_add= maxmin(self.Run,len(self.new_par.loc['parameter']), num_steps=None, initial_points=data_add, existing_points=old_DOE, use_reflection_edge_correction=None, dist_matrix_function=None, callback=None) new_DOE=np.zeros((self.Run,len(self.dynaParameters.loc['parameter']))) j=0 for i in range(0,len(self.dynaParameters.loc['parameter'])): if self.dynaParameters.loc['parameter'][i] in self.on_params: new_DOE[:,i]=DOE_new_add[:,j] j+=1 else: new_DOE[:,i]=1 df=pd.DataFrame(new_DOE) os.chdir(self.dyna_dir) df.to_csv('DOE.csv', mode='a', header=False, index=False) self.DOE= pd.read_csv('DOE.csv') for j in range(0,len(self.dynaParameters.loc['parameter'])): if self.dynaParameters.loc['parameter'][j] in self.on_params: if self.dynaParameters.loc['distribution'][j]=='Uniform': self.DOE.values[:,j]=uniform(self.dynaParameters.loc['min'][j], self.dynaParameters.loc['max'][j] - self.dynaParameters.loc['min'][j]).ppf(self.DOE.values[:, j]) elif self.dynaParameters.loc['distribution'][j]=='Normal': self.DOE.values[:, j] = norm(loc=self.dynaParameters.loc['mean'][j], scale=self.dynaParameters.loc['SD'][j]).ppf(self.DOE.values[:, j]) else: self.DOE.values[:,j]=self.dynaParameters.loc['default'][j] self.DOE=self.DOE.values elif self.int=='no': os.chdir(self.dyna_dir) df=self.DOE df.to_csv('DOE.csv', mode='a', header=False, index=False) self.DOE=np.array(self.DOE) return self.DOE def generate_keyfile(self): """ Generate the new updated .key file and a FE_Parameters.yaml file containing respective sampled values for each parameters in new folders. Parameters ---------- self.newkey : a new key file with an updated file path. self.fin_dir : final path of the created directory self.Run : Number of samples required self.para_num : number of parameters/variables/features self.para_names : Names of parameters/variables/features self.DOE : samples matrix in a list Returns ------- fldolder in the directory """ os.chdir(self.basepath) kf=KeyFile(self.key) os.chdir(self.fin_dir) key_parameters=kf["*PARAMETER"][0] key_parameters_array=np.array(kf["*PARAMETER"][0]) # Creating a dictionary with key and it's values: key_dict={} R_index=[] for i in range(0,len(key_parameters_array)): if key_parameters_array[i].startswith('R'): R_index.append(i) f=key_parameters_array[i].split(' ') key_dict[f[1]]=f[-1] par_lis=[*key_dict.keys()] os.chdir(self.fin_dir) self.folders_count =len([name for name in os.listdir(os.getcwd()) if name.startswith(self.fol_name)]) for run in range(0,self.Run): os.mkdir('{}_{:03}'.format(self.fol_name,(run+self.folders_count))) os.chdir('{}_{:03}'.format(self.fol_name,(run+self.folders_count))) FE_Parameters = {} for para in range(0,len(self.col_names)): for i in range(0,len(R_index)): if par_lis[i] == self.col_names[para]: key_parameters[i+1,1] = self.DOE[run+self.folders_count-1,para] kf.save("run_main_{:03}.key".format((run+self.folders_count))) FE_Parameters[par_lis[i]] = key_parameters[i+1,1] with open('simulation_Parameters.yaml','w') as FE_file: yaml.dump(FE_Parameters,FE_file,default_flow_style = False) os.chdir(self.fin_dir) def get_simulation_files(self): """ Runs all the methods of pre-process class """ self.read_parameters() if self.Flag==1: self.get_samples() elif self.Flag==0: self.add_samples() self.generate_keyfile()
[ "os.mkdir", "yaml.load", "pandas.read_csv", "yaml.dump", "os.path.isfile", "os.path.join", "os.chdir", "pandas.DataFrame", "os.path.abspath", "os.path.dirname", "os.path.exists", "qd.cae.dyna.KeyFile", "pandas.DataFrame.from_dict", "os.rmdir", "os.listdir", "os.getcwd", "scipy.stats....
[((2802, 2813), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2811, 2813), False, 'import os\n'), ((2832, 2867), 'pathlib.PurePath', 'PurePath', (["inp['baseline_directory']"], {}), "(inp['baseline_directory'])\n", (2840, 2867), False, 'from pathlib import PurePath\n'), ((2890, 2915), 'os.path.abspath', 'os.path.abspath', (['base_dir'], {}), '(base_dir)\n', (2905, 2915), False, 'import os\n'), ((2937, 2967), 'os.path.dirname', 'os.path.dirname', (['self.basepath'], {}), '(self.basepath)\n', (2952, 2967), False, 'import os\n'), ((3030, 3068), 'os.path.join', 'os.path.join', (['self.fin_dir', '""".dynakit"""'], {}), "(self.fin_dir, '.dynakit')\n", (3042, 3068), False, 'import os\n'), ((3211, 3240), 'os.path.exists', 'os.path.exists', (['self.dyna_dir'], {}), '(self.dyna_dir)\n', (3225, 3240), False, 'import os\n'), ((3907, 3929), 'os.chdir', 'os.chdir', (['self.fin_dir'], {}), '(self.fin_dir)\n', (3915, 3929), False, 'import os\n'), ((4215, 4248), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['dynParams'], {}), '(dynParams)\n', (4237, 4248), True, 'import pandas as pd\n'), ((4362, 4394), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['onparams'], {}), '(onparams)\n', (4384, 4394), True, 'import pandas as pd\n'), ((4895, 4918), 'os.chdir', 'os.chdir', (['self.dyna_dir'], {}), '(self.dyna_dir)\n', (4903, 4918), False, 'import os\n'), ((7200, 7218), 'os.chdir', 'os.chdir', (['self.cwd'], {}), '(self.cwd)\n', (7208, 7218), False, 'import os\n'), ((7227, 7249), 'os.chdir', 'os.chdir', (['self.fin_dir'], {}), '(self.fin_dir)\n', (7235, 7249), False, 'import os\n'), ((7370, 7393), 'os.chdir', 'os.chdir', (['self.dyna_dir'], {}), '(self.dyna_dir)\n', (7378, 7393), False, 'import os\n'), ((7406, 7431), 'os.path.isfile', 'os.path.isfile', (['"""DOE.csv"""'], {}), "('DOE.csv')\n", (7420, 7431), False, 'import os\n'), ((10669, 10692), 'os.chdir', 'os.chdir', (['self.basepath'], {}), '(self.basepath)\n', (10677, 10692), False, 'import os\n'), ((10704, 10721), 'qd.cae.dyna.KeyFile', 'KeyFile', (['self.key'], {}), '(self.key)\n', (10711, 10721), False, 'from qd.cae.dyna import KeyFile\n'), ((10730, 10752), 'os.chdir', 'os.chdir', (['self.fin_dir'], {}), '(self.fin_dir)\n', (10738, 10752), False, 'import os\n'), ((10825, 10854), 'numpy.array', 'np.array', (["kf['*PARAMETER'][0]"], {}), "(kf['*PARAMETER'][0])\n", (10833, 10854), True, 'import numpy as np\n'), ((11229, 11251), 'os.chdir', 'os.chdir', (['self.fin_dir'], {}), '(self.fin_dir)\n', (11237, 11251), False, 'import os\n'), ((1964, 2003), 'yaml.load', 'yaml.load', (['file'], {'Loader': 'yaml.FullLoader'}), '(file, Loader=yaml.FullLoader)\n', (1973, 2003), False, 'import yaml\n'), ((3400, 3423), 'os.mkdir', 'os.mkdir', (['self.dyna_dir'], {}), '(self.dyna_dir)\n', (3408, 3423), False, 'import os\n'), ((4007, 4046), 'yaml.load', 'yaml.load', (['file'], {'Loader': 'yaml.FullLoader'}), '(file, Loader=yaml.FullLoader)\n', (4016, 4046), False, 'import yaml\n'), ((5596, 5618), 'pandas.DataFrame', 'pd.DataFrame', (['self.DOE'], {}), '(self.DOE)\n', (5608, 5618), True, 'import pandas as pd\n'), ((5631, 5654), 'os.chdir', 'os.chdir', (['self.dyna_dir'], {}), '(self.dyna_dir)\n', (5639, 5654), False, 'import os\n'), ((7455, 7477), 'pandas.read_csv', 'pd.read_csv', (['"""DOE.csv"""'], {}), "('DOE.csv')\n", (7466, 7477), True, 'import pandas as pd\n'), ((8786, 8807), 'pandas.DataFrame', 'pd.DataFrame', (['new_DOE'], {}), '(new_DOE)\n', (8798, 8807), True, 'import pandas as pd\n'), ((8821, 8844), 'os.chdir', 'os.chdir', (['self.dyna_dir'], {}), '(self.dyna_dir)\n', (8829, 8844), False, 'import os\n'), ((8938, 8960), 'pandas.read_csv', 'pd.read_csv', (['"""DOE.csv"""'], {}), "('DOE.csv')\n", (8949, 8960), True, 'import pandas as pd\n'), ((12181, 12203), 'os.chdir', 'os.chdir', (['self.fin_dir'], {}), '(self.fin_dir)\n', (12189, 12203), False, 'import os\n'), ((2593, 2624), 'pandas.read_csv', 'pd.read_csv', (["inp['simulations']"], {}), "(inp['simulations'])\n", (2604, 2624), True, 'import pandas as pd\n'), ((3350, 3373), 'os.rmdir', 'os.rmdir', (['self.dyna_dir'], {}), '(self.dyna_dir)\n', (3358, 3373), False, 'import os\n'), ((6585, 6608), 'os.chdir', 'os.chdir', (['self.dyna_dir'], {}), '(self.dyna_dir)\n', (6593, 6608), False, 'import os\n'), ((6700, 6718), 'numpy.array', 'np.array', (['self.DOE'], {}), '(self.DOE)\n', (6708, 6718), True, 'import numpy as np\n'), ((9797, 9820), 'os.chdir', 'os.chdir', (['self.dyna_dir'], {}), '(self.dyna_dir)\n', (9805, 9820), False, 'import os\n'), ((9936, 9954), 'numpy.array', 'np.array', (['self.DOE'], {}), '(self.DOE)\n', (9944, 9954), True, 'import numpy as np\n'), ((3275, 3300), 'os.listdir', 'os.listdir', (['self.dyna_dir'], {}), '(self.dyna_dir)\n', (3285, 3300), False, 'import os\n'), ((11313, 11324), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (11322, 11324), False, 'import os\n'), ((12109, 12168), 'yaml.dump', 'yaml.dump', (['FE_Parameters', 'FE_file'], {'default_flow_style': '(False)'}), '(FE_Parameters, FE_file, default_flow_style=False)\n', (12118, 12168), False, 'import yaml\n'), ((7311, 7322), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (7320, 7322), False, 'import os\n'), ((6090, 6208), 'scipy.stats.uniform', 'uniform', (["self.dynaParameters.loc['min'][j]", "(self.dynaParameters.loc['max'][j] - self.dynaParameters.loc['min'][j])"], {}), "(self.dynaParameters.loc['min'][j], self.dynaParameters.loc['max'][j\n ] - self.dynaParameters.loc['min'][j])\n", (6097, 6208), False, 'from scipy.stats import uniform\n'), ((9236, 9354), 'scipy.stats.uniform', 'uniform', (["self.dynaParameters.loc['min'][j]", "(self.dynaParameters.loc['max'][j] - self.dynaParameters.loc['min'][j])"], {}), "(self.dynaParameters.loc['min'][j], self.dynaParameters.loc['max'][j\n ] - self.dynaParameters.loc['min'][j])\n", (9243, 9354), False, 'from scipy.stats import uniform\n'), ((6344, 6433), 'scipy.stats.distributions.norm', 'norm', ([], {'loc': "self.dynaParameters.loc['mean'][j]", 'scale': "self.dynaParameters.loc['SD'][j]"}), "(loc=self.dynaParameters.loc['mean'][j], scale=self.dynaParameters.loc[\n 'SD'][j])\n", (6348, 6433), False, 'from scipy.stats.distributions import norm\n'), ((9504, 9593), 'scipy.stats.distributions.norm', 'norm', ([], {'loc': "self.dynaParameters.loc['mean'][j]", 'scale': "self.dynaParameters.loc['SD'][j]"}), "(loc=self.dynaParameters.loc['mean'][j], scale=self.dynaParameters.loc[\n 'SD'][j])\n", (9508, 9593), False, 'from scipy.stats.distributions import norm\n')]
import numpy import scipy import matplotlib.pyplot as plt class Optimize(): def __init__(self): self.size_grid = [] self.pieces = [] self.forbidden = [] self.penalty = [] self.loss = [] input_data = (open('Problems/Problem1.txt', "r").read()).split('\n') self.size_grid = map(int, input_data[1].split(' ')) for i in range(3, input_data.index('FORBIDDEN')): self.pieces.append(input_data[i].split(' ')) for i in range(input_data.index('FORBIDDEN') + 1, input_data.index('PENALTY')): self.forbidden.append(input_data[i].split(',')) for i in range(input_data.index('PENALTY') + 1, len(input_data)-1): self.penalty.append(input_data[i].split(',')) for i in range(len(self.penalty)): self.loss.append(self.penalty[i][0].split(' ')[0]) self.loss.append(self.penalty[i][0].split(' ')[1]) def validate(self): print(self.size_grid) print(self.pieces) print(self.forbidden) print(self.loss) def grid(self): grid = numpy.zeros([self.size_grid[0], self.size_grid[1]]) print(grid) def rank(self): rank = [] obj = [] for i in range(len(self.pieces)): rank.append(self.loss.count(self.pieces[i][0])) obj.append(self.pieces[i][0]) zipped_pairs = zip(rank, obj)# fig = plt.figure() z = [x for _, x in sorted(zipped_pairs)] return z def box(self): grid = numpy.zeros([self.size_grid[0], self.size_grid[1]]) return grid def plot(self): plt.xlim(0 ,self.size_grid[0]) plt.ylim(0 ,self.size_grid[1]) plt.xticks([i for i in range(self.size_grid[0])]) plt.yticks([j for j in range(self.size_grid[1])]) plt.grid(color = 'b', linewidth = 1.5) plt.title("The visulaization of pieces arrangment") plt.show() def shape(self): piece = self.rank() print(piece) shape = [] for i in range(len(piece)): for j in range(len(self.pieces)): if piece[i]==self.pieces[j][0]: shape.append(self.pieces[i][1]) return shape if __name__ == "__main__": Optimize().plot()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.xlim", "matplotlib.pyplot.show", "matplotlib.pyplot.ylim", "numpy.zeros", "matplotlib.pyplot.grid" ]
[((1107, 1158), 'numpy.zeros', 'numpy.zeros', (['[self.size_grid[0], self.size_grid[1]]'], {}), '([self.size_grid[0], self.size_grid[1]])\n', (1118, 1158), False, 'import numpy\n'), ((1538, 1589), 'numpy.zeros', 'numpy.zeros', (['[self.size_grid[0], self.size_grid[1]]'], {}), '([self.size_grid[0], self.size_grid[1]])\n', (1549, 1589), False, 'import numpy\n'), ((1639, 1669), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', 'self.size_grid[0]'], {}), '(0, self.size_grid[0])\n', (1647, 1669), True, 'import matplotlib.pyplot as plt\n'), ((1678, 1708), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', 'self.size_grid[1]'], {}), '(0, self.size_grid[1])\n', (1686, 1708), True, 'import matplotlib.pyplot as plt\n'), ((1833, 1867), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'color': '"""b"""', 'linewidth': '(1.5)'}), "(color='b', linewidth=1.5)\n", (1841, 1867), True, 'import matplotlib.pyplot as plt\n'), ((1880, 1931), 'matplotlib.pyplot.title', 'plt.title', (['"""The visulaization of pieces arrangment"""'], {}), "('The visulaization of pieces arrangment')\n", (1889, 1931), True, 'import matplotlib.pyplot as plt\n'), ((1940, 1950), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1948, 1950), True, 'import matplotlib.pyplot as plt\n')]
from time import time import numpy as np from utils import arg_list from dgl.transforms import metis_partition from dgl import backend as F import dgl def get_partition_list(g, psize): p_gs = metis_partition(g, psize) graphs = [] for k, val in p_gs.items(): nids = val.ndata[dgl.NID] nids = F.asnumpy(nids) graphs.append(nids) return graphs def get_subgraph(g, par_arr, i, psize, batch_size): par_batch_ind_arr = [par_arr[s] for s in range( i * batch_size, (i + 1) * batch_size) if s < psize] g1 = g.subgraph(np.concatenate( par_batch_ind_arr).reshape(-1).astype(np.int64)) return g1
[ "dgl.transforms.metis_partition", "dgl.backend.asnumpy", "numpy.concatenate" ]
[((200, 225), 'dgl.transforms.metis_partition', 'metis_partition', (['g', 'psize'], {}), '(g, psize)\n', (215, 225), False, 'from dgl.transforms import metis_partition\n'), ((323, 338), 'dgl.backend.asnumpy', 'F.asnumpy', (['nids'], {}), '(nids)\n', (332, 338), True, 'from dgl import backend as F\n'), ((570, 603), 'numpy.concatenate', 'np.concatenate', (['par_batch_ind_arr'], {}), '(par_batch_ind_arr)\n', (584, 603), True, 'import numpy as np\n')]
'''Processes for surface turbulent heat and moisture fluxes :class:`~climlab.surface.SensibleHeatFlux` and :class:`~climlab.surface.LatentHeatFlux` implement standard bulk formulae for the turbulent heat fluxes, assuming that the heating or moistening occurs in the lowest atmospheric model level. :Example: Here is an example of setting up a single-column Radiative-Convective model with interactive water vapor and surface latent and sensible heat fluxes. This example also demonstrates *asynchronous coupling*: the radiation uses a longer timestep than the other model components:: import numpy as np import climlab from climlab import constants as const # Temperatures in a single column full_state = climlab.column_state(num_lev=30, water_depth=2.5) temperature_state = {'Tatm':full_state.Tatm,'Ts':full_state.Ts} # Initialize a nearly dry column (small background stratospheric humidity) q = np.ones_like(full_state.Tatm) * 5.E-6 # Add specific_humidity to the state dictionary full_state['q'] = q # ASYNCHRONOUS COUPLING -- the radiation uses a much longer timestep # The top-level model model = climlab.TimeDependentProcess(state=full_state, timestep=const.seconds_per_hour) # Radiation coupled to water vapor rad = climlab.radiation.RRTMG(state=temperature_state, specific_humidity=full_state.q, albedo=0.3, timestep=const.seconds_per_day ) # Convection scheme -- water vapor is a state variable conv = climlab.convection.EmanuelConvection(state=full_state, timestep=const.seconds_per_hour) # Surface heat flux processes shf = climlab.surface.SensibleHeatFlux(state=temperature_state, Cd=0.5E-3, timestep=const.seconds_per_hour) lhf = climlab.surface.LatentHeatFlux(state=full_state, Cd=0.5E-3, timestep=const.seconds_per_hour) # Couple all the submodels together model.add_subprocess('Radiation', rad) model.add_subprocess('Convection', conv) model.add_subprocess('SHF', shf) model.add_subprocess('LHF', lhf) print(model) # Run the model model.integrate_years(1) # Check for energy balance print(model.ASR - model.OLR) ''' from __future__ import division import numpy as np from climlab.utils.thermo import qsat from climlab import constants as const from climlab.process.energy_budget import EnergyBudget from climlab.domain.field import Field class _SurfaceFlux(EnergyBudget): '''Abstract parent class for SensibleHeatFlux and LatentHeatFlux''' def __init__(self, Cd=3E-3, resistance=1., **kwargs): super(_SurfaceFlux, self).__init__(**kwargs) self.Cd = Cd self.add_input('resistance', resistance) self.heating_rate['Tatm'] = np.zeros_like(self.Tatm) # fixed wind speed (for now) self.add_input('U', 5. * np.ones_like(self.Ts)) # retrieving surface pressure from model grid self.ps = self.lev_bounds[-1] def _compute_heating_rates(self): '''Compute energy flux convergences to get heating rates in :math:`W/m^2`.''' self._compute_flux() self.heating_rate['Ts'] = -self._flux # Modify only the lowest model level self.heating_rate['Tatm'][..., -1, np.newaxis] = self._flux def _air_density(self, Ta): return self.ps * const.mb_to_Pa / const.Rd / Ta class SensibleHeatFlux(_SurfaceFlux): r'''Surface turbulent sensible heat flux implemented through a bulk aerodynamic formula. The flux is computed from .. math:: SH = r ~ c_p ~\rho ~ C_D ~ U \left( T_s - T_a \right) where: - :math:`c_p` and :math:`\rho` are the specific heat and density of air - :math:`C_D` is a drag coefficient (stored as ``self.Cd``, default value is 3E-3) - :math:`U` is the near-surface wind speed, stored as ``self.U``, default value is 5 m/s - :math:`r` is an optional resistance parameter (stored as ``self.resistance``, default value = 1) The surface temperature :math:`T_s` is taken directly from ``self.state['Ts']``, while the near-surface air temperature :math:`T_a` is taken as the lowest model level in ``self.state['Tatm']`` Diagnostic quantity ``self.SHF`` gives the sensible heat flux in W/m2. Temperature tendencies associated with this flux are computed for ``Ts`` and for the lowest model level in ``Tatm``. All other tendencies (including air temperature tendencies at other levels) are set to zero. ''' def __init__(self, Cd=3E-3, **kwargs): super(SensibleHeatFlux, self).__init__(Cd=Cd, **kwargs) self.add_diagnostic('SHF', 0.*self.Ts) def _compute_flux(self): # this ensure same dimensions as Ts # (and use only the lowest model level) Ta = Field(self.Tatm[..., -1, np.newaxis], domain=self.Ts.domain) Ts = self.Ts DeltaT = Ts - Ta rho = self._air_density(Ta) # flux from bulk formula self._flux = self.resistance * const.cp * rho * self.Cd * self.U * DeltaT self.SHF = self._flux class LatentHeatFlux(_SurfaceFlux): r'''Surface turbulent latent heat flux implemented through a bulk aerodynamic formula. The flux is computed from .. math:: LH = r ~ L ~\rho ~ C_D ~ U \left( q_s - q_a \right) where: - :math:`L` and :math:`\rho` are the latent heat of vaporization and density of air - :math:`C_D` is a drag coefficient (stored as ``self.Cd``, default value is 3E-3) - :math:`U` is the near-surface wind speed, stored as ``self.U``, default value is 5 m/s - :math:`r` is an optional resistance parameter (stored as ``self.resistance``, default value = 1) The surface specific humidity :math:`q_s` is computed as the saturation specific humidity at the surface temperature ``self.state['Ts']`` and surface pressure ``self.ps``, while the near-surface specific humidity :math:`q_a` is taken as the lowest model level in the field ``self.q`` (which must be provided either as a state variable or as input). Two diagnostics are computed: - ``self.LHF`` gives the sensible heat flux in W/m2. - ``self.evaporation`` gives the evaporation rate in kg/m2/s (or mm/s) How the tendencies are computed depends on whether specific humidity ``q`` is a state variable (i.e. is present in ``self.state``): - If ``q`` is in ``self.state`` then the evaporation determines the specific humidity tendency ``self.tendencies['q']``. The water vapor is added to the lowest model level only. Evaporation cools the surface through the surface tendency ``self.tendencies['Ts']``. Air temperature tendencies are zero everywhere. - If ``q`` is not in ``self.state`` then we compute an equivalent air temperature tendency for the lowest model layer instead of a specific humidity tendency (i.e. the latent heat flux is applied in the same way as a sensible heat flux). This process does not apply a tendency to the surface water amount. In the absence of other water processes this implies an infinite water source at the surface (slab ocean). ''' def __init__(self, Cd=3E-3, **kwargs): super(LatentHeatFlux, self).__init__(Cd=Cd, **kwargs) self.add_diagnostic('LHF', 0.*self.Ts) self.add_diagnostic('evaporation', 0.*self.Ts) # in kg/m2/s or mm/s def _compute_flux(self): # specific humidity at lowest model level # assumes pressure is the last axis q = Field(self.q[..., -1, np.newaxis], domain=self.Ts.domain) Ta = Field(self.Tatm[..., -1, np.newaxis], domain=self.Ts.domain) qs = qsat(self.Ts, self.ps) Deltaq = Field(qs - q, domain=self.Ts.domain) rho = self._air_density(Ta) # flux from bulk formula self._flux = self.resistance * const.Lhvap * rho * self.Cd * self.U * Deltaq self.LHF[:] = self._flux # evporation rate, convert from W/m2 to kg/m2/s (or mm/s) self.evaporation[:] = self.LHF/const.Lhvap def _compute(self): '''Overides the _compute method of EnergyBudget''' tendencies = self._temperature_tendencies() if 'q' in self.state: # in a model with active water vapor, this flux should affect # water vapor tendency, NOT air temperature tendency! tendencies['Tatm'] *= 0. Pa_per_hPa = 100. air_mass_per_area = self.Tatm.domain.lev.delta[...,-1] * Pa_per_hPa / const.g specific_humidity_tendency = 0.*self.q specific_humidity_tendency[...,-1,np.newaxis] = self.LHF/const.Lhvap / air_mass_per_area tendencies['q'] = specific_humidity_tendency return tendencies
[ "climlab.domain.field.Field", "numpy.zeros_like", "climlab.utils.thermo.qsat", "numpy.ones_like" ]
[((3512, 3536), 'numpy.zeros_like', 'np.zeros_like', (['self.Tatm'], {}), '(self.Tatm)\n', (3525, 3536), True, 'import numpy as np\n'), ((5544, 5604), 'climlab.domain.field.Field', 'Field', (['self.Tatm[..., -1, np.newaxis]'], {'domain': 'self.Ts.domain'}), '(self.Tatm[..., -1, np.newaxis], domain=self.Ts.domain)\n', (5549, 5604), False, 'from climlab.domain.field import Field\n'), ((8248, 8305), 'climlab.domain.field.Field', 'Field', (['self.q[..., -1, np.newaxis]'], {'domain': 'self.Ts.domain'}), '(self.q[..., -1, np.newaxis], domain=self.Ts.domain)\n', (8253, 8305), False, 'from climlab.domain.field import Field\n'), ((8319, 8379), 'climlab.domain.field.Field', 'Field', (['self.Tatm[..., -1, np.newaxis]'], {'domain': 'self.Ts.domain'}), '(self.Tatm[..., -1, np.newaxis], domain=self.Ts.domain)\n', (8324, 8379), False, 'from climlab.domain.field import Field\n'), ((8393, 8415), 'climlab.utils.thermo.qsat', 'qsat', (['self.Ts', 'self.ps'], {}), '(self.Ts, self.ps)\n', (8397, 8415), False, 'from climlab.utils.thermo import qsat\n'), ((8433, 8469), 'climlab.domain.field.Field', 'Field', (['(qs - q)'], {'domain': 'self.Ts.domain'}), '(qs - q, domain=self.Ts.domain)\n', (8438, 8469), False, 'from climlab.domain.field import Field\n'), ((3608, 3629), 'numpy.ones_like', 'np.ones_like', (['self.Ts'], {}), '(self.Ts)\n', (3620, 3629), True, 'import numpy as np\n')]
#! /usr/bin/python # -*- coding: utf-8 -*- import os os.environ['TL_BACKEND'] = 'tensorflow' # os.environ['TL_BACKEND'] = 'mindspore' # os.environ['TL_BACKEND'] = 'paddle' # os.environ['TL_BACKEND'] = 'torch' import numpy as np from tensorlayerx.nn import Module, ModuleList, Linear, ModuleDict import tensorlayerx as tlx ####################### Holds submodules in a list ######################################## d1 = Linear(out_features=800, act=tlx.nn.ReLU, in_features=784, name='linear1') d2 = Linear(out_features=800, act=tlx.nn.ReLU, in_features=800, name='linear2') d3 = Linear(out_features=10, act=tlx.nn.ReLU, in_features=800, name='linear3') layer_list = ModuleList([d1, d2]) # Inserts a given d2 before a given index in the list layer_list.insert(1, d2) layer_list.insert(2, d2) # Appends d2 from a Python iterable to the end of the list. layer_list.extend([d2]) # Appends a given d3 to the end of the list. layer_list.append(d3) print(layer_list) class model(Module): def __init__(self): super(model, self).__init__() self._list = layer_list def forward(self, inputs): output = self._list[0](inputs) for i in range(1, len(self._list)): output = self._list[i](output) return output net = model() print(net.trainable_weights) print(net) print(net(tlx.nn.Input((10, 784)))) ####################### Holds submodules in a Dict ######################################## class MyModule(Module): def __init__(self): super(MyModule, self).__init__() self.dict = ModuleDict({ 'linear1': Linear(out_features=800, act=tlx.nn.ReLU, in_features=784, name='linear1'), 'linear2': Linear(out_features=800, act=tlx.nn.ReLU, in_features=800, name='linear2') }) def forward(self, x, linear): x = self.dict[linear](x) return x x = tlx.convert_to_tensor(np.ones(shape=(1,784)), dtype=tlx.float32) net = MyModule() x = net(x, 'linear1') print(x)
[ "tensorlayerx.nn.ModuleList", "tensorlayerx.nn.Linear", "numpy.ones", "tensorlayerx.nn.Input" ]
[((423, 497), 'tensorlayerx.nn.Linear', 'Linear', ([], {'out_features': '(800)', 'act': 'tlx.nn.ReLU', 'in_features': '(784)', 'name': '"""linear1"""'}), "(out_features=800, act=tlx.nn.ReLU, in_features=784, name='linear1')\n", (429, 497), False, 'from tensorlayerx.nn import Module, ModuleList, Linear, ModuleDict\n'), ((503, 577), 'tensorlayerx.nn.Linear', 'Linear', ([], {'out_features': '(800)', 'act': 'tlx.nn.ReLU', 'in_features': '(800)', 'name': '"""linear2"""'}), "(out_features=800, act=tlx.nn.ReLU, in_features=800, name='linear2')\n", (509, 577), False, 'from tensorlayerx.nn import Module, ModuleList, Linear, ModuleDict\n'), ((583, 656), 'tensorlayerx.nn.Linear', 'Linear', ([], {'out_features': '(10)', 'act': 'tlx.nn.ReLU', 'in_features': '(800)', 'name': '"""linear3"""'}), "(out_features=10, act=tlx.nn.ReLU, in_features=800, name='linear3')\n", (589, 656), False, 'from tensorlayerx.nn import Module, ModuleList, Linear, ModuleDict\n'), ((671, 691), 'tensorlayerx.nn.ModuleList', 'ModuleList', (['[d1, d2]'], {}), '([d1, d2])\n', (681, 691), False, 'from tensorlayerx.nn import Module, ModuleList, Linear, ModuleDict\n'), ((1906, 1929), 'numpy.ones', 'np.ones', ([], {'shape': '(1, 784)'}), '(shape=(1, 784))\n', (1913, 1929), True, 'import numpy as np\n'), ((1330, 1353), 'tensorlayerx.nn.Input', 'tlx.nn.Input', (['(10, 784)'], {}), '((10, 784))\n', (1342, 1353), True, 'import tensorlayerx as tlx\n'), ((1599, 1673), 'tensorlayerx.nn.Linear', 'Linear', ([], {'out_features': '(800)', 'act': 'tlx.nn.ReLU', 'in_features': '(784)', 'name': '"""linear1"""'}), "(out_features=800, act=tlx.nn.ReLU, in_features=784, name='linear1')\n", (1605, 1673), False, 'from tensorlayerx.nn import Module, ModuleList, Linear, ModuleDict\n'), ((1702, 1776), 'tensorlayerx.nn.Linear', 'Linear', ([], {'out_features': '(800)', 'act': 'tlx.nn.ReLU', 'in_features': '(800)', 'name': '"""linear2"""'}), "(out_features=800, act=tlx.nn.ReLU, in_features=800, name='linear2')\n", (1708, 1776), False, 'from tensorlayerx.nn import Module, ModuleList, Linear, ModuleDict\n')]
# -*- coding: utf-8 -*- """ Created on Sat Jun 6 21:34:08 2020 @author: Dipankar """ # -*- coding: utf-8 -*- """ Created on Sat Jun 6 17:24:34 2020 @author: Dipankar """ import numpy as np import matplotlib.pyplot as plt import matplotlib # a = np.arange(0,9,0.1) x1 = np.linspace(0.01,4.5,100) thr = 31*np.pi/180; ## Model parameters for Pd iS-O model #a = 0.40122218 #b = -0.43592192 #c = -0.06592063 #e = 0.84668574 #f = 0.28204715 a = 0.40304; b = -0.835837; c = -0.03657; e = 0.50666; f = 0.20754; ## Model parameters Ps iS-O model b1 = 0.12403 d1 = -0.3952 e1 = 0.01388 f1 = 0.676 #b1 = 0.30580876; #d1 = -0.1251497149; #e1 = 0.012258803; #f1 = 0.615; ## Model parameters Pv iS-O model #a2 = 0.61624; #b2 = 0.3143 #0.91169045; #c2 = 0.3343; #0.06829466; #d2 = 0.28659; #0.21571469; a2=2.55455746 b2=-0.3198832 c2=0.04291485 d2=0.3707592 for i in x1: ## Pd IS-O model yd=(a*1.0*np.exp((-2)*f*x1/np.cos(thr))*((b*(1-np.exp((-1)*c*x1)))+(e*(0.035*np.power(x1,2.824))))); yddb = 10*np.log10(yd) ## Ps iS-O model ys = (np.power(b1,x1)*(0.035*np.power(x1,2.824))*np.exp((-2)*d1*x1/np.cos(thr)))+(e1*1.0*np.exp((-2)*d1*x1/np.cos(thr))*np.exp((-2)*f1*(0.035*np.power(x1,2.824))/np.cos(thr))) ysdb = 10*np.log10(ys) ## Pv iS-O model yv = (1-a2)*b2*(1-np.exp((-1)*c2*x1/0.5))*np.cos(thr)*(1-np.exp((-2)*d2*x1/np.cos(thr))); yvdb = 10*np.log10(yv) fig, ax = plt.subplots(figsize=(5, 5)) plt.plot(x1,yddb,color='#FA7805',linewidth=2.5) plt.xlim([0,4.5]) plt.ylim([-35, 0]) #fig, ax = plt.subplots(figsize=(5, 5)) ### RH simulation plots #plt.xlim([0, 9]) #plt.ylim([-35, 0]) plt.plot(x1,ysdb,color="#3361FF",linewidth=2.5) plt.plot(x1,yvdb,color="#2BEC14",linewidth=2.5) #plt.plot(x1,yhsoildb) #plt.plot(x1,yhvegdb) plt.xlabel("PAI ($m^{2}~m^{-2}$)") plt.ylabel("$m-\chi$ powers (dB) ") #plt.title("RH-Rice") plt.xticks(np.arange(0, 4.5+0.5,1.5)) matplotlib.rcParams.update({'font.size': 24}) plt.savefig('mchiCal.png',bbox_inches="tight",dpi=100) plt.show() plt.close()
[ "matplotlib.pyplot.xlim", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.ylim", "matplotlib.pyplot.close", "matplotlib.rcParams.update", "numpy.power", "numpy.arange", "numpy.exp", "numpy.linspace", "numpy.cos", "matplotlib.pyplot.ylabel", "numpy.log10", "matplotlib...
[((276, 303), 'numpy.linspace', 'np.linspace', (['(0.01)', '(4.5)', '(100)'], {}), '(0.01, 4.5, 100)\n', (287, 303), True, 'import numpy as np\n'), ((1441, 1469), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(5, 5)'}), '(figsize=(5, 5))\n', (1453, 1469), True, 'import matplotlib.pyplot as plt\n'), ((1474, 1524), 'matplotlib.pyplot.plot', 'plt.plot', (['x1', 'yddb'], {'color': '"""#FA7805"""', 'linewidth': '(2.5)'}), "(x1, yddb, color='#FA7805', linewidth=2.5)\n", (1482, 1524), True, 'import matplotlib.pyplot as plt\n'), ((1522, 1540), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0, 4.5]'], {}), '([0, 4.5])\n', (1530, 1540), True, 'import matplotlib.pyplot as plt\n'), ((1540, 1558), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[-35, 0]'], {}), '([-35, 0])\n', (1548, 1558), True, 'import matplotlib.pyplot as plt\n'), ((1671, 1721), 'matplotlib.pyplot.plot', 'plt.plot', (['x1', 'ysdb'], {'color': '"""#3361FF"""', 'linewidth': '(2.5)'}), "(x1, ysdb, color='#3361FF', linewidth=2.5)\n", (1679, 1721), True, 'import matplotlib.pyplot as plt\n'), ((1721, 1771), 'matplotlib.pyplot.plot', 'plt.plot', (['x1', 'yvdb'], {'color': '"""#2BEC14"""', 'linewidth': '(2.5)'}), "(x1, yvdb, color='#2BEC14', linewidth=2.5)\n", (1729, 1771), True, 'import matplotlib.pyplot as plt\n'), ((1819, 1853), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""PAI ($m^{2}~m^{-2}$)"""'], {}), "('PAI ($m^{2}~m^{-2}$)')\n", (1829, 1853), True, 'import matplotlib.pyplot as plt\n'), ((1854, 1890), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$m-\\\\chi$ powers (dB) """'], {}), "('$m-\\\\chi$ powers (dB) ')\n", (1864, 1890), True, 'import matplotlib.pyplot as plt\n'), ((1950, 1995), 'matplotlib.rcParams.update', 'matplotlib.rcParams.update', (["{'font.size': 24}"], {}), "({'font.size': 24})\n", (1976, 1995), False, 'import matplotlib\n'), ((1996, 2052), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""mchiCal.png"""'], {'bbox_inches': '"""tight"""', 'dpi': '(100)'}), "('mchiCal.png', bbox_inches='tight', dpi=100)\n", (2007, 2052), True, 'import matplotlib.pyplot as plt\n'), ((2051, 2061), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2059, 2061), True, 'import matplotlib.pyplot as plt\n'), ((2062, 2073), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2071, 2073), True, 'import matplotlib.pyplot as plt\n'), ((1923, 1951), 'numpy.arange', 'np.arange', (['(0)', '(4.5 + 0.5)', '(1.5)'], {}), '(0, 4.5 + 0.5, 1.5)\n', (1932, 1951), True, 'import numpy as np\n'), ((1046, 1058), 'numpy.log10', 'np.log10', (['yd'], {}), '(yd)\n', (1054, 1058), True, 'import numpy as np\n'), ((1274, 1286), 'numpy.log10', 'np.log10', (['ys'], {}), '(ys)\n', (1282, 1286), True, 'import numpy as np\n'), ((1416, 1428), 'numpy.log10', 'np.log10', (['yv'], {}), '(yv)\n', (1424, 1428), True, 'import numpy as np\n'), ((1354, 1365), 'numpy.cos', 'np.cos', (['thr'], {}), '(thr)\n', (1360, 1365), True, 'import numpy as np\n'), ((1090, 1106), 'numpy.power', 'np.power', (['b1', 'x1'], {}), '(b1, x1)\n', (1098, 1106), True, 'import numpy as np\n'), ((958, 969), 'numpy.cos', 'np.cos', (['thr'], {}), '(thr)\n', (964, 969), True, 'import numpy as np\n'), ((978, 997), 'numpy.exp', 'np.exp', (['(-1 * c * x1)'], {}), '(-1 * c * x1)\n', (984, 997), True, 'import numpy as np\n'), ((1008, 1027), 'numpy.power', 'np.power', (['x1', '(2.824)'], {}), '(x1, 2.824)\n', (1016, 1027), True, 'import numpy as np\n'), ((1113, 1132), 'numpy.power', 'np.power', (['x1', '(2.824)'], {}), '(x1, 2.824)\n', (1121, 1132), True, 'import numpy as np\n'), ((1151, 1162), 'numpy.cos', 'np.cos', (['thr'], {}), '(thr)\n', (1157, 1162), True, 'import numpy as np\n'), ((1246, 1257), 'numpy.cos', 'np.cos', (['thr'], {}), '(thr)\n', (1252, 1257), True, 'import numpy as np\n'), ((1330, 1356), 'numpy.exp', 'np.exp', (['(-1 * c2 * x1 / 0.5)'], {}), '(-1 * c2 * x1 / 0.5)\n', (1336, 1356), True, 'import numpy as np\n'), ((1387, 1398), 'numpy.cos', 'np.cos', (['thr'], {}), '(thr)\n', (1393, 1398), True, 'import numpy as np\n'), ((1191, 1202), 'numpy.cos', 'np.cos', (['thr'], {}), '(thr)\n', (1197, 1202), True, 'import numpy as np\n'), ((1226, 1245), 'numpy.power', 'np.power', (['x1', '(2.824)'], {}), '(x1, 2.824)\n', (1234, 1245), True, 'import numpy as np\n')]
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # File : rng.py # Author : <NAME> # Email : <EMAIL> # Date : 01/19/2018 # # This file is part of Jacinle. # Distributed under terms of the MIT license. import os import random as sys_random import numpy as np import numpy.random as npr from jacinle.utils.defaults import defaults_manager from jacinle.utils.registry import Registry __all__ = ['JacRandomState', 'get_default_rng', 'gen_seed', 'gen_rng', 'reset_global_seed'] class JacRandomState(npr.RandomState): def choice_list(self, list_, size=1, replace=False, p=None): """Efficiently draw an element from an list, if the rng is given, use it instead of the system one.""" if size == 1: if type(list_) in (list, tuple): return list_[self.choice(len(list_), p=p)] return self.choice(list_, p=p) else: if type(list_) in (list, tuple): inds = self.choice(len(list_), size=size, replace=replace, p=p) return [list_[i] for i in inds] return self.choice(list_, size=size, replace=replace, p=p) def shuffle_list(self, list_): if type(list_) is list: sys_random.shuffle(list_, random=self.random_sample) else: self.shuffle(list_) def shuffle_multi(self, *arrs): length = len(arrs[0]) for a in arrs: assert len(a) == length, 'non-compatible length when shuffling multiple arrays' inds = np.arange(length) self.shuffle(inds) return tuple(map(lambda x: x[inds], arrs)) @defaults_manager.wrap_custom_as_default(is_local=True) def as_default(self): yield self _rng = JacRandomState() get_default_rng = defaults_manager.gen_get_default(JacRandomState, default_getter=lambda: _rng) def gen_seed(): return get_default_rng().randint(4294967296) def gen_rng(seed=None): return JacRandomState(seed) global_rng_registry = Registry() global_rng_registry.register('jacinle', lambda: _rng.seed) global_rng_registry.register('numpy', lambda: npr.seed) global_rng_registry.register('sys', lambda: sys_random.seed) def reset_global_seed(seed=None, verbose=False): if seed is None: seed = gen_seed() for k, seed_getter in global_rng_registry.items(): if verbose: from jacinle.logging import get_logger logger = get_logger(__file__) logger.critical('Reset random seed for: {} (pid={}, seed={}).'.format(k, os.getpid(), seed)) seed_getter()(seed) def _initialize_global_seed(): seed = os.getenv('JAC_RANDOM_SEED', None) if seed is not None: reset_global_seed(seed) _initialize_global_seed()
[ "jacinle.utils.defaults.defaults_manager.gen_get_default", "os.getpid", "random.shuffle", "jacinle.utils.registry.Registry", "numpy.arange", "jacinle.logging.get_logger", "jacinle.utils.defaults.defaults_manager.wrap_custom_as_default", "os.getenv" ]
[((1750, 1828), 'jacinle.utils.defaults.defaults_manager.gen_get_default', 'defaults_manager.gen_get_default', (['JacRandomState'], {'default_getter': '(lambda : _rng)'}), '(JacRandomState, default_getter=lambda : _rng)\n', (1782, 1828), False, 'from jacinle.utils.defaults import defaults_manager\n'), ((1977, 1987), 'jacinle.utils.registry.Registry', 'Registry', ([], {}), '()\n', (1985, 1987), False, 'from jacinle.utils.registry import Registry\n'), ((1604, 1658), 'jacinle.utils.defaults.defaults_manager.wrap_custom_as_default', 'defaults_manager.wrap_custom_as_default', ([], {'is_local': '(True)'}), '(is_local=True)\n', (1643, 1658), False, 'from jacinle.utils.defaults import defaults_manager\n'), ((2607, 2641), 'os.getenv', 'os.getenv', (['"""JAC_RANDOM_SEED"""', 'None'], {}), "('JAC_RANDOM_SEED', None)\n", (2616, 2641), False, 'import os\n'), ((1502, 1519), 'numpy.arange', 'np.arange', (['length'], {}), '(length)\n', (1511, 1519), True, 'import numpy as np\n'), ((1205, 1257), 'random.shuffle', 'sys_random.shuffle', (['list_'], {'random': 'self.random_sample'}), '(list_, random=self.random_sample)\n', (1223, 1257), True, 'import random as sys_random\n'), ((2409, 2429), 'jacinle.logging.get_logger', 'get_logger', (['__file__'], {}), '(__file__)\n', (2419, 2429), False, 'from jacinle.logging import get_logger\n'), ((2515, 2526), 'os.getpid', 'os.getpid', ([], {}), '()\n', (2524, 2526), False, 'import os\n')]
#%% import os import sys try: os.chdir('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/') sys.path.append('/Volumes/GoogleDrive/My Drive/python_code/maggot_models/') sys.path.append('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/') except: pass import pymaid as pymaid from pymaid_creds import url, name, password, token rm = pymaid.CatmaidInstance(url, token, name, password) import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np import connectome_tools.process_matrix as pm from graspy.plot import gridplot, heatmap from graspy.utils import binarize, pass_to_ranks from src.data import load_metagraph from src.visualization import CLASS_COLOR_DICT, adjplot # allows text to be editable in Illustrator plt.rcParams['pdf.fonttype'] = 42 plt.rcParams['ps.fonttype'] = 42 # font settings plt.rcParams['font.size'] = 5 plt.rcParams['font.family'] = 'arial' sns.set_context("talk") mg_ad = load_metagraph("Gad", version="2020-04-23", path = '/Volumes/GoogleDrive/My Drive/python_code/maggot_models/data/processed/') mg_ad.calculate_degrees(inplace=True) adj = pd.read_csv('VNC_interaction/data/brA1_axon-dendrite.csv', header = 0, index_col = 0) adj.columns = adj.columns.astype(int) #convert column names to int for easier indexing # remove A1 except for ascendings A1_ascending = pymaid.get_skids_by_annotation('mw A1 neurons paired ascending') A1 = pymaid.get_skids_by_annotation('mw A1 neurons paired') A1_local = list(np.setdiff1d(A1, A1_ascending)) # all A1 without A1_ascending pruned_index = list(np.setdiff1d(adj.index, A1_local)) adj = adj.loc[pruned_index, pruned_index] # remove all local A1 skids from adjacency matrix # load inputs and pair data inputs = pd.read_csv('VNC_interaction/data/brA1_input_counts.csv', index_col = 0) inputs = pd.DataFrame(inputs.values, index = inputs.index, columns = ['axon_input', 'dendrite_input']) pairs = pd.read_csv('VNC_interaction/data/pairs-2020-10-26.csv', header = 0) # import pairs pairs.drop(1121, inplace=True) # remove duplicate rightid # load cluster data clusters = pd.read_csv('cascades/data/meta-method=color_iso-d=8-bic_ratio=0.95-min_split=32.csv', index_col = 0, header = 0) # separate meta file with median_node_visits from sensory for each node # determined using iterative random walks meta_with_order = pd.read_csv('data/meta_data_w_order.csv', index_col = 0, header = 0) def cluster_order(lvl_label_str, meta_with_order): lvl = clusters.groupby(lvl_label_str) order_df = [] skids_df = [] for key in lvl.groups: skids = lvl.groups[key] node_visits = meta_with_order.loc[skids, :].median_node_visits order_df.append([key, np.nanmean(node_visits)]) skids_df.append([x for x in zip(skids, [key]*len(skids))]) order_df = pd.DataFrame(order_df, columns = ['cluster', 'node_visit_order']) order_df = order_df.sort_values(by = 'node_visit_order') skids_df = pd.DataFrame([x for sublist in skids_df for x in sublist], columns = ['skid', 'cluster']) skids_df = skids_df.set_index('cluster', drop=False)#.loc[order_7] skids_df.index = range(0, len(skids_df.index)) return(lvl, list(order_df.cluster), skids_df) lvl7, order_7, skids_lvl7 = cluster_order('lvl7_labels', meta_with_order) # %% # order adj properly left = pymaid.get_skids_by_annotation('mw left') right = pymaid.get_skids_by_annotation('mw right') br_neurons = pymaid.get_skids_by_annotation('mw brain neurons') ipsi = list(np.intersect1d(pymaid.get_skids_by_annotation('mw ipsilateral axon'), adj.index)) bilateral = list(np.intersect1d(pymaid.get_skids_by_annotation('mw bilateral axon'), adj.index)) contra = list(np.intersect1d(pymaid.get_skids_by_annotation('mw contralateral axon'), adj.index)) ipsi_left = list(np.intersect1d(ipsi, left)) bilateral_left = list(np.intersect1d(bilateral, left)) contra_left = list(np.intersect1d(contra, left)) ipsi_right = list(np.intersect1d(ipsi, right)) bilateral_right = list(np.intersect1d(bilateral, right)) contra_right = list(np.intersect1d(contra, right)) adj = adj.loc[ipsi_left + bilateral_left + contra_left + contra_right + bilateral_right + ipsi_right, ipsi_left + bilateral_left + contra_left + contra_right + bilateral_right + ipsi_right] meta_test = [] for i in range(len(adj.index)): if(adj.index[i] in br_neurons): meta_test.append(True) if(adj.index[i] not in br_neurons): meta_test.append(False) meta = pd.DataFrame([True]*len(adj.index), columns = ['brain_neurons'], index = adj.index) cell_type = [] for i in range(len(adj.index)): if(adj.index[i] in ipsi_left): cell_type.append('1_ipsi') if(adj.index[i] in bilateral_left): cell_type.append('2_bilateral') if(adj.index[i] in contra_left): cell_type.append('3_contra') if(adj.index[i] in ipsi_right): cell_type.append('6_ipsi') if(adj.index[i] in bilateral_right): cell_type.append('5_bilateral') if(adj.index[i] in contra_right): cell_type.append('4_contra') meta['class'] = cell_type cluster_type = [] for i in range(len(adj.index)): cluster_id = skids_lvl7[skids_lvl7.skid==adj.index[i]].cluster.values if(len(cluster_id)==1): cluster_type.append(cluster_id[0]) if(len(cluster_id)==0): cluster_type.append('unknown') meta['cluster'] = cluster_type hemisphere_type = [] for i in range(len(adj.index)): if(adj.index[i] in left): hemisphere_type.append('L') if(adj.index[i] in right): hemisphere_type.append('R') meta['hemisphere'] = hemisphere_type pair_id = [] for skid in meta.index: if(meta.loc[skid].hemisphere=='L'): pair_id.append(skid) if((meta.loc[skid].hemisphere=='R') & (skid in (list(pairs.leftid) + list(pairs.rightid)))): pair_id.append(pm.Promat.identify_pair(skid, pairs)) if((meta.loc[skid].hemisphere=='R') & (skid not in (list(pairs.leftid) + list(pairs.rightid)))): pair_id.append(skid) meta['pair_id'] = pair_id # %% # fig, ax = plt.subplots(1, 1, figsize=(15, 15)) test = adjplot( adj.values, meta=meta, plot_type="scattermap", # plot dots instead of a heatmap sizes=(1, 1), # min and max sizes for dots, so this is effectively binarizing item_order=['pair_id'], # order by pairs (some have no pair here so don't look same) ax=ax, ) plt.savefig('interhemisphere/plots/raw_adj_matrix.pdf', bbox_inches='tight') fig, ax = plt.subplots(1, 1, figsize=(15, 15)) test = adjplot( adj.values, meta=meta, sort_class='class', # group by hemisphere, this is a key for column in "meta" plot_type="scattermap", # plot dots instead of a heatmap sizes=(1, 1), # min and max sizes for dots, so this is effectively binarizing item_order=['cluster', 'pair_id'], # order by pairs (some have no pair here so don't look same) ax=ax, ) plt.savefig('interhemisphere/plots/adj_matrix_sorted-class-cluster-pair.pdf', bbox_inches='tight') fig, ax = plt.subplots(1, 1, figsize=(15, 15)) test = adjplot( adj.values, meta=meta, sort_class='cluster', # group by hemisphere, this is a key for column in "meta" plot_type="scattermap", # plot dots instead of a heatmap sizes=(1, 1), # min and max sizes for dots, so this is effectively binarizing item_order=['class', 'pair_id'], # order by pairs (some have no pair here so don't look same) ax=ax, ) plt.savefig('interhemisphere/plots/adj_matrix_sorted-cluster-class-pair.pdf', bbox_inches='tight') fig, ax = plt.subplots(1, 1, figsize=(15, 15)) test = adjplot( adj.values, meta=meta, sort_class='class', # group by hemisphere, this is a key for column in "meta" plot_type="scattermap", # plot dots instead of a heatmap sizes=(1, 1), # min and max sizes for dots, so this is effectively binarizing item_order=['pair_id'], # order by pairs (some have no pair here so don't look same) ax=ax, ) plt.savefig('interhemisphere/plots/adj_matrix_sorted-class-pair.pdf', bbox_inches='tight') # %% # # load previously generated paths all_edges_combined = pd.read_csv('interhemisphere/csv/all_paired_edges.csv', index_col=0) left = pymaid.get_skids_by_annotation('mw left') right = pymaid.get_skids_by_annotation('mw right') all_edges_combined_split = [] for i in range(len(all_edges_combined.index)): row = all_edges_combined.iloc[i] if((row.upstream_status=='paired') & (row.downstream_status=='paired')): if(row.type=='ipsilateral'): all_edges_combined_split.append([row.upstream_pair_id, row.downstream_pair_id, 'left', 'left', row.left, row.type, row.upstream_status, row.downstream_status]) all_edges_combined_split.append([pm.Promat.identify_pair(row.upstream_pair_id, pairs), pm.Promat.identify_pair(row.downstream_pair_id, pairs), 'right', 'right', row.right, row.type, row.upstream_status, row.downstream_status]) if(row.type=='contralateral'): all_edges_combined_split.append([row.upstream_pair_id, pm.Promat.identify_pair(row.downstream_pair_id, pairs), 'left', 'right', row.left, row.type, row.upstream_status, row.downstream_status]) all_edges_combined_split.append([pm.Promat.identify_pair(row.upstream_pair_id, pairs), row.downstream_pair_id, 'right', 'left', row.right, row.type, row.upstream_status, row.downstream_status]) if((row.upstream_status=='nonpaired') & (row.downstream_status=='paired')): if(row.upstream_pair_id in left): if(row.type=='ipsilateral'): all_edges_combined_split.append([row.upstream_pair_id, row.downstream_pair_id, 'left', 'left', row.left, row.type, row.upstream_status, row.downstream_status]) if(row.type=='contralateral'): all_edges_combined_split.append([row.upstream_pair_id, pm.Promat.identify_pair(row.downstream_pair_id, pairs), 'left', 'right', row.right, row.type, row.upstream_status, row.downstream_status]) if(row.upstream_pair_id in right): if(row.type=='ipsilateral'): all_edges_combined_split.append([row.upstream_pair_id, pm.Promat.identify_pair(row.downstream_pair_id, pairs), 'right', 'right', row.right, row.type, row.upstream_status, row.downstream_status]) if(row.type=='contralateral'): all_edges_combined_split.append([row.upstream_pair_id, row.downstream_pair_id, 'right', 'left', row.right, row.type, row.upstream_status, row.downstream_status]) if((row.upstream_status=='paired') & (row.downstream_status=='nonpaired')): if(row.downstream_pair_id in left): if(row.type=='ipsilateral'): all_edges_combined_split.append([row.upstream_pair_id, row.downstream_pair_id, 'left', 'left', row.left, row.type, row.upstream_status, row.downstream_status]) if(row.type=='contralateral'): all_edges_combined_split.append([pm.Promat.identify_pair(row.upstream_pair_id, pairs), row.downstream_pair_id, 'right', 'left', row.right, row.type, row.upstream_status, row.downstream_status]) if(row.downstream_pair_id in right): if(row.type=='ipsilateral'): all_edges_combined_split.append([pm.Promat.identify_pair(row.upstream_pair_id, pairs), row.downstream_pair_id, 'right', 'right', row.right, row.type, row.upstream_status, row.downstream_status]) if(row.type=='contralateral'): all_edges_combined_split.append([row.upstream_pair_id, row.downstream_pair_id, 'left', 'right', row.left, row.type, row.upstream_status, row.downstream_status]) #if((row.upstream_status=='nonpaired') & (row.downstream_status=='nonpaired')): all_edges_combined_split = pd.DataFrame(all_edges_combined_split, columns = ['upstream_pair_id', 'downstream_pair_id', 'upstream_side', 'downstream_side', 'edge_weight', 'type', 'upstream_status', 'downstream_status']) # %% # order matrix immature = pymaid.get_skids_by_annotation('mw brain few synapses') ipsi = list(np.intersect1d(pymaid.get_skids_by_annotation('mw ipsilateral axon'), adj.index)) bilateral = list(np.intersect1d(pymaid.get_skids_by_annotation('mw bilateral axon'), adj.index)) contra = list(np.intersect1d(pymaid.get_skids_by_annotation('mw contralateral axon'), adj.index)) ipsi = list(np.setdiff1d(ipsi, immature)) bilateral = list(np.setdiff1d(bilateral, immature)) contra = list(np.setdiff1d(contra, immature)) ipsi_pairs = pm.Promat.extract_pairs_from_list(ipsi, pairs) bilateral_pairs = pm.Promat.extract_pairs_from_list(bilateral, pairs) contra_pairs = pm.Promat.extract_pairs_from_list(contra, pairs) ipsi_order_left = list(ipsi_pairs[0].leftid) + list(np.intersect1d(ipsi_pairs[2].nonpaired, left)) ipsi_order_right = list(ipsi_pairs[0].rightid) + list(np.intersect1d(ipsi_pairs[2].nonpaired, right)) bilateral_order_left = list(bilateral_pairs[0].leftid) + list(np.intersect1d(bilateral_pairs[2].nonpaired, left)) bilateral_order_right = list(bilateral_pairs[0].rightid) + list(np.intersect1d(bilateral_pairs[2].nonpaired, right)) contra_order_left = list(contra_pairs[0].leftid) + list(np.intersect1d(contra_pairs[2].nonpaired, left)) contra_order_right = list(contra_pairs[0].rightid) + list(np.intersect1d(contra_pairs[2].nonpaired, right)) contra_order_right.reverse() bilateral_order_right.reverse() ipsi_order_right.reverse() order = ipsi_order_left + bilateral_order_left + contra_order_left + contra_order_right + bilateral_order_right + ipsi_order_right adj = adj.loc[order, order] meta_test = pd.DataFrame([True]*len(adj.index), columns = ['brain_neurons'], index = adj.index) # %% # fig, ax = plt.subplots(1, 1, figsize=(15, 15)) adjplot( adj.values, meta=meta_test, sort_class=None, # group by hemisphere, this is a key for column in "meta" plot_type="scattermap", # plot dots instead of a heatmap sizes=(0.5, 3), # min and max sizes for dots, so this is effectively binarizing item_order=None, # order by pairs (some have no pair here so don't look same) ax=ax, ) # %%
[ "pandas.DataFrame", "sys.path.append", "pymaid.CatmaidInstance", "pandas.read_csv", "numpy.setdiff1d", "pymaid.get_skids_by_annotation", "src.data.load_metagraph", "connectome_tools.process_matrix.Promat.identify_pair", "src.visualization.adjplot", "numpy.nanmean", "os.chdir", "numpy.intersect...
[((368, 418), 'pymaid.CatmaidInstance', 'pymaid.CatmaidInstance', (['url', 'token', 'name', 'password'], {}), '(url, token, name, password)\n', (390, 418), True, 'import pymaid as pymaid\n'), ((939, 962), 'seaborn.set_context', 'sns.set_context', (['"""talk"""'], {}), "('talk')\n", (954, 962), True, 'import seaborn as sns\n'), ((972, 1100), 'src.data.load_metagraph', 'load_metagraph', (['"""Gad"""'], {'version': '"""2020-04-23"""', 'path': '"""/Volumes/GoogleDrive/My Drive/python_code/maggot_models/data/processed/"""'}), "('Gad', version='2020-04-23', path=\n '/Volumes/GoogleDrive/My Drive/python_code/maggot_models/data/processed/')\n", (986, 1100), False, 'from src.data import load_metagraph\n'), ((1143, 1228), 'pandas.read_csv', 'pd.read_csv', (['"""VNC_interaction/data/brA1_axon-dendrite.csv"""'], {'header': '(0)', 'index_col': '(0)'}), "('VNC_interaction/data/brA1_axon-dendrite.csv', header=0,\n index_col=0)\n", (1154, 1228), True, 'import pandas as pd\n'), ((1366, 1430), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw A1 neurons paired ascending"""'], {}), "('mw A1 neurons paired ascending')\n", (1396, 1430), True, 'import pymaid as pymaid\n'), ((1436, 1490), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw A1 neurons paired"""'], {}), "('mw A1 neurons paired')\n", (1466, 1490), True, 'import pymaid as pymaid\n'), ((1755, 1825), 'pandas.read_csv', 'pd.read_csv', (['"""VNC_interaction/data/brA1_input_counts.csv"""'], {'index_col': '(0)'}), "('VNC_interaction/data/brA1_input_counts.csv', index_col=0)\n", (1766, 1825), True, 'import pandas as pd\n'), ((1837, 1930), 'pandas.DataFrame', 'pd.DataFrame', (['inputs.values'], {'index': 'inputs.index', 'columns': "['axon_input', 'dendrite_input']"}), "(inputs.values, index=inputs.index, columns=['axon_input',\n 'dendrite_input'])\n", (1849, 1930), True, 'import pandas as pd\n'), ((1939, 2005), 'pandas.read_csv', 'pd.read_csv', (['"""VNC_interaction/data/pairs-2020-10-26.csv"""'], {'header': '(0)'}), "('VNC_interaction/data/pairs-2020-10-26.csv', header=0)\n", (1950, 2005), True, 'import pandas as pd\n'), ((2113, 2231), 'pandas.read_csv', 'pd.read_csv', (['"""cascades/data/meta-method=color_iso-d=8-bic_ratio=0.95-min_split=32.csv"""'], {'index_col': '(0)', 'header': '(0)'}), "(\n 'cascades/data/meta-method=color_iso-d=8-bic_ratio=0.95-min_split=32.csv',\n index_col=0, header=0)\n", (2124, 2231), True, 'import pandas as pd\n'), ((2360, 2424), 'pandas.read_csv', 'pd.read_csv', (['"""data/meta_data_w_order.csv"""'], {'index_col': '(0)', 'header': '(0)'}), "('data/meta_data_w_order.csv', index_col=0, header=0)\n", (2371, 2424), True, 'import pandas as pd\n'), ((3344, 3385), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw left"""'], {}), "('mw left')\n", (3374, 3385), True, 'import pymaid as pymaid\n'), ((3394, 3436), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw right"""'], {}), "('mw right')\n", (3424, 3436), True, 'import pymaid as pymaid\n'), ((3450, 3500), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw brain neurons"""'], {}), "('mw brain neurons')\n", (3480, 3500), True, 'import pymaid as pymaid\n'), ((6054, 6090), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(15, 15)'}), '(1, 1, figsize=(15, 15))\n', (6066, 6090), True, 'import matplotlib.pyplot as plt\n'), ((6098, 6201), 'src.visualization.adjplot', 'adjplot', (['adj.values'], {'meta': 'meta', 'plot_type': '"""scattermap"""', 'sizes': '(1, 1)', 'item_order': "['pair_id']", 'ax': 'ax'}), "(adj.values, meta=meta, plot_type='scattermap', sizes=(1, 1),\n item_order=['pair_id'], ax=ax)\n", (6105, 6201), False, 'from src.visualization import CLASS_COLOR_DICT, adjplot\n'), ((6388, 6464), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""interhemisphere/plots/raw_adj_matrix.pdf"""'], {'bbox_inches': '"""tight"""'}), "('interhemisphere/plots/raw_adj_matrix.pdf', bbox_inches='tight')\n", (6399, 6464), True, 'import matplotlib.pyplot as plt\n'), ((6476, 6512), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(15, 15)'}), '(1, 1, figsize=(15, 15))\n', (6488, 6512), True, 'import matplotlib.pyplot as plt\n'), ((6520, 6654), 'src.visualization.adjplot', 'adjplot', (['adj.values'], {'meta': 'meta', 'sort_class': '"""class"""', 'plot_type': '"""scattermap"""', 'sizes': '(1, 1)', 'item_order': "['cluster', 'pair_id']", 'ax': 'ax'}), "(adj.values, meta=meta, sort_class='class', plot_type='scattermap',\n sizes=(1, 1), item_order=['cluster', 'pair_id'], ax=ax)\n", (6527, 6654), False, 'from src.visualization import CLASS_COLOR_DICT, adjplot\n'), ((6902, 7004), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""interhemisphere/plots/adj_matrix_sorted-class-cluster-pair.pdf"""'], {'bbox_inches': '"""tight"""'}), "('interhemisphere/plots/adj_matrix_sorted-class-cluster-pair.pdf',\n bbox_inches='tight')\n", (6913, 7004), True, 'import matplotlib.pyplot as plt\n'), ((7012, 7048), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(15, 15)'}), '(1, 1, figsize=(15, 15))\n', (7024, 7048), True, 'import matplotlib.pyplot as plt\n'), ((7056, 7190), 'src.visualization.adjplot', 'adjplot', (['adj.values'], {'meta': 'meta', 'sort_class': '"""cluster"""', 'plot_type': '"""scattermap"""', 'sizes': '(1, 1)', 'item_order': "['class', 'pair_id']", 'ax': 'ax'}), "(adj.values, meta=meta, sort_class='cluster', plot_type='scattermap',\n sizes=(1, 1), item_order=['class', 'pair_id'], ax=ax)\n", (7063, 7190), False, 'from src.visualization import CLASS_COLOR_DICT, adjplot\n'), ((7438, 7540), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""interhemisphere/plots/adj_matrix_sorted-cluster-class-pair.pdf"""'], {'bbox_inches': '"""tight"""'}), "('interhemisphere/plots/adj_matrix_sorted-cluster-class-pair.pdf',\n bbox_inches='tight')\n", (7449, 7540), True, 'import matplotlib.pyplot as plt\n'), ((7549, 7585), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(15, 15)'}), '(1, 1, figsize=(15, 15))\n', (7561, 7585), True, 'import matplotlib.pyplot as plt\n'), ((7593, 7716), 'src.visualization.adjplot', 'adjplot', (['adj.values'], {'meta': 'meta', 'sort_class': '"""class"""', 'plot_type': '"""scattermap"""', 'sizes': '(1, 1)', 'item_order': "['pair_id']", 'ax': 'ax'}), "(adj.values, meta=meta, sort_class='class', plot_type='scattermap',\n sizes=(1, 1), item_order=['pair_id'], ax=ax)\n", (7600, 7716), False, 'from src.visualization import CLASS_COLOR_DICT, adjplot\n'), ((7964, 8058), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""interhemisphere/plots/adj_matrix_sorted-class-pair.pdf"""'], {'bbox_inches': '"""tight"""'}), "('interhemisphere/plots/adj_matrix_sorted-class-pair.pdf',\n bbox_inches='tight')\n", (7975, 8058), True, 'import matplotlib.pyplot as plt\n'), ((8120, 8188), 'pandas.read_csv', 'pd.read_csv', (['"""interhemisphere/csv/all_paired_edges.csv"""'], {'index_col': '(0)'}), "('interhemisphere/csv/all_paired_edges.csv', index_col=0)\n", (8131, 8188), True, 'import pandas as pd\n'), ((8197, 8238), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw left"""'], {}), "('mw left')\n", (8227, 8238), True, 'import pymaid as pymaid\n'), ((8247, 8289), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw right"""'], {}), "('mw right')\n", (8277, 8289), True, 'import pymaid as pymaid\n'), ((11714, 11911), 'pandas.DataFrame', 'pd.DataFrame', (['all_edges_combined_split'], {'columns': "['upstream_pair_id', 'downstream_pair_id', 'upstream_side',\n 'downstream_side', 'edge_weight', 'type', 'upstream_status',\n 'downstream_status']"}), "(all_edges_combined_split, columns=['upstream_pair_id',\n 'downstream_pair_id', 'upstream_side', 'downstream_side', 'edge_weight',\n 'type', 'upstream_status', 'downstream_status'])\n", (11726, 11911), True, 'import pandas as pd\n'), ((11938, 11993), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw brain few synapses"""'], {}), "('mw brain few synapses')\n", (11968, 11993), True, 'import pymaid as pymaid\n'), ((12439, 12485), 'connectome_tools.process_matrix.Promat.extract_pairs_from_list', 'pm.Promat.extract_pairs_from_list', (['ipsi', 'pairs'], {}), '(ipsi, pairs)\n', (12472, 12485), True, 'import connectome_tools.process_matrix as pm\n'), ((12504, 12555), 'connectome_tools.process_matrix.Promat.extract_pairs_from_list', 'pm.Promat.extract_pairs_from_list', (['bilateral', 'pairs'], {}), '(bilateral, pairs)\n', (12537, 12555), True, 'import connectome_tools.process_matrix as pm\n'), ((12571, 12619), 'connectome_tools.process_matrix.Promat.extract_pairs_from_list', 'pm.Promat.extract_pairs_from_list', (['contra', 'pairs'], {}), '(contra, pairs)\n', (12604, 12619), True, 'import connectome_tools.process_matrix as pm\n'), ((13635, 13671), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(15, 15)'}), '(1, 1, figsize=(15, 15))\n', (13647, 13671), True, 'import matplotlib.pyplot as plt\n'), ((13672, 13792), 'src.visualization.adjplot', 'adjplot', (['adj.values'], {'meta': 'meta_test', 'sort_class': 'None', 'plot_type': '"""scattermap"""', 'sizes': '(0.5, 3)', 'item_order': 'None', 'ax': 'ax'}), "(adj.values, meta=meta_test, sort_class=None, plot_type='scattermap',\n sizes=(0.5, 3), item_order=None, ax=ax)\n", (13679, 13792), False, 'from src.visualization import CLASS_COLOR_DICT, adjplot\n'), ((34, 105), 'os.chdir', 'os.chdir', (['"""/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/"""'], {}), "('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/')\n", (42, 105), False, 'import os\n'), ((110, 185), 'sys.path.append', 'sys.path.append', (['"""/Volumes/GoogleDrive/My Drive/python_code/maggot_models/"""'], {}), "('/Volumes/GoogleDrive/My Drive/python_code/maggot_models/')\n", (125, 185), False, 'import sys\n'), ((190, 268), 'sys.path.append', 'sys.path.append', (['"""/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/"""'], {}), "('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/')\n", (205, 268), False, 'import sys\n'), ((1507, 1537), 'numpy.setdiff1d', 'np.setdiff1d', (['A1', 'A1_ascending'], {}), '(A1, A1_ascending)\n', (1519, 1537), True, 'import numpy as np\n'), ((1589, 1622), 'numpy.setdiff1d', 'np.setdiff1d', (['adj.index', 'A1_local'], {}), '(adj.index, A1_local)\n', (1601, 1622), True, 'import numpy as np\n'), ((2828, 2891), 'pandas.DataFrame', 'pd.DataFrame', (['order_df'], {'columns': "['cluster', 'node_visit_order']"}), "(order_df, columns=['cluster', 'node_visit_order'])\n", (2840, 2891), True, 'import pandas as pd\n'), ((2971, 3062), 'pandas.DataFrame', 'pd.DataFrame', (['[x for sublist in skids_df for x in sublist]'], {'columns': "['skid', 'cluster']"}), "([x for sublist in skids_df for x in sublist], columns=['skid',\n 'cluster'])\n", (2983, 3062), True, 'import pandas as pd\n'), ((3809, 3835), 'numpy.intersect1d', 'np.intersect1d', (['ipsi', 'left'], {}), '(ipsi, left)\n', (3823, 3835), True, 'import numpy as np\n'), ((3859, 3890), 'numpy.intersect1d', 'np.intersect1d', (['bilateral', 'left'], {}), '(bilateral, left)\n', (3873, 3890), True, 'import numpy as np\n'), ((3911, 3939), 'numpy.intersect1d', 'np.intersect1d', (['contra', 'left'], {}), '(contra, left)\n', (3925, 3939), True, 'import numpy as np\n'), ((3960, 3987), 'numpy.intersect1d', 'np.intersect1d', (['ipsi', 'right'], {}), '(ipsi, right)\n', (3974, 3987), True, 'import numpy as np\n'), ((4012, 4044), 'numpy.intersect1d', 'np.intersect1d', (['bilateral', 'right'], {}), '(bilateral, right)\n', (4026, 4044), True, 'import numpy as np\n'), ((4066, 4095), 'numpy.intersect1d', 'np.intersect1d', (['contra', 'right'], {}), '(contra, right)\n', (4080, 4095), True, 'import numpy as np\n'), ((12297, 12325), 'numpy.setdiff1d', 'np.setdiff1d', (['ipsi', 'immature'], {}), '(ipsi, immature)\n', (12309, 12325), True, 'import numpy as np\n'), ((12344, 12377), 'numpy.setdiff1d', 'np.setdiff1d', (['bilateral', 'immature'], {}), '(bilateral, immature)\n', (12356, 12377), True, 'import numpy as np\n'), ((12393, 12423), 'numpy.setdiff1d', 'np.setdiff1d', (['contra', 'immature'], {}), '(contra, immature)\n', (12405, 12423), True, 'import numpy as np\n'), ((3529, 3582), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw ipsilateral axon"""'], {}), "('mw ipsilateral axon')\n", (3559, 3582), True, 'import pymaid as pymaid\n'), ((3628, 3679), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw bilateral axon"""'], {}), "('mw bilateral axon')\n", (3658, 3679), True, 'import pymaid as pymaid\n'), ((3722, 3777), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw contralateral axon"""'], {}), "('mw contralateral axon')\n", (3752, 3777), True, 'import pymaid as pymaid\n'), ((12022, 12075), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw ipsilateral axon"""'], {}), "('mw ipsilateral axon')\n", (12052, 12075), True, 'import pymaid as pymaid\n'), ((12121, 12172), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw bilateral axon"""'], {}), "('mw bilateral axon')\n", (12151, 12172), True, 'import pymaid as pymaid\n'), ((12215, 12270), 'pymaid.get_skids_by_annotation', 'pymaid.get_skids_by_annotation', (['"""mw contralateral axon"""'], {}), "('mw contralateral axon')\n", (12245, 12270), True, 'import pymaid as pymaid\n'), ((12674, 12719), 'numpy.intersect1d', 'np.intersect1d', (['ipsi_pairs[2].nonpaired', 'left'], {}), '(ipsi_pairs[2].nonpaired, left)\n', (12688, 12719), True, 'import numpy as np\n'), ((12775, 12821), 'numpy.intersect1d', 'np.intersect1d', (['ipsi_pairs[2].nonpaired', 'right'], {}), '(ipsi_pairs[2].nonpaired, right)\n', (12789, 12821), True, 'import numpy as np\n'), ((12886, 12936), 'numpy.intersect1d', 'np.intersect1d', (['bilateral_pairs[2].nonpaired', 'left'], {}), '(bilateral_pairs[2].nonpaired, left)\n', (12900, 12936), True, 'import numpy as np\n'), ((13002, 13053), 'numpy.intersect1d', 'np.intersect1d', (['bilateral_pairs[2].nonpaired', 'right'], {}), '(bilateral_pairs[2].nonpaired, right)\n', (13016, 13053), True, 'import numpy as np\n'), ((13112, 13159), 'numpy.intersect1d', 'np.intersect1d', (['contra_pairs[2].nonpaired', 'left'], {}), '(contra_pairs[2].nonpaired, left)\n', (13126, 13159), True, 'import numpy as np\n'), ((13219, 13267), 'numpy.intersect1d', 'np.intersect1d', (['contra_pairs[2].nonpaired', 'right'], {}), '(contra_pairs[2].nonpaired, right)\n', (13233, 13267), True, 'import numpy as np\n'), ((5840, 5876), 'connectome_tools.process_matrix.Promat.identify_pair', 'pm.Promat.identify_pair', (['skid', 'pairs'], {}), '(skid, pairs)\n', (5863, 5876), True, 'import connectome_tools.process_matrix as pm\n'), ((2719, 2742), 'numpy.nanmean', 'np.nanmean', (['node_visits'], {}), '(node_visits)\n', (2729, 2742), True, 'import numpy as np\n'), ((8736, 8788), 'connectome_tools.process_matrix.Promat.identify_pair', 'pm.Promat.identify_pair', (['row.upstream_pair_id', 'pairs'], {}), '(row.upstream_pair_id, pairs)\n', (8759, 8788), True, 'import connectome_tools.process_matrix as pm\n'), ((8790, 8844), 'connectome_tools.process_matrix.Promat.identify_pair', 'pm.Promat.identify_pair', (['row.downstream_pair_id', 'pairs'], {}), '(row.downstream_pair_id, pairs)\n', (8813, 8844), True, 'import connectome_tools.process_matrix as pm\n'), ((9036, 9090), 'connectome_tools.process_matrix.Promat.identify_pair', 'pm.Promat.identify_pair', (['row.downstream_pair_id', 'pairs'], {}), '(row.downstream_pair_id, pairs)\n', (9059, 9090), True, 'import connectome_tools.process_matrix as pm\n'), ((9219, 9271), 'connectome_tools.process_matrix.Promat.identify_pair', 'pm.Promat.identify_pair', (['row.upstream_pair_id', 'pairs'], {}), '(row.upstream_pair_id, pairs)\n', (9242, 9271), True, 'import connectome_tools.process_matrix as pm\n'), ((9834, 9888), 'connectome_tools.process_matrix.Promat.identify_pair', 'pm.Promat.identify_pair', (['row.downstream_pair_id', 'pairs'], {}), '(row.downstream_pair_id, pairs)\n', (9857, 9888), True, 'import connectome_tools.process_matrix as pm\n'), ((10128, 10182), 'connectome_tools.process_matrix.Promat.identify_pair', 'pm.Promat.identify_pair', (['row.downstream_pair_id', 'pairs'], {}), '(row.downstream_pair_id, pairs)\n', (10151, 10182), True, 'import connectome_tools.process_matrix as pm\n'), ((10923, 10975), 'connectome_tools.process_matrix.Promat.identify_pair', 'pm.Promat.identify_pair', (['row.upstream_pair_id', 'pairs'], {}), '(row.upstream_pair_id, pairs)\n', (10946, 10975), True, 'import connectome_tools.process_matrix as pm\n'), ((11219, 11271), 'connectome_tools.process_matrix.Promat.identify_pair', 'pm.Promat.identify_pair', (['row.upstream_pair_id', 'pairs'], {}), '(row.upstream_pair_id, pairs)\n', (11242, 11271), True, 'import connectome_tools.process_matrix as pm\n')]
import numpy as np from astLib import astCalc as aca # check these numbers. I don't think it really matters though. aca.H0 = 72 aca.OMEGA_M0 = 0.23 aca.OMEGA_L0 = 0.77 def calcMass(vd, A1D=1082.9, alpha=0.3361): avgz = 0.0 return 1e15 / (aca.H0 * aca.Ez(avgz) / 100.) * (vd / A1D)**(1 / alpha) def calcLOSVD(M, z, A1D=1082.9, alpha=0.3361): return A1D * (M * (aca.H0 * aca.Ez(z) / 100.) / 1e15)**alpha def prob3d(train, test): # compute the LOSVD based on the true mass #LOSVD = map(calcLOSVD, train['M200c'], train['ZSPEC']) #LOSVD = [abs(i + i*np.random.normal()*2) for i in LOSVD] # make the joint probability data = np.column_stack((np.log10(train['M200c']), np.log10(train['LOSVD']), train['ZSPEC'], np.log10(train['NGAL']))) Ngrid = 41, 21, 5, 10 grid = [np.linspace(data[:, i].min(), data[:, i].max(), g + 1) for i, g in enumerate(Ngrid)] H, (xbins, ybins, zbins, ngbins) = np.histogramdd(data, bins=grid) # The bin order in the histogram now becomes z, y, x!!! H = H.T # Now we try to recover, and predict expected_mass = np.zeros((test.size, ), dtype=[('MASS', '>f4'), ('MASS_err', '>f4', (2, ))]) for j, (s, z, ng) in enumerate(zip(test['LOSVD_dist'], test['ZSPEC'], test['NGAL'])): # using the distribution of sigmas we make P(s) and ds Ps, ds = np.histogram(np.log10(s), bins=50, density=True) centers = (ds[1:] + ds[:-1]) / 2.0 # now we have to make P(m|s,z) -- from the training sample # will need to do this a bunch of times for each sigma in centers iy = np.digitize(centers, ybins) iz = np.digitize([z], zbins)[0] ing = np.digitize([np.log10(ng)], ngbins)[0] # now we make P(m) using P(m|s,z) and P(s)ds from above Pm = np.zeros(xbins.size - 1) Psds = Ps * np.diff(ds) for i, b in enumerate(iy): try: if H[ing - 1, iz - 1, b - 1, :].sum() == 0.0: Pm_sz = np.zeros(xbins.size - 1) else: Pm_sz = H[ing-1, iz-1, b-1, :]/\ H[ing-1, iz-1, b-1, :].sum() except IndexError: Pm_sz = np.zeros(xbins.size - 1) #print Pm_sz Pm += Pm_sz * Psds[i] # now we can calculate the expected mass centers = (xbins[:-1] + xbins[1:]) / 2. norm = np.sum(Pm * np.diff(xbins)) M_expect = np.sum(centers * Pm * np.diff(xbins)) / norm variance = np.sum((centers - M_expect)**2 * Pm * np.diff(xbins)) / norm expected_mass['MASS'][j] = M_expect expected_mass['MASS_err'][j] = [M_expect - np.sqrt(variance), M_expect + np.sqrt(variance)] #mask = np.where(np.isnan(expected_mass['MASS']))[0] #expected_mass = np.delete(expected_mass, mask) #test = np.delete(test, mask) return expected_mass # resamples = slice_sampler(Pm,x=centers, N=1000) # expected_mass['MASS_err'][j] = np.percentile(resamples, [16, 84]) if __name__ == "__main__": prob3d()
[ "numpy.zeros", "numpy.histogramdd", "astLib.astCalc.Ez", "numpy.diff", "numpy.log10", "numpy.digitize", "numpy.sqrt" ]
[((975, 1006), 'numpy.histogramdd', 'np.histogramdd', (['data'], {'bins': 'grid'}), '(data, bins=grid)\n', (989, 1006), True, 'import numpy as np\n'), ((1142, 1216), 'numpy.zeros', 'np.zeros', (['(test.size,)'], {'dtype': "[('MASS', '>f4'), ('MASS_err', '>f4', (2,))]"}), "((test.size,), dtype=[('MASS', '>f4'), ('MASS_err', '>f4', (2,))])\n", (1150, 1216), True, 'import numpy as np\n'), ((1759, 1786), 'numpy.digitize', 'np.digitize', (['centers', 'ybins'], {}), '(centers, ybins)\n', (1770, 1786), True, 'import numpy as np\n'), ((1957, 1981), 'numpy.zeros', 'np.zeros', (['(xbins.size - 1)'], {}), '(xbins.size - 1)\n', (1965, 1981), True, 'import numpy as np\n'), ((677, 701), 'numpy.log10', 'np.log10', (["train['M200c']"], {}), "(train['M200c'])\n", (685, 701), True, 'import numpy as np\n'), ((703, 727), 'numpy.log10', 'np.log10', (["train['LOSVD']"], {}), "(train['LOSVD'])\n", (711, 727), True, 'import numpy as np\n'), ((773, 796), 'numpy.log10', 'np.log10', (["train['NGAL']"], {}), "(train['NGAL'])\n", (781, 796), True, 'import numpy as np\n'), ((1525, 1536), 'numpy.log10', 'np.log10', (['s'], {}), '(s)\n', (1533, 1536), True, 'import numpy as np\n'), ((1800, 1823), 'numpy.digitize', 'np.digitize', (['[z]', 'zbins'], {}), '([z], zbins)\n', (1811, 1823), True, 'import numpy as np\n'), ((2002, 2013), 'numpy.diff', 'np.diff', (['ds'], {}), '(ds)\n', (2009, 2013), True, 'import numpy as np\n'), ((2573, 2587), 'numpy.diff', 'np.diff', (['xbins'], {}), '(xbins)\n', (2580, 2587), True, 'import numpy as np\n'), ((2829, 2846), 'numpy.sqrt', 'np.sqrt', (['variance'], {}), '(variance)\n', (2836, 2846), True, 'import numpy as np\n'), ((2899, 2916), 'numpy.sqrt', 'np.sqrt', (['variance'], {}), '(variance)\n', (2906, 2916), True, 'import numpy as np\n'), ((258, 270), 'astLib.astCalc.Ez', 'aca.Ez', (['avgz'], {}), '(avgz)\n', (264, 270), True, 'from astLib import astCalc as aca\n'), ((1854, 1866), 'numpy.log10', 'np.log10', (['ng'], {}), '(ng)\n', (1862, 1866), True, 'import numpy as np\n'), ((2156, 2180), 'numpy.zeros', 'np.zeros', (['(xbins.size - 1)'], {}), '(xbins.size - 1)\n', (2164, 2180), True, 'import numpy as np\n'), ((2364, 2388), 'numpy.zeros', 'np.zeros', (['(xbins.size - 1)'], {}), '(xbins.size - 1)\n', (2372, 2388), True, 'import numpy as np\n'), ((2630, 2644), 'numpy.diff', 'np.diff', (['xbins'], {}), '(xbins)\n', (2637, 2644), True, 'import numpy as np\n'), ((2710, 2724), 'numpy.diff', 'np.diff', (['xbins'], {}), '(xbins)\n', (2717, 2724), True, 'import numpy as np\n'), ((386, 395), 'astLib.astCalc.Ez', 'aca.Ez', (['z'], {}), '(z)\n', (392, 395), True, 'from astLib import astCalc as aca\n')]
from bentkus_conf_seq.conc_ineq.bentkus import bentkus import numpy as np from confseq.betting import get_ci_seq from confseq.predmix import predmix_empbern_cs from small_sample_mean_bounds.bound import b_alpha_l2norm, b_alpha_linear from typing import Sequence def hoeffding_ci(x, times, alpha=0.05): x = np.array(x) S_t = np.cumsum(x) t = np.arange(1, len(x) + 1) mu_hat_t = S_t / t margin = np.sqrt(np.log(2 / alpha) / (2 * t)) l, u = mu_hat_t - margin, mu_hat_t + margin l = np.maximum(l, 0) u = np.minimum(u, 1) return l[times - 1], u[times - 1] def predmix_empbern_ci(x, alpha, truncation=1 / 2, parallel=True): x = np.array(x) l, u = predmix_empbern_cs( x, alpha=alpha, truncation=truncation, running_intersection=True, fixed_n=len(x) ) return l[-1], u[-1] def predmix_empbern_ci_seq(x, alpha, times, truncation=1 / 2, parallel=False): ci_fn = lambda x: predmix_empbern_ci(x, alpha=alpha, truncation=truncation) return get_ci_seq(x, ci_fn, times=times, parallel=parallel) def bennett_ci(x, times, variance, alpha=0.05): x = np.array(x) S_t = np.cumsum(x) t = np.arange(1, len(x) + 1) mu_hat_t = S_t / t margin = np.sqrt(2 * variance * np.log(2 / alpha) / t) + np.log(2 / alpha) / (3 * t) l, u = mu_hat_t - margin, mu_hat_t + margin l = np.maximum(l, 0) u = np.minimum(u, 1) return l[times - 1], u[times - 1] def bentkus_ci(x, times, variance, alpha=0.05): x = np.array(x) S_t = np.cumsum(x) t = np.arange(1, len(x) + 1) mu_hat_t = (S_t / t)[times - 1] margin = np.ones(len(times)) for i in range(len(times)): time = times[i] margin[i] = (1 / time) * bentkus( n=time, delta=alpha / 2, A=np.sqrt(variance), B=1 ) l, u = mu_hat_t - margin, mu_hat_t + margin l = np.maximum(l, 0) u = np.minimum(u, 1) return l, u def anderson_ci(x, alpha): n = len(x) i = np.arange(1, n + 1) u_DKW = np.maximum(0, i / n - np.sqrt(np.log(2 / alpha) / (2 * n))) zu_i = np.sort(x) zu_iplus1 = np.append(zu_i, 1)[1:] zl_i = np.flip(1 - zu_i) zl_iplus1 = np.append(zl_i, 1)[1:] u = 1 - np.sum(u_DKW * (zu_iplus1 - zu_i)) l = np.sum(u_DKW * (zl_iplus1 - zl_i)) return l, u def anderson_ci_seq(x, alpha, times, parallel=False): def ci_fn(x): return anderson_ci(x, alpha=alpha) return get_ci_seq(x, ci_fn, times=times, parallel=parallel) def ptl_l2_ci(x, alpha): upper = b_alpha_l2norm(z=x, alpha=alpha / 2, upper=1) lower = b_alpha_l2norm(z=1 - x, alpha=alpha / 2, upper=1) return 1 - lower, upper def ptl_linear_ci(x, alpha): upper = b_alpha_linear(z=x, alpha=alpha / 2, upper=1) lower = b_alpha_linear(z=1 - x, alpha=alpha / 2, upper=1) return 1 - lower, upper def maurer_pontil_empbern_ci(x, times, alpha=0.05): x = np.array(x) S_t = np.cumsum(x) t = np.arange(1, len(x) + 1) mu_hat_t = S_t / t V_t = np.cumsum(np.power(x, 2)) / t - np.power(S_t / t, 2) margin = np.sqrt(2 * V_t * np.log(4 / alpha) / t) + 7 * np.log(4 / alpha) / ( 3 * (t - 1) ) l, u = mu_hat_t - margin, mu_hat_t + margin l = np.maximum(l, 0) u = np.minimum(u, 1) return l[times - 1], u[times - 1] def audibert_empbern_ci(x, times, alpha=0.05): x = np.array(x) S_t = np.cumsum(x) t = np.arange(1, len(x) + 1) mu_hat_t = S_t / t V_t = np.cumsum(np.power(x, 2)) / t - np.power(S_t / t, 2) margin = np.sqrt(2 * V_t * np.log(3 / alpha) / t) + 3 * np.log(3 / alpha) / t l, u = mu_hat_t - margin, mu_hat_t + margin l = np.maximum(l, 0) u = np.minimum(u, 1) return l[times - 1], u[times - 1] class LBOW_Bettor: def __init__(self, x, WoR=False, N=None): self.x = x self.WoR = WoR self.N = N t = np.arange(1, len(x) + 1) # Get mu_hat estimates mu_hat_t = (1 / 2 + np.cumsum(x)) / (t + 1) self.mu_hat_tminus1 = np.append(1 / 4, mu_hat_t[0 : (len(mu_hat_t) - 1)]) sigma2_hat_t = (1 / 4 + np.cumsum(np.power(x, 2))) / (t + 1) - np.power( mu_hat_t, 2 ) self.sigma2_hat_tminus1 = np.append( 1 / 4, sigma2_hat_t[0 : (len(sigma2_hat_t) - 1)] ) def get_bet(self, against, idx): # Get bet using the LBOW scheme m_star = against if self.mu_hat_tminus1[idx] - against >= 0 else 1 - against bet = (self.mu_hat_tminus1[idx] - against) / ( m_star * np.abs(self.mu_hat_tminus1[idx] - against) + self.sigma2_hat_tminus1[idx] + np.power(self.mu_hat_tminus1[idx] - against, 2) ) return bet def get_l_bet(self, l_bdry, idx): # Get lower bet pre-truncation if self.WoR: against = (self.N * l_bdry - np.sum(self.x[0:idx])) / (self.N - idx) else: against = l_bdry return self.get_bet(against=against, idx=idx) def get_u_bet(self, u_bdry, idx): # Get upper bet pre-truncation if self.WoR: against = (self.N * u_bdry - np.sum(self.x[0:idx])) / (self.N - idx) else: against = u_bdry return self.get_bet(against=against, idx=idx) def conbo_cs( x, Bettor=LBOW_Bettor, alpha=0.05, WoR=False, N=None, theta=1 / 2, breaks=1000, running_intersection=False, trunc_scale=1 / 2, ): n = len(x) t = np.arange(1, n + 1) l = np.zeros(n) u = np.ones(n) l_bdry = 0 u_bdry = 1 capital_vector_positive = np.ones(breaks + 1) capital_vector_negative = np.ones(breaks + 1) possible_m = np.arange(0, 1 + 1 / breaks, step=1 / breaks) bettor = Bettor(x) if WoR: assert N is not None S_tminus1 = np.append(0, np.cumsum(x)[0 : (len(x) - 1)]) # For each time for i in range(n): if WoR: m_t = (N * possible_m - S_tminus1[i]) / (N - t[i] + 1) else: m_t = possible_m l_bet = bettor.get_l_bet(l_bdry, i) l_bet = np.maximum(l_bet, 0) l_bet = np.minimum(l_bet, trunc_scale / m_t) u_bet = bettor.get_u_bet(u_bdry, i) u_bet = np.abs(np.minimum(u_bet, 0)) u_bet = np.minimum(u_bet, trunc_scale / (1 - m_t)) capital_vector_positive *= 1 + l_bet * (x[i] - m_t) capital_vector_negative *= 1 - u_bet * (x[i] - m_t) capital_vector = ( theta * capital_vector_positive + (1 - theta) * capital_vector_negative ) capital_vector[np.logical_or(m_t < 0, m_t > 1)] = math.inf assert all(capital_vector >= 0) where_not_reject = np.where(capital_vector < 1 / alpha)[0] if len(where_not_reject) is 0 and i is not 0: l[i] = l[i - 1] u[i] = u[i - 1] elif len(where_not_reject) is 0 and i is 0: l[i] = 0 u[i] = 1 else: # Need to take superset l[i] = possible_m[where_not_reject[0]] - 1 / breaks u[i] = possible_m[where_not_reject[-1]] + 1 / breaks l_bdry = max(l_bdry, l[i]) u_bdry = min(u_bdry, u[i]) if WoR: # Intersect with logical cs l_logical, u_logical = logical_cs(x, N) l = np.maximum(l, l_logical) u = np.minimum(u, u_logical) else: l = np.maximum(0, l) u = np.minimum(1, u) if running_intersection: l = np.maximum.accumulate(l) u = np.minimum.accumulate(u) return l, u def lambda_COLT18_ONS(x, m, c=1 / 2): lambdas = np.zeros(len(x)) lambdas[0] = 0 A = 1 for i in np.arange(1, len(lambdas)): g = x[i - 1] - m z = -g / (1 + g * lambdas[i - 1]) A = A + np.power(z, 2) lambdas[i] = lambdas[i - 1] - (2 / (2 - np.log(3))) * z / A lambdas[i] = np.minimum(c / m, np.maximum(-c / (1 - m), lambdas[i])) return lambdas def banco(x: Sequence[float], alpha: float, running_intersection=False): """Concentration inequality resulting from BANCO (Jun & Orabona (2019))""" # Tighest possible upper bound on the SD for [0, 1]-bounded random variables without further information sigma_1D = 1 / 2 t = np.arange(1, len(x) + 1) margin = sigma_1D * np.sqrt( 2 * np.log( np.power(6 * np.pi * np.sqrt(np.e) / alpha, 3 / 2) * (np.power(np.log(np.sqrt(t)), 2) + 1) ) / t ) mu_hat_t = np.cumsum(x) / t l, u = mu_hat_t - margin, mu_hat_t + margin if running_intersection: l = np.maximum.accumulate(l) u = np.minimum.accumulate(u) l = np.maximum(0, l) u = np.minimum(1, u) return l, u def lambda_aKelly_oracle(x, m, mu, var, WoR=False, N=None, trunc_scale=1): if WoR: m_t = mu_t(x, m, N) else: m_t = np.repeat(m, len(x)) lambdas = (mu - m_t) / (var + np.power(mu - m_t, 2)) lambdas = np.maximum(-trunc_scale / (1 - m_t), lambdas) lambdas = np.minimum(trunc_scale / m_t, lambdas) return lambdas
[ "numpy.maximum", "numpy.sum", "numpy.abs", "small_sample_mean_bounds.bound.b_alpha_l2norm", "numpy.ones", "numpy.arange", "numpy.power", "numpy.cumsum", "numpy.append", "numpy.minimum", "numpy.sort", "numpy.maximum.accumulate", "small_sample_mean_bounds.bound.b_alpha_linear", "confseq.bett...
[((312, 323), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (320, 323), True, 'import numpy as np\n'), ((334, 346), 'numpy.cumsum', 'np.cumsum', (['x'], {}), '(x)\n', (343, 346), True, 'import numpy as np\n'), ((510, 526), 'numpy.maximum', 'np.maximum', (['l', '(0)'], {}), '(l, 0)\n', (520, 526), True, 'import numpy as np\n'), ((535, 551), 'numpy.minimum', 'np.minimum', (['u', '(1)'], {}), '(u, 1)\n', (545, 551), True, 'import numpy as np\n'), ((668, 679), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (676, 679), True, 'import numpy as np\n'), ((1004, 1056), 'confseq.betting.get_ci_seq', 'get_ci_seq', (['x', 'ci_fn'], {'times': 'times', 'parallel': 'parallel'}), '(x, ci_fn, times=times, parallel=parallel)\n', (1014, 1056), False, 'from confseq.betting import get_ci_seq\n'), ((1115, 1126), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1123, 1126), True, 'import numpy as np\n'), ((1137, 1149), 'numpy.cumsum', 'np.cumsum', (['x'], {}), '(x)\n', (1146, 1149), True, 'import numpy as np\n'), ((1353, 1369), 'numpy.maximum', 'np.maximum', (['l', '(0)'], {}), '(l, 0)\n', (1363, 1369), True, 'import numpy as np\n'), ((1378, 1394), 'numpy.minimum', 'np.minimum', (['u', '(1)'], {}), '(u, 1)\n', (1388, 1394), True, 'import numpy as np\n'), ((1492, 1503), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (1500, 1503), True, 'import numpy as np\n'), ((1514, 1526), 'numpy.cumsum', 'np.cumsum', (['x'], {}), '(x)\n', (1523, 1526), True, 'import numpy as np\n'), ((1857, 1873), 'numpy.maximum', 'np.maximum', (['l', '(0)'], {}), '(l, 0)\n', (1867, 1873), True, 'import numpy as np\n'), ((1882, 1898), 'numpy.minimum', 'np.minimum', (['u', '(1)'], {}), '(u, 1)\n', (1892, 1898), True, 'import numpy as np\n'), ((1968, 1987), 'numpy.arange', 'np.arange', (['(1)', '(n + 1)'], {}), '(1, n + 1)\n', (1977, 1987), True, 'import numpy as np\n'), ((2072, 2082), 'numpy.sort', 'np.sort', (['x'], {}), '(x)\n', (2079, 2082), True, 'import numpy as np\n'), ((2133, 2150), 'numpy.flip', 'np.flip', (['(1 - zu_i)'], {}), '(1 - zu_i)\n', (2140, 2150), True, 'import numpy as np\n'), ((2245, 2279), 'numpy.sum', 'np.sum', (['(u_DKW * (zl_iplus1 - zl_i))'], {}), '(u_DKW * (zl_iplus1 - zl_i))\n', (2251, 2279), True, 'import numpy as np\n'), ((2425, 2477), 'confseq.betting.get_ci_seq', 'get_ci_seq', (['x', 'ci_fn'], {'times': 'times', 'parallel': 'parallel'}), '(x, ci_fn, times=times, parallel=parallel)\n', (2435, 2477), False, 'from confseq.betting import get_ci_seq\n'), ((2517, 2562), 'small_sample_mean_bounds.bound.b_alpha_l2norm', 'b_alpha_l2norm', ([], {'z': 'x', 'alpha': '(alpha / 2)', 'upper': '(1)'}), '(z=x, alpha=alpha / 2, upper=1)\n', (2531, 2562), False, 'from small_sample_mean_bounds.bound import b_alpha_l2norm, b_alpha_linear\n'), ((2575, 2624), 'small_sample_mean_bounds.bound.b_alpha_l2norm', 'b_alpha_l2norm', ([], {'z': '(1 - x)', 'alpha': '(alpha / 2)', 'upper': '(1)'}), '(z=1 - x, alpha=alpha / 2, upper=1)\n', (2589, 2624), False, 'from small_sample_mean_bounds.bound import b_alpha_l2norm, b_alpha_linear\n'), ((2697, 2742), 'small_sample_mean_bounds.bound.b_alpha_linear', 'b_alpha_linear', ([], {'z': 'x', 'alpha': '(alpha / 2)', 'upper': '(1)'}), '(z=x, alpha=alpha / 2, upper=1)\n', (2711, 2742), False, 'from small_sample_mean_bounds.bound import b_alpha_l2norm, b_alpha_linear\n'), ((2755, 2804), 'small_sample_mean_bounds.bound.b_alpha_linear', 'b_alpha_linear', ([], {'z': '(1 - x)', 'alpha': '(alpha / 2)', 'upper': '(1)'}), '(z=1 - x, alpha=alpha / 2, upper=1)\n', (2769, 2804), False, 'from small_sample_mean_bounds.bound import b_alpha_l2norm, b_alpha_linear\n'), ((2896, 2907), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (2904, 2907), True, 'import numpy as np\n'), ((2918, 2930), 'numpy.cumsum', 'np.cumsum', (['x'], {}), '(x)\n', (2927, 2930), True, 'import numpy as np\n'), ((3217, 3233), 'numpy.maximum', 'np.maximum', (['l', '(0)'], {}), '(l, 0)\n', (3227, 3233), True, 'import numpy as np\n'), ((3242, 3258), 'numpy.minimum', 'np.minimum', (['u', '(1)'], {}), '(u, 1)\n', (3252, 3258), True, 'import numpy as np\n'), ((3354, 3365), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (3362, 3365), True, 'import numpy as np\n'), ((3376, 3388), 'numpy.cumsum', 'np.cumsum', (['x'], {}), '(x)\n', (3385, 3388), True, 'import numpy as np\n'), ((3649, 3665), 'numpy.maximum', 'np.maximum', (['l', '(0)'], {}), '(l, 0)\n', (3659, 3665), True, 'import numpy as np\n'), ((3674, 3690), 'numpy.minimum', 'np.minimum', (['u', '(1)'], {}), '(u, 1)\n', (3684, 3690), True, 'import numpy as np\n'), ((5468, 5487), 'numpy.arange', 'np.arange', (['(1)', '(n + 1)'], {}), '(1, n + 1)\n', (5477, 5487), True, 'import numpy as np\n'), ((5496, 5507), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (5504, 5507), True, 'import numpy as np\n'), ((5516, 5526), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (5523, 5526), True, 'import numpy as np\n'), ((5589, 5608), 'numpy.ones', 'np.ones', (['(breaks + 1)'], {}), '(breaks + 1)\n', (5596, 5608), True, 'import numpy as np\n'), ((5639, 5658), 'numpy.ones', 'np.ones', (['(breaks + 1)'], {}), '(breaks + 1)\n', (5646, 5658), True, 'import numpy as np\n'), ((5676, 5721), 'numpy.arange', 'np.arange', (['(0)', '(1 + 1 / breaks)'], {'step': '(1 / breaks)'}), '(0, 1 + 1 / breaks, step=1 / breaks)\n', (5685, 5721), True, 'import numpy as np\n'), ((8665, 8681), 'numpy.maximum', 'np.maximum', (['(0)', 'l'], {}), '(0, l)\n', (8675, 8681), True, 'import numpy as np\n'), ((8690, 8706), 'numpy.minimum', 'np.minimum', (['(1)', 'u'], {}), '(1, u)\n', (8700, 8706), True, 'import numpy as np\n'), ((8957, 9002), 'numpy.maximum', 'np.maximum', (['(-trunc_scale / (1 - m_t))', 'lambdas'], {}), '(-trunc_scale / (1 - m_t), lambdas)\n', (8967, 9002), True, 'import numpy as np\n'), ((9017, 9055), 'numpy.minimum', 'np.minimum', (['(trunc_scale / m_t)', 'lambdas'], {}), '(trunc_scale / m_t, lambdas)\n', (9027, 9055), True, 'import numpy as np\n'), ((2099, 2117), 'numpy.append', 'np.append', (['zu_i', '(1)'], {}), '(zu_i, 1)\n', (2108, 2117), True, 'import numpy as np\n'), ((2167, 2185), 'numpy.append', 'np.append', (['zl_i', '(1)'], {}), '(zl_i, 1)\n', (2176, 2185), True, 'import numpy as np\n'), ((2202, 2236), 'numpy.sum', 'np.sum', (['(u_DKW * (zu_iplus1 - zu_i))'], {}), '(u_DKW * (zu_iplus1 - zu_i))\n', (2208, 2236), True, 'import numpy as np\n'), ((3030, 3050), 'numpy.power', 'np.power', (['(S_t / t)', '(2)'], {}), '(S_t / t, 2)\n', (3038, 3050), True, 'import numpy as np\n'), ((3488, 3508), 'numpy.power', 'np.power', (['(S_t / t)', '(2)'], {}), '(S_t / t, 2)\n', (3496, 3508), True, 'import numpy as np\n'), ((6084, 6104), 'numpy.maximum', 'np.maximum', (['l_bet', '(0)'], {}), '(l_bet, 0)\n', (6094, 6104), True, 'import numpy as np\n'), ((6121, 6157), 'numpy.minimum', 'np.minimum', (['l_bet', '(trunc_scale / m_t)'], {}), '(l_bet, trunc_scale / m_t)\n', (6131, 6157), True, 'import numpy as np\n'), ((6264, 6306), 'numpy.minimum', 'np.minimum', (['u_bet', '(trunc_scale / (1 - m_t))'], {}), '(u_bet, trunc_scale / (1 - m_t))\n', (6274, 6306), True, 'import numpy as np\n'), ((7294, 7318), 'numpy.maximum', 'np.maximum', (['l', 'l_logical'], {}), '(l, l_logical)\n', (7304, 7318), True, 'import numpy as np\n'), ((7331, 7355), 'numpy.minimum', 'np.minimum', (['u', 'u_logical'], {}), '(u, u_logical)\n', (7341, 7355), True, 'import numpy as np\n'), ((7378, 7394), 'numpy.maximum', 'np.maximum', (['(0)', 'l'], {}), '(0, l)\n', (7388, 7394), True, 'import numpy as np\n'), ((7407, 7423), 'numpy.minimum', 'np.minimum', (['(1)', 'u'], {}), '(1, u)\n', (7417, 7423), True, 'import numpy as np\n'), ((7466, 7490), 'numpy.maximum.accumulate', 'np.maximum.accumulate', (['l'], {}), '(l)\n', (7487, 7490), True, 'import numpy as np\n'), ((7503, 7527), 'numpy.minimum.accumulate', 'np.minimum.accumulate', (['u'], {}), '(u)\n', (7524, 7527), True, 'import numpy as np\n'), ((8487, 8499), 'numpy.cumsum', 'np.cumsum', (['x'], {}), '(x)\n', (8496, 8499), True, 'import numpy as np\n'), ((8594, 8618), 'numpy.maximum.accumulate', 'np.maximum.accumulate', (['l'], {}), '(l)\n', (8615, 8618), True, 'import numpy as np\n'), ((8631, 8655), 'numpy.minimum.accumulate', 'np.minimum.accumulate', (['u'], {}), '(u)\n', (8652, 8655), True, 'import numpy as np\n'), ((425, 442), 'numpy.log', 'np.log', (['(2 / alpha)'], {}), '(2 / alpha)\n', (431, 442), True, 'import numpy as np\n'), ((1268, 1285), 'numpy.log', 'np.log', (['(2 / alpha)'], {}), '(2 / alpha)\n', (1274, 1285), True, 'import numpy as np\n'), ((4133, 4154), 'numpy.power', 'np.power', (['mu_hat_t', '(2)'], {}), '(mu_hat_t, 2)\n', (4141, 4154), True, 'import numpy as np\n'), ((6226, 6246), 'numpy.minimum', 'np.minimum', (['u_bet', '(0)'], {}), '(u_bet, 0)\n', (6236, 6246), True, 'import numpy as np\n'), ((6572, 6603), 'numpy.logical_or', 'np.logical_or', (['(m_t < 0)', '(m_t > 1)'], {}), '(m_t < 0, m_t > 1)\n', (6585, 6603), True, 'import numpy as np\n'), ((6684, 6720), 'numpy.where', 'np.where', (['(capital_vector < 1 / alpha)'], {}), '(capital_vector < 1 / alpha)\n', (6692, 6720), True, 'import numpy as np\n'), ((7768, 7782), 'numpy.power', 'np.power', (['z', '(2)'], {}), '(z, 2)\n', (7776, 7782), True, 'import numpy as np\n'), ((7890, 7926), 'numpy.maximum', 'np.maximum', (['(-c / (1 - m))', 'lambdas[i]'], {}), '(-c / (1 - m), lambdas[i])\n', (7900, 7926), True, 'import numpy as np\n'), ((8919, 8940), 'numpy.power', 'np.power', (['(mu - m_t)', '(2)'], {}), '(mu - m_t, 2)\n', (8927, 8940), True, 'import numpy as np\n'), ((3008, 3022), 'numpy.power', 'np.power', (['x', '(2)'], {}), '(x, 2)\n', (3016, 3022), True, 'import numpy as np\n'), ((3111, 3128), 'numpy.log', 'np.log', (['(4 / alpha)'], {}), '(4 / alpha)\n', (3117, 3128), True, 'import numpy as np\n'), ((3466, 3480), 'numpy.power', 'np.power', (['x', '(2)'], {}), '(x, 2)\n', (3474, 3480), True, 'import numpy as np\n'), ((3569, 3586), 'numpy.log', 'np.log', (['(3 / alpha)'], {}), '(3 / alpha)\n', (3575, 3586), True, 'import numpy as np\n'), ((3955, 3967), 'numpy.cumsum', 'np.cumsum', (['x'], {}), '(x)\n', (3964, 3967), True, 'import numpy as np\n'), ((4633, 4680), 'numpy.power', 'np.power', (['(self.mu_hat_tminus1[idx] - against)', '(2)'], {}), '(self.mu_hat_tminus1[idx] - against, 2)\n', (4641, 4680), True, 'import numpy as np\n'), ((5821, 5833), 'numpy.cumsum', 'np.cumsum', (['x'], {}), '(x)\n', (5830, 5833), True, 'import numpy as np\n'), ((1243, 1260), 'numpy.log', 'np.log', (['(2 / alpha)'], {}), '(2 / alpha)\n', (1249, 1260), True, 'import numpy as np\n'), ((1767, 1784), 'numpy.sqrt', 'np.sqrt', (['variance'], {}), '(variance)\n', (1774, 1784), True, 'import numpy as np\n'), ((2030, 2047), 'numpy.log', 'np.log', (['(2 / alpha)'], {}), '(2 / alpha)\n', (2036, 2047), True, 'import numpy as np\n'), ((3082, 3099), 'numpy.log', 'np.log', (['(4 / alpha)'], {}), '(4 / alpha)\n', (3088, 3099), True, 'import numpy as np\n'), ((3540, 3557), 'numpy.log', 'np.log', (['(3 / alpha)'], {}), '(3 / alpha)\n', (3546, 3557), True, 'import numpy as np\n'), ((4850, 4871), 'numpy.sum', 'np.sum', (['self.x[0:idx]'], {}), '(self.x[0:idx])\n', (4856, 4871), True, 'import numpy as np\n'), ((5127, 5148), 'numpy.sum', 'np.sum', (['self.x[0:idx]'], {}), '(self.x[0:idx])\n', (5133, 5148), True, 'import numpy as np\n'), ((4104, 4118), 'numpy.power', 'np.power', (['x', '(2)'], {}), '(x, 2)\n', (4112, 4118), True, 'import numpy as np\n'), ((4533, 4575), 'numpy.abs', 'np.abs', (['(self.mu_hat_tminus1[idx] - against)'], {}), '(self.mu_hat_tminus1[idx] - against)\n', (4539, 4575), True, 'import numpy as np\n'), ((7831, 7840), 'numpy.log', 'np.log', (['(3)'], {}), '(3)\n', (7837, 7840), True, 'import numpy as np\n'), ((8361, 8374), 'numpy.sqrt', 'np.sqrt', (['np.e'], {}), '(np.e)\n', (8368, 8374), True, 'import numpy as np\n'), ((8422, 8432), 'numpy.sqrt', 'np.sqrt', (['t'], {}), '(t)\n', (8429, 8432), True, 'import numpy as np\n')]
import os import pickle import numpy as np import scipy.sparse as sparse import torch from solve import Solve from tqdm import tqdm from joblib import Memory memory = Memory('__pycache__', verbose=0) @memory.cache def generate_data(observation_smat, missing_prob, consecutive, seed): nobs = observation_smat.shape[0] data = observation_smat.data ptr = observation_smat.indptr output = [] missing_seg = [] for i in range(nobs): seed_i = None if seed is None else seed + i tlen = ptr[i+1] - ptr[i] - 2 if tlen < 2: continue full_trajectory = data[ptr[i]:ptr[i+1]] observed_seq_i, missing_seg_i = get_random_missing_obs_idxs_from_a_trajectory( full_trajectory, tlen, missing_prob, consecutive, seed_i) missing_seg.extend(missing_seg_i) if len(observed_seq_i) == 0: continue observed_seq_i_data = np.concatenate(observed_seq_i) observed_seq_i_len = np.array(list((map(len, observed_seq_i)))) output.append((observed_seq_i_data, observed_seq_i_len, missing_seg)) missing_seg = [] return output @memory.cache def load_data(path="dataset"): incidence = sparse.load_npz(f'{path}/incidence.npz') lefturn = sparse.load_npz(f'{path}/lefturn.npz') uturn = sparse.load_npz(f'{path}/uturn.npz') travel_time = sparse.load_npz(f'{path}/traveltime.npz') observation = sparse.load_npz(f'{path}/observation.npz') nlink = incidence.shape[0] link_size = load_link_size_data(f'{path}/LS', nlink) return observation, incidence, lefturn, uturn, travel_time, link_size def convert_to_sparse_mat(data, square=False, dim=0): ndims = [int(np.max(data[:, 0])), int(np.max(data[:, 1]))] if square and ndims[0] != ndims[1]: if ndims[1-dim] > ndims[dim]: m = sparse.csr_matrix((data[:, 2], (data[:, 0]-1, data[:, 1]-1)), ndims) ndims[1-dim] = ndims[dim] m = m[:ndims[0], :ndims[1]] else: ndims[1-dim] = ndims[dim] m = sparse.csr_matrix((data[:, 2], (data[:, 0]-1, data[:, 1]-1)), ndims) else: m = sparse.csr_matrix((data[:, 2], (data[:, 0]-1, data[:, 1]-1)), ndims) return m def append_zero_to_csr_matrix(csr_mat, n_zero_col=1, n_zero_row=1): indptr = np.concatenate([csr_mat.indptr, [csr_mat.indptr[-1]] * n_zero_row]) zero_appended_csr_mat = sparse.csr_matrix((csr_mat.data, csr_mat.indices, indptr), shape=(csr_mat.shape[0] + n_zero_row, csr_mat.shape[1] + n_zero_col)) return zero_appended_csr_mat def load_link_size(filename, nlink): data = np.loadtxt(filename) smat = convert_to_sparse_mat(data, True, 0) row, col = smat.shape smat = append_zero_to_csr_matrix(smat, nlink-row, nlink-col) return smat @memory.cache def load_link_size_data(link_size_folder, nlink): all_LS = [] for filename in os.listdir(link_size_folder): if filename.endswith(".txt"): path = f"{link_size_folder}/{filename}" smat = load_link_size(path, nlink) all_LS.append(smat) return all_LS @memory.cache(ignore=['LS', 'OL_indices']) def load_beta_ls(LS, OL_indices, nlink): beta_LS = [] for ls in tqdm(LS, "load_beta_ls"): ls = scipy_sparse_to_tensor(ls, [nlink, nlink]).to_dense() ls = ls[OL_indices[1], OL_indices[2]] beta_LS.append(ls) beta_LS = torch.stack(beta_LS) return beta_LS def get_random_missing_obs_idxs_from_a_trajectory(full_trajectory, tlen, missing_prob, consecutive=False, seed=None): all_observed_seq, all_missing_seg = get_random_observed_missing_idxs(tlen, missing_prob, shift=1, consecutive=consecutive, seed=seed) dummy = full_trajectory[0] dest = full_trajectory[tlen] for i, observed_seq in enumerate(all_observed_seq): observed_seq = np.concatenate([[dummy], full_trajectory[observed_seq], [dest], [dummy]]) all_observed_seq[i] = observed_seq for i, missing_seg in enumerate(all_missing_seg): missing_seg = np.concatenate([[dummy], full_trajectory[missing_seg], [dest], [dummy]]) all_missing_seg[i] = missing_seg return all_observed_seq, all_missing_seg def get_random_observed_missing_idxs(tlen, missing_prob, shift=0, consecutive=False, seed=None): if seed is not None: np.random.seed(seed) bernoulli_seq = np.concatenate([[1.0], np.random.rand(tlen-2), [1.0]]) observed_missing_seq = np.zeros_like(bernoulli_seq) observed_missing_seq[bernoulli_seq >= missing_prob] = 1.0 if consecutive: n_missing = int(len(observed_missing_seq) - observed_missing_seq.sum()) start_missing_idx = np.random.randint(1, len(observed_missing_seq) - n_missing) observed_missing_seq = np.ones_like(observed_missing_seq) observed_missing_seq[start_missing_idx:start_missing_idx+n_missing] = 0.0 all_observed_seq = [] all_missing_seg = [] observed_seq = [0 + shift] for i in range(1, len(observed_missing_seq)): if observed_missing_seq[i]: shifted_i = i + shift if shifted_i - observed_seq[-1] == 1: observed_seq.append(shifted_i) else: if len(observed_seq) > 1: all_observed_seq.append(np.array(observed_seq)) all_missing_seg.append(np.array([observed_seq[-1], shifted_i])) observed_seq = [shifted_i] if len(observed_seq) > 1: all_observed_seq.append(np.array(observed_seq)) return all_observed_seq, all_missing_seg def get_csr_from_data_length(data, lengths): ncol = np.max(lengths) nrow = len(lengths) indices = np.concatenate([np.array(range(l)) for l in lengths]) indptr = np.cumsum(np.concatenate([[0], lengths])) csr_mat = sparse.csr_matrix((data, indices, indptr), shape=(nrow, ncol)) return csr_mat def form_B(nlink, dummy_incidence_smat): n_distinct_dest = dummy_incidence_smat.shape[1] new_indptr = np.concatenate([dummy_incidence_smat.indptr, [dummy_incidence_smat.indptr[-1]]]) t = sparse.csr_matrix((dummy_incidence_smat.data, dummy_incidence_smat.indices, new_indptr), shape=(nlink + 1, n_distinct_dest)).toarray() b = np.zeros([nlink + 1, n_distinct_dest]) b[nlink, :] = 1.0 B = t + b B = torch.FloatTensor(B).unsqueeze(0) return B def form_sparse_M(ids, ireward_data, mu, nlink): ireward_data = ireward_data / mu[ids[1]] M_data = torch.exp(ireward_data).cpu() sparse_M_shape = (1, nlink + 1, nlink + 1) sparse_M = torch.sparse_coo_tensor(ids, M_data, sparse_M_shape) ids = torch.stack([ids[0], ids[2], ids[1]]) # sparse_M_shape = (nlink + 1, nlink + 1) sparse_M_transpose = torch.sparse_coo_tensor(ids, M_data, sparse_M_shape) return sparse_M, sparse_M_transpose def form_M(ids, ireward_data, mu, nlink): ireward_data = ireward_data / mu[ids[1]] M_data = torch.exp(ireward_data) M_shape = (nlink + 1, nlink + 1) M = torch.zeros(M_shape, device=M_data.device) M[ids[1], ids[2]] = M_data return M def scipy_sparse_to_tensor(data, size=None) -> torch.FloatTensor: data = data.tocoo() row = data.row.tolist() col = data.col.tolist() if size is not None: indices = np.stack([row, col]) data = torch.sparse_coo_tensor( torch.LongTensor(indices), torch.FloatTensor(data.data), size ) else: indices = np.stack([np.zeros_like(row), row, col]) data = torch.sparse_coo_tensor( torch.LongTensor(indices), torch.FloatTensor(data.data) ) return data def get_Z(M, B, I): if not M.is_sparse: A = I.to_dense()[0,...].to(M.device) - M B = B.squeeze(0).double().to(M.device) Z = torch.linalg.solve(A.double(), B) else: A = I - M Z = Solve.apply(A, B) Z = torch.squeeze(Z, 0) return Z def get_V(Z, mu): tmp = torch.log(Z) Z = torch.where(torch.isfinite(tmp), tmp, torch.ones_like(tmp)).type(mu.dtype) V = torch.unsqueeze(mu, -1) * Z return V def get_loglikelihood(nlink, V, ireward_smat, mu, mu_cpu, init_links, end_links, links, sucessors_no_dummy, dummy_links, path_probs=None, link_probs=None): v = ireward_smat[links, sucessors_no_dummy] / mu[links] V_start = V[init_links, dummy_links - nlink] / mu_cpu[init_links] V_end = V[end_links, dummy_links - nlink]/ mu_cpu[end_links] if path_probs is not None and link_probs is not None: path_probs = torch.tensor(path_probs, dtype=V.dtype, device=V.device) link_probs = torch.tensor(link_probs, dtype=v.dtype, device=v.device) v = v * link_probs V_start = V_start * path_probs V_end = V_end * path_probs V_start = V_start.type(v.dtype) V_end = V_end.type(v.dtype) loglikelihood = torch.sum(v) - torch.sum(V_start) + torch.sum(V_end) return loglikelihood def compute_Q(M, i, db): Q = M * torch.sparse_coo_tensor(i, db, M.size(), dtype=M.dtype) return Q def compute_P(I, Q, D): if Q is None: return P = Solve.apply(I - Q, D).type(Q.dtype) return P def compute_all_Q(M, Z): i = M._indices() d = torch.ones(M._nnz(), device=M.device, dtype=Z.dtype) d = d * Z[:, i[1, :]] d = d / Z[:, i[2, :]] all_Q = [compute_Q(M, i, db) for db in tqdm(d, 'compute_Q', leave=False)] return all_Q def compute_all_P(I, all_Q, all_D): missing_P_transposes = [compute_P(I, Q, D) for Q, D in tqdm(zip(all_Q, all_D), 'compute_P', leave=False)] return missing_P_transposes def get_log_path(logdir, method, seed, missing_prob, train_mu, use_LS, use_LS_for_beta): os.makedirs(logdir, exist_ok=True) logdir = os.path.join(logdir, f"{method}") os.makedirs(logdir, exist_ok=True) logdir = os.path.join(logdir, f"seed_{seed}") os.makedirs(logdir, exist_ok=True) logdir = os.path.join(logdir, f"prob_{missing_prob}") os.makedirs(logdir, exist_ok=True) logdir = os.path.join(logdir, "with_mu" if train_mu else "without_mu") os.makedirs(logdir, exist_ok=True) if use_LS: if use_LS_for_beta: logdir = os.path.join(logdir, "with_LS_beta") else: logdir = os.path.join(logdir, "with_LS") else: logdir = os.path.join(logdir, "without_LS") return logdir
[ "numpy.random.seed", "solve.Solve.apply", "os.path.join", "joblib.Memory", "numpy.zeros_like", "torch.FloatTensor", "torch.squeeze", "torch.exp", "numpy.max", "numpy.loadtxt", "torch.zeros", "torch.log", "numpy.stack", "tqdm.tqdm", "numpy.ones_like", "torch.sparse_coo_tensor", "scipy...
[((167, 199), 'joblib.Memory', 'Memory', (['"""__pycache__"""'], {'verbose': '(0)'}), "('__pycache__', verbose=0)\n", (173, 199), False, 'from joblib import Memory\n'), ((1204, 1244), 'scipy.sparse.load_npz', 'sparse.load_npz', (['f"""{path}/incidence.npz"""'], {}), "(f'{path}/incidence.npz')\n", (1219, 1244), True, 'import scipy.sparse as sparse\n'), ((1259, 1297), 'scipy.sparse.load_npz', 'sparse.load_npz', (['f"""{path}/lefturn.npz"""'], {}), "(f'{path}/lefturn.npz')\n", (1274, 1297), True, 'import scipy.sparse as sparse\n'), ((1310, 1346), 'scipy.sparse.load_npz', 'sparse.load_npz', (['f"""{path}/uturn.npz"""'], {}), "(f'{path}/uturn.npz')\n", (1325, 1346), True, 'import scipy.sparse as sparse\n'), ((1365, 1406), 'scipy.sparse.load_npz', 'sparse.load_npz', (['f"""{path}/traveltime.npz"""'], {}), "(f'{path}/traveltime.npz')\n", (1380, 1406), True, 'import scipy.sparse as sparse\n'), ((1425, 1467), 'scipy.sparse.load_npz', 'sparse.load_npz', (['f"""{path}/observation.npz"""'], {}), "(f'{path}/observation.npz')\n", (1440, 1467), True, 'import scipy.sparse as sparse\n'), ((2312, 2379), 'numpy.concatenate', 'np.concatenate', (['[csr_mat.indptr, [csr_mat.indptr[-1]] * n_zero_row]'], {}), '([csr_mat.indptr, [csr_mat.indptr[-1]] * n_zero_row])\n', (2326, 2379), True, 'import numpy as np\n'), ((2408, 2541), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['(csr_mat.data, csr_mat.indices, indptr)'], {'shape': '(csr_mat.shape[0] + n_zero_row, csr_mat.shape[1] + n_zero_col)'}), '((csr_mat.data, csr_mat.indices, indptr), shape=(csr_mat.\n shape[0] + n_zero_row, csr_mat.shape[1] + n_zero_col))\n', (2425, 2541), True, 'import scipy.sparse as sparse\n'), ((2619, 2639), 'numpy.loadtxt', 'np.loadtxt', (['filename'], {}), '(filename)\n', (2629, 2639), True, 'import numpy as np\n'), ((2896, 2924), 'os.listdir', 'os.listdir', (['link_size_folder'], {}), '(link_size_folder)\n', (2906, 2924), False, 'import os\n'), ((3229, 3253), 'tqdm.tqdm', 'tqdm', (['LS', '"""load_beta_ls"""'], {}), "(LS, 'load_beta_ls')\n", (3233, 3253), False, 'from tqdm import tqdm\n'), ((3409, 3429), 'torch.stack', 'torch.stack', (['beta_LS'], {}), '(beta_LS)\n', (3420, 3429), False, 'import torch\n'), ((4456, 4484), 'numpy.zeros_like', 'np.zeros_like', (['bernoulli_seq'], {}), '(bernoulli_seq)\n', (4469, 4484), True, 'import numpy as np\n'), ((5621, 5636), 'numpy.max', 'np.max', (['lengths'], {}), '(lengths)\n', (5627, 5636), True, 'import numpy as np\n'), ((5798, 5860), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['(data, indices, indptr)'], {'shape': '(nrow, ncol)'}), '((data, indices, indptr), shape=(nrow, ncol))\n', (5815, 5860), True, 'import scipy.sparse as sparse\n'), ((5991, 6076), 'numpy.concatenate', 'np.concatenate', (['[dummy_incidence_smat.indptr, [dummy_incidence_smat.indptr[-1]]]'], {}), '([dummy_incidence_smat.indptr, [dummy_incidence_smat.indptr[-1]]]\n )\n', (6005, 6076), True, 'import numpy as np\n'), ((6223, 6261), 'numpy.zeros', 'np.zeros', (['[nlink + 1, n_distinct_dest]'], {}), '([nlink + 1, n_distinct_dest])\n', (6231, 6261), True, 'import numpy as np\n'), ((6553, 6605), 'torch.sparse_coo_tensor', 'torch.sparse_coo_tensor', (['ids', 'M_data', 'sparse_M_shape'], {}), '(ids, M_data, sparse_M_shape)\n', (6576, 6605), False, 'import torch\n'), ((6616, 6653), 'torch.stack', 'torch.stack', (['[ids[0], ids[2], ids[1]]'], {}), '([ids[0], ids[2], ids[1]])\n', (6627, 6653), False, 'import torch\n'), ((6725, 6777), 'torch.sparse_coo_tensor', 'torch.sparse_coo_tensor', (['ids', 'M_data', 'sparse_M_shape'], {}), '(ids, M_data, sparse_M_shape)\n', (6748, 6777), False, 'import torch\n'), ((6919, 6942), 'torch.exp', 'torch.exp', (['ireward_data'], {}), '(ireward_data)\n', (6928, 6942), False, 'import torch\n'), ((6988, 7030), 'torch.zeros', 'torch.zeros', (['M_shape'], {'device': 'M_data.device'}), '(M_shape, device=M_data.device)\n', (6999, 7030), False, 'import torch\n'), ((7973, 7985), 'torch.log', 'torch.log', (['Z'], {}), '(Z)\n', (7982, 7985), False, 'import torch\n'), ((9703, 9737), 'os.makedirs', 'os.makedirs', (['logdir'], {'exist_ok': '(True)'}), '(logdir, exist_ok=True)\n', (9714, 9737), False, 'import os\n'), ((9751, 9784), 'os.path.join', 'os.path.join', (['logdir', 'f"""{method}"""'], {}), "(logdir, f'{method}')\n", (9763, 9784), False, 'import os\n'), ((9789, 9823), 'os.makedirs', 'os.makedirs', (['logdir'], {'exist_ok': '(True)'}), '(logdir, exist_ok=True)\n', (9800, 9823), False, 'import os\n'), ((9837, 9873), 'os.path.join', 'os.path.join', (['logdir', 'f"""seed_{seed}"""'], {}), "(logdir, f'seed_{seed}')\n", (9849, 9873), False, 'import os\n'), ((9878, 9912), 'os.makedirs', 'os.makedirs', (['logdir'], {'exist_ok': '(True)'}), '(logdir, exist_ok=True)\n', (9889, 9912), False, 'import os\n'), ((9926, 9970), 'os.path.join', 'os.path.join', (['logdir', 'f"""prob_{missing_prob}"""'], {}), "(logdir, f'prob_{missing_prob}')\n", (9938, 9970), False, 'import os\n'), ((9975, 10009), 'os.makedirs', 'os.makedirs', (['logdir'], {'exist_ok': '(True)'}), '(logdir, exist_ok=True)\n', (9986, 10009), False, 'import os\n'), ((10023, 10084), 'os.path.join', 'os.path.join', (['logdir', "('with_mu' if train_mu else 'without_mu')"], {}), "(logdir, 'with_mu' if train_mu else 'without_mu')\n", (10035, 10084), False, 'import os\n'), ((10089, 10123), 'os.makedirs', 'os.makedirs', (['logdir'], {'exist_ok': '(True)'}), '(logdir, exist_ok=True)\n', (10100, 10123), False, 'import os\n'), ((918, 948), 'numpy.concatenate', 'np.concatenate', (['observed_seq_i'], {}), '(observed_seq_i)\n', (932, 948), True, 'import numpy as np\n'), ((2148, 2220), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['(data[:, 2], (data[:, 0] - 1, data[:, 1] - 1))', 'ndims'], {}), '((data[:, 2], (data[:, 0] - 1, data[:, 1] - 1)), ndims)\n', (2165, 2220), True, 'import scipy.sparse as sparse\n'), ((3849, 3922), 'numpy.concatenate', 'np.concatenate', (['[[dummy], full_trajectory[observed_seq], [dest], [dummy]]'], {}), '([[dummy], full_trajectory[observed_seq], [dest], [dummy]])\n', (3863, 3922), True, 'import numpy as np\n'), ((4042, 4114), 'numpy.concatenate', 'np.concatenate', (['[[dummy], full_trajectory[missing_seg], [dest], [dummy]]'], {}), '([[dummy], full_trajectory[missing_seg], [dest], [dummy]])\n', (4056, 4114), True, 'import numpy as np\n'), ((4333, 4353), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (4347, 4353), True, 'import numpy as np\n'), ((4766, 4800), 'numpy.ones_like', 'np.ones_like', (['observed_missing_seq'], {}), '(observed_missing_seq)\n', (4778, 4800), True, 'import numpy as np\n'), ((5752, 5782), 'numpy.concatenate', 'np.concatenate', (['[[0], lengths]'], {}), '([[0], lengths])\n', (5766, 5782), True, 'import numpy as np\n'), ((7270, 7290), 'numpy.stack', 'np.stack', (['[row, col]'], {}), '([row, col])\n', (7278, 7290), True, 'import numpy as np\n'), ((7881, 7898), 'solve.Solve.apply', 'Solve.apply', (['A', 'B'], {}), '(A, B)\n', (7892, 7898), False, 'from solve import Solve\n'), ((7911, 7930), 'torch.squeeze', 'torch.squeeze', (['Z', '(0)'], {}), '(Z, 0)\n', (7924, 7930), False, 'import torch\n'), ((8077, 8100), 'torch.unsqueeze', 'torch.unsqueeze', (['mu', '(-1)'], {}), '(mu, -1)\n', (8092, 8100), False, 'import torch\n'), ((8550, 8606), 'torch.tensor', 'torch.tensor', (['path_probs'], {'dtype': 'V.dtype', 'device': 'V.device'}), '(path_probs, dtype=V.dtype, device=V.device)\n', (8562, 8606), False, 'import torch\n'), ((8628, 8684), 'torch.tensor', 'torch.tensor', (['link_probs'], {'dtype': 'v.dtype', 'device': 'v.device'}), '(link_probs, dtype=v.dtype, device=v.device)\n', (8640, 8684), False, 'import torch\n'), ((8911, 8927), 'torch.sum', 'torch.sum', (['V_end'], {}), '(V_end)\n', (8920, 8927), False, 'import torch\n'), ((10319, 10353), 'os.path.join', 'os.path.join', (['logdir', '"""without_LS"""'], {}), "(logdir, 'without_LS')\n", (10331, 10353), False, 'import os\n'), ((1702, 1720), 'numpy.max', 'np.max', (['data[:, 0]'], {}), '(data[:, 0])\n', (1708, 1720), True, 'import numpy as np\n'), ((1727, 1745), 'numpy.max', 'np.max', (['data[:, 1]'], {}), '(data[:, 1])\n', (1733, 1745), True, 'import numpy as np\n'), ((1842, 1914), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['(data[:, 2], (data[:, 0] - 1, data[:, 1] - 1))', 'ndims'], {}), '((data[:, 2], (data[:, 0] - 1, data[:, 1] - 1)), ndims)\n', (1859, 1914), True, 'import scipy.sparse as sparse\n'), ((2057, 2129), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['(data[:, 2], (data[:, 0] - 1, data[:, 1] - 1))', 'ndims'], {}), '((data[:, 2], (data[:, 0] - 1, data[:, 1] - 1)), ndims)\n', (2074, 2129), True, 'import scipy.sparse as sparse\n'), ((4397, 4421), 'numpy.random.rand', 'np.random.rand', (['(tlen - 2)'], {}), '(tlen - 2)\n', (4411, 4421), True, 'import numpy as np\n'), ((5495, 5517), 'numpy.array', 'np.array', (['observed_seq'], {}), '(observed_seq)\n', (5503, 5517), True, 'import numpy as np\n'), ((6080, 6208), 'scipy.sparse.csr_matrix', 'sparse.csr_matrix', (['(dummy_incidence_smat.data, dummy_incidence_smat.indices, new_indptr)'], {'shape': '(nlink + 1, n_distinct_dest)'}), '((dummy_incidence_smat.data, dummy_incidence_smat.indices,\n new_indptr), shape=(nlink + 1, n_distinct_dest))\n', (6097, 6208), True, 'import scipy.sparse as sparse\n'), ((6306, 6326), 'torch.FloatTensor', 'torch.FloatTensor', (['B'], {}), '(B)\n', (6323, 6326), False, 'import torch\n'), ((6461, 6484), 'torch.exp', 'torch.exp', (['ireward_data'], {}), '(ireward_data)\n', (6470, 6484), False, 'import torch\n'), ((7343, 7368), 'torch.LongTensor', 'torch.LongTensor', (['indices'], {}), '(indices)\n', (7359, 7368), False, 'import torch\n'), ((7382, 7410), 'torch.FloatTensor', 'torch.FloatTensor', (['data.data'], {}), '(data.data)\n', (7399, 7410), False, 'import torch\n'), ((7560, 7585), 'torch.LongTensor', 'torch.LongTensor', (['indices'], {}), '(indices)\n', (7576, 7585), False, 'import torch\n'), ((7599, 7627), 'torch.FloatTensor', 'torch.FloatTensor', (['data.data'], {}), '(data.data)\n', (7616, 7627), False, 'import torch\n'), ((8875, 8887), 'torch.sum', 'torch.sum', (['v'], {}), '(v)\n', (8884, 8887), False, 'import torch\n'), ((8890, 8908), 'torch.sum', 'torch.sum', (['V_start'], {}), '(V_start)\n', (8899, 8908), False, 'import torch\n'), ((9126, 9147), 'solve.Solve.apply', 'Solve.apply', (['(I - Q)', 'D'], {}), '(I - Q, D)\n', (9137, 9147), False, 'from solve import Solve\n'), ((9378, 9411), 'tqdm.tqdm', 'tqdm', (['d', '"""compute_Q"""'], {'leave': '(False)'}), "(d, 'compute_Q', leave=False)\n", (9382, 9411), False, 'from tqdm import tqdm\n'), ((10188, 10224), 'os.path.join', 'os.path.join', (['logdir', '"""with_LS_beta"""'], {}), "(logdir, 'with_LS_beta')\n", (10200, 10224), False, 'import os\n'), ((10260, 10291), 'os.path.join', 'os.path.join', (['logdir', '"""with_LS"""'], {}), "(logdir, 'with_LS')\n", (10272, 10291), False, 'import os\n'), ((7477, 7495), 'numpy.zeros_like', 'np.zeros_like', (['row'], {}), '(row)\n', (7490, 7495), True, 'import numpy as np\n'), ((8006, 8025), 'torch.isfinite', 'torch.isfinite', (['tmp'], {}), '(tmp)\n', (8020, 8025), False, 'import torch\n'), ((8032, 8052), 'torch.ones_like', 'torch.ones_like', (['tmp'], {}), '(tmp)\n', (8047, 8052), False, 'import torch\n'), ((5349, 5388), 'numpy.array', 'np.array', (['[observed_seq[-1], shifted_i]'], {}), '([observed_seq[-1], shifted_i])\n', (5357, 5388), True, 'import numpy as np\n'), ((5286, 5308), 'numpy.array', 'np.array', (['observed_seq'], {}), '(observed_seq)\n', (5294, 5308), True, 'import numpy as np\n')]
from ..layers import Module import numpy as np from ..autograd import Tensor, zeros, zeros_like from ..autograd import Parameter from typing import Generator def tensor2array(var): assert isinstance(var,Tensor),"必须传入一个Tensor" dim = len(var.shape) _tmp = [] class Optimizer: def __init__(self, lr:float, module:Module): self.lr = lr self.module = module self.iteration = 0 def step(self): """ 更新參數 optimizer.step() """ raise NotImplementedError("Overrive this method before calling!") class SGD(Optimizer): """ 随机梯度下降 Stochastic Gradient Descent """ def __init__(self, module:Module, lr: float = 1e-3) -> None: super(SGD,self).__init__(lr, module) def step(self) -> None: self.iteration += 1 for parameter in self.module.parameters(): v = parameter.grad parameter -= v * self.lr class Momentum(Optimizer): """ 动量梯度下降 Momentum """ def __init__(self, module: 'Module', lr: float = 1e-3, momentum: float = 0.9): self.module = module self.lr = lr self.momentum = momentum self.v = [] for parameter in self.module.parameters(): self.v.append(zeros(*parameter.data.shape)) def step(self): for i, parameter in enumerate(self.module.parameters()): v = self.momentum * self.v[i] + (1 - self.momentum) * parameter.grad self.v[i] = v parameter -= self.lr * v class RMSProp(Optimizer): def __init__(self, module: 'Module', lr: float = 1e-3, beta: float = 0.999, eps: float = 1e-7) -> None: """ Module -> 神经网络模型 lr -> 学习率 beta -> 权重衰减速率 MATH: s = beta * 累计平方梯度 + (1 - beta) * 参数梯度 ** 2 eta = self.lr * 参数梯度 / sqrt(s + eps) 参数更新 -= eta """ self.module = module self.lr = lr self.beta = beta self.eps = eps # 小常数 1e-7 self.s = [] # 累计平方梯度 for parameter in self.module.parameters(): self.s.append(np.zeros_like(parameter.data)) def step(self): for i,parameter in enumerate(self.module.parameters()): s = self.beta * self.s[i] + (1-self.beta) * parameter.grad.data**2 self.s[i] = s eta = self.lr * parameter.grad.data / (np.sqrt(s + self.eps)) parameter -= eta class Adam(Optimizer): """ Adaptive Moment Estimation """ def __init__(self, module: 'Module', lr: float = 1e-3, betas:float=(0.9, 0.999),eps:float=1e-7) -> None: super(Adam,self).__init__(lr, module) self.betas = betas self.eps = eps self.v = [] self.s = [] for parameter in self.module.parameters(): self.v.append(np.zeros_like(parameter.data)) self.s.append(np.zeros_like(parameter.data)) def step(self) -> None: for i,parameter in enumerate(self.module.parameters()): v = self.betas[0] * self.v[i] + (1 - self.betas[0]) * parameter.grad.data s = self.betas[1] * self.s[i] + (1 - self.betas[1]) * parameter.grad.data ** 2 self.v[i], self.s[i] = v, s eta = self.lr * v/np.sqrt(s+self.eps) parameter -= eta
[ "numpy.zeros_like", "numpy.sqrt" ]
[((2179, 2208), 'numpy.zeros_like', 'np.zeros_like', (['parameter.data'], {}), '(parameter.data)\n', (2192, 2208), True, 'import numpy as np\n'), ((2451, 2472), 'numpy.sqrt', 'np.sqrt', (['(s + self.eps)'], {}), '(s + self.eps)\n', (2458, 2472), True, 'import numpy as np\n'), ((2902, 2931), 'numpy.zeros_like', 'np.zeros_like', (['parameter.data'], {}), '(parameter.data)\n', (2915, 2931), True, 'import numpy as np\n'), ((2959, 2988), 'numpy.zeros_like', 'np.zeros_like', (['parameter.data'], {}), '(parameter.data)\n', (2972, 2988), True, 'import numpy as np\n'), ((3331, 3352), 'numpy.sqrt', 'np.sqrt', (['(s + self.eps)'], {}), '(s + self.eps)\n', (3338, 3352), True, 'import numpy as np\n')]
import gensim import numpy as np from sklearn.base import BaseEstimator, ClassifierMixin class MeanW2VEmbeddingVectorizer(BaseEstimator, ClassifierMixin): def __init__(self): pass def fit(self, X, y=None): X = [val.split() for val in X.to_list()] self.model = gensim.models.Word2Vec(X, size=100) self.word2vec = dict(zip(self.model.wv.index2word, self.model.wv.vectors)) if self.word2vec: self.dim = next(iter(self.word2vec.values())).shape[0] else: self.dim = 0 return self def get_params(self, **params): return {} def transform(self, X): return np.array([ np.mean([self.word2vec[w] for w in words if w in self.word2vec] or [np.zeros(self.dim)], axis=0) for words in X ])
[ "numpy.zeros", "gensim.models.Word2Vec" ]
[((301, 336), 'gensim.models.Word2Vec', 'gensim.models.Word2Vec', (['X'], {'size': '(100)'}), '(X, size=100)\n', (323, 336), False, 'import gensim\n'), ((788, 806), 'numpy.zeros', 'np.zeros', (['self.dim'], {}), '(self.dim)\n', (796, 806), True, 'import numpy as np\n')]
import csv import time import tensorflow as tf import tensorflow.keras.models from tensorflow.keras.preprocessing.image import load_img,img_to_array from numpy import expand_dims from os import listdir def ladeBild(pfad): bild = load_img(path = pfad,color_mode = 'grayscale') array = img_to_array(bild) array = expand_dims(array,axis = 0) return array #Pfade Spektrogramme pfadMarvin = "D:\Bachelorarbeit\Spektrogramme_MarvinGo" pfadNoise = "D:\Bachelorarbeit\Spektrogramme_Noise" pfadStille = "D:\Bachelorarbeit\Spektrogramme_Stille" #dateilisten listeDatenMarvin = listdir(pfadMarvin)[-300:] listeDatenNoise = listdir(pfadNoise)[-300:] listeDatenStille = listdir(pfadStille)[-300:] #Tabellenkopfzeilen headerNoise = ["Input = Sprache","Sprache in %","Marvin Go in %","Stille in %","Inferenzdauer in ms"] headerMarvinGo = ["Input = Marvin Go","Sprache in %","Marvin Go in %","Stille in %","Inferenzdauer in ms"] headerStille = ["Input = Stille","Sprache in %","Marvin Go in %","Stille in %","Inferenzdauer in ms"] #Optimalwerte ZielZeileNoise = ["Zielwert",100,0,0,"N/A"] ZielZeileMarvin = ["Zielwert",0,100,0,"N/A"] ZielZeileStille = ["Zielwert",0,0,100,"N/A"] datenNoise = []#Input = Noise datenMarvin = []#Input = Marvin datenStille = []#Input = Stille ############################################################# # Berechnung Tensorflow # ############################################################# print("Starte Tensorflowinferenz\n") model = tensorflow.keras.models.load_model("model.h5") #input = Noise i = 0 for noise in listeDatenNoise: pruefling = ladeBild(pfadNoise+"/"+noise) start = time.time() ergebnis = model.predict(pruefling) zeit = time.time()-start tempNoise = round(ergebnis[0][0]*100,2) tempMarvin = round(ergebnis[0][1]*100,2) tempStille = round(ergebnis[0][2]*100,2) datenNoise.append(["Sample{}".format(i),tempNoise,tempMarvin,tempStille,zeit*1000]) i+=1 #input = Marvin i = 0 for marvin in listeDatenMarvin: pruefling = ladeBild(pfadMarvin+"/"+marvin) start = time.time() ergebnis = model.predict(pruefling) zeit = time.time()-start tempNoise = round(ergebnis[0][0]*100,2) tempMarvin = round(ergebnis[0][1]*100,2) tempStille = round(ergebnis[0][2]*100,2) datenMarvin.append(["Sample{}".format(i),tempNoise,tempMarvin,tempStille,zeit*1000]) i+=1 #input = Stille i = 0 for stille in listeDatenStille: pruefling = ladeBild(pfadStille+"/"+stille) start = time.time() ergebnis = model.predict(pruefling) zeit = time.time()-start tempNoise = round(ergebnis[0][0]*100,2) tempMarvin = round(ergebnis[0][1]*100,2) tempStille = round(ergebnis[0][2]*100,2) datenStille.append(["Sample{}".format(i),tempNoise,tempMarvin,tempStille,zeit*1000]) i+=1 print("Tensorflow Inferenz abgeschlossen\n") ############################################################# # CSV Tensorflow # ############################################################# with open('tf.csv', mode='w') as file: writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL,lineterminator = "\n") #Input = Sprache print("Sprache\n") writer.writerow(headerNoise) writer.writerow(ZielZeileNoise) writer.writerows(datenNoise) writer.writerow("") #Input = <NAME> print("Marvin\n") writer.writerow(headerMarvinGo) writer.writerow(ZielZeileMarvin) writer.writerows(datenMarvin) writer.writerow("") #Input = Stille print("Stille\n") writer.writerow(headerStille) writer.writerow(ZielZeileStille) writer.writerows(datenStille) writer.writerow("") file.close() datenNoise = []#Input = Noise datenMarvin = []#Input = Marvin datenStille = []#Input = Stille ############################################################# # Berechnung Tensorflow Lite # ############################################################# print("Starte Tensorflow Lite Inferenz\n") # Load TFLite model and allocate tensors. interpreter = tf.lite.Interpreter(model_path="model.tflite") interpreter.allocate_tensors() # Get input and output tensors. input_details = interpreter.get_input_details() output_details = interpreter.get_output_details() i = 0 for noise in listeDatenNoise: pruefling = ladeBild(pfadNoise+"/"+noise) start = time.time() interpreter.set_tensor(input_details[0]['index'], pruefling) interpreter.invoke() ergebnis = interpreter.get_tensor(output_details[0]['index']) zeit = time.time() - start tempNoise = round(ergebnis[0][0]*100,2) tempMarvin = round(ergebnis[0][1]*100,2) tempStille = round(ergebnis[0][2]*100,2) datenNoise.append(["Sample{}".format(i),tempNoise,tempMarvin,tempStille,zeit*1000]) i+=1 i = 0 for marvin in listeDatenMarvin: pruefling = ladeBild(pfadMarvin+"/"+marvin) start = time.time() interpreter.set_tensor(input_details[0]['index'], pruefling) interpreter.invoke() ergebnis = interpreter.get_tensor(output_details[0]['index']) zeit = time.time() - start tempNoise = round(ergebnis[0][0]*100,2) tempMarvin = round(ergebnis[0][1]*100,2) tempStille = round(ergebnis[0][2]*100,2) datenMarvin.append(["Sample{}".format(i),tempNoise,tempMarvin,tempStille,zeit*1000]) i+=1 i = 0 for stille in listeDatenStille: start = time.time() interpreter.set_tensor(input_details[0]['index'], pruefling) interpreter.invoke() ergebnis = interpreter.get_tensor(output_details[0]['index']) zeit = time.time() - start tempNoise = round(ergebnis[0][0]*100,2) tempMarvin = round(ergebnis[0][1]*100,2) tempStille = round(ergebnis[0][2]*100,2) datenStille.append(["Sample{}".format(i),tempNoise,tempMarvin,tempStille,zeit*1000]) i+=1 print("Tensorflow Lite Inferenz abgeschlossen\n") ############################################################# # CSV Tensorflow Lite # ############################################################# with open('tfLite.csv', mode='w') as file: writer = csv.writer(file, delimiter=';', quotechar='"', quoting=csv.QUOTE_MINIMAL,lineterminator = "\n") #Input = Sprache print("Sprache\n") writer.writerow(headerNoise) writer.writerow(ZielZeileNoise) writer.writerows(datenNoise) writer.writerow("") #Input = <NAME> print("Marvin\n") writer.writerow(headerMarvinGo) writer.writerow(ZielZeileMarvin) writer.writerows(datenMarvin) writer.writerow("") #Input = Stille print("Stille\n") writer.writerow(headerStille) writer.writerow(ZielZeileStille) writer.writerows(datenStille) writer.writerow("") file.close() print("CSV erstellen Abgeschlossen\n")
[ "csv.writer", "tensorflow.keras.preprocessing.image.img_to_array", "numpy.expand_dims", "time.time", "tensorflow.lite.Interpreter", "tensorflow.keras.preprocessing.image.load_img", "os.listdir" ]
[((4120, 4166), 'tensorflow.lite.Interpreter', 'tf.lite.Interpreter', ([], {'model_path': '"""model.tflite"""'}), "(model_path='model.tflite')\n", (4139, 4166), True, 'import tensorflow as tf\n'), ((234, 277), 'tensorflow.keras.preprocessing.image.load_img', 'load_img', ([], {'path': 'pfad', 'color_mode': '"""grayscale"""'}), "(path=pfad, color_mode='grayscale')\n", (242, 277), False, 'from tensorflow.keras.preprocessing.image import load_img, img_to_array\n'), ((293, 311), 'tensorflow.keras.preprocessing.image.img_to_array', 'img_to_array', (['bild'], {}), '(bild)\n', (305, 311), False, 'from tensorflow.keras.preprocessing.image import load_img, img_to_array\n'), ((324, 350), 'numpy.expand_dims', 'expand_dims', (['array'], {'axis': '(0)'}), '(array, axis=0)\n', (335, 350), False, 'from numpy import expand_dims\n'), ((586, 605), 'os.listdir', 'listdir', (['pfadMarvin'], {}), '(pfadMarvin)\n', (593, 605), False, 'from os import listdir\n'), ((631, 649), 'os.listdir', 'listdir', (['pfadNoise'], {}), '(pfadNoise)\n', (638, 649), False, 'from os import listdir\n'), ((676, 695), 'os.listdir', 'listdir', (['pfadStille'], {}), '(pfadStille)\n', (683, 695), False, 'from os import listdir\n'), ((1666, 1677), 'time.time', 'time.time', ([], {}), '()\n', (1675, 1677), False, 'import time\n'), ((2092, 2103), 'time.time', 'time.time', ([], {}), '()\n', (2101, 2103), False, 'import time\n'), ((2519, 2530), 'time.time', 'time.time', ([], {}), '()\n', (2528, 2530), False, 'import time\n'), ((3116, 3214), 'csv.writer', 'csv.writer', (['file'], {'delimiter': '""";"""', 'quotechar': '"""\\""""', 'quoting': 'csv.QUOTE_MINIMAL', 'lineterminator': '"""\n"""'}), '(file, delimiter=\';\', quotechar=\'"\', quoting=csv.QUOTE_MINIMAL,\n lineterminator=\'\\n\')\n', (3126, 3214), False, 'import csv\n'), ((4423, 4434), 'time.time', 'time.time', ([], {}), '()\n', (4432, 4434), False, 'import time\n'), ((4951, 4962), 'time.time', 'time.time', ([], {}), '()\n', (4960, 4962), False, 'import time\n'), ((5432, 5443), 'time.time', 'time.time', ([], {}), '()\n', (5441, 5443), False, 'import time\n'), ((6155, 6253), 'csv.writer', 'csv.writer', (['file'], {'delimiter': '""";"""', 'quotechar': '"""\\""""', 'quoting': 'csv.QUOTE_MINIMAL', 'lineterminator': '"""\n"""'}), '(file, delimiter=\';\', quotechar=\'"\', quoting=csv.QUOTE_MINIMAL,\n lineterminator=\'\\n\')\n', (6165, 6253), False, 'import csv\n'), ((1729, 1740), 'time.time', 'time.time', ([], {}), '()\n', (1738, 1740), False, 'import time\n'), ((2155, 2166), 'time.time', 'time.time', ([], {}), '()\n', (2164, 2166), False, 'import time\n'), ((2582, 2593), 'time.time', 'time.time', ([], {}), '()\n', (2591, 2593), False, 'import time\n'), ((4602, 4613), 'time.time', 'time.time', ([], {}), '()\n', (4611, 4613), False, 'import time\n'), ((5130, 5141), 'time.time', 'time.time', ([], {}), '()\n', (5139, 5141), False, 'import time\n'), ((5611, 5622), 'time.time', 'time.time', ([], {}), '()\n', (5620, 5622), False, 'import time\n')]
#***********************************************************************# # Copyright (C) 2010-2012 <NAME> # # # # This file is part of CVXPY # # # # CVXPY is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # CVXPY is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/>. # #***********************************************************************# import numpy as np import cvxopt as opt from ..defs import * from ..scalars import cvxpy_obj # Class definition class cvxpy_semidefinite_cone(object): """ | :math:`\{X \in \mathbb{R}^{n \\times n} \ | \ X = X^T, \ X \succeq 0 \} = \mathbb{S}_+^n`. """ # Method: __init__ def __init__(self): """ Class constructor. """ self.type = SET self.name = 'semidefinite_cone' self.expansion_type = SDC # Method: valid_shape def valid_shape(self,shape): return shape[0] == shape[1] # Method: __str__ def __str__(self): return self.name # Method: _construct def _construct(self,el,mp,n): m = int(el.shape[0]) G = opt.spmatrix(0.0,[],[],(m*m,n)) h = opt.matrix(0.0,(m*m,1)) for j in range(0,m,1): for i in range(0,m,1): if np.isscalar(el[i,j]): h[j*m+i,0] = el[i,j]*1. elif type(el[i,j]) is cvxpy_obj: h[j*m+i,0] = el[i,j].value*1. else: G[j*m+i,mp[el[i,j]]] = -1. return G,h,m # Create instance semidefinite_cone = cvxpy_semidefinite_cone()
[ "cvxopt.spmatrix", "numpy.isscalar", "cvxopt.matrix" ]
[((2082, 2119), 'cvxopt.spmatrix', 'opt.spmatrix', (['(0.0)', '[]', '[]', '(m * m, n)'], {}), '(0.0, [], [], (m * m, n))\n', (2094, 2119), True, 'import cvxopt as opt\n'), ((2126, 2153), 'cvxopt.matrix', 'opt.matrix', (['(0.0)', '(m * m, 1)'], {}), '(0.0, (m * m, 1))\n', (2136, 2153), True, 'import cvxopt as opt\n'), ((2235, 2256), 'numpy.isscalar', 'np.isscalar', (['el[i, j]'], {}), '(el[i, j])\n', (2246, 2256), True, 'import numpy as np\n')]
import os import tensorflow as tf import numpy as np from collections import Counter from itertools import chain embedding_dim = 100 fname = 'data/glove.6B.%dd.txt'%embedding_dim glove_index_dict = {} with open(fname, 'r') as fp: glove_symbols = len(fp.readlines()) glove_embedding_weights = np.empty((glove_symbols, embedding_dim)) print("the number of words",glove_symbols) with open(fname, 'r') as fp: i = 0 for ls in fp: ls = ls.strip().split() w = ls[0] glove_index_dict[w] = i glove_embedding_weights[i,:] = np.asarray(ls[1:],dtype=np.float32) i += 1 print(glove_embedding_weights[0:2])
[ "numpy.empty", "numpy.asarray" ]
[((302, 342), 'numpy.empty', 'np.empty', (['(glove_symbols, embedding_dim)'], {}), '((glove_symbols, embedding_dim))\n', (310, 342), True, 'import numpy as np\n'), ((566, 602), 'numpy.asarray', 'np.asarray', (['ls[1:]'], {'dtype': 'np.float32'}), '(ls[1:], dtype=np.float32)\n', (576, 602), True, 'import numpy as np\n')]
import numpy as np from turtle import * # Gravitational constant G = 6.67428e-11 # Distance scale SCALE = 1e-9 # A step dphi = 0.05 * 1 / np.pi class Simulation(Turtle): ''' Draws the orbit based on the parameters - mechanical energy, masses, and angular momentum. ''' def __init__(self, m, M, E, L, color): super(Simulation, self).__init__(visible=False) self.pencolor(color) print(1 + 2 * E * L**2 / (G**2 * M**2 * m**3)) self.e = np.sqrt(1 + 2 * E * L**2 / (G**2 * M**2 * m**3)) self.r0 = L**2 / (G * M * m**2) self.r = 0.0 self.phi = 0.0 def update_position(self): self.setpos(self.r * np.cos(self.phi), self.r * np.sin(self.phi)) def update_parameters(self): self.phi += dphi self.r = self.r0 / (1 + self.e * np.cos(self.phi)) * SCALE def run(self): self.penup() self.radians() while 1: self.update_parameters() self.update_position() self.dot(2, (0, 255, 186)) def run(planets): while 1: for p in planets: p.update_parameters() p.update_position() p.dot(2) def main(): radians() colormode(255) # screen = Screen() # screen.bgcolor('black') # # m = screen.numinput('Korbit', 'Enter the planet mass(kg): ') # M = screen.numinput('Korbit', 'Enter the central body mass(kg): ') # E = screen.numinput('Korbit', 'Enter the mechanical energy(J): ') # L = screen.numinput('Korbit', 'Enter the angular momentum(Js): ') # # sim = Simulation(m, M, E, L, (0, 255, 186)) # sim.run() earth = Simulation(6e24, 2e30, -2.6e33, 2.6e40, (0, 0, 255)) venus = Simulation(4.9e24, 2e30, -3.05e33, 7.4e39, (255, 0, 0)) run([earth, venus]) if __name__ == '__main__': main()
[ "numpy.sin", "numpy.cos", "numpy.sqrt" ]
[((496, 552), 'numpy.sqrt', 'np.sqrt', (['(1 + 2 * E * L ** 2 / (G ** 2 * M ** 2 * m ** 3))'], {}), '(1 + 2 * E * L ** 2 / (G ** 2 * M ** 2 * m ** 3))\n', (503, 552), True, 'import numpy as np\n'), ((691, 707), 'numpy.cos', 'np.cos', (['self.phi'], {}), '(self.phi)\n', (697, 707), True, 'import numpy as np\n'), ((718, 734), 'numpy.sin', 'np.sin', (['self.phi'], {}), '(self.phi)\n', (724, 734), True, 'import numpy as np\n'), ((837, 853), 'numpy.cos', 'np.cos', (['self.phi'], {}), '(self.phi)\n', (843, 853), True, 'import numpy as np\n')]
# coding: utf-8 # # Model setup # # here we set the model up and explain how it works # imports and load data # In[1]: # all of this is explained in notebook 0 get_ipython().run_line_magic('run', 'imports.py') from modelinter.preprocessing.imports_load_data import read_csvs, extract_arrays raw_data = read_csvs() arrays = extract_arrays(raw_data) # We'll simulate a portfolio of N stocks and N options. We'll model the price of stocks, and feed the output of this model to the model for options. # # ## Stocks model # # The model for **stocks** is a linear regression of their returns against S&P500: # # $r_{it} = \alpha_i + \beta_i I_t + \epsilon_{it} $. # # with: # # * $r_{it}$ - returns of stock $i$ at time $t$ # * $I_{t}$ - returns of the index $I$ (S&P500) at time $t$ # * $\alpha_i$ - zero order coefficient for stock $i$ # * $\beta_i$ - first-order coefficient for stock $i$ # * $\epsilon_{it}$ - residuals of the regression for stock $i$ at time $t$ # # We expect $\alpha_{i}$ to be negligible for stocks, therefore we should be able to approximate: # # $r_{it} \approx \beta_i I_t $ # # We'll call this the **A** model. A more accurate prediction would entail sampling from the distribution of these random variables: # # $r_{it} \approx \beta_i I_t + \epsilon_{it} $ # # where we assume that the $\epsilon$ terms are normally distributed, centered on zero $E[\epsilon_{it}] = 0$, and uncorrelated ($Cov[\epsilon_{it}, \epsilon_{jt}] = 0$ $\forall i \neq j $). We will call this the **B** model, and we'll evaluate it by estimating the standard deviation of the residuals of the regression, and sampling from a normal distribution with adequate parametrisation. # # Finally, an even better model, which we'll call the **C** model, would involve removing the assumption of uncorrelated residuals: $\Sigma_{ij} \equiv Cov[\epsilon_{it}, \epsilon_{jt}] \neq 0$. We will estimate this model by evaluating the covariance matrix $\Sigma_{ij}$ with the GLASSO algorithm. # # # ___ # # #### extrapolating forward in time # # this model, being evaluated on daily returns, will predict daily returns. We want to understand what happens on timescales that are characteristic of the CCAR scenario (~4 years). In order to do so, we will have to chain daily predictions. Let's suppose that we want to predict the returns of stock at time $T = D \Delta t$. We can write the returns on index $I$ at time $T$ as the sum of the returns on all days: # # $I_T = \prod_t^D (1 + I_t) \approx \sum_t^D I_t$ # # Mind that this formula works approximately for linear returns, while it's exact for log returns. Similarly for the stock: # # $r_T = \prod_t^D (1 + r_t) \approx \sum_t^D r_t \\ # = \sum_t^D (\beta_i I_{t} + \epsilon_{it}) = \beta_i I_T + \sum_t^D \epsilon_{it}$ # # This is important, because the rules for calculating uncertainty follow from it: # # $\sigma(r_T) = \sigma(\sum_t^D \epsilon_{it}) = \sqrt{D} \sigma(\epsilon_i)$ # # where we made the hypothesis that $\epsilon_{it}$ is a stationary process, i.e. $\epsilon_{it} = \epsilon_{i}$, and that it follows a normal distribution. # # ## Options model # # For the **options**, we'll consider one put option per stock, with moneyness ($S/K$) of 1.1, that ends in five years. We'll assume a risk free rate of return of 0.25%. The model will be the original black-scholes. # # $C(S_t, t) = N(d_1)S_t - N(d_2) Ke^{-r(T - t)} \\ # d_1 = \frac{1}{\sigma\sqrt{T - t}}\left[\ln\left(\frac{S_t}{K}\right) + \left(r + \frac{\sigma^2}{2}\right)(T - t)\right] \\ # d_2 = d_1 - \sigma\sqrt{T - t}$ # # with: # * $N(\cdot)$ is the cumulative distribution function of the standard normal distribution # * $\tau \equiv T - t$ is the time to maturity (expressed in years), with $T$ the maturity date, and $t$ current time # * $S$ is the spot price of the underlying asset # * $K$ is the strike price # * $r$ is the risk free rate (annual rate, expressed in terms of continuous compounding) # * $\sigma$ is the volatility of returns of the underlying asset # # and all values are intended to be calculated at time $t$. # # ___ # # We will model the volatility $\sigma$ with a linear regression on the VIX index similar to the one for the stocks: # # $\sigma_{it} = \eta_i + \theta_i J_t + \delta_{it} $ # # therefore we should have an **A** model like this: # # $\sigma_{it} \approx \eta_i + \theta_i J_t $, # # where $J_t$ is the VIX index. We will also define, in analogy with the stocks, an **B** model: # # $\sigma_{it} \approx \eta_i + \theta_i J_t + \delta_{it}$, # # where we consider the $\delta$ to be normally distributed with mean 0, and standard deviation measured from the residuals of the regression. Finally, we'll define a **C** model where $\Sigma_{ij} \equiv Cov[\delta_{it}, \delta_{jt}] \neq 0$. # # --- # # We won't use implied volatility $VI_t$ data directly to estimate the $\theta_i$ and parametrize the model. We will instead assume that realized future volatility $\sigma_{t+p}$ as a proxy for it, i.e. we assume: # # $VI_t \propto \sigma_{t+p}$. # # For this reason, we equivalently delayed VIX by $p=-10$ days, following the result of preliminary analysis. # # ___ # # #### extrapolating forward in time # # The model for implied volatilities doesn't predict returns, but volatilities directly. The value for implied volatility at time $T$ cannot be expressed as a composition of changes along time, therefore the uncertainty for the predictions doesn't increase over time: # # $std(\sigma_T) = std(\delta_i)$ # # and of course we made the implicit hypothesis the hypothesis that $\delta_{it}$ is a stationary process, i.e. $\delta_{it} = \delta_{i}$, and that it follows a normal distribution. # let's define the functions that evaluate the model. # ## Code review # All the code is in the modelinter.pgm module. let's go through it. # In[2]: from modelinter.models.pgm import BasePgmParams, StocksPgmParams, StocksPgm, StocksPgmA, StocksPgmB, StocksPgmC, OptionsPgm # the parameters of the PGM will be stored in an object of class `BasePgmParams`, that only has the logic for saving/loading the parameters and estimating GLASSO on the residuals # In[3]: view_code(BasePgmParams) # The realization of a PGM parameters object for the stocks model is a `StocksPgmParams` object. On initialization it estimates the parameters for the model from the regression, and then calculates GLASSO on the residuals. # In[4]: view_code(StocksPgmParams) # When predicting, we'll use a realization of the `StocksPgm` base class. This base class just contains the logic for initialization (it gets passed a `StocksPgmParams` when doing `__init__()`), and the part of the prediction logic that will be called by all subclasses. # In[5]: view_code(StocksPgm) # The actual realizations of `StocksPgm` are the three kinds of model A, B and C discussed both above and in the paper: `StocksPgmA`, `StocksPgmB` and `StocksPgmC`. # # `StocksPgmA` just takes the prediction method from the base class, and changes the signature a little: # In[6]: view_code(StocksPgmA) # `StocksPgmB` and `StocksPgmC`'s `predict()` methods instead take the base prediction and generate the residuals. # In[7]: view_code(StocksPgmB); view_code(StocksPgmC) # The options model is structured the same way, with # # * `BasePgmParams` # * `OptionsPgmParams` # * `OptionsPgm` # * `optionsPgmA` # * `optionsPgmB` # * `optionsPgmC` # # the logic in `OptionsPgm` is a bit more convoluted, though, because its `predict()` method contains the code to calculate options prices through the Black-Scholes formula, which is structured as two ugly nested loops. The logic for generating volatilities is instead found in the subclasses. # In[9]: view_code(OptionsPgm) # ## Test calculation # Now let's test that they actually work: # In[15]: #DefaultSettings is just a namespace containing some settings for eval_PGM from modelinter.models.calculations import eval_PGM, DefaultSettings #we'll also need a couple of constants from modelinter.models.constants import Const import numpy as np # In[11]: #val_pgm is instead a function that estimates all the model #parameters from the data: view_code(eval_PGM) # In[12]: #let's evaluate them models = eval_PGM(arrays, DefaultSettings) # In[13]: #does it work? #prediction for stocks (models.PGM_stock_A.predict(.01)[:20], models.PGM_stock_B.predict(.01)[:20], models.PGM_stock_C.predict(.01)[:20]) # In[19]: #let's set an arbitrary level for vix vix_set = np.mean(arrays.vix) #prediction for options ( models.PGM_options_A.predict( vix=vix_set, r=Const.RISK_FREE_RATE.value, strike_price = None, stocks_prices = arrays.stocks_p[-1], tau_i = [1]*arrays.stocks_p.shape[-1], flag_i = ['p']*arrays.stocks_p.shape[-1], moneyness_i=1.1, )[:20], models.PGM_options_B.predict( vix=vix_set, r=Const.RISK_FREE_RATE.value, strike_price = None, stocks_prices = arrays.stocks_p[-1], tau_i = [1]*arrays.stocks_p.shape[-1], flag_i = ['p']*arrays.stocks_p.shape[-1], moneyness_i=1.1, )[:20], models.PGM_options_C.predict( vix=vix_set, r=Const.RISK_FREE_RATE.value, strike_price = None, stocks_prices = arrays.stocks_p[-1], tau_i = [1]*arrays.stocks_p.shape[-1], flag_i = ['p']*arrays.stocks_p.shape[-1], moneyness_i=1.1, )[:20] )
[ "modelinter.preprocessing.imports_load_data.read_csvs", "modelinter.preprocessing.imports_load_data.extract_arrays", "numpy.mean", "modelinter.models.calculations.eval_PGM" ]
[((309, 320), 'modelinter.preprocessing.imports_load_data.read_csvs', 'read_csvs', ([], {}), '()\n', (318, 320), False, 'from modelinter.preprocessing.imports_load_data import read_csvs, extract_arrays\n'), ((330, 354), 'modelinter.preprocessing.imports_load_data.extract_arrays', 'extract_arrays', (['raw_data'], {}), '(raw_data)\n', (344, 354), False, 'from modelinter.preprocessing.imports_load_data import read_csvs, extract_arrays\n'), ((8305, 8338), 'modelinter.models.calculations.eval_PGM', 'eval_PGM', (['arrays', 'DefaultSettings'], {}), '(arrays, DefaultSettings)\n', (8313, 8338), False, 'from modelinter.models.calculations import eval_PGM, DefaultSettings\n'), ((8570, 8589), 'numpy.mean', 'np.mean', (['arrays.vix'], {}), '(arrays.vix)\n', (8577, 8589), True, 'import numpy as np\n')]
""" VCD (Video Content Description) library v4.3.1 Project website: http://vcd.vicomtech.org Copyright (C) 2021, Vicomtech (http://www.vicomtech.es/), (Spain) all rights reserved. VCD is a Python library to create and manage VCD content version 4.3.1. VCD is distributed under MIT License. See LICENSE. """ import os import sys sys.path.insert(0, "..") import screeninfo import cv2 as cv import numpy as np import math from vcd import core from vcd import types from vcd import utils from vcd import draw from vcd import scl from draw import vcd_draw_pinhole import matplotlib.pyplot as plt def simple_setup_4_cams_fisheye(): vcd = core.VCD() vcd.add_coordinate_system("vehicle-iso8855", cs_type=types.CoordinateSystemType.local_cs) # Let's build the cameras img_width_px = 1280 img_height_px = 966 cX = -0.302159995 cY = -3.44617009 ################################ # CAM_FRONT ################################ # Intrinsics # ------------------------------ # This matrix converts from scs to ics d_1x4 = np.array([333.437012, 0.307729989, 2.4235599, 11.0495005]) # Extrinsics # ------------------------------ #X-Z1-Z2 provided wrt z-down x-back y-left # to be applied z1xz2 x1 = ((72-180) * np.pi) / 180.0 z1 = ((90.70 - 180) * np.pi) / 180.0 z2 = -(-0.12 * np.pi) / 180.0 R_scs_wrt_lcs = utils.euler2R([z1, x1, z2], seq=utils.EulerSeq.ZXZ) # default is ZYX C_lcs = np.array([[3.9], # frontal part of the car [0.04], # centered in the symmetry axis of the car [0.6]]) # at some height over the ground P_scs_wrt_lcs = utils.create_pose(R_scs_wrt_lcs, C_lcs) vcd.add_stream(stream_name="CAM_FRONT", uri="", description="Virtual camera", stream_type=core.StreamType.camera) vcd.add_stream_properties(stream_name="CAM_FRONT", intrinsics=types.IntrinsicsFisheye( width_px=img_width_px, height_px=img_height_px, lens_coeffs_1x4=list(d_1x4.flatten()), center_x=cX, center_y=cY, fov_deg=0.0, radius_x=0.0, radius_y=0.0 ) ) vcd.add_coordinate_system("CAM_FRONT", cs_type=types.CoordinateSystemType.sensor_cs, parent_name="vehicle-iso8855", pose_wrt_parent=list(P_scs_wrt_lcs.flatten())) ################################ # CAM_REAR ################################ # This matrix converts from scs to ics d_1x4 = np.array([333.437012, 0.307729989, 2.4235599, 11.0495005]) # Extrinsics # ------------------------------ x1 = ((41-180) * np.pi) / 180.0 z1 = ((-90.05 - 180) * np.pi) / 180.0 z2 = -(-1.07 * np.pi) / 180.0 R_scs_wrt_lcs = utils.euler2R([z1, x1, z2], seq=utils.EulerSeq.ZXZ) # default is ZYX C_lcs = np.array([[-1.125], # frontal part of the car [-0.05], # centered in the symmetry axis of the car [0.8]]) # at some height over the ground P_scs_wrt_lcs = utils.create_pose(R_scs_wrt_lcs, C_lcs) vcd.add_stream(stream_name="CAM_REAR", uri="", description="Virtual camera", stream_type=core.StreamType.camera) vcd.add_stream_properties(stream_name="CAM_REAR", intrinsics=types.IntrinsicsFisheye( width_px=img_width_px, height_px=img_height_px, lens_coeffs_1x4=list(d_1x4.flatten()), center_x=cX, center_y=cY, fov_deg=0.0, radius_x=0.0, radius_y=0.0 ) ) vcd.add_coordinate_system("CAM_REAR", cs_type=types.CoordinateSystemType.sensor_cs, parent_name="vehicle-iso8855", pose_wrt_parent=list(P_scs_wrt_lcs.flatten())) ################################ # CAM_LEFT ################################ # This matrix converts from scs to ics d_1x4 = np.array([333.437012, 0.307729989, 2.4235599, 11.0495005]) # Extrinsics # ------------------------------ # Extrinsics (1/2): Rotation using yaw(Z), pitch(Y), roll(X). This is rotation of SCS wrt LCS x1 = ((14-180) * np.pi) / 180.0 z1 = ((-164-180) * np.pi) / 180.0 z2 = -(13.29 * np.pi) / 180.0 R_scs_wrt_lcs = utils.euler2R([z1, x1, z2], seq=utils.EulerSeq.ZXZ) # default is ZYX C_lcs = np.array([[2.2], # frontal part of the car [0.9], # centered in the symmetry axis of the car [0.9]]) # at some height over the ground P_scs_wrt_lcs = utils.create_pose(R_scs_wrt_lcs, C_lcs) vcd.add_stream(stream_name="CAM_LEFT", uri="", description="Virtual camera", stream_type=core.StreamType.camera) vcd.add_stream_properties(stream_name="CAM_LEFT", intrinsics=types.IntrinsicsFisheye( width_px=img_width_px, height_px=img_height_px, lens_coeffs_1x4=list(d_1x4.flatten()), center_x=cX, center_y=cY, fov_deg=0.0, radius_x=0.0, radius_y=0.0 ) ) vcd.add_coordinate_system("CAM_LEFT", cs_type=types.CoordinateSystemType.sensor_cs, parent_name="vehicle-iso8855", pose_wrt_parent=list(P_scs_wrt_lcs.flatten())) ################################ # CAM_RIGHT ################################ # This matrix converts from scs to ics d_1x4 = np.array([333.437012, 0.307729989, 2.4235599, 11.0495005]) # Extrinsics # ------------------------------ # Extrinsics (1/2): Rotation using yaw(Z), pitch(Y), roll(X). This is rotation of SCS wrt LCS x1 = ((14-180) * np.pi) / 180.0 z1 = ((-22.05 - 180) * np.pi) / 180.0 z2 = -(-6.6 * np.pi) / 180.0 R_scs_wrt_lcs = utils.euler2R([z1, x1, z2], seq=utils.EulerSeq.ZXZ) # default is ZYX C_lcs = np.array([[2.2], # frontal part of the car [-0.9], # centered in the symmetry axis of the car [0.9]]) # at some height over the ground P_scs_wrt_lcs = utils.create_pose(R_scs_wrt_lcs, C_lcs) vcd.add_stream(stream_name="CAM_RIGHT", uri="", description="Virtual camera", stream_type=core.StreamType.camera) vcd.add_stream_properties(stream_name="CAM_RIGHT", intrinsics=types.IntrinsicsFisheye( width_px=img_width_px, height_px=img_height_px, lens_coeffs_1x4=list(d_1x4.flatten()), center_x=cX, center_y=cY, fov_deg=0.0, radius_x=0.0, radius_y=0.0 ) ) vcd.add_coordinate_system("CAM_RIGHT", cs_type=types.CoordinateSystemType.sensor_cs, parent_name="vehicle-iso8855", pose_wrt_parent=list(P_scs_wrt_lcs.flatten())) return vcd def draw_scene(vcd): # Prepare objects scene = scl.Scene(vcd) # scl.Scene has functions to project images, transforms, etc. drawer_front = draw.Image(scene, "CAM_FRONT") drawer_rear = draw.Image(scene, "CAM_REAR") drawer_left = draw.Image(scene, "CAM_LEFT") drawer_right = draw.Image(scene, "CAM_RIGHT") frameInfoDrawer = draw.FrameInfoDrawer(vcd) setupViewer = draw.SetupViewer(scene, "vehicle-iso8855") # Class colormap colorMap = {'Car': (0, 0, 255), 'Van': (255, 0, 0), 'Truck': (127, 127, 0), 'Pedestrian': (0, 255, 0), 'Person_sitting': (0, 127, 127), 'Tram': (127, 0, 127), 'Misc': (127, 127, 127), 'DontCare': (255, 255, 255), 'Cyclist': (0, 127, 255), 'Ego-car': (0, 0, 0), 'Wall': (0, 0, 255), 'Ground': (0, 255, 0)} # Get the size of the screen screen = screeninfo.get_monitors()[0] # Draw the images img_width_px = 1280 img_height_px = 966 img_front = cv.imread('./png/front.jpg') img_rear = cv.imread('./png/rear.jpg') img_left = cv.imread('./png/left.jpg') img_right = cv.imread('./png/right.jpg') imageParams = draw.Image.Params(_colorMap=colorMap) drawer_front.draw(img_front, 0, _params=imageParams) drawer_rear.draw(img_rear, 0, _params=imageParams) drawer_left.draw(img_left, 0, _params=imageParams) drawer_right.draw(img_right, 0, _params=imageParams) # Undistort cam_front = scene.get_camera("CAM_FRONT") cam_rear = scene.get_camera("CAM_REAR") cam_left = scene.get_camera("CAM_LEFT") cam_right = scene.get_camera("CAM_RIGHT") img_front_und = cam_front.undistort_image(img_front) img_rear_und = cam_rear.undistort_image(img_rear) img_left_und = cam_left.undistort_image(img_left) img_right_und = cam_right.undistort_image(img_right) # Draw the text textImg = frameInfoDrawer.draw(0, cols=400, rows=img_height_px * 2, _params=imageParams) mosaic = np.vstack((np.hstack((img_front, img_right)), np.hstack((img_left, img_rear)))) cv.line(mosaic, (mosaic.shape[1] // 2, 0), (mosaic.shape[1] // 2, mosaic.shape[0]), (0, 0, 0), 3) cv.line(mosaic, (0, mosaic.shape[0] // 2), (mosaic.shape[1], mosaic.shape[0] // 2), (0, 0, 0), 3) mosaic_und = np.vstack((np.hstack((img_front_und, img_right_und)), np.hstack((img_left_und, img_rear_und)))) cv.line(mosaic_und, (mosaic_und.shape[1] // 2, 0), (mosaic_und.shape[1] // 2, mosaic_und.shape[0]), (0, 0, 0), 3) cv.line(mosaic_und, (0, mosaic_und.shape[0] // 2), (mosaic_und.shape[1], mosaic_und.shape[0] // 2), (0, 0, 0), 3) # Draw the top view topview_width = 1280 topview_height = 1280 ar = topview_width / topview_height rangeX = (-15.0, 15.0) rangeY = (-((rangeX[1] - rangeX[0]) / ar) / 2, ((rangeX[1] - rangeX[0]) / ar) / 2) topviewParams = draw.TopView.Params(colorMap=colorMap, topViewSize=(topview_width, topview_height), background_color=255, rangeX=rangeX, rangeY=rangeY, stepX=1.0, stepY=1.0, draw_grid=False) drawerTopView1 = draw.TopView(scene, "vehicle-iso8855", params=topviewParams) drawerTopView1.add_images({'CAM_LEFT': img_left, 'CAM_FRONT': img_front, 'CAM_REAR': img_rear, 'CAM_RIGHT': img_right}, frameNum=0) topView1 = drawerTopView1.draw(frameNum=0) cv.namedWindow("Cameras", cv.WINDOW_NORMAL) cv.imshow("Cameras", mosaic) cv.namedWindow("Cameras Undistorted", cv.WINDOW_NORMAL) cv.imshow("Cameras Undistorted", mosaic_und) cv.namedWindow("VCD info") cv.imshow("VCD info", textImg) cv.namedWindow("TopView iso8855") cv.imshow("TopView iso8855", topView1) cv.waitKey(1) fig1 = setupViewer.plot_setup() plt.show() def add_some_objects(vcd): ######################################### # Cuboids ######################################### uid1 = vcd.add_object(name="", semantic_type="Car", frame_value=0) cuboid1 = types.cuboid(name="box3D", val=(4.5, 3.5, 0.7, 0.0, 0.0, (90.0 * np.pi) / 180.0, 4.2, 1.8, 1.4), coordinate_system="vehicle-iso8855") vcd.add_object_data(uid1, cuboid1, frame_value=0) ######################################### # Points3d (Walls) ######################################### xm, ym, zm = utils.generate_grid(x_params=(0, 20, 21), y_params=(-20, 20, 41), z_params=(0, 0, 1)) points3d_4xN = utils.grid_as_4xN_points3d(xm, ym, zm) uid_wall_1 = vcd.add_object(name="ground_x_pos", semantic_type="Ground", frame_value=0) mat_wall = types.mat(name="wall", val=points3d_4xN.flatten().tolist(), channels=1, width=points3d_4xN.shape[1], height=points3d_4xN.shape[0], dataType='float', coordinate_system="vehicle-iso8855") # mat_wall.add_attribute(types.vec(name="color", # val=(255, 0, 0))) vcd.add_object_data(uid_wall_1, mat_wall, frame_value=0) xm, ym, zm = utils.generate_grid(x_params=(0, -20, 21), y_params=(-20, 20, 41), z_params=(0, 0, 1)) points3d_4xN = utils.grid_as_4xN_points3d(xm, ym, zm) uid_wall_2 = vcd.add_object(name="ground_x_neg", semantic_type="Ground", frame_value=0) mat_wall = types.mat(name="wall", val=points3d_4xN.flatten().tolist(), channels=1, width=points3d_4xN.shape[1], height=points3d_4xN.shape[0], dataType='float', coordinate_system="vehicle-iso8855") # mat_wall.add_attribute(types.vec(name="color", # val=(255, 255, 0))) vcd.add_object_data(uid_wall_2, mat_wall, frame_value=0) xm, ym, zm = utils.generate_grid(x_params=(20, 20, 1), y_params=(-20, 20, 41), z_params=(0, 2, 21)) points3d_4xN = utils.grid_as_4xN_points3d(xm, ym, zm) uid_wall_3 = vcd.add_object(name="wall_front", semantic_type="Wall", frame_value=0) mat_wall = types.mat(name="wall", val=points3d_4xN.flatten().tolist(), channels=1, width=points3d_4xN.shape[1], height=points3d_4xN.shape[0], dataType='float', coordinate_system="vehicle-iso8855") # mat_wall.add_attribute(types.vec(name="color", # val=(0, 255, 0))) vcd.add_object_data(uid_wall_3, mat_wall, frame_value=0) xm, ym, zm = utils.generate_grid(x_params=(-20, -20, 1), y_params=(-20, 20, 41), z_params=(0, 2, 21)) points3d_4xN = utils.grid_as_4xN_points3d(xm, ym, zm) uid_wall_4 = vcd.add_object(name="wall_rear", semantic_type="Wall", frame_value=0) mat_wall = types.mat(name="wall", val=points3d_4xN.flatten().tolist(), channels=1, width=points3d_4xN.shape[1], height=points3d_4xN.shape[0], dataType='float', coordinate_system="vehicle-iso8855") # mat_wall.add_attribute(types.vec(name="color", # val=(0, 255, 255))) vcd.add_object_data(uid_wall_4, mat_wall, frame_value=0) xm, ym, zm = utils.generate_grid(x_params=(-20, 20, 41), y_params=(20, 20, 1), z_params=(0, 2, 21)) points3d_4xN = utils.grid_as_4xN_points3d(xm, ym, zm) uid_wall_5 = vcd.add_object(name="wall_right", semantic_type="Wall", frame_value=0) mat_wall = types.mat(name="wall", val=points3d_4xN.flatten().tolist(), channels=1, width=points3d_4xN.shape[1], height=points3d_4xN.shape[0], dataType='float', coordinate_system="vehicle-iso8855") # mat_wall.add_attribute(types.vec(name="color", # val=(255, 0, 255))) vcd.add_object_data(uid_wall_5, mat_wall, frame_value=0) xm, ym, zm = utils.generate_grid(x_params=(-20, 20, 41), y_params=(-20, -20, 1), z_params=(0, 2, 21)) points3d_4xN = utils.grid_as_4xN_points3d(xm, ym, zm) uid_wall_6 = vcd.add_object(name="wall_left", semantic_type="Wall", frame_value=0) mat_wall = types.mat(name="wall", val=points3d_4xN.flatten().tolist(), channels=1, width=points3d_4xN.shape[1], height=points3d_4xN.shape[0], dataType='float', coordinate_system="vehicle-iso8855") # mat_wall.add_attribute(types.vec(name="color", # val=(255, 255, 0))) vcd.add_object_data(uid_wall_6, mat_wall, frame_value=0) ######################################### # Ego-vehicle ######################################### vcd.add_object(name="Ego-car", semantic_type="Ego-car", uid=str(-2)) cuboid_ego = types.cuboid(name="box3D", val=(1.35, 0.0, 0.736, 0.0, 0.0, 0.0, 4.765, 1.82, 1.47), coordinate_system="vehicle-iso8855") vcd.add_object_data(str(-2), cuboid_ego) return vcd if __name__ == '__main__': print("Running " + os.path.basename(__file__)) vcd = simple_setup_4_cams_fisheye() vcd = add_some_objects(vcd) # so let's add the same objects as in vcd_draw_pinhole draw_scene(vcd)
[ "vcd.draw.FrameInfoDrawer", "vcd.utils.grid_as_4xN_points3d", "vcd.draw.Image", "vcd.draw.TopView.Params", "vcd.draw.Image.Params", "vcd.types.cuboid", "cv2.imshow", "screeninfo.get_monitors", "cv2.line", "vcd.draw.TopView", "vcd.draw.SetupViewer", "vcd.utils.euler2R", "vcd.utils.generate_gr...
[((333, 357), 'sys.path.insert', 'sys.path.insert', (['(0)', '""".."""'], {}), "(0, '..')\n", (348, 357), False, 'import sys\n'), ((644, 654), 'vcd.core.VCD', 'core.VCD', ([], {}), '()\n', (652, 654), False, 'from vcd import core\n'), ((1070, 1128), 'numpy.array', 'np.array', (['[333.437012, 0.307729989, 2.4235599, 11.0495005]'], {}), '([333.437012, 0.307729989, 2.4235599, 11.0495005])\n', (1078, 1128), True, 'import numpy as np\n'), ((1388, 1439), 'vcd.utils.euler2R', 'utils.euler2R', (['[z1, x1, z2]'], {'seq': 'utils.EulerSeq.ZXZ'}), '([z1, x1, z2], seq=utils.EulerSeq.ZXZ)\n', (1401, 1439), False, 'from vcd import utils\n'), ((1471, 1503), 'numpy.array', 'np.array', (['[[3.9], [0.04], [0.6]]'], {}), '([[3.9], [0.04], [0.6]])\n', (1479, 1503), True, 'import numpy as np\n'), ((1674, 1713), 'vcd.utils.create_pose', 'utils.create_pose', (['R_scs_wrt_lcs', 'C_lcs'], {}), '(R_scs_wrt_lcs, C_lcs)\n', (1691, 1713), False, 'from vcd import utils\n'), ((2872, 2930), 'numpy.array', 'np.array', (['[333.437012, 0.307729989, 2.4235599, 11.0495005]'], {}), '([333.437012, 0.307729989, 2.4235599, 11.0495005])\n', (2880, 2930), True, 'import numpy as np\n'), ((3117, 3168), 'vcd.utils.euler2R', 'utils.euler2R', (['[z1, x1, z2]'], {'seq': 'utils.EulerSeq.ZXZ'}), '([z1, x1, z2], seq=utils.EulerSeq.ZXZ)\n', (3130, 3168), False, 'from vcd import utils\n'), ((3199, 3235), 'numpy.array', 'np.array', (['[[-1.125], [-0.05], [0.8]]'], {}), '([[-1.125], [-0.05], [0.8]])\n', (3207, 3235), True, 'import numpy as np\n'), ((3405, 3444), 'vcd.utils.create_pose', 'utils.create_pose', (['R_scs_wrt_lcs', 'C_lcs'], {}), '(R_scs_wrt_lcs, C_lcs)\n', (3422, 3444), False, 'from vcd import utils\n'), ((4600, 4658), 'numpy.array', 'np.array', (['[333.437012, 0.307729989, 2.4235599, 11.0495005]'], {}), '([333.437012, 0.307729989, 2.4235599, 11.0495005])\n', (4608, 4658), True, 'import numpy as np\n'), ((4939, 4990), 'vcd.utils.euler2R', 'utils.euler2R', (['[z1, x1, z2]'], {'seq': 'utils.EulerSeq.ZXZ'}), '([z1, x1, z2], seq=utils.EulerSeq.ZXZ)\n', (4952, 4990), False, 'from vcd import utils\n'), ((5021, 5052), 'numpy.array', 'np.array', (['[[2.2], [0.9], [0.9]]'], {}), '([[2.2], [0.9], [0.9]])\n', (5029, 5052), True, 'import numpy as np\n'), ((5222, 5261), 'vcd.utils.create_pose', 'utils.create_pose', (['R_scs_wrt_lcs', 'C_lcs'], {}), '(R_scs_wrt_lcs, C_lcs)\n', (5239, 5261), False, 'from vcd import utils\n'), ((6418, 6476), 'numpy.array', 'np.array', (['[333.437012, 0.307729989, 2.4235599, 11.0495005]'], {}), '([333.437012, 0.307729989, 2.4235599, 11.0495005])\n', (6426, 6476), True, 'import numpy as np\n'), ((6760, 6811), 'vcd.utils.euler2R', 'utils.euler2R', (['[z1, x1, z2]'], {'seq': 'utils.EulerSeq.ZXZ'}), '([z1, x1, z2], seq=utils.EulerSeq.ZXZ)\n', (6773, 6811), False, 'from vcd import utils\n'), ((6842, 6874), 'numpy.array', 'np.array', (['[[2.2], [-0.9], [0.9]]'], {}), '([[2.2], [-0.9], [0.9]])\n', (6850, 6874), True, 'import numpy as np\n'), ((7045, 7084), 'vcd.utils.create_pose', 'utils.create_pose', (['R_scs_wrt_lcs', 'C_lcs'], {}), '(R_scs_wrt_lcs, C_lcs)\n', (7062, 7084), False, 'from vcd import utils\n'), ((8171, 8185), 'vcd.scl.Scene', 'scl.Scene', (['vcd'], {}), '(vcd)\n', (8180, 8185), False, 'from vcd import scl\n'), ((8268, 8298), 'vcd.draw.Image', 'draw.Image', (['scene', '"""CAM_FRONT"""'], {}), "(scene, 'CAM_FRONT')\n", (8278, 8298), False, 'from vcd import draw\n'), ((8317, 8346), 'vcd.draw.Image', 'draw.Image', (['scene', '"""CAM_REAR"""'], {}), "(scene, 'CAM_REAR')\n", (8327, 8346), False, 'from vcd import draw\n'), ((8365, 8394), 'vcd.draw.Image', 'draw.Image', (['scene', '"""CAM_LEFT"""'], {}), "(scene, 'CAM_LEFT')\n", (8375, 8394), False, 'from vcd import draw\n'), ((8414, 8444), 'vcd.draw.Image', 'draw.Image', (['scene', '"""CAM_RIGHT"""'], {}), "(scene, 'CAM_RIGHT')\n", (8424, 8444), False, 'from vcd import draw\n'), ((8468, 8493), 'vcd.draw.FrameInfoDrawer', 'draw.FrameInfoDrawer', (['vcd'], {}), '(vcd)\n', (8488, 8493), False, 'from vcd import draw\n'), ((8513, 8555), 'vcd.draw.SetupViewer', 'draw.SetupViewer', (['scene', '"""vehicle-iso8855"""'], {}), "(scene, 'vehicle-iso8855')\n", (8529, 8555), False, 'from vcd import draw\n'), ((9147, 9175), 'cv2.imread', 'cv.imread', (['"""./png/front.jpg"""'], {}), "('./png/front.jpg')\n", (9156, 9175), True, 'import cv2 as cv\n'), ((9191, 9218), 'cv2.imread', 'cv.imread', (['"""./png/rear.jpg"""'], {}), "('./png/rear.jpg')\n", (9200, 9218), True, 'import cv2 as cv\n'), ((9234, 9261), 'cv2.imread', 'cv.imread', (['"""./png/left.jpg"""'], {}), "('./png/left.jpg')\n", (9243, 9261), True, 'import cv2 as cv\n'), ((9278, 9306), 'cv2.imread', 'cv.imread', (['"""./png/right.jpg"""'], {}), "('./png/right.jpg')\n", (9287, 9306), True, 'import cv2 as cv\n'), ((9326, 9363), 'vcd.draw.Image.Params', 'draw.Image.Params', ([], {'_colorMap': 'colorMap'}), '(_colorMap=colorMap)\n', (9343, 9363), False, 'from vcd import draw\n'), ((10221, 10323), 'cv2.line', 'cv.line', (['mosaic', '(mosaic.shape[1] // 2, 0)', '(mosaic.shape[1] // 2, mosaic.shape[0])', '(0, 0, 0)', '(3)'], {}), '(mosaic, (mosaic.shape[1] // 2, 0), (mosaic.shape[1] // 2, mosaic.\n shape[0]), (0, 0, 0), 3)\n', (10228, 10323), True, 'import cv2 as cv\n'), ((10323, 10425), 'cv2.line', 'cv.line', (['mosaic', '(0, mosaic.shape[0] // 2)', '(mosaic.shape[1], mosaic.shape[0] // 2)', '(0, 0, 0)', '(3)'], {}), '(mosaic, (0, mosaic.shape[0] // 2), (mosaic.shape[1], mosaic.shape[0\n ] // 2), (0, 0, 0), 3)\n', (10330, 10425), True, 'import cv2 as cv\n'), ((10539, 10657), 'cv2.line', 'cv.line', (['mosaic_und', '(mosaic_und.shape[1] // 2, 0)', '(mosaic_und.shape[1] // 2, mosaic_und.shape[0])', '(0, 0, 0)', '(3)'], {}), '(mosaic_und, (mosaic_und.shape[1] // 2, 0), (mosaic_und.shape[1] // \n 2, mosaic_und.shape[0]), (0, 0, 0), 3)\n', (10546, 10657), True, 'import cv2 as cv\n'), ((10657, 10775), 'cv2.line', 'cv.line', (['mosaic_und', '(0, mosaic_und.shape[0] // 2)', '(mosaic_und.shape[1], mosaic_und.shape[0] // 2)', '(0, 0, 0)', '(3)'], {}), '(mosaic_und, (0, mosaic_und.shape[0] // 2), (mosaic_und.shape[1], \n mosaic_und.shape[0] // 2), (0, 0, 0), 3)\n', (10664, 10775), True, 'import cv2 as cv\n'), ((11021, 11203), 'vcd.draw.TopView.Params', 'draw.TopView.Params', ([], {'colorMap': 'colorMap', 'topViewSize': '(topview_width, topview_height)', 'background_color': '(255)', 'rangeX': 'rangeX', 'rangeY': 'rangeY', 'stepX': '(1.0)', 'stepY': '(1.0)', 'draw_grid': '(False)'}), '(colorMap=colorMap, topViewSize=(topview_width,\n topview_height), background_color=255, rangeX=rangeX, rangeY=rangeY,\n stepX=1.0, stepY=1.0, draw_grid=False)\n', (11040, 11203), False, 'from vcd import draw\n'), ((11457, 11517), 'vcd.draw.TopView', 'draw.TopView', (['scene', '"""vehicle-iso8855"""'], {'params': 'topviewParams'}), "(scene, 'vehicle-iso8855', params=topviewParams)\n", (11469, 11517), False, 'from vcd import draw\n'), ((11706, 11749), 'cv2.namedWindow', 'cv.namedWindow', (['"""Cameras"""', 'cv.WINDOW_NORMAL'], {}), "('Cameras', cv.WINDOW_NORMAL)\n", (11720, 11749), True, 'import cv2 as cv\n'), ((11754, 11782), 'cv2.imshow', 'cv.imshow', (['"""Cameras"""', 'mosaic'], {}), "('Cameras', mosaic)\n", (11763, 11782), True, 'import cv2 as cv\n'), ((11787, 11842), 'cv2.namedWindow', 'cv.namedWindow', (['"""Cameras Undistorted"""', 'cv.WINDOW_NORMAL'], {}), "('Cameras Undistorted', cv.WINDOW_NORMAL)\n", (11801, 11842), True, 'import cv2 as cv\n'), ((11847, 11891), 'cv2.imshow', 'cv.imshow', (['"""Cameras Undistorted"""', 'mosaic_und'], {}), "('Cameras Undistorted', mosaic_und)\n", (11856, 11891), True, 'import cv2 as cv\n'), ((11896, 11922), 'cv2.namedWindow', 'cv.namedWindow', (['"""VCD info"""'], {}), "('VCD info')\n", (11910, 11922), True, 'import cv2 as cv\n'), ((11927, 11957), 'cv2.imshow', 'cv.imshow', (['"""VCD info"""', 'textImg'], {}), "('VCD info', textImg)\n", (11936, 11957), True, 'import cv2 as cv\n'), ((11962, 11995), 'cv2.namedWindow', 'cv.namedWindow', (['"""TopView iso8855"""'], {}), "('TopView iso8855')\n", (11976, 11995), True, 'import cv2 as cv\n'), ((12000, 12038), 'cv2.imshow', 'cv.imshow', (['"""TopView iso8855"""', 'topView1'], {}), "('TopView iso8855', topView1)\n", (12009, 12038), True, 'import cv2 as cv\n'), ((12043, 12056), 'cv2.waitKey', 'cv.waitKey', (['(1)'], {}), '(1)\n', (12053, 12056), True, 'import cv2 as cv\n'), ((12098, 12108), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12106, 12108), True, 'import matplotlib.pyplot as plt\n'), ((12329, 12465), 'vcd.types.cuboid', 'types.cuboid', ([], {'name': '"""box3D"""', 'val': '(4.5, 3.5, 0.7, 0.0, 0.0, 90.0 * np.pi / 180.0, 4.2, 1.8, 1.4)', 'coordinate_system': '"""vehicle-iso8855"""'}), "(name='box3D', val=(4.5, 3.5, 0.7, 0.0, 0.0, 90.0 * np.pi / \n 180.0, 4.2, 1.8, 1.4), coordinate_system='vehicle-iso8855')\n", (12341, 12465), False, 'from vcd import types\n'), ((12768, 12858), 'vcd.utils.generate_grid', 'utils.generate_grid', ([], {'x_params': '(0, 20, 21)', 'y_params': '(-20, 20, 41)', 'z_params': '(0, 0, 1)'}), '(x_params=(0, 20, 21), y_params=(-20, 20, 41), z_params=\n (0, 0, 1))\n', (12787, 12858), False, 'from vcd import utils\n'), ((12873, 12911), 'vcd.utils.grid_as_4xN_points3d', 'utils.grid_as_4xN_points3d', (['xm', 'ym', 'zm'], {}), '(xm, ym, zm)\n', (12899, 12911), False, 'from vcd import utils\n'), ((13543, 13634), 'vcd.utils.generate_grid', 'utils.generate_grid', ([], {'x_params': '(0, -20, 21)', 'y_params': '(-20, 20, 41)', 'z_params': '(0, 0, 1)'}), '(x_params=(0, -20, 21), y_params=(-20, 20, 41), z_params\n =(0, 0, 1))\n', (13562, 13634), False, 'from vcd import utils\n'), ((13649, 13687), 'vcd.utils.grid_as_4xN_points3d', 'utils.grid_as_4xN_points3d', (['xm', 'ym', 'zm'], {}), '(xm, ym, zm)\n', (13675, 13687), False, 'from vcd import utils\n'), ((14320, 14411), 'vcd.utils.generate_grid', 'utils.generate_grid', ([], {'x_params': '(20, 20, 1)', 'y_params': '(-20, 20, 41)', 'z_params': '(0, 2, 21)'}), '(x_params=(20, 20, 1), y_params=(-20, 20, 41), z_params=\n (0, 2, 21))\n', (14339, 14411), False, 'from vcd import utils\n'), ((14426, 14464), 'vcd.utils.grid_as_4xN_points3d', 'utils.grid_as_4xN_points3d', (['xm', 'ym', 'zm'], {}), '(xm, ym, zm)\n', (14452, 14464), False, 'from vcd import utils\n'), ((15092, 15184), 'vcd.utils.generate_grid', 'utils.generate_grid', ([], {'x_params': '(-20, -20, 1)', 'y_params': '(-20, 20, 41)', 'z_params': '(0, 2, 21)'}), '(x_params=(-20, -20, 1), y_params=(-20, 20, 41),\n z_params=(0, 2, 21))\n', (15111, 15184), False, 'from vcd import utils\n'), ((15200, 15238), 'vcd.utils.grid_as_4xN_points3d', 'utils.grid_as_4xN_points3d', (['xm', 'ym', 'zm'], {}), '(xm, ym, zm)\n', (15226, 15238), False, 'from vcd import utils\n'), ((15867, 15958), 'vcd.utils.generate_grid', 'utils.generate_grid', ([], {'x_params': '(-20, 20, 41)', 'y_params': '(20, 20, 1)', 'z_params': '(0, 2, 21)'}), '(x_params=(-20, 20, 41), y_params=(20, 20, 1), z_params=\n (0, 2, 21))\n', (15886, 15958), False, 'from vcd import utils\n'), ((15973, 16011), 'vcd.utils.grid_as_4xN_points3d', 'utils.grid_as_4xN_points3d', (['xm', 'ym', 'zm'], {}), '(xm, ym, zm)\n', (15999, 16011), False, 'from vcd import utils\n'), ((16641, 16733), 'vcd.utils.generate_grid', 'utils.generate_grid', ([], {'x_params': '(-20, 20, 41)', 'y_params': '(-20, -20, 1)', 'z_params': '(0, 2, 21)'}), '(x_params=(-20, 20, 41), y_params=(-20, -20, 1),\n z_params=(0, 2, 21))\n', (16660, 16733), False, 'from vcd import utils\n'), ((16749, 16787), 'vcd.utils.grid_as_4xN_points3d', 'utils.grid_as_4xN_points3d', (['xm', 'ym', 'zm'], {}), '(xm, ym, zm)\n', (16775, 16787), False, 'from vcd import utils\n'), ((17600, 17726), 'vcd.types.cuboid', 'types.cuboid', ([], {'name': '"""box3D"""', 'val': '(1.35, 0.0, 0.736, 0.0, 0.0, 0.0, 4.765, 1.82, 1.47)', 'coordinate_system': '"""vehicle-iso8855"""'}), "(name='box3D', val=(1.35, 0.0, 0.736, 0.0, 0.0, 0.0, 4.765, \n 1.82, 1.47), coordinate_system='vehicle-iso8855')\n", (17612, 17726), False, 'from vcd import types\n'), ((9030, 9055), 'screeninfo.get_monitors', 'screeninfo.get_monitors', ([], {}), '()\n', (9053, 9055), False, 'import screeninfo\n'), ((10148, 10181), 'numpy.hstack', 'np.hstack', (['(img_front, img_right)'], {}), '((img_front, img_right))\n', (10157, 10181), True, 'import numpy as np\n'), ((10183, 10214), 'numpy.hstack', 'np.hstack', (['(img_left, img_rear)'], {}), '((img_left, img_rear))\n', (10192, 10214), True, 'import numpy as np\n'), ((10450, 10491), 'numpy.hstack', 'np.hstack', (['(img_front_und, img_right_und)'], {}), '((img_front_und, img_right_und))\n', (10459, 10491), True, 'import numpy as np\n'), ((10493, 10532), 'numpy.hstack', 'np.hstack', (['(img_left_und, img_rear_und)'], {}), '((img_left_und, img_rear_und))\n', (10502, 10532), True, 'import numpy as np\n'), ((17965, 17991), 'os.path.basename', 'os.path.basename', (['__file__'], {}), '(__file__)\n', (17981, 17991), False, 'import os\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 6 21:00:02 2019 @author: ben """ #import matplotlib.pyplot as plt import numpy as np import pointCollection as pc import scipy.ndimage as snd import sys import os import re import argparse def pad_mask_canvas(D, N): dx=np.diff(D.x[0:2]) left=np.arange(-N*dx,0, dx) right=np.arange(0, N*dx, dx) x1=np.unique(np.concatenate([left+D.x[0], D.x, D.x[-1]+right])) y1=np.unique(np.concatenate([left+D.y[0], D.y, D.y[-1]+right])) cols=np.flatnonzero(np.in1d(x1, D.x)) rows=np.flatnonzero(np.in1d(y1, D.y)) z1=np.zeros([y1.size, x1.size], dtype='bool') z1[rows[0]:rows[-1]+1,cols[0]:cols[-1]+1]=D.z.astype('bool') return pc.grid.data().from_dict({'x':x1, 'y':y1,'z':z1}) # define the script. This is assumed to be in the path of the environment # that is running prog = "ATL11_to_ATL15.py" environment = "IS2" # account for a bug in argparse that misinterprets negative agruents argv=sys.argv for i, arg in enumerate(argv): if (arg[0] == '-') and arg[1].isdigit(): argv[i] = ' ' + arg parser = argparse.ArgumentParser(description="generate a list of commands to run ATL11_to_ATL15") parser.add_argument('step', type=str) parser.add_argument('defaults_files', nargs='+', type=str) parser.add_argument('--region_file', '-R', type=str) parser.add_argument('--skip_errors','-s', action='store_true') parser.add_argument('--tile_spacing', type=int) args = parser.parse_args() if args.step not in ['centers', 'edges','corners']: raise(ValueError('step argument not known: must be one of : centers, edges, corners')) sys.exit() if args.skip_errors: calc_errors=False else: calc_errors=True XR=None YR=None if args.region_file is not None: line_re=re.compile('(..)\s*=\s*\[\s*(\S+),\s*(\S+)\s*]') temp={} with open(args.region_file,'r') as fh: for line in fh: m = line_re.search(line) temp[m.group(1)]=[np.float(m.group(2)), np.float(m.group(3))] XR=temp['XR'] YR=temp['YR'] defaults_re=re.compile('(.*)\s*=\s*(.*)') # read in all defaults files (must be of syntax --key=value or -key=value) defaults={} for defaults_file in args.defaults_files: with open(defaults_file,'r') as fh: for line in fh: m=defaults_re.search(line) if m is not None: defaults[m.group(1)]=m.group(2) # check if enough parameters have been specified to allow a run required_keys_present=True for key in ['--ATL14_root', '--region', '--Release','--Hemisphere', '--mask_file']: if key not in defaults: print(f"make_1415_queue.py:\n\tError: required key {key} not in defaults files") required_keys_present=False if not required_keys_present: sys.exit(1) if '--mask_dir' in defaults: defaults['--mask_file']=os.path.join(defaults['--mask_dir'], defaults['--mask_file']) if '--tide_mask_file' in defaults and not os.path.isfile(defaults['--tide_mask_file']): defaults['--tide_mask_file']=os.path.join(defaults['--mask_dir'], defaults['--tide_mask_file']) defaults.pop('--mask_dir', None) if defaults['--Hemisphere']==1 or defaults['--Hemisphere']=="1": hemisphere_name='north' else: hemisphere_name='south' # figure out what directories we need to make release_dir = os.path.join(defaults['--ATL14_root'], "rel"+defaults['--Release']) hemi_dir=os.path.join(release_dir, hemisphere_name) region_dir=os.path.join(hemi_dir, defaults['--region']) for this in [release_dir, hemi_dir, region_dir]: if not os.path.isdir(this): print("missing directory: "+ this) sys.exit(1) # write out the composite defaults file defaults_file=os.path.join(region_dir, f'input_args_{defaults["--region"]}.txt') with open(defaults_file, 'w') as fh: for key, val in defaults.items(): fh.write(f'{key}={val}\n') fh.write(f"-b={region_dir}\n") step_dir=os.path.join(region_dir, args.step) if not os.path.isdir(step_dir): os.mkdir(step_dir) # generate the center locations if args.tile_spacing is None: Wxy=float(defaults['-W']) else: Wxy=args.tile_spacing Hxy=Wxy/2 mask_base, mask_ext = os.path.splitext(defaults['--mask_file']) if mask_ext in ('.tif'): tif_1km=defaults['--mask_file'].replace('100m','1km').replace('125m','1km') temp=pc.grid.data().from_geotif(tif_1km) mask_G=pad_mask_canvas(temp, 200) mask_G.z=snd.binary_dilation(mask_G.z, structure=np.ones([1, int(3*Hxy/1000)+1], dtype='bool')) mask_G.z=snd.binary_dilation(mask_G.z, structure=np.ones([int(3*Hxy/1000)+1, 1], dtype='bool')) x0=np.unique(np.round(mask_G.x/Hxy)*Hxy) y0=np.unique(np.round(mask_G.y/Hxy)*Hxy) x0, y0 = np.meshgrid(x0, y0) xg=x0.ravel() yg=y0.ravel() good=(np.abs(mask_G.interp(xg, yg)-1)<0.1) & (np.mod(xg, Wxy)==0) & (np.mod(yg, Wxy)==0) elif mask_ext in ['.shp','.db']: # the mask is a shape. # We require that an 80-km grid based on the mask exists if not os.path.isfile(mask_base+'_80km.tif'): raise(OSError(f"gridded mask file {mask_base+'_80km.tif'} not found")) mask_G=pc.grid.data().from_geotif(mask_base+'_80km.tif') xg, yg = np.meshgrid(mask_G.x, mask_G.y) xg=xg.ravel()[mask_G.z.ravel()==1] yg=yg.ravel()[mask_G.z.ravel()==1] good=np.ones_like(xg, dtype=bool) if XR is not None: good &= (xg>=XR[0]) & (xg <= XR[1]) & (yg > YR[0]) & (yg < YR[1]) xg=xg[good] yg=yg[good] if args.step=='centers': delta_x=[0] delta_y=[0] elif args.step=='edges': delta_x=[-1, 0, 0, 1.] delta_y=[0, -1, 1, 0.] elif args.step=='corners': delta_x=[-1, 1, -1, 1.] delta_y=[-1, -1, 1, 1.] queued=[]; queue_file=f"1415_queue_{defaults['--region']}_{args.step}.txt" with open(queue_file,'w') as qh: for xy0 in zip(xg, yg): for dx, dy in zip(delta_x, delta_y): xy1=np.array(xy0)+np.array([dx, dy])*Hxy if tuple(xy1) in queued: continue else: queued.append(tuple(xy1)) out_file='%s/E%d_N%d.h5' % (step_dir, xy1[0]/1000, xy1[1]/1000) if not os.path.isfile(out_file): cmd='%s --xy0 %d %d --%s @%s ' % (prog, xy1[0], xy1[1], args.step, defaults_file) if calc_errors: cmd += '; '+cmd+' --calc_error_for_xy' qh.write(f'source activate {environment}; '+cmd+'; echo COMPLETE\n') print("Wrote commands to "+queue_file)
[ "os.mkdir", "argparse.ArgumentParser", "pointCollection.grid.data", "os.path.isfile", "numpy.arange", "numpy.round", "os.path.join", "numpy.meshgrid", "numpy.ones_like", "numpy.mod", "numpy.concatenate", "sys.exit", "re.compile", "os.path.isdir", "numpy.zeros", "numpy.diff", "numpy.a...
[((1110, 1203), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""generate a list of commands to run ATL11_to_ATL15"""'}), "(description=\n 'generate a list of commands to run ATL11_to_ATL15')\n", (1133, 1203), False, 'import argparse\n'), ((2071, 2102), 're.compile', 're.compile', (['"""(.*)\\\\s*=\\\\s*(.*)"""'], {}), "('(.*)\\\\s*=\\\\s*(.*)')\n", (2081, 2102), False, 'import re\n'), ((3338, 3407), 'os.path.join', 'os.path.join', (["defaults['--ATL14_root']", "('rel' + defaults['--Release'])"], {}), "(defaults['--ATL14_root'], 'rel' + defaults['--Release'])\n", (3350, 3407), False, 'import os\n'), ((3415, 3457), 'os.path.join', 'os.path.join', (['release_dir', 'hemisphere_name'], {}), '(release_dir, hemisphere_name)\n', (3427, 3457), False, 'import os\n'), ((3469, 3513), 'os.path.join', 'os.path.join', (['hemi_dir', "defaults['--region']"], {}), "(hemi_dir, defaults['--region'])\n", (3481, 3513), False, 'import os\n'), ((3714, 3780), 'os.path.join', 'os.path.join', (['region_dir', 'f"""input_args_{defaults[\'--region\']}.txt"""'], {}), '(region_dir, f"input_args_{defaults[\'--region\']}.txt")\n', (3726, 3780), False, 'import os\n'), ((3936, 3971), 'os.path.join', 'os.path.join', (['region_dir', 'args.step'], {}), '(region_dir, args.step)\n', (3948, 3971), False, 'import os\n'), ((4186, 4227), 'os.path.splitext', 'os.path.splitext', (["defaults['--mask_file']"], {}), "(defaults['--mask_file'])\n", (4202, 4227), False, 'import os\n'), ((297, 314), 'numpy.diff', 'np.diff', (['D.x[0:2]'], {}), '(D.x[0:2])\n', (304, 314), True, 'import numpy as np\n'), ((324, 349), 'numpy.arange', 'np.arange', (['(-N * dx)', '(0)', 'dx'], {}), '(-N * dx, 0, dx)\n', (333, 349), True, 'import numpy as np\n'), ((357, 381), 'numpy.arange', 'np.arange', (['(0)', '(N * dx)', 'dx'], {}), '(0, N * dx, dx)\n', (366, 381), True, 'import numpy as np\n'), ((607, 649), 'numpy.zeros', 'np.zeros', (['[y1.size, x1.size]'], {'dtype': '"""bool"""'}), "([y1.size, x1.size], dtype='bool')\n", (615, 649), True, 'import numpy as np\n'), ((1635, 1645), 'sys.exit', 'sys.exit', ([], {}), '()\n', (1643, 1645), False, 'import sys\n'), ((1783, 1839), 're.compile', 're.compile', (['"""(..)\\\\s*=\\\\s*\\\\[\\\\s*(\\\\S+),\\\\s*(\\\\S+)\\\\s*]"""'], {}), "('(..)\\\\s*=\\\\s*\\\\[\\\\s*(\\\\S+),\\\\s*(\\\\S+)\\\\s*]')\n", (1793, 1839), False, 'import re\n'), ((2776, 2787), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2784, 2787), False, 'import sys\n'), ((2846, 2907), 'os.path.join', 'os.path.join', (["defaults['--mask_dir']", "defaults['--mask_file']"], {}), "(defaults['--mask_dir'], defaults['--mask_file'])\n", (2858, 2907), False, 'import os\n'), ((3979, 4002), 'os.path.isdir', 'os.path.isdir', (['step_dir'], {}), '(step_dir)\n', (3992, 4002), False, 'import os\n'), ((4008, 4026), 'os.mkdir', 'os.mkdir', (['step_dir'], {}), '(step_dir)\n', (4016, 4026), False, 'import os\n'), ((4733, 4752), 'numpy.meshgrid', 'np.meshgrid', (['x0', 'y0'], {}), '(x0, y0)\n', (4744, 4752), True, 'import numpy as np\n'), ((397, 450), 'numpy.concatenate', 'np.concatenate', (['[left + D.x[0], D.x, D.x[-1] + right]'], {}), '([left + D.x[0], D.x, D.x[-1] + right])\n', (411, 450), True, 'import numpy as np\n'), ((465, 518), 'numpy.concatenate', 'np.concatenate', (['[left + D.y[0], D.y, D.y[-1] + right]'], {}), '([left + D.y[0], D.y, D.y[-1] + right])\n', (479, 518), True, 'import numpy as np\n'), ((540, 556), 'numpy.in1d', 'np.in1d', (['x1', 'D.x'], {}), '(x1, D.x)\n', (547, 556), True, 'import numpy as np\n'), ((582, 598), 'numpy.in1d', 'np.in1d', (['y1', 'D.y'], {}), '(y1, D.y)\n', (589, 598), True, 'import numpy as np\n'), ((3040, 3106), 'os.path.join', 'os.path.join', (["defaults['--mask_dir']", "defaults['--tide_mask_file']"], {}), "(defaults['--mask_dir'], defaults['--tide_mask_file'])\n", (3052, 3106), False, 'import os\n'), ((3575, 3594), 'os.path.isdir', 'os.path.isdir', (['this'], {}), '(this)\n', (3588, 3594), False, 'import os\n'), ((3647, 3658), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (3655, 3658), False, 'import sys\n'), ((5206, 5237), 'numpy.meshgrid', 'np.meshgrid', (['mask_G.x', 'mask_G.y'], {}), '(mask_G.x, mask_G.y)\n', (5217, 5237), True, 'import numpy as np\n'), ((5325, 5353), 'numpy.ones_like', 'np.ones_like', (['xg'], {'dtype': 'bool'}), '(xg, dtype=bool)\n', (5337, 5353), True, 'import numpy as np\n'), ((726, 740), 'pointCollection.grid.data', 'pc.grid.data', ([], {}), '()\n', (738, 740), True, 'import pointCollection as pc\n'), ((2957, 3001), 'os.path.isfile', 'os.path.isfile', (["defaults['--tide_mask_file']"], {}), "(defaults['--tide_mask_file'])\n", (2971, 3001), False, 'import os\n'), ((4347, 4361), 'pointCollection.grid.data', 'pc.grid.data', ([], {}), '()\n', (4359, 4361), True, 'import pointCollection as pc\n'), ((4647, 4671), 'numpy.round', 'np.round', (['(mask_G.x / Hxy)'], {}), '(mask_G.x / Hxy)\n', (4655, 4671), True, 'import numpy as np\n'), ((4692, 4716), 'numpy.round', 'np.round', (['(mask_G.y / Hxy)'], {}), '(mask_G.y / Hxy)\n', (4700, 4716), True, 'import numpy as np\n'), ((4862, 4877), 'numpy.mod', 'np.mod', (['yg', 'Wxy'], {}), '(yg, Wxy)\n', (4868, 4877), True, 'import numpy as np\n'), ((5014, 5053), 'os.path.isfile', 'os.path.isfile', (["(mask_base + '_80km.tif')"], {}), "(mask_base + '_80km.tif')\n", (5028, 5053), False, 'import os\n'), ((4839, 4854), 'numpy.mod', 'np.mod', (['xg', 'Wxy'], {}), '(xg, Wxy)\n', (4845, 4854), True, 'import numpy as np\n'), ((5143, 5157), 'pointCollection.grid.data', 'pc.grid.data', ([], {}), '()\n', (5155, 5157), True, 'import pointCollection as pc\n'), ((5891, 5904), 'numpy.array', 'np.array', (['xy0'], {}), '(xy0)\n', (5899, 5904), True, 'import numpy as np\n'), ((6147, 6171), 'os.path.isfile', 'os.path.isfile', (['out_file'], {}), '(out_file)\n', (6161, 6171), False, 'import os\n'), ((5905, 5923), 'numpy.array', 'np.array', (['[dx, dy]'], {}), '([dx, dy])\n', (5913, 5923), True, 'import numpy as np\n')]
import json import pickle import numpy as np import pandas as pd results_dir = "/science/image/nlp-datasets/emanuele/results/xm-influence/flickr30kentities_vis4lang/" def get_rows(df, basedir, name): # none ablation mlm = pickle.load(open(basedir + 'val_none_mlm.pkl', 'rb')) mlm = np.mean(mlm) df = df.append({'Model': name, 'Mask': "None", "MLM": mlm}, ignore_index=True) # object ablation (with different thresholds) for i in range(9, -1, -1): mlm = pickle.load(open(basedir + f'val_object0.{i}_mlm.pkl', 'rb')) mlm = np.mean(mlm) df = df.append({'Model': "UNITER", 'Mask': i/10, "MLM": mlm}, ignore_index=True) # all ablation mlm = pickle.load(open(basedir + 'val_all_mlm.pkl', 'rb')) mlm = np.mean(mlm) df = df.append({'Model': "UNITER", 'Mask': "All", "MLM": mlm}, ignore_index=True) return df df = pd.DataFrame(columns=["Model", "Mask", "MLM"]) # BERT basedir = results_dir + "bert/" mlm = pickle.load(open(basedir + 'val_mlm.pkl', 'rb')) mlm = np.mean(bert_mlm) df = df.append({'Model': "BERT", 'Mask': None, "MLM": mlm}, ignore_index=True) # BERT_CC basedir = results_dir + "bert-cc_pre5/" mlm = pickle.load(open(basedir + 'val_mlm.pkl', 'rb')) mlm = np.mean(bert_mlm) df = df.append({'Model': "BERT-CC", 'Mask': None, "MLM": mlm}, ignore_index=True) name2dir = { "UNITER": "ctrl_uniter/", "VL-BERT": "ctrl_vl-bert/", "VisualBERT": "ctrl_visualbert/", "ViLBERT": "ctrl_vilbert/", "LXMERT": "ctrl_lxmert/", "UNITER_rnd-vl": "ctrl_uniter_rnd-vl", "ViLBERT_rnd-vl": "ctrl_vilbert_rnd-vl", "UNITER_rnd-v-vl": "ctrl_uniter_rnd-v-vl", "UNITER_bert-v-vl": "ctrl_uniter_bert-v-vl", "UNITER_thr02": "ctrl_uniter_thr02/", "UNITER_thr04": "ctrl_uniter_thr04/", "UNITER_thr06": "ctrl_uniter_thr06/", "UNITER_thr10": "ctrl_uniter_thr10/", "UNITER_thr02iot": "ctrl_uniter_thr02iot/", "UNITER_thr04iot": "ctrl_uniter_thr04iot/", "UNITER_thr06iot": "ctrl_uniter_thr06iot/", "UNITER-xent": "ctrl_uniter_xent/" } for name, d in name2dir.items(): basedir = results_dir + d for abl in ['all', 'object', 'none']: res = get_row(basedir, abl, name) # nats to bits res['MLM'] /= np.log(2) df = df.append(res, ignore_index=True) # Results by seed models = ['lxmert', 'vilbert', 'vl-bert', 'visualbert', 'uniter'] names = ['LXMERT_s%s', 'ViLBERT_s%s', 'VL-BERT_s%s', 'VisualBERT_s%s', 'UNITER_s%s'] seeds = ['0', '1234', '27', '33', '42', '54', '69', '73', '89', '93'] basedir = results_dir + "ctrl_%s_s%s/" for abl in ['all', 'phrase', 'none']: for s in seeds: for im, m in enumerate(models): res = get_row(basedir % (m, s), abl, names[im] % s) res['MLM'] /= np.log(2) df = df.append(res, ignore_index=True) df.to_csv("val_%.1f_vis4lang.tsv" % thr, sep='\t')
[ "pandas.DataFrame", "numpy.mean", "numpy.log" ]
[((891, 937), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['Model', 'Mask', 'MLM']"}), "(columns=['Model', 'Mask', 'MLM'])\n", (903, 937), True, 'import pandas as pd\n'), ((1039, 1056), 'numpy.mean', 'np.mean', (['bert_mlm'], {}), '(bert_mlm)\n', (1046, 1056), True, 'import numpy as np\n'), ((1248, 1265), 'numpy.mean', 'np.mean', (['bert_mlm'], {}), '(bert_mlm)\n', (1255, 1265), True, 'import numpy as np\n'), ((303, 315), 'numpy.mean', 'np.mean', (['mlm'], {}), '(mlm)\n', (310, 315), True, 'import numpy as np\n'), ((770, 782), 'numpy.mean', 'np.mean', (['mlm'], {}), '(mlm)\n', (777, 782), True, 'import numpy as np\n'), ((575, 587), 'numpy.mean', 'np.mean', (['mlm'], {}), '(mlm)\n', (582, 587), True, 'import numpy as np\n'), ((2274, 2283), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (2280, 2283), True, 'import numpy as np\n'), ((2798, 2807), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (2804, 2807), True, 'import numpy as np\n')]
# coding: utf-8 # In[4]: import numpy as np from numpy import* import pandas as pd import matplotlib.pyplot as plt from sklearn.kernel_ridge import KernelRidge from sklearn.model_selection import GridSearchCV from pylab import scatter, show, legend, xlabel, ylabel from sklearn.metrics import r2_score import seaborn as sns cm = sns.light_palette("green", as_cmap=True) dataset = pd.read_csv("data_akbilgic.csv", header=0) attributeList = ["ISE", "DAX", "FTSE", "NIKKEI", "BOVESPA", "EU", "EM"] yAttribute = "SP" X = dataset[attributeList[:]] X = np.array(X) Y = dataset[[yAttribute]] Y = np.array(Y) # dax = dataset[attributeList["DAX"]] # dax = np.array(dax) # daxA = "DAX" dax = dataset[["DAX"]] dax = np.array(dax) # print(dax) # print(dataset["DAX"]) # In[59]: dataset["DAX"].corr(dataset["EU"]) # In[60]: dataset.drop(['SP'], axis=1).corr(method='spearman') # In[61]: dataset.drop(['SP'], axis=1).corr(method='pearson').style.format("{:.2}").background_gradient(cmap=plt.get_cmap('coolwarm'), axis=1) # In[53]: dataset.drop(['SP'], axis=1).corr(method='spearman').style.format("{:.2}").background_gradient(cmap=plt.get_cmap('coolwarm'), axis=1) # In[54]: dataset.drop(['SP'], axis=1).corr(method='kendall').style.format("{:.2}").background_gradient(cmap=plt.get_cmap('coolwarm'), axis=1) # In[55]: dataset.corr(method='pearson').style.format("{:.2}").background_gradient(cmap=plt.get_cmap('coolwarm'), axis=1) # In[70]: dataset.corr(method='pearson').style.set_caption('Colormaps, with a caption.').background_gradient(cmap=cm) # In[71]: dataset.corr(method='kendall').style.set_caption('Colormaps, with a caption.').background_gradient(cmap=cm) # In[73]: dataset.corr(method='spearman').style.set_caption('Colormaps, with a caption.').background_gradient(cmap=cm) # In[16]: # plot corelated values plt.rcParams['figure.figsize'] = [32, 4] fig, ax = plt.subplots(nrows=1, ncols=8) ax=ax.flatten() cols = ['DAX', 'FTSE', 'BOVESPA', 'BOVESPA', 'EU', 'EM', 'ISE', 'NIKKEI'] colors = ['#415952', '#415952', '#415952', '#415952', '#415952', '#415952', '#415952', '#415952'] j = 0 for i in ax: if j==0: i.set_ylabel('SP') i.scatter(dataset[cols[j]], dataset['SP'], alpha=0.5, color=colors[j]) i.set_xlabel(cols[j]) i.set_title('Pearson: %s'%dataset.corr().loc[cols[j]]['SP'].round(2)+' Spearman: %s'%dataset.corr(method='spearman').loc[cols[j]]['SP'].round(2)) j+=1 plt.show() # In[77]: # plot corelated values plt.rcParams['figure.figsize'] = [16, 6] fig, ax = plt.subplots(nrows=1, ncols=3) ax=ax.flatten() cols = ['BOVESPA', 'EU', 'EM'] colors = ['#415952', '#f35134', '#243AB5', '#243AB5'] j = 0 for i in ax: if j==0: i.set_ylabel('SP') i.scatter(dataset[cols[j]], dataset['SP'], alpha=0.5, color=colors[j]) i.set_xlabel(cols[j]) i.set_title('Pearson: %s'%dataset.corr().loc[cols[j]]['SP'].round(2)+' Spearman: %s'%dataset.corr(method='spearman').loc[cols[j]]['SP'].round(2)) j+=1 plt.show()
[ "matplotlib.pyplot.show", "matplotlib.pyplot.get_cmap", "pandas.read_csv", "seaborn.light_palette", "numpy.array", "matplotlib.pyplot.subplots" ]
[((336, 376), 'seaborn.light_palette', 'sns.light_palette', (['"""green"""'], {'as_cmap': '(True)'}), "('green', as_cmap=True)\n", (353, 376), True, 'import seaborn as sns\n'), ((388, 430), 'pandas.read_csv', 'pd.read_csv', (['"""data_akbilgic.csv"""'], {'header': '(0)'}), "('data_akbilgic.csv', header=0)\n", (399, 430), True, 'import pandas as pd\n'), ((555, 566), 'numpy.array', 'np.array', (['X'], {}), '(X)\n', (563, 566), True, 'import numpy as np\n'), ((597, 608), 'numpy.array', 'np.array', (['Y'], {}), '(Y)\n', (605, 608), True, 'import numpy as np\n'), ((715, 728), 'numpy.array', 'np.array', (['dax'], {}), '(dax)\n', (723, 728), True, 'import numpy as np\n'), ((1908, 1938), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(8)'}), '(nrows=1, ncols=8)\n', (1920, 1938), True, 'import matplotlib.pyplot as plt\n'), ((2454, 2464), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2462, 2464), True, 'import matplotlib.pyplot as plt\n'), ((2555, 2585), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'ncols': '(3)'}), '(nrows=1, ncols=3)\n', (2567, 2585), True, 'import matplotlib.pyplot as plt\n'), ((3014, 3024), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3022, 3024), True, 'import matplotlib.pyplot as plt\n'), ((996, 1020), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""coolwarm"""'], {}), "('coolwarm')\n", (1008, 1020), True, 'import matplotlib.pyplot as plt\n'), ((1144, 1168), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""coolwarm"""'], {}), "('coolwarm')\n", (1156, 1168), True, 'import matplotlib.pyplot as plt\n'), ((1291, 1315), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""coolwarm"""'], {}), "('coolwarm')\n", (1303, 1315), True, 'import matplotlib.pyplot as plt\n'), ((1417, 1441), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""coolwarm"""'], {}), "('coolwarm')\n", (1429, 1441), True, 'import matplotlib.pyplot as plt\n')]
""" $lic$ Copyright (C) 2016-2017 by The Board of Trustees of Stanford University This program is free software: you can redistribute it and/or modify it under the terms of the Modified BSD-3 License as published by the Open Source Initiative. If you use this program in your research, we request that you reference the TETRIS paper ("TETRIS: Scalable and Efficient Neural Network Acceleration with 3D Memory", in ASPLOS'17. April, 2017), and that you send us a citation of your work. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the BSD-3 License for more details. You should have received a copy of the Modified BSD-3 License along with this program. If not, see <https://opensource.org/licenses/BSD-3-Clause>. """ ''' Utilities. ''' import numpy as np def idivc(valx, valy): ''' Integer division and ceiling. Return the min integer that is no less than `valx / valy`. ''' return (valx + valy - 1) // valy def approx_dividable(total, num, overhead=0.2): ''' Whether it is reasonable to divide `total` into `num` parts. `overhead` is the allowed max padding overhead. ''' return idivc(total, num) * num < total * (1 + overhead) def factorize(value, num, limits=None): ''' Factorize given `value` into `num` numbers. Return as a copy of num-length np.array. Iterate over factor combinations of which the product is `value`. `limits` is a (num-1)-length tuple, specifying the upper limits for the first num-1 factors. ''' if limits is None: limits = [float('inf')] * (num - 1) assert len(limits) >= num - 1 limits = limits[:num-1] + [float('inf')] factors = np.ones(num, dtype=int) while True: # Calculate the last factor. factors[-1] = idivc(value, np.prod(factors[:-1])) if np.prod(factors) == value \ and np.all(np.less(factors, limits)): yield tuple(np.copy(factors)) # Update the first n - 1 factor combination, backwards. lvl = num - 1 while lvl >= 0: factors[lvl] += 1 if np.prod(factors[:lvl+1]) <= value: break else: factors[lvl] = 1 lvl -= 1 if lvl < 0: return def closest_factor(value, factor): ''' Return the maximum factor of `value` that is no larger than `factor`, and the minimum factor of `value` that is no less than `factor`, as a tuple. ''' res = tuple() # Maximum no-larger factor. f = int(factor) while f > 1: if value % f == 0 and f <= factor: break f -= 1 res += (max(1, f), ) # Minimum no-smaller factor. f = int(factor) while f < value: if f != 0 and value % f == 0 and f >= factor: break f += 1 res += (min(value, f), ) return res
[ "numpy.less", "numpy.copy", "numpy.ones", "numpy.prod" ]
[((1796, 1819), 'numpy.ones', 'np.ones', (['num'], {'dtype': 'int'}), '(num, dtype=int)\n', (1803, 1819), True, 'import numpy as np\n'), ((1908, 1929), 'numpy.prod', 'np.prod', (['factors[:-1]'], {}), '(factors[:-1])\n', (1915, 1929), True, 'import numpy as np\n'), ((1942, 1958), 'numpy.prod', 'np.prod', (['factors'], {}), '(factors)\n', (1949, 1958), True, 'import numpy as np\n'), ((1997, 2021), 'numpy.less', 'np.less', (['factors', 'limits'], {}), '(factors, limits)\n', (2004, 2021), True, 'import numpy as np\n'), ((2222, 2248), 'numpy.prod', 'np.prod', (['factors[:lvl + 1]'], {}), '(factors[:lvl + 1])\n', (2229, 2248), True, 'import numpy as np\n'), ((2048, 2064), 'numpy.copy', 'np.copy', (['factors'], {}), '(factors)\n', (2055, 2064), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- # # stimulus_params.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # NEST is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. ''' microcircuit stimulus parameters -------------------------------- Stimulus parameters for the microcircuit. <NAME>, <NAME>, <NAME>; May 2016 ''' import numpy as np from network_params import net_dict stim_dict = { # Turn thalamic input on or off (True or False). 'thalamic_input': False, # Turn DC input on or off (True or False). 'dc_input': False, # Number of thalamic neurons. 'n_thal': 902, # Mean amplitude of the thalamic postsynaptic potential (in mV). 'PSP_th': 0.15, # Standard deviation of the postsynaptic potential (in relative units). 'PSP_sd': 0.1, # Start of the thalamic input (in ms). 'th_start': 700.0, # Duration of the thalamic input (in ms). 'th_duration': 10.0, # Rate of the thalamic input (in Hz). 'th_rate': 120.0, # Start of the DC generator (in ms). 'dc_start': 0.0, # Duration of the DC generator (in ms). 'dc_dur': 1000.0, # Connection probabilities of the thalamus to the different populations. # Order as in 'populations' in 'network_params.py' 'conn_probs_th': np.array([0.0, 0.0, 0.0983, 0.0619, 0.0, 0.0, 0.0512, 0.0196]), # Mean delay of the thalamic input (in ms). 'delay_th': np.asarray([1.5 for i in list(range(len(net_dict['populations'])))]), # Standard deviation of the thalamic delay (in ms). 'delay_th_sd': np.asarray([0.75 for i in list(range(len(net_dict['populations'])))]), # Amplitude of the DC generator (in pA). 'dc_amp': np.ones(len(net_dict['populations'])) * 0.3, }
[ "numpy.array" ]
[((1835, 1897), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0983, 0.0619, 0.0, 0.0, 0.0512, 0.0196]'], {}), '([0.0, 0.0, 0.0983, 0.0619, 0.0, 0.0, 0.0512, 0.0196])\n', (1843, 1897), True, 'import numpy as np\n')]
import torch import tensorflow as tf import paddle import numpy as np from termcolor import colored # test for compatibility with different AI framework a = torch.randn(2, 3) b = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) print("==>> b.shape: ", b.shape) print(colored("==>> type(b): ", "blue"), type(b)) # print("==>> type(b): ", type(b)) # print("==>> b.shape: ", b.shape) c = paddle.to_tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) print("==>>c.shape: ", c.shape) d = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) print(colored("==>> d.shape: ", "red"), d.shape) print(colored("==>> type(d): ", "blue"), type(d)) print("==>>d.shape: ", d.shape) # test for line with indent if True: a += torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]) a.bernoulli_(0.1)
[ "torch.randn", "tensorflow.constant", "termcolor.colored", "numpy.array", "paddle.to_tensor", "torch.tensor" ]
[((158, 175), 'torch.randn', 'torch.randn', (['(2)', '(3)'], {}), '(2, 3)\n', (169, 175), False, 'import torch\n'), ((181, 228), 'tensorflow.constant', 'tf.constant', (['[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]'], {}), '([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n', (192, 228), True, 'import tensorflow as tf\n'), ((387, 439), 'paddle.to_tensor', 'paddle.to_tensor', (['[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]'], {}), '([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n', (403, 439), False, 'import paddle\n'), ((477, 521), 'numpy.array', 'np.array', (['[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]'], {}), '([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n', (485, 521), True, 'import numpy as np\n'), ((268, 301), 'termcolor.colored', 'colored', (['"""==>> type(b): """', '"""blue"""'], {}), "('==>> type(b): ', 'blue')\n", (275, 301), False, 'from termcolor import colored\n'), ((528, 560), 'termcolor.colored', 'colored', (['"""==>> d.shape: """', '"""red"""'], {}), "('==>> d.shape: ', 'red')\n", (535, 560), False, 'from termcolor import colored\n'), ((577, 610), 'termcolor.colored', 'colored', (['"""==>> type(d): """', '"""blue"""'], {}), "('==>> type(d): ', 'blue')\n", (584, 610), False, 'from termcolor import colored\n'), ((700, 748), 'torch.tensor', 'torch.tensor', (['[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]'], {}), '([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n', (712, 748), False, 'import torch\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals range = getattr(__builtins__, 'xrange', range) # end of py2 compatability boilerplate import os import pytest import numpy as np from matrixprofile.algorithms.stomp import stomp from matrixprofile.algorithms.skimp import skimp from matrixprofile.visualize import visualize def test_catch_all_visualize_invalid_structure(): data = {} with pytest.raises(Exception) as e: visualize(data) assert('MatrixProfile, Pan-MatrixProfile or Statistics data structure expected!' == str(e.value)) def test_catch_all_visualize_mp_only(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = 4 profile = stomp(ts, w, n_jobs=1) # expect only the matrix profile plot figures = visualize(profile) assert(len(figures) == 1) def test_catch_all_visualize_mp_cmp(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = 4 profile = stomp(ts, w, n_jobs=1) profile['cmp'] = np.arange(len(ts) - w + 1) figures = visualize(profile) assert(len(figures) == 2) def test_catch_all_visualize_mp_av(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = 4 profile = stomp(ts, w, n_jobs=1) profile['av'] = np.arange(len(ts) - w + 1) figures = visualize(profile) assert(len(figures) == 2) def test_catch_all_visualize_mp_cmp_av(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = 4 profile = stomp(ts, w, n_jobs=1) profile['cmp'] = np.arange(len(ts) - w + 1) profile['av'] = np.arange(len(ts) - w + 1) figures = visualize(profile) assert(len(figures) == 3) def test_catch_all_visualize_mp_discords(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = 4 profile = stomp(ts, w, n_jobs=1) profile['discords'] = [0, 1] figures = visualize(profile) assert(len(figures) == 2) def test_catch_all_visualize_mp_motifs(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = 4 profile = stomp(ts, w, n_jobs=1) profile['motifs'] = [{'motifs': [1, 1], 'neighbors': []}] figures = visualize(profile) assert(len(figures) == 3) def test_catch_all_visualize_mp_motifs_discords(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = 4 profile = stomp(ts, w, n_jobs=1) profile['discords'] = [0, 1] profile['motifs'] = [{'motifs': [1, 1], 'neighbors': []}] figures = visualize(profile) assert(len(figures) == 4) def test_catch_all_visualize_pmp_only(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = [4, 5, 6] profile = skimp(ts, w, n_jobs=1) # expect only the matrix profile plot figures = visualize(profile) assert(len(figures) == 1) def test_catch_all_visualize_pmp_discords(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = [4, 5, 6] profile = skimp(ts, w, n_jobs=1) profile['discords'] = [(0, 1), (0, 2)] figures = visualize(profile) assert(len(figures) == 3) def test_catch_all_visualize_pmp_motifs(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = [4, 5, 6] profile = skimp(ts, w, n_jobs=1) profile['motifs'] = [{'motifs': [(1, 1)], 'neighbors': []}] figures = visualize(profile) assert(len(figures) == 3) def test_catch_all_visualize_pmp_motifs_discords(): ts = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) w = [4, 5, 6] profile = skimp(ts, w, n_jobs=1) profile['discords'] = [(0, 1), (0, 2)] profile['motifs'] = [{'motifs': [(1, 1)], 'neighbors': []}] figures = visualize(profile) assert(len(figures) == 5) def test_catch_all_stats(): profile = { 'class': 'Statistics', 'ts': np.array([]), 'window_size': 100 } figures = visualize(profile) assert(len(figures) == 1)
[ "matrixprofile.algorithms.stomp.stomp", "matrixprofile.visualize.visualize", "matrixprofile.algorithms.skimp.skimp", "pytest.raises", "numpy.array" ]
[((760, 809), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (768, 809), True, 'import numpy as np\n'), ((835, 857), 'matrixprofile.algorithms.stomp.stomp', 'stomp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (840, 857), False, 'from matrixprofile.algorithms.stomp import stomp\n'), ((915, 933), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (924, 933), False, 'from matrixprofile.visualize import visualize\n'), ((1014, 1063), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (1022, 1063), True, 'import numpy as np\n'), ((1089, 1111), 'matrixprofile.algorithms.stomp.stomp', 'stomp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (1094, 1111), False, 'from matrixprofile.algorithms.stomp import stomp\n'), ((1175, 1193), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (1184, 1193), False, 'from matrixprofile.visualize import visualize\n'), ((1273, 1322), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (1281, 1322), True, 'import numpy as np\n'), ((1348, 1370), 'matrixprofile.algorithms.stomp.stomp', 'stomp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (1353, 1370), False, 'from matrixprofile.algorithms.stomp import stomp\n'), ((1433, 1451), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (1442, 1451), False, 'from matrixprofile.visualize import visualize\n'), ((1535, 1584), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (1543, 1584), True, 'import numpy as np\n'), ((1610, 1632), 'matrixprofile.algorithms.stomp.stomp', 'stomp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (1615, 1632), False, 'from matrixprofile.algorithms.stomp import stomp\n'), ((1743, 1761), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (1752, 1761), False, 'from matrixprofile.visualize import visualize\n'), ((1847, 1896), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (1855, 1896), True, 'import numpy as np\n'), ((1922, 1944), 'matrixprofile.algorithms.stomp.stomp', 'stomp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (1927, 1944), False, 'from matrixprofile.algorithms.stomp import stomp\n'), ((1993, 2011), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (2002, 2011), False, 'from matrixprofile.visualize import visualize\n'), ((2095, 2144), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (2103, 2144), True, 'import numpy as np\n'), ((2170, 2192), 'matrixprofile.algorithms.stomp.stomp', 'stomp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (2175, 2192), False, 'from matrixprofile.algorithms.stomp import stomp\n'), ((2270, 2288), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (2279, 2288), False, 'from matrixprofile.visualize import visualize\n'), ((2381, 2430), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (2389, 2430), True, 'import numpy as np\n'), ((2456, 2478), 'matrixprofile.algorithms.stomp.stomp', 'stomp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (2461, 2478), False, 'from matrixprofile.algorithms.stomp import stomp\n'), ((2589, 2607), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (2598, 2607), False, 'from matrixprofile.visualize import visualize\n'), ((2690, 2739), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (2698, 2739), True, 'import numpy as np\n'), ((2773, 2795), 'matrixprofile.algorithms.skimp.skimp', 'skimp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (2778, 2795), False, 'from matrixprofile.algorithms.skimp import skimp\n'), ((2853, 2871), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (2862, 2871), False, 'from matrixprofile.visualize import visualize\n'), ((2958, 3007), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (2966, 3007), True, 'import numpy as np\n'), ((3041, 3063), 'matrixprofile.algorithms.skimp.skimp', 'skimp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (3046, 3063), False, 'from matrixprofile.algorithms.skimp import skimp\n'), ((3122, 3140), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (3131, 3140), False, 'from matrixprofile.visualize import visualize\n'), ((3225, 3274), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (3233, 3274), True, 'import numpy as np\n'), ((3308, 3330), 'matrixprofile.algorithms.skimp.skimp', 'skimp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (3313, 3330), False, 'from matrixprofile.algorithms.skimp import skimp\n'), ((3410, 3428), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (3419, 3428), False, 'from matrixprofile.visualize import visualize\n'), ((3521, 3570), 'numpy.array', 'np.array', (['[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]'], {}), '([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n', (3529, 3570), True, 'import numpy as np\n'), ((3604, 3626), 'matrixprofile.algorithms.skimp.skimp', 'skimp', (['ts', 'w'], {'n_jobs': '(1)'}), '(ts, w, n_jobs=1)\n', (3609, 3626), False, 'from matrixprofile.algorithms.skimp import skimp\n'), ((3749, 3767), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (3758, 3767), False, 'from matrixprofile.visualize import visualize\n'), ((3951, 3969), 'matrixprofile.visualize.visualize', 'visualize', (['profile'], {}), '(profile)\n', (3960, 3969), False, 'from matrixprofile.visualize import visualize\n'), ((548, 572), 'pytest.raises', 'pytest.raises', (['Exception'], {}), '(Exception)\n', (561, 572), False, 'import pytest\n'), ((587, 602), 'matrixprofile.visualize.visualize', 'visualize', (['data'], {}), '(data)\n', (596, 602), False, 'from matrixprofile.visualize import visualize\n'), ((3889, 3901), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (3897, 3901), True, 'import numpy as np\n')]
# BSD 3-Clause License # # This file is part of the DM-VIO-Python-Tools. # https://github.com/lukasvst/dm-vio-python-tools # # Copyright (c) 2022, <NAME>, TUM # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the # following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following # disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the # following disclaimer in the documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote # products derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. from enum import Enum from pathlib import Path import trajectory_evaluation.evaluate_ate as evaluate_ate import trajectory_evaluation.associate as associate import numpy as np from ruamel.yaml import YAML from tqdm import tqdm class Dataset(Enum): euroc = 0 tumvi = 1 four_seasons = 2 class EvalResults: """Stores the results (rmse, etc.) of the evaluation for further analysis. run_folder path to the results folder. folder_names names of all the sequences of the dataset evaluated on. errors : np.array(num_iter x num_sequences) rmse (absolute trajectory error) for each run scales : np.array(num_iter x num_sequences) the estimated scale for each run. scale_errors : np.array(num_iter x num_sequences) scale error (in percentage) for each run. percentage_done : np.array(num_iter x num_sequences) for each run the percentage of the sequence completed. name : str name of the result for plot legend, can be None. median_errors : np.array(num_sequences) median rmse (ate) for each sequence. median_scale_errors : np.array(num_sequences) scale error of the median run (in terms of rmse) for each sequence. median_index : np.array(num_sequences) index of the median result (in terms of rmse) for each sequence. If num_iter is even this will be the middle result with larger error. """ def __init__(self, run_folder, folder_names, errors, scales, scale_errors, percentage_done, dataset: Dataset): self.run_folder = run_folder self.folder_names = folder_names self.errors = errors self.scales = scales self.scale_errors = scale_errors self.percentage_done = percentage_done self.name = None self.dataset = dataset self.num_iter = errors.shape[0] # Compute median results. self.median_errors = np.median(errors, axis=0) # Note: When even we use the worse of the middle results. self.median_index = np.argsort(errors, axis=0)[errors.shape[0] // 2, :] # We don't save median scale, but the scale of the median result (according to rmse). # The reason is that we think it makes more sense to sort results based on rmse than on scale error, but # probably both would be fine. self.median_scale_errors = np.take_along_axis(scale_errors, self.median_index[None, :], axis=0).flatten() def evaluate_with_config(pair, always_reevaluate=False): """ Evaluate a run (compute rmse, scale_error, etc.) for all sequences. If already evaluated it will just load the results from file. :param pair: one entry in the list computed by load_result_yamls (first folder, then loaded config). :param always_reevaluate: If true the results will be re-evaluated even if results have already been saved to file. :return: result (uses estimated scale), result_gt_scaled (uses groundtruth scale); both of type EvalResults. """ folder, setup = pair dataset_name = setup['dataset'] noimu_bool = 'noimu' in setup and setup['noimu'] if 'tumvi' in dataset_name: dataset = Dataset.tumvi elif '4seasons' in dataset_name: dataset = Dataset.four_seasons elif 'euroc' in dataset_name: dataset = Dataset.euroc else: raise ValueError("ERROR: Unknown dataset") return evaluate_run(folder, dataset, setup['num_iter'], None, always_reevaluate) def evaluate_run(run_folder: Path, dataset: Dataset, num_iter: int, name=None, always_reevaluate=False) -> ( EvalResults, EvalResults): """Evaluate all sequences and iterations of a run and save it to file (and return it). If the evaluation result has already been saved to file it will just load it. returns :param run_folder: Folder of the run which will be evaluated. :param dataset: Dataset to evaluate on. :param num_iter: Number of iterations this run used. :param name: Name which will be stored in the returned results. :param always_reevaluate: If true the results will be re-evaluated even if results have already been saved to file. :return: result (uses estimated scale), result_gt_scaled (uses groundtruth scale); both of type EvalResults. """ np.set_printoptions(precision=3, suppress=True) # First check if result already exists. if not always_reevaluate: result, result_gt_scale = load_eval_results_from_folder(run_folder, dataset) if not result is None: print('Loaded pre-evaluated results from file.') if not name is None: result.name = name result_gt_scale.name = 'gt_scale_' + name return result, result_gt_scale print("Evaluating now.") sequences, time_threshold = get_groundtruth_data(dataset) # Rows are iterations, columns are sequences. all_percentage_done = np.zeros((num_iter, len(sequences))) all_rmse = np.ones((num_iter, len(sequences))) * np.inf all_scales = np.ones((num_iter, len(sequences))) * np.inf all_scale_errors = np.ones((num_iter, len(sequences))) * np.inf all_rmse_gt_scaled = np.ones((num_iter, len(sequences))) * np.inf all_gt_scales = np.ones((num_iter, len(sequences))) * np.inf for i, sequence in enumerate(tqdm(sequences, leave=False)): for iter in range(num_iter): results_file = run_folder / 'results' / '{}_{}.txt'.format(sequence.folder, iter) if results_file.exists(): # Read scale to use from scale file. scale_file = run_folder / '{}_{}'.format(sequence.folder, iter) / 'scalesdso.txt' if not scale_file.exists(): print("WARNING: No scale file exists --> assuming scale of 1.") scale = 1.0 else: try: scale = get_estimated_scale(scale_file) except IndexError: print("WARNING: Could not get scale for result {}. --> Skipping.".format(results_file)) continue result, result_gt_scale, min_and_max_time = evaluate_ate.compute_ate_fast(sequence.groundtruth_data, results_file, scale, 0.05, allow_unassociated=( dataset != Dataset.euroc)) # Compute percentage of the sequence completed and invalidate result if it is too low. percentage_done = (min_and_max_time[1] - min_and_max_time[0]) / sequence.duration # Enforce that incomplete sequences don't count as success. if percentage_done < time_threshold: if not result is None: result.rmse = float('inf') result_gt_scale.rmse = float('inf') all_percentage_done[iter, i] = percentage_done all_rmse[iter, i] = result.rmse all_scales[iter, i] = result.scale all_scale_errors[iter, i] = get_scale_error(result.scale, result_gt_scale.scale) all_rmse_gt_scaled[iter, i] = result_gt_scale.rmse all_gt_scales[iter, i] = result_gt_scale.scale else: print('WARNING: Skipping because does not exist: {}'.format(results_file)) folder_names = [sequence.folder for sequence in sequences] result = EvalResults(run_folder, folder_names, all_rmse, all_scales, all_scale_errors, all_percentage_done, dataset) result_gt_scale = EvalResults(run_folder, folder_names, all_rmse_gt_scaled, all_gt_scales, np.zeros((num_iter, len(sequences))), all_percentage_done, dataset) # Save result. save_results_to_folder(run_folder, result, result_gt_scale) if not name is None: result.name = name result_gt_scale.name = 'gt_scale_' + name return result, result_gt_scale def get_scale_error(estimated_scale, gt_scale): scale_err = gt_scale / estimated_scale # Note that we do not use the more simple formulation of # scale_err_simple = abs(gt_scale / estimated_scale - 1) # The simple formulation can only a get a maximum scale error of 100% in one direction, # whereas ours is symmetric (in the way that a too large and a too small scale both have the same effect). # For small scale errors as present in most evaluations they are very similar though, so in practice it only makes # a small difference. if scale_err < 1: scale_err = 1.0 / scale_err scale_err = scale_err - 1 # return in percentage. return scale_err * 100 def get_estimated_scale(scale_filename): """Read the estimated scale from file.""" with open(scale_filename) as scale_file: lines = scale_file.readlines() # We use the latest estimated scale. return float(lines[-1].split(' ')[1]) def load_eval_results_from_folder(folder: Path, dataset: Dataset): """ if EvalResults have been stored to file they will be read by this method.""" filename = folder / 'setup' / 'evaluation_results.txt' if not filename.exists(): return None, None try: yaml = YAML() with open(filename, 'r') as results_file: eval_results = yaml.load(results_file) folder_names = eval_results['folder_names'] results = eval_results['results'] results_gt_scale = eval_results['results_gt_scale'] results_out = EvalResults(folder, folder_names, np.array(results['errors']), np.array(results['scales']), np.array(results['scale_errors']), np.array(results['percentage_done']), dataset) results_gt_scale_out = EvalResults(folder, folder_names, np.array(results_gt_scale['errors']), np.array(results_gt_scale['scales']), np.array(results_gt_scale['scale_errors']), np.array(results_gt_scale['percentage_done']), dataset) except KeyError: return None, None return results_out, results_gt_scale_out def save_results_to_folder(folder: Path, results: EvalResults, results_gt_scale: EvalResults): """Save the evaluation results to file.""" filename = folder / 'setup' / 'evaluation_results.txt' res = { 'folder_names': results.folder_names, 'results': { 'errors': results.errors.tolist(), 'scales': results.errors.tolist(), 'scale_errors': results.scale_errors.tolist(), 'percentage_done': results.percentage_done.tolist() }, 'results_gt_scale': { 'errors': results_gt_scale.errors.tolist(), 'scales': results_gt_scale.errors.tolist(), 'scale_errors': results_gt_scale.scale_errors.tolist(), 'percentage_done': results_gt_scale.percentage_done.tolist() } } yaml = YAML() with open(filename, 'w') as results_file: yaml.dump(res, results_file) class GroundtruthDataForSequence: def __init__(self, folder, start_time, end_time, times_file, groundtruth_file): self.folder = folder self.start_time = start_time self.end_time = end_time self.times_file = times_file self.groundtruth_file = groundtruth_file # Preload GT data. self.groundtruth_data = associate.read_file_list(self.groundtruth_file) # Read times data with open(self.times_file) as times_file_handle: times_lines = times_file_handle.readlines() self.times = [float(line.split(' ')[1]) for line in times_lines if not line.startswith('#')] # start_time and end_time are the start and end frame (starting with 0). These are the times for them. real_start_time = self.times[start_time] real_end_time = self.times[-1] if end_time is None else self.times[end_time] self.duration = real_end_time - real_start_time def get_groundtruth_data(dataset: Dataset): # We don't just read them from configs.yaml, so that different configs (e.g. 4seasons and 4seasonsCR) can be # compared against each other without having the risk that different params are used for the evaluation. # groundtruth files are stored in this repository. groundtruth_folder = Path('groundtruth_files') if dataset == Dataset.euroc: folder_names = ['MH_01_easy', 'MH_02_easy', 'MH_03_medium', 'MH_04_difficult', 'MH_05_difficult', 'V1_01_easy', 'V1_02_medium', 'V1_03_difficult', 'V2_01_easy', 'V2_02_medium', 'V2_03_difficult'] start_times = [950, 800, 410, 445, 460, 22, 115, 250, 26, 100, 115] end_times = [3600, 3000, 2600, 1925, 2200, 2800, 1600, 2020, 2130, 2230, 1880] res_prefix = 'mav_' folder_names = [res_prefix + folder for folder in folder_names] path = groundtruth_folder / 'euroc' time_th = 0.8 # Threshold taken over from DSO Matlab evaluation tools. # return GroundtruthData and time threshold return [GroundtruthDataForSequence(folder_names[i], start_times[i], end_times[i], path / 'timesFiles' / '{}.txt'.format(folder_names[i]), path / 'gtFiles' / '{}.txt'.format(folder_names[i]) ) for i in range(len(folder_names))], time_th elif dataset == Dataset.tumvi: folder_names = ['dataset-corridor1_512_16', 'dataset-corridor2_512_16', 'dataset-corridor3_512_16', 'dataset-corridor4_512_16', 'dataset-corridor5_512_16', 'dataset-magistrale1_512_16', 'dataset-magistrale2_512_16', 'dataset-magistrale3_512_16', 'dataset-magistrale4_512_16', 'dataset-magistrale5_512_16', 'dataset-magistrale6_512_16', 'dataset-outdoors1_512_16', 'dataset-outdoors2_512_16', 'dataset-outdoors3_512_16', 'dataset-outdoors4_512_16', 'dataset-outdoors5_512_16', 'dataset-outdoors6_512_16', 'dataset-outdoors7_512_16', 'dataset-outdoors8_512_16', 'dataset-room1_512_16', 'dataset-room2_512_16', 'dataset-room3_512_16', 'dataset-room4_512_16', 'dataset-room5_512_16', 'dataset-room6_512_16', 'dataset-slides1_512_16', 'dataset-slides2_512_16', 'dataset-slides3_512_16'] res_prefix = 'tumvi_' folder_names = [res_prefix + folder for folder in folder_names] time_th = 0.9 # For TUM-VI we use a larger threshold to ensure that both, the start and the end of the sequence # are evaluated # return GroundtruthData and time threshold path = groundtruth_folder / 'tumvi' return [GroundtruthDataForSequence(folder_names[i], 2, None, path / 'timesFiles' / '{}.txt'.format(folder_names[i]), path / 'gtFiles' / '{}.txt'.format(folder_names[i]) ) for i in range(len(folder_names))], time_th elif dataset == Dataset.four_seasons: folder_names = ['office_2021-01-07_12-04-03', 'office_2021-02-25_13-51-57', 'office_2020-03-24_17-36-22', 'office_2020-03-24_17-45-31', 'office_2020-04-07_10-20-32', 'office_2020-06-12_10-10-57', 'neighbor_2020-10-07_14-47-51', 'neighbor_2020-10-07_14-53-52', 'neighbor_2020-12-22_11-54-24', 'neighbor_2021-02-25_13-25-15', 'neighbor_2020-03-26_13-32-55', 'neighbor_2021-05-10_18-02-12', 'neighbor_2021-05-10_18-32-32', 'business_2021-01-07_13-12-23', 'business_2021-02-25_14-16-43', 'business_2020-10-08_09-30-57', 'country_2020-10-08_09-57-28', 'country_2021-01-07_13-30-07', 'country_2020-04-07_11-33-45', 'country_2020-06-12_11-26-43', 'city_2020-12-22_11-33-15', 'city_2021-01-07_14-36-17', 'city_2021-02-25_11-09-49', 'oldtown_2020-10-08_11-53-41', 'oldtown_2021-01-07_10-49-45', 'oldtown_2021-02-25_12-34-08', 'oldtown_2021-05-10_21-32-00', 'parking_2020-12-22_12-04-35', 'parking_2021-02-25_13-39-06', 'parking_2021-05-10_19-15-19'] res_prefix = '4seasons_' folder_names = [res_prefix + folder for folder in folder_names] time_th = 0.9 # return GroundtruthData and time threshold path = groundtruth_folder / '4seasons' return [GroundtruthDataForSequence(folder_names[i], 2, None, path / 'timesFiles' / '{}.txt'.format(folder_names[i]), path / 'gtFiles' / '{}.txt'.format(folder_names[i]) ) for i in range(len(folder_names))], time_th
[ "tqdm.tqdm", "numpy.set_printoptions", "trajectory_evaluation.associate.read_file_list", "numpy.median", "ruamel.yaml.YAML", "numpy.argsort", "pathlib.Path", "numpy.array", "trajectory_evaluation.evaluate_ate.compute_ate_fast", "numpy.take_along_axis" ]
[((5953, 6000), 'numpy.set_printoptions', 'np.set_printoptions', ([], {'precision': '(3)', 'suppress': '(True)'}), '(precision=3, suppress=True)\n', (5972, 6000), True, 'import numpy as np\n'), ((12984, 12990), 'ruamel.yaml.YAML', 'YAML', ([], {}), '()\n', (12988, 12990), False, 'from ruamel.yaml import YAML\n'), ((14379, 14404), 'pathlib.Path', 'Path', (['"""groundtruth_files"""'], {}), "('groundtruth_files')\n", (14383, 14404), False, 'from pathlib import Path\n'), ((3584, 3609), 'numpy.median', 'np.median', (['errors'], {'axis': '(0)'}), '(errors, axis=0)\n', (3593, 3609), True, 'import numpy as np\n'), ((6988, 7016), 'tqdm.tqdm', 'tqdm', (['sequences'], {'leave': '(False)'}), '(sequences, leave=False)\n', (6992, 7016), False, 'from tqdm import tqdm\n'), ((11206, 11212), 'ruamel.yaml.YAML', 'YAML', ([], {}), '()\n', (11210, 11212), False, 'from ruamel.yaml import YAML\n'), ((13439, 13486), 'trajectory_evaluation.associate.read_file_list', 'associate.read_file_list', (['self.groundtruth_file'], {}), '(self.groundtruth_file)\n', (13463, 13486), True, 'import trajectory_evaluation.associate as associate\n'), ((3705, 3731), 'numpy.argsort', 'np.argsort', (['errors'], {'axis': '(0)'}), '(errors, axis=0)\n', (3715, 3731), True, 'import numpy as np\n'), ((11525, 11552), 'numpy.array', 'np.array', (["results['errors']"], {}), "(results['errors'])\n", (11533, 11552), True, 'import numpy as np\n'), ((11554, 11581), 'numpy.array', 'np.array', (["results['scales']"], {}), "(results['scales'])\n", (11562, 11581), True, 'import numpy as np\n'), ((11617, 11650), 'numpy.array', 'np.array', (["results['scale_errors']"], {}), "(results['scale_errors'])\n", (11625, 11650), True, 'import numpy as np\n'), ((11652, 11688), 'numpy.array', 'np.array', (["results['percentage_done']"], {}), "(results['percentage_done'])\n", (11660, 11688), True, 'import numpy as np\n'), ((11764, 11800), 'numpy.array', 'np.array', (["results_gt_scale['errors']"], {}), "(results_gt_scale['errors'])\n", (11772, 11800), True, 'import numpy as np\n'), ((11845, 11881), 'numpy.array', 'np.array', (["results_gt_scale['scales']"], {}), "(results_gt_scale['scales'])\n", (11853, 11881), True, 'import numpy as np\n'), ((11926, 11968), 'numpy.array', 'np.array', (["results_gt_scale['scale_errors']"], {}), "(results_gt_scale['scale_errors'])\n", (11934, 11968), True, 'import numpy as np\n'), ((12013, 12058), 'numpy.array', 'np.array', (["results_gt_scale['percentage_done']"], {}), "(results_gt_scale['percentage_done'])\n", (12021, 12058), True, 'import numpy as np\n'), ((4038, 4106), 'numpy.take_along_axis', 'np.take_along_axis', (['scale_errors', 'self.median_index[None, :]'], {'axis': '(0)'}), '(scale_errors, self.median_index[None, :], axis=0)\n', (4056, 4106), True, 'import numpy as np\n'), ((7855, 7987), 'trajectory_evaluation.evaluate_ate.compute_ate_fast', 'evaluate_ate.compute_ate_fast', (['sequence.groundtruth_data', 'results_file', 'scale', '(0.05)'], {'allow_unassociated': '(dataset != Dataset.euroc)'}), '(sequence.groundtruth_data, results_file,\n scale, 0.05, allow_unassociated=dataset != Dataset.euroc)\n', (7884, 7987), True, 'import trajectory_evaluation.evaluate_ate as evaluate_ate\n')]
import sys sys.path.append('./src/') import numpy as np import networkx as nx from util import * import matplotlib.pyplot as plt n = 50 d_list = [3] numtrials = 10 numinnertrials = 100 s_upperlim = 8 upper_bound = [] max_lower_bound = [] avg_lin_err = [] avg_opt_err = [] for d_index in range(len(d_list)): d = d_list[d_index] s_set = list(range(d,s_upperlim)) print("Starting d = " + str(d)) for t1 in range(numtrials): # Random d-regular graph tests --- expander_ver=0 B = getBapprox(n,d,0) assert(all((B[:] == B.T[:]).ravel())) #checking to make sure B is symmetric eigs, eigvecs = np.linalg.eig(d*B) eigs.sort() lambd = max(abs(eigs[0]), abs(eigs[-2])) # # Random d-reg bipartite graphs --- expander_ver=1 # B = getBapprox(n,d,1) # a1 = np.dot(np.array(B), np.ones(n)) # a2 = np.dot(np.array(B.T), np.ones(n)) # assert(np.linalg.norm(a1 - a2,ord = np.inf) <= 1e-5) # U, svals, V = np.linalg.svd(d*B) # svals.sort() # lambd = max(abs(svals[0]), abs(svals[-2])) # # Random margulis graphs --- expander_ver=2 # assert(d==8) # B = getBapprox(n,d,2) # assert(all((B[:] == B.T[:]).ravel())) #checking to make sure B is symmetric # eigs, eigvecs = np.linalg.eig(d*B) # eigs.sort() # lambd = max(abs(eigs[0]), abs(eigs[-2])) for s in s_set: upper_bound.append( (d,s,(lambd/d)*np.sqrt(n*s/(n-s)))) max_lower_bound.append( (d,s,np.sqrt(s/d))) lin_err = [] opt_err = [] for t2 in range(numinnertrials): completed_workers = np.array([False]*n, dtype=bool) completed_workers[np.random.permutation(n)[:n-s]] = True Alinear = getArowlinear(completed_workers) completed_ind_set = [i for i in range(n) if completed_workers[i]] Aopt = np.linalg.lstsq(B[completed_ind_set,:].T,np.ones(n))[0] lin_err.append(np.linalg.norm(np.dot(Alinear, B)-np.ones((1,n)))) opt_err.append(np.linalg.norm(np.dot(Aopt,B[completed_ind_set,:])-np.ones((1,n)))) # avg_lin_err.append((d,s,np.linalg.norm(np.dot(Alinear, B)-np.ones((1,n))))) # avg_opt_err.append((d,s,np.linalg.norm(np.dot(Aopt,B[completed_ind_set,:])-np.ones((1,n))))) # print("Linear Error = %.3f, Optimal Error = %.3f"%(np.mean(lin_err),np.mean(opt_err))) avg_lin_err.append((d,s,np.mean(lin_err))) avg_opt_err.append((d,s,np.mean(opt_err))) print("\t Done with trial "+ str(t1)) # ---- Plotting code for d_index in range(len(d_list)): d = d_list[d_index] s_set = list(range(d,s_upperlim)) fig = plt.figure() plt.ylabel('L2-Error') plt.xlabel('No. of Stragglers (s) ') plt.title('L2-Error vs No. of Stragglers') up_set = [] up_err_set = [] max_lb_set = [] lin_set = [] lin_err_set = [] opt_set = [] opt_err_set = [] for s in s_set: up_set.append(np.mean([u[2] for u in upper_bound if u[0]==d and u[1]==s])) up_err_set.append(np.std([u[2] for u in upper_bound if u[0]==d and u[1]==s])) max_lb_set.append(np.mean([u[2] for u in max_lower_bound if u[0]==d and u[1]==s])) lin_set.append(np.mean([u[2] for u in avg_lin_err if u[0]==d and u[1]==s])) lin_err_set.append(np.std([u[2] for u in avg_lin_err if u[0]==d and u[1]==s])) opt_set.append(np.mean([u[2] for u in avg_opt_err if u[0]==d and u[1]==s])) opt_err_set.append(np.std([u[2] for u in avg_opt_err if u[0]==d and u[1]==s])) plt.errorbar(s_set, up_set, yerr=up_err_set, linewidth = 1.2, label = 'Upper Bound (theoretical)') plt.errorbar(s_set, max_lb_set, linewidth = 1.2, label = 'Lower Bound (worst case)') plt.errorbar(s_set, lin_set, yerr=lin_err_set, linewidth = 1.2, label = 'Linear Decoder (avg. case)') plt.errorbar(s_set, opt_set, yerr=opt_err_set, linewidth = 1.2, label = 'Optimal Decoder (avg. case)') plt.legend(loc='best') ax = fig.gca() ax.set_xticks(range(d-1,s_upperlim+1), minor = True) ax.tick_params(axis = 'both', which = 'minor', labelsize = 0) plt.grid(True, which = 'minor', axis = 'x', linestyle = '--', linewidth = '0.4') plt.savefig('randomdreg_d_%d.pdf'%(d)) # plt.savefig('randomdregbip_d_%d.pdf'%(d)) # plt.savefig('randommargulis_d_%d.pdf'%(d)) plt.show() plt.close()
[ "matplotlib.pyplot.title", "numpy.ones", "matplotlib.pyplot.figure", "numpy.mean", "sys.path.append", "numpy.std", "matplotlib.pyplot.close", "numpy.linalg.eig", "matplotlib.pyplot.errorbar", "matplotlib.pyplot.show", "matplotlib.pyplot.legend", "numpy.random.permutation", "numpy.dot", "ma...
[((11, 36), 'sys.path.append', 'sys.path.append', (['"""./src/"""'], {}), "('./src/')\n", (26, 36), False, 'import sys\n'), ((2468, 2480), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2478, 2480), True, 'import matplotlib.pyplot as plt\n'), ((2482, 2504), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""L2-Error"""'], {}), "('L2-Error')\n", (2492, 2504), True, 'import matplotlib.pyplot as plt\n'), ((2506, 2542), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""No. of Stragglers (s) """'], {}), "('No. of Stragglers (s) ')\n", (2516, 2542), True, 'import matplotlib.pyplot as plt\n'), ((2544, 2586), 'matplotlib.pyplot.title', 'plt.title', (['"""L2-Error vs No. of Stragglers"""'], {}), "('L2-Error vs No. of Stragglers')\n", (2553, 2586), True, 'import matplotlib.pyplot as plt\n'), ((3284, 3383), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['s_set', 'up_set'], {'yerr': 'up_err_set', 'linewidth': '(1.2)', 'label': '"""Upper Bound (theoretical)"""'}), "(s_set, up_set, yerr=up_err_set, linewidth=1.2, label=\n 'Upper Bound (theoretical)')\n", (3296, 3383), True, 'import matplotlib.pyplot as plt\n'), ((3384, 3469), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['s_set', 'max_lb_set'], {'linewidth': '(1.2)', 'label': '"""Lower Bound (worst case)"""'}), "(s_set, max_lb_set, linewidth=1.2, label='Lower Bound (worst case)'\n )\n", (3396, 3469), True, 'import matplotlib.pyplot as plt\n'), ((3470, 3572), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['s_set', 'lin_set'], {'yerr': 'lin_err_set', 'linewidth': '(1.2)', 'label': '"""Linear Decoder (avg. case)"""'}), "(s_set, lin_set, yerr=lin_err_set, linewidth=1.2, label=\n 'Linear Decoder (avg. case)')\n", (3482, 3572), True, 'import matplotlib.pyplot as plt\n'), ((3573, 3676), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['s_set', 'opt_set'], {'yerr': 'opt_err_set', 'linewidth': '(1.2)', 'label': '"""Optimal Decoder (avg. case)"""'}), "(s_set, opt_set, yerr=opt_err_set, linewidth=1.2, label=\n 'Optimal Decoder (avg. case)')\n", (3585, 3676), True, 'import matplotlib.pyplot as plt\n'), ((3677, 3699), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""'}), "(loc='best')\n", (3687, 3699), True, 'import matplotlib.pyplot as plt\n'), ((3834, 3906), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'which': '"""minor"""', 'axis': '"""x"""', 'linestyle': '"""--"""', 'linewidth': '"""0.4"""'}), "(True, which='minor', axis='x', linestyle='--', linewidth='0.4')\n", (3842, 3906), True, 'import matplotlib.pyplot as plt\n'), ((3916, 3954), 'matplotlib.pyplot.savefig', 'plt.savefig', (["('randomdreg_d_%d.pdf' % d)"], {}), "('randomdreg_d_%d.pdf' % d)\n", (3927, 3954), True, 'import matplotlib.pyplot as plt\n'), ((4047, 4057), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4055, 4057), True, 'import matplotlib.pyplot as plt\n'), ((4059, 4070), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4068, 4070), True, 'import matplotlib.pyplot as plt\n'), ((607, 627), 'numpy.linalg.eig', 'np.linalg.eig', (['(d * B)'], {}), '(d * B)\n', (620, 627), True, 'import numpy as np\n'), ((2735, 2798), 'numpy.mean', 'np.mean', (['[u[2] for u in upper_bound if u[0] == d and u[1] == s]'], {}), '([u[2] for u in upper_bound if u[0] == d and u[1] == s])\n', (2742, 2798), True, 'import numpy as np\n'), ((2816, 2878), 'numpy.std', 'np.std', (['[u[2] for u in upper_bound if u[0] == d and u[1] == s]'], {}), '([u[2] for u in upper_bound if u[0] == d and u[1] == s])\n', (2822, 2878), True, 'import numpy as np\n'), ((2897, 2964), 'numpy.mean', 'np.mean', (['[u[2] for u in max_lower_bound if u[0] == d and u[1] == s]'], {}), '([u[2] for u in max_lower_bound if u[0] == d and u[1] == s])\n', (2904, 2964), True, 'import numpy as np\n'), ((2980, 3043), 'numpy.mean', 'np.mean', (['[u[2] for u in avg_lin_err if u[0] == d and u[1] == s]'], {}), '([u[2] for u in avg_lin_err if u[0] == d and u[1] == s])\n', (2987, 3043), True, 'import numpy as np\n'), ((3062, 3124), 'numpy.std', 'np.std', (['[u[2] for u in avg_lin_err if u[0] == d and u[1] == s]'], {}), '([u[2] for u in avg_lin_err if u[0] == d and u[1] == s])\n', (3068, 3124), True, 'import numpy as np\n'), ((3140, 3203), 'numpy.mean', 'np.mean', (['[u[2] for u in avg_opt_err if u[0] == d and u[1] == s]'], {}), '([u[2] for u in avg_opt_err if u[0] == d and u[1] == s])\n', (3147, 3203), True, 'import numpy as np\n'), ((3222, 3284), 'numpy.std', 'np.std', (['[u[2] for u in avg_opt_err if u[0] == d and u[1] == s]'], {}), '([u[2] for u in avg_opt_err if u[0] == d and u[1] == s])\n', (3228, 3284), True, 'import numpy as np\n'), ((1498, 1531), 'numpy.array', 'np.array', (['([False] * n)'], {'dtype': 'bool'}), '([False] * n, dtype=bool)\n', (1506, 1531), True, 'import numpy as np\n'), ((1389, 1403), 'numpy.sqrt', 'np.sqrt', (['(s / d)'], {}), '(s / d)\n', (1396, 1403), True, 'import numpy as np\n'), ((2239, 2255), 'numpy.mean', 'np.mean', (['lin_err'], {}), '(lin_err)\n', (2246, 2255), True, 'import numpy as np\n'), ((2285, 2301), 'numpy.mean', 'np.mean', (['opt_err'], {}), '(opt_err)\n', (2292, 2301), True, 'import numpy as np\n'), ((1336, 1360), 'numpy.sqrt', 'np.sqrt', (['(n * s / (n - s))'], {}), '(n * s / (n - s))\n', (1343, 1360), True, 'import numpy as np\n'), ((1552, 1576), 'numpy.random.permutation', 'np.random.permutation', (['n'], {}), '(n)\n', (1573, 1576), True, 'import numpy as np\n'), ((1762, 1772), 'numpy.ones', 'np.ones', (['n'], {}), '(n)\n', (1769, 1772), True, 'import numpy as np\n'), ((1812, 1830), 'numpy.dot', 'np.dot', (['Alinear', 'B'], {}), '(Alinear, B)\n', (1818, 1830), True, 'import numpy as np\n'), ((1831, 1846), 'numpy.ones', 'np.ones', (['(1, n)'], {}), '((1, n))\n', (1838, 1846), True, 'import numpy as np\n'), ((1882, 1919), 'numpy.dot', 'np.dot', (['Aopt', 'B[completed_ind_set, :]'], {}), '(Aopt, B[completed_ind_set, :])\n', (1888, 1919), True, 'import numpy as np\n'), ((1918, 1933), 'numpy.ones', 'np.ones', (['(1, n)'], {}), '((1, n))\n', (1925, 1933), True, 'import numpy as np\n')]
import os import tensorflow as tf import numpy as np import datetime import time import sys import logging from tensorflow.keras.utils import Progbar from src.utils.loss import get_loss from src import models logging.basicConfig(format='[ %(levelname)s ] %(message)s', level=logging.INFO, stream=sys.stdout) class Trainer(object): def __init__(self, cfg, strategy): self.cfg = cfg self.strategy = strategy self.saved_dir = os.path.join(cfg['COMMON']['saved_dir'], f"{cfg['DATASET']['name']}_{cfg['MODEL']['name']}_{cfg['MODEL']['mobile']}_" f"{cfg['DATASET']['use_aid']}") if cfg['DATASET']['name'] == 'coco': num_joints = 19 elif cfg['DATASET']['name'] == 'kinect': num_joints = 33 else: raise NotImplementedError num_pafs = num_joints * 2 with self.strategy.scope(): lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay( initial_learning_rate=cfg['TRAIN']['learning_rate'], decay_steps=cfg['TRAIN']['decay_step'], decay_rate=cfg['TRAIN']['decay_rate'], staircase=True ) self.optimizer = tf.keras.optimizers.RMSprop(learning_rate=lr_schedule) self.model = models.__dict__[cfg['MODEL']['name']](num_channels=cfg['MODEL']['num_channels'], num_refinement_stages=cfg['MODEL']['num_stages'], num_joints=num_joints, num_pafs=num_pafs, mobile=cfg['MODEL']['mobile']) # initialize model self.model(np.zeros((1, cfg['MODEL']['input_size'], cfg['MODEL']['input_size'], 3), dtype=np.float32)) self.model.summary() self.checkpoint = tf.train.Checkpoint(epoch=tf.Variable(0), model=self.model) self.manager = tf.train.CheckpointManager(checkpoint=self.checkpoint, directory=os.path.join(self.saved_dir, 'ckpts'), max_to_keep=5) if cfg['COMMON']['retrain']: self._restore_weight() self._setup_logger() def _restore_weight(self): if self.manager.latest_checkpoint: self.checkpoint.restore(self.manager.latest_checkpoint).assert_consumed() logging.info(f"Restored from {self.manager.latest_checkpoint}") else: logging.info("Initializing from scratch.") def _setup_logger(self): current_time = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") log_dir = os.path.join(self.saved_dir, 'logs', current_time) self.writer = tf.summary.create_file_writer(log_dir) @tf.function def train_step(self, inputs): images, target, mask = inputs with tf.GradientTape() as tape: outputs = self.model(images, training=True) loss = get_loss(target=target, outputs=outputs, mask=mask) grads = tape.gradient(loss, self.model.trainable_weights) self.optimizer.apply_gradients(zip(grads, self.model.trainable_weights)) return loss @tf.function def eval_step(self, inputs): images, target, mask = inputs outputs = self.model(images, training=False) unscaled_loss = get_loss(target=target, outputs=outputs, mask=mask) return unscaled_loss @tf.function def distributed_train_step(self, dist_inputs): def _step_fn(inputs): images, target, mask = inputs with tf.GradientTape() as tape: outputs = self.model(images, training=True) per_batch_loss = get_loss(target=target, outputs=outputs, mask=mask) grads = tape.gradient(per_batch_loss, self.model.trainable_weights) self.optimizer.apply_gradients(zip(grads, self.model.trainable_weights)) return per_batch_loss per_replica_loss = self.strategy.run(_step_fn, args=(dist_inputs,)) mean_loss = self.strategy.reduce( tf.distribute.ReduceOp.MEAN, per_replica_loss, axis=None ) return mean_loss @tf.function def distributed_eval_step(self, dist_inputs): def _step_fn(inputs): images, target, mask = inputs outputs = self.model(images, training=False) per_batch_loss = get_loss(target=target, outputs=outputs, mask=mask) return per_batch_loss per_replica_loss = self.strategy.run(_step_fn, args=(dist_inputs,)) mean_loss = self.strategy.reduce( tf.distribute.ReduceOp.MEAN, per_replica_loss, axis=None ) return mean_loss def custom_loop(self, train_dataset, val_dataset, num_train_batch, num_val_batch): epoch = last_epoch = int(self.checkpoint.epoch) if self.cfg['TRAIN']['num_epochs'] <= int(self.checkpoint.epoch): logging.info("Already reached this epoch") return for ep in range(self.cfg['TRAIN']['num_epochs'] - last_epoch): epoch = ep + 1 + last_epoch logging.info(f'Start of epoch {epoch}') self.checkpoint.epoch.assign_add(1) train_loss = 0 val_loss = 0 step = None train_progbar = Progbar(target=num_train_batch, stateful_metrics=['loss']) val_progbar = Progbar(target=num_val_batch, stateful_metrics=['loss']) start_time = time.time() for step, dist_inputs in enumerate(train_dataset): current_loss = self.train_step(dist_inputs) train_progbar.update(step + 1, [('loss', current_loss)]) train_loss += current_loss train_loss /= step + 1 for step, dist_inputs in enumerate(val_dataset): current_loss = self.eval_step(dist_inputs) val_progbar.update(step + 1, [('loss', current_loss)]) val_loss += current_loss val_loss /= step + 1 end_time = time.time() with self.writer.as_default(): tf.summary.scalar('Training loss', train_loss, step=epoch) tf.summary.scalar('Val loss', val_loss, step=epoch) self.writer.flush() logging.info(f'Epoch {epoch}, Total executing time: {(end_time - start_time):.2f}, ' f'Loss: {train_loss:.3f}, Test Loss: {val_loss:3f}') if epoch % self.cfg['COMMON']['saved_epochs'] == 0: saved_path = self.manager.save() logging.info(f"Saved checkpoint for epoch {epoch}: {saved_path}") logging.info(f"Finish training at {epoch}") self.writer.close() def distributed_custom_loop(self, train_dist_dataset, val_dist_dataset, num_train_batch, num_val_batch): epoch = last_epoch = int(self.checkpoint.epoch) if self.cfg['TRAIN']['num_epochs'] <= int(self.checkpoint.epoch): logging.info("Already reached this epoch") return for ep in range(self.cfg['TRAIN']['num_epochs'] - last_epoch): epoch = ep + 1 + last_epoch logging.info(f'Start of epoch {epoch}') self.checkpoint.epoch.assign_add(1) train_loss = 0 val_loss = 0 step = None train_progbar = Progbar(target=num_train_batch, stateful_metrics=['loss']) val_progbar = Progbar(target=num_val_batch, stateful_metrics=['loss']) start_time = time.time() for step, dist_inputs in enumerate(train_dist_dataset): current_loss = self.distributed_train_step(dist_inputs) train_progbar.update(step + 1, [('loss', current_loss)]) train_loss += current_loss train_loss /= step + 1 for step, dist_inputs in enumerate(val_dist_dataset): current_loss = self.distributed_eval_step(dist_inputs) val_progbar.update(step + 1, [('loss', current_loss)]) val_loss += current_loss val_loss /= step + 1 end_time = time.time() with self.writer.as_default(): tf.summary.scalar('Training loss', train_loss, step=epoch) tf.summary.scalar('Val loss', val_loss, step=epoch) self.writer.flush() logging.info(f'Epoch {epoch}, Total executing time: {(end_time - start_time):.2f}, ' f'Loss: {train_loss:.3f}, Test Loss: {val_loss:.3f}') if epoch % self.cfg['COMMON']['saved_epochs'] == 0: saved_path = self.manager.save() print("Saved checkpoint for epoch {}: {}".format(epoch, saved_path)) print("Finished training at %d" % epoch) self.writer.close()
[ "src.utils.loss.get_loss", "tensorflow.keras.utils.Progbar", "logging.basicConfig", "tensorflow.summary.scalar", "numpy.zeros", "datetime.datetime.now", "time.time", "logging.info", "tensorflow.Variable", "tensorflow.GradientTape", "tensorflow.summary.create_file_writer", "os.path.join", "te...
[((209, 312), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""[ %(levelname)s ] %(message)s"""', 'level': 'logging.INFO', 'stream': 'sys.stdout'}), "(format='[ %(levelname)s ] %(message)s', level=logging.\n INFO, stream=sys.stdout)\n", (228, 312), False, 'import logging\n'), ((453, 607), 'os.path.join', 'os.path.join', (["cfg['COMMON']['saved_dir']", 'f"""{cfg[\'DATASET\'][\'name\']}_{cfg[\'MODEL\'][\'name\']}_{cfg[\'MODEL\'][\'mobile\']}_{cfg[\'DATASET\'][\'use_aid\']}"""'], {}), '(cfg[\'COMMON\'][\'saved_dir\'],\n f"{cfg[\'DATASET\'][\'name\']}_{cfg[\'MODEL\'][\'name\']}_{cfg[\'MODEL\'][\'mobile\']}_{cfg[\'DATASET\'][\'use_aid\']}"\n )\n', (465, 607), False, 'import os\n'), ((2821, 2871), 'os.path.join', 'os.path.join', (['self.saved_dir', '"""logs"""', 'current_time'], {}), "(self.saved_dir, 'logs', current_time)\n", (2833, 2871), False, 'import os\n'), ((2894, 2932), 'tensorflow.summary.create_file_writer', 'tf.summary.create_file_writer', (['log_dir'], {}), '(log_dir)\n', (2923, 2932), True, 'import tensorflow as tf\n'), ((3523, 3574), 'src.utils.loss.get_loss', 'get_loss', ([], {'target': 'target', 'outputs': 'outputs', 'mask': 'mask'}), '(target=target, outputs=outputs, mask=mask)\n', (3531, 3574), False, 'from src.utils.loss import get_loss\n'), ((6853, 6896), 'logging.info', 'logging.info', (['f"""Finish training at {epoch}"""'], {}), "(f'Finish training at {epoch}')\n", (6865, 6896), False, 'import logging\n'), ((978, 1181), 'tensorflow.keras.optimizers.schedules.ExponentialDecay', 'tf.keras.optimizers.schedules.ExponentialDecay', ([], {'initial_learning_rate': "cfg['TRAIN']['learning_rate']", 'decay_steps': "cfg['TRAIN']['decay_step']", 'decay_rate': "cfg['TRAIN']['decay_rate']", 'staircase': '(True)'}), "(initial_learning_rate=cfg[\n 'TRAIN']['learning_rate'], decay_steps=cfg['TRAIN']['decay_step'],\n decay_rate=cfg['TRAIN']['decay_rate'], staircase=True)\n", (1024, 1181), True, 'import tensorflow as tf\n'), ((1280, 1334), 'tensorflow.keras.optimizers.RMSprop', 'tf.keras.optimizers.RMSprop', ([], {'learning_rate': 'lr_schedule'}), '(learning_rate=lr_schedule)\n', (1307, 1334), True, 'import tensorflow as tf\n'), ((2567, 2630), 'logging.info', 'logging.info', (['f"""Restored from {self.manager.latest_checkpoint}"""'], {}), "(f'Restored from {self.manager.latest_checkpoint}')\n", (2579, 2630), False, 'import logging\n'), ((2657, 2699), 'logging.info', 'logging.info', (['"""Initializing from scratch."""'], {}), "('Initializing from scratch.')\n", (2669, 2699), False, 'import logging\n'), ((3036, 3053), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (3051, 3053), True, 'import tensorflow as tf\n'), ((3138, 3189), 'src.utils.loss.get_loss', 'get_loss', ([], {'target': 'target', 'outputs': 'outputs', 'mask': 'mask'}), '(target=target, outputs=outputs, mask=mask)\n', (3146, 3189), False, 'from src.utils.loss import get_loss\n'), ((4582, 4633), 'src.utils.loss.get_loss', 'get_loss', ([], {'target': 'target', 'outputs': 'outputs', 'mask': 'mask'}), '(target=target, outputs=outputs, mask=mask)\n', (4590, 4633), False, 'from src.utils.loss import get_loss\n'), ((5121, 5163), 'logging.info', 'logging.info', (['"""Already reached this epoch"""'], {}), "('Already reached this epoch')\n", (5133, 5163), False, 'import logging\n'), ((5306, 5345), 'logging.info', 'logging.info', (['f"""Start of epoch {epoch}"""'], {}), "(f'Start of epoch {epoch}')\n", (5318, 5345), False, 'import logging\n'), ((5498, 5556), 'tensorflow.keras.utils.Progbar', 'Progbar', ([], {'target': 'num_train_batch', 'stateful_metrics': "['loss']"}), "(target=num_train_batch, stateful_metrics=['loss'])\n", (5505, 5556), False, 'from tensorflow.keras.utils import Progbar\n'), ((5583, 5639), 'tensorflow.keras.utils.Progbar', 'Progbar', ([], {'target': 'num_val_batch', 'stateful_metrics': "['loss']"}), "(target=num_val_batch, stateful_metrics=['loss'])\n", (5590, 5639), False, 'from tensorflow.keras.utils import Progbar\n'), ((5665, 5676), 'time.time', 'time.time', ([], {}), '()\n', (5674, 5676), False, 'import time\n'), ((6240, 6251), 'time.time', 'time.time', ([], {}), '()\n', (6249, 6251), False, 'import time\n'), ((6487, 6628), 'logging.info', 'logging.info', (['f"""Epoch {epoch}, Total executing time: {end_time - start_time:.2f}, Loss: {train_loss:.3f}, Test Loss: {val_loss:3f}"""'], {}), "(\n f'Epoch {epoch}, Total executing time: {end_time - start_time:.2f}, Loss: {train_loss:.3f}, Test Loss: {val_loss:3f}'\n )\n", (6499, 6628), False, 'import logging\n'), ((7177, 7219), 'logging.info', 'logging.info', (['"""Already reached this epoch"""'], {}), "('Already reached this epoch')\n", (7189, 7219), False, 'import logging\n'), ((7362, 7401), 'logging.info', 'logging.info', (['f"""Start of epoch {epoch}"""'], {}), "(f'Start of epoch {epoch}')\n", (7374, 7401), False, 'import logging\n'), ((7554, 7612), 'tensorflow.keras.utils.Progbar', 'Progbar', ([], {'target': 'num_train_batch', 'stateful_metrics': "['loss']"}), "(target=num_train_batch, stateful_metrics=['loss'])\n", (7561, 7612), False, 'from tensorflow.keras.utils import Progbar\n'), ((7639, 7695), 'tensorflow.keras.utils.Progbar', 'Progbar', ([], {'target': 'num_val_batch', 'stateful_metrics': "['loss']"}), "(target=num_val_batch, stateful_metrics=['loss'])\n", (7646, 7695), False, 'from tensorflow.keras.utils import Progbar\n'), ((7721, 7732), 'time.time', 'time.time', ([], {}), '()\n', (7730, 7732), False, 'import time\n'), ((8330, 8341), 'time.time', 'time.time', ([], {}), '()\n', (8339, 8341), False, 'import time\n'), ((8577, 8719), 'logging.info', 'logging.info', (['f"""Epoch {epoch}, Total executing time: {end_time - start_time:.2f}, Loss: {train_loss:.3f}, Test Loss: {val_loss:.3f}"""'], {}), "(\n f'Epoch {epoch}, Total executing time: {end_time - start_time:.2f}, Loss: {train_loss:.3f}, Test Loss: {val_loss:.3f}'\n )\n", (8589, 8719), False, 'import logging\n'), ((1807, 1901), 'numpy.zeros', 'np.zeros', (["(1, cfg['MODEL']['input_size'], cfg['MODEL']['input_size'], 3)"], {'dtype': 'np.float32'}), "((1, cfg['MODEL']['input_size'], cfg['MODEL']['input_size'], 3),\n dtype=np.float32)\n", (1815, 1901), True, 'import numpy as np\n'), ((2017, 2031), 'tensorflow.Variable', 'tf.Variable', (['(0)'], {}), '(0)\n', (2028, 2031), True, 'import tensorflow as tf\n'), ((2189, 2226), 'os.path.join', 'os.path.join', (['self.saved_dir', '"""ckpts"""'], {}), "(self.saved_dir, 'ckpts')\n", (2201, 2226), False, 'import os\n'), ((2753, 2776), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2774, 2776), False, 'import datetime\n'), ((3762, 3779), 'tensorflow.GradientTape', 'tf.GradientTape', ([], {}), '()\n', (3777, 3779), True, 'import tensorflow as tf\n'), ((3882, 3933), 'src.utils.loss.get_loss', 'get_loss', ([], {'target': 'target', 'outputs': 'outputs', 'mask': 'mask'}), '(target=target, outputs=outputs, mask=mask)\n', (3890, 3933), False, 'from src.utils.loss import get_loss\n'), ((6312, 6370), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Training loss"""', 'train_loss'], {'step': 'epoch'}), "('Training loss', train_loss, step=epoch)\n", (6329, 6370), True, 'import tensorflow as tf\n'), ((6387, 6438), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Val loss"""', 'val_loss'], {'step': 'epoch'}), "('Val loss', val_loss, step=epoch)\n", (6404, 6438), True, 'import tensorflow as tf\n'), ((6779, 6844), 'logging.info', 'logging.info', (['f"""Saved checkpoint for epoch {epoch}: {saved_path}"""'], {}), "(f'Saved checkpoint for epoch {epoch}: {saved_path}')\n", (6791, 6844), False, 'import logging\n'), ((8402, 8460), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Training loss"""', 'train_loss'], {'step': 'epoch'}), "('Training loss', train_loss, step=epoch)\n", (8419, 8460), True, 'import tensorflow as tf\n'), ((8477, 8528), 'tensorflow.summary.scalar', 'tf.summary.scalar', (['"""Val loss"""', 'val_loss'], {'step': 'epoch'}), "('Val loss', val_loss, step=epoch)\n", (8494, 8528), True, 'import tensorflow as tf\n')]
from torch.utils.data import Dataset from skimage.io import imread from os.path import join from glob import glob from PIL import Image from numpy import zeros from json import load class Dataset(Dataset): """Dataset for images""" def __init__(self, root_dir, joint_transform=None, input_transform=None, target_transform=None): """ Args: root_dir (string): Directory with all the images and ground truth. joint_transform (callable, optional): Optional transform to be applied to both input and mask. input_transform (callable, optional): Optional transform to be applied on input. target_transform (callable, optional): Optional transform to be applied on mask. """ self.root_dir = root_dir self.names = sorted(glob(join(self.root_dir, 'image_*.tif'))) self.masks = sorted(glob(join(self.root_dir, 'mask_*.tif'))) self.joint_transform = joint_transform self.input_transform = input_transform self.target_transform = target_transform def __len__(self): return len(self.names) def __getitem__(self, idx): #name = # image = imread(self.names[idx]) #image[int(image.shape[0]/2)-10:int(image.shape[0]/2)+10,int(image.shape[1]/2)-10:int(image.shape[1]/2)+10,:] = [255, 255, 255] if len(self.masks) != 0: mask = Image.fromarray(imread(self.masks[idx])) else: mask = Image.fromarray(zeros((image.shape[0], image.shape[1]))) image = Image.fromarray(image) if self.joint_transform: image, mask = self.joint_transform(image, mask) if self.input_transform: image = self.input_transform(image) if self.target_transform: mask = self.target_transform(mask) return image, mask
[ "PIL.Image.fromarray", "numpy.zeros", "os.path.join", "skimage.io.imread" ]
[((1233, 1256), 'skimage.io.imread', 'imread', (['self.names[idx]'], {}), '(self.names[idx])\n', (1239, 1256), False, 'from skimage.io import imread\n'), ((1592, 1614), 'PIL.Image.fromarray', 'Image.fromarray', (['image'], {}), '(image)\n', (1607, 1614), False, 'from PIL import Image\n'), ((862, 896), 'os.path.join', 'join', (['self.root_dir', '"""image_*.tif"""'], {}), "(self.root_dir, 'image_*.tif')\n", (866, 896), False, 'from os.path import join\n'), ((932, 965), 'os.path.join', 'join', (['self.root_dir', '"""mask_*.tif"""'], {}), "(self.root_dir, 'mask_*.tif')\n", (936, 965), False, 'from os.path import join\n'), ((1461, 1484), 'skimage.io.imread', 'imread', (['self.masks[idx]'], {}), '(self.masks[idx])\n', (1467, 1484), False, 'from skimage.io import imread\n'), ((1535, 1574), 'numpy.zeros', 'zeros', (['(image.shape[0], image.shape[1])'], {}), '((image.shape[0], image.shape[1]))\n', (1540, 1574), False, 'from numpy import zeros\n')]
import mpld3 from mpld3 import plugins import matplotlib.pyplot as plt import numpy as np def main(): fig, ax = plt.subplots(2, 2, sharex='col', sharey='row') X = np.random.normal(0, 1, (2, 100)) for i in range(2): for j in range(2): points = ax[1 - i, j].scatter(X[i], X[j]) plugins.connect(fig, plugins.LinkedBrush(points)) return fig if __name__ == '__main__': fig = main() plt.show()
[ "mpld3.plugins.LinkedBrush", "matplotlib.pyplot.subplots", "numpy.random.normal", "matplotlib.pyplot.show" ]
[((117, 163), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(2)', '(2)'], {'sharex': '"""col"""', 'sharey': '"""row"""'}), "(2, 2, sharex='col', sharey='row')\n", (129, 163), True, 'import matplotlib.pyplot as plt\n'), ((173, 205), 'numpy.random.normal', 'np.random.normal', (['(0)', '(1)', '(2, 100)'], {}), '(0, 1, (2, 100))\n', (189, 205), True, 'import numpy as np\n'), ((431, 441), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (439, 441), True, 'import matplotlib.pyplot as plt\n'), ((337, 364), 'mpld3.plugins.LinkedBrush', 'plugins.LinkedBrush', (['points'], {}), '(points)\n', (356, 364), False, 'from mpld3 import plugins\n')]
#!/usr/bin/python # Copyright 2022 <NAME> (<EMAIL>) # scipy based WAV -> C64 TAP converter. # https://web.archive.org/web/20180709173001/http://c64tapes.org/dokuwiki/doku.php?id=analyzing_loaders#tap_format # http://unusedino.de/ec64/technical/formats/tap.html import argparse import struct import pandas as pd import numpy as np import scipy.io.wavfile parser = argparse.ArgumentParser(description='Convert WAV file into a C64 .tap file') parser.add_argument('wavfile', help='input WAV file') parser.add_argument('--cpufreq', default=int(985248), help='CPU frequency in Hz') args = parser.parse_args() # TODO: could add audio/gain processing here. sr, x = scipy.io.wavfile.read(args.wavfile) if len(x.shape) == 1: df = pd.DataFrame(x, columns=['s'], dtype=pd.Float32Dtype()) else: # if stereo, mean of channel samples df = pd.DataFrame(np.column_stack(np.transpose(x)), columns=['x', 'y'], dtype=pd.Float32Dtype()) df['s'] = df.mean(axis=1) # calculate timestamps df['t'] = df.index / sr * 1e6 df['t'] = df['t'].astype(np.uint64) # calculate zero crossings, between samples df['ls'] = df['s'].shift(1).fillna(0) df.loc[(df.ls == df.s), ['ls', 's']] = pd.NA df['zo'] = df.ls / (df.ls - df.s) df.loc[~((df.ls < 0) & (df.s >= 0)), ['zo']] = pd.NA df['lastzo'] = df['zo'].shift().fillna(method='ffill') df['zt'] = df['t'] + df['zo'] - df['lastzo'] # select zero crossings df = df[df['zt'].notna()] # calculate pulse length bytes df['pl'] = df.zt.diff().fillna(0) * ((1e-6 * args.cpufreq) / 8) # remove overflows df.loc[df['pl'] > 255, ['pl']] = 0 df['pl'] = df.pl.fillna(0).astype(np.uint8) outfile = args.wavfile.replace('.wav', '.tap') assert args.wavfile != outfile with open(outfile, 'wb') as f: f.write(bytes('C64-TAPE-RAW', 'utf8')) # version 0, no long pulse handling f.write(struct.pack('b', 0)) # reserved f.write(bytes(3)) # payload f.write(struct.pack('I', len(df.pl))) f.write(df.pl.to_numpy().tobytes())
[ "numpy.transpose", "argparse.ArgumentParser", "struct.pack", "pandas.Float32Dtype" ]
[((368, 444), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Convert WAV file into a C64 .tap file"""'}), "(description='Convert WAV file into a C64 .tap file')\n", (391, 444), False, 'import argparse\n'), ((1819, 1838), 'struct.pack', 'struct.pack', (['"""b"""', '(0)'], {}), "('b', 0)\n", (1830, 1838), False, 'import struct\n'), ((767, 784), 'pandas.Float32Dtype', 'pd.Float32Dtype', ([], {}), '()\n', (782, 784), True, 'import pandas as pd\n'), ((871, 886), 'numpy.transpose', 'np.transpose', (['x'], {}), '(x)\n', (883, 886), True, 'import numpy as np\n'), ((915, 932), 'pandas.Float32Dtype', 'pd.Float32Dtype', ([], {}), '()\n', (930, 932), True, 'import pandas as pd\n')]
import click import pandas as pd import plotly.express as px from numpy import log10, sqrt __all__ = ["plot_overall_ss"] @click.command() @click.argument( "scores", type=click.Path( exists=False, dir_okay=False, file_okay=True, writable=True, resolve_path=True ), ) def plot_overall_ss( scores: str, ): """ Plot overall SS. """ df = pd.read_csv(scores) fig = plot_ss(df) fig.write_html("ss_curve.html") fig = plot_boxplot_avg(df, "amean", "amean = (sensitivity + specifity) / 2") fig.write_html("amean_ss.html") fig = plot_boxplot_avg(df, "gmean", "gmean = sqrt(sensitivity * specifity)") fig.write_html("gmean_ss.html") title = "Sensitivity (true positive rate) and specificity (true negative rate)" fig = plot_boxplot_score(df, title) fig.write_html("box_ss.html") def plot_ss(df: pd.DataFrame): df = df[df["space_type"] == "prof-target"] df = df[~df["space_repeat"]] title = "Sensitivity (true positive rate) and specificity" title += " (true negative rate) (prof-target, multihit=discard)" fig = px.line( df, x="sensitivity", y="specifity", hover_data=["accession", "e_value"], color="accession", title=title, ) return fig def plot_boxplot_avg(df, y, title): df = df.copy() df = df[df["space_type"] == "prof-target"] df.rename(columns={"space_repeat": "multihit"}, inplace=True) df["multihit"] = ~df["multihit"] df["multihit"] = df["multihit"].astype(str) df["amean"] = (df["sensitivity"] + df["specifity"]) / 2 df["gmean"] = sqrt(df["sensitivity"] * df["specifity"]) df["hmean"] = ( 2 * (df["sensitivity"] * df["specifity"]) / (df["sensitivity"] + df["specifity"]) ) df["-log10(e_value)"] = -log10(df["e_value"]) fig = px.box( df, x="-log10(e_value)", y=y, color="multihit", hover_data=["accession"], title=title, ) fig.update_yaxes(range=[0, 1]) return fig def plot_boxplot_score(df, title): df = df.copy() df = df[df["space_type"] == "prof-target"] df.rename(columns={"space_repeat": "multihit"}, inplace=True) df["multihit"] = ~df["multihit"] df["multihit"] = df["multihit"].astype(str) df0 = df.copy() df1 = df.copy() df0["value"] = df0["sensitivity"] df0["score"] = "sensitivity" df1["value"] = df1["specifity"] df1["score"] = "specifity" df = pd.concat([df0, df1]).reset_index(drop=True) df["-log10(e_value)"] = -log10(df["e_value"]) fig = px.box( df, x="-log10(e_value)", y="value", color="multihit", hover_data=["accession"], title=title, facet_col="score", ) fig.update_yaxes(range=[0, 1]) return fig
[ "plotly.express.box", "pandas.read_csv", "plotly.express.line", "click.command", "click.Path", "numpy.log10", "pandas.concat", "numpy.sqrt" ]
[((125, 140), 'click.command', 'click.command', ([], {}), '()\n', (138, 140), False, 'import click\n'), ((376, 395), 'pandas.read_csv', 'pd.read_csv', (['scores'], {}), '(scores)\n', (387, 395), True, 'import pandas as pd\n'), ((1105, 1221), 'plotly.express.line', 'px.line', (['df'], {'x': '"""sensitivity"""', 'y': '"""specifity"""', 'hover_data': "['accession', 'e_value']", 'color': '"""accession"""', 'title': 'title'}), "(df, x='sensitivity', y='specifity', hover_data=['accession',\n 'e_value'], color='accession', title=title)\n", (1112, 1221), True, 'import plotly.express as px\n'), ((1621, 1662), 'numpy.sqrt', 'sqrt', (["(df['sensitivity'] * df['specifity'])"], {}), "(df['sensitivity'] * df['specifity'])\n", (1625, 1662), False, 'from numpy import log10, sqrt\n'), ((1855, 1953), 'plotly.express.box', 'px.box', (['df'], {'x': '"""-log10(e_value)"""', 'y': 'y', 'color': '"""multihit"""', 'hover_data': "['accession']", 'title': 'title'}), "(df, x='-log10(e_value)', y=y, color='multihit', hover_data=[\n 'accession'], title=title)\n", (1861, 1953), True, 'import plotly.express as px\n'), ((2605, 2728), 'plotly.express.box', 'px.box', (['df'], {'x': '"""-log10(e_value)"""', 'y': '"""value"""', 'color': '"""multihit"""', 'hover_data': "['accession']", 'title': 'title', 'facet_col': '"""score"""'}), "(df, x='-log10(e_value)', y='value', color='multihit', hover_data=[\n 'accession'], title=title, facet_col='score')\n", (2611, 2728), True, 'import plotly.express as px\n'), ((181, 275), 'click.Path', 'click.Path', ([], {'exists': '(False)', 'dir_okay': '(False)', 'file_okay': '(True)', 'writable': '(True)', 'resolve_path': '(True)'}), '(exists=False, dir_okay=False, file_okay=True, writable=True,\n resolve_path=True)\n', (191, 275), False, 'import click\n'), ((1824, 1844), 'numpy.log10', 'log10', (["df['e_value']"], {}), "(df['e_value'])\n", (1829, 1844), False, 'from numpy import log10, sqrt\n'), ((2574, 2594), 'numpy.log10', 'log10', (["df['e_value']"], {}), "(df['e_value'])\n", (2579, 2594), False, 'from numpy import log10, sqrt\n'), ((2499, 2520), 'pandas.concat', 'pd.concat', (['[df0, df1]'], {}), '([df0, df1])\n', (2508, 2520), True, 'import pandas as pd\n')]
# -*- coding:utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import os import logging import json def _parse_db_text(file_name: str, word_index_from=5, label_index_from=3, lower=True, sent_delimiter='\t'): """ Parse virushostdb.tsv """ virus_entities = [] refseq_set = set() if os.path.exists(file_name) is False: logging.error("File is not exists: {}".format(file_name)) return virus_entities, refseq_set try: file = open(file_name, 'r', encoding="utf-8") index = 0 for line in file: if index == 0: index += 1 continue # Replace '\n' if len(line) > 0: line = line[:-1] # virus tax id, # virus name, # virus lineage, # refseq id, # KEGG GENOME, # KEGG DISEASE, # DISEASE # host tax id # host name # host lineage # pmid # evidence # sample type # source organism # 存在 一个 virus tax id 对多个 refseq id 和 对个 host tax id的场景 tokens = line.split(sent_delimiter) if len(tokens) < 14: continue virus_tax_id = tokens[0] refseq_ids = tokens[3] refseq_tokens = refseq_ids.split(',') if refseq_tokens is None or len(refseq_tokens) == 0: continue host_tax_id = tokens[7] for refseq in refseq_tokens: refseq = refseq.strip() refseq = refseq.lower() virus_entity = {} virus_entity['virus_tax_id'] = virus_tax_id virus_entity['virus name'] = tokens[1] virus_entity['virus lineage'] = tokens[2] virus_entity['refseq_id'] = refseq virus_entity['host_tax_id'] = host_tax_id virus_entity['host name'] = tokens[8] virus_entity['host lineage'] = tokens[9] virus_entity['DISEASE'] = tokens[6] virus_entities.append(virus_entity) refseq_set.add(refseq.lower()) #print(virus_entity) #print() index += 1 except Exception as e: logging.error(e) return virus_entities, refseq_set def _parse_genomic_text(file_name: str, refseq_set:set=None, word_index_from:int=5, label_index_from:int=3, lower:bool=True, sent_delimiter:str='\t'): """ Parse virushostdb.tsv """ refseq_entities = {} if os.path.exists(file_name) is False: logging.error("File is not exists: {}".format(file_name)) return refseq_entities try: file = open(file_name, 'r', encoding="utf-8") index = 0 refseq_id = '' refseq = '' for line in file: # Replace '\n' if len(line) > 0: line = line[:-1] if line.startswith('>'): # Replace '>' and '||' line = line[1:-2] if len(refseq_id) > 0 and len(refseq) > 0: refseq_id = refseq_id.lower() # Check refseq_id if refseq_set is not None and refseq_id in refseq_set: refseq_entities[refseq_id] = refseq if len(refseq_entities) == 10: print(refseq) else: print(refseq_id) refseq_id = '' refseq = '' # Sequence_accession virus name # Hostname # Virus lineage # Host lineage # Sample type # Taxonomic identifier tokens = line.split('|') if len(tokens) < 1: continue # refseq_id for ii in range(len(tokens[0])): if tokens[0][ii] == ' ': break refseq_id += tokens[0][ii] #print(refseq_id) else: refseq += line index += 1 if len(refseq_id) > 0 and len(refseq) > 0: refseq_id = refseq_id.lower() # Check refseq_id if refseq_set is not None and refseq_id in refseq_set: refseq_entities[refseq_id] = refseq except Exception as e: logging.error(e) print(index) return refseq_entities if __name__ == '__main__': train_paths = [ "F:\\Research\\Data\\medical\\train.txt", # "E:\\Research\Corpus\\pku_training_bies", # "E:\\Research\Corpus\\weibo_train_bies", # "E:\\Research\Corpus\\people_2014_train_bies", # "E:\\Research\Corpus\\people_1998_train_bies", ] virushostdb_file = '/home/huanghaiping/Research/Medical/VirusHostDb/virushostdb.tsv' virus_entities, refseq_set = _parse_db_text(virushostdb_file) virus_genomic_file = '/home/huanghaiping/Research/Medical/VirusHostDb/virushostdb.formatted.genomic.fna' refset_entities = _parse_genomic_text(virus_genomic_file, refseq_set=refseq_set) print(len(refset_entities)) seq_lens = [] output_file = '/home/huanghaiping/Research/Medical/Data/virus_host_db.txt' with open(output_file, "w") as fh: for virus_entity in virus_entities: refseq_id = virus_entity['refseq_id'] refseq_id = refseq_id.lower() if refseq_id not in refset_entities.keys(): print(virus_entity) virus_entity['refseq'] = refset_entities[refseq_id] seq_len = len(refset_entities[refseq_id]) seq_lens.append(seq_len) if seq_len > 40 * 1024: print(seq_len) fh.write(json.dumps(virus_entity) + '\n') seq_lens = np.array(seq_lens) print("Max len: ", max(seq_lens)) print("Min len: ", min(seq_lens)) print("Mean len: ", np.mean(seq_lens))
[ "logging.error", "os.path.exists", "json.dumps", "numpy.mean", "numpy.array" ]
[((6032, 6050), 'numpy.array', 'np.array', (['seq_lens'], {}), '(seq_lens)\n', (6040, 6050), True, 'import numpy as np\n'), ((396, 421), 'os.path.exists', 'os.path.exists', (['file_name'], {}), '(file_name)\n', (410, 421), False, 'import os\n'), ((2709, 2734), 'os.path.exists', 'os.path.exists', (['file_name'], {}), '(file_name)\n', (2723, 2734), False, 'import os\n'), ((6151, 6168), 'numpy.mean', 'np.mean', (['seq_lens'], {}), '(seq_lens)\n', (6158, 6168), True, 'import numpy as np\n'), ((2425, 2441), 'logging.error', 'logging.error', (['e'], {}), '(e)\n', (2438, 2441), False, 'import logging\n'), ((4602, 4618), 'logging.error', 'logging.error', (['e'], {}), '(e)\n', (4615, 4618), False, 'import logging\n'), ((5981, 6005), 'json.dumps', 'json.dumps', (['virus_entity'], {}), '(virus_entity)\n', (5991, 6005), False, 'import json\n')]
import numpy as np import matplotlib.pyplot as plt from supernet.model import SuperNet from supernet.train import train_supernet_mnist import pickle def main(): # Training settings training_settings = {'seed': 1, 'batch_size': 64, 'test_batch_size': 1000, 'epochs': 14, 'learning_rate': 1.0, 'gamma': 0.7, 'no_cuda': True, 'log_interval': 50, 'save_model': True } # 1. Train SuperNet and evaluate top-1 accuracy of sampled nets top1_oneshot_ = np.array(train_supernet_mnist(SuperNet(conv1channels=8, conv2channels=8, hidden=32), training_settings)) with open('top1_oneshot_.pickle', 'wb') as handle: pickle.dump(top1_oneshot_, handle) fig, ax = plt.subplots() ax.plot(top1_oneshot_, '-s') ax.grid() ax.legend([[0, 0], [1, 0], [0, 1], [1, 1]]) plt.title('One-shot SuperNet training') plt.xlabel('Epoch') plt.ylabel('Top-1 accuracy on test set') fig.savefig('figures/top1_oneshot_.png') plt.show() # 2. Train stand-alone subnets from scratch top1_standalone = [] training_settings['epochs'] = 14 for k, subnet in enumerate([[0, 0], [1, 0], [0, 1], [1, 1]]): top1_standalone.append(train_supernet_mnist(SuperNet(conv1channels=8, conv2channels=8, hidden=32), training_settings, subnet=subnet)) top1_standalone_ = np.array(top1_standalone) with open('top1_standalone_.pickle', 'wb') as handle: pickle.dump(top1_standalone_, handle) fig, ax = plt.subplots() ax.plot(top1_standalone_.T, '-s') ax.grid() ax.legend([[0, 0], [1, 0], [0, 1], [1, 1]]) plt.title('Stand-alone model training') plt.xlabel('Epoch') plt.ylabel('Top-1 accuracy on test set') plt.show() fig, ax = plt.subplots() ax.plot(top1_oneshot_[-1, :], top1_standalone_.T[-1, :], 'o') ax.grid() plt.xlabel('One-shot model accuracy') plt.ylabel('Stand-alone model accuracy') fig.savefig('figures/oneshot_v_standalone_.png') plt.show() if __name__ == '__main__': main()
[ "matplotlib.pyplot.title", "pickle.dump", "matplotlib.pyplot.show", "numpy.array", "matplotlib.pyplot.ylabel", "supernet.model.SuperNet", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.subplots" ]
[((957, 971), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (969, 971), True, 'import matplotlib.pyplot as plt\n'), ((1071, 1110), 'matplotlib.pyplot.title', 'plt.title', (['"""One-shot SuperNet training"""'], {}), "('One-shot SuperNet training')\n", (1080, 1110), True, 'import matplotlib.pyplot as plt\n'), ((1115, 1134), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (1125, 1134), True, 'import matplotlib.pyplot as plt\n'), ((1139, 1179), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Top-1 accuracy on test set"""'], {}), "('Top-1 accuracy on test set')\n", (1149, 1179), True, 'import matplotlib.pyplot as plt\n'), ((1229, 1239), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1237, 1239), True, 'import matplotlib.pyplot as plt\n'), ((1634, 1659), 'numpy.array', 'np.array', (['top1_standalone'], {}), '(top1_standalone)\n', (1642, 1659), True, 'import numpy as np\n'), ((1779, 1793), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1791, 1793), True, 'import matplotlib.pyplot as plt\n'), ((1898, 1937), 'matplotlib.pyplot.title', 'plt.title', (['"""Stand-alone model training"""'], {}), "('Stand-alone model training')\n", (1907, 1937), True, 'import matplotlib.pyplot as plt\n'), ((1942, 1961), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (1952, 1961), True, 'import matplotlib.pyplot as plt\n'), ((1966, 2006), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Top-1 accuracy on test set"""'], {}), "('Top-1 accuracy on test set')\n", (1976, 2006), True, 'import matplotlib.pyplot as plt\n'), ((2011, 2021), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2019, 2021), True, 'import matplotlib.pyplot as plt\n'), ((2037, 2051), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (2049, 2051), True, 'import matplotlib.pyplot as plt\n'), ((2136, 2173), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""One-shot model accuracy"""'], {}), "('One-shot model accuracy')\n", (2146, 2173), True, 'import matplotlib.pyplot as plt\n'), ((2178, 2218), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Stand-alone model accuracy"""'], {}), "('Stand-alone model accuracy')\n", (2188, 2218), True, 'import matplotlib.pyplot as plt\n'), ((2276, 2286), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2284, 2286), True, 'import matplotlib.pyplot as plt\n'), ((907, 941), 'pickle.dump', 'pickle.dump', (['top1_oneshot_', 'handle'], {}), '(top1_oneshot_, handle)\n', (918, 941), False, 'import pickle\n'), ((1726, 1763), 'pickle.dump', 'pickle.dump', (['top1_standalone_', 'handle'], {}), '(top1_standalone_, handle)\n', (1737, 1763), False, 'import pickle\n'), ((719, 772), 'supernet.model.SuperNet', 'SuperNet', ([], {'conv1channels': '(8)', 'conv2channels': '(8)', 'hidden': '(32)'}), '(conv1channels=8, conv2channels=8, hidden=32)\n', (727, 772), False, 'from supernet.model import SuperNet\n'), ((1469, 1522), 'supernet.model.SuperNet', 'SuperNet', ([], {'conv1channels': '(8)', 'conv2channels': '(8)', 'hidden': '(32)'}), '(conv1channels=8, conv2channels=8, hidden=32)\n', (1477, 1522), False, 'from supernet.model import SuperNet\n')]
import numpy as np #As the name says, this class is intended to wrap the raw TPD data. #This means it acts as an interface between the data file (.csv) and the UI. #It also contains the relevant methods for processing the raw data # This could be decoupled by adding a class responsible for the processing. class RawDataWrapper(): def __init__(self, filePath): self.m_filePath = filePath substrings = filePath.split('/') self.m_fileName = substrings[len(substrings) - 1] self.m_dataParsed = False self.m_dataProcessed = False self.m_correctedTemp = None self.m_interpolatedTemp = None self.m_reciprocalTemp = None # self.m_interpolatedTime = None self.m_coveragesNormalized = False self.m_interpolatedData = {} self.m_logInterpolatedData = {} self.m_parsedCoverage = "No coverage in filename!" self.m_parsedCoverageAvailable = False self.m_coverages = {} self.m_parsedExperimentNumber = "No experiment number!" def parseRawDataFile(self): #This function parses the .csv if(self.m_dataParsed): return substrings = self.m_fileName.split(' ') self.m_parsedExperimentNumber = substrings[0] #first substring should always be number for s in substrings: if (s[-1] == 'L' or s[-1] == 'l'): try: s = float(s[:-1]) #this will throw a value error if not possible self.m_parsedCoverage = "{:04.2f}L".format(s) self.m_parsedCoverageAvailable = True break except ValueError: continue #Not a float self.m_headerData = np.loadtxt(self.m_filePath,dtype=str, skiprows=1,max_rows=1, delimiter=',') #second item is the number of lines remaining in the header after the second line headerLength = int(self.m_headerData.item(1)) m_parsedDataTitles = np.loadtxt(self.m_filePath,dtype=str, skiprows=headerLength + 1,max_rows=1, delimiter=',') self.m_listOfColumns = [t for t in [e.strip("\'\"") for e in m_parsedDataTitles.tolist()] if not t == ''] self.m_listOfColumns.remove('Time') #we are ignornign the first column # print(self.m_listOfColumns) #for debugging #parsed data is in row major format i.e. time(ms),temp, m1, m2, m3... temp = np.loadtxt(self.m_filePath, dtype = float, skiprows=headerLength + 2, delimiter=',', usecols=range(1,len(self.m_listOfColumns)+1)) #now columns can be traversed contiguously in memory self.m_parsedRawData = temp.transpose().copy() self.m_dataParsed = True # del temp #free memory, or at least suggest it to the garbage collector def getRawTempMin(self): #Get lowest available temperature from raw temperature data. return np.amin(self.m_parsedRawData[(self.m_listOfColumns.index('temperature')),:]) def getRawTempMax(self): #Get highest available temperature from raw temperature data. return np.amax(self.m_parsedRawData[(self.m_listOfColumns.index('temperature')),:]) def getRawDataVSRawTemp(self, desiredMasses): #Get raw data vs temperature as np.array result = np.array(self.m_parsedRawData[(self.m_listOfColumns.index('temperature')),:]) for i in self.massListToIndices(desiredMasses): result = np.vstack((result, self.m_parsedRawData[i,:])) return result def getRawDataVSRawTime(self, desiredMasses): #Get raw data vs time as np.array result = np.array(self.m_parsedRawData[(self.m_listOfColumns.index('ms')),:]) for i in self.massListToIndices(desiredMasses): result = np.vstack((result, self.m_parsedRawData[i,:])) return result def getRawTempVSRawTime(self): #Get raw temperature vs time as np.array # result = np.vstack((self.m_interpolatedTime, self.m_interpolatedTemp)) result = np.vstack((self.m_parsedRawData[0,:], self.m_parsedRawData[(self.m_listOfColumns.index('temperature')),:])) return result def getMassList(self): #return all available massses in the file return self.m_listOfColumns[2:] #first two columns are "ms" and "temperature" def massListToIndices(self, massList): #convert mass list argument to indices in self.m_parsedRawData result = list() for m in massList: try: result.append(self.m_listOfColumns.index(m)) except ValueError: continue return result#[self.m_listOfColumns.index(m) for m in massList] def smooth_running_average(self, x, N): #running average over N points cumsum = np.cumsum(np.insert(x, 0, 0)) smoothResult = (cumsum[N:] - cumsum[:-N]) / float(N) smoothResult = np.insert(smoothResult,0,x[:N-1]) smoothResult = np.append(smoothResult,x[N:-1:-1]) return smoothResult #The process parsed data function takes care of smoothing and interpolating the raw (noisy) temperature data on a uniform grid. #The counts can then also be interpolated and provided on a uniform grid. This makes inversion analysis (the integration part) #easier down the line. def processParsedData(self, tRampStart, tRampEnd, tCutStart, tCutEnd, removeBackground, smooth, tempScaleCorrection, tempOffsetCorrection, smoothpoints = 5, tStep = 0.1): if (self.m_dataProcessed == True): return # self.m_tStep = tStep # self.m_correctedTemp = np.zeros(self.m_parsedRawData.shape[1]) # correct temperature (taken from Honza's scripts) self.m_correctedTemp = np.array(self.m_parsedRawData[(self.m_listOfColumns.index('temperature')),:]) self.m_correctedTemp *= tempScaleCorrection self.m_correctedTemp += tempOffsetCorrection #get running average from temperature data self.m_correctedTemp = self.smooth_running_average(self.m_correctedTemp, 20) tRampStart = np.median(self.m_correctedTemp) # starting the search in the middle of the temperature ramp (approximately) tRampEnd = tRampStart tempSearchInput = np.abs(self.m_correctedTemp - tRampStart) tRampStartIndex = np.argwhere(tempSearchInput == np.amin(tempSearchInput))[-1][0] #find closest value to input while self.m_correctedTemp[tRampStartIndex + 1] > self.m_correctedTemp[tRampStartIndex]: tRampStartIndex -= 1 # find lowest index of the ramp if(tRampStartIndex == 0): break tempSearchInput = np.abs(self.m_correctedTemp - tRampEnd) tRampEndIndex = np.argwhere(tempSearchInput == np.amin(tempSearchInput))[-1][0] #find closest value to input del tempSearchInput #no need to waste memory while self.m_correctedTemp[tRampEndIndex - 1] < self.m_correctedTemp[tRampEndIndex]: tRampEndIndex += 1 # find highest index of the ramp if(tRampEndIndex == self.m_correctedTemp.size - 1): break self.m_interpolatedTemp = np.arange(tCutStart, tCutEnd, tStep) #generate equidistantly spaced range of temperature points self.m_reciprocalTemp = np.reciprocal(self.m_interpolatedTemp) # self.m_interpolatedTime = np.interp(self.m_interpolatedTemp, self.m_correctedTemp[tRampStartIndex:tRampEndIndex], self.m_parsedRawData[0,tRampStartIndex:tRampEndIndex]) # print(tRampStartIndex, tRampEndIndex) for m in self.getMassList(): #for each mass #interpolate data by default interpDataBuffer = np.interp(self.m_interpolatedTemp, self.m_correctedTemp[tRampStartIndex:tRampEndIndex], self.m_parsedRawData[self.m_listOfColumns.index(m),tRampStartIndex:tRampEndIndex]) if smooth: #if we use the smooth option, also smooth the data (counts/s) interpDataBuffer = self.smooth_running_average(interpDataBuffer, smoothpoints) if removeBackground: #if we want to remove the background, do that interpDataBuffer -= np.amin(interpDataBuffer) zeroIndices = np.where(interpDataBuffer == 0) #find zeros for i in zeroIndices: interpDataBuffer[i] = np.finfo(float).eps #add machine epsilon to zeros to avoid divide by zero in log later on # if normalize: #first step to normalizing -> find coverages self.m_coverages[m] = np.trapz(interpDataBuffer, dx= tStep) #write absolute coverage into dictionary self.m_interpolatedData[m] = interpDataBuffer #write buffer into "permanent" storage self.m_logInterpolatedData[m] = np.log(interpDataBuffer) self.m_dataProcessed = True #This function allows normalizing the available spectra to a specific spectrum which is defined to be the "monolayer coverage". #Doesn't actually need to be the monolayer, but the area under that spectrum will be defined as 1, and all others will be normalized to it. def normalizeDataTo(self, referenceRawDataWrapper): if (not self.m_dataProcessed or not referenceRawDataWrapper.m_dataProcessed): return #only try to normalize masses which we actually have access to availableMasses = list(set(self.getMassList()) & set(referenceRawDataWrapper.getMassList())) for m in availableMasses: referenceCoverage = referenceRawDataWrapper.m_coverages[m] # self.m_coverages[m] = np.trapz(self.m_interpolatedData[m], dx= self.m_tStep) self.m_coverages[m] /= referenceCoverage self.m_interpolatedData[m] /= referenceCoverage self.m_coveragesNormalized = True def getProcessedData(self, desiredMasses): #get processed data versus temperature as np.array result = self.m_interpolatedTemp for m in desiredMasses: if m in self.m_listOfColumns: result = np.vstack((result, self.m_interpolatedData[m])) # return np.concatenate((self.m_correctedTemp,self.m_parsedRawData[self.m_listOfColumns.index('temperature')+1:,:])) return result def getProcessedLNData(self, desiredMasses): #ln(desorption rate) vs temperature result = self.m_interpolatedTemp for m in desiredMasses: if m in self.m_listOfColumns: result = np.vstack((result, self.m_logInterpolatedData[m])) return result def getProcessedArrheniusData(self, desiredMasses): #ln(desorption rate) vs 1/temperature result = self.m_reciprocalTemp for m in desiredMasses: if m in self.m_listOfColumns: result = np.vstack((result, self.m_logInterpolatedData[m])) return result def getParsedCoverageAsFloat(self): return float(self.m_parsedCoverage[0:-1]) #TODO: in the future, one can use the calibration mol/uc/L to get ML normalized coverages def getCoverageLabels(self, desiredMasses):#get the labels for the plot legend for each of the desired masses. result = [] for m in desiredMasses: if m in self.m_listOfColumns: if self.m_coveragesNormalized: #Either returning normalized coverages result.append("M" + m + ' {:04.2f} ML'.format(self.m_coverages[m]) + " #" + self.m_parsedExperimentNumber) else:#Or returning absolute counts result.append("M" + m + " " + self.m_parsedCoverage + " #" + self.m_parsedExperimentNumber) # result.append("M" + m + ' {:f} Counts'.format(self.m_coverages[m])) return result def getLangmuirLabels(self, desiredMasses):#get labels for the plot legend in langmuir result = [] for m in desiredMasses: if m in self.m_listOfColumns: result.append("M" + m + " " + self.m_parsedCoverage + " #" + self.m_parsedExperimentNumber) return result
[ "numpy.trapz", "numpy.abs", "numpy.log", "numpy.amin", "numpy.median", "numpy.reciprocal", "numpy.insert", "numpy.append", "numpy.finfo", "numpy.where", "numpy.arange", "numpy.loadtxt", "numpy.vstack" ]
[((1740, 1817), 'numpy.loadtxt', 'np.loadtxt', (['self.m_filePath'], {'dtype': 'str', 'skiprows': '(1)', 'max_rows': '(1)', 'delimiter': '""","""'}), "(self.m_filePath, dtype=str, skiprows=1, max_rows=1, delimiter=',')\n", (1750, 1817), True, 'import numpy as np\n'), ((1991, 2088), 'numpy.loadtxt', 'np.loadtxt', (['self.m_filePath'], {'dtype': 'str', 'skiprows': '(headerLength + 1)', 'max_rows': '(1)', 'delimiter': '""","""'}), "(self.m_filePath, dtype=str, skiprows=headerLength + 1, max_rows=\n 1, delimiter=',')\n", (2001, 2088), True, 'import numpy as np\n'), ((4833, 4870), 'numpy.insert', 'np.insert', (['smoothResult', '(0)', 'x[:N - 1]'], {}), '(smoothResult, 0, x[:N - 1])\n', (4842, 4870), True, 'import numpy as np\n'), ((4890, 4925), 'numpy.append', 'np.append', (['smoothResult', 'x[N:-1:-1]'], {}), '(smoothResult, x[N:-1:-1])\n', (4899, 4925), True, 'import numpy as np\n'), ((6021, 6052), 'numpy.median', 'np.median', (['self.m_correctedTemp'], {}), '(self.m_correctedTemp)\n', (6030, 6052), True, 'import numpy as np\n'), ((6186, 6227), 'numpy.abs', 'np.abs', (['(self.m_correctedTemp - tRampStart)'], {}), '(self.m_correctedTemp - tRampStart)\n', (6192, 6227), True, 'import numpy as np\n'), ((6581, 6620), 'numpy.abs', 'np.abs', (['(self.m_correctedTemp - tRampEnd)'], {}), '(self.m_correctedTemp - tRampEnd)\n', (6587, 6620), True, 'import numpy as np\n'), ((7055, 7091), 'numpy.arange', 'np.arange', (['tCutStart', 'tCutEnd', 'tStep'], {}), '(tCutStart, tCutEnd, tStep)\n', (7064, 7091), True, 'import numpy as np\n'), ((7183, 7221), 'numpy.reciprocal', 'np.reciprocal', (['self.m_interpolatedTemp'], {}), '(self.m_interpolatedTemp)\n', (7196, 7221), True, 'import numpy as np\n'), ((3415, 3462), 'numpy.vstack', 'np.vstack', (['(result, self.m_parsedRawData[i, :])'], {}), '((result, self.m_parsedRawData[i, :]))\n', (3424, 3462), True, 'import numpy as np\n'), ((3732, 3779), 'numpy.vstack', 'np.vstack', (['(result, self.m_parsedRawData[i, :])'], {}), '((result, self.m_parsedRawData[i, :]))\n', (3741, 3779), True, 'import numpy as np\n'), ((4729, 4747), 'numpy.insert', 'np.insert', (['x', '(0)', '(0)'], {}), '(x, 0, 0)\n', (4738, 4747), True, 'import numpy as np\n'), ((8434, 8470), 'numpy.trapz', 'np.trapz', (['interpDataBuffer'], {'dx': 'tStep'}), '(interpDataBuffer, dx=tStep)\n', (8442, 8470), True, 'import numpy as np\n'), ((8654, 8678), 'numpy.log', 'np.log', (['interpDataBuffer'], {}), '(interpDataBuffer)\n', (8660, 8678), True, 'import numpy as np\n'), ((8057, 8082), 'numpy.amin', 'np.amin', (['interpDataBuffer'], {}), '(interpDataBuffer)\n', (8064, 8082), True, 'import numpy as np\n'), ((8113, 8144), 'numpy.where', 'np.where', (['(interpDataBuffer == 0)'], {}), '(interpDataBuffer == 0)\n', (8121, 8144), True, 'import numpy as np\n'), ((9916, 9963), 'numpy.vstack', 'np.vstack', (['(result, self.m_interpolatedData[m])'], {}), '((result, self.m_interpolatedData[m]))\n', (9925, 9963), True, 'import numpy as np\n'), ((10337, 10387), 'numpy.vstack', 'np.vstack', (['(result, self.m_logInterpolatedData[m])'], {}), '((result, self.m_logInterpolatedData[m]))\n', (10346, 10387), True, 'import numpy as np\n'), ((10644, 10694), 'numpy.vstack', 'np.vstack', (['(result, self.m_logInterpolatedData[m])'], {}), '((result, self.m_logInterpolatedData[m]))\n', (10653, 10694), True, 'import numpy as np\n'), ((6285, 6309), 'numpy.amin', 'np.amin', (['tempSearchInput'], {}), '(tempSearchInput)\n', (6292, 6309), True, 'import numpy as np\n'), ((6676, 6700), 'numpy.amin', 'np.amin', (['tempSearchInput'], {}), '(tempSearchInput)\n', (6683, 6700), True, 'import numpy as np\n'), ((8237, 8252), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (8245, 8252), True, 'import numpy as np\n')]
"""Queue classes.""" import os from collections import defaultdict from datetime import datetime import logging import numpy as np import pandas as pd import astropy.coordinates as coord import astropy.units as u from astropy.time import Time, TimeDelta import astroplan from .Fields import Fields from .optimize import tsp_optimize, night_optimize from .cadence import enough_gap_since_last_obs from .constants import P48_loc, PROGRAM_IDS, FILTER_IDS, TIME_BLOCK_SIZE from .constants import EXPOSURE_TIME, READOUT_TIME, FILTER_CHANGE_TIME, slew_time from .constants import PROGRAM_BLOCK_SEQUENCE, LEN_BLOCK_SEQUENCE, MAX_AIRMASS from .constants import BASE_DIR from .utils import approx_hours_of_darkness from .utils import skycoord_to_altaz, seeing_at_pointing from .utils import altitude_to_airmass, airmass_to_altitude, RA_to_HA, HA_to_RA from .utils import scalar_len, nightly_blocks, block_index, block_index_to_time from .utils import block_use_fraction, maximum_altitude, compute_limiting_mag class QueueEmptyError(Exception): """Error class for when the nightly queue has no more fields""" pass class QueueManager(object): def __init__(self, queue_name, queue_configuration, rp=None, fields=None): self.logger = logging.getLogger(__name__) # queue name (useful in Scheduler object when swapping queues) self.queue_name = queue_name # list of ObservingPrograms self.observing_programs = queue_configuration.build_observing_programs() # defaults to handle time-windowed queues self.is_TOO = False self.validity_window = None # Hack for greedy queues self.requests_in_window = True if 'validity_window_mjd' in queue_configuration.config: window = queue_configuration.config['validity_window_mjd'] if window is not None: assert(len(window) == 2) self.set_validity_window_mjd(window[0], window[1]) else: self.validity_window = None else: self.validity_window = None # flag to check if assign_nightly_requests has been called tonight self.queue_night = None # block on which the queue parameters were calculated self.queue_slot = None # number allowed requests by subprogram tonight # (dict of (program_id, subprogram_name)) self.requests_allowed = {} # the queue itself self.queue = pd.DataFrame() # should we only consider fields from one program in a given # observing block? # CURRENTLY NOT IMPLEMENTED. self.block_programs = False if rp is None: # initialize an empty RequestPool self.rp = RequestPool() else: self.rp = rp if fields is None: self.fields = Fields() else: self.fields = fields self.missed_obs_queue = None def is_valid(self, time): if self.validity_window is None: return True window_start = self.validity_window[0] window_stop = self.validity_window[1] return window_start <= time <= window_stop def validity_window_mjd(self): if self.validity_window is None: return None return [self.validity_window[0].mjd, self.validity_window[1].mjd] def set_validity_window_mjd(self, window_start, window_stop): """Set the time at which this queue can run. Parameters ---------- window_start : `float` Modified Julian Date start time window_stop : `float` Modified Julian Date end time """ if window_start >= window_stop: raise ValueError("validity window start time must be less than end time") # rough sanity checks if window_start <= Time('2017-01-01').mjd: raise ValueError(f"MJD likely out of range: {window_start}") if window_stop >= Time('2030-01-01').mjd: raise ValueError(f"MJD likely out of range: {window_stop}") self.validity_window = [Time(window_start,format='mjd'), Time(window_stop,format='mjd')] def compute_block_use(self): """Returns a dictionary with the fraction of blocks used by the queue, assuming observing starts at the beginning of the validity window""" if self.validity_window is None: raise ValueError('All blocks are valid') start_block = block_index(self.validity_window[0]) obs_start_time = Time(self.validity_window[0],format='mjd') # greedy queues have no len until they have assignments made, so # just use the validity window if len(self.queue) == 0: stop_block = block_index(self.validity_window[1]) obs_end_time = self.validity_window[1] else: # with no weather, we start at the start of the window if 'n_repeats' in self.queue.columns: n_obs = np.sum(self.queue.n_repeats) exp_time = np.sum(self.queue.exposure_time * self.queue.n_repeats) else: n_obs = len(self.queue) exp_time = np.sum(self.queue.exposure_time) obs_time = (exp_time * u.second) + n_obs * READOUT_TIME obs_end_time = self.validity_window[0] + obs_time stop_block = block_index(obs_end_time) # below breaks if the window is longer than the observations #stop_block = block_index(self.validity_window[1]) assert obs_end_time > obs_start_time # compute fraction of the blocks used by the queue block_use = defaultdict(float) for block in np.arange(start_block, stop_block+1): block_use[block] = block_use_fraction(block, obs_start_time, obs_end_time) return block_use def add_observing_program(self, observing_program): self.observing_programs.append(observing_program) def assign_nightly_requests(self, current_state, obs_log, time_limit = 30 * u.second, block_use = defaultdict(float), timed_obs_count = defaultdict(int)): # clear previous request pool if self.queue_name != 'missed_obs': self.rp.clear_all_request_sets() # set number of allowed requests by program. self.determine_allowed_requests(current_state['current_time'], obs_log, timed_obs_count = timed_obs_count) # can be used by field_selection_functions downstream program_fields = {} for program in self.observing_programs: key = (program.program_id, program.subprogram_name) program_fields[key] = \ {'field_ids': program.field_ids, 'field_selection_function': program.field_selection_function, 'requests_allowed': self.requests_allowed[key]} for program in self.observing_programs: request_sets = program.assign_nightly_requests( current_state['current_time'], self.fields, obs_log, program_fields, block_programs=self.block_programs) for rs in request_sets: self.rp.add_request_sets(rs['program_id'], rs['subprogram_name'], rs['program_pi'], rs['field_ids'], rs['filter_ids'], rs['intranight_gap'], rs['exposure_time'], rs['total_requests_tonight']) # assert(len(self.rp.pool) > 0) # any specific tasks needed) self._assign_nightly_requests(current_state, time_limit = time_limit, block_use = block_use) # mark that we've set up the pool for tonight self.queue_night = np.floor(current_state['current_time'].mjd) def adjust_program_exposures_tonight(self, obs_log, mjd_start, mjd_stop): """Use past history to adjust the number of exposures per program tonight. Counts exposures from the start of the month and equalizes any excess over NIGHTS_TO_REDISTRIBUTE or the number of nights to the end of the month, whichever is less.""" obs_count_by_program = obs_log.count_equivalent_obs_by_program( mjd_range = [mjd_start, mjd_stop]) # drop engineering/commissioning obs_count_by_program = obs_count_by_program[ obs_count_by_program['program_id'] != 0] obs_count_by_program.set_index('program_id', inplace=True) # if there are no observations, add zeros for program_id in PROGRAM_IDS: if program_id != 0: if program_id not in obs_count_by_program.index: obs_count_by_program.loc[program_id] = 0 total_obs = np.sum(obs_count_by_program['n_obs']) # infer the program fractions from the subprograms target_program_fractions = {propid:0 for propid in PROGRAM_IDS if propid != 0} for op in self.observing_programs: target_program_fractions[op.program_id] = \ op.program_observing_time_fraction target_program_fractions = pd.Series(target_program_fractions) target_program_fractions.index.name = 'program_id' target_program_fractions.name = 'target_fraction' target_program_nobs = target_program_fractions * total_obs target_program_nobs.name = 'target_program_nobs' # note that this gives 0 in case of no observations, as desired # have to do the subtraction backwords because of Series/DataFrame # API nonsense delta_program_nobs = \ -1*obs_count_by_program.subtract(target_program_nobs, axis=0) NIGHTS_TO_REDISTRIBUTE = 5 time = Time(mjd_stop,format='mjd') dtnow = time.to_datetime() if dtnow.month != 12: next_month_start_mjd = Time(datetime(dtnow.year,dtnow.month+1,1), scale='utc').mjd else: next_month_start_mjd = Time(datetime(dtnow.year+1,1,1), scale='utc').mjd nights_left_this_month = np.round(next_month_start_mjd - time.mjd) if nights_left_this_month > NIGHTS_TO_REDISTRIBUTE: divisor = NIGHTS_TO_REDISTRIBUTE else: divisor = nights_left_this_month if divisor == 0: divisor = 1 delta_program_nobs /= divisor delta_program_nobs = np.round(delta_program_nobs).astype(int) return delta_program_nobs def adjust_subprogram_exposures_tonight(self, obs_log, mjd_start, mjd_stop): """Use past history to adjust the number of exposures per subprogram tonight. Counts exposures from the start of the month and equalizes any excess over NIGHTS_TO_REDISTRIBUTE or the number of nights to the end of the month, whichever is less.""" obs_count_by_subprogram_all = obs_log.count_equivalent_obs_by_subprogram( mjd_range = [mjd_start, mjd_stop]) # drop engineering/commissioning obs_count_by_subprogram_all = obs_count_by_subprogram_all[ obs_count_by_subprogram_all['program_id'] != 0] obs_count_by_subprogram_all.set_index(['program_id','subprogram_name'], inplace=True) # only count the subprograms that are currently active. This is # going to cause problems when the programs change--but we are going to # only use the subprogram balance for i-band obs_count_by_current_subprogram_dict = {} # if there are no observations, add zeros for op in self.observing_programs: idx = (op.program_id, op.subprogram_name) if idx not in obs_count_by_subprogram_all.index: obs_count_by_current_subprogram_dict[idx] = 0 else: obs_count_by_current_subprogram_dict[idx] = obs_count_by_subprogram_all.loc[idx,'n_obs'] obs_count_by_subprogram = pd.Series(obs_count_by_current_subprogram_dict) obs_count_by_subprogram.name = 'n_obs' obs_count_by_subprogram.index.set_names( ['program_id','subprogram_name'], inplace=True) total_obs = obs_count_by_subprogram.sum() # record the subprogram fractions target_subprogram_fractions = defaultdict(float) for op in self.observing_programs: target_subprogram_fractions[(op.program_id, op.subprogram_name)] = \ op.program_observing_time_fraction * op.subprogram_fraction target_subprogram_fractions = pd.Series(target_subprogram_fractions) # target_program_fractions.index.name = 'program_id' target_subprogram_fractions.name = 'target_fraction' target_subprogram_nobs = target_subprogram_fractions * total_obs target_subprogram_nobs.name = 'target_subprogram_nobs' target_subprogram_nobs.index.set_names( ['program_id','subprogram_name'], inplace=True) # note that this gives 0 in case of no observations, as desired # have to do the subtraction backwords because of Series/DataFrame # API nonsense delta_subprogram_nobs = \ -1*obs_count_by_subprogram.subtract(target_subprogram_nobs, axis=0).fillna(0) NIGHTS_TO_REDISTRIBUTE = 5 time = Time(mjd_stop,format='mjd') dtnow = time.to_datetime() if dtnow.month != 12: next_month_start_mjd = Time(datetime(dtnow.year,dtnow.month+1,1), scale='utc').mjd else: next_month_start_mjd = Time(datetime(dtnow.year+1,1,1), scale='utc').mjd nights_left_this_month = np.round(next_month_start_mjd - time.mjd) if nights_left_this_month > NIGHTS_TO_REDISTRIBUTE: divisor = NIGHTS_TO_REDISTRIBUTE else: divisor = nights_left_this_month if divisor == 0: divisor = 1 delta_subprogram_nobs /= divisor delta_subprogram_nobs = np.round(delta_subprogram_nobs).astype(int) return delta_subprogram_nobs def determine_allowed_requests(self, time, obs_log, timed_obs_count = defaultdict(int)): """Use count of past observations and expected observing time fractions to determine number of allowed requests tonight. Exclude observations already planned in timed queues.""" self.requests_allowed = {} # rather than using equivalent obs, might be easier to work in # exposure time directly? # enforce program balance on a monthly basis dtnow = time.to_datetime() month_start_mjd = Time(datetime(dtnow.year,dtnow.month,1), scale='utc').mjd delta_program_exposures_tonight = self.adjust_program_exposures_tonight( obs_log, month_start_mjd, time.mjd) # use this for i-band only delta_subprogram_exposures_tonight = self.adjust_subprogram_exposures_tonight( obs_log, month_start_mjd, time.mjd) self.logger.info(f'Change in allowed exposures: {delta_program_exposures_tonight}') self.logger.info(f'Needed change in allowed exposures by subprogram: {delta_subprogram_exposures_tonight}') self.logger.debug(f"Sum of change in allowed exposures by subprogram: {delta_subprogram_exposures_tonight.reset_index().groupby('program_id').agg(np.sum)}") self.logger.info(f'Number of timed observations: {timed_obs_count}') dark_time = approx_hours_of_darkness(time) # calculate subprogram fractions excluding list queues and TOOs scheduled_subprogram_sum = defaultdict(float) for op in self.observing_programs: # list queues and TOOs should set field_ids = [], but not None # OPs scheduled using field_selection_function will have # field_ids = None if op.field_ids is not None: if len(op.field_ids) == 0: continue scheduled_subprogram_sum[op.program_id] += \ op.subprogram_fraction for op in self.observing_programs: program_time_tonight = ( dark_time * op.program_observing_time_fraction + (delta_program_exposures_tonight.loc[op.program_id,'n_obs'] - timed_obs_count[op.program_id]) * (EXPOSURE_TIME+READOUT_TIME)) subprogram_time_tonight = ( program_time_tonight * op.subprogram_fraction / scheduled_subprogram_sum[op.program_id]) n_requests = (subprogram_time_tonight.to(u.min) / op.time_per_exposure().to(u.min)).value[0] n_requests = np.round(n_requests).astype(np.int) # i_band program balance needs individual tuning due to # longer cadence and filter blocking if op.subprogram_name == 'i_band': delta_i_nexp = delta_subprogram_exposures_tonight.loc[(2,'i_band')] if delta_i_nexp > 0: self.logger.info(f'Adding {delta_i_nexp} additional i-band exposures') n_requests += delta_i_nexp else: self.logger.info(f'Implied change in i-band exposures is negative, skipping supplementation: {delta_i_nexp}') self.requests_allowed[(op.program_id, op.subprogram_name)] = n_requests for key, n_requests in self.requests_allowed.items(): if n_requests < 0: self.requests_allowed[key] = 0 self.logger.info(self.requests_allowed) def next_obs(self, current_state, obs_log): """Given current state, return the parameters for the next request""" # don't store the telescope state locally! # check that assign_nightly_requests has been called tonight. if self.queue_type != 'list': if np.floor(current_state['current_time'].mjd) != self.queue_night: self.assign_nightly_requests(current_state, obs_log) # define functions that actually do the work in subclasses next_obs = self._next_obs(current_state, obs_log) # check if we have a disallowed observation, and reject it: if next_obs['target_limiting_mag'] < 0: self.logger.warning(f'Target is unobservable! Removing from queue {next_obs}') self.remove_requests(next_obs['request_id']) next_obs = self.next_obs(current_state, obs_log) next_obs['queue_name'] = self.queue_name return next_obs def update_queue(self, current_state, obs_log, **kwargs): """Recalculate queue""" # define functions that actually do the work in subclasses return self._update_queue(current_state, obs_log) def remove_requests(self, request_id): """Remove a request from both the queue and the request set pool""" # define functions that actually do the work in subclasses return self._remove_requests(request_id) def return_queue(self): """Return queue values, ordered in the expected sequence if possible""" queue = self._return_queue() cols = ['field_id','filter_id','exposure_time','program_id', 'subprogram_name','ra','dec','ordered'] if self.queue_type == 'gurobi': cols.append('slot_start_time') if self.queue_type == 'list': cols.append('mode_num') cols.append('ewr_num_images') return queue.loc[:,cols] class GurobiQueueManager(QueueManager): def __init__(self, queue_name, queue_configuration, **kwargs): super().__init__(queue_name, queue_configuration, **kwargs) self.block_obs_number = 0 self.queue_type = 'gurobi' def _assign_nightly_requests(self, current_state, time_limit = 30.*u.second, block_use = defaultdict(float)): self._assign_slots(current_state, time_limit = time_limit, block_use = block_use) def _next_obs(self, current_state, obs_log): """Select the highest value request.""" # do the slot assignment at the beginning of the night # (or if the queue is empty, which should be unusual) # if we've entered a new block, solve the TSP to sequence the requests if (block_index(current_state['current_time'])[0] != self.queue_slot): try: self._move_requests_to_missed_obs(self.queue_slot) except Exception as e: self.logger.exception(e) self.logger.error('Failed moving requests to missed obs!') self._sequence_requests_in_block(current_state) if (len(self.queue_order) == 0): raise QueueEmptyError("Ran out of observations this block.") idx = self.queue_order[0] row = self.queue.loc[idx] if self.queue_slot in self.filter_by_slot: filter_id = int(self.filter_by_slot[self.queue_slot]) else: raise QueueEmptyError("No requests in this slot!") next_obs = {'target_field_id': int(row['field_id']), 'target_ra': row['ra'], 'target_dec': row['dec'], 'target_filter_id': filter_id, 'target_program_id': int(row['program_id']), 'target_subprogram_name': row['subprogram_name'], 'target_program_pi': row['program_pi'], 'target_exposure_time': row['exposure_time'] * u.second, 'target_sky_brightness': self.block_sky_brightness.loc[idx,self.queue_slot][filter_id], 'target_limiting_mag': self.block_lim_mags.loc[idx,self.queue_slot][filter_id], 'target_metric_value': self.block_slot_metric.loc[idx,self.queue_slot][filter_id], 'target_total_requests_tonight': int(row['total_requests_tonight']), 'target_mode_num': 0, 'target_num_images': 1, 'request_id': idx} # 'target_sky_brightness': self.queue.ix[idx].sky_brightness, # 'target_limiting_mag': self.queue.ix[idx].limiting_mag, # 'target_metric_value': self.queue.ix[idx].value, # 'target_request_number_tonight': return next_obs def _slot_metric(self, limiting_mag, dec): """Calculate metric for assigning fields to slots. penalizes volume for both extinction (airmass) and fwhm penalty due to atmospheric refraction, plus sky brightness from moon phase and distance == 1 for 21st mag. normalize metrics by maximum value at transit so low-declination fields are not penalized """ #see 200430 notes metric = (10.**(0.6 * (limiting_mag - 21)) / (1-1e-4*(maximum_altitude(dec) - 90)**2.)) # lock out -99 limiting mags even more aggressively return metric.where(limiting_mag > 0, -0.99) def _assign_slots(self, current_state, time_limit = 30*u.second, block_use = defaultdict(float)): """Assign requests in the Pool to slots""" # check that the pool has fields in it if len(self.rp.pool) == 0: raise QueueEmptyError("No fields in pool") # join with fields so we have the information we need # make a copy so rp.pool and self.queue are not linked df = self.rp.pool.join(self.fields.fields, on='field_id').copy() # calculate limiting mag by block. uses the block midpoint time blocks, times = nightly_blocks(current_state['current_time'], time_block_size=TIME_BLOCK_SIZE) # remove the excluded blocks, if any. Could do this in optimize.py # but it makes the optimization problem unneccesarily bigger # don't demand 100% of the block is used: tiny fractions lead to # infeasible models exclude_blocks = [b for (b,v) in block_use.items() if v > 0.95] self.logger.debug(f'Excluding completely filled blocks {exclude_blocks}') if len(exclude_blocks): cut_blocks = np.setdiff1d(blocks, exclude_blocks) cut_times = block_index_to_time(cut_blocks, current_state['current_time'], where='mid') blocks, times = cut_blocks, cut_times lim_mags = {} sky_brightnesses = {} decs = {} for bi, ti in zip(blocks, times): if 'altitude' in df.columns: df.drop('altitude', axis=1, inplace=True) if 'azimuth' in df.columns: df.drop('azimuth', axis=1, inplace=True) # use pre-computed blocks df_alt = self.fields.block_alt[bi] df_alt.name = 'altitude' df = df.join(df_alt, on='field_id') df_az = self.fields.block_az[bi] df_az.name = 'azimuth' df = df.join(df_az, on='field_id') for fid in FILTER_IDS: df_limmag, df_sky = \ compute_limiting_mag(df, ti, self.fields.Sky, filter_id = fid) lim_mags[(bi, fid)] = df_limmag sky_brightnesses[(bi, fid)] = df_sky decs[(bi, fid)] = df.dec # this results in a MultiIndex on the *columns*: level 0 is block, # level 1 is filter_id. df_metric.unstack() flattens it self.block_lim_mags = pd.DataFrame(lim_mags) self.block_sky_brightness = pd.DataFrame(sky_brightnesses) block_decs = pd.DataFrame(decs) self.block_slot_metric = self._slot_metric(self.block_lim_mags, block_decs) # count the number of observations requested by filter df['n_reqs_tot'] = 0 for fid in FILTER_IDS: df['n_reqs_{}'.format(fid)] = \ df.filter_ids.apply(lambda x: np.sum([xi == fid for xi in x])) df['n_reqs_tot'] += df['n_reqs_{}'.format(fid)] # prepare the data for input to gurobi #import shelve #s = shelve.open('tmp_vars.shelf') #s['block_lim_mags'] = self.block_lim_mags #s['block_slot_metric'] = self.block_slot_metric #s['df'] = df #s.close() self.request_sets_tonight, df_slots, dft = night_optimize( self.block_slot_metric, df, self.requests_allowed, time_limit = time_limit, block_use = block_use) grp = df_slots.groupby('slot') self.queued_requests_by_slot = grp['request_id'].apply(list) self.filter_by_slot = \ grp['metric_filter_id'].apply(lambda x: np.unique(x)[0]) # rework to dump output df_slots['scheduled'] = True dft.set_index(['request_id','slot','metric_filter_id'],inplace=True) df_slots.set_index(['request_id','slot','metric_filter_id'],inplace=True) dft = dft.join(df_slots,how='outer') dft['scheduled'] = dft['scheduled'].fillna(False) dft.reset_index(inplace=True) dft = pd.merge(dft,df[['field_id']], left_on='request_id', right_index=True) n_requests_scheduled = np.sum(dft['scheduled']) total_metric_value = np.sum(dft['scheduled']*dft['metric']) avg_metric_value = total_metric_value / n_requests_scheduled tot_avail_requests_bysubprogram = \ df.groupby(['program_id','subprogram_name'])['n_reqs_tot'].agg(np.sum) tot_avail_requests_bysubprogram.name = 'available' # use self.requests_allowed and join this all up nscheduled_requests_bysubprogram = \ dft.loc[dft['scheduled'],['program_id','subprogram_name']].groupby(['program_id','subprogram_name']).agg(len) nscheduled_requests_bysubprogram.name = 'scheduled' # reformat requests_allowed for joining mux = pd.MultiIndex.from_tuples(self.requests_allowed.keys(), names = ['program_id','subprogram_name']) df_allowed = pd.DataFrame(list(self.requests_allowed.values()), index=mux,columns=['allowed']) df_summary = df_allowed.join(tot_avail_requests_bysubprogram).join(nscheduled_requests_bysubprogram) self.logger.info(df_summary) self.logger.info(f'{n_requests_scheduled} requests scheduled') self.logger.info(f'{total_metric_value:.2f} total metric value; ' f'{avg_metric_value:.2f} average per request') # this is not ideal for tnow = current_state['current_time'] yymmdd = tnow.iso.split()[0][2:].replace('-','') solution_outfile = f'{BASE_DIR}/../sims/gurobi_solution_{yymmdd}.csv' before_noon_utc = (tnow.mjd - np.floor(tnow.mjd)) < 0.5 # avoid clobbering the solution file with restarts after observing has # completed if before_noon_utc or (not os.path.exists(solution_outfile)): dft.drop(columns=['Yrtf']).to_csv(solution_outfile) def _sequence_requests_in_block(self, current_state): """Solve the TSP for requests in this slot""" self.queue_slot = block_index(current_state['current_time'])[0] # raise an error if there are missing blocks--potentially due to # excluded blocks if self.queue_slot not in self.queued_requests_by_slot.index: raise QueueEmptyError(f"Current block {self.queue_slot} is not stored") # retrieve requests to be observed in this block req_list = self.queued_requests_by_slot.loc[self.queue_slot] # request_set ids should be unique per block assert( (len(set(req_list)) == len(req_list) ) ) if np.all(np.isnan(req_list)): raise QueueEmptyError("No requests assigned to this block") idx = pd.Index(req_list) # reconstruct df = self.rp.pool.loc[idx].join(self.fields.fields, on='field_id').copy() az = self.fields.block_az[self.queue_slot] df = df.join(az, on='field_id') # now prepend the CALSTOW positoin so we can minimize slew from # filter exchanges # Need to use current HA=0 df_blockstart = pd.DataFrame({'ra':HA_to_RA(0, current_state['current_time']).to(u.degree).value, 'dec':-48.,'azimuth':180.},index=[0]) df_fakestart = pd.concat([df_blockstart,df],sort=True) # compute overhead time between all request pairs # compute pairwise slew times by axis for all pointings slews_by_axis = {} def coord_to_slewtime(coord, axis=None): c1, c2 = np.meshgrid(coord, coord) dangle = np.abs(c1 - c2) angle = np.where(dangle < (360. - dangle), dangle, 360. - dangle) return slew_time(axis, angle * u.deg) slews_by_axis['dome'] = coord_to_slewtime( df_fakestart['azimuth'], axis='dome') slews_by_axis['dec'] = coord_to_slewtime( df_fakestart['dec'], axis='dec') slews_by_axis['ra'] = coord_to_slewtime( df_fakestart['ra'], axis='ha') maxradec = np.maximum(slews_by_axis['ra'], slews_by_axis['dec']) maxslews = np.maximum(slews_by_axis['dome'], maxradec) # impose a penalty on zero-length slews (which by construction # in this mode are from different programs) wnoslew = maxslews == 0 maxslews[wnoslew] = READOUT_TIME * 10. overhead_time = np.maximum(maxslews, READOUT_TIME) tsp_order, tsp_overhead_time = tsp_optimize(overhead_time.value) # remove the fake starting point. tsp_optimize always starts with # the first observation in df, which by construction is our fake point, # so we can simply cut it off. tsp_order = tsp_order[1:] assert(0 not in tsp_order) # tsp_order is 0-indexed from overhead time, so I need to # reconstruct the request_id self.queue_order = df_fakestart.index.values[tsp_order] self.queue = df def _move_requests_to_missed_obs(self, queue_slot): """After a block is expired, move any un-observed requests into the missed_obs queue.""" #self.queue should have any remaining obs if len(self.queue): cols = ['program_id', 'subprogram_name', 'program_pi', 'field_id', 'intranight_gap_min', 'exposure_time', 'priority'] # it's a little confusing, because each queue entry has all of the # filter_ids from the original request set. So we have to # make a pool that only has single filters in it. filter_id = int(self.filter_by_slot[queue_slot]) missed_obs = self.queue.loc[:,cols].copy() missed_obs['filter_ids'] = pd.Series([[filter_id] for i in missed_obs.index],index=missed_obs.index) missed_obs['total_requests_tonight'] = 1 self.logger.info(f"Saving {len(missed_obs)} requests (filter {filter_id}) to the missed_obs queue: {missed_obs.loc[:,['subprogram_name','field_id']]}") # the missed obs RequestPool wants request *sets*, so find out # if previous requests were missed rows_to_append = [] for idx, row in missed_obs.iterrows(): if idx in self.missed_obs_queue.rp.pool.index: assert(len(self.missed_obs_queue.rp.pool.loc[idx] == 1)) self.missed_obs_queue.rp.pool.loc[idx,'filter_ids'].append(filter_id) self.missed_obs_queue.rp.pool.loc[idx,'total_requests_tonight'] += 1 else: rows_to_append.append(row) self.missed_obs_queue.rp.pool = self.missed_obs_queue.rp.pool.append(rows_to_append) else: self.logger.debug(f'No remaining queued observations in slot {queue_slot}') def _remove_requests(self, request_set_id): """Remove a request from both the queue and the pool. Note that gurobi queue uses request_set_id to index.""" # should be the topmost item assert (self.queue_order[0] == request_set_id) self.queue_order = self.queue_order[1:] row = self.queue.loc[request_set_id] self.queue = self.queue.drop(request_set_id) # (past slot assignments are still in self.queued_requests_by_slot) # (we will only reuse the RequestPool if we do recomputes) self.rp.remove_request(request_set_id, self.filter_by_slot.loc[self.queue_slot]) def _return_queue(self): # start by setting up the current slot if len(self.queue) > 0: queue = self.queue.loc[self.queue_order].copy() queue.loc[:,'ordered'] = True queue.loc[:,'slot_start_time'] = block_index_to_time( self.queue_slot, Time.now(), where='start').iso else: # before the night starts, the queue is empty queue = self.queue.copy() # now loop over upcoming slots, ensuring they are sorted (should be) slots = self.queued_requests_by_slot.index.values slots = np.sort(slots) for slot in slots: if (self.queue_slot is not None): if slot <= self.queue_slot: continue slot_requests = self.queued_requests_by_slot.loc[slot] idx = pd.Index(slot_requests) # reconstruct df = self.rp.pool.loc[idx].join(self.fields.fields, on='field_id').copy() df.loc[:,'filter_id'] = self.filter_by_slot[slot] df.loc[:,'ordered'] = False df.loc[:,'slot_start_time'] = block_index_to_time(slot, Time.now(), where='start').iso queue = queue.append(df) return queue class GreedyQueueManager(QueueManager): def __init__(self, queue_name, queue_configuration, **kwargs): super().__init__(queue_name, queue_configuration, **kwargs) self.time_of_last_filter_change = None self.min_time_before_filter_change = TIME_BLOCK_SIZE self.queue_type = 'greedy' def _assign_nightly_requests(self, current_state, time_limit = 30.*u.second, block_use = defaultdict(float)): # initialize the time of last filter change if self.time_of_last_filter_change is None: self.time_of_last_filter_change = current_state['current_time'] def _next_obs(self, current_state, obs_log): """Select the highest value request.""" # since this is a greedy queue, we update the queue after each obs # for speed, only do the whole recalculation if we're in a new slot # if ((block_index(current_state['current_time'])[0] != self.queue_slot) # or (len(self.queue) == 0)): # self._update_queue(current_state) # else: # # otherwise just recalculate the overhead times # _ = self._update_overhead(current_state) # to get the "on the fly" cadence windows to work I have to # run the whole queue every time right now... self._update_queue(current_state, obs_log) # in case this wasn't initialized by assign_nightly_requests if self.time_of_last_filter_change is None: self.time_of_last_filter_change = current_state['current_time'] # check if filter changes are allowed yet if ((current_state['current_time'] - self.time_of_last_filter_change) < self.min_time_before_filter_change): # only consider observations in the current filter queue = self.queue[self.queue['filter_id'] == current_state['current_filter_id']] # unless there are no more observations, in which case allow a # change if len(queue) == 0: queue = self.queue else: # allow filter changes if desired queue = self.queue # request_id of the highest value request max_idx = queue.value.idxmax() row = queue.loc[max_idx] next_obs = {'target_field_id': row['field_id'], 'target_ra': row['ra'], 'target_dec': row['dec'], 'target_filter_id': row['filter_id'], 'target_program_id': row['program_id'], 'target_subprogram_name': row['subprogram_name'], 'target_program_pi': row['program_pi'], 'target_exposure_time': row['exposure_time'] * u.second, 'target_sky_brightness': row['sky_brightness'], 'target_limiting_mag': row['limiting_mag'], 'target_metric_value': row['value'], 'target_total_requests_tonight': row['total_requests_tonight'], 'target_mode_num': 0, 'target_num_images': 1, 'request_id': max_idx} return next_obs def _metric(self, df): """Calculate metric for prioritizing fields. Penalizes volume for both extinction (airmass) and fwhm penalty due to atmospheric refraction, plus sky brightness from moon phase and distance, overhead time == 1 for 21st mag, 15 sec overhead. Normalize by value at transit.""" return 10.**(0.6 * (df['limiting_mag'] - 21)) / \ (1-1e-4*(maximum_altitude(df['dec']) - 90)**2.) / \ ((EXPOSURE_TIME.value + df['overhead_time']) / (EXPOSURE_TIME.value + 10.)) def _update_overhead(self, current_state, df=None): """recalculate overhead values without regenerating whole queue""" inplace = df is None if inplace: # no dataframe supplied, so replace existing self.queue on exit df = self.queue df.drop(['overhead_time', 'altitude', 'azimuth'], axis=1, inplace=True) # compute readout/slew overhead times, plus current alt/az df_overhead, df_altaz = self.fields.overhead_time(current_state) # nb: df has index request_id, not field_id df = pd.merge(df, df_overhead, left_on='field_id', right_index=True) df = pd.merge(df, df_altaz, left_on='field_id', right_index=True) df.rename(columns={'alt': 'altitude', 'az': 'azimuth'}, inplace=True) # add overhead for filter changes w = df['filter_id'] != current_state['current_filter_id'] if np.sum(w): df.loc[w, 'overhead_time'] += FILTER_CHANGE_TIME.to(u.second).value if inplace: df.loc[:, 'value'] = self._metric(df) self.queue = df return df def _update_queue(self, current_state, obs_log): """Calculate greedy weighting of requests in the Pool using current telescope state only""" # store block index for which these values were calculated self.queue_slot = block_index(current_state['current_time'])[0] # check that the pool has fields in it if len(self.rp.pool) == 0: raise QueueEmptyError("No fields in pool") # join with fields so we have the information we need # make a copy so rp.pool and self.queue are not linked df_rs = self.rp.pool.join(self.fields.fields, on='field_id').copy() # now expand the dataframe of request sets to a dataframe with one # row per obs. requests = [] for request_set_id, row in df_rs.iterrows(): rdict = row.to_dict() filter_ids = rdict.pop('filter_ids') for filter_id in filter_ids: ri = rdict.copy() ri['filter_id'] = filter_id ri['request_set_id'] = request_set_id requests.append(ri) df = pd.DataFrame(requests) df = self._update_overhead(current_state, df=df) # start with conservative altitude cut; # airmass weighting applied naturally below # also make a copy because otherwise it retains knowledge of # (discarded) previous reference and raises SettingWithCopyWarnings df = df.loc[df['altitude'] > 20, :].copy() if len(df) == 0: raise QueueEmptyError("No fields in queue above altitude cut") # if restricting to one program per block, drop other programs if self.block_programs: current_block_program = PROGRAM_BLOCK_SEQUENCE[ self.queue_slot % LEN_BLOCK_SEQUENCE] df = df.loc[df['program_id'] == current_block_program, :] cadence_cuts = enough_gap_since_last_obs(df, current_state,obs_log) self.requests_in_window = np.sum(cadence_cuts) > 0 if ~self.requests_in_window: self.logger.warning(calc_queue_stats(df, current_state, intro="No fields with observable cadence windows. Queue in progress:")) raise QueueEmptyError("No fields with observable cadence windows") # also make a copy because otherwise it retains knowledge of # (discarded) previous reference and raises SettingWithCopyWarnings df = df.loc[cadence_cuts, :].copy() # compute airmasses by field_id # airmass = zenith_angle_to_airmass(90. - df_alt) # airmass.name = 'airmass' # df = pd.merge(df, pd.DataFrame(airmass), # left_on='field_id', right_index=True) # airmass cut (or add airmass weighting to value below) # df = df[(df['airmass'] <= MAX_AIRMASS) & (df['airmass'] > 0)] df_limmag, df_sky = compute_limiting_mag(df, current_state['current_time'], self.fields.Sky) df.loc[:, 'limiting_mag'] = df_limmag df.loc[:, 'sky_brightness'] = df_sky #df_limmag.name = 'limiting_mag' #df = pd.merge(df, df_limmag, left_on='field_id', right_index=True) df.loc[:, 'value'] = self._metric(df) self.queue = df def _remove_requests(self, request_id): """Remove a request from both the queue and the request pool""" row = self.queue.loc[request_id] self.queue = self.queue.drop(request_id) self.rp.remove_request(row['request_set_id'], row['filter_id']) def _return_queue(self): if 'value' in self.queue.columns: queue = self.queue.sort_values('value',ascending=False).copy() else: queue = self.queue.copy() # we have put these in value order but the sequence can change queue['ordered'] = False return queue class ListQueueManager(QueueManager): """Simple Queue that returns observations in order.""" def __init__(self, queue_name, queue_configuration, fields=None, **kwargs): self.queue_type = 'list' # queue name (useful in Scheduler object when swapping queues) self.queue_name = queue_name if fields is None: self.fields = Fields() else: self.fields = fields # the queue itself self.load_list_queue(queue_configuration.config['targets']) if 'validity_window_mjd' in queue_configuration.config: window = queue_configuration.config['validity_window_mjd'] if window is not None: assert(len(window) == 2) assert(window[1] > window[0]) self.validity_window = [Time(window[0],format='mjd'), Time(window[1],format='mjd')] else: self.validity_window = None else: self.validity_window = None self.is_TOO = queue_configuration.config['targets'][0]['subprogram_name'].startswith('ToO') def _assign_nightly_requests(self, current_state, **kwargs): pass def _update_queue(self, current_state, obs_log): pass def load_list_queue(self, queue_dict_list, append=False): """Initialize an ordered queue. queue_dict_list is a list of dicts, one per observation""" df = pd.DataFrame(queue_dict_list) # check that major columns are included required_columns = ['field_id','program_id', 'subprogram_name', 'filter_id', 'program_pi'] for col in required_columns: if col not in df.columns: raise ValueError(f'Missing required column {col}') # by default use field ids alone to specify pointings, # but allow manual ra/dec if needed if ('ra' not in df.columns) and ('dec' not in df.columns): queue = df.join(self.fields.fields, on='field_id', how='inner').sort_index().copy() else: queue = df # if some of the field ids are bad, there will be missing rows if len(queue) != len(df): raise ValueError('One or more field ids are malformed: {}'.format( df.index.difference(self.fields.fields.index))) # add standard keywords if not present if 'exposure_time' not in queue.columns: queue['exposure_time'] = EXPOSURE_TIME.to(u.second).value if 'max_airmass' not in queue.columns: queue['max_airmass'] = MAX_AIRMASS if 'n_repeats' not in queue.columns: queue['n_repeats'] = 1 if 'mode_num' not in queue.columns: queue['mode_num'] = 0 if 'ewr_num_images' not in queue.columns: queue['num_images'] = 1 else: queue['num_images'] = queue['ewr_num_images'] if append: self.queue = self.queue.append(queue, ignore_index=True) else: self.queue = queue def _next_obs(self, current_state, obs_log): """Return the next observation in the time ordered queue unless it has expired.""" if len(self.queue) == 0: raise QueueEmptyError("No more observations in queue!") # take the next observation in line idx = 0 while True: if idx == len(self.queue): raise QueueEmptyError("No valid observations in queue!") ra = self.queue.iloc[idx].ra ha = RA_to_HA(ra * u.degree, current_state['current_time'] ).to(u.degree).wrap_at(180.*u.degree).value dec = self.queue.iloc[idx].dec sc = coord.SkyCoord(ra,dec, unit=u.deg) airmass = altitude_to_airmass( skycoord_to_altaz(sc, current_state['current_time']).alt.to(u.deg).value) if airmass >= self.queue.iloc[idx].max_airmass: idx += 1 continue # Reed limits |HA| to < 5.95 hours (most relevant for circumpolar # fields not hit by the airmass cut) if np.abs(ha) >= (5.95 * u.hourangle).to(u.degree).value: idx += 1 continue # 1) HA < -17.6 deg && Dec < -22 deg is rejected for both track & stow because of interference with FFI. if (ha <= -17.6) & (dec <= -22): idx += 1 continue # West of HA -17.6 deg, Dec < -45 deg is rejected for tracking because of the service platform in the south. if (ha >= -17.6) & (dec <= -45): idx += 1 continue # fabs(HA) > 3 deg is rejected for Dec < -46 to protect the shutter "ears". if (np.abs(ha) >= 3.) & (dec <= -46): idx += 1 continue # dec > 87.5 is rejected if (dec > 87.5): idx += 1 continue break next_obs = {'target_field_id': int(self.queue.iloc[idx].field_id), 'target_ra': self.queue.iloc[idx].ra, 'target_dec': self.queue.iloc[idx].dec, 'target_filter_id': self.queue.iloc[idx].filter_id, 'target_program_id': int(self.queue.iloc[idx].program_id), 'target_subprogram_name': self.queue.iloc[idx].subprogram_name, 'target_program_pi': self.queue.iloc[idx].program_pi, 'target_exposure_time': self.queue.iloc[idx].exposure_time * u.second, 'target_sky_brightness': 0., 'target_limiting_mag': 0., 'target_metric_value': 0., 'target_total_requests_tonight': 1, 'target_mode_num': int(self.queue.iloc[idx].mode_num), 'target_num_images': int(self.queue.iloc[idx].num_images), 'request_id': self.queue.index[idx]} return next_obs def _remove_requests(self, request_id): """Remove a request from the queue""" try: if self.queue.loc[request_id,'n_repeats'] > 1: self.queue.loc[request_id,'n_repeats'] -= 1 else: self.queue = self.queue.drop(request_id) except Exception: self.logger.exception(f'Failure removing request {request_id}') def _return_queue(self): # by construction the list queue is already in order queue = self.queue.copy() queue['ordered'] = True return queue class RequestPool(object): def __init__(self): # initialize empty dataframe to add to self.pool = pd.DataFrame() pass def add_request_sets(self, program_id, subprogram_name, program_pi, field_ids, filter_ids, intranight_gap, exposure_time, total_requests_tonight, priority=1): """program_ids must be scalar""" assert (scalar_len(program_id) == 1) assert (scalar_len(subprogram_name) == 1) n_fields = scalar_len(field_ids) if n_fields == 1: # see if it's iterable or not try: iterator = iter(field_ids) except TypeError: # if not, assume it's a scalar and wrap in a list field_ids = [field_ids] # build df as a list of dicts request_sets = [] for i, field_id in enumerate(field_ids): request_sets.append({ 'program_id': program_id, 'subprogram_name': subprogram_name, 'program_pi': program_pi, 'field_id': field_id, 'filter_ids': filter_ids.copy(), # pandas doesn't play well with astropy quantities, so change # back to seconds 'intranight_gap_min': intranight_gap.to(u.minute).value, 'exposure_time': exposure_time.to(u.second).value, 'total_requests_tonight': total_requests_tonight, 'priority': priority}) self.pool = self.pool.append(pd.DataFrame(request_sets), ignore_index=True) def n_request_sets(self): return len(self.pool) def remove_request_sets(self, request_set_ids): """Remove completed or otherwise unwanted requests by request_id request_ids : scalar or list requests to drop (index of self.pool)""" self.pool = self.pool.drop(request_set_ids) def remove_request(self, request_set_id, filter_id): """Remove single completed request from a request set. request_set_id: scalar request set to modify (index of self.pool) filter_id: scalar filter_id of completed observation""" rs = self.pool.loc[request_set_id].copy() filters = rs['filter_ids'] # this is another step that shouldn't be necessary... filters.remove(filter_id) if len(filters) == 0: self.remove_request_sets(request_set_id) else: self.pool.at[request_set_id, 'filter_ids'] = filters def clear_all_request_sets(self): self.pool = pd.DataFrame() # utils for examining inputs def calc_pool_stats(df, intro=""): """ df = Q.rp.pool""" stats_str = intro + "\n" stats_str += "\t{} request sets\n".format(len(df)) stats_str += "\t{} unique fields\n".format(len(set(df.field_id))) for prog_id in PROGRAM_IDS: w = df.program_id == prog_id stats_str += "\tProgram {}:\n".format(prog_id) stats_str += "\t\t{} request sets\n".format(np.sum(w)) stats_str += "\t\t{} unique fields\n".format( len(set(df.loc[w, 'field_id']))) stats_str += "\t\t{} median requests tonight per field\n".format( np.median(df.loc[w, 'total_requests_tonight'])) return stats_str def calc_queue_stats(df, current_state, intro=""): """ df = Q.queue""" stats_str = intro + "\n" stats_str += "\t{} queued requests\n".format(len(df)) stats_str += "\t{} unique fields\n".format(len(set(df.field_id))) for prog_id in PROGRAM_IDS: w = df.program_id == prog_id stats_str += "\tProgram {}:\n".format(prog_id) if np.sum(w) == 0: stats_str += "\t\tNo queued requests!\n" continue stats_str += "\t\t{} requests\n".format(np.sum(w)) stats_str += "\t\t{} unique fields\n".format( len(set(df.loc[w, 'field_id']))) walt = w & (df.loc[w, 'altitude'] > 20) stats_str += "\t\t{} fields above altitude cut\n".format( np.sum(walt)) # wfirst = walt & (df.loc[walt, 'request_number_tonight'] == 1) # stats_str += "\t\t{} requests awaiting first obs tonight\n".format( # np.sum(wfirst)) return stats_str
[ "numpy.sum", "numpy.maximum", "numpy.abs", "numpy.floor", "numpy.isnan", "collections.defaultdict", "numpy.arange", "numpy.round", "numpy.unique", "pandas.DataFrame", "numpy.meshgrid", "pandas.merge", "os.path.exists", "pandas.concat", "numpy.median", "astropy.time.Time", "astropy.ti...
[((1247, 1274), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (1264, 1274), False, 'import logging\n'), ((2479, 2493), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (2491, 2493), True, 'import pandas as pd\n'), ((4589, 4632), 'astropy.time.Time', 'Time', (['self.validity_window[0]'], {'format': '"""mjd"""'}), "(self.validity_window[0], format='mjd')\n", (4593, 4632), False, 'from astropy.time import Time, TimeDelta\n'), ((5723, 5741), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (5734, 5741), False, 'from collections import defaultdict\n'), ((5764, 5802), 'numpy.arange', 'np.arange', (['start_block', '(stop_block + 1)'], {}), '(start_block, stop_block + 1)\n', (5773, 5802), True, 'import numpy as np\n'), ((6197, 6215), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (6208, 6215), False, 'from collections import defaultdict\n'), ((6247, 6263), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (6258, 6263), False, 'from collections import defaultdict\n'), ((7933, 7976), 'numpy.floor', 'np.floor', (["current_state['current_time'].mjd"], {}), "(current_state['current_time'].mjd)\n", (7941, 7976), True, 'import numpy as np\n'), ((8963, 9000), 'numpy.sum', 'np.sum', (["obs_count_by_program['n_obs']"], {}), "(obs_count_by_program['n_obs'])\n", (8969, 9000), True, 'import numpy as np\n'), ((9355, 9390), 'pandas.Series', 'pd.Series', (['target_program_fractions'], {}), '(target_program_fractions)\n', (9364, 9390), True, 'import pandas as pd\n'), ((9986, 10014), 'astropy.time.Time', 'Time', (['mjd_stop'], {'format': '"""mjd"""'}), "(mjd_stop, format='mjd')\n", (9990, 10014), False, 'from astropy.time import Time, TimeDelta\n'), ((10346, 10387), 'numpy.round', 'np.round', (['(next_month_start_mjd - time.mjd)'], {}), '(next_month_start_mjd - time.mjd)\n', (10354, 10387), True, 'import numpy as np\n'), ((12246, 12293), 'pandas.Series', 'pd.Series', (['obs_count_by_current_subprogram_dict'], {}), '(obs_count_by_current_subprogram_dict)\n', (12255, 12293), True, 'import pandas as pd\n'), ((12586, 12604), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (12597, 12604), False, 'from collections import defaultdict\n'), ((12848, 12886), 'pandas.Series', 'pd.Series', (['target_subprogram_fractions'], {}), '(target_subprogram_fractions)\n', (12857, 12886), True, 'import pandas as pd\n'), ((13629, 13657), 'astropy.time.Time', 'Time', (['mjd_stop'], {'format': '"""mjd"""'}), "(mjd_stop, format='mjd')\n", (13633, 13657), False, 'from astropy.time import Time, TimeDelta\n'), ((13989, 14030), 'numpy.round', 'np.round', (['(next_month_start_mjd - time.mjd)'], {}), '(next_month_start_mjd - time.mjd)\n', (13997, 14030), True, 'import numpy as np\n'), ((14508, 14524), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (14519, 14524), False, 'from collections import defaultdict\n'), ((16013, 16031), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (16024, 16031), False, 'from collections import defaultdict\n'), ((20289, 20307), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (20300, 20307), False, 'from collections import defaultdict\n'), ((23490, 23508), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (23501, 23508), False, 'from collections import defaultdict\n'), ((25860, 25882), 'pandas.DataFrame', 'pd.DataFrame', (['lim_mags'], {}), '(lim_mags)\n', (25872, 25882), True, 'import pandas as pd\n'), ((25919, 25949), 'pandas.DataFrame', 'pd.DataFrame', (['sky_brightnesses'], {}), '(sky_brightnesses)\n', (25931, 25949), True, 'import pandas as pd\n'), ((25971, 25989), 'pandas.DataFrame', 'pd.DataFrame', (['decs'], {}), '(decs)\n', (25983, 25989), True, 'import pandas as pd\n'), ((27449, 27520), 'pandas.merge', 'pd.merge', (['dft', "df[['field_id']]"], {'left_on': '"""request_id"""', 'right_index': '(True)'}), "(dft, df[['field_id']], left_on='request_id', right_index=True)\n", (27457, 27520), True, 'import pandas as pd\n'), ((27564, 27588), 'numpy.sum', 'np.sum', (["dft['scheduled']"], {}), "(dft['scheduled'])\n", (27570, 27588), True, 'import numpy as np\n'), ((27618, 27658), 'numpy.sum', 'np.sum', (["(dft['scheduled'] * dft['metric'])"], {}), "(dft['scheduled'] * dft['metric'])\n", (27624, 27658), True, 'import numpy as np\n'), ((30185, 30203), 'pandas.Index', 'pd.Index', (['req_list'], {}), '(req_list)\n', (30193, 30203), True, 'import pandas as pd\n'), ((30727, 30768), 'pandas.concat', 'pd.concat', (['[df_blockstart, df]'], {'sort': '(True)'}), '([df_blockstart, df], sort=True)\n', (30736, 30768), True, 'import pandas as pd\n'), ((31496, 31549), 'numpy.maximum', 'np.maximum', (["slews_by_axis['ra']", "slews_by_axis['dec']"], {}), "(slews_by_axis['ra'], slews_by_axis['dec'])\n", (31506, 31549), True, 'import numpy as np\n'), ((31569, 31612), 'numpy.maximum', 'np.maximum', (["slews_by_axis['dome']", 'maxradec'], {}), "(slews_by_axis['dome'], maxradec)\n", (31579, 31612), True, 'import numpy as np\n'), ((31839, 31873), 'numpy.maximum', 'np.maximum', (['maxslews', 'READOUT_TIME'], {}), '(maxslews, READOUT_TIME)\n', (31849, 31873), True, 'import numpy as np\n'), ((35522, 35536), 'numpy.sort', 'np.sort', (['slots'], {}), '(slots)\n', (35529, 35536), True, 'import numpy as np\n'), ((36623, 36641), 'collections.defaultdict', 'defaultdict', (['float'], {}), '(float)\n', (36634, 36641), False, 'from collections import defaultdict\n'), ((40428, 40491), 'pandas.merge', 'pd.merge', (['df', 'df_overhead'], {'left_on': '"""field_id"""', 'right_index': '(True)'}), "(df, df_overhead, left_on='field_id', right_index=True)\n", (40436, 40491), True, 'import pandas as pd\n'), ((40505, 40565), 'pandas.merge', 'pd.merge', (['df', 'df_altaz'], {'left_on': '"""field_id"""', 'right_index': '(True)'}), "(df, df_altaz, left_on='field_id', right_index=True)\n", (40513, 40565), True, 'import pandas as pd\n'), ((40764, 40773), 'numpy.sum', 'np.sum', (['w'], {}), '(w)\n', (40770, 40773), True, 'import numpy as np\n'), ((42099, 42121), 'pandas.DataFrame', 'pd.DataFrame', (['requests'], {}), '(requests)\n', (42111, 42121), True, 'import pandas as pd\n'), ((46364, 46393), 'pandas.DataFrame', 'pd.DataFrame', (['queue_dict_list'], {}), '(queue_dict_list)\n', (46376, 46393), True, 'import pandas as pd\n'), ((51602, 51616), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (51614, 51616), True, 'import pandas as pd\n'), ((54118, 54132), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (54130, 54132), True, 'import pandas as pd\n'), ((4133, 4165), 'astropy.time.Time', 'Time', (['window_start'], {'format': '"""mjd"""'}), "(window_start, format='mjd')\n", (4137, 4165), False, 'from astropy.time import Time, TimeDelta\n'), ((4178, 4209), 'astropy.time.Time', 'Time', (['window_stop'], {'format': '"""mjd"""'}), "(window_stop, format='mjd')\n", (4182, 4209), False, 'from astropy.time import Time, TimeDelta\n'), ((24549, 24585), 'numpy.setdiff1d', 'np.setdiff1d', (['blocks', 'exclude_blocks'], {}), '(blocks, exclude_blocks)\n', (24561, 24585), True, 'import numpy as np\n'), ((30077, 30095), 'numpy.isnan', 'np.isnan', (['req_list'], {}), '(req_list)\n', (30085, 30095), True, 'import numpy as np\n'), ((30996, 31021), 'numpy.meshgrid', 'np.meshgrid', (['coord', 'coord'], {}), '(coord, coord)\n', (31007, 31021), True, 'import numpy as np\n'), ((31043, 31058), 'numpy.abs', 'np.abs', (['(c1 - c2)'], {}), '(c1 - c2)\n', (31049, 31058), True, 'import numpy as np\n'), ((31079, 31136), 'numpy.where', 'np.where', (['(dangle < 360.0 - dangle)', 'dangle', '(360.0 - dangle)'], {}), '(dangle < 360.0 - dangle, dangle, 360.0 - dangle)\n', (31087, 31136), True, 'import numpy as np\n'), ((33155, 33229), 'pandas.Series', 'pd.Series', (['[[filter_id] for i in missed_obs.index]'], {'index': 'missed_obs.index'}), '([[filter_id] for i in missed_obs.index], index=missed_obs.index)\n', (33164, 33229), True, 'import pandas as pd\n'), ((35771, 35794), 'pandas.Index', 'pd.Index', (['slot_requests'], {}), '(slot_requests)\n', (35779, 35794), True, 'import pandas as pd\n'), ((43002, 43022), 'numpy.sum', 'np.sum', (['cadence_cuts'], {}), '(cadence_cuts)\n', (43008, 43022), True, 'import numpy as np\n'), ((48661, 48696), 'astropy.coordinates.SkyCoord', 'coord.SkyCoord', (['ra', 'dec'], {'unit': 'u.deg'}), '(ra, dec, unit=u.deg)\n', (48675, 48696), True, 'import astropy.coordinates as coord\n'), ((53038, 53064), 'pandas.DataFrame', 'pd.DataFrame', (['request_sets'], {}), '(request_sets)\n', (53050, 53064), True, 'import pandas as pd\n'), ((54562, 54571), 'numpy.sum', 'np.sum', (['w'], {}), '(w)\n', (54568, 54571), True, 'import numpy as np\n'), ((54758, 54804), 'numpy.median', 'np.median', (["df.loc[w, 'total_requests_tonight']"], {}), "(df.loc[w, 'total_requests_tonight'])\n", (54767, 54804), True, 'import numpy as np\n'), ((55204, 55213), 'numpy.sum', 'np.sum', (['w'], {}), '(w)\n', (55210, 55213), True, 'import numpy as np\n'), ((55343, 55352), 'numpy.sum', 'np.sum', (['w'], {}), '(w)\n', (55349, 55352), True, 'import numpy as np\n'), ((55579, 55591), 'numpy.sum', 'np.sum', (['walt'], {}), '(walt)\n', (55585, 55591), True, 'import numpy as np\n'), ((3881, 3899), 'astropy.time.Time', 'Time', (['"""2017-01-01"""'], {}), "('2017-01-01')\n", (3885, 3899), False, 'from astropy.time import Time, TimeDelta\n'), ((4004, 4022), 'astropy.time.Time', 'Time', (['"""2030-01-01"""'], {}), "('2030-01-01')\n", (4008, 4022), False, 'from astropy.time import Time, TimeDelta\n'), ((5049, 5077), 'numpy.sum', 'np.sum', (['self.queue.n_repeats'], {}), '(self.queue.n_repeats)\n', (5055, 5077), True, 'import numpy as np\n'), ((5105, 5160), 'numpy.sum', 'np.sum', (['(self.queue.exposure_time * self.queue.n_repeats)'], {}), '(self.queue.exposure_time * self.queue.n_repeats)\n', (5111, 5160), True, 'import numpy as np\n'), ((5246, 5278), 'numpy.sum', 'np.sum', (['self.queue.exposure_time'], {}), '(self.queue.exposure_time)\n', (5252, 5278), True, 'import numpy as np\n'), ((10679, 10707), 'numpy.round', 'np.round', (['delta_program_nobs'], {}), '(delta_program_nobs)\n', (10687, 10707), True, 'import numpy as np\n'), ((14328, 14359), 'numpy.round', 'np.round', (['delta_subprogram_nobs'], {}), '(delta_subprogram_nobs)\n', (14336, 14359), True, 'import numpy as np\n'), ((15009, 15045), 'datetime.datetime', 'datetime', (['dtnow.year', 'dtnow.month', '(1)'], {}), '(dtnow.year, dtnow.month, 1)\n', (15017, 15045), False, 'from datetime import datetime\n'), ((18307, 18350), 'numpy.floor', 'np.floor', (["current_state['current_time'].mjd"], {}), "(current_state['current_time'].mjd)\n", (18315, 18350), True, 'import numpy as np\n'), ((29112, 29130), 'numpy.floor', 'np.floor', (['tnow.mjd'], {}), '(tnow.mjd)\n', (29120, 29130), True, 'import numpy as np\n'), ((29281, 29313), 'os.path.exists', 'os.path.exists', (['solution_outfile'], {}), '(solution_outfile)\n', (29295, 29313), False, 'import os\n'), ((49110, 49120), 'numpy.abs', 'np.abs', (['ha'], {}), '(ha)\n', (49116, 49120), True, 'import numpy as np\n'), ((10119, 10159), 'datetime.datetime', 'datetime', (['dtnow.year', '(dtnow.month + 1)', '(1)'], {}), '(dtnow.year, dtnow.month + 1, 1)\n', (10127, 10159), False, 'from datetime import datetime\n'), ((10248, 10278), 'datetime.datetime', 'datetime', (['(dtnow.year + 1)', '(1)', '(1)'], {}), '(dtnow.year + 1, 1, 1)\n', (10256, 10278), False, 'from datetime import datetime\n'), ((13762, 13802), 'datetime.datetime', 'datetime', (['dtnow.year', '(dtnow.month + 1)', '(1)'], {}), '(dtnow.year, dtnow.month + 1, 1)\n', (13770, 13802), False, 'from datetime import datetime\n'), ((13891, 13921), 'datetime.datetime', 'datetime', (['(dtnow.year + 1)', '(1)', '(1)'], {}), '(dtnow.year + 1, 1, 1)\n', (13899, 13921), False, 'from datetime import datetime\n'), ((17100, 17120), 'numpy.round', 'np.round', (['n_requests'], {}), '(n_requests)\n', (17108, 17120), True, 'import numpy as np\n'), ((26305, 26338), 'numpy.sum', 'np.sum', (['[(xi == fid) for xi in x]'], {}), '([(xi == fid) for xi in x])\n', (26311, 26338), True, 'import numpy as np\n'), ((27047, 27059), 'numpy.unique', 'np.unique', (['x'], {}), '(x)\n', (27056, 27059), True, 'import numpy as np\n'), ((35229, 35239), 'astropy.time.Time.now', 'Time.now', ([], {}), '()\n', (35237, 35239), False, 'from astropy.time import Time, TimeDelta\n'), ((36097, 36107), 'astropy.time.Time.now', 'Time.now', ([], {}), '()\n', (36105, 36107), False, 'from astropy.time import Time, TimeDelta\n'), ((45704, 45733), 'astropy.time.Time', 'Time', (['window[0]'], {'format': '"""mjd"""'}), "(window[0], format='mjd')\n", (45708, 45733), False, 'from astropy.time import Time, TimeDelta\n'), ((45754, 45783), 'astropy.time.Time', 'Time', (['window[1]'], {'format': '"""mjd"""'}), "(window[1], format='mjd')\n", (45758, 45783), False, 'from astropy.time import Time, TimeDelta\n'), ((49749, 49759), 'numpy.abs', 'np.abs', (['ha'], {}), '(ha)\n', (49755, 49759), True, 'import numpy as np\n')]
import yaml import tensorflow as tf import numpy as np import time from datetime import datetime from tqdm.auto import trange, tqdm class Logger(object): def __init__(self, epochs, frequency): # print("Hyperparameters:") # print(json.dumps(HP, indent=2)) # print() print("TensorFlow version: {}".format(tf.__version__)) print("Eager execution: {}".format(tf.executing_eagerly())) print("GPU-accerelated: {}".format(tf.test.is_gpu_available())) self.start_time = time.time() self.prev_time = self.start_time self.tf_epochs = epochs self.frequency = frequency self.pbar = None self.epochs = [] self.logs = [] self.logs_keys = None self.get_val_err = None def get_epoch_duration(self): now = time.time() edur = datetime.fromtimestamp(now - self.prev_time) \ .strftime("%S.%f")[:-5] self.prev_time = now return edur def get_elapsed(self): return datetime.fromtimestamp(time.time() - self.start_time) \ .strftime("%M:%S") def set_val_err_fn(self, fn): self.get_val_err = fn def log_train_start(self): print("\nTraining started") print("================") self.pbar = tqdm(total=self.tf_epochs) def log_train_epoch(self, epoch, loss, custom="", is_iter=False): self.pbar.update(1) self.pbar.set_description(f"L: {loss:.4e}") if epoch % self.frequency == 0: logs = {"L": loss, **self.get_val_err()} if self.logs_keys is None: self.logs_keys = list(logs.keys()) logs_values = [logs[x] for x in self.logs_keys] logs_message = "" for i, key in enumerate(self.logs_keys): if i >= len(logs_values) - 2: logs_message += f" {key}: {logs_values[i]:.4f}" else: logs_message += f" {key}: {logs_values[i]:.3e}" name = 'nt_epoch' if is_iter else '#' message = f"{name}: {epoch:6d} " + \ logs_message + custom self.pbar.write(message) self.epochs.append(epoch) self.logs.append(logs_values) def log_train_opt(self, name): print(f"-- Starting {name} optimization --") def log_train_end(self, epoch, custom=""): self.pbar.close() print("==================") print(f"Training finished (epoch {epoch}): " + f"duration = {self.get_elapsed()} " + custom) def get_logs(self): epochs = np.array(self.epochs)[:, None] logs = np.array(self.logs) header = "epoch\t" header += "\t".join(self.logs_keys) values = np.hstack((epochs, logs)) return (header, np.hstack((epochs, logs)))
[ "numpy.hstack", "tqdm.auto.tqdm", "tensorflow.executing_eagerly", "time.time", "numpy.array", "datetime.datetime.fromtimestamp", "tensorflow.test.is_gpu_available" ]
[((526, 537), 'time.time', 'time.time', ([], {}), '()\n', (535, 537), False, 'import time\n'), ((832, 843), 'time.time', 'time.time', ([], {}), '()\n', (841, 843), False, 'import time\n'), ((1312, 1338), 'tqdm.auto.tqdm', 'tqdm', ([], {'total': 'self.tf_epochs'}), '(total=self.tf_epochs)\n', (1316, 1338), False, 'from tqdm.auto import trange, tqdm\n'), ((2687, 2706), 'numpy.array', 'np.array', (['self.logs'], {}), '(self.logs)\n', (2695, 2706), True, 'import numpy as np\n'), ((2797, 2822), 'numpy.hstack', 'np.hstack', (['(epochs, logs)'], {}), '((epochs, logs))\n', (2806, 2822), True, 'import numpy as np\n'), ((2641, 2662), 'numpy.array', 'np.array', (['self.epochs'], {}), '(self.epochs)\n', (2649, 2662), True, 'import numpy as np\n'), ((2856, 2881), 'numpy.hstack', 'np.hstack', (['(epochs, logs)'], {}), '((epochs, logs))\n', (2865, 2881), True, 'import numpy as np\n'), ((402, 424), 'tensorflow.executing_eagerly', 'tf.executing_eagerly', ([], {}), '()\n', (422, 424), True, 'import tensorflow as tf\n'), ((470, 496), 'tensorflow.test.is_gpu_available', 'tf.test.is_gpu_available', ([], {}), '()\n', (494, 496), True, 'import tensorflow as tf\n'), ((859, 903), 'datetime.datetime.fromtimestamp', 'datetime.fromtimestamp', (['(now - self.prev_time)'], {}), '(now - self.prev_time)\n', (881, 903), False, 'from datetime import datetime\n'), ((1057, 1068), 'time.time', 'time.time', ([], {}), '()\n', (1066, 1068), False, 'import time\n')]
import numpy as np from Bio import AlignIO from scipy.ndimage import gaussian_filter from skimage.transform import resize as imresize import pickle import h5py import pandas as pd from copy import deepcopy #function form def alnFileToArray(filename): alnfile = filename msa = AlignIO.read(alnfile , format = 'fasta') align_array = np.array([ list(rec.upper()) for rec in msa], np.character) return align_array def generateGapMatrix(align_array): gap_array = np.array([[1 if (align_array[i][j] == b'.' or align_array[i][j] == b'-') else 0 for j in range(align_array.shape[1])] for i in range(align_array.shape[0])]) return gap_array def generateAlignVoxel(align_array, numerical,properties, verbose = False): assert align_array is not None align_prop_voxel = np.zeros((align_array.shape[0], align_array.shape[1], len(numerical) + 1), dtype=float) if(verbose): print('final voxel shape: ', align_prop_voxel.shape) if(verbose): print('initial array shape: ', align_array.shape) for prop in numerical: align_prop_array = np.zeros(align_array.shape, dtype=float) #align_prop_array = [[properties[prop][bstring] for bstring in seq] for seq in align_array] i = 0 j = 0 for seq in align_array: j = 0 for bstring in seq: if i >= align_array.shape[0] or j >= align_array.shape[1]: print('out of bounds. align_array size: ', align_array.shape, 'i: ', i, 'j: ', j) if bstring in unambiguousAANames: align_prop_array[i][j] = properties[prop][bstring] elif bstring == b'B': align_prop_array[i][j] = properties[prop][b'D'] elif bstring == b'Z': align_prop_array[i][j] = properties[prop][b'E'] else: align_prop_array[i][j] = properties[prop][b'A'] j = j+1 i = i+1 align_prop_voxel[:,:,numerical.index(prop)] = align_prop_array gap_array = generateGapMatrix(align_array) align_prop_voxel[:,:,12] = gap_array if(verbose): print('full voxel shape: ', align_prop_voxel.shape) return align_prop_voxel def clip_fft_edge(infft , keep_edge = [ 20 , 115 , 5 ]): #create a compact little voxel only containing the corners of the fft #for storgage in hdf5 original_shape = infft.shape #make a smaller voxel containing just the corners of the original corners = np.zeros(2*np.array(keep_edge), np.complex) boundaries = [[ keep_edge[i] , infft.shape[i] -keep_edge[i] ] for i in range(len(keep_edge))] #print(boundaries) #not spatial axes... prob should use nicer var names but whatever #keep the 8 corners of the cube for i,x in enumerate(boundaries[0]): for j,y in enumerate(boundaries[1]): for k,z in enumerate(boundaries[2]): slc1 = [slice(None)] * len(infft.shape) slc2 = [slice(None)] * len(infft.shape) '''print('i, j, k', i, j, k) print('x, y, z', x, y, z)''' for n,corn in enumerate(zip([i,j,k],[x,y,z])): #print(corn) if corn[0] == 0: slc1[n] = slice(0, corn[1]) #print('corner slice: ', slc1) slc2[n] = slice(0, corn[1]) #print('voxel slice: ', slc2) else: slc1[n] = slice(keep_edge[n], None) #print('corner slice: ', slc1) slc2[n] = slice(corn[1], None) #print('voxel slice: ', slc2) #grab corner '''print(slc1, 'going to ') print(slc2)''' corners[slc1] = infft[slc2] return original_shape , corners def clip_fft_edge_no_depth(infft , keep_edge = [20, 115]): #keep only the 4 outer corners of the voxel (depth stays the same) #for storgage in hdf5 original_shape = infft.shape #make a smaller voxel containing just the corners of the original corners = np.zeros((2*keep_edge[0], 2*keep_edge[1], infft.shape[2]), np.complex) boundaries = [[ keep_edge[i] , infft.shape[i] -keep_edge[i] ] for i in range(len(keep_edge))] boundaries.append([0, infft.shape[2]]) for i,x in enumerate(boundaries[0]): for j,y in enumerate(boundaries[1]): for k,z in enumerate(boundaries[2]): slc1 = [slice(None)] * len(infft.shape) slc2 = [slice(None)] * len(infft.shape) for n,corn in enumerate(zip([i,j],[x,y])): if corn[0] == 0: slc1[n] = slice(0, corn[1]) #print('corner slice: ', slc1) slc2[n] = slice(0, corn[1]) #print('voxel slice: ', slc2) else: slc1[n] = slice(keep_edge[n], None) #print('corner slice: ', slc1) slc2[n] = slice(corn[1], None) #print('voxel slice: ', slc2) #grab corner '''print(slc1, 'going to ') print(slc2)''' corners[slc1] = infft[slc2] return original_shape , corners def clippded2original(corners , original_shape, keep_edge = [ 20 , 115 , 5 ]): #restore the fft to its original shape original = np.zeros(original_shape, np.complex) boundaries = [[ keep_edge[i] , original.shape[i] -keep_edge[i] ] for i in range(len(keep_edge)) ] for i,x in enumerate(boundaries[0]): for j,y in enumerate(boundaries[1]): for k,z in enumerate(boundaries[2]): slc1 = [slice(None)] * len(original.shape) slc2 = [slice(None)] * len(original.shape) for n,corn in enumerate(zip([i,j,k],[x,y,z])): if corn[0] == 0: slc1[n] = slice(0, corn[1]) slc2[n] = slice(0, corn[1]) '''print('corner slice: ', slc1) print('voxel slice: ', slc2)''' else: slc1[n] = slice(keep_edge[n], None) slc2[n] = slice(corn[1], None) #grab corner original[slc2] = corners[slc1] return original def clippded2original_no_depth(corners , original_shape, keep_edge = [ 20, 115 ]): #restore the fft to its original shape original = np.zeros(original_shape, np.complex) boundaries = [[ keep_edge[i] , original.shape[i] -keep_edge[i] ] for i in range(len(keep_edge)) ] boundaries.append([0, original_shape[2]]) for i,x in enumerate(boundaries[0]): for j,y in enumerate(boundaries[1]): for k,z in enumerate(boundaries[2]): slc1 = [slice(None)] * len(original.shape) slc2 = [slice(None)] * len(original.shape) for n,corn in enumerate(zip([i,j],[x,y])): if corn[0] == 0: slc1[n] = slice(0, corn[1]) slc2[n] = slice(0, corn[1]) else: slc1[n] = slice(keep_edge[n], None) slc2[n] = slice(corn[1], None) #grab corner original[slc2] = corners[slc1] return original def fourierNDarrayVoxels(array, clipSizes = [ None , None , None ] ): arrayFFT = None if array is not None: arrayFFT = np.fft.rfftn(array, s = clipSizes) return arrayFFT def aln2fft(alnglob, propfile = './physicalpropTable.csv' , scaling = [ 4 , 4 , 4 ] , keep_edge = [ 20, 115 , 15 ] , sigma_filter = .1 , saveout= False ): propdf = pd.read_csv(propfile) numerical = [ 'pKa side chain', 'pka2', 'pka3', 'PI', 'Solubility Molal', 'MW', 'charge', 'ww hydrophob scale', 'hydr or amine', 'aliphatic', 'aromatic', 'hydrophobicity at ph7'] for col in numerical: #scale from 0 to 1 propdf[col] = propdf[col]-propdf[col].min() propdf[col] = propdf[col]/propdf[col].max() properties = { prop: dict(zip(propdf['letter Code' ] , propdf[prop] ) ) for prop in numerical } properties = { prop:{c.encode(): properties[prop][c] for c in properties[prop]} for prop in properties} unambiguousAANames = {b'A', b'R', b'N', b'D', b'C', b'Q', b'E', b'G', b'H', b'I', b'L', b'K', b'M', b'F', b'P', b'S', b'T', b'W', b'Y', b'V'} for alnfile in alnglob: msa = AlignIO.read(alnfile , format = 'fasta') align_array = np.array([ list(rec.upper()) for rec in msa], np.character) vox = generateAlignVoxel( align_array,propdf, numerical ) original_shape = vox.shape #interpolate to upsample resized = imresize(vox , [scaling[i]*dim for i,dim in enumerate(vox.shape)] ) #smooth to get rid of the hard edges voxfiltered = gaussian_filter( resized , sigma= sigma_filter) fft_vox = fourierNDarrayVoxels(voxfiltered) fft_original_shape, fft_corners = clip_fft_edge(fft_vox2) if saveout: pass #todsave the FFTs in numpy format else: yield fft_original_shape, original_shape , fft_corners , fft_vox if __name__ == '__main__': #propfile = './physicalpropTable.csv' , scaling = [ 4 , 4 , 4 ] , sigma_filter = .1 , saveout= False , keep_edge = [ 20, 115 ] parser=argparse.ArgumentParser() parser.add_argument('--aln', help='glob of alignment file to turn into 3D spectra',type = str) parser.add_argument('--proptable', help='properties of amino acids to use while generating the FFT',type = str) parser.add_argument('--keepedge', help='size of low freq range to keep' , type = str) parser.add_argument('--sigmafilter', help='name of the db', type = str) parser.add_argument('--scaling', help='preconfigured taxonomic ranges' , type = str) parser.add_argument('--nthreads', help='nthreads for multiprocessing' , type = int)
[ "pandas.read_csv", "scipy.ndimage.gaussian_filter", "numpy.zeros", "numpy.fft.rfftn", "Bio.AlignIO.read", "numpy.array" ]
[((288, 325), 'Bio.AlignIO.read', 'AlignIO.read', (['alnfile'], {'format': '"""fasta"""'}), "(alnfile, format='fasta')\n", (300, 325), False, 'from Bio import AlignIO\n'), ((4241, 4315), 'numpy.zeros', 'np.zeros', (['(2 * keep_edge[0], 2 * keep_edge[1], infft.shape[2])', 'np.complex'], {}), '((2 * keep_edge[0], 2 * keep_edge[1], infft.shape[2]), np.complex)\n', (4249, 4315), True, 'import numpy as np\n'), ((5604, 5640), 'numpy.zeros', 'np.zeros', (['original_shape', 'np.complex'], {}), '(original_shape, np.complex)\n', (5612, 5640), True, 'import numpy as np\n'), ((6700, 6736), 'numpy.zeros', 'np.zeros', (['original_shape', 'np.complex'], {}), '(original_shape, np.complex)\n', (6708, 6736), True, 'import numpy as np\n'), ((7988, 8009), 'pandas.read_csv', 'pd.read_csv', (['propfile'], {}), '(propfile)\n', (7999, 8009), True, 'import pandas as pd\n'), ((1099, 1139), 'numpy.zeros', 'np.zeros', (['align_array.shape'], {'dtype': 'float'}), '(align_array.shape, dtype=float)\n', (1107, 1139), True, 'import numpy as np\n'), ((7762, 7794), 'numpy.fft.rfftn', 'np.fft.rfftn', (['array'], {'s': 'clipSizes'}), '(array, s=clipSizes)\n', (7774, 7794), True, 'import numpy as np\n'), ((8782, 8819), 'Bio.AlignIO.read', 'AlignIO.read', (['alnfile'], {'format': '"""fasta"""'}), "(alnfile, format='fasta')\n", (8794, 8819), False, 'from Bio import AlignIO\n'), ((9194, 9238), 'scipy.ndimage.gaussian_filter', 'gaussian_filter', (['resized'], {'sigma': 'sigma_filter'}), '(resized, sigma=sigma_filter)\n', (9209, 9238), False, 'from scipy.ndimage import gaussian_filter\n'), ((2547, 2566), 'numpy.array', 'np.array', (['keep_edge'], {}), '(keep_edge)\n', (2555, 2566), True, 'import numpy as np\n')]
""" Deep learning toolkit """ import tensorflow as tf import keras from keras.models import Sequential from keras.layers import Dense from keras.optimizers import Adam import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import DataLoader from tensorboardX import SummaryWriter """ general toolkit """ import matplotlib.pyplot as plt import pandas as pd import numpy as np import os import socket import time import random import glob import argparse, json import pickle import networkx as nx from tqdm import tqdm # show a smart progress meter """ GNN toolkit """ import dgl from dgl.nn.pytorch import GraphConv """ IMPORTING CUSTOM MODULES/METHODS """ from data_test_case import case33_tieline, case33_tieline_DG from NN_model import DNN_TieLine, DNN_VarCon from nets.superpixels_graph_classification.load_net import gnn_model # import all GNNS from data.data import LoadData # import dataset """ ==================== Graph dataset preparation ================= """ # ====================== build a graph based on the system =============== # define the graph by the source nodes and destination nodes grid = case33_tieline() src = grid["line"][:, 1] - 1 # source nodes in array format dst = grid["line"][:, 2] - 1 # destination nodes in array format # Edges are directional in DGL; Make them bi-directional. u = np.concatenate([src, dst]) v = np.concatenate([dst, src]) # build graph using DGL g = dgl.DGLGraph((u, v)) print('We have %d nodes.' % g.number_of_nodes()) print('We have %d edges.' % g.number_of_edges()) # Since the actual graph is undirected, we convert it for visualization purpose. nx_G = g.to_networkx().to_undirected() # Kamada-Kawaii layout usually looks pretty for arbitrary graphs pos = nx.kamada_kawai_layout(nx_G) nx.draw(nx_G, pos, with_labels=True, node_color=[[.7, .7, .7]]) """ # ======================= add features to the nodes and edges ===================== """ dt = pd.read_csv("trajectory_BC__2021_01_05_14_36.csv", converters={'line': eval, 'load': eval, 'action': eval}) n_sample = dt.shape[0] feat_e = np.reshape(dt['line'].iloc[0], (1, 37)) feat_n = np.reshape(dt['load'].iloc[0], (1, 33)) # inverse one-hot encoding y = np.reshape(dt['action'].iloc[0].index(1), (1, 1)) # find the index of the one element as label for i in range(1, n_sample): feat_e = np.append(feat_e, np.reshape(dt['line'].iloc[i], (1, 37)), axis=0) feat_n = np.append(feat_n, np.reshape(dt['load'].iloc[i], (1, 33)), axis=0) y = np.append(y, np.reshape(dt['action'].iloc[i].index(1), (1, 1)), axis=0) feat_e = pd.DataFrame(feat_e) feat_n = pd.DataFrame(feat_n) """ ============== Define a graph convolutional neural networks ================= """ use_gpu = False; gpu_id = -1; device = None # CPU MODEL_NAME = 'GatedGCN' n_heads = -1 edge_feat = False pseudo_dim_MoNet = -1 kernel = -1 gnn_per_block = -1 embedding_dim = -1 pool_ratio = -1 n_mlp_GIN = -1 gated = False self_loop = False # self_loop = True max_time = 12 if MODEL_NAME == 'GatedGCN': seed = 41; epochs = 1000; batch_size = 5; init_lr = 5e-5; lr_reduce_factor = 0.5; lr_schedule_patience = 25; min_lr = 1e-6; weight_decay = 0 L = 4; hidden_dim = 70; out_dim = hidden_dim; dropout = 0.0; readout = 'mean' # generic new_params net_params = {} net_params['device'] = device net_params['gated'] = gated # for mlpnet baseline net_params['in_dim'] = feat_n.shape[0] # each node has three feature values representing the RGB net_params['in_dim_edge'] = feat_e.shape[0] # each node has one feature value representing the Euclidean length net_params['residual'] = True net_params['hidden_dim'] = hidden_dim net_params['out_dim'] = out_dim num_classes = len(np.unique(np.array(y))) net_params['n_classes'] = num_classes net_params['n_heads'] = n_heads net_params['L'] = L # min L should be 2 net_params['readout'] = "sum" net_params['layer_norm'] = True net_params['batch_norm'] = True net_params['in_feat_dropout'] = 0.0 net_params['dropout'] = 0.0 net_params['edge_feat'] = edge_feat net_params['self_loop'] = self_loop model = gnn_model(MODEL_NAME, net_params) """ =========================== Training ======================= """ # (1) Pytorch Dataset is based on Python typing.generic # (2) Pytorch DataLoader retrieve the data based on the index, that is, x[i] # (3) So, it is important to define __getitem__(self, index) so that DataLoader can retrieve the correct samples # (4) a Python iterator object must implement two special methods, __iter__() and __next__(), collectively called the iterator protocol from torch.utils.data import Dataset class torch_data_def(Dataset): def __init__(self, X, Y): self.X = X self.Y = Y def __getitem__(self, index): x, y = self.X[index], self.Y[index] return x, y, index def __len__(self): return len(self.X) # # ================= test code for the Pytorch Dataset and DataLoader =================== # X = np.array([[1, 2], [2, 3], [6, 7], [3, 5], [6, 9], [3, 5], [6, 7]]) # Y = np.array([[114], [203], [678], [345], [123], [423], [523]]) # # using both Dataset and DataLoader # torch_data = torch_data_def(X, Y) # a = DataLoader(torch_data, batch_size=2) # for batch_ndx, (x, y, idx) in enumerate(a): # print(batch_ndx) # print(x) # print(y) # print(idx) # # using only DataLoader # b = DataLoader(X, batch_size=2) # for batch_ndx, sample in enumerate(b): # print(batch_ndx) # print(sample) # # ================= test code for list =================== a = [1, 2, 3, 4, 5] for i in a: print(i) # # ================= create Pytorch DataLoader for training and testing data =================== # a = DataLoader(feat_e.to_numpy(), batch_size=1) # for batch_ndx, sample in enumerate(a): # print(sample) # train_loader = DataLoader(trainset, batch_size=params['batch_size'], shuffle=True, drop_last=drop_last, collate_fn=dataset.collate) # val_loader = DataLoader(valset, batch_size=params['batch_size'], shuffle=False, drop_last=drop_last, collate_fn=dataset.collate) # test_loader = DataLoader(testset, batch_size=params['batch_size'], shuffle=False, drop_last=drop_last, collate_fn=dataset.collate) # parameters params = {} params['seed'] = seed params['epochs'] = epochs params['batch_size'] = batch_size params['init_lr'] = init_lr params['lr_reduce_factor'] = lr_reduce_factor params['lr_schedule_patience'] = lr_schedule_patience params['min_lr'] = min_lr params['weight_decay'] = weight_decay params['print_epoch_interval'] = 5 params['max_time'] = max_time optimizer = optim.Adam(model.parameters(), lr=params['init_lr'], weight_decay=params['weight_decay']) # =============== begine training ============= model.train() epoch_loss = 0 epoch_train_acc = 0 nb_data = 0 gpu_mem = 0 # for iter, (batch_graphs, batch_labels) in enumerate(train_loader): # batch_x = batch_graphs.ndata['feat'].to(device) # num x feat # batch_e = batch_graphs.edata['feat'].to(device) # batch_labels = batch_labels.to(device) # optimizer.zero_grad() # # batch_scores = model.forward(batch_graphs, batch_x, batch_e) # loss = model.loss(batch_scores, batch_labels) # loss.backward() # optimizer.step() # epoch_loss += loss.detach().item() # epoch_train_acc += accuracy(batch_scores, batch_labels) # nb_data += batch_labels.size(0) # epoch_loss /= (iter + 1) # epoch_train_acc /= nb_data # model.eval() # epoch_test_loss = 0 # epoch_test_acc = 0 # nb_data = 0 # with torch.no_grad(): # for iter, (batch_graphs, batch_labels) in enumerate(data_loader): # batch_x = batch_graphs.ndata['feat'].to(device) # batch_e = batch_graphs.edata['feat'].to(device) # batch_labels = batch_labels.to(device) # # batch_scores = model.forward(batch_graphs, batch_x, batch_e) # loss = model.loss(batch_scores, batch_labels) # epoch_test_loss += loss.detach().item() # epoch_test_acc += accuracy(batch_scores, batch_labels) # nb_data += batch_labels.size(0) # epoch_test_loss /= (iter + 1) # epoch_test_acc /= nb_data
[ "pandas.DataFrame", "data_test_case.case33_tieline", "pandas.read_csv", "networkx.kamada_kawai_layout", "dgl.DGLGraph", "networkx.draw", "numpy.reshape", "numpy.array", "nets.superpixels_graph_classification.load_net.gnn_model", "numpy.concatenate" ]
[((1192, 1208), 'data_test_case.case33_tieline', 'case33_tieline', ([], {}), '()\n', (1206, 1208), False, 'from data_test_case import case33_tieline, case33_tieline_DG\n'), ((1400, 1426), 'numpy.concatenate', 'np.concatenate', (['[src, dst]'], {}), '([src, dst])\n', (1414, 1426), True, 'import numpy as np\n'), ((1431, 1457), 'numpy.concatenate', 'np.concatenate', (['[dst, src]'], {}), '([dst, src])\n', (1445, 1457), True, 'import numpy as np\n'), ((1487, 1507), 'dgl.DGLGraph', 'dgl.DGLGraph', (['(u, v)'], {}), '((u, v))\n', (1499, 1507), False, 'import dgl\n'), ((1798, 1826), 'networkx.kamada_kawai_layout', 'nx.kamada_kawai_layout', (['nx_G'], {}), '(nx_G)\n', (1820, 1826), True, 'import networkx as nx\n'), ((1827, 1893), 'networkx.draw', 'nx.draw', (['nx_G', 'pos'], {'with_labels': '(True)', 'node_color': '[[0.7, 0.7, 0.7]]'}), '(nx_G, pos, with_labels=True, node_color=[[0.7, 0.7, 0.7]])\n', (1834, 1893), True, 'import networkx as nx\n'), ((1989, 2100), 'pandas.read_csv', 'pd.read_csv', (['"""trajectory_BC__2021_01_05_14_36.csv"""'], {'converters': "{'line': eval, 'load': eval, 'action': eval}"}), "('trajectory_BC__2021_01_05_14_36.csv', converters={'line': eval,\n 'load': eval, 'action': eval})\n", (2000, 2100), True, 'import pandas as pd\n'), ((2129, 2168), 'numpy.reshape', 'np.reshape', (["dt['line'].iloc[0]", '(1, 37)'], {}), "(dt['line'].iloc[0], (1, 37))\n", (2139, 2168), True, 'import numpy as np\n'), ((2178, 2217), 'numpy.reshape', 'np.reshape', (["dt['load'].iloc[0]", '(1, 33)'], {}), "(dt['load'].iloc[0], (1, 33))\n", (2188, 2217), True, 'import numpy as np\n'), ((2622, 2642), 'pandas.DataFrame', 'pd.DataFrame', (['feat_e'], {}), '(feat_e)\n', (2634, 2642), True, 'import pandas as pd\n'), ((2652, 2672), 'pandas.DataFrame', 'pd.DataFrame', (['feat_n'], {}), '(feat_n)\n', (2664, 2672), True, 'import pandas as pd\n'), ((4158, 4191), 'nets.superpixels_graph_classification.load_net.gnn_model', 'gnn_model', (['MODEL_NAME', 'net_params'], {}), '(MODEL_NAME, net_params)\n', (4167, 4191), False, 'from nets.superpixels_graph_classification.load_net import gnn_model\n'), ((2404, 2443), 'numpy.reshape', 'np.reshape', (["dt['line'].iloc[i]", '(1, 37)'], {}), "(dt['line'].iloc[i], (1, 37))\n", (2414, 2443), True, 'import numpy as np\n'), ((2484, 2523), 'numpy.reshape', 'np.reshape', (["dt['load'].iloc[i]", '(1, 33)'], {}), "(dt['load'].iloc[i], (1, 33))\n", (2494, 2523), True, 'import numpy as np\n'), ((3794, 3805), 'numpy.array', 'np.array', (['y'], {}), '(y)\n', (3802, 3805), True, 'import numpy as np\n')]
print('__file__={0:<35} | __name__={1:<20} | __package__={2:<20}'.format(__file__,__name__,str(__package__))) # import thermotar as th from thermotar.utils import lmp_utils as lmu from thermotar.utils import parse_logs from thermotar.utils import df_utils import thermotar.thermo as th import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit class Dipoles(th.Thermo): '''Class is essentially the Thermo class, with extra methods for computing dielectric properties The constructor takes an input dataframe and returns the ''' _tauD = None _diel = None # def __init__(self,df): @classmethod def from_xvg(cls,*files,**kwargs): #create a list of data frames dfs = [parse_logs.parse_xvg(file,**kwargs) for file in files] #reorder dfs by number of rows, so longest duplicated is kept # TODO this has issues when the dataframes columns with the same name start with different values, such as different times # need to work out a way of stictching this together # #dfs.sort(key=lambda x : len(x.index),reverse=True) # joined_df = pd.concat(dfs,axis=1) # duped_names = joined_df.columns.duplicated() # dfs_indexed #drop duplicate columns # joined_df = joined_df.loc[:,~joined_df.columns.duplicated()] joined_df = df_utils.merge_no_dupes(*dfs) return Dipoles(joined_df) @property def tauD(self): if self._tauD is None: return self.relaxation_time()[0] else: return self._tauD @property def diel(self): if self._diel is None: return self.calc_epsilon() else: return self._diel def relaxation_time(self,t_start = 1, t_end = 20, t_name = 'Time',corr_name='C',n_exp=1,method = 'fit',all_params = False,p0=None): """ Find the debye relaxation time(s) (ps) and other fitting parameters """ t = self.data[t_name] C = self.data[corr_name] def exp_func(t,a,tau): return a*np.exp(-t/tau) select = np.logical_and(t > t_start, t<t_end) if not p0: p0 = (1,t_end-t_start) # if p0 is not initialised, set the guess to be the range of the fit fit,cov = curve_fit(exp_func,t[select],C[select],p0=p0) self._tauD = fit[1] self.tau_fit = fit if all_params: return fit, cov else: # to do make it return error return fit[1], cov[1][1]**0.5 def calc_epsilon(self, calc_method = 'auto', V=None, ave_lower = 0.90, ave_upper = 1.00, time_name = 'Time', epsilon_name='epsilon',M_fluc_name = 'Mfluc'): """ By default will calculate epsilon as the average of the last 10% of the epsilon column If epsilon is not defined as a dedicated column, can calculate from the fluctuation of the dipole moment can be manually specified """ # todo: move to a library for reuse in other modules def average_range(df, ave_lower,ave_upper): ll = df[time_name].max()*ave_lower ul = df[time_name].max()*ave_upper select = np.logical_and(df[time_name]> ll, df[time_name]<ul) return df[epsilon_name][select].mean() if calc_method == 'auto': try: eps = average_range(self.data,ave_lower,ave_upper) except IndexError: raise IndexError(f'No such column{epsilon_name}') return eps if __name__ == "__main__": rep1 = Dipoles.from_xvg('test_files/rep1/dipcorr.xvg','test_files/rep1/epsilon.xvg') tau = rep1.relaxation_time()[0] eps = rep1.diel eps = rep1.calc_epsilon() print(tau) print(eps) plt.plot(rep1.Time,rep1.C) plt.plot(rep1.Time,np.exp(-rep1.Time/tau)) plt.yscale('log') plt.show() plt.plot(rep1.Time,rep1.epsilon) plt.axhline(eps,c='red') plt.show() print(rep1.data.head())
[ "matplotlib.pyplot.axhline", "matplotlib.pyplot.yscale", "matplotlib.pyplot.show", "thermotar.utils.parse_logs.parse_xvg", "matplotlib.pyplot.plot", "numpy.logical_and", "scipy.optimize.curve_fit", "numpy.exp", "thermotar.utils.df_utils.merge_no_dupes" ]
[((3867, 3894), 'matplotlib.pyplot.plot', 'plt.plot', (['rep1.Time', 'rep1.C'], {}), '(rep1.Time, rep1.C)\n', (3875, 3894), True, 'import matplotlib.pyplot as plt\n'), ((3945, 3962), 'matplotlib.pyplot.yscale', 'plt.yscale', (['"""log"""'], {}), "('log')\n", (3955, 3962), True, 'import matplotlib.pyplot as plt\n'), ((3967, 3977), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3975, 3977), True, 'import matplotlib.pyplot as plt\n'), ((3983, 4016), 'matplotlib.pyplot.plot', 'plt.plot', (['rep1.Time', 'rep1.epsilon'], {}), '(rep1.Time, rep1.epsilon)\n', (3991, 4016), True, 'import matplotlib.pyplot as plt\n'), ((4020, 4045), 'matplotlib.pyplot.axhline', 'plt.axhline', (['eps'], {'c': '"""red"""'}), "(eps, c='red')\n", (4031, 4045), True, 'import matplotlib.pyplot as plt\n'), ((4049, 4059), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4057, 4059), True, 'import matplotlib.pyplot as plt\n'), ((1423, 1452), 'thermotar.utils.df_utils.merge_no_dupes', 'df_utils.merge_no_dupes', (['*dfs'], {}), '(*dfs)\n', (1446, 1452), False, 'from thermotar.utils import df_utils\n'), ((2176, 2214), 'numpy.logical_and', 'np.logical_and', (['(t > t_start)', '(t < t_end)'], {}), '(t > t_start, t < t_end)\n', (2190, 2214), True, 'import numpy as np\n'), ((2344, 2392), 'scipy.optimize.curve_fit', 'curve_fit', (['exp_func', 't[select]', 'C[select]'], {'p0': 'p0'}), '(exp_func, t[select], C[select], p0=p0)\n', (2353, 2392), False, 'from scipy.optimize import curve_fit\n'), ((3917, 3941), 'numpy.exp', 'np.exp', (['(-rep1.Time / tau)'], {}), '(-rep1.Time / tau)\n', (3923, 3941), True, 'import numpy as np\n'), ((786, 822), 'thermotar.utils.parse_logs.parse_xvg', 'parse_logs.parse_xvg', (['file'], {}), '(file, **kwargs)\n', (806, 822), False, 'from thermotar.utils import parse_logs\n'), ((3266, 3320), 'numpy.logical_and', 'np.logical_and', (['(df[time_name] > ll)', '(df[time_name] < ul)'], {}), '(df[time_name] > ll, df[time_name] < ul)\n', (3280, 3320), True, 'import numpy as np\n'), ((2143, 2159), 'numpy.exp', 'np.exp', (['(-t / tau)'], {}), '(-t / tau)\n', (2149, 2159), True, 'import numpy as np\n')]
import json import os from collections import OrderedDict import numpy as np class Datatransfer(object): """ The DataTransfer object contains information about datatransfers that happened between tasks. """ _version = "1.0" def __init__(self, id, type, ts_start, transfertime, source, destination, size, size_unit="B", events=None): if events is None: events = dict() self.id = id # An ID that identifies this data transfer self.type = type # Network in/out, local cp self.ts_submit = ts_start # Data transfer start time stamp, in milliseconds self.transfertime = max(transfertime, 0) # Data transfer time in milliseconds self.source = source # The ID of the source self.destination = destination # The ID of the destination self.size = size # The size of transferred data self.size_unit = size_unit # B(yte), KB, MB, GB, TB self.events = events # Dict with event time stamps, such as submitted, active, (pause), done , if known def get_json_dict(self): return { "id": self.id, "type": self.type, "ts_submit": self.ts_submit, "transfertime": self.transfertime, "source": self.source, "destination": self.destination, "size": self.size, "size_unit": self.size_unit, "events": self.events, "version": self._version, } @staticmethod def get_parquet_meta_dict(): type_info = { "id": np.int64, "type": np.str, "ts_submit": np.int64, "transfertime": np.int64, "source": np.int64, "destination": np.int64, "size": np.int64, "size_unit": np.str, "events": np.str, } ordered_dict = OrderedDict(sorted(type_info.items(), key=lambda t: t[0])) return ordered_dict def get_parquet_dict(self): return { "id": np.int64(self.id), "type": np.str(self.type), "ts_submit": np.int64(self.ts_submit), "transfertime": np.int64(self.transfertime), "source": np.int64(self.source), "destination": np.int64(self.destination), "size": np.int64(self.size), "size_unit": np.str(self.size_unit), "events": np.str(json.dumps(self.events)), } @staticmethod def versioned_dir_name(): return "schema-{}".format(Datatransfer._version) @staticmethod def output_path(): return os.path.join("datatransfers", Datatransfer.versioned_dir_name())
[ "numpy.str", "json.dumps", "numpy.int64" ]
[((2039, 2056), 'numpy.int64', 'np.int64', (['self.id'], {}), '(self.id)\n', (2047, 2056), True, 'import numpy as np\n'), ((2078, 2095), 'numpy.str', 'np.str', (['self.type'], {}), '(self.type)\n', (2084, 2095), True, 'import numpy as np\n'), ((2122, 2146), 'numpy.int64', 'np.int64', (['self.ts_submit'], {}), '(self.ts_submit)\n', (2130, 2146), True, 'import numpy as np\n'), ((2176, 2203), 'numpy.int64', 'np.int64', (['self.transfertime'], {}), '(self.transfertime)\n', (2184, 2203), True, 'import numpy as np\n'), ((2227, 2248), 'numpy.int64', 'np.int64', (['self.source'], {}), '(self.source)\n', (2235, 2248), True, 'import numpy as np\n'), ((2277, 2303), 'numpy.int64', 'np.int64', (['self.destination'], {}), '(self.destination)\n', (2285, 2303), True, 'import numpy as np\n'), ((2325, 2344), 'numpy.int64', 'np.int64', (['self.size'], {}), '(self.size)\n', (2333, 2344), True, 'import numpy as np\n'), ((2371, 2393), 'numpy.str', 'np.str', (['self.size_unit'], {}), '(self.size_unit)\n', (2377, 2393), True, 'import numpy as np\n'), ((2424, 2447), 'json.dumps', 'json.dumps', (['self.events'], {}), '(self.events)\n', (2434, 2447), False, 'import json\n')]
# Copyright (c) 2022, Skolkovo Institute of Science and Technology (Skoltech) # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Any from nptyping import NDArray import numpy as np import evops.metrics.constants from evops.utils.MetricsUtils import __get_tp, __filter_unsegmented def __precision( pred_labels: NDArray[Any, np.int32], gt_labels: NDArray[Any, np.int32], tp_condition: str, ) -> np.float64: true_positive = __get_tp(pred_labels, gt_labels, tp_condition) pred_labels = __filter_unsegmented(pred_labels) return true_positive / np.unique(pred_labels).size def __recall( pred_labels: NDArray[Any, np.int32], gt_labels: NDArray[Any, np.int32], tp_condition: str, ) -> np.float64: true_positive = __get_tp(pred_labels, gt_labels, tp_condition) gt_labels = __filter_unsegmented(gt_labels) return true_positive / np.unique(gt_labels).size def __fScore( pred_labels: NDArray[Any, np.int32], gt_labels: NDArray[Any, np.int32], tp_condition: str, ) -> np.float64: precision = __precision(pred_labels, gt_labels, tp_condition) recall = __recall(pred_labels, gt_labels, tp_condition) return 2 * precision * recall / (precision + recall)
[ "evops.utils.MetricsUtils.__filter_unsegmented", "evops.utils.MetricsUtils.__get_tp", "numpy.unique" ]
[((955, 1001), 'evops.utils.MetricsUtils.__get_tp', '__get_tp', (['pred_labels', 'gt_labels', 'tp_condition'], {}), '(pred_labels, gt_labels, tp_condition)\n', (963, 1001), False, 'from evops.utils.MetricsUtils import __get_tp, __filter_unsegmented\n'), ((1020, 1053), 'evops.utils.MetricsUtils.__filter_unsegmented', '__filter_unsegmented', (['pred_labels'], {}), '(pred_labels)\n', (1040, 1053), False, 'from evops.utils.MetricsUtils import __get_tp, __filter_unsegmented\n'), ((1266, 1312), 'evops.utils.MetricsUtils.__get_tp', '__get_tp', (['pred_labels', 'gt_labels', 'tp_condition'], {}), '(pred_labels, gt_labels, tp_condition)\n', (1274, 1312), False, 'from evops.utils.MetricsUtils import __get_tp, __filter_unsegmented\n'), ((1329, 1360), 'evops.utils.MetricsUtils.__filter_unsegmented', '__filter_unsegmented', (['gt_labels'], {}), '(gt_labels)\n', (1349, 1360), False, 'from evops.utils.MetricsUtils import __get_tp, __filter_unsegmented\n'), ((1082, 1104), 'numpy.unique', 'np.unique', (['pred_labels'], {}), '(pred_labels)\n', (1091, 1104), True, 'import numpy as np\n'), ((1389, 1409), 'numpy.unique', 'np.unique', (['gt_labels'], {}), '(gt_labels)\n', (1398, 1409), True, 'import numpy as np\n')]
import string from copy import deepcopy from shutil import copyfile from typing import List, Tuple, Dict, Optional import warnings import re import matplotlib import numpy as np import pandas as pd import seaborn as sns from adjustText import adjust_text from matplotlib import pyplot as plt from tqdm.auto import tqdm, trange from matplotlib.ticker import MaxNLocator, MultipleLocator from matplotlib.font_manager import FontProperties import adjustText import matplotlib.patches as mpatches import matplotlib.lines as mlines from titrato import closest_pka, hungarian_pka, align_pka, TitrationCurve from titrato import fit_titration_curves_3d from titrato.stats import ( absolute_loss, squared_loss, array_mae, array_rmse, wrap_pearsonr, bootstrapped_func, array_median_error, ) from .sampl import ( TitrationCurveType, SAMPL6DataProvider, bootstrap_rmse_r, bootstrap_pKa_dataframe, HaspKaType, TypeIPrediction, ) from .stats import ( area_between_curves, area_curve_vectorized, rmsd_curve_vectorized, BootstrapDistribution, ) from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes import logging from typing import List from uncertainties import ufloat import networkx as nx from networkx.drawing.nx_pydot import pydot_layout from collections import deque log = logging.getLogger() # Default styling sns.set_style("ticks") glob_font = {"size": 8} matplotlib.rc("font", **glob_font) matplotlib.rc("lines", **{"markersize": 4}) # Default colors per charge charge_colors = { -4: "#470911", -3: "#b2182b", -2: "#d6604d", -1: "#f4a582", 0: "#333333", 1: "#92c5de", 2: "#4393c3", 3: "#2166ac", 4: "#0d2844", } import os def to_str(num: ufloat): """Formats ufloat with one precision digit on the uncertainty and latex syntax""" return "{:.1uL}".format(num) class TexBlock: """Basic class for latex syntax block, to be added to report.""" tex_src = "" def __init__(self, **kwargs): self._variables = kwargs return def render_source(self): """Fill in all variable fields and return complete latex source.""" return self.tex_src.format(**self._variables) class ReportHeader(TexBlock): """Represents the preamble and document start.""" tex_src = ( "\\documentclass[9pt]{{standalone}}\n" "\\renewcommand{{\\familydefault}}{{\\sfdefault}}\n" "\\usepackage[utf8]{{inputenc}}\n" "\\usepackage{{graphicx}}\n" "\n\\begin{{document}}\n" ) # syntax for adding a new variable tex_var = "\\newcommand{{\\{}}}{{{}}}\n" def __init__(self, mol_id, method_names, img_ext="pdf"): """Initialize the header of the file by setting all appropriate variables""" variables = dict() variables["molid"] = mol_id variables["imgext"] = img_ext self.ids = list() # need to assign ascii name to method for use as tex variable for method, name in enumerate(method_names): id = string.ascii_lowercase[method] variables[f"method{id}"] = name # Keep track of ids defined in header self.ids.append(id) self._variables = variables def render_source(self): src = self.tex_src.format() for name, value in self._variables.items(): src += self.tex_var.format(name, value) return src class ReportFooter(TexBlock): tex_src = "\\end{{document}}\n" class OverviewRow(TexBlock): """Latex syntax provider for the overview section.""" tex_src = ( "\\section{{\\molid}}" "\n\\noindent \n" "\\begin{{minipage}}[s]{{0.35\\textwidth}}\\centering\n" "\\includegraphics[width=\\textwidth]{{Reports/\\molid-molecule.\\imgext}}\n" "\\end{{minipage}}\n" "\\begin{{minipage}}[s]{{0.35\\textwidth}}\n" "\\includegraphics[width=\\textwidth]{{Reports/overview-virtual-titration-\\molid.\\imgext}}\n" "\\end{{minipage}}\n" "\\begin{{minipage}}[s]{{0.23\\textwidth}}\n" "\\includegraphics[width=\\textwidth]{{Reports/overview-legend-\\molid.\\imgext}}\n" "\\end{{minipage}}\n" ) class MethodResultRow(TexBlock): """A row of figures for a single method""" tex_src = ( "\n\\begin{{minipage}}[s]{{\\textwidth}}\\centering\n" "{{\\textbf \\method{id}}}\n" "\\end{{minipage}}\n" "\n\\noindent\n" "\\begin{{minipage}}[s]{{0.33\\textwidth}}\\centering\n" "\\includegraphics[width=\\textwidth]{{Reports/\\method{id}-virtual-titration-\\molid.\\imgext}}\n" "\\end{{minipage}}\n" "\\begin{{minipage}}[s]{{0.33\\textwidth}}\n" "\\includegraphics[\\textwidth]{{Reports/\\method{id}-free-energy-\\molid.\\imgext}}\n" "\\end{{minipage}}\n" "\\begin{{minipage}}[s]{{0.33\\textwidth}}\n" "\\includegraphics[\\textwidth]{{Reports/\\method{id}-populations-\\molid.\\imgext}}\n" "\\end{{minipage}}\n" ) def __init__(self, id): """A row of figures for a single method. Parameters id - the 1-letter identifier for the method (a-z). """ self._variables = dict(id=id) class SAMPL6ReportGenerator: """This class provides an interface for generating analysis plots between experiment, and a prediction for a single molecule.""" # Assume pH values are spaced apart by 0.1 for any integration purposes. _dpH = 0.1 # Plotting defaults _figprops = { "dpi": 150, "figsize": (2.0, 2.0), # 3 figures fitting between 3 cm margins on letter paper "line_styles": ["-", "--", "-.", ":"], "line_widths": [0.75, 1.25, 1.25, 1.25], "colors_per_charge": charge_colors, # Use consistent colors for each method "extra_colors": sns.color_palette("dark"), } # Default number of bootstrap samples used to estimate titration curve confidence intervals num_bootstrap_curves = 10000 def __init__( self, mol_id: str, exp_provider: SAMPL6DataProvider, data_providers: List[SAMPL6DataProvider], mol_img_loc: str, ) -> None: """Instantiate the analysis from the identifier of the molecule, and providers of the data. Parameters ---------- mol_id - molecule associated with this report exp_provider - provider for the experimental data source prediction_provides - list of providers for all the predictions mol_png_loc - location where an image of the molecule can be found """ self._exp_provider = exp_provider self._prediction_providers = data_providers self._figures: Dict[str, Dict[str, matplotlib.figure.Figure]] = { pred.method_desc: dict() for pred in data_providers } # Add dict for overview figures self._figures["overview"] = dict() self._figures[exp_provider.method_desc] = dict() # Data tables by description, and latex format self._tables: Dict[str, str] = dict() # Latex Report document self._tex_source = "" self._num_predictions = len(data_providers) self._mol_id = mol_id self._mol_img = mol_img_loc return def _plot_charge_legend(self): """Generate a legend for all charges.""" fig, ax = self._newfig() for charge in range(-4, 5): color = self._figprops["colors_per_charge"][charge] ax.plot([0, 1], [0, 1], color=color, label=f"{charge:+d}") # Separate legend figure figlegend, axlegend = plt.subplots( 1, 1, figsize=[8, 0.5], dpi=self._figprops["dpi"] ) handles, labels = ax.get_legend_handles_labels() # handles = np.concatenate((handles[::2],handles[1::2]),axis=0) # labels = np.concatenate((labels[::2],labels[1::2]),axis=0) leg = figlegend.legend(handles, labels, loc="center", ncol=9) axlegend.get_xaxis().set_visible(False) axlegend.get_yaxis().set_visible(False) for spine in ["top", "left", "bottom", "right"]: axlegend.spines[spine].set_visible(False) self._figures["overview"]["charge-legend"] = figlegend plt.close(fig) def make_all_plots(self): """Make all available plots for each prediction and the experiment..""" # self._plot_virtual_titration_overview() self._plot_charge_legend() # overview plot self._plot_virtual_titration_overview() # Experiment gets its own plots # Virtual titration plot figtype = "virtual-titration" newfig = self.plot_virtual_titration(self._exp_provider) self._figures["Experiment"][figtype] = newfig # Free enery values figtype = "free-energy" newfig = self.plot_predicted_free_energy(self._exp_provider) self._figures["Experiment"][figtype] = newfig # Populations figtype = "populations" newfig = self.plot_predicted_population(self._exp_provider) self._figures["Experiment"][figtype] = newfig # Each method gets its own plots for p, pred_loader in enumerate(self._prediction_providers): desc = pred_loader.method_desc # Virtual titration plot figtype = "virtual-titration" newfig = self.plot_virtual_titration( self._exp_provider, pred_loader=pred_loader, index=p ) self._figures[desc][figtype] = newfig # Free enery values figtype = "free-energy" newfig = self.plot_predicted_free_energy(pred_loader) self._figures[desc][figtype] = newfig # Populations figtype = "populations" newfig = self.plot_predicted_population(pred_loader) self._figures[desc][figtype] = newfig def _plot_virtual_titration_overview(self): """Plot an overview of all methods using the virtual charge titration. Also stores a legend with color codes for each method, that can be used with other overview figures. """ # TODO fill in the new structure for experimental plots # Overview charge titration titration_fig_ax = self._newfig() for idx, pred in enumerate(self._prediction_providers, start=0): desc = pred.method_desc if pred.can_bootstrap: exp_data, exp_curves, exp_bootstrap_data = ( self._load_experiment_with_bootstrap() ) pred_data, bootstrap_data = pred.bootstrap( self._mol_id, self.num_bootstrap_curves ) pred_data.align_mean_charge(exp_data, area_between_curves, self._dpH) # Align all to experiment curve (note this is a joint bootstrap of experiment and prediction) curves = list() for dat, exp_dat in zip(bootstrap_data, exp_bootstrap_data): dat.align_mean_charge(exp_dat, area_between_curves, self._dpH) curves.append(deepcopy(dat.mean_charge)) curves = np.asarray(curves) self._add_virtual_titration_bootstrap_sd( titration_fig_ax, desc, pred_data, curves, idx, linestyle="-" ) # experiment plotted as dashed line self._add_virtual_titration_bootstrap_sd( titration_fig_ax, f"{desc}-exp", exp_data, exp_curves, idx, linestyle="--", alpha=0.5, ) else: exp_data = self._exp_provider.load(self._mol_id) pred_data = pred.load(self._mol_id) pred_data.align_mean_charge(exp_data, area_between_curves, self._dpH) curve = pred_data.mean_charge self._add_virtual_titration_bootstrap_sd( titration_fig_ax, desc, pred_data, np.asarray([curve]), idx ) # Unpack tuple. fig, ax = titration_fig_ax ax.set_title(f"{self._mol_id}", fontsize=9) # Integer labels for y axis ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # No labels on y axis, but indicate the integer values with ticks # labels = [item.get_text() for item in ax.get_yticklabels()] # empty_string_labels = [""] * len(labels) # ax.set_yticklabels(empty_string_labels) ax.set_ylabel(r"$Q_\mathsf{avg}$") ax.set_xlabel("pH") # x-tick every 2 pH units ax.set_xticks(np.arange(2.0, 14.0, 2.0)) # remove top and right spines sns.despine() # fit everything within bounds fig.tight_layout() # Separate legend figure figlegend, axlegend = self._newfig() leg = figlegend.legend(*ax.get_legend_handles_labels(), loc="center") axlegend.get_xaxis().set_visible(False) axlegend.get_yaxis().set_visible(False) for spine in ["top", "left", "bottom", "right"]: axlegend.spines[spine].set_visible(False) self._figures["overview"]["virtual-titration"] = fig self._figures["overview"]["legend"] = figlegend def _load_experiment_with_bootstrap(self): # All methods tested against the same experimental values. exp_data = self._exp_provider.load(self._mol_id) if self._exp_provider.can_bootstrap: exp_data, exp_bootstrap_data = self._exp_provider.bootstrap( self._mol_id, self.num_bootstrap_curves ) # Virtual titration curves exp_curves = np.asarray([curve.mean_charge for curve in exp_bootstrap_data]) return exp_data, exp_curves, exp_bootstrap_data def save_all(self, dir: str, ext="pdf"): """Save all figures. Parameters ---------- dir - output directory for all files ext - Extension of the images. """ if not os.path.isdir(dir): os.makedirs(dir) for desc, method in self._figures.items(): for figtype, figure in method.items(): figure.savefig( os.path.join(dir, f"{desc}-{figtype}-{self._mol_id}.{ext}") ) copyfile(self._mol_img, os.path.join(dir, f"{self._mol_id}-molecule.{ext}")) with open(os.path.join(dir, f"report-{self._mol_id}.tex"), "w") as latexfile: latexfile.write(self._tex_source) def generate_latex(self, img_ext="pdf") -> None: """Make a minipage latex document layout containing figures""" blocks: List[TexBlock] = list() header = ReportHeader( self._mol_id, [ meth.method_desc for meth in [self._exp_provider] + self._prediction_providers ], img_ext=img_ext, ) blocks.append(header) blocks.append(OverviewRow()) for id in header.ids: blocks.append(MethodResultRow(id)) blocks.append(ReportFooter()) for block in blocks: self._tex_source += block.render_source() def close(self) -> None: """Close all figures contained within this reporter to save memory.""" for desc, method in self._figures.items(): for figtype, figure in method.items(): plt.close(figure) return @classmethod def _newfig(cls) -> Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]: # Ensure style before starting figure sns.set_style("ticks") font = {"size": 11} matplotlib.rc("font", **font) return plt.subplots( 1, 1, figsize=cls._figprops["figsize"], dpi=cls._figprops["dpi"] ) @classmethod def _add_virtual_titration_bootstrap_sd( cls, fig_ax: Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes], label: str, curve: TitrationCurveType, bootstrap_curves: np.ndarray, color_idx: int, perc: float = 5, fill=False, linestyle="-", alpha=1.0, ) -> None: """Plot the estimate and 2 standard deviations from a bootstrap set in existing fig and axes. Parameters ---------- fig_ax - figure and corresponding axes to add lines to label - label for plot, used for legend curve - TitrationCurve object containing the mean, and the pH values bootstrap_curves - 2D array of floats, bootstrap titration curves, with the 0 axis being the different curves, and the 1 axis the pH values. ph_values - 1d array the ph values that each point corresponds to. color_idx - integer index for picking color from class array `extra_colors` perc - percentile, and 100-percentile to plot default 5, so 5th and 95th are plotted. fill - fill the area between percentiles with color. """ color = cls._figprops["extra_colors"][color_idx] std = np.std(bootstrap_curves, axis=0) ph_values = curve.ph_values mean = curve.mean_charge # Unpack tuple fig, ax = fig_ax ax.plot( ph_values, mean, linestyle, linewidth=0.75, color=color, alpha=alpha, label=label, ) ax.plot( ph_values, mean + (2 * std), ":", linewidth=0.75, color=color, alpha=0.5 * alpha, ) ax.plot( ph_values, mean - (2 * std), ":", linewidth=0.75, color=color, alpha=0.5 * alpha, ) if fill: ax.fill_between( ph_values, mean - (2 * std), mean + (2 * std), facecolor=color, alpha=0.1, ) return def plot_virtual_titration( self, exp_loader: SAMPL6DataProvider, pred_loader: Optional[SAMPL6DataProvider] = None, fig_ax: Optional[Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]] = None, index: int = None, ): """Plot titration curve using the mean charge.""" if fig_ax is None: fig, ax = self._newfig() else: fig, ax = fig_ax # Experiment a black dotted curve, prediction is black solid exp_data = deepcopy(exp_loader.load(self._mol_id)) if pred_loader is None: ls = 0 else: pred_data = deepcopy(pred_loader.load(self._mol_id)) ls = 1 exp_data.align_mean_charge(pred_data, area_between_curves, self._dpH) area = area_between_curves( pred_data.mean_charge, exp_data.mean_charge, self._dpH ) ax.plot( exp_data.ph_values, exp_data.mean_charge, color="#333333", ls=self._figprops["line_styles"][3], ) if pred_loader is not None: ax.plot( pred_data.ph_values, pred_data.mean_charge, color="#333333", ls=self._figprops["line_styles"][0], ) # Area between curves is colored in gray ax.fill_between( pred_data.ph_values, exp_data.mean_charge, pred_data.mean_charge, facecolor=self._figprops["extra_colors"][index], interpolate=True, alpha=0.7, ) ax.set_title(r"$\Delta$ area : {:.2f}".format(area)) # Integer labels for y axis ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # ensure at least one integer unit of charge on axis + .1 for spacing ymin, ymax = ax.get_ylim() round_min = round(ymin) - 0.05 round_max = round(ymax) + 0.05 if ymax < round_max: ymax = round_max if ymin > round_min: ymin = round_min ax.set_ylim([ymin, ymax]) # WITH labels on y axis, but indicate the integer values with ticks labels = [item.get_text() for item in ax.get_yticklabels()] # empty_string_labels = [""] * len(labels) # ax.set_yticklabels(empty_string_labels) ax.set_ylabel(r"$Q_\mathsf{avg}$") ax.set_xlabel("pH") # x-tick every 2 pH units ax.set_xticks(np.arange(2.0, 14.0, 2.0)) # remove top and right spines sns.despine() # fit everything within bounds fig.tight_layout() return fig def plot_predicted_free_energy( self, pred_loader: SAMPL6DataProvider ) -> matplotlib.figure.Figure: """Plot titration curve using free energies.""" # colored by number of protons bound fig, ax = self._newfig() pred_data = pred_loader.load(self._mol_id) for i, state_id in enumerate(pred_data.state_ids): charge = pred_data.charges[i] color = self._figprops["colors_per_charge"][charge] # neutral on top zorder = 10 - abs(charge) ls = 0 ax.plot( pred_data.ph_values, pred_data.free_energies[i], ls=self._figprops["line_styles"][ls], color=color, label="n={}".format(charge), zorder=zorder, ) ax.set_ylabel(r"Free energy ($k_B T$)") ax.set_xlabel("pH") ax.set_xticks(np.arange(2.0, 14.0, 2.0)) # remove top and right spines sns.despine(ax=ax) # fit everything within bounds fig.tight_layout() return fig def plot_predicted_population( self, pred_loader: TitrationCurveType ) -> matplotlib.figure.Figure: """Plot titration TitrationCurve using free energies.""" # colored by number of protons bound pred_data = pred_loader.load(self._mol_id) fig, ax = self._newfig() for i, state_id in enumerate(pred_data.state_ids): charge = pred_data.charges[i] color = self._figprops["colors_per_charge"][charge] linestyle = 0 # Neutral on top zorder = 10 - abs(charge) ax.plot( pred_data.ph_values, pred_data.populations[i], ls=self._figprops["line_styles"][linestyle], color=color, label="n={}".format(charge), zorder=zorder, ) ax.yaxis.set_major_locator(MaxNLocator(integer=True)) ax.set_ylim([-0.05, 1.05]) labels = [item.get_text() for item in ax.get_yticklabels()] empty_string_labels = [""] * len(labels) ax.set_yticklabels(empty_string_labels) ax.set_ylabel("Population") ax.set_xlabel("pH") ax.set_xticks(np.arange(2.0, 14.0, 2.0)) # remove top and right spines sns.despine(ax=ax) # fit everything within bounds fig.tight_layout() return fig def plot_experimental_free_energy( self, exp_loader: SAMPL6DataProvider ) -> matplotlib.figure.Figure: # colored by number of protons bound fig, ax = self._newfig() exp_data = exp_loader.load(self._mol_id) for i, state_id in enumerate(exp_data.state_ids): nbound = exp_data.charges[i] color = self._figprops["colors_per_charge"][nbound] if nbound == 0: zorder = 10 else: zorder = 2 ax.plot( exp_data.ph_values, exp_data.free_energies[i], ls=self._figprops["line_styles"][0], color=color, label="n={}".format(nbound), ) ax.set_ylabel(r"Free energy ($k_B T$)") ax.set_xlabel("pH") ax.set_xticks(np.arange(2.0, 14.0, 2.0)) # remove top and right spines sns.despine(ax=ax) # fit everything within bounds fig.tight_layout() return fig def get_percentiles(array, percentiles): nums = list() for q in percentiles: nums.append(np.percentile(array, q, axis=0)) return nums def plot_quantiles( curves: np.ndarray, ph_range: np.ndarray, color: str, perc: float = 5, fill=True ): """Plot the median, and outer percentiles. Parameters ---------- curves - 2D array of bootstrap titration curves, with the 0 axis being the different curves, anx the 1 axis the pH values. ph_range - the ph values that each point corresponds to. color - a matplotlib color for the elements in the plot perc - percentile, and 100-percentile to plot default 5, so 5th and 95th are plotted. fill - fill the area between percentiles with color. """ quantiles = get_percentiles(curves, [50.0, perc, 100.0 - perc]) plt.plot(ph_range, quantiles[0], "-", color=color, alpha=1.0, label="median") plt.plot( ph_range, quantiles[1], ":", color=color, alpha=1.0, label="{:.0f}th/{:.0f}th percentile".format(perc, 100 - perc), ) plt.plot(ph_range, quantiles[2], ":", color=color, alpha=1.0) if fill: plt.fill_between( ph_range, quantiles[2], quantiles[1], facecolor=color, alpha=0.1 ) def plot_mean_twosigma(curves: np.ndarray, ph_range: np.ndarray, color: str, fill=True): """Plot the mean, plus/minus 2 sigma. Parameters ---------- curves - 2D array of bootstrap titration curves, with the 0 axis being the different curves, anx the 1 axis the pH values. ph_range - the ph values that each point corresponds to. color - a matplotlib color for the elements in the plot fill - fill the area between +/- 2 sigma with color. """ mean = np.mean(curves, axis=0) std = np.std(curves, axis=0) plt.plot(ph_range, mean, "-", color=color, label="mean") plt.plot( ph_range, mean + 2 * std, ":", alpha=1.0, color=color, label=r"$\pm$2$\sigma$" ) plt.plot(ph_range, mean - 2 * std, ":", alpha=1.0, color=color) if fill: plt.fill_between( ph_range, mean + 2 * std, mean - 2 * std, facecolor=color, alpha=0.1 ) def plot_subset(curves, ph_range, n_choices: int, color="gray", alpha=0.1): """Plot a subset of bootstrap samples. Parameters ---------- curves - 2D array of bootstrap titration curves, with the 0 axis being the different curves, anx the 1 axis the pH values. ph_range - the ph values that each point corresponds to. n_choices - number of samples to plot color - a matplotlib color for the elements in the plot alpha - transparency of the curves. """ choices = np.random.choice(curves.shape[0], n_choices, replace=False) for i in choices: plt.plot(ph_range, curves[i], "-", color=color, zorder=0, alpha=alpha) def plot_correlation_analysis( dataframe: pd.DataFrame, xlabel: str, ylabel: str, title: str, color: str, marker: str, error_color="black", facecolor="none", shaded=True, insets=True, ): """Plot correlation between experiment and prediction. Parameters ---------- dataframe - a typeI/typeIII pKa dataframe Has columns "Experimental" , "Experimental SEM" ,"Predicted", and "Predicted SEM" title - to put above plot. use '' (empty string) for no title. color - edge color of the markers. This plot uses open markers. error_color - color of the error bars facecolor - color of the face of markers """ # plt.clf() fig = plt.figure(figsize=[2.5, 2.5], dpi=150) ax = plt.gca() ax.set_title(title, fontsize=9) # If possible at least show 0, 14 but allow for larger axes limit_axes = True if ( np.any(0 > dataframe["pKa Method1"]) or np.any(16.0 < dataframe["pKa Method1"]) or np.any(0 > dataframe["pKa Method2"]) or np.any(16.0 < dataframe["pKa Method2"]) ): limit_axes = False ax.errorbar( dataframe["pKa Method1"], dataframe["pKa Method2"], xerr=dataframe["pKa SEM Method1"], yerr=dataframe["pKa SEM Method2"], fmt="none", color=error_color, alpha=0.8, linewidth=0.5, zorder=1, ) ax.scatter( dataframe["pKa Method1"], dataframe["pKa Method2"], marker=marker, color=color, facecolors=facecolor, edgecolors=color, alpha=0.8, linewidth=0.7, zorder=0, ) texts = [] for r, row in dataframe.iterrows(): if abs(row.Delta) > 2: texts.append( ax.text( row["pKa Method1"], row["pKa Method2"], row.Molecule, va="center", ha="center", fontsize=8, zorder=2, ) ) adjust_text(texts, arrowprops=dict(arrowstyle="->", color="black", zorder=2)) ax.set_ylabel(ylabel, fontsize=8) ax.set_xlabel(xlabel, fontsize=8) # enforce limits before linear parts a plotted xlim = ax.get_xlim() ylim = ax.get_ylim() lims = [min([xlim[0], ylim[0]]), max([xlim[1], ylim[1]])] ax.set_xlim(lims) ax.set_ylim(lims) ax.xaxis.set_major_locator(MultipleLocator(2.0)) ax.yaxis.set_major_locator(MultipleLocator(2.0)) if limit_axes: ax.set_xlim([0, 16]) ax.set_ylim([0, 16]) plt.tight_layout() sns.despine(fig) # Add linear guides for 1 and 2 pK unit deviation ax.plot((-50.0, 50.0), (-50.0, 50.0), "k", zorder=-1, linewidth=0.5, alpha=0.5) ax.plot( (-52.0, 48.0), (-50.0, 50.0), "gray", linestyle="--", zorder=-1, linewidth=0.5, alpha=0.5, ) ax.plot( (-48.0, 52.0), (-50.0, 50.0), "gray", linestyle="--", zorder=-1, linewidth=0.5, alpha=0.5, ) if shaded: ax.fill_between( [-50.0, 50.0], [-51.0, 49.0], [-49.0, 51.0], color="gray", alpha=0.1 ) return fig, ax class FullpKaComparison: """Compile a full report of pKa mapping analysis across all of the SAMPL6 pKa molecules.""" _loss_functions = {"square": squared_loss} _correlation_metrics = { "RMSE": array_rmse, "Mean abs. error": array_mae, r"pearson $\rho$": wrap_pearsonr, "Median abs. error": array_median_error, } # algorithms per data type _mapping_algorithms = dict( typeiii={ "closest": closest_pka, "hungarian": hungarian_pka, "align": align_pka, }, typei={"closest": closest_pka, "hungarian": hungarian_pka}, exp={"closest": closest_pka, "hungarian": hungarian_pka, "align": align_pka}, typeimacro={ "closest": closest_pka, "hungarian": hungarian_pka, "align": align_pka, }, ) def __init__( self, exp_provider: SAMPL6DataProvider, data_providers: List[SAMPL6DataProvider], included_molecules: Optional[List[str]] = None, n_bootstrap_correlation=5000, ): """Compile a full report of pKa mapping analysis across all of the SAMPL6 pKa molecules.""" # TODO this is commented out for debugging, please put check back in in final version. # if "exp" != exp_provider.data_type: # raise TypeError("Need an experimental provider as data type") self._exp_provider = exp_provider self._providers = data_providers # Take all the sampl6 molecules by default if no names provided self.included_molecules = ( ["SM{:02d}".format(molecule + 1) for molecule in range(24)] if included_molecules is None else included_molecules ) self._pka_data = pd.DataFrame() self._correlation_df = pd.DataFrame() for provider in self._providers: if provider.data_type == "exp": warnings.warn( "An experiment was provided as a prediction.", UserWarning ) # number of samples for correlation bootstrap analysis self._n_bootstrap_correlation = n_bootstrap_correlation def analyze_all(self): """Calculate all possible pKa mappings es for all molecules and methods""" all_providers: List[SAMPL6DataProvider] = [self._exp_provider] + self._providers pbar1 = tqdm(all_providers, desc="Dataset", unit="data set") for provider1 in pbar1: pbar2 = tqdm(all_providers, desc="Dataset2", unit="data set", leave=False) for provider2 in pbar2: if provider1 == provider2: continue pkamap = self._perform_pka_maps(provider1, provider2) self._pka_data = self._pka_data.append( pkamap, ignore_index=True, sort=False ) self._correlation_df = self._calculate_correlations() @staticmethod def _extract_pka_df(titrationcurve: HaspKaType) -> pd.DataFrame: """Extract pKa values and standard errors from a TitrationCurve class that has pKa values.""" return pd.DataFrame({"pKa": titrationcurve.pkas, "SEM": titrationcurve.sems}) def _perform_pka_maps( self, provider1: SAMPL6DataProvider, provider2: SAMPL6DataProvider ): full_df = pd.DataFrame() for mol in tqdm( self.included_molecules, desc="pKa maps", unit="molecules", leave=False ): exp = provider1.load(mol) comp = provider2.load(mol) exp_pka = self._extract_pka_df(exp) comp_pka = self._extract_pka_df(comp) # name, function for alg, f in self._mapping_algorithms[provider2.data_type].items(): # name, function if alg not in self._mapping_algorithms[provider1.data_type]: continue for loss, l in self._loss_functions.items(): row_df = f(exp_pka, comp_pka, l) row_df["Algorithm"] = alg row_df["Loss function"] = loss row_df["Molecule"] = mol row_df["Type1"] = provider1.data_type row_df["Method1"] = provider1.label row_df["Method2"] = provider2.label row_df["Type2"] = provider2.data_type full_df = full_df.append(row_df, ignore_index=True, sort=False) # Patch dataframe column names # Default labels first method as experiment and second as prediction full_df = full_df.rename( columns={ "Experimental": "pKa Method1", "Experimental SEM": "pKa SEM Method1", "Predicted": "pKa Method2", "Predicted SEM": "pKa SEM Method2", } ) full_df["Delta"] = full_df.apply( lambda row: ( ufloat(row["pKa Method2"], row["pKa SEM Method2"]) - ufloat(row["pKa Method1"], row["pKa SEM Method1"]) ), axis=1, ) return full_df def _calculate_correlations(self): """Calculate correlation metrics from pKa mapping dataframes using bootstrap analysis.""" # name correlation_df = pd.DataFrame() nonan = self._pka_data.dropna() for (method1, method2, algorithm, loss), group in tqdm( nonan.groupby(["Method1", "Method2", "Algorithm", "Loss function"]), desc="Comparison", leave=True, ): samples = [] for i in trange( self._n_bootstrap_correlation, desc="Bootstrap", unit="sample", leave=False, ): # Draw new dataframe by bootstrapping over rows bootstrap_df = bootstrap_pKa_dataframe(group) pkas1 = bootstrap_df["pKa Method1"] pkas2 = bootstrap_df["pKa Method2"] samples.append([pkas1, pkas2]) for metric, m in self._correlation_metrics.items(): estimate = m(group["pKa Method1"], group["pKa Method2"]) bootstrap_estimates = [m(meth1, meth2) for meth1, meth2 in samples] correlation_df = correlation_df.append( { "Algorithm": algorithm, "Metric": metric, "Method1": method1, "Method2": method2, "Loss function": loss, "Value": BootstrapDistribution( estimate, np.asarray(bootstrap_estimates) ), }, ignore_index=True, sort=False, ) return correlation_df def plot_correlation(self): """Make plot of computed versus measured pKa values.""" figures = dict() pal = sns.color_palette("dark") labels = [prov.label for prov in self._providers] nonan = self._pka_data.dropna() for (method1, method2, algorithm, loss), group in tqdm( nonan.groupby(["Method1", "Method2", "Algorithm", "Loss function"]), desc="Comparison", leave=True, ): if method1 == "Experiment" and method2 != "Experiment": facecolor = pal[labels.index(method2)] elif method2 == "Experiment" and method1 != "Experiment": facecolor = pal[labels.index(method1)] else: facecolor = "black" fig, ax = plot_correlation_analysis( group, method1 + " pKa", method2 + " pKa", "", "gray", "s", "gray", facecolor=facecolor, ) figures[(method1, method2, algorithm, loss)] = fig return figures def plot_distribution(self, algorithm): """Make plot of deltas between computed versus measured pKa values.""" jointfig, jointax = plt.subplots(1, 1, figsize=(2.5, 2.5), dpi=150) figures = dict() pal = sns.color_palette("dark") labels = [prov.label for prov in self._providers] nonan = self._pka_data.dropna() for (method1, method2, algo, loss), group in tqdm( nonan.groupby(["Method1", "Method2", "Algorithm", "Loss function"]), desc="Comparison", leave=True, ): if algo != algorithm: continue if method1 == "Experiment" and method2 != "Experiment": color = pal[labels.index(method2)] elif method2 == "Experiment" and method1 != "Experiment": color = pal[labels.index(method1)] else: color = "black" fig, ax = plt.subplots(1, 1, figsize=(2.5, 2.5), dpi=150) delta = group.Delta.apply(lambda val: val.nominal_value) sns.distplot( delta, hist=False, rug=True, kde_kws={"shade": True}, color=color, ax=ax ) ylims = ax.get_ylim() xlims = ax.get_xlim() if xlims[0] > -5.5 and xlims[1] < 5.5: ax.set_xlim([-5, 5]) texts = [] for r, row in group.iterrows(): if abs(row.Delta) > 2: texts.append( ax.text( row.Delta.nominal_value, 0.1 * ylims[1], row.Molecule, va="center", ha="center", fontsize=8, zorder=2, ) ) adjust_text(texts) if method1 == "Experiment": sns.distplot( delta, hist=False, rug=False, color=color, ax=jointax, label=f"{method2}", ) plt.axvline(np.median(delta), lw=1, color="black") # Every 0.5 add a tick ax.xaxis.set_major_locator(MultipleLocator(1.0)) plt.xlabel(rf"$pKa$ {method2} - $pKa$ {method1}") plt.yticks([]) plt.tight_layout() sns.despine(left=True) figures[(algorithm, (method1, method2))] = fig jointax.set_yticks([]) jointax.xaxis.set_major_locator(MultipleLocator(1.0)) jointax.legend(fontsize=8) jointax.set_xlabel(r"$pKa$ computed - $pKa$ experiment") jointxlims = jointax.get_xlim() if jointxlims[0] > -5.5 and jointxlims[1] < 5.5: jointax.set_xlim([-5, 5]) sns.despine(ax=jointax, left=True) jointfig.tight_layout() figures[(algorithm, ("overview", ""))] = jointfig return figures def table_pka(self, algorithm): """Produce pKa table for a particular algorithm.""" df = self._pka_data.dropna() df = df[(df.Method1 == "Experiment") & (df.Algorithm == algorithm)] labels = [prov.label for prov in self._providers] observed_labels = [] table = None for label in labels: subset = df[df.Method2 == label] if subset.size == 0: continue observed_labels.append(label) if table is None: table = subset[["Molecule", "pKa Method1", "pKa SEM Method1"]] newset = subset[ [ "Molecule", "pKa Method1", "pKa SEM Method1", "pKa Method2", "pKa SEM Method2", "Delta", ] ] table = table.merge( newset, on=["Molecule", "pKa Method1", "pKa SEM Method1"] ) table[label] = table.apply( lambda row: ufloat(row["pKa Method2"], row["pKa SEM Method2"]), axis=1 ) table = table.rename(columns={"Delta": label + " Delta"}) table = table.drop(columns=["pKa Method2", "pKa SEM Method2"]) table["Experiment"] = table.apply( lambda row: ufloat(row["pKa Method1"], row["pKa SEM Method1"]), axis=1 ) delta_in_order = [l + " Delta" for l in observed_labels] cols = [ label for pair in zip(observed_labels, delta_in_order) for label in pair ] cols.insert(0, "Experiment") for col in cols: table[col] = table[col].apply(to_str) table = table[["Molecule", *cols]] # table = table.rename(columns={"Molecule": "{Molecule}"}) # Column names need to be wrapped for siunitx table table.columns = [f"{{{col}}}" for col in table.columns] tex_syntax = table.to_latex(escape=False, index=False) # regex grabs the line with specification of column types colspec_finder = r"\\begin{tabular}{.*}\n" # Exp has two decimals on the uncertainty and one sig digit exp_col_type = "S[table-format=-1.2,table-figures-uncertainty=1]" # Prediction typically has only one decimal on the uncertainty pred_col_type = "S[table-format=-1.1,table-figures-uncertainty=1]" tex_syntax = re.sub( colspec_finder, f"\\\\begin{{tabular}}{{c{exp_col_type}{(len(df.columns)-1) * pred_col_type}}}", tex_syntax, 0, ) tex_table = ( "\\sisetup{separate-uncertainty=true}\n" "\\begin{table}\n" "\\centering\n" f"{tex_syntax}" "\\end{table}\n" ) return tex_table def table_correlations(self, algorithm): """Return overall correlation/error statistics for pKa comparison.""" selection = (self._correlation_df["Method1"] == "Experiment") & ( self._correlation_df["Algorithm"] == algorithm ) subset = self._correlation_df[selection] subset = subset.rename(columns={"Method2": "Method"}) return subset[["Method", "Metric", "Value"]].to_latex(index=True, escape=False) class TitrationComparison: """Compile a full report of titration curve analysis across all of the SAMPL6 pKa molecules.""" _curve_metrics = {"area": area_curve_vectorized, "rmsd": rmsd_curve_vectorized} # default interval between pH _dpH = 0.1 def __init__( self, exp_provider: SAMPL6DataProvider, data_providers: List[SAMPL6DataProvider], included_molecules: Optional[List[str]] = None, n_bootstrap_titration=100, ): """Compile a full report of pKa mapping analysis across all of the SAMPL6 pKa molecules.""" if "exp" != exp_provider.data_type: raise TypeError("Need an experimental provider as data type") self._exp_provider = exp_provider self._providers = data_providers # Take all the sampl6 molecules by default if no names provided self.included_molecules = ( ["SM{:02d}".format(molecule + 1) for molecule in range(24)] if included_molecules is None else included_molecules ) self._curve_df = pd.DataFrame() self._exp_data = dict() self._raw_curves = dict() for provider in self._providers: if provider.data_type == "exp": warnings.warn( "An experiment was provided as a prediction.", UserWarning ) self._n_bootstrap_titration = n_bootstrap_titration def analyze_all(self): """Calculate all possible pKa mappings, and all area between curves for all molecules and methods""" pbar = tqdm(self._providers, desc="Dataset", unit="data set") for provider in pbar: pbar.set_description(desc=provider.method_desc, refresh=True) self._curve_df = self._curve_df.append( self._compare_titration_curves(self._exp_provider, provider), ignore_index=True, sort=False, ) pbar.set_description(desc="Done.", refresh=True) def _compare_titration_curves( self, exp_provider: SAMPL6DataProvider, computed_provider: SAMPL6DataProvider ): """Calculate deviation between all titration curves.""" full_df = pd.DataFrame() for mol in tqdm( self.included_molecules, desc="Titration", unit="molecule", leave=False ): log.debug(mol) if computed_provider.can_bootstrap: if mol not in self._exp_data: exp_data, exp_bootstrap_data = exp_provider.bootstrap( mol, self._n_bootstrap_titration ) self._exp_data[mol] = (exp_data, exp_bootstrap_data) else: exp_data, exp_bootstrap_data = self._exp_data[mol] # move the movable curve to be as close to the target as possible, as estimated by area # Virtual titration curves pred_data, bootstrap_data = computed_provider.bootstrap( mol, self._n_bootstrap_titration ) exp_curves = np.asarray( [curve.mean_charge for curve in exp_bootstrap_data] ) pred_curves = np.asarray( [curve.mean_charge for curve in bootstrap_data] ) exp_curves = np.vstack([exp_curves, exp_data.mean_charge]) pred_curves = np.vstack([pred_curves, pred_data.mean_charge]) for metric, m in tqdm( self._curve_metrics.items(), desc="Delta", unit="metric", leave=False, ): log.debug(metric) q_curves_pred, q_curves_exp_fit, scores = fit_titration_curves_3d( pred_curves, exp_curves, m, self._dpH ) self._raw_curves[(computed_provider.method_desc, mol, metric)] = ( q_curves_pred, q_curves_exp_fit, scores, pred_data.ph_values, ) dist = BootstrapDistribution( np.asscalar(scores[-1]), scores[:-1].squeeze() ) full_df = full_df.append( dict( Molecule=mol, Metric=metric, Value=dist, Method=computed_provider.method_desc, Type=computed_provider.data_type, ), ignore_index=True, sort=False, ) else: for metric, m in tqdm( self._curve_metrics.items(), desc="Delta", unit="metric", leave=False, ): log.debug(metric) exp_data = exp_provider.load(mol) pred_data = computed_provider.load(mol) exp_data.align_mean_charge(pred_data, m, self._dpH) dev = np.asscalar( m( pred_data.mean_charge[:, np.newaxis].T, exp_data.mean_charge[:, np.newaxis].T, self._dpH, ) ) # single decimal point reported only dev = round(dev * 10) / 10 full_df = full_df.append( dict( Molecule=mol, Metric=metric, Value=dev, Method=computed_provider.method_desc, Type=computed_provider.data_type, ), ignore_index=True, sort=False, ) self._raw_curves[(computed_provider.method_desc, mol, metric)] = ( np.asarray([pred_data.mean_charge]), np.asarray([exp_data.mean_charge]), np.asarray([dev]), pred_data.ph_values, ) return full_df def titration_color_legend(self): """Produce legend for colors of titration curves.""" pal = sns.color_palette("dark") fig, ax = plt.subplots(1, 1, figsize=(4, 2), dpi=150) ax.plot([0, 1], [0, 1], color="black", lw=3, label="Experiment") for p, prov in enumerate(self._providers): ax.plot([0, 1], [0, 1], color=pal[p], lw=3, label=prov.label) ax.plot([0, 1], [0, 1], color="black", ls="--", lw=3, label="95% bootstrap CI") # Separate legend figure figlegend, axlegend = plt.subplots(1, 1, figsize=[8, 1], dpi=150) handles, labels = ax.get_legend_handles_labels() # handles = np.concatenate((handles[::2],handles[1::2]),axis=0) # labels = np.concatenate((labels[::2],labels[1::2]),axis=0) leg = figlegend.legend(handles, labels, loc="center", ncol=4, frameon=False) axlegend.get_xaxis().set_visible(False) axlegend.get_yaxis().set_visible(False) for spine in ["top", "left", "bottom", "right"]: axlegend.spines[spine].set_visible(False) plt.close(fig) return figlegend def plot_titration_curves(self, include_micro=False): """Plot the titration curves for all the methods that were analyzed.""" pal = sns.color_palette("dark") figures = dict() for mol in tqdm( self.included_molecules, desc="Titration", unit="molecule", leave=False ): fullfig, fullax = plt.subplots(1, 1, figsize=(3, 3), dpi=150) for p, prov in enumerate(self._providers): sepfig, sepax = plt.subplots(1, 1, figsize=(3, 3), dpi=150) if not include_micro: if prov.data_type not in ["typeiii", "typeimacro"]: continue computed, experimental, scores, ph_values = self._raw_curves[ (prov.method_desc, mol, "area") ] alpha = 0.9 color = pal[p] std = np.std(computed, axis=0) mean = computed[-1, :] # Unpack tuple for i, ax in enumerate([fullax, sepax]): ax.plot( ph_values, mean, "-", linewidth=1.5, color=color, alpha=alpha ) ax.plot( ph_values, experimental[-1, :], "-", linewidth=1.5, color="black", alpha=0.7, ) ax.plot( ph_values, mean + (2 * std), "--", linewidth=0.75, color=color, alpha=0.5 * alpha, ) ax.plot( ph_values, mean - (2 * std), "--", linewidth=0.75, color=color, alpha=0.5 * alpha, ) if i == 1: ax.fill_between( ph_values, mean - (2 * std), mean + (2 * std), facecolor=color, alpha=0.05, ) sepax.yaxis.set_major_locator(MaxNLocator(integer=True)) # No labels on y axis, but indicate the integer values with ticks # labels = [item.get_text() for item in ax.get_yticklabels()] # empty_string_labels = [""] * len(labels) # ax.set_yticklabels(empty_string_labels) sepax.set_ylabel(r"$Q_\mathsf{avg}$") sepax.set_xlabel("pH") # x-tick every 2 pH units sepax.set_xticks(np.arange(2.0, 14.0, 2.0)) # remove top and right spines sns.despine(sepfig) title = f"{prov.method_desc} {mol}" sepax.set_title(title) # fit everything within bounds sepfig.tight_layout() figures[title] = sepfig fullax.yaxis.set_major_locator(MaxNLocator(integer=True)) # No labels on y axis, but indicate the integer values with ticks # labels = [item.get_text() for item in ax.get_yticklabels()] # empty_string_labels = [""] * len(labels) # ax.set_yticklabels(empty_string_labels) fullax.set_ylabel(r"$Q_\mathsf{avg}$") fullax.set_xlabel("pH") # x-tick every 2 pH units fullax.set_xticks(np.arange(2.0, 14.0, 2.0)) # remove top and right spines sns.despine(fullfig) fullax.set_title(mol) # fit everything within bounds fullfig.tight_layout() figures[f"overview {mol}"] = fullfig return figures def table_overall_performance(self): """Compile the general overview table.""" # Individual assessments are stored as distributions, but for aggregation, use floats. self._curve_df["Value_float"] = self._curve_df["Value"].apply(float) aggregate_df = pd.DataFrame() # average over all molecules for (method, metric, stype), group in self._curve_df.groupby( ["Method", "Metric", "Type"] ): aggregate_df = aggregate_df.append( dict( Method=method, Metric=metric, Type=stype, Algorithm="Titration curve", Value=bootstrapped_func(group["Value_float"], 10000, np.mean), ), ignore_index=True, sort=False, ) aggregate_df = aggregate_df.append(self._corr_df, ignore_index=True, sort=False) # Every method is a row. rownames = [prov.method_desc for prov in self._providers] # used to find row indices in table row_key = list(set(rownames)) # Every comparison algorithm/method e.g. Hungarian, closest, or titration curve gets a main column # Type iii used here because it should have all types, whereas typei doesnt have align column_key = list(self._mapping_algorithms["typeiii"].keys()) column_key.append("Titration curve") # subcolumn indices as lists in a dict[main column] subcolumn_keys = dict() for column in column_key: if column in self._mapping_algorithms["typeiii"]: subcolumn_keys[column] = list(self._correlation_metrics.keys()) elif column == "Titration curve": subcolumn_keys[column] = list(self._curve_metrics.keys()) else: raise ValueError(f"Unexpected column encountered: {column}.") # Number of rows is one row per method and two label rows num_rows = len(row_key) + 2 # The number of actual columns in the table is the number of subcolumns and one label column num_columns = sum([len(col) for col in subcolumn_keys.values()]) + 1 # Array of strings shorter than 32 unicode characters table = np.empty((num_rows, num_columns), dtype="<U32") # em dash for anything with no value table[2:, 1:] = " \\textemdash " # Label rows in table for row_idx, rowname in enumerate(row_key, start=2): table[row_idx, 0] = rowname # label columns in table offset = 1 for col_idx, (colname, subcols) in enumerate(subcolumn_keys.items(), start=1): table[0, offset] = colname for subcol_idx, subcolname in enumerate(subcols, start=offset): table[1, subcol_idx] = subcolname offset += len(subcols) # insert value in cells for ix, cell in aggregate_df.iterrows(): # skip these for now if cell["Loss function"] == "abs": continue val = str(cell.Value) row_idx = row_key.index(cell.Method) + 2 subcol_idx = 1 for colname, subcols in subcolumn_keys.items(): if colname == cell.Algorithm: subcol_idx += subcols.index(cell.Metric) break elif colname != cell.Algorithm: subcol_idx += len(subcols) # print(cell, row_idx, subcol_idx) table[row_idx, subcol_idx] = val alignment_string = "{}".format(num_columns * "c") content = "" for line in table: content += " & ".join(line) + "\\\\\n" return LatexTable(alignment_string, content).render_source() def table_curve_area(self): return ( self._curve_df[self._curve_df.Metric == "area"] .pivot(index="Molecule", columns="Method", values="Value")[ [p.method_desc for p in self._providers] ] .to_latex() ) def table_curve_rmsd(self): return ( self._curve_df[self._curve_df.Metric == "rmsd"] .pivot(index="Molecule", columns="Method", values="Value")[ [p.method_desc for p in self._providers] ] .to_latex() ) class LatexTable(TexBlock): """Basic class for latex syntax block, to be added to report.""" tex_src = ( "\\begin{{{sideways}table}}\n" "\\centering\n" "\\begin{{tabular}}{{{alignment}}}\n" "{content}\n" "\\end{{tabular}}\n" "\\end{{{sideways}table}}\n" ) def __init__(self, alignment, content, sideways=False): super(LatexTable, self).__init__(alignment=alignment, content=content) if sideways: self._variables["sideways"] = "sideways" warnings.warn( "Remember to add \\usepackage{{rotating}} to your preamble", UserWarning ) else: self._variables["sideways"] = "" return def plot_micropka_network( titrationcurve: TypeIPrediction ) -> Tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]: """Plot the network of microstates connected by pKa values.""" if not issubclass(type(titrationcurve), TypeIPrediction): raise TypeError( "This function only implements handling of TypeIPrediction objects." ) charges = dict(zip(titrationcurve.state_ids, titrationcurve.charges)) node_colors = [] for node in titrationcurve.graph.nodes: node_colors.append(charge_colors[charges[node]]) edge_labels = dict() for edge in titrationcurve.graph.edges: # multiply by -1 to make arrow direction match pKa direction edge_labels[(edge[0], edge[1])] = "pKa : {:.2f}".format( -1 * titrationcurve.graph.edges[edge[0], edge[1]]["pKa"] ) fig = plt.figure(figsize=(7, 11), dpi=75) pos = pydot_layout(titrationcurve.graph, prog="dot") nx.draw_networkx_nodes( titrationcurve.graph, pos, node_color=node_colors, alpha=0.85, node_size=6000, node_shape="o", ) nx.draw_networkx_labels( titrationcurve.graph, pos, node_color=node_colors, alpha=1 ) nx.draw_networkx_edge_labels( titrationcurve.graph, pos, edge_labels=edge_labels, alpha=0.75, ) nx.draw_networkx_edges( titrationcurve.graph, pos, edge_labels=edge_labels, alpha=0.75, node_size=6000, ) plt.tight_layout() sns.palplot(charge_colors.values()) ax = plt.gca() xticks = ax.get_xticks() xticks = [x + 0.5 for x in xticks] ax.set_xticks(xticks) ax.set_xticklabels(["{:+d}".format(l) for l in charge_colors.keys()]) for tick in ax.xaxis.get_major_ticks(): tick.label.set_fontsize(16) plt.tight_layout() return (fig, ax) def tabulate_cycles(titrationcurve: TypeIPrediction, length: int = 4) -> str: """Returns a string with table of all cycles of specified length (default: 4). Warning ------- This example implementation uses networkx.simple_cycles. It is not very optimized, and involves making the list of all cycles and then picking out the ones of the correct length. This will be very slow for larger networks. """ # # Find cycles of a specific length if not issubclass(type(titrationcurve), TypeIPrediction): raise TypeError( "This function only implements handling of TypeIPrediction objects." ) markdown: str = "" cycles: List[Tuple[List[str], float]] = [] for cycle in tqdm(nx.simple_cycles(titrationcurve.augmented_graph), desc="cycles"): if len(cycle) == length: rotated = deque(cycle) rotated.rotate(1) tot = 0.0 for edge in zip(cycle, rotated): tot += titrationcurve.augmented_graph.edges[edge]["pKa"] cycles.append((cycle, tot)) markdown += "cycle | sum pKa \n -----|----- \n " for (cycle, tot) in cycles: markdown += f" {cycle} | {tot:.3f} \n" return markdown def plot_free_energy_vs_ph( curve: TitrationCurve, base_e: bool = True, color_by_charge=True, mono_color=False ): """Plot the free energy of each state as a function of pH. Parameters ---------- curve - Titration curve object base_e - Plot free energy in base e (RT units), set to false for pKa units. color_by_charge - Plot each state colored according to charge. mono_color - If not coloring by charge, use a single color (printer/colorblind friendly). Unfortunately has low contrast. """ fig = plt.figure(figsize=(6, 7), dpi=90) ax = plt.gca() log_base = 1.0 if base_e else np.log(10) if color_by_charge: colors = [ charge_colors[q] for q in curve.charges ] # charge for each state converted to color else: if mono_color: colors = sns.color_palette("Greys", len(curve.state_ids)) else: colors = sns.color_palette("hls", len(curve.state_ids)) for i in range(len(curve.state_ids)): label = curve.state_ids[i] free_energy = curve.free_energies[i, :] / log_base plt.plot(curve.ph_values, free_energy, color=colors[i], label=label) # If colored by charge, add some textual labels on the right side if color_by_charge: t = plt.annotate( label.split("_")[1][5:], (curve.ph_values[-1], free_energy[-1]), (curve.ph_values[-1] + 0.8 * (i % 5), free_energy[-1]), backgroundcolor="white", color=colors[i], alpha=1.0, size=10, # arrowprops={"arrowstyle": "->", "color":"black"}, ) t.set_bbox(dict(alpha=0.0)) if base_e: plt.ylabel("Free energy (RT)", size=12) else: plt.ylabel("Free energy (pKa units)", size=12) plt.xlabel("pH", size=12) plt.xticks(size=12) plt.yticks(size=12) plt.tight_layout() return fig, ax def plot_population_vs_ph(curve: TitrationCurve, mono_color=False): """Plot the free energy of each state as a function of pH. Parameters ---------- curve - Titration curve object mono_color - If not coloring by charge, use a single color (printer/colorblind friendly). Unfortunately has low contrast. """ fig = plt.figure(figsize=(6, 7), dpi=90) ax = plt.gca() if mono_color: colors = sns.color_palette("Greys", len(curve.state_ids)) else: colors = sns.color_palette("hls", len(curve.state_ids)) for i in range(len(curve.state_ids)): label = curve.state_ids[i] pop = curve.populations[i, :] plt.plot(curve.ph_values, pop, color=colors[i], label=label) plt.ylabel("Population", size=12) plt.xlabel("pH", size=12) plt.xticks(size=12) plt.yticks(size=12) plt.tight_layout() return fig, ax def tabulate_free_energy( curve: TypeIPrediction, base_e: bool = True, ph: float = 0.0 ) -> str: """Make a table of the free energy of each state, and how it was derived. Parameters ---------- curve - TypeIPrediction object for a single molecule to list free energy for. base_e - Set to True to in natural log base instead of pKa units. ph - The pH at which the free energy is to be retrieved (make sure this is included in the supplied curve.) Returns ------- str with markdown formatted table. Note ---- The most deprotonated state is typically the pKa reference, from which other states are derived. """ # Find where pH is equal to specified value. If this raises index error, no pH 0 value is included try: index = np.argwhere(np.isclose(ph, curve.ph_values))[0][0] except IndexError: raise IndexError(f"Titration curve does not include pH {ph:f}.") # log base correction to switch between 10 and e. log_base = 1.0 if base_e else np.log(10) if base_e: table_name = f"Free energy (RT) at pH {ph}" else: table_name = f"Free energy (pKa units) at pH {ph}" markdown = f"Microstate | {table_name} | pKa references\n ---|---|---\n" for (i, f, p) in zip( curve.state_ids, curve.free_energies[:, index] / (log_base), curve.pka_paths ): markdown += f"{i} | {f} | {' -> '.join(p)}\n" return markdown
[ "matplotlib.rc", "numpy.empty", "adjustText.adjust_text", "matplotlib.pyplot.figure", "numpy.mean", "networkx.draw_networkx_nodes", "numpy.arange", "networkx.draw_networkx_labels", "matplotlib.pyplot.gca", "numpy.isclose", "networkx.draw_networkx_edge_labels", "matplotlib.pyplot.fill_between",...
[((1400, 1419), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1417, 1419), False, 'import logging\n'), ((1442, 1464), 'seaborn.set_style', 'sns.set_style', (['"""ticks"""'], {}), "('ticks')\n", (1455, 1464), True, 'import seaborn as sns\n'), ((1491, 1525), 'matplotlib.rc', 'matplotlib.rc', (['"""font"""'], {}), "('font', **glob_font)\n", (1504, 1525), False, 'import matplotlib\n'), ((1527, 1570), 'matplotlib.rc', 'matplotlib.rc', (['"""lines"""'], {}), "('lines', **{'markersize': 4})\n", (1540, 1570), False, 'import matplotlib\n'), ((25949, 26026), 'matplotlib.pyplot.plot', 'plt.plot', (['ph_range', 'quantiles[0]', '"""-"""'], {'color': 'color', 'alpha': '(1.0)', 'label': '"""median"""'}), "(ph_range, quantiles[0], '-', color=color, alpha=1.0, label='median')\n", (25957, 26026), True, 'from matplotlib import pyplot as plt\n'), ((26224, 26285), 'matplotlib.pyplot.plot', 'plt.plot', (['ph_range', 'quantiles[2]', '""":"""'], {'color': 'color', 'alpha': '(1.0)'}), "(ph_range, quantiles[2], ':', color=color, alpha=1.0)\n", (26232, 26285), True, 'from matplotlib import pyplot as plt\n'), ((26917, 26940), 'numpy.mean', 'np.mean', (['curves'], {'axis': '(0)'}), '(curves, axis=0)\n', (26924, 26940), True, 'import numpy as np\n'), ((26952, 26974), 'numpy.std', 'np.std', (['curves'], {'axis': '(0)'}), '(curves, axis=0)\n', (26958, 26974), True, 'import numpy as np\n'), ((26980, 27036), 'matplotlib.pyplot.plot', 'plt.plot', (['ph_range', 'mean', '"""-"""'], {'color': 'color', 'label': '"""mean"""'}), "(ph_range, mean, '-', color=color, label='mean')\n", (26988, 27036), True, 'from matplotlib import pyplot as plt\n'), ((27042, 27136), 'matplotlib.pyplot.plot', 'plt.plot', (['ph_range', '(mean + 2 * std)', '""":"""'], {'alpha': '(1.0)', 'color': 'color', 'label': '"""$\\\\pm$2$\\\\sigma$"""'}), "(ph_range, mean + 2 * std, ':', alpha=1.0, color=color, label=\n '$\\\\pm$2$\\\\sigma$')\n", (27050, 27136), True, 'from matplotlib import pyplot as plt\n'), ((27152, 27215), 'matplotlib.pyplot.plot', 'plt.plot', (['ph_range', '(mean - 2 * std)', '""":"""'], {'alpha': '(1.0)', 'color': 'color'}), "(ph_range, mean - 2 * std, ':', alpha=1.0, color=color)\n", (27160, 27215), True, 'from matplotlib import pyplot as plt\n'), ((27870, 27929), 'numpy.random.choice', 'np.random.choice', (['curves.shape[0]', 'n_choices'], {'replace': '(False)'}), '(curves.shape[0], n_choices, replace=False)\n', (27886, 27929), True, 'import numpy as np\n'), ((28773, 28812), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '[2.5, 2.5]', 'dpi': '(150)'}), '(figsize=[2.5, 2.5], dpi=150)\n', (28783, 28812), True, 'from matplotlib import pyplot as plt\n'), ((28823, 28832), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (28830, 28832), True, 'from matplotlib import pyplot as plt\n'), ((30773, 30791), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (30789, 30791), True, 'from matplotlib import pyplot as plt\n'), ((30797, 30813), 'seaborn.despine', 'sns.despine', (['fig'], {}), '(fig)\n', (30808, 30813), True, 'import seaborn as sns\n'), ((64246, 64281), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(7, 11)', 'dpi': '(75)'}), '(figsize=(7, 11), dpi=75)\n', (64256, 64281), True, 'from matplotlib import pyplot as plt\n'), ((64293, 64339), 'networkx.drawing.nx_pydot.pydot_layout', 'pydot_layout', (['titrationcurve.graph'], {'prog': '"""dot"""'}), "(titrationcurve.graph, prog='dot')\n", (64305, 64339), False, 'from networkx.drawing.nx_pydot import pydot_layout\n'), ((64345, 64466), 'networkx.draw_networkx_nodes', 'nx.draw_networkx_nodes', (['titrationcurve.graph', 'pos'], {'node_color': 'node_colors', 'alpha': '(0.85)', 'node_size': '(6000)', 'node_shape': '"""o"""'}), "(titrationcurve.graph, pos, node_color=node_colors,\n alpha=0.85, node_size=6000, node_shape='o')\n", (64367, 64466), True, 'import networkx as nx\n'), ((64530, 64617), 'networkx.draw_networkx_labels', 'nx.draw_networkx_labels', (['titrationcurve.graph', 'pos'], {'node_color': 'node_colors', 'alpha': '(1)'}), '(titrationcurve.graph, pos, node_color=node_colors,\n alpha=1)\n', (64553, 64617), True, 'import networkx as nx\n'), ((64635, 64732), 'networkx.draw_networkx_edge_labels', 'nx.draw_networkx_edge_labels', (['titrationcurve.graph', 'pos'], {'edge_labels': 'edge_labels', 'alpha': '(0.75)'}), '(titrationcurve.graph, pos, edge_labels=\n edge_labels, alpha=0.75)\n', (64663, 64732), True, 'import networkx as nx\n'), ((64777, 64883), 'networkx.draw_networkx_edges', 'nx.draw_networkx_edges', (['titrationcurve.graph', 'pos'], {'edge_labels': 'edge_labels', 'alpha': '(0.75)', 'node_size': '(6000)'}), '(titrationcurve.graph, pos, edge_labels=edge_labels,\n alpha=0.75, node_size=6000)\n', (64799, 64883), True, 'import networkx as nx\n'), ((64940, 64958), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (64956, 64958), True, 'from matplotlib import pyplot as plt\n'), ((65012, 65021), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (65019, 65021), True, 'from matplotlib import pyplot as plt\n'), ((65283, 65301), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (65299, 65301), True, 'from matplotlib import pyplot as plt\n'), ((67190, 67224), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 7)', 'dpi': '(90)'}), '(figsize=(6, 7), dpi=90)\n', (67200, 67224), True, 'from matplotlib import pyplot as plt\n'), ((67235, 67244), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (67242, 67244), True, 'from matplotlib import pyplot as plt\n'), ((68556, 68581), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""pH"""'], {'size': '(12)'}), "('pH', size=12)\n", (68566, 68581), True, 'from matplotlib import pyplot as plt\n'), ((68587, 68606), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'size': '(12)'}), '(size=12)\n', (68597, 68606), True, 'from matplotlib import pyplot as plt\n'), ((68612, 68631), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'size': '(12)'}), '(size=12)\n', (68622, 68631), True, 'from matplotlib import pyplot as plt\n'), ((68637, 68655), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (68653, 68655), True, 'from matplotlib import pyplot as plt\n'), ((69029, 69063), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6, 7)', 'dpi': '(90)'}), '(figsize=(6, 7), dpi=90)\n', (69039, 69063), True, 'from matplotlib import pyplot as plt\n'), ((69074, 69083), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (69081, 69083), True, 'from matplotlib import pyplot as plt\n'), ((69444, 69477), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Population"""'], {'size': '(12)'}), "('Population', size=12)\n", (69454, 69477), True, 'from matplotlib import pyplot as plt\n'), ((69485, 69510), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""pH"""'], {'size': '(12)'}), "('pH', size=12)\n", (69495, 69510), True, 'from matplotlib import pyplot as plt\n'), ((69516, 69535), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'size': '(12)'}), '(size=12)\n', (69526, 69535), True, 'from matplotlib import pyplot as plt\n'), ((69541, 69560), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'size': '(12)'}), '(size=12)\n', (69551, 69560), True, 'from matplotlib import pyplot as plt\n'), ((69566, 69584), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (69582, 69584), True, 'from matplotlib import pyplot as plt\n'), ((6078, 6103), 'seaborn.color_palette', 'sns.color_palette', (['"""dark"""'], {}), "('dark')\n", (6095, 6103), True, 'import seaborn as sns\n'), ((7925, 7988), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '[8, 0.5]', 'dpi': "self._figprops['dpi']"}), "(1, 1, figsize=[8, 0.5], dpi=self._figprops['dpi'])\n", (7937, 7988), True, 'from matplotlib import pyplot as plt\n'), ((8573, 8587), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (8582, 8587), True, 'from matplotlib import pyplot as plt\n'), ((13232, 13245), 'seaborn.despine', 'sns.despine', ([], {}), '()\n', (13243, 13245), True, 'import seaborn as sns\n'), ((16220, 16242), 'seaborn.set_style', 'sns.set_style', (['"""ticks"""'], {}), "('ticks')\n", (16233, 16242), True, 'import seaborn as sns\n'), ((16281, 16310), 'matplotlib.rc', 'matplotlib.rc', (['"""font"""'], {}), "('font', **font)\n", (16294, 16310), False, 'import matplotlib\n'), ((16327, 16405), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': "cls._figprops['figsize']", 'dpi': "cls._figprops['dpi']"}), "(1, 1, figsize=cls._figprops['figsize'], dpi=cls._figprops['dpi'])\n", (16339, 16405), True, 'from matplotlib import pyplot as plt\n'), ((17713, 17745), 'numpy.std', 'np.std', (['bootstrap_curves'], {'axis': '(0)'}), '(bootstrap_curves, axis=0)\n', (17719, 17745), True, 'import numpy as np\n'), ((21376, 21389), 'seaborn.despine', 'sns.despine', ([], {}), '()\n', (21387, 21389), True, 'import seaborn as sns\n'), ((22511, 22529), 'seaborn.despine', 'sns.despine', ([], {'ax': 'ax'}), '(ax=ax)\n', (22522, 22529), True, 'import seaborn as sns\n'), ((23928, 23946), 'seaborn.despine', 'sns.despine', ([], {'ax': 'ax'}), '(ax=ax)\n', (23939, 23946), True, 'import seaborn as sns\n'), ((24988, 25006), 'seaborn.despine', 'sns.despine', ([], {'ax': 'ax'}), '(ax=ax)\n', (24999, 25006), True, 'import seaborn as sns\n'), ((26309, 26395), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['ph_range', 'quantiles[2]', 'quantiles[1]'], {'facecolor': 'color', 'alpha': '(0.1)'}), '(ph_range, quantiles[2], quantiles[1], facecolor=color,\n alpha=0.1)\n', (26325, 26395), True, 'from matplotlib import pyplot as plt\n'), ((27239, 27329), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['ph_range', '(mean + 2 * std)', '(mean - 2 * std)'], {'facecolor': 'color', 'alpha': '(0.1)'}), '(ph_range, mean + 2 * std, mean - 2 * std, facecolor=color,\n alpha=0.1)\n', (27255, 27329), True, 'from matplotlib import pyplot as plt\n'), ((27962, 28032), 'matplotlib.pyplot.plot', 'plt.plot', (['ph_range', 'curves[i]', '"""-"""'], {'color': 'color', 'zorder': '(0)', 'alpha': 'alpha'}), "(ph_range, curves[i], '-', color=color, zorder=0, alpha=alpha)\n", (27970, 28032), True, 'from matplotlib import pyplot as plt\n'), ((28981, 29017), 'numpy.any', 'np.any', (["(0 > dataframe['pKa Method1'])"], {}), "(0 > dataframe['pKa Method1'])\n", (28987, 29017), True, 'import numpy as np\n'), ((29030, 29069), 'numpy.any', 'np.any', (["(16.0 < dataframe['pKa Method1'])"], {}), "(16.0 < dataframe['pKa Method1'])\n", (29036, 29069), True, 'import numpy as np\n'), ((29082, 29118), 'numpy.any', 'np.any', (["(0 > dataframe['pKa Method2'])"], {}), "(0 > dataframe['pKa Method2'])\n", (29088, 29118), True, 'import numpy as np\n'), ((29131, 29170), 'numpy.any', 'np.any', (["(16.0 < dataframe['pKa Method2'])"], {}), "(16.0 < dataframe['pKa Method2'])\n", (29137, 29170), True, 'import numpy as np\n'), ((30608, 30628), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(2.0)'], {}), '(2.0)\n', (30623, 30628), False, 'from matplotlib.ticker import MaxNLocator, MultipleLocator\n'), ((30662, 30682), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(2.0)'], {}), '(2.0)\n', (30677, 30682), False, 'from matplotlib.ticker import MaxNLocator, MultipleLocator\n'), ((33304, 33318), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (33316, 33318), True, 'import pandas as pd\n'), ((33351, 33365), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (33363, 33365), True, 'import pandas as pd\n'), ((33940, 33992), 'tqdm.auto.tqdm', 'tqdm', (['all_providers'], {'desc': '"""Dataset"""', 'unit': '"""data set"""'}), "(all_providers, desc='Dataset', unit='data set')\n", (33944, 33992), False, 'from tqdm.auto import tqdm, trange\n'), ((34706, 34776), 'pandas.DataFrame', 'pd.DataFrame', (["{'pKa': titrationcurve.pkas, 'SEM': titrationcurve.sems}"], {}), "({'pKa': titrationcurve.pkas, 'SEM': titrationcurve.sems})\n", (34718, 34776), True, 'import pandas as pd\n'), ((34910, 34924), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (34922, 34924), True, 'import pandas as pd\n'), ((34945, 35022), 'tqdm.auto.tqdm', 'tqdm', (['self.included_molecules'], {'desc': '"""pKa maps"""', 'unit': '"""molecules"""', 'leave': '(False)'}), "(self.included_molecules, desc='pKa maps', unit='molecules', leave=False)\n", (34949, 35022), False, 'from tqdm.auto import tqdm, trange\n'), ((36936, 36950), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (36948, 36950), True, 'import pandas as pd\n'), ((38691, 38716), 'seaborn.color_palette', 'sns.color_palette', (['"""dark"""'], {}), "('dark')\n", (38708, 38716), True, 'import seaborn as sns\n'), ((39883, 39930), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(2.5, 2.5)', 'dpi': '(150)'}), '(1, 1, figsize=(2.5, 2.5), dpi=150)\n', (39895, 39930), True, 'from matplotlib import pyplot as plt\n'), ((39972, 39997), 'seaborn.color_palette', 'sns.color_palette', (['"""dark"""'], {}), "('dark')\n", (39989, 39997), True, 'import seaborn as sns\n'), ((42702, 42736), 'seaborn.despine', 'sns.despine', ([], {'ax': 'jointax', 'left': '(True)'}), '(ax=jointax, left=True)\n', (42713, 42736), True, 'import seaborn as sns\n'), ((47378, 47392), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (47390, 47392), True, 'import pandas as pd\n'), ((47902, 47956), 'tqdm.auto.tqdm', 'tqdm', (['self._providers'], {'desc': '"""Dataset"""', 'unit': '"""data set"""'}), "(self._providers, desc='Dataset', unit='data set')\n", (47906, 47956), False, 'from tqdm.auto import tqdm, trange\n'), ((48550, 48564), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (48562, 48564), True, 'import pandas as pd\n'), ((48587, 48664), 'tqdm.auto.tqdm', 'tqdm', (['self.included_molecules'], {'desc': '"""Titration"""', 'unit': '"""molecule"""', 'leave': '(False)'}), "(self.included_molecules, desc='Titration', unit='molecule', leave=False)\n", (48591, 48664), False, 'from tqdm.auto import tqdm, trange\n'), ((52977, 53002), 'seaborn.color_palette', 'sns.color_palette', (['"""dark"""'], {}), "('dark')\n", (52994, 53002), True, 'import seaborn as sns\n'), ((53022, 53065), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(4, 2)', 'dpi': '(150)'}), '(1, 1, figsize=(4, 2), dpi=150)\n', (53034, 53065), True, 'from matplotlib import pyplot as plt\n'), ((53429, 53472), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '[8, 1]', 'dpi': '(150)'}), '(1, 1, figsize=[8, 1], dpi=150)\n', (53441, 53472), True, 'from matplotlib import pyplot as plt\n'), ((53982, 53996), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (53991, 53996), True, 'from matplotlib import pyplot as plt\n'), ((54182, 54207), 'seaborn.color_palette', 'sns.color_palette', (['"""dark"""'], {}), "('dark')\n", (54199, 54207), True, 'import seaborn as sns\n'), ((54254, 54331), 'tqdm.auto.tqdm', 'tqdm', (['self.included_molecules'], {'desc': '"""Titration"""', 'unit': '"""molecule"""', 'leave': '(False)'}), "(self.included_molecules, desc='Titration', unit='molecule', leave=False)\n", (54258, 54331), False, 'from tqdm.auto import tqdm, trange\n'), ((58392, 58406), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (58404, 58406), True, 'import pandas as pd\n'), ((60447, 60494), 'numpy.empty', 'np.empty', (['(num_rows, num_columns)'], {'dtype': '"""<U32"""'}), "((num_rows, num_columns), dtype='<U32')\n", (60455, 60494), True, 'import numpy as np\n'), ((66123, 66171), 'networkx.simple_cycles', 'nx.simple_cycles', (['titrationcurve.augmented_graph'], {}), '(titrationcurve.augmented_graph)\n', (66139, 66171), True, 'import networkx as nx\n'), ((67280, 67290), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (67286, 67290), True, 'import numpy as np\n'), ((67784, 67852), 'matplotlib.pyplot.plot', 'plt.plot', (['curve.ph_values', 'free_energy'], {'color': 'colors[i]', 'label': 'label'}), '(curve.ph_values, free_energy, color=colors[i], label=label)\n', (67792, 67852), True, 'from matplotlib import pyplot as plt\n'), ((68442, 68481), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Free energy (RT)"""'], {'size': '(12)'}), "('Free energy (RT)', size=12)\n", (68452, 68481), True, 'from matplotlib import pyplot as plt\n'), ((68502, 68548), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Free energy (pKa units)"""'], {'size': '(12)'}), "('Free energy (pKa units)', size=12)\n", (68512, 68548), True, 'from matplotlib import pyplot as plt\n'), ((69376, 69436), 'matplotlib.pyplot.plot', 'plt.plot', (['curve.ph_values', 'pop'], {'color': 'colors[i]', 'label': 'label'}), '(curve.ph_values, pop, color=colors[i], label=label)\n', (69384, 69436), True, 'from matplotlib import pyplot as plt\n'), ((70668, 70678), 'numpy.log', 'np.log', (['(10)'], {}), '(10)\n', (70674, 70678), True, 'import numpy as np\n'), ((12750, 12775), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (12761, 12775), False, 'from matplotlib.ticker import MaxNLocator, MultipleLocator\n'), ((13157, 13182), 'numpy.arange', 'np.arange', (['(2.0)', '(14.0)', '(2.0)'], {}), '(2.0, 14.0, 2.0)\n', (13166, 13182), True, 'import numpy as np\n'), ((14241, 14304), 'numpy.asarray', 'np.asarray', (['[curve.mean_charge for curve in exp_bootstrap_data]'], {}), '([curve.mean_charge for curve in exp_bootstrap_data])\n', (14251, 14304), True, 'import numpy as np\n'), ((14597, 14615), 'os.path.isdir', 'os.path.isdir', (['dir'], {}), '(dir)\n', (14610, 14615), False, 'import os\n'), ((14630, 14646), 'os.makedirs', 'os.makedirs', (['dir'], {}), '(dir)\n', (14641, 14646), False, 'import os\n'), ((14919, 14970), 'os.path.join', 'os.path.join', (['dir', 'f"""{self._mol_id}-molecule.{ext}"""'], {}), "(dir, f'{self._mol_id}-molecule.{ext}')\n", (14931, 14970), False, 'import os\n'), ((20538, 20563), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (20549, 20563), False, 'from matplotlib.ticker import MaxNLocator, MultipleLocator\n'), ((21301, 21326), 'numpy.arange', 'np.arange', (['(2.0)', '(14.0)', '(2.0)'], {}), '(2.0, 14.0, 2.0)\n', (21310, 21326), True, 'import numpy as np\n'), ((22436, 22461), 'numpy.arange', 'np.arange', (['(2.0)', '(14.0)', '(2.0)'], {}), '(2.0, 14.0, 2.0)\n', (22445, 22461), True, 'import numpy as np\n'), ((23531, 23556), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (23542, 23556), False, 'from matplotlib.ticker import MaxNLocator, MultipleLocator\n'), ((23851, 23876), 'numpy.arange', 'np.arange', (['(2.0)', '(14.0)', '(2.0)'], {}), '(2.0, 14.0, 2.0)\n', (23860, 23876), True, 'import numpy as np\n'), ((24913, 24938), 'numpy.arange', 'np.arange', (['(2.0)', '(14.0)', '(2.0)'], {}), '(2.0, 14.0, 2.0)\n', (24922, 24938), True, 'import numpy as np\n'), ((25210, 25241), 'numpy.percentile', 'np.percentile', (['array', 'q'], {'axis': '(0)'}), '(array, q, axis=0)\n', (25223, 25241), True, 'import numpy as np\n'), ((34047, 34113), 'tqdm.auto.tqdm', 'tqdm', (['all_providers'], {'desc': '"""Dataset2"""', 'unit': '"""data set"""', 'leave': '(False)'}), "(all_providers, desc='Dataset2', unit='data set', leave=False)\n", (34051, 34113), False, 'from tqdm.auto import tqdm, trange\n'), ((37258, 37345), 'tqdm.auto.trange', 'trange', (['self._n_bootstrap_correlation'], {'desc': '"""Bootstrap"""', 'unit': '"""sample"""', 'leave': '(False)'}), "(self._n_bootstrap_correlation, desc='Bootstrap', unit='sample',\n leave=False)\n", (37264, 37345), False, 'from tqdm.auto import tqdm, trange\n'), ((40693, 40740), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(2.5, 2.5)', 'dpi': '(150)'}), '(1, 1, figsize=(2.5, 2.5), dpi=150)\n', (40705, 40740), True, 'from matplotlib import pyplot as plt\n'), ((40824, 40915), 'seaborn.distplot', 'sns.distplot', (['delta'], {'hist': '(False)', 'rug': '(True)', 'kde_kws': "{'shade': True}", 'color': 'color', 'ax': 'ax'}), "(delta, hist=False, rug=True, kde_kws={'shade': True}, color=\n color, ax=ax)\n", (40836, 40915), True, 'import seaborn as sns\n'), ((41658, 41676), 'adjustText.adjust_text', 'adjust_text', (['texts'], {}), '(texts)\n', (41669, 41676), False, 'from adjustText import adjust_text\n'), ((42150, 42198), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['f"""$pKa$ {method2} - $pKa$ {method1}"""'], {}), "(f'$pKa$ {method2} - $pKa$ {method1}')\n", (42160, 42198), True, 'from matplotlib import pyplot as plt\n'), ((42213, 42227), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (42223, 42227), True, 'from matplotlib import pyplot as plt\n'), ((42241, 42259), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (42257, 42259), True, 'from matplotlib import pyplot as plt\n'), ((42273, 42295), 'seaborn.despine', 'sns.despine', ([], {'left': '(True)'}), '(left=True)\n', (42284, 42295), True, 'import seaborn as sns\n'), ((42431, 42451), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(1.0)'], {}), '(1.0)\n', (42446, 42451), False, 'from matplotlib.ticker import MaxNLocator, MultipleLocator\n'), ((54388, 54431), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(3, 3)', 'dpi': '(150)'}), '(1, 1, figsize=(3, 3), dpi=150)\n', (54400, 54431), True, 'from matplotlib import pyplot as plt\n'), ((57883, 57903), 'seaborn.despine', 'sns.despine', (['fullfig'], {}), '(fullfig)\n', (57894, 57903), True, 'import seaborn as sns\n'), ((63162, 63253), 'warnings.warn', 'warnings.warn', (['"""Remember to add \\\\usepackage{{rotating}} to your preamble"""', 'UserWarning'], {}), "('Remember to add \\\\usepackage{{rotating}} to your preamble',\n UserWarning)\n", (63175, 63253), False, 'import warnings\n'), ((66246, 66258), 'collections.deque', 'deque', (['cycle'], {}), '(cycle)\n', (66251, 66258), False, 'from collections import deque\n'), ((11585, 11603), 'numpy.asarray', 'np.asarray', (['curves'], {}), '(curves)\n', (11595, 11603), True, 'import numpy as np\n'), ((14993, 15040), 'os.path.join', 'os.path.join', (['dir', 'f"""report-{self._mol_id}.tex"""'], {}), "(dir, f'report-{self._mol_id}.tex')\n", (15005, 15040), False, 'import os\n'), ((16030, 16047), 'matplotlib.pyplot.close', 'plt.close', (['figure'], {}), '(figure)\n', (16039, 16047), True, 'from matplotlib import pyplot as plt\n'), ((33472, 33545), 'warnings.warn', 'warnings.warn', (['"""An experiment was provided as a prediction."""', 'UserWarning'], {}), "('An experiment was provided as a prediction.', UserWarning)\n", (33485, 33545), False, 'import warnings\n'), ((41737, 41829), 'seaborn.distplot', 'sns.distplot', (['delta'], {'hist': '(False)', 'rug': '(False)', 'color': 'color', 'ax': 'jointax', 'label': 'f"""{method2}"""'}), "(delta, hist=False, rug=False, color=color, ax=jointax, label=\n f'{method2}')\n", (41749, 41829), True, 'import seaborn as sns\n'), ((41998, 42014), 'numpy.median', 'np.median', (['delta'], {}), '(delta)\n', (42007, 42014), True, 'import numpy as np\n'), ((42113, 42133), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(1.0)'], {}), '(1.0)\n', (42128, 42133), False, 'from matplotlib.ticker import MaxNLocator, MultipleLocator\n'), ((44257, 44307), 'uncertainties.ufloat', 'ufloat', (["row['pKa Method1']", "row['pKa SEM Method1']"], {}), "(row['pKa Method1'], row['pKa SEM Method1'])\n", (44263, 44307), False, 'from uncertainties import ufloat\n'), ((47567, 47640), 'warnings.warn', 'warnings.warn', (['"""An experiment was provided as a prediction."""', 'UserWarning'], {}), "('An experiment was provided as a prediction.', UserWarning)\n", (47580, 47640), False, 'import warnings\n'), ((49468, 49531), 'numpy.asarray', 'np.asarray', (['[curve.mean_charge for curve in exp_bootstrap_data]'], {}), '([curve.mean_charge for curve in exp_bootstrap_data])\n', (49478, 49531), True, 'import numpy as np\n'), ((49603, 49662), 'numpy.asarray', 'np.asarray', (['[curve.mean_charge for curve in bootstrap_data]'], {}), '([curve.mean_charge for curve in bootstrap_data])\n', (49613, 49662), True, 'import numpy as np\n'), ((49735, 49780), 'numpy.vstack', 'np.vstack', (['[exp_curves, exp_data.mean_charge]'], {}), '([exp_curves, exp_data.mean_charge])\n', (49744, 49780), True, 'import numpy as np\n'), ((49812, 49859), 'numpy.vstack', 'np.vstack', (['[pred_curves, pred_data.mean_charge]'], {}), '([pred_curves, pred_data.mean_charge])\n', (49821, 49859), True, 'import numpy as np\n'), ((54523, 54566), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(3, 3)', 'dpi': '(150)'}), '(1, 1, figsize=(3, 3), dpi=150)\n', (54535, 54566), True, 'from matplotlib import pyplot as plt\n'), ((54952, 54976), 'numpy.std', 'np.std', (['computed'], {'axis': '(0)'}), '(computed, axis=0)\n', (54958, 54976), True, 'import numpy as np\n'), ((57062, 57081), 'seaborn.despine', 'sns.despine', (['sepfig'], {}), '(sepfig)\n', (57073, 57081), True, 'import seaborn as sns\n'), ((57349, 57374), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (57360, 57374), False, 'from matplotlib.ticker import MaxNLocator, MultipleLocator\n'), ((57800, 57825), 'numpy.arange', 'np.arange', (['(2.0)', '(14.0)', '(2.0)'], {}), '(2.0, 14.0, 2.0)\n', (57809, 57825), True, 'import numpy as np\n'), ((12517, 12536), 'numpy.asarray', 'np.asarray', (['[curve]'], {}), '([curve])\n', (12527, 12536), True, 'import numpy as np\n'), ((14805, 14864), 'os.path.join', 'os.path.join', (['dir', 'f"""{desc}-{figtype}-{self._mol_id}.{ext}"""'], {}), "(dir, f'{desc}-{figtype}-{self._mol_id}.{ext}')\n", (14817, 14864), False, 'import os\n'), ((36556, 36606), 'uncertainties.ufloat', 'ufloat', (["row['pKa Method2']", "row['pKa SEM Method2']"], {}), "(row['pKa Method2'], row['pKa SEM Method2'])\n", (36562, 36606), False, 'from uncertainties import ufloat\n'), ((36626, 36676), 'uncertainties.ufloat', 'ufloat', (["row['pKa Method1']", "row['pKa SEM Method1']"], {}), "(row['pKa Method1'], row['pKa SEM Method1'])\n", (36632, 36676), False, 'from uncertainties import ufloat\n'), ((43965, 44015), 'uncertainties.ufloat', 'ufloat', (["row['pKa Method2']", "row['pKa SEM Method2']"], {}), "(row['pKa Method2'], row['pKa SEM Method2'])\n", (43971, 44015), False, 'from uncertainties import ufloat\n'), ((50179, 50241), 'titrato.fit_titration_curves_3d', 'fit_titration_curves_3d', (['pred_curves', 'exp_curves', 'm', 'self._dpH'], {}), '(pred_curves, exp_curves, m, self._dpH)\n', (50202, 50241), False, 'from titrato import fit_titration_curves_3d\n'), ((56491, 56516), 'matplotlib.ticker.MaxNLocator', 'MaxNLocator', ([], {'integer': '(True)'}), '(integer=True)\n', (56502, 56516), False, 'from matplotlib.ticker import MaxNLocator, MultipleLocator\n'), ((56971, 56996), 'numpy.arange', 'np.arange', (['(2.0)', '(14.0)', '(2.0)'], {}), '(2.0, 14.0, 2.0)\n', (56980, 56996), True, 'import numpy as np\n'), ((70439, 70470), 'numpy.isclose', 'np.isclose', (['ph', 'curve.ph_values'], {}), '(ph, curve.ph_values)\n', (70449, 70470), True, 'import numpy as np\n'), ((11532, 11557), 'copy.deepcopy', 'deepcopy', (['dat.mean_charge'], {}), '(dat.mean_charge)\n', (11540, 11557), False, 'from copy import deepcopy\n'), ((50639, 50662), 'numpy.asscalar', 'np.asscalar', (['scores[-1]'], {}), '(scores[-1])\n', (50650, 50662), True, 'import numpy as np\n'), ((52622, 52657), 'numpy.asarray', 'np.asarray', (['[pred_data.mean_charge]'], {}), '([pred_data.mean_charge])\n', (52632, 52657), True, 'import numpy as np\n'), ((52684, 52718), 'numpy.asarray', 'np.asarray', (['[exp_data.mean_charge]'], {}), '([exp_data.mean_charge])\n', (52694, 52718), True, 'import numpy as np\n'), ((52745, 52762), 'numpy.asarray', 'np.asarray', (['[dev]'], {}), '([dev])\n', (52755, 52762), True, 'import numpy as np\n'), ((58827, 58882), 'titrato.stats.bootstrapped_func', 'bootstrapped_func', (["group['Value_float']", '(10000)', 'np.mean'], {}), "(group['Value_float'], 10000, np.mean)\n", (58844, 58882), False, 'from titrato.stats import absolute_loss, squared_loss, array_mae, array_rmse, wrap_pearsonr, bootstrapped_func, array_median_error\n'), ((38341, 38372), 'numpy.asarray', 'np.asarray', (['bootstrap_estimates'], {}), '(bootstrap_estimates)\n', (38351, 38372), True, 'import numpy as np\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- #------------------------------------------------------------------------------- __author__ = "<NAME>" #------------------------------------------------------------------------------- # in this script, we take a large data frame file and label the rows according # to a model of semantic proximation of words, choosing tags from another table; # for it to run, it will also need a word vector file. The output is the same # data frame from the start joined with rank columns containing the tags # # for more details and resources, check the notebook file #------------------------------------------------------------------------------- import pandas as pd import re import numpy as np import nltk from spellchecker import SpellChecker from nltk.corpus import stopwords #------------------------------------------------------------------------------- nltk.download('stopwords') #------------------------------------------------------------------------------- # relevant urls; the first two are too big for the repository, so you'll need # to download them to run the script, only the tags.csv file is provided url_1 = 'donations.csv' #https://milliondollarlist.org/ url_2 = 'glove.6B.300d.txt' #https://nlp.stanford.edu/projects/glove/ url_3 = 'tags.csv' #tags .csv file url_4 = 'outputtable.csv' #output .csv file #------------------------------------------------------------------------------- # functions def replace_nan(s): # NaN or str -> str, '' if NaN if str(s) == 'nan': return '' else: return s def replace_disaster(s): # 'yes' -> 'disaster' if s == 'yes': return 'disaster' else: return s def str_to_set_of_words(s): # str -> set s = s.lower() #we need lower case only s = re.sub(r'[0-9]', ' ', s) #replace any number by ' ' s = re.sub(r'\W', ' ', s) #replace useless symbols by ' ' s = s.split() #split the string ret = [word for word in s if len(word) >2] #get rid of small words return set(ret) #returns a set, so no repetition def remove_stop_words(set_of_words): # set -> set # remove stopwords from the set return set_of_words.difference(stopwords.words('English')) def correct_text(set_of_words, correction): ''' set , dict -> set correct words from set according to dict we also remove new stopwords that may have appeared ''' set_of_words = remove_stop_words(set_of_words) iterating = set_of_words.copy() for word in iterating: if word in correction: corrected_word = correction[word] corrected_word = corrected_word.split() corrected_word = set(corrected_word) set_of_words.union(corrected_word) set_of_words.remove(word) return set_of_words def correction_tags(set_of_words): # set -> set , small manual corrections + remove stopwords set_of_words = remove_stop_words(set_of_words) iterating = set_of_words.copy() for word in iterating: if word == 'imrpoving': set_of_words.add('improving') set_of_words.remove('imrpoving') elif word == 'informationon': set_of_words.add('information') set_of_words.remove('informationon') elif word == 'meatâ': set_of_words.add('meat') set_of_words.remove('meatâ') elif word == 'valuesâ': set_of_words.add('values') set_of_words.remove('valuesâ') return set_of_words def cos_angle(vec_1 , vec_2): # np.array(float) , np.array(float) -> float , cos(angle between vectors) ve_1 = vec_1/np.linalg.norm(vec_1) ve_2 = vec_2/np.linalg.norm(vec_2) return np.dot(ve_1 ,ve_2) def set_distance(set_1 , set_2 , word_distances): ''' set , set -> float given two sets, calculate the "distance" between every combination of words possible, square them keeping the signal and return the mean of the values ''' dist = 0 for word_1 in set_1: for word_2 in set_2: d = word_distances[word_1][word_2] if d == 0: pass else: dist += (d**3)/d n = len(set_1)*len(set_2) if n == 0: return 0 else: return dist/n def dist_ranks(set_0 , tags , tags_dict , word_distances): ''' set , pd.DataFrame, dict -> list get a set of words, a data frame containing tags and the dictionary that converts tags into a set of words, returning the best 5 matches. One could change the parameter size for a bigger or smaller rank ''' size = 5 distances_tags = {} distances = [] for tag in tags['tags']: d = set_distance(set_0 , tags_dict[tag] , word_distances) distances_tags[tag] = d distances += [d] distances.sort(reverse = True) ret = [] done = set({}) for i in range(size): for d in distances_tags: if distances_tags[d] == distances[i]: if d in done: pass else: ret += [[d , distances[i]]] break return ret def chooose_index(l, i , j): # list , int , int -> list element return l[i][j] def to_int(s): # string -> int , convert '$5,000,000.00' to 5000000 list_numbers = re.findall('[0-9]+', s) number = ''.join(list_numbers) return int(int(number)/10) #------------------------------------------------------------------------------- def main(): print('Started.') donations_df = pd.read_csv(url_1, encoding = "ISO-8859-1") restrictions = ['Dollars', 'Recipient', 'Recipient Notes', 'Recipient Subsector', 'Recipient Sub Group', 'Gift Notes', 'Gift Purpose', 'Disaster'] donations_df_r = donations_df[restrictions] print('donations.cvs: opened and filtered') for column in donations_df_r.columns: donations_df_r[column] = donations_df_r[column].apply(replace_nan) donations_df_r['Disaster'] = donations_df_r[column].apply(replace_disaster) print('NaN values replaced and disaster status added.') donations_df_r['Joined'] = (donations_df_r["Recipient"].astype(str)+' ' +donations_df_r['Recipient Notes'].astype(str)+' ' +donations_df_r['Recipient Subsector'].astype(str)+' ' +donations_df_r['Recipient Sub Group'].astype(str)+' ' +donations_df_r['Gift Notes'].astype(str)+' ' +donations_df_r['Gift Purpose'].astype(str)) joined_df = donations_df_r[['Dollars','Joined']] print('Strings joined.') joined_df['Sets of words'] = joined_df['Joined'].apply(str_to_set_of_words) joined_df['Sets of words'] = joined_df['Sets of words'].apply( remove_stop_words) print('Stopwords removed and sets of words created.') words = set({}) for set_words in joined_df['Sets of words']: words = words.union(set_words) print('Set of words created. Loading word2vec') word2vec = {} with open(url_2, encoding="utf8") as infile: for line in infile: lst = [] line = str(line) lst = line.split() dictkey = lst.pop(0) floats = np.array(lst) word2vec[dictkey] = floats.astype(np.float64) print('Word2vec loaded') wordsout = set({}) for word in words: if not (word in word2vec): wordsout.add(word) print('Spell checking.') spell = SpellChecker() correction = {} misspelled = spell.unknown(wordsout) for word in misspelled: correction[word] = spell.correction(word) print('Correcting the words.') joined_df['Sets of words'] = joined_df['Sets of words'].apply(lambda x : correct_text(x , correction)) print('Automatic correction done, now doing manual correction.') words = set({}) for set_words in joined_df['Sets of words']: words = words.union(set_words) wordsout = set({}) for word in words: if not (word in word2vec): wordsout.add(word) correction['abour'] = 'about' correction['acces'] = 'access' correction['acti'] = 'act' correction['actr'] = 'act' correction['childern'] = 'children' correction['cleen'] = 'clean' correction['childr'] = 'children' correction['citywards'] = 'city wards' correction['comefor'] = 'come for' correction['contr'] = 'contribution' correction['contrib'] = 'contribution' correction['cultur'] = 'culture' correction['demostrate'] = 'demonstrate' correction['engagment'] = 'engagement' correction['peop'] = 'people' correction['peopl'] = 'people' correction['schoo'] = 'school' correction['soci'] = 'social' joined_df['Sets of words'] = joined_df['Sets of words'].apply(lambda x : correct_text(x , correction)) print('Correction done. Now loading and correcting tags.') tags = pd.read_csv(url_3, encoding = "ISO-8859-1") tags['tags_sets'] = tags['tags'].apply(str_to_set_of_words) tags['tags_sets'] = tags['tags_sets'].apply(correction_tags) tags_dict = {} for tag in tags['tags']: tags_dict[tag] = correction_tags(str_to_set_of_words(tag)) print('Generating distances matrix.') word_tags = set({}) for word_set in tags['tags_sets']: word_tags = word_tags.union(word_set) word_distances = {} for word_1 in words: for word_2 in word_tags: try: try: word_distances[word_1][word_2] = cos_angle( word2vec[word_1] , word2vec[word_2]) except: word_distances[word_1] = {word_2 : cos_angle( word2vec[word_1] , word2vec[word_2])} except: try: word_distances[word_1][word_2] = 0 except: word_distances[word_1] = {word_2 : 0} print('Ranking.') joined_df['ranks'] = joined_df['Sets of words'].apply(lambda x : dist_ranks(x , tags , tags_dict, word_distances)) print('Ranking done, generating output.') filter_to_columns = ['Dollars', 'Sets of words'] for i in range(5): filter_to_columns += [f'rank {i+1} tag'] joined_df[f'rank {i+1} tag'] = joined_df['ranks'].apply(lambda x : chooose_index(x, i , 0)) filter_to_columns += [f'rank {i+1} distance'] joined_df[f'rank {i+1} distance'] = joined_df['ranks'].apply(lambda x : chooose_index(x, i , 1)) df_final_clean = joined_df[filter_to_columns].copy() df_final_clean['Dollars'] = df_final_clean['Dollars'].apply(to_int) to_join = pd.read_csv(url_1, encoding = "ISO-8859-1") dff = df_final_clean.copy() dff = dff.rename(columns = {'Dollars' : 'Dollars Int'}) to_save = to_join.join(dff) to_save.to_csv(url_4, index = False) print('All done.') #------------------------------------------------------------------------------- if __name__ == '__main__': main()
[ "pandas.read_csv", "spellchecker.SpellChecker", "nltk.download", "re.findall", "numpy.linalg.norm", "numpy.array", "nltk.corpus.stopwords.words", "numpy.dot", "re.sub" ]
[((929, 955), 'nltk.download', 'nltk.download', (['"""stopwords"""'], {}), "('stopwords')\n", (942, 955), False, 'import nltk\n'), ((1914, 1937), 're.sub', 're.sub', (['"""[0-9]"""', '""" """', 's'], {}), "('[0-9]', ' ', s)\n", (1920, 1937), False, 'import re\n'), ((1990, 2011), 're.sub', 're.sub', (['"""\\\\W"""', '""" """', 's'], {}), "('\\\\W', ' ', s)\n", (1996, 2011), False, 'import re\n'), ((4030, 4048), 'numpy.dot', 'np.dot', (['ve_1', 've_2'], {}), '(ve_1, ve_2)\n', (4036, 4048), True, 'import numpy as np\n'), ((5748, 5771), 're.findall', 're.findall', (['"""[0-9]+"""', 's'], {}), "('[0-9]+', s)\n", (5758, 5771), False, 'import re\n'), ((5994, 6035), 'pandas.read_csv', 'pd.read_csv', (['url_1'], {'encoding': '"""ISO-8859-1"""'}), "(url_1, encoding='ISO-8859-1')\n", (6005, 6035), True, 'import pandas as pd\n'), ((8243, 8257), 'spellchecker.SpellChecker', 'SpellChecker', ([], {}), '()\n', (8255, 8257), False, 'from spellchecker import SpellChecker\n'), ((9806, 9847), 'pandas.read_csv', 'pd.read_csv', (['url_3'], {'encoding': '"""ISO-8859-1"""'}), "(url_3, encoding='ISO-8859-1')\n", (9817, 9847), True, 'import pandas as pd\n'), ((11769, 11810), 'pandas.read_csv', 'pd.read_csv', (['url_1'], {'encoding': '"""ISO-8859-1"""'}), "(url_1, encoding='ISO-8859-1')\n", (11780, 11810), True, 'import pandas as pd\n'), ((2415, 2441), 'nltk.corpus.stopwords.words', 'stopwords.words', (['"""English"""'], {}), "('English')\n", (2430, 2441), False, 'from nltk.corpus import stopwords\n'), ((3956, 3977), 'numpy.linalg.norm', 'np.linalg.norm', (['vec_1'], {}), '(vec_1)\n', (3970, 3977), True, 'import numpy as np\n'), ((3996, 4017), 'numpy.linalg.norm', 'np.linalg.norm', (['vec_2'], {}), '(vec_2)\n', (4010, 4017), True, 'import numpy as np\n'), ((7941, 7954), 'numpy.array', 'np.array', (['lst'], {}), '(lst)\n', (7949, 7954), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Fri Jun 16 17:09:03 2017 @author: Subhy Compute theoretical distribution of maximum distortion of Gaussian random manifolds under random projections """ import numpy as np from numpy import ndarray as array # ============================================================================= # calculate theory # ============================================================================= def numerator_LGG(mfld_dim: int, ambient_dim: array, vol: array, epsilon: array, prob: float) -> array: # our theory """ Theoretical M * epsilon^2 / K, our formula Parameters ---------- mfld_dim K, dimensionality of manifold ambient_dim N, dimensionality of ambient space vol V, volume of manifold epsilon allowed distortion prob allowed failure probability """ onev = np.ones_like(epsilon) Me_K = (np.log(vol / prob) / mfld_dim + 0.5 * np.log(27. / mfld_dim) + np.log(ambient_dim / 4.) + 1.5 * onev) return 16 * Me_K def numerator_BW(mfld_dim: int, ambient_dim: array, vol: array, epsilon: array, prob: float) -> array: # BW theory """ Theoretical M * epsilon^2 / K, Baraniuk & Wakin's formula Parameters ---------- mfld_dim K, dimensionality of manifold ambient_dim N, dimensionality of ambient space vol V, volume of manifold epsilon allowed distortion prob allowed failure probability """ R = 1. / np.sqrt(2. * np.pi * np.e) tau = 1.1 * np.sqrt(2.) Me_K = (np.log(vol**2 / prob) / mfld_dim + np.log(3100.**4 * mfld_dim * (1. * ambient_dim)**3 * R**2 / (epsilon**6 * tau**2))) return 676 * Me_K def numerator_Verma(mfld_dim: int, ambient_dim: array, vol: array, epsilon: array, prob: float) -> array: # Verma theory """ Theoretical M * epsilon^2 / K, Verma's formula Parameters ---------- mfld_dim K, dimensionality of manifold ambient_dim N, dimensionality of ambient space vol V, volume of manifold epsilon = allowed distortion prob allowed failure probability """ onev = np.ones_like(ambient_dim) Me_K = (np.log(vol / prob) / mfld_dim + onev * np.log(2**35 * 3**5 * 13**2 * mfld_dim / (epsilon**6 * np.pi * np.e)) / 2.) return 64 * Me_K def numerator_EW(mfld_dim: int, ambient_dim: array, vol: array, epsilon: array, prob: float) -> array: # Verma theory """ Theoretical M * epsilon^2 / K, Eftekhari & Wakin's formula Parameters ---------- mfld_dim K, dimensionality of manifold ambient_dim N, dimensionality of ambient space vol V, volume of manifold epsilon = allowed distortion prob allowed failure probability """ onev = np.ones_like(ambient_dim) tau = 1.1 * np.sqrt(2.) Me_K = (np.log(2 * vol**2) / mfld_dim + onev * (np.log(mfld_dim / (epsilon**4 * tau**2)) + 24)) Me_K = np.maximum(Me_K, np.log(8 / prob)) return 18 * Me_K # ============================================================================= # analytic data # ============================================================================= def get_all_analytic(epsilons: array, ambient_dims: array, vols: array, prob: float) -> (array, array, array, array, array, array, array, array, array, array): """ Calculate all theory Parameters ---------- epsilons list of allowed distortions proj_dims list of M's, dimensionalities of projected space ambient_dims ndarray of N's, dimensionality of ambient space vols tuple of tuples of ndarrays of (V^1/K)'s, volume of manifold, one for eack K, one for varying N/V prob allowed failure probability Returns ------- Ns, Vs, LGG_num, LGG_vol, BW_num, BW_vol, Vr_num, Vr_vol: values of (M * epsilon^2 / K) from: our theory, Baraniuk & Wakin's, Verma's formula for differnt N,V """ eps = np.array(epsilons)[..., np.newaxis] Vs = np.logspace(np.log10(vols[:, 0].min()), np.log10(vols[:, -1].max()), 10) Ns = np.logspace(np.log10(ambient_dims[0]), np.log10(ambient_dims[-1]), 10) N = ambient_dims[-1] V = vols[:, -1] LGG_num = np.stack((numerator_LGG(1, Ns, V[0], eps, prob), numerator_LGG(2, Ns, V[1]**2, eps, prob)), axis=0) LGG_vol = np.stack((numerator_LGG(1, N, Vs, eps, prob), numerator_LGG(2, N, Vs**2, eps, prob)), axis=0) BW_num = np.stack((numerator_BW(1, Ns, V[0], eps, prob), numerator_BW(2, Ns, V[1]**2, eps, prob)), axis=0) BW_vol = np.stack((numerator_BW(1, N, Vs, eps, prob), numerator_BW(2, N, Vs**2, eps, prob)), axis=0) Verma_num = np.stack((numerator_Verma(1, Ns, V[0], eps, prob), numerator_Verma(2, Ns, V[1]**2, eps, prob)), axis=0) Verma_vol = np.stack((numerator_Verma(1, N, Vs, eps, prob), numerator_Verma(2, N, Vs**2, eps, prob)), axis=0) EW_num = np.stack((numerator_EW(1, Ns, V[0], eps, prob), numerator_EW(2, Ns, V[1]**2, eps, prob)), axis=0) EW_vol = np.stack((numerator_EW(1, N, Vs, eps, prob), numerator_EW(2, N, Vs**2, eps, prob)), axis=0) return (Ns, Vs, LGG_num, LGG_vol, BW_num, BW_vol, Verma_num, Verma_vol, EW_num, EW_vol) # ============================================================================= # test code # ============================================================================= if __name__ == "__main__": print('Run from outside package.')
[ "numpy.ones_like", "numpy.log", "numpy.array", "numpy.log10", "numpy.sqrt" ]
[((956, 977), 'numpy.ones_like', 'np.ones_like', (['epsilon'], {}), '(epsilon)\n', (968, 977), True, 'import numpy as np\n'), ((2459, 2484), 'numpy.ones_like', 'np.ones_like', (['ambient_dim'], {}), '(ambient_dim)\n', (2471, 2484), True, 'import numpy as np\n'), ((3222, 3247), 'numpy.ones_like', 'np.ones_like', (['ambient_dim'], {}), '(ambient_dim)\n', (3234, 3247), True, 'import numpy as np\n'), ((1665, 1692), 'numpy.sqrt', 'np.sqrt', (['(2.0 * np.pi * np.e)'], {}), '(2.0 * np.pi * np.e)\n', (1672, 1692), True, 'import numpy as np\n'), ((1708, 1720), 'numpy.sqrt', 'np.sqrt', (['(2.0)'], {}), '(2.0)\n', (1715, 1720), True, 'import numpy as np\n'), ((1780, 1879), 'numpy.log', 'np.log', (['(3100.0 ** 4 * mfld_dim * (1.0 * ambient_dim) ** 3 * R ** 2 / (epsilon ** 6 *\n tau ** 2))'], {}), '(3100.0 ** 4 * mfld_dim * (1.0 * ambient_dim) ** 3 * R ** 2 / (\n epsilon ** 6 * tau ** 2))\n', (1786, 1879), True, 'import numpy as np\n'), ((3264, 3276), 'numpy.sqrt', 'np.sqrt', (['(2.0)'], {}), '(2.0)\n', (3271, 3276), True, 'import numpy as np\n'), ((3416, 3432), 'numpy.log', 'np.log', (['(8 / prob)'], {}), '(8 / prob)\n', (3422, 3432), True, 'import numpy as np\n'), ((4545, 4563), 'numpy.array', 'np.array', (['epsilons'], {}), '(epsilons)\n', (4553, 4563), True, 'import numpy as np\n'), ((4707, 4732), 'numpy.log10', 'np.log10', (['ambient_dims[0]'], {}), '(ambient_dims[0])\n', (4715, 4732), True, 'import numpy as np\n'), ((4755, 4781), 'numpy.log10', 'np.log10', (['ambient_dims[-1]'], {}), '(ambient_dims[-1])\n', (4763, 4781), True, 'import numpy as np\n'), ((1065, 1090), 'numpy.log', 'np.log', (['(ambient_dim / 4.0)'], {}), '(ambient_dim / 4.0)\n', (1071, 1090), True, 'import numpy as np\n'), ((1733, 1756), 'numpy.log', 'np.log', (['(vol ** 2 / prob)'], {}), '(vol ** 2 / prob)\n', (1739, 1756), True, 'import numpy as np\n'), ((2497, 2515), 'numpy.log', 'np.log', (['(vol / prob)'], {}), '(vol / prob)\n', (2503, 2515), True, 'import numpy as np\n'), ((3288, 3308), 'numpy.log', 'np.log', (['(2 * vol ** 2)'], {}), '(2 * vol ** 2)\n', (3294, 3308), True, 'import numpy as np\n'), ((2548, 2625), 'numpy.log', 'np.log', (['(2 ** 35 * 3 ** 5 * 13 ** 2 * mfld_dim / (epsilon ** 6 * np.pi * np.e))'], {}), '(2 ** 35 * 3 ** 5 * 13 ** 2 * mfld_dim / (epsilon ** 6 * np.pi * np.e))\n', (2554, 2625), True, 'import numpy as np\n'), ((3340, 3384), 'numpy.log', 'np.log', (['(mfld_dim / (epsilon ** 4 * tau ** 2))'], {}), '(mfld_dim / (epsilon ** 4 * tau ** 2))\n', (3346, 3384), True, 'import numpy as np\n'), ((990, 1008), 'numpy.log', 'np.log', (['(vol / prob)'], {}), '(vol / prob)\n', (996, 1008), True, 'import numpy as np\n'), ((1028, 1051), 'numpy.log', 'np.log', (['(27.0 / mfld_dim)'], {}), '(27.0 / mfld_dim)\n', (1034, 1051), True, 'import numpy as np\n')]
import numpy as np def dirac(m, x, x0): """Dirac computed at resolution m but restricted to a subinterval determined by x""" if type(x0) != list: a = np.sinc((float(m) - .5) * (x - x0) / np.pi) b = np.sinc(.5 * (x - x0) / np.pi) d = (m - .5) * a / b + .5 * np.cos(m * (x - x0)) return d / float(m) elif type(x0) == list and len(x0) == 2: return np.outer(dirac(m, x, x0[0]), dirac(m, x, x0[1])) else: print('Invalid input for Dirac') return def dsinc(x): return np.where(x >= 0, -np.pi * jn(1, np.pi * x), np.pi * jn(1, -np.pi * x)) def ddirac(m, x, x0): z = (m - .5) * (x - x0) / np.pi zz = .5 * (x - x0) / np.pi a = (m - .5)**2 / np.pi * dsinc(z) / np.sinc(zz) b = (m - .5) / 2 / np.pi * np.sinc(z) * dsinc(zz) / np.sinc(zz)**2 c = .5 * m * np.sin(m * x) return (-a + b + c) / float(m) def dvdirac(m, x, x0, v): a = v[0] * np.outer(ddirac(m, x, x0[0]), dirac(m, x, x0[1])) b = v[1] * np.outer(dirac(m, x, x0[0]), ddirac(m, x, x0[1])) return a + b
[ "numpy.sinc", "numpy.sin", "numpy.cos" ]
[((228, 259), 'numpy.sinc', 'np.sinc', (['(0.5 * (x - x0) / np.pi)'], {}), '(0.5 * (x - x0) / np.pi)\n', (235, 259), True, 'import numpy as np\n'), ((768, 779), 'numpy.sinc', 'np.sinc', (['zz'], {}), '(zz)\n', (775, 779), True, 'import numpy as np\n'), ((868, 881), 'numpy.sin', 'np.sin', (['(m * x)'], {}), '(m * x)\n', (874, 881), True, 'import numpy as np\n'), ((836, 847), 'numpy.sinc', 'np.sinc', (['zz'], {}), '(zz)\n', (843, 847), True, 'import numpy as np\n'), ((295, 315), 'numpy.cos', 'np.cos', (['(m * (x - x0))'], {}), '(m * (x - x0))\n', (301, 315), True, 'import numpy as np\n'), ((811, 821), 'numpy.sinc', 'np.sinc', (['z'], {}), '(z)\n', (818, 821), True, 'import numpy as np\n')]
# Environment Setup # ---------------------------------------------------------------- # Dependencies import csv import pandas as pd import numpy as np from faker import Faker fake = Faker() # Output File Name file_output_schools = "generated_data/schools_complete.csv" file_output_students = "generated_data/students_complete.csv" # Generate a random number of Schools type_options = ("District", "Charter") num_schools = 11 # School Size Ranges small_school_size = (250, 2500) large_school_size = (2501, 5000) # Budget Amount Ranges low_capita_budget = (575, 650) high_capita_budget = (625, 675) # Student Math Scores Data low_math_scores = [64, 100] high_math_scores = [68, 100] # Student Reading Scores Data low_reading_scores = [55, 100] high_reading_scores = [89, 100] # Grade Ratios grade_options = ["9th", "10th", "11th", "12th"] grade_ratios = [0.27, 0.29, 0.22, 0.22] # Create Schools # ---------------------------------------------------------------- # Function for creating schools def create_school(): # Create an object for holding schools school = {} # Specify the School Name school_name = fake.last_name() + " High School" school["school_name"] = school_name # Specify the School Type school_type = np.random.choice(type_options) school["type"] = school_type # Specify the School Budget if school["type"] == "Charter": school_size = np.random.randint(small_school_size[0], small_school_size[1]) school_budget = np.random.randint(low_capita_budget[0], low_capita_budget[1]) * school_size else: school_size = np.random.randint(large_school_size[0], large_school_size[1]) school_budget = np.random.randint(high_capita_budget[0], high_capita_budget[1]) * school_size # Set the school size and budget school["size"] = school_size school["budget"] = school_budget return(school) # Create a set number of schools schools_list = [] # Add each generated school to the schools_list for x in range(num_schools): new_school = create_school() schools_list.append(new_school) print(". ", end="") # Convert to DataFrame for easy export schools_list_pd = pd.DataFrame(schools_list) # Reorder columns schools_list_pd = schools_list_pd[["school_name", "type", "size", "budget"]] # Export to CSV schools_list_pd.to_csv(file_output_schools, index_label="School ID") # Create Students # ---------------------------------------------------------------- # Function for creating students def create_student(school): # Create an object for holding students student = {} # Specify the Student Name student_data = fake.simple_profile() student_name = student_data["name"] # Minor cleanup of the name student["student_name"] = student_name # Assign the student a school student["school_name"] = school["school_name"] # Assign the student a grade student["grade"] = np.random.choice(grade_options, p=grade_ratios) # Assign the student a gender student["gender"] = student_data["sex"] # Assign the student a math score (include charter bonus) if school["type"] == "Charter": student["math_score"] = np.random.randint(high_math_scores[0], high_math_scores[1]) else: student["math_score"] = np.random.randint(low_math_scores[0], high_math_scores[1]) # Assign the student a reading score if school["type"] == "Charter": student["reading_score"] = np.random.randint(high_reading_scores[0], high_reading_scores[1]) else: student["reading_score"] = np.random.randint(low_reading_scores[0], high_reading_scores[1]) # Return the constructed student return(student) # Create an array of students students_list = [] # For each school, fill the student population for i, school in enumerate(schools_list): for student in range(school["size"]): new_student = create_student(school) students_list.append(new_student) print("Printing School #%s. Student #%s\n" % (i + 1, student), end="") # Convert to DataFrame for easy export students_list_pd = pd.DataFrame(students_list) # Reorder the columns upon export students_list_pd = students_list_pd[["student_name", "gender", "grade", "school_name", "reading_score", "math_score"]] # Export to CSV students_list_pd.to_csv(file_output_students, index_label="Student ID")
[ "pandas.DataFrame", "numpy.random.randint", "faker.Faker", "numpy.random.choice" ]
[((183, 190), 'faker.Faker', 'Faker', ([], {}), '()\n', (188, 190), False, 'from faker import Faker\n'), ((2346, 2372), 'pandas.DataFrame', 'pd.DataFrame', (['schools_list'], {}), '(schools_list)\n', (2358, 2372), True, 'import pandas as pd\n'), ((4481, 4508), 'pandas.DataFrame', 'pd.DataFrame', (['students_list'], {}), '(students_list)\n', (4493, 4508), True, 'import pandas as pd\n'), ((1258, 1288), 'numpy.random.choice', 'np.random.choice', (['type_options'], {}), '(type_options)\n', (1274, 1288), True, 'import numpy as np\n'), ((3099, 3146), 'numpy.random.choice', 'np.random.choice', (['grade_options'], {'p': 'grade_ratios'}), '(grade_options, p=grade_ratios)\n', (3115, 3146), True, 'import numpy as np\n'), ((1413, 1474), 'numpy.random.randint', 'np.random.randint', (['small_school_size[0]', 'small_school_size[1]'], {}), '(small_school_size[0], small_school_size[1])\n', (1430, 1474), True, 'import numpy as np\n'), ((1690, 1751), 'numpy.random.randint', 'np.random.randint', (['large_school_size[0]', 'large_school_size[1]'], {}), '(large_school_size[0], large_school_size[1])\n', (1707, 1751), True, 'import numpy as np\n'), ((3357, 3416), 'numpy.random.randint', 'np.random.randint', (['high_math_scores[0]', 'high_math_scores[1]'], {}), '(high_math_scores[0], high_math_scores[1])\n', (3374, 3416), True, 'import numpy as np\n'), ((3510, 3568), 'numpy.random.randint', 'np.random.randint', (['low_math_scores[0]', 'high_math_scores[1]'], {}), '(low_math_scores[0], high_math_scores[1])\n', (3527, 3568), True, 'import numpy as np\n'), ((3732, 3797), 'numpy.random.randint', 'np.random.randint', (['high_reading_scores[0]', 'high_reading_scores[1]'], {}), '(high_reading_scores[0], high_reading_scores[1])\n', (3749, 3797), True, 'import numpy as np\n'), ((3897, 3961), 'numpy.random.randint', 'np.random.randint', (['low_reading_scores[0]', 'high_reading_scores[1]'], {}), '(low_reading_scores[0], high_reading_scores[1])\n', (3914, 3961), True, 'import numpy as np\n'), ((1539, 1600), 'numpy.random.randint', 'np.random.randint', (['low_capita_budget[0]', 'low_capita_budget[1]'], {}), '(low_capita_budget[0], low_capita_budget[1])\n', (1556, 1600), True, 'import numpy as np\n'), ((1816, 1879), 'numpy.random.randint', 'np.random.randint', (['high_capita_budget[0]', 'high_capita_budget[1]'], {}), '(high_capita_budget[0], high_capita_budget[1])\n', (1833, 1879), True, 'import numpy as np\n')]
## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. # # U.S. EXPORT CONTROLLED TECHNICAL DATA # This software product contains export-restricted data whose # export/transfer/disclosure is restricted by U.S. law. Dissemination # to non-U.S. persons whether in the United States or abroad requires # an export license or other authorization. # # Contractor Name: <NAME> # Contractor Address: 6825 Pine Street, Suite 340 # Mail Stop B8 # Omaha, NE 68106 # 402.291.0100 # # See the AWIPS II Master Rights File ("Master Rights File.pdf") for # further licensing information. ## # ---------------------------------------------------------------- # Calculate the derived parameter WV/IR # # ---------------------------------------------------------------- # # SOFTWARE HISTORY # # Date Ticket# Engineer Description # ------------ ---------- ----------- ----------- # ??? Initial creation # Aug 05, 2015 4703 njensen cast 0 to uint8 # import numpy ## # Calculate the derived parameter WV/IR # This function accepts numpy arrays of the appropriate values. # # @param Imager_6pp7hh6pp5_micron_IR_ooWVcc: Water Vapor # @param Imager_11_micron_IR : Imager 11 micron IR # @return: # @rtype: numpy array or scalar # def execute(Imager_6pp7hh6pp5_micron_IR_ooWVcc, Imager_11_micron_IR): uWV = Imager_6pp7hh6pp5_micron_IR_ooWVcc.astype(numpy.uint8) WV = (uWV * 0.708).astype(numpy.uint8) uIR = Imager_11_micron_IR.astype(numpy.uint8) IR = numpy.where(uIR < 180, numpy.uint8(0), uIR) result = IR mask = (IR == 0) result[mask] = WV[mask] return result.astype(numpy.int8)
[ "numpy.uint8" ]
[((1723, 1737), 'numpy.uint8', 'numpy.uint8', (['(0)'], {}), '(0)\n', (1734, 1737), False, 'import numpy\n')]
import numbers from collections.abc import Iterable import numpy from hydep.lib import Universe from hydep import Pin, InfiniteMaterial, Material from .typed import BoundedTyped, TypedAttr from hydep.internal import Boundaries __all__ = ("LatticeStack",) class LatticeStack(Universe): """Representation of a 1D stack of universes Coded up to reflect a vertical stack with the :attr:`nLayers` and :attr:`heights` attributes. Providing the :attr:`items`, :attr:`heights`, and :attr:`outer` attributes is likely required to fully represent this stack. Fulfills a :class:`~collections.abc.Sequence` interface, wherein the stack can be iterated over, indexed, and each index can be set directly through the object. Parameters ---------- nLayers : int Positive integer for the number of layers heights : Iterable[float], optional Boundaries for each layer, so must have :attr:`nLayers` + 1 entries. Must all be increasing items : iterable of hydep.lib.Universe, optional Iterable of universes that fill each layer. Must have ``nLayers`` elements. Ordered such that ``items[i]`` occupies the space between ``heights`` name : str, optional Name of this stack outer : hydep.Material, optional Material that fills the space outside this stack Attributes ---------- nLayers : int Number of layers heights : Iterable[float], optional Boundaries for each layer. Must have :attr:`nLayers` + 1 entries. Must all be increasing in value. items : iterable of hydep.lib.Universe or None Iterable of universes that fill each layer. Must have :attr:`nLayers` elements. Ordered such that ``items[i]`` occupies the space between ``heights[i]`` and ``heights[i + 1]`` name : str or None Name of this stack outer : hydep.Material or None Material that fills the space outside this stack id : str Unique identifier bounds : None or Iterable[Iterable[float]] or :class:`hydep.internal.Boundaries` Spatial bounds for this universe. A value of ``None`` implies unbounded in space. Examples -------- >>> import hydep >>> m = hydep.Material("material") >>> u = hydep.InfiniteMaterial(m, name="empty" ) >>> stack = hydep.LatticeStack(2, [0, 0.5, 1], [u, u]) >>> stack[0] <InfiniteMaterial empty at ...> >>> stack[0] is u True >>> for ix, item in enumerate(stack): ... assert item is stack[ix] """ _nLayers = BoundedTyped("nLayers", numbers.Integral, gt=0) outer = TypedAttr("outer", Material, allowNone=True) def __init__(self, nLayers, heights=None, items=None, name=None, outer=None): super().__init__(name) self._nLayers = nLayers self._items = None self._heights = None if heights is not None: self.heights = heights if items is not None: self.items = items self.outer = outer def __len__(self): """Number of layers in this stack""" return self._nLayers def __iter__(self): """Iterate over all :attr:`items`""" return iter([] if self._items is None else self._items) def __getitem__(self, index) -> Universe: """Return the :class:`hydep.lib.Universe` at ``index``""" if self._items is None: raise AttributeError("Vertical stack not set") return self._items[index] def __setitem__(self, index, universe): """Set the :class:`hydep.lib.Universe` at ``index`` to be ``universe``""" if self._items is None: raise AttributeError("Vertical stack not set") assert isinstance(index, numbers.Integral) assert isinstance(universe, Universe) self._items[index] = universe def allocate(self): """Create :attr:`items` array but do not populate""" if self._items is not None: return self._items = numpy.empty(self.nLayers, dtype=object) @property def nLayers(self): return self._nLayers @property def heights(self): return self._heights @heights.setter def heights(self, heights): heights = numpy.asarray(heights, dtype=float).reshape(self.nLayers + 1) prev = heights.min() assert heights[0] == prev for value in heights[1:]: assert value > prev prev = value self._heights = heights @property def items(self): return self._items @items.setter def items(self, items): if self.items is None: self.allocate() elif items is None: self._items = None assert isinstance(items, Iterable) assert len(items) == self.nLayers assert all(isinstance(x, Universe) for x in items) for ix, item in enumerate(items): self._items[ix] = item def findMaterials(self, memo=None): """Yield all materials present in this and contained universes Parameters ---------- memo : set, optional Set containing ids of previously visited materials. Don't pass unless you know what you're doing. If given, will be modified with discovered materials Yields ------ hydep.Material The first occurance of this material. """ if self._items is None: raise AttributeError("Vertical stack {} not set".format(self)) memo = set() if memo is None else memo for item in self.items: hid = id(item) if hid in memo: continue for m in item.findMaterials(memo): yield m memo.add(hid) if self.outer is not None and id(self.outer) not in memo: memo.add(id(self.outer)) yield self.outer def countBurnableMaterials(self, memo=None): """Count all occurances of burnable materials Useful prior to cloning new burnable materials, so that volumes can be properly scaled. Parameters ---------- memo : dict of str to [hydep.BurnableMaterial, int], optional Previously visited universes will populate this as they traverse the geometry. Needed for internal use, and modified through the traversal. Keys indicate ids of universes as they are discovered and will be updated. Returns ------- Mapping[str, [hydep.BurnableMaterial, int]] Map of unique hashable IDs for unique burnable materials to the material and the number of instance found on this instance. """ # TODO Share with CartesianLattice? if self.items is None: raise AttributeError("Vertical stack {} not set".format(self)) memo = {} if memo is None else memo local = {} for item in self.items: hid = id(item) previous = memo.get(hid) if previous is None: memo[hid] = previous = item.countBurnableMaterials(memo) for uid, (mat, count) in previous.items(): present = local.get(uid) if present is None: local[uid] = [mat, count] else: local[uid][1] += count return local def differentiateBurnableMaterials(self, memo=None): """Create new burnable materials and potentially mimic this universe This routine is important to create unique burnable materials that can be depleted using spatially correct fluxes and reaction rates. This method digs through contained universes and creates unique :class:`hydep.BurnedMaterial` objects and potentially new interior universes. This material itself may be cloned if the following conditions are met: 1. At least one contained universe was cloned (e.g.a fuel pin was replaced) 2. This object has been encountered before If at least one contained universe was cloned but this is the first time encountering this universe, the modifications will be made in-place, and the original returned. Parameters ---------- memo : set of str, optional Set containing unique ids of previously found universes. Needed for internal use and not necessary for most end users. Returns ------- LatticeStack Either the originating universe or a near clone, but with one or more underlying materials changed. """ # TODO Support for outer - assume not burnable if self.items is None: raise AttributeError("Vertical stack not set for {}".format(self)) memo = set() if memo is None else memo updates = {} for ix, item in enumerate(self): new = item.differentiateBurnableMaterials(memo) if new is not item: updates[ix] = new memo.add(id(new)) if not updates: memo.add(id(self)) return self newitems = numpy.empty_like(self.items) for ix, item in enumerate(self): newitems[ix] = updates.get(ix, item) if id(self) not in memo: memo.add(id(self)) self.items = newitems return self return self.__class__(self.nLayers, self.heights, newitems, self.name, self.outer) def boundaries(self, memo=None): """Find boundaries in x, y, and z direction Also used to set :attr:`bounds` Parameters ---------- memo : dict, optional Not usually required by end-user. Used to track which sub-universes have already been traversed. Will map universe ids to discovered boundaries Returns ------- b : None or hydep.internal.Boundaries A value of ``None`` implies this object is unbounded in all directions. Otherwise, the ``x``, ``y``, and ``z`` attributes of the returned object describe the boundaries, potentially +/- ``numpy.inf``, for each dimension. """ memo = {} if memo is None else memo if self._bounds is not False: memo[id(self)] = self._bounds return self._bounds bx = (-numpy.inf, numpy.inf) by = (-numpy.inf, numpy.inf) for u in self.items: if isinstance(u, (Pin, InfiniteMaterial)): continue bounds = memo.get(id(u), False) # None is a valid answer if bounds is False: memo[id(u)] = bounds = u.boundaries(memo) if bounds is None: continue if bounds.x is not None: bx = self._compareUpdateBounds(bx, bounds.x) if bounds.y is not None: by = self._compareUpdateBounds(by, bounds.y) if -bx[0] == bx[1] == numpy.inf: bx = None if -by[0] == by[1] == numpy.inf: by = None mybounds = Boundaries(bx, by, (self.heights[0], self.heights[-1])) memo[id(self)] = mybounds return mybounds
[ "numpy.empty", "hydep.internal.Boundaries", "numpy.empty_like", "numpy.asarray" ]
[((4045, 4084), 'numpy.empty', 'numpy.empty', (['self.nLayers'], {'dtype': 'object'}), '(self.nLayers, dtype=object)\n', (4056, 4084), False, 'import numpy\n'), ((9327, 9355), 'numpy.empty_like', 'numpy.empty_like', (['self.items'], {}), '(self.items)\n', (9343, 9355), False, 'import numpy\n'), ((11318, 11373), 'hydep.internal.Boundaries', 'Boundaries', (['bx', 'by', '(self.heights[0], self.heights[-1])'], {}), '(bx, by, (self.heights[0], self.heights[-1]))\n', (11328, 11373), False, 'from hydep.internal import Boundaries\n'), ((4290, 4325), 'numpy.asarray', 'numpy.asarray', (['heights'], {'dtype': 'float'}), '(heights, dtype=float)\n', (4303, 4325), False, 'import numpy\n')]
# coding: utf-8 import chainer import chainer.functions as F class ConcatTuple(chainer.Chain): def forward(self, x, y): return F.concat((x, y)) class ConcatList(chainer.Chain): def forward(self, x, y): return F.concat([x, y]) # ====================================== from chainer_compiler import ch2o import numpy as np if __name__ == '__main__': v = np.random.rand(7, 4, 2).astype(np.float32) w = np.random.rand(7, 3, 2).astype(np.float32) ch2o.generate_testcase(ConcatTuple, [v, w]) ch2o.generate_testcase(ConcatList, [v, w], subname='list')
[ "numpy.random.rand", "chainer_compiler.ch2o.generate_testcase", "chainer.functions.concat" ]
[((487, 530), 'chainer_compiler.ch2o.generate_testcase', 'ch2o.generate_testcase', (['ConcatTuple', '[v, w]'], {}), '(ConcatTuple, [v, w])\n', (509, 530), False, 'from chainer_compiler import ch2o\n'), ((536, 594), 'chainer_compiler.ch2o.generate_testcase', 'ch2o.generate_testcase', (['ConcatList', '[v, w]'], {'subname': '"""list"""'}), "(ConcatList, [v, w], subname='list')\n", (558, 594), False, 'from chainer_compiler import ch2o\n'), ((142, 158), 'chainer.functions.concat', 'F.concat', (['(x, y)'], {}), '((x, y))\n', (150, 158), True, 'import chainer.functions as F\n'), ((238, 254), 'chainer.functions.concat', 'F.concat', (['[x, y]'], {}), '([x, y])\n', (246, 254), True, 'import chainer.functions as F\n'), ((388, 411), 'numpy.random.rand', 'np.random.rand', (['(7)', '(4)', '(2)'], {}), '(7, 4, 2)\n', (402, 411), True, 'import numpy as np\n'), ((439, 462), 'numpy.random.rand', 'np.random.rand', (['(7)', '(3)', '(2)'], {}), '(7, 3, 2)\n', (453, 462), True, 'import numpy as np\n')]
import torch import numpy as np from Tools.logger import save_context, Logger, CheckpointIO from Tools import FLAGS, load_config, utils_torch # from library import loss_gan from library import inputs, data_iters from library.trainer import trainer_byol from library import evaluator KEY_ARGUMENTS = load_config(FLAGS.config_file) text_logger, MODELS_FOLDER, SUMMARIES_FOLDER = save_context(__file__, KEY_ARGUMENTS) seed_bias = int(FLAGS.seed_bias) torch.manual_seed(1234 + seed_bias) torch.cuda.manual_seed(1235 + seed_bias) np.random.seed(1236 + seed_bias) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = True device = torch.device("cuda" if torch.cuda.is_available() else "cpu") FLAGS.device = device onlineModel, optim_o = inputs.get_model() targetModel, optim_t = inputs.get_model() onlineModel = torch.nn.DataParallel(onlineModel).to(device) targetModel = torch.nn.DataParallel(targetModel).to(device) utils_torch.update_average(targetModel, onlineModel, 0.0) scheduler_o = inputs.get_scheduler(optim_o) scheduler_t = inputs.get_scheduler(optim_t) ema_fun = inputs.get_ema_coefficiency() optim = inputs.OptimizerWrapper([optim_o, optim_t]) scheduler = inputs.SchedulerWrapper([scheduler_o, scheduler_t]) augmentWrapper = data_iters.get_data_augmentation(aug=True, toTensor=False) augmentWrapper = torch.nn.DataParallel(augmentWrapper).to(device) checkpoint_io = CheckpointIO(checkpoint_dir=MODELS_FOLDER) checkpoint_io.register_modules(onlineModel=onlineModel, targetModel=targetModel, optim_o=optim_o, optim_t=optim_t) logger = Logger(log_dir=SUMMARIES_FOLDER) if FLAGS.old_model != "NotApply": print("Loading old model") checkpoint_io.load_file(FLAGS.old_model) else: print("No old model, train from scratch") trainer_dict = {"byol": trainer_byol} trainer = trainer_dict[FLAGS.method].Trainer(onlineModel, targetModel, optim, ema_fun, augmentWrapper) evaluater = evaluator.Evaluator(onlineModel, targetModel) print_interv, eval_interv, sample_interv = 20, 400, 1000 iters, iters_per_epoch = data_iters.get_dataloader() iters_total = iters_per_epoch * FLAGS.training.nepoch x, y = iters.__next__() logger.add_imgs(x[:100, :3], "OriginImage") text_logger.info("Start Training") for iter_num in range(iters_total): x, y = iters.__next__() return_dict = trainer.step(x.to(device), y.to(device), iter_num) logger.addvs("Training", return_dict, iter_num) scheduler.step() if iter_num % print_interv == 0: prefix = "Iter {}/{}".format(iter_num, iters_total) logger.log_info(prefix, text_logger.info, ["Training"]) if iter_num % eval_interv == 0: iters_test = data_iters.get_dataloader(train=False, infinity=False, train_aug=False) return_dict = evaluater(iters_test) logger.addvs("Testing", return_dict, iter_num) prefix = "Iter {}".format(iter_num) logger.log_info(prefix, text_logger.info, ["Testing"]) if iter_num > 0 and (iter_num % 10000 == 0 or iter_num == (iters_total - 1)): checkpoint_io.save("Model{:08d}.pth".format(iter_num)) logger.save()
[ "library.inputs.SchedulerWrapper", "Tools.logger.Logger", "numpy.random.seed", "library.inputs.get_scheduler", "library.inputs.OptimizerWrapper", "library.data_iters.get_data_augmentation", "torch.manual_seed", "library.data_iters.get_dataloader", "Tools.load_config", "torch.cuda.manual_seed", "...
[((302, 332), 'Tools.load_config', 'load_config', (['FLAGS.config_file'], {}), '(FLAGS.config_file)\n', (313, 332), False, 'from Tools import FLAGS, load_config, utils_torch\n'), ((380, 417), 'Tools.logger.save_context', 'save_context', (['__file__', 'KEY_ARGUMENTS'], {}), '(__file__, KEY_ARGUMENTS)\n', (392, 417), False, 'from Tools.logger import save_context, Logger, CheckpointIO\n'), ((452, 487), 'torch.manual_seed', 'torch.manual_seed', (['(1234 + seed_bias)'], {}), '(1234 + seed_bias)\n', (469, 487), False, 'import torch\n'), ((488, 528), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['(1235 + seed_bias)'], {}), '(1235 + seed_bias)\n', (510, 528), False, 'import torch\n'), ((529, 561), 'numpy.random.seed', 'np.random.seed', (['(1236 + seed_bias)'], {}), '(1236 + seed_bias)\n', (543, 561), True, 'import numpy as np\n'), ((758, 776), 'library.inputs.get_model', 'inputs.get_model', ([], {}), '()\n', (774, 776), False, 'from library import inputs, data_iters\n'), ((800, 818), 'library.inputs.get_model', 'inputs.get_model', ([], {}), '()\n', (816, 818), False, 'from library import inputs, data_iters\n'), ((939, 996), 'Tools.utils_torch.update_average', 'utils_torch.update_average', (['targetModel', 'onlineModel', '(0.0)'], {}), '(targetModel, onlineModel, 0.0)\n', (965, 996), False, 'from Tools import FLAGS, load_config, utils_torch\n'), ((1011, 1040), 'library.inputs.get_scheduler', 'inputs.get_scheduler', (['optim_o'], {}), '(optim_o)\n', (1031, 1040), False, 'from library import inputs, data_iters\n'), ((1055, 1084), 'library.inputs.get_scheduler', 'inputs.get_scheduler', (['optim_t'], {}), '(optim_t)\n', (1075, 1084), False, 'from library import inputs, data_iters\n'), ((1095, 1124), 'library.inputs.get_ema_coefficiency', 'inputs.get_ema_coefficiency', ([], {}), '()\n', (1122, 1124), False, 'from library import inputs, data_iters\n'), ((1133, 1176), 'library.inputs.OptimizerWrapper', 'inputs.OptimizerWrapper', (['[optim_o, optim_t]'], {}), '([optim_o, optim_t])\n', (1156, 1176), False, 'from library import inputs, data_iters\n'), ((1189, 1240), 'library.inputs.SchedulerWrapper', 'inputs.SchedulerWrapper', (['[scheduler_o, scheduler_t]'], {}), '([scheduler_o, scheduler_t])\n', (1212, 1240), False, 'from library import inputs, data_iters\n'), ((1258, 1316), 'library.data_iters.get_data_augmentation', 'data_iters.get_data_augmentation', ([], {'aug': '(True)', 'toTensor': '(False)'}), '(aug=True, toTensor=False)\n', (1290, 1316), False, 'from library import inputs, data_iters\n'), ((1400, 1442), 'Tools.logger.CheckpointIO', 'CheckpointIO', ([], {'checkpoint_dir': 'MODELS_FOLDER'}), '(checkpoint_dir=MODELS_FOLDER)\n', (1412, 1442), False, 'from Tools.logger import save_context, Logger, CheckpointIO\n'), ((1567, 1599), 'Tools.logger.Logger', 'Logger', ([], {'log_dir': 'SUMMARIES_FOLDER'}), '(log_dir=SUMMARIES_FOLDER)\n', (1573, 1599), False, 'from Tools.logger import save_context, Logger, CheckpointIO\n'), ((1917, 1962), 'library.evaluator.Evaluator', 'evaluator.Evaluator', (['onlineModel', 'targetModel'], {}), '(onlineModel, targetModel)\n', (1936, 1962), False, 'from library import evaluator\n'), ((2046, 2073), 'library.data_iters.get_dataloader', 'data_iters.get_dataloader', ([], {}), '()\n', (2071, 2073), False, 'from library import inputs, data_iters\n'), ((674, 699), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (697, 699), False, 'import torch\n'), ((833, 867), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['onlineModel'], {}), '(onlineModel)\n', (854, 867), False, 'import torch\n'), ((893, 927), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['targetModel'], {}), '(targetModel)\n', (914, 927), False, 'import torch\n'), ((1334, 1371), 'torch.nn.DataParallel', 'torch.nn.DataParallel', (['augmentWrapper'], {}), '(augmentWrapper)\n', (1355, 1371), False, 'import torch\n'), ((2658, 2729), 'library.data_iters.get_dataloader', 'data_iters.get_dataloader', ([], {'train': '(False)', 'infinity': '(False)', 'train_aug': '(False)'}), '(train=False, infinity=False, train_aug=False)\n', (2683, 2729), False, 'from library import inputs, data_iters\n')]
import seaborn as sns import numpy as np import matplotlib.pyplot as plt import pandas as pd flights = sns.load_dataset('flights') sns.lineplot(data=flights, x='year', y='passengers') sns.lineplot(data=flights, x='year', y='passengers') plt.legend(['a', 'b']) plt.title('asd', fontsize=17) plt.xlabel("iteration", fontsize=15) plt.xticks(fontsize=13) plt.ylabel('asdasd', fontsize=15) plt.yticks(fontsize=13) plt.show() df = pd.DataFrame({'A': 1., 'B': 2., 'C': np.zeros((100,))}) print(df) print(df.dtypes)
[ "matplotlib.pyplot.title", "seaborn.lineplot", "matplotlib.pyplot.show", "matplotlib.pyplot.legend", "matplotlib.pyplot.yticks", "seaborn.load_dataset", "numpy.zeros", "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ]
[((104, 131), 'seaborn.load_dataset', 'sns.load_dataset', (['"""flights"""'], {}), "('flights')\n", (120, 131), True, 'import seaborn as sns\n'), ((132, 184), 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'flights', 'x': '"""year"""', 'y': '"""passengers"""'}), "(data=flights, x='year', y='passengers')\n", (144, 184), True, 'import seaborn as sns\n'), ((185, 237), 'seaborn.lineplot', 'sns.lineplot', ([], {'data': 'flights', 'x': '"""year"""', 'y': '"""passengers"""'}), "(data=flights, x='year', y='passengers')\n", (197, 237), True, 'import seaborn as sns\n'), ((238, 260), 'matplotlib.pyplot.legend', 'plt.legend', (["['a', 'b']"], {}), "(['a', 'b'])\n", (248, 260), True, 'import matplotlib.pyplot as plt\n'), ((261, 290), 'matplotlib.pyplot.title', 'plt.title', (['"""asd"""'], {'fontsize': '(17)'}), "('asd', fontsize=17)\n", (270, 290), True, 'import matplotlib.pyplot as plt\n'), ((291, 327), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""iteration"""'], {'fontsize': '(15)'}), "('iteration', fontsize=15)\n", (301, 327), True, 'import matplotlib.pyplot as plt\n'), ((328, 351), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(13)'}), '(fontsize=13)\n', (338, 351), True, 'import matplotlib.pyplot as plt\n'), ((352, 385), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""asdasd"""'], {'fontsize': '(15)'}), "('asdasd', fontsize=15)\n", (362, 385), True, 'import matplotlib.pyplot as plt\n'), ((386, 409), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(13)'}), '(fontsize=13)\n', (396, 409), True, 'import matplotlib.pyplot as plt\n'), ((410, 420), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (418, 420), True, 'import matplotlib.pyplot as plt\n'), ((502, 518), 'numpy.zeros', 'np.zeros', (['(100,)'], {}), '((100,))\n', (510, 518), True, 'import numpy as np\n')]
import numpy as np import vrep import ctypes import math import nengo vrep_mode = vrep.simx_opmode_oneshot def b( num ): """ forces magnitude to be 1 or less """ if abs( num ) > 1.0: return math.copysign( 1.0, num ) else: return num def convert_angles( ang ): """ Converts Euler angles from x-y-z to z-x-y convention """ s1 = math.sin(ang[0]) s2 = math.sin(ang[1]) s3 = math.sin(ang[2]) c1 = math.cos(ang[0]) c2 = math.cos(ang[1]) c3 = math.cos(ang[2]) pitch = math.asin( b(c1*c3*s2-s1*s3) ) cp = math.cos(pitch) # just in case if cp == 0: cp = 0.000001 yaw = math.asin( b((c1*s3+c3*s1*s2)/cp) ) #flipped # Fix for getting the quadrants right if c3 < 0 and yaw > 0: yaw = math.pi - yaw elif c3 < 0 and yaw < 0: yaw = -math.pi - yaw roll = math.asin( b((c3*s1+c1*s2*s3)/cp) ) #flipped return [roll, pitch, yaw] class Robot(object): def __init__(self, sim_dt=0.05, nengo_dt=0.001, sync=True): vrep.simxFinish(-1) # just in case, close all opened connections self.cid = vrep.simxStart('127.0.0.1',19997,True,True,5000,5) self.sync = sync if self.cid != -1: print ('Connected to V-REP remote API server, client id: %s' % self.cid) vrep.simxStartSimulation( self.cid, vrep.simx_opmode_oneshot ) if self.sync: vrep.simxSynchronous( self.cid, True ) else: print ('Failed connecting to V-REP remote API server') exit(1) self.count = 0 self.sim_dt = sim_dt self.nengo_dt = nengo_dt def handle_input(self, values): raise NotImplemented def handle_output(self): raise NotImplemented def __call__(self, t, values): self.count += 1 if self.count == int(round(self.sim_dt/self.nengo_dt)): self.count = 0 self.handle_input( values ) if self.sync: vrep.simxSynchronousTrigger( self.cid ) return self.handle_output() class CustomRobot(Robot): """ Sensors and actuators may be added to this component after it is created """ def __init__(self, sim_dt=0.01, nengo_dt=0.001, sync=True): super(CustomRobot, self).__init__(sim_dt, nengo_dt, sync) self.sensors = [] self.actuators = [] self.size_in = 0 self.size_out = 0 # Store the output here so it doesn't need to be generated for each # Nengo timestep, only for V-REP timesteps self.output = [] def handle_input(self, values): count = 0 for handle, func, dim in self.actuators: func(self.cid, handle, values[count:count+dim]) count += dim self.generate_output() def generate_output(self): ret = [] for handle, func in self.sensors: tmp = func(self.cid, handle) for i in tmp: ret.append(i) self.output = ret def handle_output(self): return self.output def add_sensor(self, name, func, dim=1): if name is None: handle = None else: err, handle = vrep.simxGetObjectHandle(self.cid, name, vrep.simx_opmode_oneshot_wait ) self.sensors.append([handle, func]) # This is needed so Nengo doesn't error on the first timestep self.output.extend([0]*dim) self.size_out += dim def add_actuator(self, name, func, dim=1): if name is None: handle = None else: err, handle = vrep.simxGetObjectHandle(self.cid, name, vrep.simx_opmode_oneshot_wait ) self.actuators.append([handle, func, dim]) self.size_in += dim def build_node(self): return nengo.Node(self, size_in=self.size_in, size_out=self.size_out) class Pendulum(Robot): def __init__(self): super(Pendulum, self).__init__() err, self.arm_joint = vrep.simxGetObjectHandle(self.cid, "arm_joint", vrep.simx_opmode_oneshot_wait ) def handle_input(self, values): # Set the velocity to some large number with the correct sign, # because v-rep is weird like that vrep.simxSetJointTargetVelocity(self.cid, self.arm_joint, values[0]*100, vrep.simx_opmode_oneshot) # Apply the desired torques to the joints # V-REP is looking for just the absolute value here vrep.simxSetJointForce(self.cid, self.arm_joint, abs(values[0]), vrep.simx_opmode_oneshot) def handle_output(self): err, arm_ori = vrep.simxGetJointPosition(self.cid, self.arm_joint, vrep.simx_opmode_oneshot) #2012 is the code for joint velocity err, arm_vel = vrep.simxGetObjectFloatParameter(self.cid, self.arm_joint, 2012, vrep.simx_opmode_oneshot) return [arm_ori, arm_vel] class Arm(Robot): def __init__(self, sim_dt=0.05): super(Arm, self).__init__(sim_dt) err, self.hand = vrep.simxGetObjectHandle(self.cid, "hand_end", vrep.simx_opmode_oneshot_wait ) err, self.target = vrep.simxGetObjectHandle(self.cid, "target", vrep.simx_opmode_oneshot_wait ) err, self.hand_joint = vrep.simxGetObjectHandle(self.cid, "hand_joint", vrep.simx_opmode_oneshot_wait ) err, self.arm_joint = vrep.simxGetObjectHandle(self.cid, "arm_joint", vrep.simx_opmode_oneshot_wait ) def handle_input(self, values): # Set the velocity to some large number with the correct sign, # because v-rep is weird like that vrep.simxSetJointTargetVelocity(self.cid, self.arm_joint, values[0]*100, vrep.simx_opmode_oneshot) vrep.simxSetJointTargetVelocity(self.cid, self.hand_joint, values[1]*100, vrep.simx_opmode_oneshot) # Apply the desired torques to the joints # V-REP is looking for just the absolute value here vrep.simxSetJointForce(self.cid, self.arm_joint, abs(values[0]), vrep.simx_opmode_oneshot) vrep.simxSetJointForce(self.cid, self.hand_joint, abs(values[1]), vrep.simx_opmode_oneshot) def handle_output(self): # return whatever state information you need to get the error you want # this will get you the information for the center of the object. If you # want something like the position of the end of an arm, you will need # to do some calculations, or just make a dummy object, attach it to # the point you want, and get the position of the dummy object #err, hand_pos = vrep.simxGetObjectPosition(self.cid, self.hand, -1, # vrep.simx_opmode_oneshot) #err, hand_ori = vrep.simxGetObjectOrientation(self.cid, self.hand, -1, # vrep.simx_opmode_oneshot) err, hand_ori = vrep.simxGetJointPosition(self.cid, self.hand_joint, vrep.simx_opmode_oneshot) err, arm_ori = vrep.simxGetJointPosition(self.cid, self.arm_joint, vrep.simx_opmode_oneshot) err, hand_vel = vrep.simxGetObjectFloatParameter(self.cid, self.hand_joint, 2012, vrep.simx_opmode_oneshot) err, arm_vel = vrep.simxGetObjectFloatParameter(self.cid, self.arm_joint, 2012, vrep.simx_opmode_oneshot) err, hand_pos = vrep.simxGetObjectPosition(self.cid, self.hand, -1, vrep.simx_opmode_oneshot) err, target_pos = vrep.simxGetObjectPosition(self.cid, self.target, -1, vrep.simx_opmode_oneshot) return [arm_ori, hand_ori, arm_vel, hand_vel, hand_pos[0], hand_pos[2], target_pos[0], target_pos[1]] class Quadcopter( Robot ): """ This callable class will return the state of the quadcopter relative to its target whenever it is called. It will also accept motor commands which will be sent to the quadcopter in V-REP. """ def __init__( self, sim_dt=0.01, max_target_distance=3, noise=False, noise_std=[0,0,0,0,0,0], target_func=None, ): super(Quadcopter, self).__init__(sim_dt) err, self.copter = vrep.simxGetObjectHandle(self.cid, "Quadricopter_base", vrep.simx_opmode_oneshot_wait ) err, self.target = vrep.simxGetObjectHandle(self.cid, "Quadricopter_target", vrep.simx_opmode_oneshot_wait ) # Reset the motor commands to zero packedData=vrep.simxPackFloats([0,0,0,0]) raw_bytes = (ctypes.c_ubyte * len(packedData)).from_buffer_copy(packedData) err = vrep.simxSetStringSignal(self.cid, "rotorTargetVelocities", raw_bytes, vrep_mode) self.pos = [0,0,0] self.pos_err = [0,0,0] self.t_pos = [0,0,0] self.lin = [0,0,0] self.ori = [0,0,0] self.ori_err = [0,0,0] self.t_ori = [0,0,0] self.ang = [0,0,0] self.vert_prox_dist = 0 self.left_prox_dist = 0 self.right_prox_dist = 0 # Distance reading recorded when nothing is in range self.max_vert_dist = 1.5 self.max_left_dist = 1.0 self.max_right_dist = 1.0 # Maximum target distance error that can be returned self.max_target_distance = max_target_distance # If noise is being modelled self.noise = noise # Standard Deviation of the noise for the 4 state variables self.noise_std = noise_std # Overwrite the get_target method if the target is to be controlled by a # function instead of by V-REP if target_func is not None: self.step = 0 self.target_func = target_func def get_target(): self.t_pos, self.t_ori = self.target_func( self.step ) self.step += 1 self.get_target = get_target def reset( self ): err = vrep.simxStopSimulation(self.cid, vrep.simx_opmode_oneshot_wait) time.sleep(1) self.pos_err = [0,0,0] self.ori_err = [0,0,0] self.lin = [0,0,0] self.ang = [0,0,0] self.vert_prox = 0 self.left_prox = 0 self.right_prox = 0 err = vrep.simxStartSimulation(self.cid, vrep.simx_opmode_oneshot_wait) if self.sync: vrep.simxSynchronous( self.cid, True ) def exit( self ): exit(1) def get_target( self ): err, self.t_ori = vrep.simxGetObjectOrientation(self.cid, self.target, -1, vrep_mode ) err, self.t_pos = vrep.simxGetObjectPosition(self.cid, self.target, -1, vrep_mode ) # Convert orientations to z-y-x convention self.t_ori = convert_angles(self.t_ori) def calculate_error( self ): # Return the state variables err, self.ori = vrep.simxGetObjectOrientation(self.cid, self.copter, -1, vrep_mode ) err, self.pos = vrep.simxGetObjectPosition(self.cid, self.copter, -1, vrep_mode ) err, self.lin, self.ang = vrep.simxGetObjectVelocity(self.cid, self.copter, vrep_mode ) self.ori = convert_angles(self.ori) # Apply noise to each measurement if required if self.noise: self.pos += np.random.normal(0,self.noise_std[0],3) self.lin += np.random.normal(0,self.noise_std[1],3) self.ori += np.random.normal(0,self.noise_std[2],3) self.ang += np.random.normal(0,self.noise_std[3],3) #TODO: might have to wrap angles here # Find the error self.ori_err = [self.t_ori[0] - self.ori[0], self.t_ori[1] - self.ori[1], self.t_ori[2] - self.ori[2]] cz = math.cos(self.ori[2]) sz = math.sin(self.ori[2]) x_err = self.t_pos[0] - self.pos[0] y_err = self.t_pos[1] - self.pos[1] self.pos_err = [ x_err * cz + y_err * sz, -x_err * sz + y_err * cz, self.t_pos[2] - self.pos[2]] self.lin = [self.lin[0]*cz+self.lin[1]*sz, -self.lin[0]*sz+self.lin[1]*cz, self.lin[2]] self.ang = [self.ang[0]*cz+self.ang[1]*sz, -self.ang[0]*sz+self.ang[1]*cz, self.ang[2]] for i in range(3): if self.ori_err[i] > math.pi: self.ori_err[i] -= 2 * math.pi elif self.ori_err[i] < -math.pi: self.ori_err[i] += 2 * math.pi def send_motor_commands( self, values ): motor_values = np.zeros(4) for i in range(4): motor_values[i] = values[i] packedData=vrep.simxPackFloats(motor_values.flatten()) raw_bytes = (ctypes.c_ubyte * len(packedData)).from_buffer_copy(packedData) err = vrep.simxSetStringSignal(self.cid, "rotorTargetVelocities", raw_bytes, vrep_mode) def handle_input( self, values ): # Send motor commands to V-REP self.send_motor_commands( values ) # Retrieve target location self.get_target() # Calculate state error self.calculate_error() def bound( self, value ): if abs( value ) > self.max_target_distance: return math.copysign( self.max_target_distance, value ) else: return value def handle_output( self ): l = math.sqrt(self.pos_err[0]**2 + self.pos_err[1]**2) bl = self.bound(l) r = (bl+.1)/(l+.1) return [r*self.pos_err[0], r*self.pos_err[1], self.bound(self.pos_err[2]), self.lin[0], self.lin[1], self.lin[2], self.ori_err[0], self.ori_err[1], self.ori_err[2], self.ang[0], self.ang[1], self.ang[2], ] class SensorQuadcopter( Quadcopter ): def __init__( self, *args, **kwargs ): super(SensorQuadcopter, self).__init__(*args, **kwargs) err, self.vert_prox = vrep.simxGetObjectHandle(self.cid, "vert_prox", vrep.simx_opmode_oneshot_wait ) err, self.left_prox = vrep.simxGetObjectHandle(self.cid, "left_prox", vrep.simx_opmode_oneshot_wait ) err, self.right_prox = vrep.simxGetObjectHandle(self.cid, "right_prox", vrep.simx_opmode_oneshot_wait ) def read_proximity( self ): err, state, point, handle, normal = vrep.simxReadProximitySensor(self.cid, self.vert_prox, vrep_mode) if state: self.vert_prox_dist = point[2] else: self.vert_prox_dist = self.max_vert_dist err, state, point, handle, normal =\ vrep.simxReadProximitySensor(self.cid, self.left_prox, vrep_mode) if state: self.left_prox_dist = point[2] else: self.left_prox_dist = self.max_left_dist err, state, point, handle, normal =\ vrep.simxReadProximitySensor(self.cid, self.right_prox, vrep_mode) if state: self.right_prox_dist = point[2] else: self.right_prox_dist = self.max_right_dist def handle_input( self, values ): # Send motor commands to V-REP self.send_motor_commands( values ) # Retrieve target location self.get_target() # Calculate state error self.calculate_error() # Get proximity sensor readings self.read_proximity() def handle_output( self ): l = math.sqrt(self.pos_err[0]**2 + self.pos_err[1]**2) bl = self.bound(l) r = (bl+.1)/(l+.1) return [r*self.pos_err[0], r*self.pos_err[1], self.bound(self.pos_err[2]), self.lin[0], self.lin[1], self.lin[2], self.ori_err[0], self.ori_err[1], self.ori_err[2], self.ang[0], self.ang[1], self.ang[2], self.vert_prox_dist, self.left_prox_dist, self.right_prox_dist, ] class TargetQuadcopter( Quadcopter ): """ Returns target position as well """ def __init__( self, *args, **kwargs ): super(TargetQuadcopter, self).__init__(*args, **kwargs) def handle_output( self ): l = math.sqrt(self.pos_err[0]**2 + self.pos_err[1]**2) bl = self.bound(l) r = (bl+.1)/(l+.1) return [r*self.pos_err[0], r*self.pos_err[1], self.bound(self.pos_err[2]), self.lin[0], self.lin[1], self.lin[2], self.ori_err[0], self.ori_err[1], self.ori_err[2], self.ang[0], self.ang[1], self.ang[2], self.t_pos[0], self.t_pos[1], self.t_pos[2], self.t_ori[0], self.t_ori[1], self.t_ori[2], ] class WaypointQuadcopter( Quadcopter ): """ Takes the desired target as an input rather than moving to the green circle """ def __init__( self, sim_dt=0.01, max_target_distance=3, noise=False, noise_std=[0,0,0,0,0,0], ): # Call the superclass of Quadcopter, which is Robot super(Quadcopter, self).__init__(sim_dt) err, self.copter = vrep.simxGetObjectHandle(self.cid, "Quadricopter_base", vrep.simx_opmode_oneshot_wait ) # Reset the motor commands to zero packedData=vrep.simxPackFloats([0,0,0,0]) raw_bytes = (ctypes.c_ubyte * len(packedData)).from_buffer_copy(packedData) err = vrep.simxSetStringSignal(self.cid, "rotorTargetVelocities", raw_bytes, vrep_mode) self.pos = [0,0,0] self.pos_err = [0,0,0] self.t_pos = [0,0,0] self.lin = [0,0,0] self.ori = [0,0,0] self.ori_err = [0,0,0] self.t_ori = [0,0,0] self.ang = [0,0,0] # Maximum target distance error that can be returned self.max_target_distance = max_target_distance # If noise is being modelled self.noise = noise # Standard Deviation of the noise for the 4 state variables self.noise_std = noise_std def handle_input( self, values ): # Send motor commands to V-REP self.send_motor_commands( values[:4] ) # Retrieve target location self.t_pos = values[[4,5,6]] self.t_ori = values[[7,8,9]] # Calculate state error self.calculate_error()
[ "vrep.simxGetObjectVelocity", "vrep.simxSynchronousTrigger", "math.copysign", "vrep.simxStart", "numpy.random.normal", "vrep.simxSynchronous", "vrep.simxGetObjectHandle", "vrep.simxSetStringSignal", "nengo.Node", "vrep.simxGetJointPosition", "math.cos", "vrep.simxSetJointTargetVelocity", "vr...
[((347, 363), 'math.sin', 'math.sin', (['ang[0]'], {}), '(ang[0])\n', (355, 363), False, 'import math\n'), ((371, 387), 'math.sin', 'math.sin', (['ang[1]'], {}), '(ang[1])\n', (379, 387), False, 'import math\n'), ((395, 411), 'math.sin', 'math.sin', (['ang[2]'], {}), '(ang[2])\n', (403, 411), False, 'import math\n'), ((419, 435), 'math.cos', 'math.cos', (['ang[0]'], {}), '(ang[0])\n', (427, 435), False, 'import math\n'), ((443, 459), 'math.cos', 'math.cos', (['ang[1]'], {}), '(ang[1])\n', (451, 459), False, 'import math\n'), ((467, 483), 'math.cos', 'math.cos', (['ang[2]'], {}), '(ang[2])\n', (475, 483), False, 'import math\n'), ((535, 550), 'math.cos', 'math.cos', (['pitch'], {}), '(pitch)\n', (543, 550), False, 'import math\n'), ((200, 223), 'math.copysign', 'math.copysign', (['(1.0)', 'num'], {}), '(1.0, num)\n', (213, 223), False, 'import math\n'), ((974, 993), 'vrep.simxFinish', 'vrep.simxFinish', (['(-1)'], {}), '(-1)\n', (989, 993), False, 'import vrep\n'), ((1058, 1113), 'vrep.simxStart', 'vrep.simxStart', (['"""127.0.0.1"""', '(19997)', '(True)', '(True)', '(5000)', '(5)'], {}), "('127.0.0.1', 19997, True, True, 5000, 5)\n", (1072, 1113), False, 'import vrep\n'), ((3864, 3926), 'nengo.Node', 'nengo.Node', (['self'], {'size_in': 'self.size_in', 'size_out': 'self.size_out'}), '(self, size_in=self.size_in, size_out=self.size_out)\n', (3874, 3926), False, 'import nengo\n'), ((4056, 4134), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""arm_joint"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'arm_joint', vrep.simx_opmode_oneshot_wait)\n", (4080, 4134), False, 'import vrep\n'), ((4347, 4451), 'vrep.simxSetJointTargetVelocity', 'vrep.simxSetJointTargetVelocity', (['self.cid', 'self.arm_joint', '(values[0] * 100)', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.arm_joint, values[0] * 100,\n vrep.simx_opmode_oneshot)\n', (4378, 4451), False, 'import vrep\n'), ((4789, 4866), 'vrep.simxGetJointPosition', 'vrep.simxGetJointPosition', (['self.cid', 'self.arm_joint', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.arm_joint, vrep.simx_opmode_oneshot)\n', (4814, 4866), False, 'import vrep\n'), ((4986, 5081), 'vrep.simxGetObjectFloatParameter', 'vrep.simxGetObjectFloatParameter', (['self.cid', 'self.arm_joint', '(2012)', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.arm_joint, 2012, vrep.\n simx_opmode_oneshot)\n', (5018, 5081), False, 'import vrep\n'), ((5349, 5426), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""hand_end"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'hand_end', vrep.simx_opmode_oneshot_wait)\n", (5373, 5426), False, 'import vrep\n'), ((5503, 5578), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""target"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'target', vrep.simx_opmode_oneshot_wait)\n", (5527, 5578), False, 'import vrep\n'), ((5659, 5738), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""hand_joint"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'hand_joint', vrep.simx_opmode_oneshot_wait)\n", (5683, 5738), False, 'import vrep\n'), ((5818, 5896), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""arm_joint"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'arm_joint', vrep.simx_opmode_oneshot_wait)\n", (5842, 5896), False, 'import vrep\n'), ((6113, 6217), 'vrep.simxSetJointTargetVelocity', 'vrep.simxSetJointTargetVelocity', (['self.cid', 'self.arm_joint', '(values[0] * 100)', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.arm_joint, values[0] * 100,\n vrep.simx_opmode_oneshot)\n', (6144, 6217), False, 'import vrep\n'), ((6261, 6366), 'vrep.simxSetJointTargetVelocity', 'vrep.simxSetJointTargetVelocity', (['self.cid', 'self.hand_joint', '(values[1] * 100)', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.hand_joint, values[1] * 100,\n vrep.simx_opmode_oneshot)\n', (6292, 6366), False, 'import vrep\n'), ((7555, 7633), 'vrep.simxGetJointPosition', 'vrep.simxGetJointPosition', (['self.cid', 'self.hand_joint', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.hand_joint, vrep.simx_opmode_oneshot)\n', (7580, 7633), False, 'import vrep\n'), ((7708, 7785), 'vrep.simxGetJointPosition', 'vrep.simxGetJointPosition', (['self.cid', 'self.arm_joint', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.arm_joint, vrep.simx_opmode_oneshot)\n', (7733, 7785), False, 'import vrep\n'), ((7861, 7957), 'vrep.simxGetObjectFloatParameter', 'vrep.simxGetObjectFloatParameter', (['self.cid', 'self.hand_joint', '(2012)', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.hand_joint, 2012, vrep.\n simx_opmode_oneshot)\n', (7893, 7957), False, 'import vrep\n'), ((8033, 8128), 'vrep.simxGetObjectFloatParameter', 'vrep.simxGetObjectFloatParameter', (['self.cid', 'self.arm_joint', '(2012)', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.arm_joint, 2012, vrep.\n simx_opmode_oneshot)\n', (8065, 8128), False, 'import vrep\n'), ((8204, 8281), 'vrep.simxGetObjectPosition', 'vrep.simxGetObjectPosition', (['self.cid', 'self.hand', '(-1)', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.hand, -1, vrep.simx_opmode_oneshot)\n', (8230, 8281), False, 'import vrep\n'), ((8359, 8438), 'vrep.simxGetObjectPosition', 'vrep.simxGetObjectPosition', (['self.cid', 'self.target', '(-1)', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, self.target, -1, vrep.simx_opmode_oneshot)\n', (8385, 8438), False, 'import vrep\n'), ((9110, 9201), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""Quadricopter_base"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'Quadricopter_base', vrep.\n simx_opmode_oneshot_wait)\n", (9134, 9201), False, 'import vrep\n'), ((9273, 9366), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""Quadricopter_target"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'Quadricopter_target', vrep.\n simx_opmode_oneshot_wait)\n", (9297, 9366), False, 'import vrep\n'), ((9474, 9507), 'vrep.simxPackFloats', 'vrep.simxPackFloats', (['[0, 0, 0, 0]'], {}), '([0, 0, 0, 0])\n', (9493, 9507), False, 'import vrep\n'), ((9605, 9690), 'vrep.simxSetStringSignal', 'vrep.simxSetStringSignal', (['self.cid', '"""rotorTargetVelocities"""', 'raw_bytes', 'vrep_mode'], {}), "(self.cid, 'rotorTargetVelocities', raw_bytes,\n vrep_mode)\n", (9629, 9690), False, 'import vrep\n'), ((11001, 11065), 'vrep.simxStopSimulation', 'vrep.simxStopSimulation', (['self.cid', 'vrep.simx_opmode_oneshot_wait'], {}), '(self.cid, vrep.simx_opmode_oneshot_wait)\n', (11024, 11065), False, 'import vrep\n'), ((11300, 11365), 'vrep.simxStartSimulation', 'vrep.simxStartSimulation', (['self.cid', 'vrep.simx_opmode_oneshot_wait'], {}), '(self.cid, vrep.simx_opmode_oneshot_wait)\n', (11324, 11365), False, 'import vrep\n'), ((11535, 11602), 'vrep.simxGetObjectOrientation', 'vrep.simxGetObjectOrientation', (['self.cid', 'self.target', '(-1)', 'vrep_mode'], {}), '(self.cid, self.target, -1, vrep_mode)\n', (11564, 11602), False, 'import vrep\n'), ((11682, 11746), 'vrep.simxGetObjectPosition', 'vrep.simxGetObjectPosition', (['self.cid', 'self.target', '(-1)', 'vrep_mode'], {}), '(self.cid, self.target, -1, vrep_mode)\n', (11708, 11746), False, 'import vrep\n'), ((11999, 12066), 'vrep.simxGetObjectOrientation', 'vrep.simxGetObjectOrientation', (['self.cid', 'self.copter', '(-1)', 'vrep_mode'], {}), '(self.cid, self.copter, -1, vrep_mode)\n', (12028, 12066), False, 'import vrep\n'), ((12140, 12204), 'vrep.simxGetObjectPosition', 'vrep.simxGetObjectPosition', (['self.cid', 'self.copter', '(-1)', 'vrep_mode'], {}), '(self.cid, self.copter, -1, vrep_mode)\n', (12166, 12204), False, 'import vrep\n'), ((12284, 12344), 'vrep.simxGetObjectVelocity', 'vrep.simxGetObjectVelocity', (['self.cid', 'self.copter', 'vrep_mode'], {}), '(self.cid, self.copter, vrep_mode)\n', (12310, 12344), False, 'import vrep\n'), ((13048, 13069), 'math.cos', 'math.cos', (['self.ori[2]'], {}), '(self.ori[2])\n', (13056, 13069), False, 'import math\n'), ((13083, 13104), 'math.sin', 'math.sin', (['self.ori[2]'], {}), '(self.ori[2])\n', (13091, 13104), False, 'import math\n'), ((13817, 13828), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (13825, 13828), True, 'import numpy as np\n'), ((14056, 14141), 'vrep.simxSetStringSignal', 'vrep.simxSetStringSignal', (['self.cid', '"""rotorTargetVelocities"""', 'raw_bytes', 'vrep_mode'], {}), "(self.cid, 'rotorTargetVelocities', raw_bytes,\n vrep_mode)\n", (14080, 14141), False, 'import vrep\n'), ((14708, 14762), 'math.sqrt', 'math.sqrt', (['(self.pos_err[0] ** 2 + self.pos_err[1] ** 2)'], {}), '(self.pos_err[0] ** 2 + self.pos_err[1] ** 2)\n', (14717, 14762), False, 'import math\n'), ((15285, 15363), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""vert_prox"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'vert_prox', vrep.simx_opmode_oneshot_wait)\n", (15309, 15363), False, 'import vrep\n'), ((15443, 15521), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""left_prox"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'left_prox', vrep.simx_opmode_oneshot_wait)\n", (15467, 15521), False, 'import vrep\n'), ((15602, 15681), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""right_prox"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'right_prox', vrep.simx_opmode_oneshot_wait)\n", (15626, 15681), False, 'import vrep\n'), ((15809, 15874), 'vrep.simxReadProximitySensor', 'vrep.simxReadProximitySensor', (['self.cid', 'self.vert_prox', 'vrep_mode'], {}), '(self.cid, self.vert_prox, vrep_mode)\n', (15837, 15874), False, 'import vrep\n'), ((16057, 16122), 'vrep.simxReadProximitySensor', 'vrep.simxReadProximitySensor', (['self.cid', 'self.left_prox', 'vrep_mode'], {}), '(self.cid, self.left_prox, vrep_mode)\n', (16085, 16122), False, 'import vrep\n'), ((16313, 16379), 'vrep.simxReadProximitySensor', 'vrep.simxReadProximitySensor', (['self.cid', 'self.right_prox', 'vrep_mode'], {}), '(self.cid, self.right_prox, vrep_mode)\n', (16341, 16379), False, 'import vrep\n'), ((16882, 16936), 'math.sqrt', 'math.sqrt', (['(self.pos_err[0] ** 2 + self.pos_err[1] ** 2)'], {}), '(self.pos_err[0] ** 2 + self.pos_err[1] ** 2)\n', (16891, 16936), False, 'import math\n'), ((17593, 17647), 'math.sqrt', 'math.sqrt', (['(self.pos_err[0] ** 2 + self.pos_err[1] ** 2)'], {}), '(self.pos_err[0] ** 2 + self.pos_err[1] ** 2)\n', (17602, 17647), False, 'import math\n'), ((18513, 18604), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', '"""Quadricopter_base"""', 'vrep.simx_opmode_oneshot_wait'], {}), "(self.cid, 'Quadricopter_base', vrep.\n simx_opmode_oneshot_wait)\n", (18537, 18604), False, 'import vrep\n'), ((18712, 18745), 'vrep.simxPackFloats', 'vrep.simxPackFloats', (['[0, 0, 0, 0]'], {}), '([0, 0, 0, 0])\n', (18731, 18745), False, 'import vrep\n'), ((18843, 18928), 'vrep.simxSetStringSignal', 'vrep.simxSetStringSignal', (['self.cid', '"""rotorTargetVelocities"""', 'raw_bytes', 'vrep_mode'], {}), "(self.cid, 'rotorTargetVelocities', raw_bytes,\n vrep_mode)\n", (18867, 18928), False, 'import vrep\n'), ((1259, 1319), 'vrep.simxStartSimulation', 'vrep.simxStartSimulation', (['self.cid', 'vrep.simx_opmode_oneshot'], {}), '(self.cid, vrep.simx_opmode_oneshot)\n', (1283, 1319), False, 'import vrep\n'), ((3164, 3235), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', 'name', 'vrep.simx_opmode_oneshot_wait'], {}), '(self.cid, name, vrep.simx_opmode_oneshot_wait)\n', (3188, 3235), False, 'import vrep\n'), ((3619, 3690), 'vrep.simxGetObjectHandle', 'vrep.simxGetObjectHandle', (['self.cid', 'name', 'vrep.simx_opmode_oneshot_wait'], {}), '(self.cid, name, vrep.simx_opmode_oneshot_wait)\n', (3643, 3690), False, 'import vrep\n'), ((11398, 11434), 'vrep.simxSynchronous', 'vrep.simxSynchronous', (['self.cid', '(True)'], {}), '(self.cid, True)\n', (11418, 11434), False, 'import vrep\n'), ((12567, 12608), 'numpy.random.normal', 'np.random.normal', (['(0)', 'self.noise_std[0]', '(3)'], {}), '(0, self.noise_std[0], 3)\n', (12583, 12608), True, 'import numpy as np\n'), ((12629, 12670), 'numpy.random.normal', 'np.random.normal', (['(0)', 'self.noise_std[1]', '(3)'], {}), '(0, self.noise_std[1], 3)\n', (12645, 12670), True, 'import numpy as np\n'), ((12691, 12732), 'numpy.random.normal', 'np.random.normal', (['(0)', 'self.noise_std[2]', '(3)'], {}), '(0, self.noise_std[2], 3)\n', (12707, 12732), True, 'import numpy as np\n'), ((12753, 12794), 'numpy.random.normal', 'np.random.normal', (['(0)', 'self.noise_std[3]', '(3)'], {}), '(0, self.noise_std[3], 3)\n', (12769, 12794), True, 'import numpy as np\n'), ((14578, 14624), 'math.copysign', 'math.copysign', (['self.max_target_distance', 'value'], {}), '(self.max_target_distance, value)\n', (14591, 14624), False, 'import math\n'), ((1362, 1398), 'vrep.simxSynchronous', 'vrep.simxSynchronous', (['self.cid', '(True)'], {}), '(self.cid, True)\n', (1382, 1398), False, 'import vrep\n'), ((1943, 1980), 'vrep.simxSynchronousTrigger', 'vrep.simxSynchronousTrigger', (['self.cid'], {}), '(self.cid)\n', (1970, 1980), False, 'import vrep\n')]
# coding: utf-8 # In[3]: import numpy as np import cv2 # In[1]: def draw_lines(undist,M_inv,warped,left_fitx,right_fitx,ploty): # Create an image to draw the lines on warp_zero = np.zeros_like(warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) pts = None result = undist # Recast the x and y points into usable format for cv2.fillPoly() if left_fitx is not None and len(left_fitx)> 0 and right_fitx is not None and len(right_fitx)>0: pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))]) pts = np.hstack((pts_left, pts_right)) if pts is not None and len(pts) > 0: # Draw the lane onto the warped blank image cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0)) # Warp the blank back to original image space using inverse perspective matrix (Minv) newwarp = cv2.warpPerspective(color_warp, M_inv, (undist.shape[1], undist.shape[0])) # Combine the result with the original image result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0) return result
[ "numpy.dstack", "cv2.warpPerspective", "numpy.zeros_like", "numpy.int_", "cv2.addWeighted", "numpy.hstack", "numpy.vstack" ]
[((249, 293), 'numpy.dstack', 'np.dstack', (['(warp_zero, warp_zero, warp_zero)'], {}), '((warp_zero, warp_zero, warp_zero))\n', (258, 293), True, 'import numpy as np\n'), ((678, 710), 'numpy.hstack', 'np.hstack', (['(pts_left, pts_right)'], {}), '((pts_left, pts_right))\n', (687, 710), True, 'import numpy as np\n'), ((979, 1053), 'cv2.warpPerspective', 'cv2.warpPerspective', (['color_warp', 'M_inv', '(undist.shape[1], undist.shape[0])'], {}), '(color_warp, M_inv, (undist.shape[1], undist.shape[0]))\n', (998, 1053), False, 'import cv2\n'), ((1125, 1168), 'cv2.addWeighted', 'cv2.addWeighted', (['undist', '(1)', 'newwarp', '(0.3)', '(0)'], {}), '(undist, 1, newwarp, 0.3, 0)\n', (1140, 1168), False, 'import cv2\n'), ((193, 214), 'numpy.zeros_like', 'np.zeros_like', (['warped'], {}), '(warped)\n', (206, 214), True, 'import numpy as np\n'), ((838, 852), 'numpy.int_', 'np.int_', (['[pts]'], {}), '([pts])\n', (845, 852), True, 'import numpy as np\n'), ((543, 572), 'numpy.vstack', 'np.vstack', (['[left_fitx, ploty]'], {}), '([left_fitx, ploty])\n', (552, 572), True, 'import numpy as np\n'), ((629, 659), 'numpy.vstack', 'np.vstack', (['[right_fitx, ploty]'], {}), '([right_fitx, ploty])\n', (638, 659), True, 'import numpy as np\n')]
#!/usr/bin/env python ''' ''' import numpy as np from .radar_controller import RadarController class Scanner(RadarController): '''Takes in a scan and create a scanning radar controller. ''' META_FIELDS = RadarController.META_FIELDS + [ 'scan_type', 'dwell', ] def __init__(self, radar, scan, r=np.linspace(300e3,1000e3,num=10), profiler=None, logger=None, return_copy=False, meta=None, **kwargs): super().__init__(radar, profiler=profiler, logger=logger, meta=meta) self.scan = scan self.r = r self.return_copy = return_copy if self.logger is not None: self.logger.info(f'Scanner:init') def default_meta(self): dic = super().default_meta() dic['scan_type'] = self.scan.__class__ return dic def point_radar(self, t): '''Assumes t is not array ''' if self.profiler is not None: self.profiler.start('Scanner:generator:point_radar') if self.return_copy: radar = self.radar.copy() else: radar = self.radar meta = self.default_meta() meta['dwell'] = self.scan.dwell(t) point_rx_to_tx = [] point_tx = [] for tx in radar.tx: point = self.scan.ecef_pointing(t, tx) if len(point.shape) > 1: point_tx.append(point + tx.ecef[:,None]) __ptx = point[:,:,None]*self.r[None,None,:] + tx.ecef[:,None,None] point_rx_to_tx.append(__ptx.reshape(3, __ptx.shape[1]*__ptx.shape[2])) else: point_tx.append(point + tx.ecef) point_rx_to_tx.append(point[:,None]*self.r[None,:] + tx.ecef[:,None]) if self.profiler is not None: self.profiler.start('Scanner:generator:point_radar:_point_station[tx]') RadarController._point_station(tx, point_tx[-1]) if self.profiler is not None: self.profiler.stop('Scanner:generator:point_radar:_point_station[tx]') for rx in radar.rx: rx_point = [] for txi, tx in enumerate(radar.tx): #< 200 meters apart = same location for pointing if np.linalg.norm(tx.ecef - rx.ecef) < 200.0: __ptx = point_tx[txi] if len(__ptx.shape) == 1: __ptx = __ptx.reshape(3,1) rx_point.append(__ptx) else: rx_point.append(point_rx_to_tx[txi]) rx_point = np.concatenate(rx_point, axis=1) if self.profiler is not None: self.profiler.start('Scanner:generator:point_radar:_point_station[rx]') RadarController._point_station(rx, rx_point) if self.profiler is not None: self.profiler.stop('Scanner:generator:point_radar:_point_station[rx]') if self.profiler is not None: self.profiler.stop('Scanner:generator:point_radar') return radar, meta def generator(self, t): for ti in range(len(t)): yield self.point_radar(t[ti])
[ "numpy.linalg.norm", "numpy.concatenate", "numpy.linspace" ]
[((338, 378), 'numpy.linspace', 'np.linspace', (['(300000.0)', '(1000000.0)'], {'num': '(10)'}), '(300000.0, 1000000.0, num=10)\n', (349, 378), True, 'import numpy as np\n'), ((2591, 2623), 'numpy.concatenate', 'np.concatenate', (['rx_point'], {'axis': '(1)'}), '(rx_point, axis=1)\n', (2605, 2623), True, 'import numpy as np\n'), ((2264, 2297), 'numpy.linalg.norm', 'np.linalg.norm', (['(tx.ecef - rx.ecef)'], {}), '(tx.ecef - rx.ecef)\n', (2278, 2297), True, 'import numpy as np\n')]
""" Maps: Parametrized Layer ======================== Build a model of a parametrized layer in a wholespace. If you want to build a model of a parametrized layer in a halfspace, also use Maps.InjectActiveCell. The model is .. code:: m = [ 'background physical property value', 'layer physical property value', 'layer center', 'layer thickness' ] """ from SimPEG import Mesh, Maps import numpy as np import matplotlib.pyplot as plt def run(plotIt=True): mesh = Mesh.TensorMesh([50, 50], x0='CC') # 2D tensor mesh mapping = Maps.ParametricLayer(mesh) # parametric layer in wholespace # model m = np.hstack( np.r_[ 1., # background value 2., # layer value -0.1, # layer center 0.2 # layer thickness ] ) rho = mapping * m # apply the mapping if plotIt is True: fig, ax = plt.subplots(1, 1, figsize=(4, 6)) mesh.plotImage(rho, ax=ax) if __name__ == '__main__': run() plt.show()
[ "matplotlib.pyplot.show", "SimPEG.Mesh.TensorMesh", "numpy.hstack", "matplotlib.pyplot.subplots", "SimPEG.Maps.ParametricLayer" ]
[((511, 545), 'SimPEG.Mesh.TensorMesh', 'Mesh.TensorMesh', (['[50, 50]'], {'x0': '"""CC"""'}), "([50, 50], x0='CC')\n", (526, 545), False, 'from SimPEG import Mesh, Maps\n'), ((578, 604), 'SimPEG.Maps.ParametricLayer', 'Maps.ParametricLayer', (['mesh'], {}), '(mesh)\n', (598, 604), False, 'from SimPEG import Mesh, Maps\n'), ((660, 697), 'numpy.hstack', 'np.hstack', (['np.r_[1.0, 2.0, -0.1, 0.2]'], {}), '(np.r_[1.0, 2.0, -0.1, 0.2])\n', (669, 697), True, 'import numpy as np\n'), ((1030, 1040), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1038, 1040), True, 'import matplotlib.pyplot as plt\n'), ((918, 952), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'figsize': '(4, 6)'}), '(1, 1, figsize=(4, 6))\n', (930, 952), True, 'import matplotlib.pyplot as plt\n')]
#!/usr/bin/env python import yaml import triangle import numpy as np f = open("config.yaml") config = yaml.load(f) f.close() flatchain = np.load(config["TlL_samples"]) labels = [r"$T_\textrm{eff}$ [K]", r"$\log_{10} L\; [L_\odot]$"] figure = triangle.corner(flatchain, quantiles=[0.16, 0.5, 0.84], plot_contours=True, plot_datapoints=False, labels=labels, show_titles=True) figure.savefig("triangle_TLl.png")
[ "triangle.corner", "yaml.load", "numpy.load" ]
[((104, 116), 'yaml.load', 'yaml.load', (['f'], {}), '(f)\n', (113, 116), False, 'import yaml\n'), ((140, 170), 'numpy.load', 'np.load', (["config['TlL_samples']"], {}), "(config['TlL_samples'])\n", (147, 170), True, 'import numpy as np\n'), ((248, 383), 'triangle.corner', 'triangle.corner', (['flatchain'], {'quantiles': '[0.16, 0.5, 0.84]', 'plot_contours': '(True)', 'plot_datapoints': '(False)', 'labels': 'labels', 'show_titles': '(True)'}), '(flatchain, quantiles=[0.16, 0.5, 0.84], plot_contours=True,\n plot_datapoints=False, labels=labels, show_titles=True)\n', (263, 383), False, 'import triangle\n')]
import logging import collections import numpy as np import torch from torch import nn from torch import optim from . import agent from ..tools import flag_tools class DqnAgent(agent.Agent): def _build_model(self): cfg = self._model_cfg self._model = cfg.model_factory() self._model.to(device=self._device) self._q_fn_learning = self._model.q_fn_learning self._q_fn_target = self._model.q_fn_target self._q_fn_target.load_state_dict( self._q_fn_learning.state_dict()) self._vars_learning = self._q_fn_learning.state_dict() self._vars_target = self._q_fn_target.state_dict() def _build_optimizer(self): cfg = self._optimizer_cfg self._optimizer = cfg.optimizer_factory( self._q_fn_learning.parameters()) def _build_loss(self, batch): # modules and tensors s1 = batch.s1 s2 = batch.s2 a = batch.a r = batch.r dsc = batch.dsc batch_size = a.shape[0] ###################### # networks q_vals_learning = self._q_fn_learning(s1) q_val_learning = q_vals_learning[torch.arange(batch_size), a] q_vals_target = self._q_fn_target(s2) val_target = q_vals_target.max(-1)[0] q_val_target = (r + dsc * val_target).detach() loss = (q_val_learning - q_val_target).pow(2).mean() # build print info info = self._train_info info['q_loss'] = loss.item() info['mean_q'] = q_val_target.mean().item() info['min_q'] = q_val_target.min().item() info['max_q'] = q_val_target.max().item() info['mean_r'] = r.mean().item() info['mean_dsc'] = dsc.mean().item() # # for i, w in enumerate(self._q_fn_learning.parameters()): # print(i, w.sum().item()) return loss def _policy_fn(self, state): time_step, _ = state s = np.expand_dims(self._obs_prepro(time_step.observation), 0) s = self._tensor(s) with torch.no_grad(): q_vals = self._q_fn_learning(s).cpu().numpy() return q_vals[0] def _train_policy_fn(self, state): # epsilon greedy q_vals = self._policy_fn(state) eps = self._actor_cfg.epsilon_greedy if np.random.uniform() <= eps: a = self._action_spec.sample() else: a = np.argmax(q_vals) return a, None def _test_policy_fn(self, state): q_vals = self._policy_fn(state) return np.argmax(q_vals), None def save_ckpt(self, filepath): torch.save(self._model.state_dict(), filepath) class DqnAgentModel(nn.Module): def __init__(self, q_model_factory): super().__init__() self.q_fn_learning = q_model_factory() self.q_fn_target = q_model_factory() class DqnAgentConfig(agent.AgentConfig): def _set_default_flags(self): super()._set_default_flags() flags = self._flags flags.actor_cfg = flag_tools.Flags(epsilon_greedy=0.2) flags.opt_args = flag_tools.Flags(name='Adam', lr=0.001) def _q_model_factory(self): raise NotImplementedError def _model_factory(self): return DqnAgentModel(self._q_model_factory) def _optimizer_factory(self, parameters): opt = getattr(optim, self._flags.opt_args.name) opt_fn = opt(parameters, lr=self._flags.opt_args.lr) return opt_fn
[ "numpy.random.uniform", "torch.no_grad", "torch.arange", "numpy.argmax" ]
[((2070, 2085), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2083, 2085), False, 'import torch\n'), ((2331, 2350), 'numpy.random.uniform', 'np.random.uniform', ([], {}), '()\n', (2348, 2350), True, 'import numpy as np\n'), ((2432, 2449), 'numpy.argmax', 'np.argmax', (['q_vals'], {}), '(q_vals)\n', (2441, 2449), True, 'import numpy as np\n'), ((2567, 2584), 'numpy.argmax', 'np.argmax', (['q_vals'], {}), '(q_vals)\n', (2576, 2584), True, 'import numpy as np\n'), ((1187, 1211), 'torch.arange', 'torch.arange', (['batch_size'], {}), '(batch_size)\n', (1199, 1211), False, 'import torch\n')]
import functools import json import pickle from collections import defaultdict from multiprocessing import Pool from typing import Dict, List, Optional, Tuple, Union import click import numpy import rich from click_option_group import optgroup from nagl.utilities.toolkits import capture_toolkit_warnings from openff.recharge.charges.bcc import BCCCollection, BCCGenerator from openff.recharge.charges.library import ( LibraryChargeCollection, LibraryChargeGenerator, LibraryChargeParameter, ) from openff.recharge.charges.qc import QCChargeGenerator, QCChargeSettings from openff.recharge.charges.vsite import VirtualSiteCollection, VirtualSiteGenerator from openff.recharge.conformers import ConformerGenerator, ConformerSettings from openff.recharge.esp.storage import MoleculeESPRecord from openff.recharge.utilities.geometry import compute_inverse_distance_matrix from openff.recharge.utilities.molecule import extract_conformers from openff.toolkit.topology import Molecule from openff.units import unit from pydantic import parse_file_as from rich.progress import track _CACHED_CHARGES = {} def compute_base_charge( molecule: Molecule, conformer_settings: ConformerSettings, charge_settings: QCChargeSettings, ): tagged_smiles = molecule.to_smiles(mapped=True) if tagged_smiles in _CACHED_CHARGES: return _CACHED_CHARGES[tagged_smiles] conformers = ConformerGenerator.generate(molecule, conformer_settings) charges = QCChargeGenerator.generate(molecule, conformers, charge_settings) charge_collection = LibraryChargeCollection( parameters=[ LibraryChargeParameter( smiles=tagged_smiles, value=[float(v) for v in charges.flatten().tolist()], ) ] ) _CACHED_CHARGES[tagged_smiles] = charge_collection return charge_collection def compute_test_molecule_rmse( esp_records: List[MoleculeESPRecord], charge_collection: Union[ Tuple[ConformerSettings, QCChargeSettings], LibraryChargeCollection ], bcc_collection: BCCCollection, vsite_collection: VirtualSiteCollection, ) -> float: from simtk import unit as simtk_unit with capture_toolkit_warnings(): molecule: Molecule = Molecule.from_mapped_smiles( esp_records[0].tagged_smiles, allow_undefined_stereo=True ) if not isinstance(charge_collection, LibraryChargeCollection): conformer_settings, charge_settings = charge_collection charge_collection = compute_base_charge( molecule, conformer_settings, charge_settings ) atom_charges = LibraryChargeGenerator.generate(molecule, charge_collection) n_vsites = 0 if len(bcc_collection.parameters) > 0: atom_charges += BCCGenerator.generate(molecule, bcc_collection) if len(vsite_collection.parameters) > 0: vsite_charges = VirtualSiteGenerator.generate_charge_increments( molecule, vsite_collection ) n_vsites = len(vsite_charges) - molecule.n_atoms full_charges = ( numpy.vstack([atom_charges, numpy.zeros((n_vsites, 1))]) + vsite_charges ) else: full_charges = atom_charges per_record_rmse = [] for esp_record in esp_records: esp_molecule: Molecule = Molecule.from_mapped_smiles( esp_record.tagged_smiles, allow_undefined_stereo=True ) esp_molecule._conformers = [esp_record.conformer * simtk_unit.angstrom] _, mapping = Molecule.are_isomorphic( esp_molecule, molecule, return_atom_map=True ) esp_molecule = esp_molecule.remap(mapping, current_to_new=True) [esp_conformer] = extract_conformers(esp_molecule) if n_vsites > 0: vsite_coordinates = VirtualSiteGenerator.generate_positions( esp_molecule, vsite_collection, esp_conformer ) full_coordinates = numpy.vstack([esp_conformer, vsite_coordinates]) else: full_coordinates = esp_conformer inverse_distance_matrix = compute_inverse_distance_matrix( esp_record.grid_coordinates, full_coordinates.m_as(unit.angstrom) ) inverse_distance_matrix = unit.convert( inverse_distance_matrix, unit.angstrom**-1, unit.bohr**-1 ) delta = inverse_distance_matrix @ full_charges - esp_record.esp rmse = numpy.sqrt(numpy.mean(delta * delta)) per_record_rmse.append(rmse) return float(numpy.mean(per_record_rmse)) def compute_test_rmse( esp_records: List[MoleculeESPRecord], charge_collection: Union[ Tuple[ConformerSettings, QCChargeSettings], LibraryChargeCollection ], bcc_collection: BCCCollection, vsite_collection: Optional[VirtualSiteCollection], n_processes: int, ) -> Dict[str, float]: esp_records_by_smiles = defaultdict(list) with capture_toolkit_warnings(): for esp_record in track(esp_records, "grouping records by molecule"): smiles = Molecule.from_smiles( esp_record.tagged_smiles, allow_undefined_stereo=True ).to_smiles(mapped=False) esp_records_by_smiles[smiles].append(esp_record) with Pool(processes=n_processes) as pool: per_molecule_rmse_func = functools.partial( compute_test_molecule_rmse, charge_collection=charge_collection, bcc_collection=bcc_collection, vsite_collection=vsite_collection, ) smiles_list, smiles_esp_records = zip(*esp_records_by_smiles.items()) rmse_list = list( track( pool.imap(per_molecule_rmse_func, smiles_esp_records), "computing per molecule RMSE", total=len(smiles_esp_records), ) ) per_molecule_rmse = { smiles: rmse for smiles, rmse in zip(smiles_list, rmse_list) } return per_molecule_rmse @click.command() @click.option( "--input-esp-records", "input_path", help="The file path to the input set of ESP records to test against.", type=click.Path(exists=True, file_okay=True, dir_okay=False), required=True, ) @click.option( "--input-parameters-base", "charge_collection_path", help="The path to the base charge model parameters", type=click.Path(exists=True, file_okay=True, dir_okay=False), required=True, ) @click.option( "--input-parameters-bcc", "bcc_collection_path", help="The path to the BCC parameters", type=click.Path(exists=True, file_okay=True, dir_okay=False), required=False, ) @click.option( "--input-parameters-v-site", "vsite_collection_path", help="The path to the BCC parameters", type=click.Path(exists=True, file_okay=True, dir_okay=False), required=False, ) @click.option( "--output", "output_path", help="A path to the JSON file to save the average per molecule RMSE to.", type=click.Path(exists=False, file_okay=True, dir_okay=False), required=True, ) @optgroup("Data processing") @optgroup.option( "--n-loader-processes", "n_processes", type=int, default=1, show_default=True, ) def main( input_path, charge_collection_path, bcc_collection_path, vsite_collection_path, output_path, n_processes, ): console = rich.get_console() console.print("") console.rule("test data") console.print("") with open(input_path, "rb") as file: with console.status("loading test data"): esp_records_test = pickle.load(file) console.print(f"loaded {len(esp_records_test)} testing records") console.print("") console.rule("model parameters") console.print("") with capture_toolkit_warnings(): with console.status("loading base charge model"): charge_collection = parse_file_as( Union[ Tuple[ConformerSettings, QCChargeSettings], LibraryChargeCollection ], charge_collection_path, ) if bcc_collection_path is not None: bcc_collection = BCCCollection.parse_file(bcc_collection_path) else: bcc_collection = BCCCollection(parameters=[]) if vsite_collection_path is not None: with capture_toolkit_warnings(): vsite_collection = VirtualSiteCollection.parse_file(vsite_collection_path) else: vsite_collection = VirtualSiteCollection(parameters=[]) # Determine which parameters will be trained console.print("testing a charge model containing ...") console.print("") console.rule("testing") console.print("") per_molecule_rmse = compute_test_rmse( esp_records_test, charge_collection, bcc_collection, vsite_collection, n_processes, ) with open(output_path, "w") as file: json.dump(per_molecule_rmse, file) if __name__ == "__main__": main()
[ "openff.recharge.charges.bcc.BCCCollection", "click_option_group.optgroup", "openff.recharge.charges.vsite.VirtualSiteGenerator.generate_positions", "openff.recharge.charges.vsite.VirtualSiteGenerator.generate_charge_increments", "collections.defaultdict", "numpy.mean", "pickle.load", "click.Path", ...
[((6194, 6209), 'click.command', 'click.command', ([], {}), '()\n', (6207, 6209), False, 'import click\n'), ((7280, 7307), 'click_option_group.optgroup', 'optgroup', (['"""Data processing"""'], {}), "('Data processing')\n", (7288, 7307), False, 'from click_option_group import optgroup\n'), ((7309, 7407), 'click_option_group.optgroup.option', 'optgroup.option', (['"""--n-loader-processes"""', '"""n_processes"""'], {'type': 'int', 'default': '(1)', 'show_default': '(True)'}), "('--n-loader-processes', 'n_processes', type=int, default=1,\n show_default=True)\n", (7324, 7407), False, 'from click_option_group import optgroup\n'), ((1407, 1464), 'openff.recharge.conformers.ConformerGenerator.generate', 'ConformerGenerator.generate', (['molecule', 'conformer_settings'], {}), '(molecule, conformer_settings)\n', (1434, 1464), False, 'from openff.recharge.conformers import ConformerGenerator, ConformerSettings\n'), ((1479, 1544), 'openff.recharge.charges.qc.QCChargeGenerator.generate', 'QCChargeGenerator.generate', (['molecule', 'conformers', 'charge_settings'], {}), '(molecule, conformers, charge_settings)\n', (1505, 1544), False, 'from openff.recharge.charges.qc import QCChargeGenerator, QCChargeSettings\n'), ((5095, 5112), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (5106, 5112), False, 'from collections import defaultdict\n'), ((7585, 7603), 'rich.get_console', 'rich.get_console', ([], {}), '()\n', (7601, 7603), False, 'import rich\n'), ((2207, 2233), 'nagl.utilities.toolkits.capture_toolkit_warnings', 'capture_toolkit_warnings', ([], {}), '()\n', (2231, 2233), False, 'from nagl.utilities.toolkits import capture_toolkit_warnings\n'), ((2265, 2355), 'openff.toolkit.topology.Molecule.from_mapped_smiles', 'Molecule.from_mapped_smiles', (['esp_records[0].tagged_smiles'], {'allow_undefined_stereo': '(True)'}), '(esp_records[0].tagged_smiles,\n allow_undefined_stereo=True)\n', (2292, 2355), False, 'from openff.toolkit.topology import Molecule\n'), ((2668, 2728), 'openff.recharge.charges.library.LibraryChargeGenerator.generate', 'LibraryChargeGenerator.generate', (['molecule', 'charge_collection'], {}), '(molecule, charge_collection)\n', (2699, 2728), False, 'from openff.recharge.charges.library import LibraryChargeCollection, LibraryChargeGenerator, LibraryChargeParameter\n'), ((4722, 4749), 'numpy.mean', 'numpy.mean', (['per_record_rmse'], {}), '(per_record_rmse)\n', (4732, 4749), False, 'import numpy\n'), ((5123, 5149), 'nagl.utilities.toolkits.capture_toolkit_warnings', 'capture_toolkit_warnings', ([], {}), '()\n', (5147, 5149), False, 'from nagl.utilities.toolkits import capture_toolkit_warnings\n'), ((5178, 5228), 'rich.progress.track', 'track', (['esp_records', '"""grouping records by molecule"""'], {}), "(esp_records, 'grouping records by molecule')\n", (5183, 5228), False, 'from rich.progress import track\n'), ((5454, 5481), 'multiprocessing.Pool', 'Pool', ([], {'processes': 'n_processes'}), '(processes=n_processes)\n', (5458, 5481), False, 'from multiprocessing import Pool\n'), ((5525, 5683), 'functools.partial', 'functools.partial', (['compute_test_molecule_rmse'], {'charge_collection': 'charge_collection', 'bcc_collection': 'bcc_collection', 'vsite_collection': 'vsite_collection'}), '(compute_test_molecule_rmse, charge_collection=\n charge_collection, bcc_collection=bcc_collection, vsite_collection=\n vsite_collection)\n', (5542, 5683), False, 'import functools\n'), ((7985, 8011), 'nagl.utilities.toolkits.capture_toolkit_warnings', 'capture_toolkit_warnings', ([], {}), '()\n', (8009, 8011), False, 'from nagl.utilities.toolkits import capture_toolkit_warnings\n'), ((8369, 8414), 'openff.recharge.charges.bcc.BCCCollection.parse_file', 'BCCCollection.parse_file', (['bcc_collection_path'], {}), '(bcc_collection_path)\n', (8393, 8414), False, 'from openff.recharge.charges.bcc import BCCCollection, BCCGenerator\n'), ((8450, 8478), 'openff.recharge.charges.bcc.BCCCollection', 'BCCCollection', ([], {'parameters': '[]'}), '(parameters=[])\n', (8463, 8478), False, 'from openff.recharge.charges.bcc import BCCCollection, BCCGenerator\n'), ((8687, 8723), 'openff.recharge.charges.vsite.VirtualSiteCollection', 'VirtualSiteCollection', ([], {'parameters': '[]'}), '(parameters=[])\n', (8708, 8723), False, 'from openff.recharge.charges.vsite import VirtualSiteCollection, VirtualSiteGenerator\n'), ((9130, 9164), 'json.dump', 'json.dump', (['per_molecule_rmse', 'file'], {}), '(per_molecule_rmse, file)\n', (9139, 9164), False, 'import json\n'), ((6354, 6409), 'click.Path', 'click.Path', ([], {'exists': '(True)', 'file_okay': '(True)', 'dir_okay': '(False)'}), '(exists=True, file_okay=True, dir_okay=False)\n', (6364, 6409), False, 'import click\n'), ((6574, 6629), 'click.Path', 'click.Path', ([], {'exists': '(True)', 'file_okay': '(True)', 'dir_okay': '(False)'}), '(exists=True, file_okay=True, dir_okay=False)\n', (6584, 6629), False, 'import click\n'), ((6776, 6831), 'click.Path', 'click.Path', ([], {'exists': '(True)', 'file_okay': '(True)', 'dir_okay': '(False)'}), '(exists=True, file_okay=True, dir_okay=False)\n', (6786, 6831), False, 'import click\n'), ((6984, 7039), 'click.Path', 'click.Path', ([], {'exists': '(True)', 'file_okay': '(True)', 'dir_okay': '(False)'}), '(exists=True, file_okay=True, dir_okay=False)\n', (6994, 7039), False, 'import click\n'), ((7200, 7256), 'click.Path', 'click.Path', ([], {'exists': '(False)', 'file_okay': '(True)', 'dir_okay': '(False)'}), '(exists=False, file_okay=True, dir_okay=False)\n', (7210, 7256), False, 'import click\n'), ((2827, 2874), 'openff.recharge.charges.bcc.BCCGenerator.generate', 'BCCGenerator.generate', (['molecule', 'bcc_collection'], {}), '(molecule, bcc_collection)\n', (2848, 2874), False, 'from openff.recharge.charges.bcc import BCCCollection, BCCGenerator\n'), ((2953, 3028), 'openff.recharge.charges.vsite.VirtualSiteGenerator.generate_charge_increments', 'VirtualSiteGenerator.generate_charge_increments', (['molecule', 'vsite_collection'], {}), '(molecule, vsite_collection)\n', (3000, 3028), False, 'from openff.recharge.charges.vsite import VirtualSiteCollection, VirtualSiteGenerator\n'), ((3415, 3501), 'openff.toolkit.topology.Molecule.from_mapped_smiles', 'Molecule.from_mapped_smiles', (['esp_record.tagged_smiles'], {'allow_undefined_stereo': '(True)'}), '(esp_record.tagged_smiles,\n allow_undefined_stereo=True)\n', (3442, 3501), False, 'from openff.toolkit.topology import Molecule\n'), ((3638, 3707), 'openff.toolkit.topology.Molecule.are_isomorphic', 'Molecule.are_isomorphic', (['esp_molecule', 'molecule'], {'return_atom_map': '(True)'}), '(esp_molecule, molecule, return_atom_map=True)\n', (3661, 3707), False, 'from openff.toolkit.topology import Molecule\n'), ((3845, 3877), 'openff.recharge.utilities.molecule.extract_conformers', 'extract_conformers', (['esp_molecule'], {}), '(esp_molecule)\n', (3863, 3877), False, 'from openff.recharge.utilities.molecule import extract_conformers\n'), ((4426, 4501), 'openff.units.unit.convert', 'unit.convert', (['inverse_distance_matrix', '(unit.angstrom ** -1)', '(unit.bohr ** -1)'], {}), '(inverse_distance_matrix, unit.angstrom ** -1, unit.bohr ** -1)\n', (4438, 4501), False, 'from openff.units import unit\n'), ((7802, 7819), 'pickle.load', 'pickle.load', (['file'], {}), '(file)\n', (7813, 7819), False, 'import pickle\n'), ((8104, 8221), 'pydantic.parse_file_as', 'parse_file_as', (['Union[Tuple[ConformerSettings, QCChargeSettings], LibraryChargeCollection]', 'charge_collection_path'], {}), '(Union[Tuple[ConformerSettings, QCChargeSettings],\n LibraryChargeCollection], charge_collection_path)\n', (8117, 8221), False, 'from pydantic import parse_file_as\n'), ((8535, 8561), 'nagl.utilities.toolkits.capture_toolkit_warnings', 'capture_toolkit_warnings', ([], {}), '()\n', (8559, 8561), False, 'from nagl.utilities.toolkits import capture_toolkit_warnings\n'), ((8594, 8649), 'openff.recharge.charges.vsite.VirtualSiteCollection.parse_file', 'VirtualSiteCollection.parse_file', (['vsite_collection_path'], {}), '(vsite_collection_path)\n', (8626, 8649), False, 'from openff.recharge.charges.vsite import VirtualSiteCollection, VirtualSiteGenerator\n'), ((3944, 4034), 'openff.recharge.charges.vsite.VirtualSiteGenerator.generate_positions', 'VirtualSiteGenerator.generate_positions', (['esp_molecule', 'vsite_collection', 'esp_conformer'], {}), '(esp_molecule, vsite_collection,\n esp_conformer)\n', (3983, 4034), False, 'from openff.recharge.charges.vsite import VirtualSiteCollection, VirtualSiteGenerator\n'), ((4104, 4152), 'numpy.vstack', 'numpy.vstack', (['[esp_conformer, vsite_coordinates]'], {}), '([esp_conformer, vsite_coordinates])\n', (4116, 4152), False, 'import numpy\n'), ((4635, 4660), 'numpy.mean', 'numpy.mean', (['(delta * delta)'], {}), '(delta * delta)\n', (4645, 4660), False, 'import numpy\n'), ((5252, 5327), 'openff.toolkit.topology.Molecule.from_smiles', 'Molecule.from_smiles', (['esp_record.tagged_smiles'], {'allow_undefined_stereo': '(True)'}), '(esp_record.tagged_smiles, allow_undefined_stereo=True)\n', (5272, 5327), False, 'from openff.toolkit.topology import Molecule\n'), ((3194, 3220), 'numpy.zeros', 'numpy.zeros', (['(n_vsites, 1)'], {}), '((n_vsites, 1))\n', (3205, 3220), False, 'import numpy\n')]
import cv2 import mediapipe as mp import numpy as np class FaceDetection(object): def __init__(self, method='mediapipe'): if method == 'mediapipe': self.inference_engine = mp.solutions.face_detection.FaceDetection(min_detection_confidence=0.5) self.draw_engine = mp.solutions.drawing_utils self.method = method def inference(self, image): image = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2RGB) results = self.inference_engine.process(image) return results def draw(self, image, results): if results.detections: image = image.copy() for detection in results.detections: self.draw_engine.draw_detection(image, detection) return image class FaceMesh(object): def __init__(self, method='mediapipe'): if method == 'mediapipe': self.inference_engine = mp.solutions.face_mesh.FaceMesh(min_detection_confidence=0.5, min_tracking_confidence=0.5) self.draw_engine = mp.solutions.drawing_utils self.method = method def inference(self, image): image = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2RGB) results = self.inference_engine.process(image) return results def draw(self, image, results): if results.multi_face_landmarks: image = image.copy() drawing_spec = self.draw_engine.DrawingSpec(thickness=1, circle_radius=1) for face_landmarks in results.multi_face_landmarks: self.draw_engine.draw_landmarks(image=image, landmark_list=face_landmarks, connections=mp.solutions.face_mesh.FACE_CONNECTIONS, landmark_drawing_spec=drawing_spec, connection_drawing_spec=drawing_spec) return image def get_lip_location(sell, results, image_shape): # Clockwise upper_lip_index = [61, 185, 40, 39, 37, 0, 267, 269, 270, 409, 291, 306, 292, 308, 415, 310, 311, 312, 13, 82, 81, 80, 191, 78, 62, 76] lower_lip_index = [61, 72, 62, 78, 95, 88, 178, 87, 14, 317, 402, 318, 324, 308, 292, 306, 291, 375, 321, 405, 314, 17, 84, 181, 91, 146] # 只选取第一个人脸 face_landmarks = [] if results.multi_face_landmarks: landmarks = results.multi_face_landmarks[0] x = [landmark.x for landmark in landmarks.landmark] y = [landmark.y for landmark in landmarks.landmark] face_landmarks = np.transpose(np.stack((x, y))) * [image_shape[1], image_shape[0]] face_landmarks = face_landmarks.astype(np.int32) return face_landmarks[upper_lip_index], face_landmarks[lower_lip_index] return None, None def get_mask_location(self, results, image_shape): # Clockwise #mask_index = [93, 6, 323, 365, 152, 136] mask_index = [118, 197, 347, 422, 152, 202] # 只选取第一个人脸 face_landmarks = [] if results.multi_face_landmarks: landmarks = results.multi_face_landmarks[0] x = [landmark.x for landmark in landmarks.landmark] y = [landmark.y for landmark in landmarks.landmark] face_landmarks = np.transpose(np.stack((x, y))) * [image_shape[1], image_shape[0]] return face_landmarks[mask_index] return None def mouth_opened_detection(self, results, image_shape, threshold=0.2): # Clockwise mouth_feature_index = [78, 82, 312, 308, 317, 87] # 只选取第一个人脸 face_landmarks = [] if results.multi_face_landmarks: landmarks = results.multi_face_landmarks[0] x = [landmark.x for landmark in landmarks.landmark] y = [landmark.y for landmark in landmarks.landmark] face_landmarks = np.transpose(np.stack((y, x))) * image_shape[:2] # left eye mouth_feature_location = face_landmarks[mouth_feature_index] mouth_horizontal_distance = self.calculation_distance(mouth_feature_location[0], mouth_feature_location[3]) mouth_vertical_distance = (self.calculation_distance(mouth_feature_location[1], mouth_feature_location[5]) + self.calculation_distance(mouth_feature_location[2], mouth_feature_location[4])) /2 mouth_distance_ratio = mouth_vertical_distance / mouth_horizontal_distance if mouth_distance_ratio > threshold: return True return False def eyes_closed_detection(self, results, image_shape, threshold=0.2): # Clockwise left_eye_feature_index = [33, 160, 158, 133, 153, 144] right_eye_feature_index = [362, 385, 387, 263, 373, 380] # 只选取第一个人脸 face_landmarks = [] if results.multi_face_landmarks: landmarks = results.multi_face_landmarks[0] x = [landmark.x for landmark in landmarks.landmark] y = [landmark.y for landmark in landmarks.landmark] face_landmarks = np.transpose(np.stack((y, x))) * image_shape[:2] # left eye left_eye_feature_location = face_landmarks[left_eye_feature_index] left_eye_horizontal_distance = self.calculation_distance(left_eye_feature_location[0], left_eye_feature_location[3]) left_eye_vertical_distance = (self.calculation_distance(left_eye_feature_location[1], left_eye_feature_location[5]) + self.calculation_distance(left_eye_feature_location[2], left_eye_feature_location[4])) /2 left_eye_distance_ratio = left_eye_vertical_distance / left_eye_horizontal_distance #print(left_eye_distance_ratio) # right eye right_eye_feature_location = face_landmarks[right_eye_feature_index] right_eye_horizontal_distance = self.calculation_distance(right_eye_feature_location[0], right_eye_feature_location[3]) right_eye_vertical_distance = (self.calculation_distance(right_eye_feature_location[1], right_eye_feature_location[5]) + self.calculation_distance(right_eye_feature_location[2], right_eye_feature_location[4])) /2 right_eye_distance_ratio = right_eye_vertical_distance / right_eye_horizontal_distance #print(right_eye_distance_ratio) if left_eye_distance_ratio < threshold and right_eye_distance_ratio < threshold: return True return False def eyes_enlarged(self, results, image, enlarge_factor): # Clockwise left_eye_feature_index = [33, 160, 158, 133, 153, 144] right_eye_feature_index = [362, 385, 387, 263, 373, 380] new_image = image.copy() # 只选取第一个人脸 face_landmarks = [] if results.multi_face_landmarks: landmarks = results.multi_face_landmarks[0] x = [landmark.x for landmark in landmarks.landmark] y = [landmark.y for landmark in landmarks.landmark] face_landmarks = np.transpose(np.stack((y, x))) * image.shape[:2] left_eye_feature_location = face_landmarks[left_eye_feature_index] right_eye_feature_location = face_landmarks[right_eye_feature_index] left_eye_center_location = np.mean(left_eye_feature_location, axis=0).astype(np.int) right_eye_center_location = np.mean(right_eye_feature_location, axis=0).astype(np.int) r_max = int(self.calculation_distance(left_eye_feature_location, right_eye_feature_location) / 4) ''' # slow for i in range(image.shape[0]): for j in range(image.shape[1]): raw_point = np.array([i, j]) left_r = self.calculation_distance(left_eye_center_location, raw_point) if left_r < r_max: factor = (1.0 - np.power((left_r/r_max -1.0),2.0) * enlarge_factor) new_point = (left_eye_center_location + (raw_point - left_eye_center_location) * factor).astype(np.int) new_image[i, j] = image[new_point[0], new_point[1]] right_r = self.calculation_distance(right_eye_center_location, raw_point) if right_r < r_max: factor = (1.0 - np.power((right_r/r_max -1.0),2.0) * enlarge_factor) new_point = (right_eye_center_location + (raw_point - right_eye_center_location) * factor).astype(np.int) new_image[i, j] = image[new_point[0], new_point[1]] ''' # quick for eye_center_location in [left_eye_center_location, right_eye_center_location]: x_grid_range = np.arange(max(eye_center_location[0]-r_max, 0), min(eye_center_location[0]+r_max+1, image.shape[0]), 1) y_grid_range = np.arange(max(eye_center_location[1]-r_max, 0), min(eye_center_location[1]+r_max+1, image.shape[1]), 1) x_grid, y_grid = np.meshgrid(x_grid_range, y_grid_range, indexing='ij') xy_grid = np.transpose(np.stack((x_grid.flatten(), y_grid.flatten()))) eye_distances = np.linalg.norm(eye_center_location - xy_grid, axis=1) eye_indexs = (eye_distances < r_max) enlarge_factors = 1.0 - np.power((eye_distances[eye_indexs]/r_max -1.0),2.0) * enlarge_factor enlarge_factors = np.transpose(np.stack((enlarge_factors,enlarge_factors))) eye_new_locations = (eye_center_location + (xy_grid[eye_indexs] - eye_center_location) * enlarge_factors).astype(np.int) vaild_indexs = (eye_new_locations[:, 0] < image.shape[0]) * (eye_new_locations[:, 1] < image.shape[1]) new_image[xy_grid[eye_indexs][vaild_indexs, 0], xy_grid[eye_indexs][vaild_indexs, 1]] = image[eye_new_locations[vaild_indexs, 0], eye_new_locations[vaild_indexs, 1]] return new_image def calculation_distance(self, point1, point2): #return np.sqrt(np.sum(np.square(point1 - point2))) return np.linalg.norm(point1-point2)
[ "numpy.stack", "numpy.meshgrid", "mediapipe.solutions.face_mesh.FaceMesh", "numpy.power", "mediapipe.solutions.face_detection.FaceDetection", "numpy.mean", "numpy.linalg.norm" ]
[((10040, 10071), 'numpy.linalg.norm', 'np.linalg.norm', (['(point1 - point2)'], {}), '(point1 - point2)\n', (10054, 10071), True, 'import numpy as np\n'), ((199, 270), 'mediapipe.solutions.face_detection.FaceDetection', 'mp.solutions.face_detection.FaceDetection', ([], {'min_detection_confidence': '(0.5)'}), '(min_detection_confidence=0.5)\n', (240, 270), True, 'import mediapipe as mp\n'), ((913, 1007), 'mediapipe.solutions.face_mesh.FaceMesh', 'mp.solutions.face_mesh.FaceMesh', ([], {'min_detection_confidence': '(0.5)', 'min_tracking_confidence': '(0.5)'}), '(min_detection_confidence=0.5,\n min_tracking_confidence=0.5)\n', (944, 1007), True, 'import mediapipe as mp\n'), ((8947, 9001), 'numpy.meshgrid', 'np.meshgrid', (['x_grid_range', 'y_grid_range'], {'indexing': '"""ij"""'}), "(x_grid_range, y_grid_range, indexing='ij')\n", (8958, 9001), True, 'import numpy as np\n'), ((9138, 9191), 'numpy.linalg.norm', 'np.linalg.norm', (['(eye_center_location - xy_grid)'], {'axis': '(1)'}), '(eye_center_location - xy_grid, axis=1)\n', (9152, 9191), True, 'import numpy as np\n'), ((2448, 2464), 'numpy.stack', 'np.stack', (['(x, y)'], {}), '((x, y))\n', (2456, 2464), True, 'import numpy as np\n'), ((3166, 3182), 'numpy.stack', 'np.stack', (['(x, y)'], {}), '((x, y))\n', (3174, 3182), True, 'import numpy as np\n'), ((3763, 3779), 'numpy.stack', 'np.stack', (['(y, x)'], {}), '((y, x))\n', (3771, 3779), True, 'import numpy as np\n'), ((4979, 4995), 'numpy.stack', 'np.stack', (['(y, x)'], {}), '((y, x))\n', (4987, 4995), True, 'import numpy as np\n'), ((6950, 6966), 'numpy.stack', 'np.stack', (['(y, x)'], {}), '((y, x))\n', (6958, 6966), True, 'import numpy as np\n'), ((7186, 7228), 'numpy.mean', 'np.mean', (['left_eye_feature_location'], {'axis': '(0)'}), '(left_eye_feature_location, axis=0)\n', (7193, 7228), True, 'import numpy as np\n'), ((7284, 7327), 'numpy.mean', 'np.mean', (['right_eye_feature_location'], {'axis': '(0)'}), '(right_eye_feature_location, axis=0)\n', (7291, 7327), True, 'import numpy as np\n'), ((9402, 9446), 'numpy.stack', 'np.stack', (['(enlarge_factors, enlarge_factors)'], {}), '((enlarge_factors, enlarge_factors))\n', (9410, 9446), True, 'import numpy as np\n'), ((9285, 9339), 'numpy.power', 'np.power', (['(eye_distances[eye_indexs] / r_max - 1.0)', '(2.0)'], {}), '(eye_distances[eye_indexs] / r_max - 1.0, 2.0)\n', (9293, 9339), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Use GLImageItem to display image data on rectangular planes. In this example, the image data is sampled from a volume and the image planes placed as if they slice through the volume. """ ## Add path to library (just for examples; you do not need this) import initExample from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph.opengl as gl import pyqtgraph as pg import numpy as np app = QtGui.QApplication([]) w = gl.GLViewWidget() w.opts['distance'] = 200 w.show() w.setWindowTitle('pyqtgraph example: GLImageItem') ## create volume data set to slice three images from shape = (100,100,70) data = pg.gaussianFilter(np.random.normal(size=shape), (4,4,4)) data += pg.gaussianFilter(np.random.normal(size=shape), (15,15,15))*15 ## slice out three planes, convert to RGBA for OpenGL texture levels = (-0.08, 0.08) tex1 = pg.makeRGBA(data[shape[0]/2], levels=levels)[0] # yz plane tex2 = pg.makeRGBA(data[:,shape[1]/2], levels=levels)[0] # xz plane tex3 = pg.makeRGBA(data[:,:,shape[2]/2], levels=levels)[0] # xy plane #tex1[:,:,3] = 128 #tex2[:,:,3] = 128 #tex3[:,:,3] = 128 ## Create three image items from textures, add to view v1 = gl.GLImageItem(tex1) v1.translate(-shape[1]/2, -shape[2]/2, 0) v1.rotate(90, 0,0,1) v1.rotate(-90, 0,1,0) w.addItem(v1) v2 = gl.GLImageItem(tex2) v2.translate(-shape[0]/2, -shape[2]/2, 0) v2.rotate(-90, 1,0,0) w.addItem(v2) v3 = gl.GLImageItem(tex3) v3.translate(-shape[0]/2, -shape[1]/2, 0) w.addItem(v3) ax = gl.GLAxisItem() w.addItem(ax) ## Start Qt event loop unless running in interactive mode. if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
[ "pyqtgraph.opengl.GLAxisItem", "pyqtgraph.opengl.GLImageItem", "pyqtgraph.Qt.QtGui.QApplication.instance", "pyqtgraph.makeRGBA", "pyqtgraph.opengl.GLViewWidget", "numpy.random.normal", "pyqtgraph.Qt.QtGui.QApplication" ]
[((435, 457), 'pyqtgraph.Qt.QtGui.QApplication', 'QtGui.QApplication', (['[]'], {}), '([])\n', (453, 457), False, 'from pyqtgraph.Qt import QtCore, QtGui\n'), ((463, 480), 'pyqtgraph.opengl.GLViewWidget', 'gl.GLViewWidget', ([], {}), '()\n', (478, 480), True, 'import pyqtgraph.opengl as gl\n'), ((1216, 1236), 'pyqtgraph.opengl.GLImageItem', 'gl.GLImageItem', (['tex1'], {}), '(tex1)\n', (1230, 1236), True, 'import pyqtgraph.opengl as gl\n'), ((1346, 1366), 'pyqtgraph.opengl.GLImageItem', 'gl.GLImageItem', (['tex2'], {}), '(tex2)\n', (1360, 1366), True, 'import pyqtgraph.opengl as gl\n'), ((1454, 1474), 'pyqtgraph.opengl.GLImageItem', 'gl.GLImageItem', (['tex3'], {}), '(tex3)\n', (1468, 1474), True, 'import pyqtgraph.opengl as gl\n'), ((1541, 1556), 'pyqtgraph.opengl.GLAxisItem', 'gl.GLAxisItem', ([], {}), '()\n', (1554, 1556), True, 'import pyqtgraph.opengl as gl\n'), ((673, 701), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'shape'}), '(size=shape)\n', (689, 701), True, 'import numpy as np\n'), ((881, 927), 'pyqtgraph.makeRGBA', 'pg.makeRGBA', (['data[shape[0] / 2]'], {'levels': 'levels'}), '(data[shape[0] / 2], levels=levels)\n', (892, 927), True, 'import pyqtgraph as pg\n'), ((954, 1003), 'pyqtgraph.makeRGBA', 'pg.makeRGBA', (['data[:, shape[1] / 2]'], {'levels': 'levels'}), '(data[:, shape[1] / 2], levels=levels)\n', (965, 1003), True, 'import pyqtgraph as pg\n'), ((1027, 1079), 'pyqtgraph.makeRGBA', 'pg.makeRGBA', (['data[:, :, shape[2] / 2]'], {'levels': 'levels'}), '(data[:, :, shape[2] / 2], levels=levels)\n', (1038, 1079), True, 'import pyqtgraph as pg\n'), ((739, 767), 'numpy.random.normal', 'np.random.normal', ([], {'size': 'shape'}), '(size=shape)\n', (755, 767), True, 'import numpy as np\n'), ((1764, 1793), 'pyqtgraph.Qt.QtGui.QApplication.instance', 'QtGui.QApplication.instance', ([], {}), '()\n', (1791, 1793), False, 'from pyqtgraph.Qt import QtCore, QtGui\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.1.5 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # s_aggregation_norm [<img src="https://www.arpm.co/lab/icons/icon_permalink.png" width=30 height=30 style="display: inline;">](https://www.arpm.co/lab/redirect.php?code=s_aggregation_norm&codeLang=Python) # For details, see [here](https://www.arpm.co/lab/redirect.php?permalink=eb-normal-first-order-approx). # + import pandas as pd import numpy as np from scipy.stats import norm import matplotlib.pyplot as plt from arpym.tools.histogram_sp import histogram_sp # from arpym.tools.logo import add_logo # - # ## [Input parameters](https://www.arpm.co/lab/redirect.php?permalink=s_aggregation_norm-parameters) h = np.array([100000, 80000]) # portfolio holdings # ## [Step 1](https://www.arpm.co/lab/redirect.php?permalink=s_aggregation_norm-implementation-step01): Load data # + path = 'databases/temporary-databases' df = pd.read_csv(path + '/db_pricing_zcb.csv', header=0) j_, _ = df.shape # number of scenarios # number of key-rates d_ = len(np.array(df['y_tnow'].dropna(axis=0, how='all'))) # number of instruments n_ = len(np.array(df['v_zcb_tnow'].dropna(axis=0, how='all'))) # scenarios for the ex-ante P&L's pl = np.array([df['pl' + str(i + 1)] for i in range(n_)]).T # bonds' P&L's mean mu_pl = np.array(df['mu_pl'].dropna(axis=0, how='all')) # bonds' P&L's covariance sig2_pl = np.array(df['sig2_pl'].dropna(axis=0, how='all')).reshape((n_, n_)) # horizon deltat = float(df['time2hor_tnow'].dropna(axis=0, how='all')) # - # ## [Step 2](https://www.arpm.co/lab/redirect.php?permalink=s_aggregation_norm-implementation-step02): Scenarios for the portfolio's P&L and its expectation and variance pl_h = pl@h # portfolio P&L scenarios mu_h = mu_pl@h # portfolio P&L expectation sig2_h = h@sig2_pl@h # portfolio P&L variance # ## [Step 3](https://www.arpm.co/lab/redirect.php?permalink=s_aggregation_norm-implementation-step03): Compute the heights and bin centers of the histogram f_pi_h, ksi = histogram_sp(pl_h, p=(1 / j_ * np.ones(j_)), k_=np.round(10 * np.log(j_))) # ## [Step 4](https://www.arpm.co/lab/redirect.php?permalink=s_aggregation_norm-implementation-step04): Save data in database db_aggregation_normal # + output = {'n_': pd.Series(n_), 'mu_h': pd.Series(mu_h), 'sig2_h': pd.Series(sig2_h), 'h': pd.Series(h), } df = pd.DataFrame(output) df.to_csv(path + 'db_aggregation_normal.csv') # - # ## Plots # + # plt.style.use('arpm') fig = plt.figure() ax = fig.add_subplot(111) lgray = [.8, .8, .8] # light gray dgray = [.7, .7, .7] # dark gray plt.bar(ksi, f_pi_h, width=ksi[1] - ksi[0], facecolor=lgray, edgecolor=dgray) plt.title(r"Distribution of the portfolio's P&L " + "at the horizon ($\Delta t=${horizon:.0f} days)" .format(horizon=deltat * 252)) x_hor = np.linspace(mu_h - 7 * np.sqrt(sig2_h), mu_h + 7 * np.sqrt(sig2_h), 500) taylor_first = norm.pdf(x_hor, loc=mu_h, scale=np.sqrt(sig2_h)) plt.plot(x_hor, taylor_first.flatten(), 'r', lw=1.5) ax.set_xlim([x_hor[0], x_hor[-1]]) plt.legend(['Normal approx']) # add_logo(fig) plt.tight_layout()
[ "pandas.DataFrame", "numpy.log", "pandas.read_csv", "matplotlib.pyplot.bar", "matplotlib.pyplot.legend", "numpy.ones", "matplotlib.pyplot.figure", "numpy.array", "pandas.Series", "matplotlib.pyplot.tight_layout", "numpy.sqrt" ]
[((931, 956), 'numpy.array', 'np.array', (['[100000, 80000]'], {}), '([100000, 80000])\n', (939, 956), True, 'import numpy as np\n'), ((1143, 1194), 'pandas.read_csv', 'pd.read_csv', (["(path + '/db_pricing_zcb.csv')"], {'header': '(0)'}), "(path + '/db_pricing_zcb.csv', header=0)\n", (1154, 1194), True, 'import pandas as pd\n'), ((2612, 2632), 'pandas.DataFrame', 'pd.DataFrame', (['output'], {}), '(output)\n', (2624, 2632), True, 'import pandas as pd\n'), ((2731, 2743), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2741, 2743), True, 'import matplotlib.pyplot as plt\n'), ((2840, 2917), 'matplotlib.pyplot.bar', 'plt.bar', (['ksi', 'f_pi_h'], {'width': '(ksi[1] - ksi[0])', 'facecolor': 'lgray', 'edgecolor': 'dgray'}), '(ksi, f_pi_h, width=ksi[1] - ksi[0], facecolor=lgray, edgecolor=dgray)\n', (2847, 2917), True, 'import matplotlib.pyplot as plt\n'), ((3333, 3362), 'matplotlib.pyplot.legend', 'plt.legend', (["['Normal approx']"], {}), "(['Normal approx'])\n", (3343, 3362), True, 'import matplotlib.pyplot as plt\n'), ((3380, 3398), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (3396, 3398), True, 'import matplotlib.pyplot as plt\n'), ((2477, 2490), 'pandas.Series', 'pd.Series', (['n_'], {}), '(n_)\n', (2486, 2490), True, 'import pandas as pd\n'), ((2510, 2525), 'pandas.Series', 'pd.Series', (['mu_h'], {}), '(mu_h)\n', (2519, 2525), True, 'import pandas as pd\n'), ((2547, 2564), 'pandas.Series', 'pd.Series', (['sig2_h'], {}), '(sig2_h)\n', (2556, 2564), True, 'import pandas as pd\n'), ((2581, 2593), 'pandas.Series', 'pd.Series', (['h'], {}), '(h)\n', (2590, 2593), True, 'import pandas as pd\n'), ((3227, 3242), 'numpy.sqrt', 'np.sqrt', (['sig2_h'], {}), '(sig2_h)\n', (3234, 3242), True, 'import numpy as np\n'), ((2263, 2274), 'numpy.ones', 'np.ones', (['j_'], {}), '(j_)\n', (2270, 2274), True, 'import numpy as np\n'), ((3110, 3125), 'numpy.sqrt', 'np.sqrt', (['sig2_h'], {}), '(sig2_h)\n', (3117, 3125), True, 'import numpy as np\n'), ((3158, 3173), 'numpy.sqrt', 'np.sqrt', (['sig2_h'], {}), '(sig2_h)\n', (3165, 3173), True, 'import numpy as np\n'), ((2294, 2304), 'numpy.log', 'np.log', (['j_'], {}), '(j_)\n', (2300, 2304), True, 'import numpy as np\n')]
import argparse import os import nibabel as nib import numpy as np from .infer import Predictor def Brain_Segmenatation(path_in, path_out, path_model): """Docs.""" mask_predictor = Predictor(path_model) probability = mask_predictor.predict(path_in) ni_img = nib.Nifti1Image(probability, affine=np.eye(4)) nib.save(ni_img, os.path.join(path_out, "output.nii.gz")) if __name__ == "__main__": parser = argparse.ArgumentParser(description="folders to files") parser.add_argument("path_in", type=str, help="dir with image") parser.add_argument("path_out", type=str, help="output dir") parser.add_argument("path_model", type=str, help="path_model") args = parser.parse_args() Brain_Segmenatation(args.path_in, args.path_out, args.path_model)
[ "numpy.eye", "os.path.join", "argparse.ArgumentParser" ]
[((429, 484), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""folders to files"""'}), "(description='folders to files')\n", (452, 484), False, 'import argparse\n'), ((346, 385), 'os.path.join', 'os.path.join', (['path_out', '"""output.nii.gz"""'], {}), "(path_out, 'output.nii.gz')\n", (358, 385), False, 'import os\n'), ((314, 323), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (320, 323), True, 'import numpy as np\n')]
import numpy as np import cv2 import matplotlib.pyplot as plt from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from scipy import stats import warnings warnings.filterwarnings('error') class ExpMax: def __init__(self, dx, dy, means, colors=None, indices=None, bounds=(0, 0, 255, 255), max_iterations=30, point_alpha=1.0, covariance_weight=1.0, axis_titles=("x", "y")): self.data_x = dx self.data_y = dy self.n = self.data_x.shape[0] self.colors = colors if colors is not None else ["#000000"] * means self.original = indices self.clusters = indices if indices is not None else (np.zeros((self.n,), dtype=np.int32) - 1) self.k = means self.x_means = [] self.x_std = [] self.y_means = [] self.y_std = [] self.weights = np.zeros((self.k, self.n), dtype=np.float64) self.cov = [] self.plot_frames = [] self.plot_bounds = bounds self.max_iterations = max_iterations self.plot_point_alpha = point_alpha self.covariance_weight = covariance_weight self.x_title, self.y_title = axis_titles success = False while not success: self.plot_frames = [] success = self.maximize() def initialize_means(self): avg_xmean = np.mean(self.data_x) avg_ymean = np.mean(self.data_y) avg_xstd = np.std(self.data_x) avg_ystd = np.std(self.data_y) min_distance = -1.0 for i in range(5): theta = i / self.k / 5 x_means = [avg_xmean + avg_xstd * np.cos((theta + k / self.k) * 2.0 * np.pi) for k in range(self.k)] y_means = [avg_ymean + avg_ystd * np.sin((theta + k / self.k) * 2.0 * np.pi) for k in range(self.k)] new_distance = np.sum(np.min(np.array([(self.data_x - x_means[k]) ** 2 + (self.data_y - y_means[k]) ** 2 for k in range(self.k)]), axis=0)) if new_distance < min_distance or min_distance < 0.0: min_distance = new_distance self.x_means = x_means self.y_means = y_means self.x_std = [avg_xstd / self.k] * self.k self.y_std = [avg_ystd / self.k] * self.k self.cov = [np.diagflat([avg_xstd ** 2, avg_ystd ** 2]).astype(np.float64) + 1.0] * self.k def maximize(self, tolerance=0.0005): """ Expectation Maximization Implementation Parameters ---------- tolerance: float The ratio of the total change in the location of the means to the total of the standard deviations. As the plots converge, this ratio decreases, and when it gets below tolerance, the EM has converged. Returns ------- bool True if convergence was successful, False otherwise """ # Evenly distribute means and standard deviations for initial guesses. self.initialize_means() priors = np.array([[1.0/self.k] * self.n] * self.k) p_gauss = np.zeros((self.k, self.n), dtype=np.float64) delta = tolerance * 2.0 # E-step and M-step implementations self.plot(0, with_gaussian=False) iteration = 1 while delta >= tolerance and iteration < self.max_iterations: # E-step: Estimate responsibilities try: for j in range(self.k): p_gauss[j] = np.exp(-(((self.data_x - self.x_means[j]) / (np.sqrt(2) * self.x_std[j])) ** 2) - ((self.data_y - self.y_means[j]) / (np.sqrt(2) * self.y_std[j])) ** 2) / \ np.sqrt(2.0 * np.pi * np.abs(self.cov[j][0, 1]) ** self.covariance_weight) except Warning: # In case a Gaussian vanishes, where standard deviation = 0.0 return False self.weights = p_gauss * priors total_weights = np.sum(self.weights, axis=0) self.weights /= np.repeat(np.expand_dims(total_weights, axis=0), self.k, axis=0) self.clusters = np.argmax(self.weights, axis=0) self.plot(iteration) # M-step: Estimate parameters priors = np.repeat(np.expand_dims(np.sum(self.weights, axis=1) / self.n, axis=1), self.n, axis=1) contribution = self.weights / (self.n * priors) x_prev = self.x_means y_prev = self.y_means self.x_means = [np.sum(self.data_x * contribution[j]) for j in range(self.k)] self.y_means = [np.sum(self.data_y * contribution[j]) for j in range(self.k)] self.x_std = [np.sqrt(np.sum((self.data_x - self.x_means[j]) ** 2 * contribution[j])) for j in range(self.k)] self.y_std = [np.sqrt(np.sum((self.data_y - self.y_means[j]) ** 2 * contribution[j])) for j in range(self.k)] for j in range(self.k): cov = np.sum((self.data_x - self.x_means[j]) * (self.data_y - self.y_means[j]) * contribution[j]) self.cov[j] = np.array([[self.x_std[j] ** 2, cov], [cov, self.y_std[j] ** 2]], dtype=np.float64) # Check for convergence using the total distance that the Gaussians traveled x_dist = [x_prev[i] - self.x_means[i] for i in range(self.k)] y_dist = [y_prev[i] - self.y_means[i] for i in range(self.k)] total_dist = sum([np.sqrt(x_dist[i] ** 2 + y_dist[i] ** 2) for i in range(self.k)]) total_std = sum([np.sqrt(self.x_std[i] ** 2 + self.y_std[i] ** 2) for i in range(self.k)]) delta = total_dist / total_std iteration += 1 self.plot(iteration) return True def plot(self, index, with_gaussian=True): """ Parameters ---------- index: int The iteration of the expectation maximization, to include in the title of the plot. with_gaussian: bool Whether to plot the Gaussian distributions along with the data points (True) or not (False). References ---------- https://matplotlib.org/gallery/units/ellipse_with_units.html#sphx-glr-gallery-units-ellipse-with-units-py https://www.visiondummy.com/2014/04/draw-error-ellipse-representing-covariance-matrix/ """ fig = plt.figure(figsize=(8.0, 6.4)) width = int((fig.get_size_inches() * fig.get_dpi())[0]) height = int((fig.get_size_inches() * fig.get_dpi())[1]) canvas = FigureCanvas(fig) plt.title("Data (Iteration: %d)" % index) plt.xlabel(self.x_title) plt.ylabel(self.y_title) plt.xlim(self.plot_bounds[0] - 10.0, self.plot_bounds[2] + 10.0) plt.ylim(self.plot_bounds[1] - 10.0, self.plot_bounds[3] + 10.0) plt.subplots_adjust(left=0.15, bottom=0.15, right=0.85, top=0.85) # Plot data points colors = np.array([self.colors[c] if c >= 0 else "#000000" for c in self.clusters]) plt.scatter(self.data_x, self.data_y, s=1.0, c=colors, alpha=self.plot_point_alpha) # Plot Gaussian distributions for 90.0 %, 97.5 %, and 99.5 % confidence levels if with_gaussian: theta = np.arange(0, 360, 2).astype(np.float64) * np.pi / 180.0 confidence = stats.chi2.ppf([0.9, 0.975, 0.995], 2) for i in range(self.k): xc = self.x_means[i] yc = self.y_means[i] try: eigenvalues, eigenvectors = np.linalg.eig(self.cov[i]) except np.linalg.LinAlgError: return rotation = -np.arctan2(eigenvectors[0][1], eigenvectors[0][0]) r_mat = np.array([[np.cos(rotation), -np.sin(rotation)], [np.sin(rotation), np.cos(rotation)]], dtype=np.float64) for j, c in enumerate(confidence): x_points = self.x_std[i] * np.cos(theta) * np.sqrt(c) y_points = self.y_std[i] * np.sin(theta) * np.sqrt(c) x_points, y_points = np.dot(r_mat, np.array([x_points, y_points])) x_points += xc y_points += yc plt.fill(x_points, y_points, alpha=0.125/(1+j), facecolor=self.colors[i]) canvas.draw() image = np.frombuffer(canvas.tostring_rgb(), dtype=np.uint8).reshape(height, width, 3) self.plot_frames.append(cv2.cvtColor(image, cv2.COLOR_RGB2BGR)) plt.close(fig) def get_parameters(self): """ Retrieve resulting means and covariance matrices from the expectation maximization. Returns ------- tuple x_means, y_means, cov: parameters to use for data categorization """ return self.x_means, self.y_means, self.cov def play_animation(self): for i in range(len(self.plot_frames)): cv2.imshow("Plot", self.plot_frames[i]) cv2.waitKey(0 if (i <= 1 or i == len(self.plot_frames) - 1) else 200) cv2.destroyWindow("Plot") def main(): params = [(35.0, 7.0, 30.0, 4.0, 200, "#FF0000"), (40.0, 6.0, 70.0, 9.0, 300, "#00C000"), (70.0, 5.0, 50.0, 12.0, 400, "#0000FF")] sample_x = np.zeros((0,), dtype=np.float64) sample_y = np.zeros((0,), dtype=np.float64) sample_i = np.zeros((0,), dtype=np.int32) sample_c = [] for i in range(len(params)): sxm, sxs, sym, sys, sn, color = params[i] sample_x = np.concatenate((sample_x, np.random.normal(sxm, sxs, sn)), axis=0) sample_y = np.concatenate((sample_y, np.random.normal(sym, sys, sn)), axis=0) sample_i = np.concatenate((sample_i, np.array([i] * sn)), axis=0) sample_c.append(color) sample_y[:200] -= (sample_x[:200] * 0.5) em = ExpMax(sample_x, sample_y, len(params), colors=sample_c, indices=None, bounds=(0, 0, 100, 100)) em.play_animation() if __name__ == '__main__': main()
[ "matplotlib.pyplot.title", "numpy.sum", "numpy.arctan2", "numpy.abs", "numpy.argmax", "numpy.diagflat", "matplotlib.pyplot.figure", "numpy.mean", "numpy.sin", "numpy.arange", "numpy.random.normal", "cv2.imshow", "numpy.std", "matplotlib.backends.backend_agg.FigureCanvasAgg", "matplotlib....
[((178, 210), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""error"""'], {}), "('error')\n", (201, 210), False, 'import warnings\n'), ((9354, 9386), 'numpy.zeros', 'np.zeros', (['(0,)'], {'dtype': 'np.float64'}), '((0,), dtype=np.float64)\n', (9362, 9386), True, 'import numpy as np\n'), ((9402, 9434), 'numpy.zeros', 'np.zeros', (['(0,)'], {'dtype': 'np.float64'}), '((0,), dtype=np.float64)\n', (9410, 9434), True, 'import numpy as np\n'), ((9450, 9480), 'numpy.zeros', 'np.zeros', (['(0,)'], {'dtype': 'np.int32'}), '((0,), dtype=np.int32)\n', (9458, 9480), True, 'import numpy as np\n'), ((862, 906), 'numpy.zeros', 'np.zeros', (['(self.k, self.n)'], {'dtype': 'np.float64'}), '((self.k, self.n), dtype=np.float64)\n', (870, 906), True, 'import numpy as np\n'), ((1358, 1378), 'numpy.mean', 'np.mean', (['self.data_x'], {}), '(self.data_x)\n', (1365, 1378), True, 'import numpy as np\n'), ((1399, 1419), 'numpy.mean', 'np.mean', (['self.data_y'], {}), '(self.data_y)\n', (1406, 1419), True, 'import numpy as np\n'), ((1439, 1458), 'numpy.std', 'np.std', (['self.data_x'], {}), '(self.data_x)\n', (1445, 1458), True, 'import numpy as np\n'), ((1478, 1497), 'numpy.std', 'np.std', (['self.data_y'], {}), '(self.data_y)\n', (1484, 1497), True, 'import numpy as np\n'), ((3046, 3090), 'numpy.array', 'np.array', (['([[1.0 / self.k] * self.n] * self.k)'], {}), '([[1.0 / self.k] * self.n] * self.k)\n', (3054, 3090), True, 'import numpy as np\n'), ((3107, 3151), 'numpy.zeros', 'np.zeros', (['(self.k, self.n)'], {'dtype': 'np.float64'}), '((self.k, self.n), dtype=np.float64)\n', (3115, 3151), True, 'import numpy as np\n'), ((6412, 6442), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(8.0, 6.4)'}), '(figsize=(8.0, 6.4))\n', (6422, 6442), True, 'import matplotlib.pyplot as plt\n'), ((6589, 6606), 'matplotlib.backends.backend_agg.FigureCanvasAgg', 'FigureCanvas', (['fig'], {}), '(fig)\n', (6601, 6606), True, 'from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\n'), ((6615, 6656), 'matplotlib.pyplot.title', 'plt.title', (["('Data (Iteration: %d)' % index)"], {}), "('Data (Iteration: %d)' % index)\n", (6624, 6656), True, 'import matplotlib.pyplot as plt\n'), ((6665, 6689), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['self.x_title'], {}), '(self.x_title)\n', (6675, 6689), True, 'import matplotlib.pyplot as plt\n'), ((6698, 6722), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['self.y_title'], {}), '(self.y_title)\n', (6708, 6722), True, 'import matplotlib.pyplot as plt\n'), ((6731, 6795), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(self.plot_bounds[0] - 10.0)', '(self.plot_bounds[2] + 10.0)'], {}), '(self.plot_bounds[0] - 10.0, self.plot_bounds[2] + 10.0)\n', (6739, 6795), True, 'import matplotlib.pyplot as plt\n'), ((6804, 6868), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(self.plot_bounds[1] - 10.0)', '(self.plot_bounds[3] + 10.0)'], {}), '(self.plot_bounds[1] - 10.0, self.plot_bounds[3] + 10.0)\n', (6812, 6868), True, 'import matplotlib.pyplot as plt\n'), ((6877, 6942), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'left': '(0.15)', 'bottom': '(0.15)', 'right': '(0.85)', 'top': '(0.85)'}), '(left=0.15, bottom=0.15, right=0.85, top=0.85)\n', (6896, 6942), True, 'import matplotlib.pyplot as plt\n'), ((6988, 7064), 'numpy.array', 'np.array', (["[(self.colors[c] if c >= 0 else '#000000') for c in self.clusters]"], {}), "([(self.colors[c] if c >= 0 else '#000000') for c in self.clusters])\n", (6996, 7064), True, 'import numpy as np\n'), ((7071, 7159), 'matplotlib.pyplot.scatter', 'plt.scatter', (['self.data_x', 'self.data_y'], {'s': '(1.0)', 'c': 'colors', 'alpha': 'self.plot_point_alpha'}), '(self.data_x, self.data_y, s=1.0, c=colors, alpha=self.\n plot_point_alpha)\n', (7082, 7159), True, 'import matplotlib.pyplot as plt\n'), ((8578, 8592), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (8587, 8592), True, 'import matplotlib.pyplot as plt\n'), ((9136, 9161), 'cv2.destroyWindow', 'cv2.destroyWindow', (['"""Plot"""'], {}), "('Plot')\n", (9153, 9161), False, 'import cv2\n'), ((3999, 4027), 'numpy.sum', 'np.sum', (['self.weights'], {'axis': '(0)'}), '(self.weights, axis=0)\n', (4005, 4027), True, 'import numpy as np\n'), ((4150, 4181), 'numpy.argmax', 'np.argmax', (['self.weights'], {'axis': '(0)'}), '(self.weights, axis=0)\n', (4159, 4181), True, 'import numpy as np\n'), ((7370, 7408), 'scipy.stats.chi2.ppf', 'stats.chi2.ppf', (['[0.9, 0.975, 0.995]', '(2)'], {}), '([0.9, 0.975, 0.995], 2)\n', (7384, 7408), False, 'from scipy import stats\n'), ((8530, 8568), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_RGB2BGR'], {}), '(image, cv2.COLOR_RGB2BGR)\n', (8542, 8568), False, 'import cv2\n'), ((9006, 9045), 'cv2.imshow', 'cv2.imshow', (['"""Plot"""', 'self.plot_frames[i]'], {}), "('Plot', self.plot_frames[i])\n", (9016, 9045), False, 'import cv2\n'), ((675, 710), 'numpy.zeros', 'np.zeros', (['(self.n,)'], {'dtype': 'np.int32'}), '((self.n,), dtype=np.int32)\n', (683, 710), True, 'import numpy as np\n'), ((4066, 4103), 'numpy.expand_dims', 'np.expand_dims', (['total_weights'], {'axis': '(0)'}), '(total_weights, axis=0)\n', (4080, 4103), True, 'import numpy as np\n'), ((4524, 4561), 'numpy.sum', 'np.sum', (['(self.data_x * contribution[j])'], {}), '(self.data_x * contribution[j])\n', (4530, 4561), True, 'import numpy as np\n'), ((4614, 4651), 'numpy.sum', 'np.sum', (['(self.data_y * contribution[j])'], {}), '(self.data_y * contribution[j])\n', (4620, 4651), True, 'import numpy as np\n'), ((5030, 5125), 'numpy.sum', 'np.sum', (['((self.data_x - self.x_means[j]) * (self.data_y - self.y_means[j]) *\n contribution[j])'], {}), '((self.data_x - self.x_means[j]) * (self.data_y - self.y_means[j]) *\n contribution[j])\n', (5036, 5125), True, 'import numpy as np\n'), ((5152, 5239), 'numpy.array', 'np.array', (['[[self.x_std[j] ** 2, cov], [cov, self.y_std[j] ** 2]]'], {'dtype': 'np.float64'}), '([[self.x_std[j] ** 2, cov], [cov, self.y_std[j] ** 2]], dtype=np.\n float64)\n', (5160, 5239), True, 'import numpy as np\n'), ((9627, 9657), 'numpy.random.normal', 'np.random.normal', (['sxm', 'sxs', 'sn'], {}), '(sxm, sxs, sn)\n', (9643, 9657), True, 'import numpy as np\n'), ((9713, 9743), 'numpy.random.normal', 'np.random.normal', (['sym', 'sys', 'sn'], {}), '(sym, sys, sn)\n', (9729, 9743), True, 'import numpy as np\n'), ((9799, 9817), 'numpy.array', 'np.array', (['([i] * sn)'], {}), '([i] * sn)\n', (9807, 9817), True, 'import numpy as np\n'), ((4710, 4772), 'numpy.sum', 'np.sum', (['((self.data_x - self.x_means[j]) ** 2 * contribution[j])'], {}), '((self.data_x - self.x_means[j]) ** 2 * contribution[j])\n', (4716, 4772), True, 'import numpy as np\n'), ((4858, 4920), 'numpy.sum', 'np.sum', (['((self.data_y - self.y_means[j]) ** 2 * contribution[j])'], {}), '((self.data_y - self.y_means[j]) ** 2 * contribution[j])\n', (4864, 4920), True, 'import numpy as np\n'), ((5503, 5543), 'numpy.sqrt', 'np.sqrt', (['(x_dist[i] ** 2 + y_dist[i] ** 2)'], {}), '(x_dist[i] ** 2 + y_dist[i] ** 2)\n', (5510, 5543), True, 'import numpy as np\n'), ((5598, 5646), 'numpy.sqrt', 'np.sqrt', (['(self.x_std[i] ** 2 + self.y_std[i] ** 2)'], {}), '(self.x_std[i] ** 2 + self.y_std[i] ** 2)\n', (5605, 5646), True, 'import numpy as np\n'), ((7588, 7614), 'numpy.linalg.eig', 'np.linalg.eig', (['self.cov[i]'], {}), '(self.cov[i])\n', (7601, 7614), True, 'import numpy as np\n'), ((7716, 7766), 'numpy.arctan2', 'np.arctan2', (['eigenvectors[0][1]', 'eigenvectors[0][0]'], {}), '(eigenvectors[0][1], eigenvectors[0][0])\n', (7726, 7766), True, 'import numpy as np\n'), ((8307, 8384), 'matplotlib.pyplot.fill', 'plt.fill', (['x_points', 'y_points'], {'alpha': '(0.125 / (1 + j))', 'facecolor': 'self.colors[i]'}), '(x_points, y_points, alpha=0.125 / (1 + j), facecolor=self.colors[i])\n', (8315, 8384), True, 'import matplotlib.pyplot as plt\n'), ((1634, 1676), 'numpy.cos', 'np.cos', (['((theta + k / self.k) * 2.0 * np.pi)'], {}), '((theta + k / self.k) * 2.0 * np.pi)\n', (1640, 1676), True, 'import numpy as np\n'), ((1747, 1789), 'numpy.sin', 'np.sin', (['((theta + k / self.k) * 2.0 * np.pi)'], {}), '((theta + k / self.k) * 2.0 * np.pi)\n', (1753, 1789), True, 'import numpy as np\n'), ((4304, 4332), 'numpy.sum', 'np.sum', (['self.weights'], {'axis': '(1)'}), '(self.weights, axis=1)\n', (4310, 4332), True, 'import numpy as np\n'), ((8045, 8055), 'numpy.sqrt', 'np.sqrt', (['c'], {}), '(c)\n', (8052, 8055), True, 'import numpy as np\n'), ((8119, 8129), 'numpy.sqrt', 'np.sqrt', (['c'], {}), '(c)\n', (8126, 8129), True, 'import numpy as np\n'), ((8185, 8215), 'numpy.array', 'np.array', (['[x_points, y_points]'], {}), '([x_points, y_points])\n', (8193, 8215), True, 'import numpy as np\n'), ((2325, 2368), 'numpy.diagflat', 'np.diagflat', (['[avg_xstd ** 2, avg_ystd ** 2]'], {}), '([avg_xstd ** 2, avg_ystd ** 2])\n', (2336, 2368), True, 'import numpy as np\n'), ((7289, 7309), 'numpy.arange', 'np.arange', (['(0)', '(360)', '(2)'], {}), '(0, 360, 2)\n', (7298, 7309), True, 'import numpy as np\n'), ((7802, 7818), 'numpy.cos', 'np.cos', (['rotation'], {}), '(rotation)\n', (7808, 7818), True, 'import numpy as np\n'), ((7875, 7891), 'numpy.sin', 'np.sin', (['rotation'], {}), '(rotation)\n', (7881, 7891), True, 'import numpy as np\n'), ((7893, 7909), 'numpy.cos', 'np.cos', (['rotation'], {}), '(rotation)\n', (7899, 7909), True, 'import numpy as np\n'), ((8029, 8042), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (8035, 8042), True, 'import numpy as np\n'), ((8103, 8116), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (8109, 8116), True, 'import numpy as np\n'), ((7821, 7837), 'numpy.sin', 'np.sin', (['rotation'], {}), '(rotation)\n', (7827, 7837), True, 'import numpy as np\n'), ((3754, 3779), 'numpy.abs', 'np.abs', (['self.cov[j][0, 1]'], {}), '(self.cov[j][0, 1])\n', (3760, 3779), True, 'import numpy as np\n'), ((3660, 3670), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (3667, 3670), True, 'import numpy as np\n'), ((3547, 3557), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (3554, 3557), True, 'import numpy as np\n')]
import gc import os import os.path as p import json import requests from pathlib import Path from typing import List, Tuple, Union import numpy as np import tensorflow as tf import tensorflow_hub as hub from .base_vectorizer import BaseVectorizer tf.logging.set_verbosity(tf.logging.ERROR) __all__ = ['DockerVectorizer', 'SentenceVectorizer'] #### Query Vectorization #### class DockerVectorizer(BaseVectorizer): """ Intended for online query vectorization. Note: Ensure docker container is running before importing class. """ DOCKER_EMB = List[List[np.float32]] def __init__(self, large: bool = False, model_name: str = None): super().__init__() if not model_name and large: model_name = 'USE-large-v3' self.large_USE = True elif not model_name: model_name = 'USE-lite-v2' self.url = f'http://localhost:8501/v1/models/{model_name}:predict' def make_vectors(self, query: Union[str, List[str]]) -> DOCKER_EMB: """ Takes one query """ if not isinstance(query, list): query = [str(query)] elif len(query) > 1: query = query[:1] payload = {"inputs": {"text": query}} payload = json.dumps(payload) response = requests.post(self.url, data=payload) response.raise_for_status() return response.json()['outputs'] #### Corpus Vectorization #### class SentenceVectorizer(BaseVectorizer): """ Intended for batch vectorization of a large text corpus """ ID_BATCH = List[int] SENT_BATCH = List[str] GEN_BATCH = Tuple[ID_BATCH, SENT_BATCH] EMB_BATCH = List[tf.Tensor] def __init__(self, large: bool = False, path_to_model: Path = None): super().__init__() model_parent_dir = p.abspath(p.join(p.dirname(__file__), 'model/')) if large: model_dir = '96e8f1d3d4d90ce86b2db128249eb8143a91db73/' model_url = 'https://tfhub.dev/google/universal-sentence-encoder-large/3' self.large_USE = True else: model_dir = '1fb57c3ffe1a38479233ee9853ddd7a8ac8a8c47/' model_url = 'https://tfhub.dev/google/universal-sentence-encoder/2' model_path = p.join(model_parent_dir, model_dir) if path_to_model: self.path_to_model = p.abspath(path_to_model) elif p.isdir(model_path): self.path_to_model = model_path else: self.path_to_model = model_url os.makedirs(model_parent_dir, exist_ok=True) os.environ['TFHUB_CACHE_DIR'] = model_parent_dir self.graph = None self.model = None self.sess = None print(f'Loading model: {self.path_to_model}') self.define_graph() print('Initializing TF Session...') self.start_session() def define_graph(self): self.graph = tf.get_default_graph() with self.graph.as_default(): self.model = hub.Module(self.path_to_model) def start_session(self): self.sess = tf.Session() with self.graph.as_default(): self.sess.run([tf.global_variables_initializer(), tf.tables_initializer()]) def close_session(self): self.sess.close() tf.reset_default_graph() self.define_graph() @staticmethod def batch_generator(id_sent_tsv: Path, batch_size: int = 128 * 128) -> GEN_BATCH: """ Generator for tf.data.Dataset object """ ids = list() sents = list() with open(p.abspath(id_sent_tsv)) as tsv: for line in tsv: sent_id, sent_text = str(line).replace('\n', '').split('\t') ids.append(int(sent_id)), sents.append(str(sent_text)) while len(sents): yield (list(ids[:batch_size]), list(sents[:batch_size])) ids, sents = list(ids[batch_size:]), list(sents[batch_size:]) gc.collect() def make_vectors(self, sents: List[str], minibatch_size: int = 128) -> EMB_BATCH: """ High throughput, GPU-friendly vectorization """ embeddings = list() batched_tensors = list() with self.graph.as_default(): # High throughput vectorization (fast) if len(sents) > minibatch_size: while len(sents) >= minibatch_size: batch = list(sents[:minibatch_size]) sents = list(sents[minibatch_size:]) batched_tensors.append(tf.constant(batch, dtype=tf.string)) dataset = tf.data.Dataset.from_tensor_slices(batched_tensors) dataset = dataset.make_one_shot_iterator() make_embeddings = self.model(dataset.get_next()) while True: try: embeddings.append(self.sess.run(make_embeddings)) except tf.errors.OutOfRangeError: break # Tail end vectorization (slow) if len(sents): basic_batch = self.model(sents) embeddings.append(self.sess.run(basic_batch)) return embeddings def prep_npz(self, input_tsv: Path, output_npz: Path, batch_size: int = 512 * 128, minibatch_size: int = 128): """ Vectorizes sentences and saves id into a numpy disk array. Avoids redundant computation if index must be rebuilt. :param input_tsv: Path to input file.tsv * Format: int(ID) "sentence" :param output_npz: Path to output file.npz * Items: ['ids'] int (n, ) ['sents'] str (n, ) ['embs'] float32 (n, 512) :param batch_size: N sent yielded by batch_generator :param minibatch_size: batch_size % minibatch_size should be 0 Writes file to path: output_npz """ all_ids, all_sents, all_embs = list(), list(), list() batch_gen = self.batch_generator(input_tsv, batch_size=batch_size) for id_batch, sent_batch in batch_gen: embs = self.make_vectors(sent_batch, minibatch_size=minibatch_size) id_batch = np.array(id_batch, dtype=np.int64) emb_batch = np.vstack(embs).astype(np.float32) sent_batch = np.array(sent_batch, dtype=np.str) all_ids.append(id_batch) all_embs.append(emb_batch) all_sents.append(sent_batch) all_ids = np.concatenate(all_ids, axis=None) all_embs = np.concatenate(all_embs, axis=0) all_sents = np.concatenate(all_sents, axis=None) np.savez(output_npz, ids=all_ids, embs=all_embs, sents=all_sents, compressed=True)
[ "tensorflow_hub.Module", "tensorflow.reset_default_graph", "tensorflow.logging.set_verbosity", "json.dumps", "gc.collect", "tensorflow.tables_initializer", "requests.post", "tensorflow.get_default_graph", "os.path.join", "os.path.abspath", "os.path.dirname", "tensorflow.global_variables_initia...
[((249, 291), 'tensorflow.logging.set_verbosity', 'tf.logging.set_verbosity', (['tf.logging.ERROR'], {}), '(tf.logging.ERROR)\n', (273, 291), True, 'import tensorflow as tf\n'), ((1238, 1257), 'json.dumps', 'json.dumps', (['payload'], {}), '(payload)\n', (1248, 1257), False, 'import json\n'), ((1278, 1315), 'requests.post', 'requests.post', (['self.url'], {'data': 'payload'}), '(self.url, data=payload)\n', (1291, 1315), False, 'import requests\n'), ((2233, 2268), 'os.path.join', 'p.join', (['model_parent_dir', 'model_dir'], {}), '(model_parent_dir, model_dir)\n', (2239, 2268), True, 'import os.path as p\n'), ((2890, 2912), 'tensorflow.get_default_graph', 'tf.get_default_graph', ([], {}), '()\n', (2910, 2912), True, 'import tensorflow as tf\n'), ((3057, 3069), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (3067, 3069), True, 'import tensorflow as tf\n'), ((3287, 3311), 'tensorflow.reset_default_graph', 'tf.reset_default_graph', ([], {}), '()\n', (3309, 3311), True, 'import tensorflow as tf\n'), ((6591, 6625), 'numpy.concatenate', 'np.concatenate', (['all_ids'], {'axis': 'None'}), '(all_ids, axis=None)\n', (6605, 6625), True, 'import numpy as np\n'), ((6645, 6677), 'numpy.concatenate', 'np.concatenate', (['all_embs'], {'axis': '(0)'}), '(all_embs, axis=0)\n', (6659, 6677), True, 'import numpy as np\n'), ((6698, 6734), 'numpy.concatenate', 'np.concatenate', (['all_sents'], {'axis': 'None'}), '(all_sents, axis=None)\n', (6712, 6734), True, 'import numpy as np\n'), ((6744, 6830), 'numpy.savez', 'np.savez', (['output_npz'], {'ids': 'all_ids', 'embs': 'all_embs', 'sents': 'all_sents', 'compressed': '(True)'}), '(output_npz, ids=all_ids, embs=all_embs, sents=all_sents,\n compressed=True)\n', (6752, 6830), True, 'import numpy as np\n'), ((2329, 2353), 'os.path.abspath', 'p.abspath', (['path_to_model'], {}), '(path_to_model)\n', (2338, 2353), True, 'import os.path as p\n'), ((2367, 2386), 'os.path.isdir', 'p.isdir', (['model_path'], {}), '(model_path)\n', (2374, 2386), True, 'import os.path as p\n'), ((2976, 3006), 'tensorflow_hub.Module', 'hub.Module', (['self.path_to_model'], {}), '(self.path_to_model)\n', (2986, 3006), True, 'import tensorflow_hub as hub\n'), ((3975, 3987), 'gc.collect', 'gc.collect', ([], {}), '()\n', (3985, 3987), False, 'import gc\n'), ((6300, 6334), 'numpy.array', 'np.array', (['id_batch'], {'dtype': 'np.int64'}), '(id_batch, dtype=np.int64)\n', (6308, 6334), True, 'import numpy as np\n'), ((6419, 6453), 'numpy.array', 'np.array', (['sent_batch'], {'dtype': 'np.str'}), '(sent_batch, dtype=np.str)\n', (6427, 6453), True, 'import numpy as np\n'), ((1812, 1831), 'os.path.dirname', 'p.dirname', (['__file__'], {}), '(__file__)\n', (1821, 1831), True, 'import os.path as p\n'), ((2501, 2545), 'os.makedirs', 'os.makedirs', (['model_parent_dir'], {'exist_ok': '(True)'}), '(model_parent_dir, exist_ok=True)\n', (2512, 2545), False, 'import os\n'), ((3584, 3606), 'os.path.abspath', 'p.abspath', (['id_sent_tsv'], {}), '(id_sent_tsv)\n', (3593, 3606), True, 'import os.path as p\n'), ((4624, 4675), 'tensorflow.data.Dataset.from_tensor_slices', 'tf.data.Dataset.from_tensor_slices', (['batched_tensors'], {}), '(batched_tensors)\n', (4658, 4675), True, 'import tensorflow as tf\n'), ((3135, 3168), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (3166, 3168), True, 'import tensorflow as tf\n'), ((3197, 3220), 'tensorflow.tables_initializer', 'tf.tables_initializer', ([], {}), '()\n', (3218, 3220), True, 'import tensorflow as tf\n'), ((6359, 6374), 'numpy.vstack', 'np.vstack', (['embs'], {}), '(embs)\n', (6368, 6374), True, 'import numpy as np\n'), ((4560, 4595), 'tensorflow.constant', 'tf.constant', (['batch'], {'dtype': 'tf.string'}), '(batch, dtype=tf.string)\n', (4571, 4595), True, 'import tensorflow as tf\n')]
import sys import typing import numba as nb import numpy as np @nb.njit((nb.b1[:], ), cache=True) def solve(c: np.ndarray) -> typing.NoReturn: n = len(c) a = np.sort(c)[::-1] s = 0 for i in range(n): s += a[i] != c[i] print(s // 2) def main() -> typing.NoReturn: n = int(sys.stdin.buffer.readline().rstrip()) c = np.frombuffer( sys.stdin.buffer.readline().rstrip(), dtype='S1', ) == b'R' solve(c) main()
[ "numpy.sort", "sys.stdin.buffer.readline", "numba.njit" ]
[((74, 106), 'numba.njit', 'nb.njit', (['(nb.b1[:],)'], {'cache': '(True)'}), '((nb.b1[:],), cache=True)\n', (81, 106), True, 'import numba as nb\n'), ((175, 185), 'numpy.sort', 'np.sort', (['c'], {}), '(c)\n', (182, 185), True, 'import numpy as np\n'), ((310, 337), 'sys.stdin.buffer.readline', 'sys.stdin.buffer.readline', ([], {}), '()\n', (335, 337), False, 'import sys\n'), ((375, 402), 'sys.stdin.buffer.readline', 'sys.stdin.buffer.readline', ([], {}), '()\n', (400, 402), False, 'import sys\n')]
from mpnum.utils.extmath import matdot import numpy as np from scipy.linalg import svd class LocalCompression: """Container for local compression parameters (so they don't have to be passed every time)""" def __init__(self, relerr=1e-10, rank=None, stable=False, direction=None, canonicalize=True, reduced_canonicalization=True, **kwargs): """ See the StarTMP real time propagator factory docstring for an explanation of the parameters """ self.relerr = relerr self.rank = rank self.stable = stable self.direction = direction self.canonicalize = canonicalize self.reduced_canonicalization = reduced_canonicalization def compress(self, mpa, bond): """ Compresses the mpa bond with index 'site' """ ln, rn = mpa.canonical_form default_direction = 'left' if len(mpa) - rn > ln else 'right' direction = default_direction if self.direction is None else self.direction if direction == 'right': if self.canonicalize: if self.reduced_canonicalization: mpa.canonicalize(right=bond + 1) else: mpa.canonicalize(right=1) self._local_svd_r_compression(mpa, bond) elif direction == 'left': if self.canonicalize: if self.reduced_canonicalization: mpa.canonicalize(left=bond + 1) else: mpa.canonicalize(left=len(mpa) - 1) self._local_svd_l_compression(mpa, bond + 1) else: raise ValueError('{} is not a valid direction'.format(direction)) def _local_svd_r_compression(self, mpa, site): """ SVD for a single site in the mpa chain for a right canonicalized chain :return: """ rank = max(mpa.ranks) if self.rank is None else self.rank ltens = mpa._lt[site] matshape = (-1, ltens.shape[-1]) if not self.stable: try: u, sv, v = svd(ltens.reshape(matshape), lapack_driver='gesdd', full_matrices=False) except np.linalg.LinAlgError: u, sv, v = svd(ltens.reshape(matshape), lapack_driver='gesvd', overwrite_a=True, full_matrices=False) else: u, sv, v = svd(ltens.reshape(matshape), lapack_driver='gesvd', overwrite_a=True, full_matrices=False) if self.relerr is None: k_prime = min(rank, len(sv)) u = u[:, :k_prime] sv = sv[:k_prime] v = v[:k_prime, :] rank_t = len(sv) else: svsum = np.cumsum(sv) / np.sum(sv) rank_relerr = np.searchsorted(svsum, 1 - self.relerr) + 1 rank_t = min(ltens.shape[-1], u.shape[1], rank, rank_relerr) # If the compressed u is small enough, copy it and let the gc clean up the original u if u[:rank_t, :].size / u.size < 0.7: newtens = (u[:, :rank_t].reshape(ltens.shape[:-1] + (rank_t,)).copy(), matdot(sv[:rank_t, None] * v[:rank_t, :], mpa._lt[site + 1])) else: newtens = (u[:, :rank_t].reshape(ltens.shape[:-1] + (rank_t,)), matdot(sv[:rank_t, None] * v[:rank_t, :], mpa._lt[site + 1])) mpa._lt.update(slice(site, site + 2), newtens, canonicalization=('left', None)) def _local_svd_l_compression(self, mpa, site): """ SVD for a single site in the mpa chain for a left canonicalized chain :return: """ rank = max(mpa.ranks) if self.rank is None else self.rank ltens = mpa._lt[site] matshape = (ltens.shape[0], -1) if not self.stable: try: u, sv, v = svd(ltens.reshape(matshape), lapack_driver='gesdd', full_matrices=False) except np.linalg.LinAlgError: u, sv, v = svd(ltens.reshape(matshape), lapack_driver='gesvd', overwrite_a=True, full_matrices=False) else: u, sv, v = svd(ltens.reshape(matshape), lapack_driver='gesvd', overwrite_a=True, full_matrices=False) if self.relerr is None: k_prime = min(rank, len(sv)) u = u[:, :k_prime] sv = sv[:k_prime] v = v[:k_prime, :] rank_t = len(sv) else: svsum = np.cumsum(sv) / np.sum(sv) rank_relerr = np.searchsorted(svsum, 1 - self.relerr) + 1 rank_t = min(ltens.shape[0], v.shape[0], rank, rank_relerr) # If the compressed v is small enough, copy it and let the gc clean up the original v if v[:rank_t, :].size / v.size < 0.7: newtens = (matdot(mpa._lt[site - 1], u[:, :rank_t] * sv[None, :rank_t]), v[:rank_t, :].reshape((rank_t,) + ltens.shape[1:]).copy()) else: newtens = (matdot(mpa._lt[site - 1], u[:, :rank_t] * sv[None, :rank_t]), v[:rank_t, :].reshape((rank_t,) + ltens.shape[1:])) mpa._lt.update(slice(site - 1, site + 1), newtens, canonicalization=(None, 'right')) def update(self, relerr=1e-10, rank=None, direction=None, stable=False, canonicalize_every_step=True, reduced_canonicalization=True, **kwargs): self.relerr = relerr self.rank = rank self.stable = stable self.direction = direction self.canonicalize = canonicalize_every_step self.reduced_canonicalization = reduced_canonicalization def local_svd_compression(mpa, bond, relerr=1e-10, rank=None, stable=False, direction=None, canonicalize=True, reduced_canonicalization=True, **kwargs): """ SVD for a single bond in the mpa chain """ lc = LocalCompression(relerr=relerr, rank=rank, stable=stable, direction=direction, canonicalize=canonicalize, reduced_canonicalization=reduced_canonicalization) lc.compress(mpa, bond)
[ "numpy.cumsum", "numpy.sum", "numpy.searchsorted", "mpnum.utils.extmath.matdot" ]
[((2745, 2758), 'numpy.cumsum', 'np.cumsum', (['sv'], {}), '(sv)\n', (2754, 2758), True, 'import numpy as np\n'), ((2761, 2771), 'numpy.sum', 'np.sum', (['sv'], {}), '(sv)\n', (2767, 2771), True, 'import numpy as np\n'), ((2798, 2837), 'numpy.searchsorted', 'np.searchsorted', (['svsum', '(1 - self.relerr)'], {}), '(svsum, 1 - self.relerr)\n', (2813, 2837), True, 'import numpy as np\n'), ((3161, 3221), 'mpnum.utils.extmath.matdot', 'matdot', (['(sv[:rank_t, None] * v[:rank_t, :])', 'mpa._lt[site + 1]'], {}), '(sv[:rank_t, None] * v[:rank_t, :], mpa._lt[site + 1])\n', (3167, 3221), False, 'from mpnum.utils.extmath import matdot\n'), ((3336, 3396), 'mpnum.utils.extmath.matdot', 'matdot', (['(sv[:rank_t, None] * v[:rank_t, :])', 'mpa._lt[site + 1]'], {}), '(sv[:rank_t, None] * v[:rank_t, :], mpa._lt[site + 1])\n', (3342, 3396), False, 'from mpnum.utils.extmath import matdot\n'), ((4518, 4531), 'numpy.cumsum', 'np.cumsum', (['sv'], {}), '(sv)\n', (4527, 4531), True, 'import numpy as np\n'), ((4534, 4544), 'numpy.sum', 'np.sum', (['sv'], {}), '(sv)\n', (4540, 4544), True, 'import numpy as np\n'), ((4571, 4610), 'numpy.searchsorted', 'np.searchsorted', (['svsum', '(1 - self.relerr)'], {}), '(svsum, 1 - self.relerr)\n', (4586, 4610), True, 'import numpy as np\n'), ((4850, 4910), 'mpnum.utils.extmath.matdot', 'matdot', (['mpa._lt[site - 1]', '(u[:, :rank_t] * sv[None, :rank_t])'], {}), '(mpa._lt[site - 1], u[:, :rank_t] * sv[None, :rank_t])\n', (4856, 4910), False, 'from mpnum.utils.extmath import matdot\n'), ((5031, 5091), 'mpnum.utils.extmath.matdot', 'matdot', (['mpa._lt[site - 1]', '(u[:, :rank_t] * sv[None, :rank_t])'], {}), '(mpa._lt[site - 1], u[:, :rank_t] * sv[None, :rank_t])\n', (5037, 5091), False, 'from mpnum.utils.extmath import matdot\n')]
import cv2 import numpy as np class PageExtractor: def __init__(self, output_process=False): self.output_process = output_process self.src = None self.dst = None self.m = None self.max_width = None self.max_height = None def __call__(self, image, quad): warped = image.copy() rect = PageExtractor.order_points(quad) (tl, tr, br, bl) = rect rect = np.array(rect, dtype = "float32") # compute the width of the new image, which will be the # maximum distance between bottom-right and bottom-left # x-coordiates or the top-right and top-left x-coordinates widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2)) widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2)) maxWidth = max(int(widthA), int(widthB)) # compute the height of the new image, which will be the # maximum distance between the top-right and bottom-right # y-coordinates or the top-left and bottom-left y-coordinates heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2)) heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2)) maxHeight = max(int(heightA), int(heightB)) # now that we have the dimensions of the new image, construct # the set of destination points to obtain a "birds eye view", # (i.e. top-down view) of the image, again specifying points # in the top-left, top-right, bottom-right, and bottom-left # order dst = np.array([ [0, 0], # Top left point [maxWidth - 1, 0], # Top right point [maxWidth - 1, maxHeight - 1], # Bottom right point [0, maxHeight - 1]], # Bottom left point dtype = "float32" # Date type ) # compute the perspective transform matrix and then apply it M = cv2.getPerspectiveTransform(rect, dst) warped = cv2.warpPerspective(warped, M, (maxWidth, maxHeight)) if self.output_process: cv2.imwrite('output/deskewed.jpg', warped) self.src = rect self.dst = dst self.m = M self.max_width = maxWidth self.max_height = maxHeight # for the entire image, not just the height of the extracted quadrilateral self.src_img_dims = image.shape return warped def reverse_skew(self, image): m_inv = cv2.getPerspectiveTransform(self.dst, self.src) unskewed = cv2.warpPerspective(image, m_inv, (self.src_img_dims[1], self.src_img_dims[0])) return unskewed @classmethod def order_points(cls, quad): summed = [sum(p[0]) for p in quad] topleft = quad[summed.index(min(summed))][0] bottomright = quad[summed.index(max(summed))][0] remain = [] for i, x in enumerate(quad): if not i in [summed.index(min(summed)), summed.index(max(summed))]: remain.append(x[0]) # bottom left has steeper gradient from topleft grads = [abs((topleft[1]-y)/(topleft[0]-x+1e-12)) for x,y in remain] bottomleft = remain[grads.index(max(grads))] topright = remain[grads.index(min(grads))] topleft = [c for c in map(int, topleft)] topright = [c for c in map(int, topright)] bottomleft = [c for c in map(int, bottomleft)] bottomright = [c for c in map(int, bottomright)] topleft = tuple(topleft) topright = tuple(topright) bottomleft = tuple(bottomleft) bottomright = tuple(bottomright) return topleft, topright, bottomright, bottomleft def set_force_output_process(self): self.output_process = True
[ "cv2.warpPerspective", "cv2.getPerspectiveTransform", "cv2.imwrite", "numpy.array", "numpy.sqrt" ]
[((389, 420), 'numpy.array', 'np.array', (['rect'], {'dtype': '"""float32"""'}), "(rect, dtype='float32')\n", (397, 420), True, 'import numpy as np\n'), ((617, 669), 'numpy.sqrt', 'np.sqrt', (['((br[0] - bl[0]) ** 2 + (br[1] - bl[1]) ** 2)'], {}), '((br[0] - bl[0]) ** 2 + (br[1] - bl[1]) ** 2)\n', (624, 669), True, 'import numpy as np\n'), ((686, 738), 'numpy.sqrt', 'np.sqrt', (['((tr[0] - tl[0]) ** 2 + (tr[1] - tl[1]) ** 2)'], {}), '((tr[0] - tl[0]) ** 2 + (tr[1] - tl[1]) ** 2)\n', (693, 738), True, 'import numpy as np\n'), ((988, 1040), 'numpy.sqrt', 'np.sqrt', (['((tr[0] - br[0]) ** 2 + (tr[1] - br[1]) ** 2)'], {}), '((tr[0] - br[0]) ** 2 + (tr[1] - br[1]) ** 2)\n', (995, 1040), True, 'import numpy as np\n'), ((1058, 1110), 'numpy.sqrt', 'np.sqrt', (['((tl[0] - bl[0]) ** 2 + (tl[1] - bl[1]) ** 2)'], {}), '((tl[0] - bl[0]) ** 2 + (tl[1] - bl[1]) ** 2)\n', (1065, 1110), True, 'import numpy as np\n'), ((1441, 1551), 'numpy.array', 'np.array', (['[[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]]'], {'dtype': '"""float32"""'}), "([[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, \n maxHeight - 1]], dtype='float32')\n", (1449, 1551), True, 'import numpy as np\n'), ((1798, 1836), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['rect', 'dst'], {}), '(rect, dst)\n', (1825, 1836), False, 'import cv2\n'), ((1849, 1902), 'cv2.warpPerspective', 'cv2.warpPerspective', (['warped', 'M', '(maxWidth, maxHeight)'], {}), '(warped, M, (maxWidth, maxHeight))\n', (1868, 1902), False, 'import cv2\n'), ((2272, 2319), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['self.dst', 'self.src'], {}), '(self.dst, self.src)\n', (2299, 2319), False, 'import cv2\n'), ((2334, 2413), 'cv2.warpPerspective', 'cv2.warpPerspective', (['image', 'm_inv', '(self.src_img_dims[1], self.src_img_dims[0])'], {}), '(image, m_inv, (self.src_img_dims[1], self.src_img_dims[0]))\n', (2353, 2413), False, 'import cv2\n'), ((1936, 1978), 'cv2.imwrite', 'cv2.imwrite', (['"""output/deskewed.jpg"""', 'warped'], {}), "('output/deskewed.jpg', warped)\n", (1947, 1978), False, 'import cv2\n')]
#! /usr/bin/env python3 # Copyright (c) 2017 <NAME> import openpyxl as opx import numpy as np from scipy import interpolate import matplotlib.pyplot as plt import math import argparse import os def is_number(s): """Return True if the value is a number.""" try: float(s) return True except ValueError: return False def findFirstCell(sheet, search_str): """Return a coordinate tuple of the first containing the keyword. Usage: findFirstCell(sheet, 'Te') params: sheet: openpyxl.worksheet Excel worksheet object returns: coordinate(row, column) Excel coordinate of the cell """ for row in sheet.iter_rows(): for cell in row: if search_str in str(cell.value): return opx.utils.cell.coordinate_to_tuple(cell.coordinate) def plotComparison(raw_list, std_list, lin_list, custom_fn): """Plot concentration vs cps for different interpolating method all lists are in increasing order. Usage: plotComparison(raw_list, std_list, lin_list, f) params: raw_list: List List of raw cps data std_list: List List of concentrations of standard samples (ug/L) lin_list: List List of concentrations of analyzed Cal-10 to Cal-1 custom_fn: Scipy.interpolate.InterpolatedUnivariateSpline object or other function that can return y from custom_fn(x) Function of custom interpolated fitting """ digits = round(math.log10(max(raw_list))) # generate a list with log interval from 1 to the max of raw_list xlog = np.logspace(1, digits) ylog = custom_fn(xlog) # plot comparing the fitting plt.loglog(raw_list, std_list, 'o', label='standard') plt.loglog(raw_list, lin_list, label='linear fitting from Agilent 8800') plt.loglog(xlog, ylog, label='interpolated univariate spline (k=1)') plt.xlabel('CPS') plt.ylabel('Concentration (ug/L)') plt.title("Different interpolations") plt.legend(loc = 'upper left') plt.show() def main(): """ Add 1-degree interpolation smoothing spline for ICP-MS concentration. Modify the analyzed concentrations from Agilent ICP-MS 8800 QQQ. Use 1-degree smoothing spline for linear interpolation between each data points The fitting out of the standard range is a linear extrapolation from the minimum and maximum data points *this fixes one element at a time Example: python3 interp.icpms.py Te standard.xlsx raw_data.xlsx analyzed_data.xlsx Author: <NAME> """ parser = argparse.ArgumentParser(description = main.__doc__, formatter_class = argparse.RawDescriptionHelpFormatter) parser.add_argument('element', help = "Element to modify") parser.add_argument('std_filename', help = "Excel for standard concentration") parser.add_argument('raw_filename', help = "Excel for raw data in CPS") parser.add_argument('alz_filename', help = "Excel for analyzed data in ug/L") parser.add_argument('-v', "--verbosity", action = "store_true", default = False, help = "increase output verbosity") parser.add_argument('-p', help = "Print comparison graph", action = "store_true", default = False) parser.add_argument('-k', help = "Degree of smoothing spline", default = 1) args = parser.parse_args() global raw_filename, std_filename, alz_filename, v_value, p_value, k_value el = args.element raw_filename = args.raw_filename std_filename = args.std_filename alz_filename = args.alz_filename v_value = args.verbosity p_value = args.p k_value = args.k process(el, std_filename, raw_filename, alz_filename, v_value, p_value, k_value) def process(el, std_filename, raw_filename, alz_filename, v_value, p_value, k_value): """ Process data read from the given Excel files Usage: process('Te', 'std.xlsx', 'raw.xlsx', 'alz.xlsx', True, False, 1): params: el: str Name of the element to be modified std_filename: str Filename for standard concentration raw_filename: str Filename for raw data in CPS alz_filename: str Filename for analyzed data in ug/L v_value: bool Boolean value for increase verbosity p_value: bool Boolean value for graph plotting k_value: bool Degree of smoothing spline """ print("Loading standard file:", std_filename) std = opx.load_workbook(std_filename, data_only = True) std_sheet = std.get_sheet_by_name(std.get_sheet_names()[0]) keyword_coord = findFirstCell(std_sheet,'Final:') element_list_row = keyword_coord[0]-1 std_list = [] for element_col in std_sheet.iter_cols( min_row = element_list_row, min_col = (keyword_coord[1]+1)): if el in element_col[0].value: for cell in element_col[2:]: std_list.append(cell.value) std_list = std_list[::-1] print("Loading raw file:", raw_filename) raw = opx.load_workbook(raw_filename, data_only = True) raw_sheet = raw.get_sheet_by_name(raw.get_sheet_names()[0]) raw_list = [] for raw_element_col in raw_sheet.iter_cols(max_row = 13): if el in str(raw_element_col[0].value): for cell in raw_element_col[3:]: raw_list.append(cell.value) f1d = interpolate.InterpolatedUnivariateSpline(raw_list, std_list, k=k_value) print("Loading analyzed file:", alz_filename) alz = opx.load_workbook(alz_filename, data_only = True) alz_sheet = alz.get_sheet_by_name(alz.get_sheet_names()[0]) samplename_column = findFirstCell(alz_sheet, 'Sample Name')[1] print("Converting...") name_list = [] lin_list = [] el_col = opx.utils.get_column_letter(findFirstCell(alz_sheet, el)[1]) for raw_element_col in raw_sheet.iter_cols(): if 'Sample Name' in str(raw_element_col[1].value): for cell in raw_element_col[2:]: name_list.append(cell.value) if (el in str(raw_element_col[0].value)): i = 0 status = 'CPS' for cell in raw_element_col[2:]: if 0 < i <=10: lin_list.append(alz_sheet[el_col + str(cell.row)].value) if is_number(cell.value): try: value_new = float(f1d(cell.value)) value_old = alz_sheet[el_col + str(cell.row)].value if v_value : print("Converting", name_list[i], status, ": (", cell.value, " )", value_old, "-->", value_new) alz_sheet[el_col + str(cell.row)].value = value_new except: print(name_list[i], ": cannot convert -- value: ", cell.value) else: print(name_list[i], ": not float -- value: ", cell.value) i += 1 save_filename = os.path.splitext(alz_filename)[0] + "_mod.xlsx" alz.save(save_filename) print("Converted successfully. Saved as", save_filename) if p_value : plotComparison(raw_list, std_list, lin_list, f1d) if __name__ == '__main__': main()
[ "matplotlib.pyplot.loglog", "matplotlib.pyplot.title", "matplotlib.pyplot.show", "argparse.ArgumentParser", "scipy.interpolate.InterpolatedUnivariateSpline", "numpy.logspace", "matplotlib.pyplot.legend", "openpyxl.load_workbook", "os.path.splitext", "openpyxl.utils.cell.coordinate_to_tuple", "ma...
[((1603, 1625), 'numpy.logspace', 'np.logspace', (['(1)', 'digits'], {}), '(1, digits)\n', (1614, 1625), True, 'import numpy as np\n'), ((1691, 1744), 'matplotlib.pyplot.loglog', 'plt.loglog', (['raw_list', 'std_list', '"""o"""'], {'label': '"""standard"""'}), "(raw_list, std_list, 'o', label='standard')\n", (1701, 1744), True, 'import matplotlib.pyplot as plt\n'), ((1749, 1821), 'matplotlib.pyplot.loglog', 'plt.loglog', (['raw_list', 'lin_list'], {'label': '"""linear fitting from Agilent 8800"""'}), "(raw_list, lin_list, label='linear fitting from Agilent 8800')\n", (1759, 1821), True, 'import matplotlib.pyplot as plt\n'), ((1826, 1894), 'matplotlib.pyplot.loglog', 'plt.loglog', (['xlog', 'ylog'], {'label': '"""interpolated univariate spline (k=1)"""'}), "(xlog, ylog, label='interpolated univariate spline (k=1)')\n", (1836, 1894), True, 'import matplotlib.pyplot as plt\n'), ((1900, 1917), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""CPS"""'], {}), "('CPS')\n", (1910, 1917), True, 'import matplotlib.pyplot as plt\n'), ((1922, 1956), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Concentration (ug/L)"""'], {}), "('Concentration (ug/L)')\n", (1932, 1956), True, 'import matplotlib.pyplot as plt\n'), ((1962, 1999), 'matplotlib.pyplot.title', 'plt.title', (['"""Different interpolations"""'], {}), "('Different interpolations')\n", (1971, 1999), True, 'import matplotlib.pyplot as plt\n'), ((2005, 2033), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""'}), "(loc='upper left')\n", (2015, 2033), True, 'import matplotlib.pyplot as plt\n'), ((2040, 2050), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2048, 2050), True, 'import matplotlib.pyplot as plt\n'), ((2582, 2690), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': 'main.__doc__', 'formatter_class': 'argparse.RawDescriptionHelpFormatter'}), '(description=main.__doc__, formatter_class=argparse.\n RawDescriptionHelpFormatter)\n', (2605, 2690), False, 'import argparse\n'), ((4457, 4504), 'openpyxl.load_workbook', 'opx.load_workbook', (['std_filename'], {'data_only': '(True)'}), '(std_filename, data_only=True)\n', (4474, 4504), True, 'import openpyxl as opx\n'), ((5025, 5072), 'openpyxl.load_workbook', 'opx.load_workbook', (['raw_filename'], {'data_only': '(True)'}), '(raw_filename, data_only=True)\n', (5042, 5072), True, 'import openpyxl as opx\n'), ((5368, 5439), 'scipy.interpolate.InterpolatedUnivariateSpline', 'interpolate.InterpolatedUnivariateSpline', (['raw_list', 'std_list'], {'k': 'k_value'}), '(raw_list, std_list, k=k_value)\n', (5408, 5439), False, 'from scipy import interpolate\n'), ((5501, 5548), 'openpyxl.load_workbook', 'opx.load_workbook', (['alz_filename'], {'data_only': '(True)'}), '(alz_filename, data_only=True)\n', (5518, 5548), True, 'import openpyxl as opx\n'), ((7004, 7034), 'os.path.splitext', 'os.path.splitext', (['alz_filename'], {}), '(alz_filename)\n', (7020, 7034), False, 'import os\n'), ((791, 842), 'openpyxl.utils.cell.coordinate_to_tuple', 'opx.utils.cell.coordinate_to_tuple', (['cell.coordinate'], {}), '(cell.coordinate)\n', (825, 842), True, 'import openpyxl as opx\n')]
from __future__ import division import math import numpy as np from typing import Optional def build_sinusoidal_positional_embedding( num_embeddings: int, embedding_dim: int, padding_idx: Optional[int] = None, dtype=np.float32 ): """ Build sinusoidal embeddings """ half_dim = embedding_dim // 2 emb = math.log(10000) / (half_dim - 1) emb = np.exp(-emb * np.arange(half_dim, dtype=dtype)) emb = np.arange(num_embeddings, dtype=dtype)[:, None] * emb[None, :] emb = np.concatenate([np.sin(emb), np.cos(emb)], axis=1) emb = np.reshape(emb, [num_embeddings, -1]) if embedding_dim % 2 == 1: # zero pad emb = np.concatenate( [emb, np.zeros(shape=[num_embeddings, 1], dtype=dtype)], axis=1 ) if padding_idx is not None: emb[padding_idx, :] = 0 return emb
[ "numpy.zeros", "numpy.sin", "numpy.arange", "numpy.reshape", "numpy.cos", "math.log" ]
[((576, 613), 'numpy.reshape', 'np.reshape', (['emb', '[num_embeddings, -1]'], {}), '(emb, [num_embeddings, -1])\n', (586, 613), True, 'import numpy as np\n'), ((341, 356), 'math.log', 'math.log', (['(10000)'], {}), '(10000)\n', (349, 356), False, 'import math\n'), ((398, 430), 'numpy.arange', 'np.arange', (['half_dim'], {'dtype': 'dtype'}), '(half_dim, dtype=dtype)\n', (407, 430), True, 'import numpy as np\n'), ((442, 480), 'numpy.arange', 'np.arange', (['num_embeddings'], {'dtype': 'dtype'}), '(num_embeddings, dtype=dtype)\n', (451, 480), True, 'import numpy as np\n'), ((531, 542), 'numpy.sin', 'np.sin', (['emb'], {}), '(emb)\n', (537, 542), True, 'import numpy as np\n'), ((544, 555), 'numpy.cos', 'np.cos', (['emb'], {}), '(emb)\n', (550, 555), True, 'import numpy as np\n'), ((712, 760), 'numpy.zeros', 'np.zeros', ([], {'shape': '[num_embeddings, 1]', 'dtype': 'dtype'}), '(shape=[num_embeddings, 1], dtype=dtype)\n', (720, 760), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ Created on Tue Feb 23 12:26:05 2021 @author: <NAME> """ import numpy as np import matplotlib.pyplot as plt from numpy import pi as π from pathlib import Path import pycoilib as pycoil from pycoilib.segment import Arc, Line, Circle vec_x = np.array([1., 0., 0.]) vec_y = np.array([0., 1., 0.]) vec_z = np.array([0., 0., 1.]) vec_0 = np.array([0., 0., 0.]) ell = 0.10 a = 0.001 θ = np.linspace(0., 2 * π, round(360 / 5 + 1)) wire = pycoil.wire.WireCircular(a) inductance = [] # Premier cas : line line = Line(np.array([0., 0., 0.]), np.array([0., 0., ell])) coil = pycoil.coil.Coil([line], wire) inductance.append(coil.get_inductance()) # Premier line : arc for θ_i in θ[1:]: R = ell / θ_i arc = Arc(R, θ_i, vec_0, vec_x, vec_y, vec_z) coil = pycoil.coil.Coil([arc], wire) inductance.append(coil.get_inductance()) inductance = np.array(inductance) loop = Circle(R) I_loop = pycoil.coil.Coil([loop], wire).get_inductance() I_line = inductance[0] fig = plt.figure(figsize=(6.5 / 2.54, 5. / 2.54), dpi=300) ax = plt.gca() plt.plot(θ / (2 * π), inductance / 1e-9, ) plt.plot(θ / (2 * π), inductance ** 0 * I_line / 1e-9, "gray", lw=1, alpha=0.5) plt.plot(θ / (2 * π), inductance ** 0 * I_loop / 1e-9, "gray", lw=1, alpha=0.5) # ax.set_ylim([55,90]) ax.set_xlabel(r"Arc angle [$2\pi$]") ax.set_ylabel(r"Inductance [nH]") props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) ax.text(0.05, 0.18, r"Self of a Circle", transform=ax.transAxes, fontsize=8, verticalalignment='top', c="gray") ax.text(0.60, 0.92, r"Self of a line", transform=ax.transAxes, fontsize=8, verticalalignment='top', c="gray") ax.text(0.60, 0.92, r"Self of a line", transform=ax.transAxes, fontsize=8, verticalalignment='top', c="gray") fig.tight_layout() # fig.savefig(Path("output/Appli-fil-courbe.png"), dpi=300) plt.show()
[ "pycoilib.segment.Circle", "matplotlib.pyplot.show", "pycoilib.coil.Coil", "matplotlib.pyplot.plot", "pycoilib.wire.WireCircular", "matplotlib.pyplot.figure", "numpy.array", "pycoilib.segment.Arc", "matplotlib.pyplot.gca" ]
[((273, 298), 'numpy.array', 'np.array', (['[1.0, 0.0, 0.0]'], {}), '([1.0, 0.0, 0.0])\n', (281, 298), True, 'import numpy as np\n'), ((304, 329), 'numpy.array', 'np.array', (['[0.0, 1.0, 0.0]'], {}), '([0.0, 1.0, 0.0])\n', (312, 329), True, 'import numpy as np\n'), ((335, 360), 'numpy.array', 'np.array', (['[0.0, 0.0, 1.0]'], {}), '([0.0, 0.0, 1.0])\n', (343, 360), True, 'import numpy as np\n'), ((366, 391), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (374, 391), True, 'import numpy as np\n'), ((466, 493), 'pycoilib.wire.WireCircular', 'pycoil.wire.WireCircular', (['a'], {}), '(a)\n', (490, 493), True, 'import pycoilib as pycoil\n'), ((601, 631), 'pycoilib.coil.Coil', 'pycoil.coil.Coil', (['[line]', 'wire'], {}), '([line], wire)\n', (617, 631), True, 'import pycoilib as pycoil\n'), ((880, 900), 'numpy.array', 'np.array', (['inductance'], {}), '(inductance)\n', (888, 900), True, 'import numpy as np\n'), ((909, 918), 'pycoilib.segment.Circle', 'Circle', (['R'], {}), '(R)\n', (915, 918), False, 'from pycoilib.segment import Arc, Line, Circle\n'), ((1006, 1059), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(6.5 / 2.54, 5.0 / 2.54)', 'dpi': '(300)'}), '(figsize=(6.5 / 2.54, 5.0 / 2.54), dpi=300)\n', (1016, 1059), True, 'import matplotlib.pyplot as plt\n'), ((1064, 1073), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (1071, 1073), True, 'import matplotlib.pyplot as plt\n'), ((1075, 1116), 'matplotlib.pyplot.plot', 'plt.plot', (['(θ / (2 * π))', '(inductance / 1e-09)'], {}), '(θ / (2 * π), inductance / 1e-09)\n', (1083, 1116), True, 'import matplotlib.pyplot as plt\n'), ((1118, 1203), 'matplotlib.pyplot.plot', 'plt.plot', (['(θ / (2 * π))', '(inductance ** 0 * I_line / 1e-09)', '"""gray"""'], {'lw': '(1)', 'alpha': '(0.5)'}), "(θ / (2 * π), inductance ** 0 * I_line / 1e-09, 'gray', lw=1, alpha=0.5\n )\n", (1126, 1203), True, 'import matplotlib.pyplot as plt\n'), ((1198, 1283), 'matplotlib.pyplot.plot', 'plt.plot', (['(θ / (2 * π))', '(inductance ** 0 * I_loop / 1e-09)', '"""gray"""'], {'lw': '(1)', 'alpha': '(0.5)'}), "(θ / (2 * π), inductance ** 0 * I_loop / 1e-09, 'gray', lw=1, alpha=0.5\n )\n", (1206, 1283), True, 'import matplotlib.pyplot as plt\n'), ((1874, 1884), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1882, 1884), True, 'import matplotlib.pyplot as plt\n'), ((545, 570), 'numpy.array', 'np.array', (['[0.0, 0.0, 0.0]'], {}), '([0.0, 0.0, 0.0])\n', (553, 570), True, 'import numpy as np\n'), ((569, 594), 'numpy.array', 'np.array', (['[0.0, 0.0, ell]'], {}), '([0.0, 0.0, ell])\n', (577, 594), True, 'import numpy as np\n'), ((741, 780), 'pycoilib.segment.Arc', 'Arc', (['R', 'θ_i', 'vec_0', 'vec_x', 'vec_y', 'vec_z'], {}), '(R, θ_i, vec_0, vec_x, vec_y, vec_z)\n', (744, 780), False, 'from pycoilib.segment import Arc, Line, Circle\n'), ((792, 821), 'pycoilib.coil.Coil', 'pycoil.coil.Coil', (['[arc]', 'wire'], {}), '([arc], wire)\n', (808, 821), True, 'import pycoilib as pycoil\n'), ((928, 958), 'pycoilib.coil.Coil', 'pycoil.coil.Coil', (['[loop]', 'wire'], {}), '([loop], wire)\n', (944, 958), True, 'import pycoilib as pycoil\n')]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ GreedyPy - greedy weak diffeomorphic registration in python Copyright: <NAME> Began: November 2019 """ import numpy as np from itertools import product class local_correlation: # TODO: store rad and tolerance in class def __init__(self, fixed, moving, rad, tolerance=1e-6): """ """ s = self s.mov_mean = np.mean(moving) # should recomp after interp, but accurate enough s.mov_winsor_min, s.mov_winsor_max = np.percentile(moving, [0.1, 99.9]) s.fix_mean = np.mean(fixed) s.fix_shifted = fixed - s.fix_mean s.u_fix_shifted = s._local_means(s.fix_shifted, rad) s.u_fix = s.u_fix_shifted + s.fix_mean s.v_fix = s._local_means(s.fix_shifted**2, rad) - s.u_fix_shifted**2 winsor_min, winsor_max = np.percentile(fixed, [0.1, 99.9]) s.fix_mask = s.v_fix / (winsor_max - winsor_min) < tolerance def evaluate(self, fixed, moving, rad, tolerance=1e-6, mean=True): """ """ s = self mov_shifted = moving - s.mov_mean u_mov_shifted = s._local_means(mov_shifted, rad) u_mov = u_mov_shifted + s.mov_mean v_mov = s._local_means(mov_shifted**2, rad) - u_mov_shifted**2 mov_mask = v_mov / (s.mov_winsor_max - s.mov_winsor_min) < tolerance v_fixmov = s._local_means(s.fix_shifted*mov_shifted, rad) - \ s.u_fix_shifted*u_mov_shifted with np.errstate(divide='ignore', invalid='ignore'): cc = v_fixmov**2 / (s.v_fix * v_mov) if mean: cc = -np.mean(cc[~(s.fix_mask + mov_mask)]) return cc def gradient(self, fixed, moving, rad, vox, tolerance=1e-6): """ """ s = self mov_shifted = moving - s.mov_mean u_mov_shifted = s._local_means(mov_shifted, rad) u_mov = u_mov_shifted + s.mov_mean v_mov = s._local_means(mov_shifted**2, rad) - u_mov_shifted**2 mov_mask = v_mov / (s.mov_winsor_max - s.mov_winsor_min) < tolerance v_fixmov = s._local_means(s.fix_shifted*mov_shifted, rad) - \ s.u_fix_shifted*u_mov_shifted with np.errstate(divide='ignore', invalid='ignore'): cc = v_fixmov**2 / (s.v_fix * v_mov) cc = -np.mean(cc[~(s.fix_mask + mov_mask)]) ccgrad = v_fixmov * ( (moving-u_mov) * v_fixmov - \ (fixed-s.u_fix) * v_mov ) / (s.v_fix*v_mov**2) ccgrad[s.fix_mask + mov_mask] = 0 grad = np.moveaxis(np.gradient(moving, *vox), 0, -1) ccgrad = ccgrad[..., np.newaxis] * np.ascontiguousarray(grad) return cc, ccgrad def _local_means(self, im, rad): """ """ # pad array, compute summed area table d = len(im.shape) im_ = im / (2*rad+1)**d # more stable to apply denominator first (smaller numbers) sat = np.pad(im_, [(rad+1, rad),]*d, mode='reflect') # potential stability problems with np.cumsum (sequential adding) for i in range(d): sat.cumsum(axis=i, out=sat, dtype=np.longdouble) # take appropriate vectorized array differences # kept track using binary strings and slice objects binary_strings = ["".join(x) for x in product("01", repeat=d)] so = self._get_slice_object(binary_strings.pop(-1), rad) means = np.copy(sat[so]) for bs in binary_strings: so = self._get_slice_object(bs, rad) s = (-1)**(d - np.sum( [int(x) for x in bs] )) means += s*sat[so] return means.astype(im.dtype) def _get_slice_object(self, bs, rad): """ """ so0 = slice(None, -2*rad-1, None) so1 = slice(2*rad+1, None, None) return tuple([so0 if b == "0" else so1 for b in bs]) class sum_squared_differences: def __init__(self): """ """ None def evaluate(self, fixed, moving): """ """ return np.sum( (fixed - moving)**2 ) def gradient(self, fixed, moving, vox): """ """ diff = fixed - moving grad = np.moveaxis(np.gradient(moving, vox), 0, -1) return diff * np.ascontiguousarray(grad)
[ "numpy.pad", "numpy.sum", "numpy.copy", "numpy.errstate", "numpy.percentile", "numpy.mean", "itertools.product", "numpy.ascontiguousarray", "numpy.gradient" ]
[((401, 416), 'numpy.mean', 'np.mean', (['moving'], {}), '(moving)\n', (408, 416), True, 'import numpy as np\n'), ((513, 547), 'numpy.percentile', 'np.percentile', (['moving', '[0.1, 99.9]'], {}), '(moving, [0.1, 99.9])\n', (526, 547), True, 'import numpy as np\n'), ((569, 583), 'numpy.mean', 'np.mean', (['fixed'], {}), '(fixed)\n', (576, 583), True, 'import numpy as np\n'), ((845, 878), 'numpy.percentile', 'np.percentile', (['fixed', '[0.1, 99.9]'], {}), '(fixed, [0.1, 99.9])\n', (858, 878), True, 'import numpy as np\n'), ((2962, 3011), 'numpy.pad', 'np.pad', (['im_', '([(rad + 1, rad)] * d)'], {'mode': '"""reflect"""'}), "(im_, [(rad + 1, rad)] * d, mode='reflect')\n", (2968, 3011), True, 'import numpy as np\n'), ((3440, 3456), 'numpy.copy', 'np.copy', (['sat[so]'], {}), '(sat[so])\n', (3447, 3456), True, 'import numpy as np\n'), ((4059, 4088), 'numpy.sum', 'np.sum', (['((fixed - moving) ** 2)'], {}), '((fixed - moving) ** 2)\n', (4065, 4088), True, 'import numpy as np\n'), ((1499, 1545), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (1510, 1545), True, 'import numpy as np\n'), ((2221, 2267), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (2232, 2267), True, 'import numpy as np\n'), ((2589, 2614), 'numpy.gradient', 'np.gradient', (['moving', '*vox'], {}), '(moving, *vox)\n', (2600, 2614), True, 'import numpy as np\n'), ((2666, 2692), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['grad'], {}), '(grad)\n', (2686, 2692), True, 'import numpy as np\n'), ((4217, 4241), 'numpy.gradient', 'np.gradient', (['moving', 'vox'], {}), '(moving, vox)\n', (4228, 4241), True, 'import numpy as np\n'), ((4272, 4298), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['grad'], {}), '(grad)\n', (4292, 4298), True, 'import numpy as np\n'), ((1619, 1656), 'numpy.mean', 'np.mean', (['cc[~(s.fix_mask + mov_mask)]'], {}), '(cc[~(s.fix_mask + mov_mask)])\n', (1626, 1656), True, 'import numpy as np\n'), ((2336, 2373), 'numpy.mean', 'np.mean', (['cc[~(s.fix_mask + mov_mask)]'], {}), '(cc[~(s.fix_mask + mov_mask)])\n', (2343, 2373), True, 'import numpy as np\n'), ((3334, 3357), 'itertools.product', 'product', (['"""01"""'], {'repeat': 'd'}), "('01', repeat=d)\n", (3341, 3357), False, 'from itertools import product\n')]
import numpy as np from abc import ABC, abstractmethod # Observer pattern # The oberserver pattern defines a one-to-many relationship between a set of objects. # # When the state of one object changes, all of its dependents are notified # CREATE INTERFACES class Subject(ABC): @abstractmethod def registerObserver(self): raise NotImplementedError @abstractmethod def removeObserver(self): raise NotImplementedError @abstractmethod def notifyObserver(self): raise NotImplementedError class Observer(ABC): @abstractmethod def update(self): raise NotImplementedError class DisplayElement(ABC): @abstractmethod def display(self): raise NotImplementedError class WeatherData(Subject): def __init__(self): self.observers = [] self.temperature = None self.humidity = None self.pressure = None def registerObserver(self, o): self.observers.append(o) def removeObserver(self, o): self.observers.remove(0) def notifyObserver(self): [o.update() for o in self.observers] def measurementsChanged(self): self.notifyObserver() def setMeasurements(self, temperature: float, humidity: float, pressure: float): self.temperature = temperature self.humidity = humidity self.pressure = pressure self.measurementsChanged() def getTemperature(self): return self.temperature def getHumidity(self): return self.humidity def getPressure(self): return self.pressure class CurrentConditionDisplay(Observer, DisplayElement): def __init__(self, weatherData): self.temperature = None self.humidity = None self.weatherData = weatherData self.weatherData.registerObserver(self) def update(self): self.temperature = self.weatherData.getTemperature() self.humidity = self.weatherData.getTemperature() self.display() def display(self): print(f'Current Conditions: {self.temperature}F degrees and {self.humidity}% humidity') class StatisticsDisplay(Observer, DisplayElement): def __init__(self, weatherData): self.temperature = [] self.humidity = [] self.weatherData = weatherData self.weatherData.registerObserver(self) def update(self): self.temperature = self.weatherData.getTemperature() self.humidity = self.weatherData.getTemperature() self.display() def display(self): print( f'Avg/Max/Min temperature: {np.mean(self.temperature)}/{np.max(self.temperature)}/{np.min(self.temperature)}') class ForecastDisplay(Observer, DisplayElement): def __init__(self, weatherData): self.temperature = None self.humidity = None self.currentPressure = 29.92 self.lastPressure = None self.weatherData = weatherData self.weatherData.registerObserver(self) def update(self): self.lastPressure = self.currentPressure self.currentPressure = weatherData.getPressure() self.temperature = self.weatherData.getTemperature() self.humidity = self.weatherData.getTemperature() self.display() def display(self): if self.currentPressure == self.lastPressure: print('Forecast: more of the same') elif self.currentPressure < self.lastPressure: print('Forecast: Watch out for cooler, rainy weather') elif self.currentPressure > self.lastPressure: print('Forecast: Improving weather on the way!') def heat_index(t, rh): index = ((16.923 + (0.185212 * t) + (5.37941 * rh) - (0.100254 * t * rh) + (0.00941695 * (t * t)) + (0.00728898 * (rh * rh)) + (0.000345372 * (t * t * rh)) - (0.000814971 * (t * rh * rh)) + (0.0000102102 * (t * t * rh * rh)) - (0.000038646 * (t * t * t)) + (0.0000291583 * (rh * rh * rh)) + ( 0.00000142721 * (t * t * t * rh)) + (0.000000197483 * (t * rh * rh * rh)) - (0.0000000218429 * (t * t * t * rh * rh)) + 0.000000000843296 * (t * t * rh * rh * rh)) - (0.0000000000481975 * (t * t * t * rh * rh * rh))) return index if __name__ == '__main__': weatherData = WeatherData() currentDisplay = CurrentConditionDisplay(weatherData) statisticalDisplay = StatisticsDisplay(weatherData) forecastDisplay = ForecastDisplay(weatherData) weatherData.setMeasurements(80.0, 65.0, 30.4) weatherData.setMeasurements(82.0, 70.0, 29.2) weatherData.setMeasurements(78.0, 90.0, 29.2)
[ "numpy.max", "numpy.mean", "numpy.min" ]
[((2604, 2629), 'numpy.mean', 'np.mean', (['self.temperature'], {}), '(self.temperature)\n', (2611, 2629), True, 'import numpy as np\n'), ((2632, 2656), 'numpy.max', 'np.max', (['self.temperature'], {}), '(self.temperature)\n', (2638, 2656), True, 'import numpy as np\n'), ((2659, 2683), 'numpy.min', 'np.min', (['self.temperature'], {}), '(self.temperature)\n', (2665, 2683), True, 'import numpy as np\n')]
#!/usr/bin/env python3 # This file is part of qdpy. # # qdpy is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation, either version 3 of # the License, or (at your option) any later version. # # qdpy is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with qdpy. If not, see <http://www.gnu.org/licenses/>. """A simple example of NSLC to illuminate a fitness function based on a normalised rastrigin function. The illumination process is ran with 2 features corresponding to the first 2 values of the genomes. It is possible to increase the difficulty of the illumination process by using problem dimension above 3.""" import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt from qdpy.algorithms import * from qdpy.containers import * from qdpy.benchmarks import * from qdpy.plots import * from qdpy.base import * from qdpy import tools import os import numpy as np import random from functools import partial # Iteration callback to modify the archive parameter each iteration def iteration_callback(algo, batch_elapsed): if algo.container.threshold_novelty > 0.02: algo.container.threshold_novelty -= 0.003 if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('--maxTotalBins', type=int, default=1000, help="Maximum number of bins in the grid") parser.add_argument('--dimension', type=int, default=4, help="Problem dimension") parser.add_argument('--nbFeatures', type=int, default=2, help="Number of features") parser.add_argument('--seed', type=int, default=None, help="Numpy random seed") parser.add_argument('-p', '--parallelismType', type=str, default='none', help = "Type of parallelism to use (none, concurrent, scoop)") parser.add_argument('-o', '--outputDir', type=str, default=None, help = "Path of the output log files") args = parser.parse_args() if args.seed != None: seed = args.seed else: seed = np.random.randint(1000000) # Algorithm parameters dimension = args.dimension # The dimension of the target problem (i.e. genomes size) assert(dimension >= 2) nb_features = args.nbFeatures # The number of features to take into account in the container assert(nb_features >= 1) bins_per_dim = int(pow(args.maxTotalBins, 1./nb_features)) nb_bins = (bins_per_dim,) * nb_features # The number of bins of the grid of elites. Here, we consider only $nb_features$ features with $maxTotalBins^(1/nb_features)$ bins each ind_domain = (0., 1.) # The domain (min/max values) of the individual genomes features_domain = [(0., 1.),] * nb_features # The domain (min/max values) of the features fitness_domain = [(0., 1.),] # The domain (min/max values) of the fitness #fitness_domain = [(-np.inf, np.inf),] # The domain (min/max values) of the fitness init_batch_size = 400#0 # The number of evaluations of the initial batch ('batch' = population) batch_size = 400#0 # The number of evaluations in each subsequent batch nb_iterations = 10 # The number of iterations (i.e. times where a new batch is evaluated) mutation_pb = 0.4 # The probability of mutating each value of a genome eta = 20.0 # The ETA parameter of the polynomial mutation (as defined in the origin NSGA-II paper by Deb.). It corresponds to the crowding degree of the mutation. A high ETA will produce mutants close to its parent, a small ETA will produce offspring with more changes. k = 15 # The number of nearest neighbours used to compute novelty threshold_novelty = 0.06 # The threshold of novelty score used to assess whether an individual can be added to the archive max_items_per_bin = 1 # The number of items in each bin of the grid verbose = True log_base_path = args.outputDir if args.outputDir is not None else "." # Update and print seed np.random.seed(seed) random.seed(seed) print("Seed: %i" % seed) # Create container container = NoveltyArchive(k=k, threshold_novelty=threshold_novelty, fitness_domain=fitness_domain, features_domain=features_domain, storage_type=list, depot_type=OrderedSet) # Define evaluation function eval_fn = partial(illumination_rastrigin_normalised, nb_features = nb_features) # Create algo algo = RandomSearchMutPolyBounded(container, budget=batch_size*nb_iterations, batch_size=batch_size, optimisation_task="minimisation", dimension=dimension, ind_domain=ind_domain, sel_pb=0.5, init_pb=0.5, mut_pb=mutation_pb, eta=eta, name="algo") algo.add_callback("iteration", iteration_callback) logger = TQDMAlgorithmLogger(algo, log_base_path = log_base_path) # Run illumination process ! with ParallelismManager(args.parallelismType) as pMgr: best = algo.optimise(eval_fn, executor = pMgr.executor, batch_mode=False) # Print results info print("\n------------------------\n") print(algo.summary()) #print(f"Total elapsed: {algo.total_elapsed}\n") #print(container.summary()) ##print("Best ever fitness: ", container.best_fitness) ##print("Best ever ind: ", container.best) ##print("Performances container: ", container.fitness) ##print("Features container: ", container.features) novelty_best, local_competition_best = container.novelty_local_competition(container.best, k=15, ignore_first=True) print(f"\nNovelty best: {novelty_best} local competition best: {local_competition_best}") novelty_first, local_competition_first = container.novelty_local_competition(container[0], k=15, ignore_first=True) print(f"Novelty first: {novelty_first} local competition first: {local_competition_first}") # Transform the container into a grid, if needed if isinstance(container, containers.Grid): grid = container else: print("\n{:70s}".format("Transforming the container into a grid, for visualisation..."), end="", flush=True) grid = Grid(container.depot, shape=nb_bins, max_items_per_bin=max_items_per_bin, fitness_domain=fitness_domain, features_domain=features_domain, storage_type=list) print("\tDone !") print(grid.summary()) # Create plot of the performance grid plot_path = os.path.join(log_base_path, "performancesGrid.pdf") plotGridSubplots(grid.quality_array[... ,0], plot_path, plt.get_cmap("nipy_spectral_r"), grid.features_domain, grid.fitness_domain[0], nbTicks=None) print("\nA plot of the performance grid was saved in '%s'." % os.path.abspath(plot_path)) plot_path = os.path.join(log_base_path, "activityGrid.pdf") max_activity = np.max(grid.activity_per_bin) plotGridSubplots(grid.activity_per_bin, plot_path, plt.get_cmap("Reds", max_activity), grid.features_domain, [0, max_activity], nbTicks=None) print("\nA plot of the activity grid was saved in '%s'." % os.path.abspath(plot_path)) print("\nAll results are available in the '%s' pickle file." % logger.final_filename) print(f""" To open it, you can use the following python code: import pickle # You may want to import your own packages if the pickle file contains custom objects with open("{logger.final_filename}", "rb") as f: data = pickle.load(f) # ``data`` is now a dictionary containing all results, including the final container, all solutions, the algorithm parameters, etc. grid = data['container'] print(grid.best) print(grid.best.fitness) print(grid.best.features) """) # MODELINE "{{{1 # vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8 # vim:foldmethod=marker
[ "functools.partial", "os.path.abspath", "numpy.random.seed", "argparse.ArgumentParser", "matplotlib.pyplot.get_cmap", "numpy.max", "matplotlib.use", "random.seed", "numpy.random.randint", "os.path.join" ]
[((1056, 1070), 'matplotlib.use', 'mpl.use', (['"""Agg"""'], {}), "('Agg')\n", (1063, 1070), True, 'import matplotlib as mpl\n'), ((1615, 1640), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1638, 1640), False, 'import argparse\n'), ((4544, 4564), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (4558, 4564), True, 'import numpy as np\n'), ((4569, 4586), 'random.seed', 'random.seed', (['seed'], {}), '(seed)\n', (4580, 4586), False, 'import random\n'), ((4867, 4934), 'functools.partial', 'partial', (['illumination_rastrigin_normalised'], {'nb_features': 'nb_features'}), '(illumination_rastrigin_normalised, nb_features=nb_features)\n', (4874, 4934), False, 'from functools import partial\n'), ((6902, 6953), 'os.path.join', 'os.path.join', (['log_base_path', '"""performancesGrid.pdf"""'], {}), "(log_base_path, 'performancesGrid.pdf')\n", (6914, 6953), False, 'import os\n'), ((7218, 7265), 'os.path.join', 'os.path.join', (['log_base_path', '"""activityGrid.pdf"""'], {}), "(log_base_path, 'activityGrid.pdf')\n", (7230, 7265), False, 'import os\n'), ((7285, 7314), 'numpy.max', 'np.max', (['grid.activity_per_bin'], {}), '(grid.activity_per_bin)\n', (7291, 7314), True, 'import numpy as np\n'), ((2364, 2390), 'numpy.random.randint', 'np.random.randint', (['(1000000)'], {}), '(1000000)\n', (2381, 2390), True, 'import numpy as np\n'), ((7014, 7045), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""nipy_spectral_r"""'], {}), "('nipy_spectral_r')\n", (7026, 7045), True, 'import matplotlib.pyplot as plt\n'), ((7370, 7404), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""Reds"""', 'max_activity'], {}), "('Reds', max_activity)\n", (7382, 7404), True, 'import matplotlib.pyplot as plt\n'), ((7173, 7199), 'os.path.abspath', 'os.path.abspath', (['plot_path'], {}), '(plot_path)\n', (7188, 7199), False, 'import os\n'), ((7524, 7550), 'os.path.abspath', 'os.path.abspath', (['plot_path'], {}), '(plot_path)\n', (7539, 7550), False, 'import os\n')]
import sys sys.path.append('..') from util import * import numpy as np import scipy.io from tqdm import tqdm import matplotlib.pyplot as plt subjects = [101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117] labels = [1, 2, 3, 4, 5] class_names = "None,Brow lower,Brow raiser,Cheek raiser,Nose wrinkler,Lip raiser,Mouth open".split(',') X_all_raw = None X_all = None # np.zeros(shape=(0,201*10)) y_all = [] groups = [] # to change the path, change the function in prepare_data.py from prepare_data import get_path # change these values to show data for other subjects/labels/trials graph_subject = 103 graph_label = 5 # in range [1,5] graph_trial = 1 # in range [1,20] # map from (subject, label, subject_trial) -> X_all index index_dict = dict() curr_index = 0 # accumulate the data for the all the subjects print("reading raw data into memory") for subject in tqdm(subjects): # subject_data = np.zeros(shape=(0,201,10)) for label in labels: path = get_path(subject, label) # [ trial * window frames * sensor channels ] subject_matrix = scipy.io.loadmat(path)['data_chunk'] for subject_trial in range(subject_matrix.shape[0]): index_dict[(subject, label, subject_trial)] = curr_index curr_index += 1 groups += [subject]*subject_matrix.shape[0] y_all += [label]*subject_matrix.shape[0] for trial in range(subject_matrix.shape[0]): raw_window = subject_matrix[trial,:,:] # print(raw_window.shape) if X_all_raw is None: X_all_raw = np.empty(shape=(0,len(raw_window), 10), dtype=float) # print(X_all_raw.shape) # exit() X_all_raw = np.concatenate((X_all_raw, raw_window[np.newaxis,:,:]), axis=0) print("normalizing data") # normalize accelerometer signals a = np.mean(np.std(X_all_raw[:,:,0:3], axis=2)) X_all_raw[:,:,0:3] = X_all_raw[:,:,0:3] / a # normalize gyroscope signals a = np.mean(np.std(X_all_raw[:,:,3:6], axis=2)) X_all_raw[:,:,3:6] = X_all_raw[:,:,3:6] / a # normalize eog signals a = np.mean(np.std(X_all_raw[:,:,6:], axis=2)) X_all_raw[:,:,6:10] = X_all_raw[:,:,6:10] / a window_index = index_dict[graph_subject, graph_label, graph_trial-1] print("plotting window for trial at index {}".format(window_index)) single_window = X_all_raw[window_index,:,:] x = np.arange(single_window.shape[0]) # set the title of the graph title = "Subject {} '{}' Trial {}".format(graph_subject, class_names[graph_label-1], graph_trial).title() fig = plt.figure(title) plt.title(title) # graph the accelerometer plt.scatter(x, single_window[:,0], c='xkcd:red', alpha=0.5, label="accel x") plt.scatter(x, single_window[:,1], c='xkcd:orange', alpha=0.5, label="accel y") plt.scatter(x, single_window[:,2], c='xkcd:goldenrod', alpha=0.5, label="accel z") # graph the gyroscope plt.scatter(x, single_window[:,3], c='xkcd:green', alpha=0.5, label="gyro x") plt.scatter(x, single_window[:,4], c='xkcd:blue', alpha=0.5, label="gyro y") plt.scatter(x, single_window[:,5], c='xkcd:indigo', alpha=0.5, label="gyro z") # graph the eog signals plt.scatter(x, single_window[:,6], c='xkcd:violet', alpha=0.5, label="eog l") plt.scatter(x, single_window[:,7], c='xkcd:gray', alpha=0.5, label="eog r") plt.scatter(x, single_window[:,8], c='xkcd:black', alpha=0.5, label="eog h") plt.scatter(x, single_window[:,9], c='xkcd:bright pink', alpha=0.5, label="eog v") plt.xlabel("Frame #") plt.ylabel("Magnitude of feature") plt.legend(loc=2) plt.show()
[ "sys.path.append", "matplotlib.pyplot.title", "tqdm.tqdm", "matplotlib.pyplot.show", "numpy.std", "matplotlib.pyplot.scatter", "matplotlib.pyplot.legend", "prepare_data.get_path", "matplotlib.pyplot.figure", "numpy.arange", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.conca...
[((11, 32), 'sys.path.append', 'sys.path.append', (['""".."""'], {}), "('..')\n", (26, 32), False, 'import sys\n'), ((897, 911), 'tqdm.tqdm', 'tqdm', (['subjects'], {}), '(subjects)\n', (901, 911), False, 'from tqdm import tqdm\n'), ((2395, 2428), 'numpy.arange', 'np.arange', (['single_window.shape[0]'], {}), '(single_window.shape[0])\n', (2404, 2428), True, 'import numpy as np\n'), ((2571, 2588), 'matplotlib.pyplot.figure', 'plt.figure', (['title'], {}), '(title)\n', (2581, 2588), True, 'import matplotlib.pyplot as plt\n'), ((2589, 2605), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2598, 2605), True, 'import matplotlib.pyplot as plt\n'), ((2633, 2710), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'single_window[:, 0]'], {'c': '"""xkcd:red"""', 'alpha': '(0.5)', 'label': '"""accel x"""'}), "(x, single_window[:, 0], c='xkcd:red', alpha=0.5, label='accel x')\n", (2644, 2710), True, 'import matplotlib.pyplot as plt\n'), ((2710, 2795), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'single_window[:, 1]'], {'c': '"""xkcd:orange"""', 'alpha': '(0.5)', 'label': '"""accel y"""'}), "(x, single_window[:, 1], c='xkcd:orange', alpha=0.5, label='accel y'\n )\n", (2721, 2795), True, 'import matplotlib.pyplot as plt\n'), ((2790, 2878), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'single_window[:, 2]'], {'c': '"""xkcd:goldenrod"""', 'alpha': '(0.5)', 'label': '"""accel z"""'}), "(x, single_window[:, 2], c='xkcd:goldenrod', alpha=0.5, label=\n 'accel z')\n", (2801, 2878), True, 'import matplotlib.pyplot as plt\n'), ((2896, 2974), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'single_window[:, 3]'], {'c': '"""xkcd:green"""', 'alpha': '(0.5)', 'label': '"""gyro x"""'}), "(x, single_window[:, 3], c='xkcd:green', alpha=0.5, label='gyro x')\n", (2907, 2974), True, 'import matplotlib.pyplot as plt\n'), ((2974, 3051), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'single_window[:, 4]'], {'c': '"""xkcd:blue"""', 'alpha': '(0.5)', 'label': '"""gyro y"""'}), "(x, single_window[:, 4], c='xkcd:blue', alpha=0.5, label='gyro y')\n", (2985, 3051), True, 'import matplotlib.pyplot as plt\n'), ((3051, 3130), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'single_window[:, 5]'], {'c': '"""xkcd:indigo"""', 'alpha': '(0.5)', 'label': '"""gyro z"""'}), "(x, single_window[:, 5], c='xkcd:indigo', alpha=0.5, label='gyro z')\n", (3062, 3130), True, 'import matplotlib.pyplot as plt\n'), ((3155, 3233), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'single_window[:, 6]'], {'c': '"""xkcd:violet"""', 'alpha': '(0.5)', 'label': '"""eog l"""'}), "(x, single_window[:, 6], c='xkcd:violet', alpha=0.5, label='eog l')\n", (3166, 3233), True, 'import matplotlib.pyplot as plt\n'), ((3233, 3309), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'single_window[:, 7]'], {'c': '"""xkcd:gray"""', 'alpha': '(0.5)', 'label': '"""eog r"""'}), "(x, single_window[:, 7], c='xkcd:gray', alpha=0.5, label='eog r')\n", (3244, 3309), True, 'import matplotlib.pyplot as plt\n'), ((3309, 3386), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'single_window[:, 8]'], {'c': '"""xkcd:black"""', 'alpha': '(0.5)', 'label': '"""eog h"""'}), "(x, single_window[:, 8], c='xkcd:black', alpha=0.5, label='eog h')\n", (3320, 3386), True, 'import matplotlib.pyplot as plt\n'), ((3386, 3474), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'single_window[:, 9]'], {'c': '"""xkcd:bright pink"""', 'alpha': '(0.5)', 'label': '"""eog v"""'}), "(x, single_window[:, 9], c='xkcd:bright pink', alpha=0.5, label=\n 'eog v')\n", (3397, 3474), True, 'import matplotlib.pyplot as plt\n'), ((3470, 3491), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Frame #"""'], {}), "('Frame #')\n", (3480, 3491), True, 'import matplotlib.pyplot as plt\n'), ((3492, 3526), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Magnitude of feature"""'], {}), "('Magnitude of feature')\n", (3502, 3526), True, 'import matplotlib.pyplot as plt\n'), ((3527, 3544), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '(2)'}), '(loc=2)\n', (3537, 3544), True, 'import matplotlib.pyplot as plt\n'), ((3545, 3555), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3553, 3555), True, 'import matplotlib.pyplot as plt\n'), ((1882, 1918), 'numpy.std', 'np.std', (['X_all_raw[:, :, 0:3]'], {'axis': '(2)'}), '(X_all_raw[:, :, 0:3], axis=2)\n', (1888, 1918), True, 'import numpy as np\n'), ((2005, 2041), 'numpy.std', 'np.std', (['X_all_raw[:, :, 3:6]'], {'axis': '(2)'}), '(X_all_raw[:, :, 3:6], axis=2)\n', (2011, 2041), True, 'import numpy as np\n'), ((2122, 2157), 'numpy.std', 'np.std', (['X_all_raw[:, :, 6:]'], {'axis': '(2)'}), '(X_all_raw[:, :, 6:], axis=2)\n', (2128, 2157), True, 'import numpy as np\n'), ((1001, 1025), 'prepare_data.get_path', 'get_path', (['subject', 'label'], {}), '(subject, label)\n', (1009, 1025), False, 'from prepare_data import get_path\n'), ((1744, 1809), 'numpy.concatenate', 'np.concatenate', (['(X_all_raw, raw_window[np.newaxis, :, :])'], {'axis': '(0)'}), '((X_all_raw, raw_window[np.newaxis, :, :]), axis=0)\n', (1758, 1809), True, 'import numpy as np\n')]
import streamlit as st import pandas as pd import numpy as np import pickle from sklearn.ensemble import RandomForestClassifier st.write(""" # Penguin Prediction App This app predicts the **Palmer Penguin** species! Data obtained from the [palmerpenguins library](https://github.com/allisonhorst/palmerpenguins) in R by <NAME>. """) st.sidebar.header('User Input Features') st.sidebar.markdown(""" [Example CSV input file](https://raw.githubusercontent.com/dataprofessor/data/master/penguins_example.csv) """) # Collects user input features into dataframe uploaded_file = st.sidebar.file_uploader( "Upload your input CSV file", type=["csv"]) if uploaded_file is not None: input_df = pd.read_csv(uploaded_file) else: def user_input_features(): island = st.sidebar.selectbox( 'Island', ('Biscoe', 'Dream', 'Torgersen')) sex = st.sidebar.selectbox('Sex', ('male', 'female')) bill_length_mm = st.sidebar.slider( 'Bill length (mm)', 32.1, 59.6, 43.9) bill_depth_mm = st.sidebar.slider('Bill depth (mm)', 13.1, 21.5, 17.2) flipper_length_mm = st.sidebar.slider( 'Flipper length (mm)', 172.0, 231.0, 201.0) body_mass_g = st.sidebar.slider( 'Body mass (g)', 2700.0, 6300.0, 4207.0) data = {'island': island, 'bill_length_mm': bill_length_mm, 'bill_depth_mm': bill_depth_mm, 'flipper_length_mm': flipper_length_mm, 'body_mass_g': body_mass_g, 'sex': sex} features = pd.DataFrame(data, index=[0]) return features input_df = user_input_features() # Combines user input features with entire penguins dataset # This will be useful for the encoding phase penguins_raw = pd.read_csv('penguins_cleaned.csv') penguins = penguins_raw.drop(columns=['species']) df = pd.concat([input_df, penguins], axis=0) # Encoding of ordinal features # https://www.kaggle.com/pratik1120/penguin-dataset-eda-classification-and-clustering encode = ['sex', 'island'] for col in encode: dummy = pd.get_dummies(df[col], prefix=col) df = pd.concat([df, dummy], axis=1) del df[col] df = df[:1] # Selects only the first row (the user input data) # Displays the user input features st.subheader('User Input features') if uploaded_file is not None: st.write(df) else: st.write( 'Awaiting CSV file to be uploaded. Currently using example input parameters (shown below).') st.write(df) # Reads in saved classification model load_clf = pickle.load(open('penguins_clf.pkl', 'rb')) # Apply model to make predictions prediction = load_clf.predict(df) prediction_proba = load_clf.predict_proba(df) st.subheader('Prediction') penguins_species = np.array(['Adelie', 'Chinstrap', 'Gentoo']) st.write(penguins_species[prediction]) st.subheader('Prediction Probability') st.write(prediction_proba)
[ "pandas.DataFrame", "streamlit.subheader", "streamlit.sidebar.slider", "streamlit.sidebar.header", "pandas.read_csv", "pandas.get_dummies", "streamlit.write", "streamlit.sidebar.selectbox", "streamlit.sidebar.markdown", "numpy.array", "streamlit.sidebar.file_uploader", "pandas.concat" ]
[((129, 343), 'streamlit.write', 'st.write', (['"""\n# Penguin Prediction App\nThis app predicts the **Palmer Penguin** species!\nData obtained from the [palmerpenguins library](https://github.com/allisonhorst/palmerpenguins) in R by <NAME>.\n"""'], {}), '(\n """\n# Penguin Prediction App\nThis app predicts the **Palmer Penguin** species!\nData obtained from the [palmerpenguins library](https://github.com/allisonhorst/palmerpenguins) in R by <NAME>.\n"""\n )\n', (137, 343), True, 'import streamlit as st\n'), ((335, 375), 'streamlit.sidebar.header', 'st.sidebar.header', (['"""User Input Features"""'], {}), "('User Input Features')\n", (352, 375), True, 'import streamlit as st\n'), ((377, 522), 'streamlit.sidebar.markdown', 'st.sidebar.markdown', (['"""\n[Example CSV input file](https://raw.githubusercontent.com/dataprofessor/data/master/penguins_example.csv)\n"""'], {}), '(\n """\n[Example CSV input file](https://raw.githubusercontent.com/dataprofessor/data/master/penguins_example.csv)\n"""\n )\n', (396, 522), True, 'import streamlit as st\n'), ((576, 644), 'streamlit.sidebar.file_uploader', 'st.sidebar.file_uploader', (['"""Upload your input CSV file"""'], {'type': "['csv']"}), "('Upload your input CSV file', type=['csv'])\n", (600, 644), True, 'import streamlit as st\n'), ((1777, 1812), 'pandas.read_csv', 'pd.read_csv', (['"""penguins_cleaned.csv"""'], {}), "('penguins_cleaned.csv')\n", (1788, 1812), True, 'import pandas as pd\n'), ((1868, 1907), 'pandas.concat', 'pd.concat', (['[input_df, penguins]'], {'axis': '(0)'}), '([input_df, penguins], axis=0)\n', (1877, 1907), True, 'import pandas as pd\n'), ((2276, 2311), 'streamlit.subheader', 'st.subheader', (['"""User Input features"""'], {}), "('User Input features')\n", (2288, 2311), True, 'import streamlit as st\n'), ((2709, 2735), 'streamlit.subheader', 'st.subheader', (['"""Prediction"""'], {}), "('Prediction')\n", (2721, 2735), True, 'import streamlit as st\n'), ((2755, 2798), 'numpy.array', 'np.array', (["['Adelie', 'Chinstrap', 'Gentoo']"], {}), "(['Adelie', 'Chinstrap', 'Gentoo'])\n", (2763, 2798), True, 'import numpy as np\n'), ((2799, 2837), 'streamlit.write', 'st.write', (['penguins_species[prediction]'], {}), '(penguins_species[prediction])\n', (2807, 2837), True, 'import streamlit as st\n'), ((2839, 2877), 'streamlit.subheader', 'st.subheader', (['"""Prediction Probability"""'], {}), "('Prediction Probability')\n", (2851, 2877), True, 'import streamlit as st\n'), ((2878, 2904), 'streamlit.write', 'st.write', (['prediction_proba'], {}), '(prediction_proba)\n', (2886, 2904), True, 'import streamlit as st\n'), ((695, 721), 'pandas.read_csv', 'pd.read_csv', (['uploaded_file'], {}), '(uploaded_file)\n', (706, 721), True, 'import pandas as pd\n'), ((2084, 2119), 'pandas.get_dummies', 'pd.get_dummies', (['df[col]'], {'prefix': 'col'}), '(df[col], prefix=col)\n', (2098, 2119), True, 'import pandas as pd\n'), ((2129, 2159), 'pandas.concat', 'pd.concat', (['[df, dummy]'], {'axis': '(1)'}), '([df, dummy], axis=1)\n', (2138, 2159), True, 'import pandas as pd\n'), ((2347, 2359), 'streamlit.write', 'st.write', (['df'], {}), '(df)\n', (2355, 2359), True, 'import streamlit as st\n'), ((2370, 2481), 'streamlit.write', 'st.write', (['"""Awaiting CSV file to be uploaded. Currently using example input parameters (shown below)."""'], {}), "(\n 'Awaiting CSV file to be uploaded. Currently using example input parameters (shown below).'\n )\n", (2378, 2481), True, 'import streamlit as st\n'), ((2485, 2497), 'streamlit.write', 'st.write', (['df'], {}), '(df)\n', (2493, 2497), True, 'import streamlit as st\n'), ((776, 840), 'streamlit.sidebar.selectbox', 'st.sidebar.selectbox', (['"""Island"""', "('Biscoe', 'Dream', 'Torgersen')"], {}), "('Island', ('Biscoe', 'Dream', 'Torgersen'))\n", (796, 840), True, 'import streamlit as st\n'), ((868, 915), 'streamlit.sidebar.selectbox', 'st.sidebar.selectbox', (['"""Sex"""', "('male', 'female')"], {}), "('Sex', ('male', 'female'))\n", (888, 915), True, 'import streamlit as st\n'), ((941, 996), 'streamlit.sidebar.slider', 'st.sidebar.slider', (['"""Bill length (mm)"""', '(32.1)', '(59.6)', '(43.9)'], {}), "('Bill length (mm)', 32.1, 59.6, 43.9)\n", (958, 996), True, 'import streamlit as st\n'), ((1034, 1088), 'streamlit.sidebar.slider', 'st.sidebar.slider', (['"""Bill depth (mm)"""', '(13.1)', '(21.5)', '(17.2)'], {}), "('Bill depth (mm)', 13.1, 21.5, 17.2)\n", (1051, 1088), True, 'import streamlit as st\n'), ((1117, 1178), 'streamlit.sidebar.slider', 'st.sidebar.slider', (['"""Flipper length (mm)"""', '(172.0)', '(231.0)', '(201.0)'], {}), "('Flipper length (mm)', 172.0, 231.0, 201.0)\n", (1134, 1178), True, 'import streamlit as st\n'), ((1214, 1272), 'streamlit.sidebar.slider', 'st.sidebar.slider', (['"""Body mass (g)"""', '(2700.0)', '(6300.0)', '(4207.0)'], {}), "('Body mass (g)', 2700.0, 6300.0, 4207.0)\n", (1231, 1272), True, 'import streamlit as st\n'), ((1565, 1594), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {'index': '[0]'}), '(data, index=[0])\n', (1577, 1594), True, 'import pandas as pd\n')]
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Simple image classification with Inception. Run image classification with Inception trained on ImageNet 2012 Challenge data set. This program creates a graph from a saved GraphDef protocol buffer, and runs inference on an input JPEG image. It outputs human readable strings of the top 5 predictions along with their probabilities. Change the --image_file argument to any jpg image to compute a classification of that image. Please see the tutorial and website for a detailed description of how to use this script to perform image recognition. https://tensorflow.org/tutorials/image_recognition/ Modified by <NAME> 2017 """ import argparse import numpy as np import tensorflow as tf lookup = None sess = None softmax_tensor = None def create_graph(graph_path): with tf.gfile.FastGFile(graph_path, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) tf.import_graph_def(graph_def, name='') def create_lookup(lookup_path): if not tf.gfile.Exists(lookup_path): tf.logging.fatal('lookup file does not exist %s', lookup_path) lines = tf.gfile.GFile(lookup_path).readlines() return [int(l.replace('\n', '')) for l in lines] def run(image): global sess, softmax_tensor, lookup if not tf.gfile.Exists(image): tf.logging.fatal('File does not exist %s', image) image_data = tf.gfile.FastGFile(image, 'rb').read() predictions = sess.run(softmax_tensor, {'DecodeJpeg/contents:0': image_data}) predictions = np.squeeze(predictions) top = predictions.argsort()[-1] return (lookup[top], predictions[top]) def setup(model_dir): global sess if sess is not None: cleanup() create_graph('{}/output_graph.pb'.format(model_dir)) global lookup lookup = create_lookup('{}/output_labels.txt'.format(model_dir)) sess = tf.Session() global softmax_tensor softmax_tensor = sess.graph.get_tensor_by_name('final_result:0') def cleanup(): global lookup, sess, softmax_tensor sess.close() sess = None lookup = None softmax_tensor = None def main(model_dir, image_file): setup(model_dir) result = run(image_file) print(result) cleanup() if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'model_dir', type=str, help="path to model (.pb file) and labels (.txt)") parser.add_argument( 'image_file', type=str, help='Absolute path to image file.' ) args, unparsed = parser.parse_known_args() main(args.model_dir, args.image_file)
[ "tensorflow.gfile.FastGFile", "tensorflow.gfile.Exists", "argparse.ArgumentParser", "tensorflow.logging.fatal", "tensorflow.Session", "tensorflow.gfile.GFile", "numpy.squeeze", "tensorflow.import_graph_def", "tensorflow.GraphDef" ]
[((2164, 2187), 'numpy.squeeze', 'np.squeeze', (['predictions'], {}), '(predictions)\n', (2174, 2187), True, 'import numpy as np\n'), ((2489, 2501), 'tensorflow.Session', 'tf.Session', ([], {}), '()\n', (2499, 2501), True, 'import tensorflow as tf\n'), ((2867, 2892), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2890, 2892), False, 'import argparse\n'), ((1470, 1506), 'tensorflow.gfile.FastGFile', 'tf.gfile.FastGFile', (['graph_path', '"""rb"""'], {}), "(graph_path, 'rb')\n", (1488, 1506), True, 'import tensorflow as tf\n'), ((1529, 1542), 'tensorflow.GraphDef', 'tf.GraphDef', ([], {}), '()\n', (1540, 1542), True, 'import tensorflow as tf\n'), ((1587, 1626), 'tensorflow.import_graph_def', 'tf.import_graph_def', (['graph_def'], {'name': '""""""'}), "(graph_def, name='')\n", (1606, 1626), True, 'import tensorflow as tf\n'), ((1670, 1698), 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['lookup_path'], {}), '(lookup_path)\n', (1685, 1698), True, 'import tensorflow as tf\n'), ((1704, 1766), 'tensorflow.logging.fatal', 'tf.logging.fatal', (['"""lookup file does not exist %s"""', 'lookup_path'], {}), "('lookup file does not exist %s', lookup_path)\n", (1720, 1766), True, 'import tensorflow as tf\n'), ((1935, 1957), 'tensorflow.gfile.Exists', 'tf.gfile.Exists', (['image'], {}), '(image)\n', (1950, 1957), True, 'import tensorflow as tf\n'), ((1963, 2012), 'tensorflow.logging.fatal', 'tf.logging.fatal', (['"""File does not exist %s"""', 'image'], {}), "('File does not exist %s', image)\n", (1979, 2012), True, 'import tensorflow as tf\n'), ((1778, 1805), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['lookup_path'], {}), '(lookup_path)\n', (1792, 1805), True, 'import tensorflow as tf\n'), ((2028, 2059), 'tensorflow.gfile.FastGFile', 'tf.gfile.FastGFile', (['image', '"""rb"""'], {}), "(image, 'rb')\n", (2046, 2059), True, 'import tensorflow as tf\n')]
import argparse import numpy as np import matplotlib.pyplot as plt parser = argparse.ArgumentParser() parser.add_argument('--workspace', type=str, default='workspace', help='workspace path') args = parser.parse_args() lr = np.loadtxt(f'{args.workspace}/log/lr.txt') plt.title('learning scheduler') plt.xlabel('batch index') plt.ylabel('learning rate') plt.plot(lr) plt.show()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "argparse.ArgumentParser", "matplotlib.pyplot.plot", "numpy.loadtxt", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel" ]
[((81, 106), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (104, 106), False, 'import argparse\n'), ((233, 275), 'numpy.loadtxt', 'np.loadtxt', (['f"""{args.workspace}/log/lr.txt"""'], {}), "(f'{args.workspace}/log/lr.txt')\n", (243, 275), True, 'import numpy as np\n'), ((277, 308), 'matplotlib.pyplot.title', 'plt.title', (['"""learning scheduler"""'], {}), "('learning scheduler')\n", (286, 308), True, 'import matplotlib.pyplot as plt\n'), ((310, 335), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""batch index"""'], {}), "('batch index')\n", (320, 335), True, 'import matplotlib.pyplot as plt\n'), ((337, 364), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""learning rate"""'], {}), "('learning rate')\n", (347, 364), True, 'import matplotlib.pyplot as plt\n'), ((366, 378), 'matplotlib.pyplot.plot', 'plt.plot', (['lr'], {}), '(lr)\n', (374, 378), True, 'import matplotlib.pyplot as plt\n'), ((380, 390), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (388, 390), True, 'import matplotlib.pyplot as plt\n')]
""" This module provides the EvaluateModel class. """ import logging import math import os import warnings import numpy as np import torch import torch.nn as nn from selene_sdk.sequences import Genome from selene_sdk.utils import ( PerformanceMetrics, initialize_logger, load_model_from_state_dict, ) from sklearn.metrics import average_precision_score, roc_auc_score from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from src.utils import MAX_TOTAL_VAL_TARGET_SIZE, expand_dims logger = logging.getLogger("selene") class EvaluateModel(object): """ Evaluate model on a test set of sequences with known targets. Parameters ---------- model : torch.nn.Module The model architecture. criterion : torch.nn._Loss The loss function that was optimized during training. data_loader : torch.utils.data.DataLoader Data loader that fetches test batches. trained_model_path : str Path to the trained model file, saved using `torch.save`. report_gt_feature_n_positives : int, optional Default is 10. In the final test set, each class/feature must have more than `report_gt_feature_n_positives` positive samples in order to be considered in the test performance computation. The output file that states each class' performance will report 'NA' for classes that do not have enough positive samples. device : str, optional Default is `cpu`. Specify a CUDA-device, e.g. 'cuda:2' for on-GPU training. data_parallel : bool, optional Default is `False`. Specify whether multiple GPUs are available for torch to use during training. log_cell_type_embeddings_to_tensorboard : bool, optional Default is `True`. Whether to publish cell type embeddings to tensorboard. NOTE: If True, a model should have `get_cell_type_embeddings` method. metrics : dict(metric_name: metric_fn) Default is `dict(roc_auc=roc_auc_score, average_precision=average_precision_score)`. Metric functions to log. Attributes ---------- model : torch.nn.Module The trained model. criterion : torch.nn._Loss The model was trained using this loss function. data_loader : torch.utils.data.DataLoader Test data loader. target_features : list(str) List of features the model predicts. device : torch.device Device on which the computation is carried out. """ def __init__( self, model, criterion, data_loader, trained_model_path, report_gt_feature_n_positives=10, device="cpu", data_parallel=False, log_cell_type_embeddings_to_tensorboard=True, metrics=dict(roc_auc=roc_auc_score, average_precision=average_precision_score), ): self.data_loader = data_loader self.output_dir = os.path.join( os.path.dirname(trained_model_path), "evaluation/" ) os.makedirs(self.output_dir, exist_ok=True) initialize_logger( os.path.join(self.output_dir, "{0}.log".format(__name__)), verbosity=2 ) logger.info("Evaluation results will be saved at\n{}".format(self.output_dir)) self.criterion = criterion trained_model = torch.load( trained_model_path, map_location=lambda storage, location: storage ) if "state_dict" in trained_model: self.model = load_model_from_state_dict(trained_model["state_dict"], model) else: self.model = load_model_from_state_dict(trained_model, model) if log_cell_type_embeddings_to_tensorboard: self.log_cell_type_embeddings_to_tensorboard() self.model.eval() self.device = torch.device(device) self.data_parallel = data_parallel if self.data_parallel: self.model = nn.DataParallel(model) logger.debug("Wrapped model in DataParallel") else: self.model.to(self.device) self.criterion.to(self.device) logger.debug(f"Set modules to use device {device}") self.target_features = self.data_loader.dataset.target_features self._metrics = PerformanceMetrics( self._get_feature_from_index, report_gt_feature_n_positives=report_gt_feature_n_positives, metrics=metrics, ) self.masked_targets = self.data_loader.dataset.cell_wise self.val_reduction_factor = 1 val_batch_size = self.data_loader.batch_size val_target_size = self.data_loader.dataset.target_size total_val_target_size = len(self.data_loader) * val_batch_size * val_target_size if total_val_target_size > MAX_TOTAL_VAL_TARGET_SIZE: self.val_reduction_factor = math.ceil( total_val_target_size / MAX_TOTAL_VAL_TARGET_SIZE ) def log_cell_type_embeddings_to_tensorboard(self): embeddings = self.model.get_cell_type_embeddings() cell_type_labels = self.data_loader.dataset._cell_types writer = SummaryWriter(self.output_dir) writer.add_embedding(embeddings, cell_type_labels) writer.flush() writer.close() def evaluate(self): """ Makes predictions for some labeled input data. Parameters ---------- data_in_batches : list(SamplesBatch) A list of tuples of the data, where the first element is the example, and the second element is the label. Returns ------- tuple(float, list(numpy.ndarray)) Returns the average loss, and the list of all predictions. """ self.model.eval() batch_losses = [] all_predictions = [] all_targets = [] if self.masked_targets: all_target_masks = [] else: all_target_masks = None for batch in tqdm(self.data_loader): if self.masked_targets: sequence_batch = batch[0].to(self.device) cell_type_batch = batch[1].to(self.device) targets = batch[2].to(self.device) target_mask = batch[3].to(self.device) else: # retrieved_seq, target sequence_batch = batch[0].to(self.device) targets = batch[1].to(self.device) with torch.no_grad(): if self.masked_targets: outputs = self.model(sequence_batch, cell_type_batch) self.criterion.weight = target_mask else: outputs = self.model(sequence_batch) loss = self.criterion(outputs, targets) if self.criterion.reduction == "sum": loss = loss / self.criterion.weight.sum() predictions = torch.sigmoid(outputs) predictions = predictions.view(-1, predictions.shape[-1]) targets = targets.view(-1, targets.shape[-1]) if self.masked_targets: target_mask = target_mask.view(-1, target_mask.shape[-1]) if self.val_reduction_factor > 1: reduced_val_batch_size = ( predictions.shape[0] // self.val_reduction_factor ) reduced_index = np.random.choice( predictions.shape[0], reduced_val_batch_size ) predictions = predictions[reduced_index] targets = targets[reduced_index] if self.masked_targets: target_mask = target_mask[reduced_index] all_predictions.append(predictions.data.cpu().numpy()) all_targets.append(targets.data.cpu().numpy()) if self.masked_targets: all_target_masks.append(target_mask.data.cpu().numpy()) batch_losses.append(loss.item()) all_predictions = expand_dims(np.concatenate(all_predictions)) all_targets = expand_dims(np.concatenate(all_targets)) if self.masked_targets: all_target_masks = expand_dims(np.concatenate(all_target_masks)) average_scores = self._metrics.update( all_predictions, all_targets, all_target_masks ) self._metrics.visualize( all_predictions, all_targets, self.output_dir, all_target_masks ) loss = np.average(batch_losses) logger.info("test loss: {0}".format(loss)) for name, score in average_scores.items(): logger.info("test {0}: {1}".format(name, score)) test_performance = os.path.join(self.output_dir, "test_performance.txt") feature_scores_dict = self._metrics.write_feature_scores_to_file( test_performance ) return feature_scores_dict def _get_feature_from_index(self, index): """ Gets the feature at an index in the features list. Parameters ---------- index : int Returns ------- str The name of the feature/target at the specified index. """ return self.target_features[index]
[ "selene_sdk.utils.load_model_from_state_dict", "tqdm.tqdm", "numpy.random.choice", "numpy.average", "os.makedirs", "numpy.concatenate", "math.ceil", "torch.load", "os.path.dirname", "selene_sdk.utils.PerformanceMetrics", "torch.sigmoid", "torch.utils.tensorboard.SummaryWriter", "torch.device...
[((525, 552), 'logging.getLogger', 'logging.getLogger', (['"""selene"""'], {}), "('selene')\n", (542, 552), False, 'import logging\n'), ((3016, 3059), 'os.makedirs', 'os.makedirs', (['self.output_dir'], {'exist_ok': '(True)'}), '(self.output_dir, exist_ok=True)\n', (3027, 3059), False, 'import os\n'), ((3330, 3408), 'torch.load', 'torch.load', (['trained_model_path'], {'map_location': '(lambda storage, location: storage)'}), '(trained_model_path, map_location=lambda storage, location: storage)\n', (3340, 3408), False, 'import torch\n'), ((3811, 3831), 'torch.device', 'torch.device', (['device'], {}), '(device)\n', (3823, 3831), False, 'import torch\n'), ((4270, 4405), 'selene_sdk.utils.PerformanceMetrics', 'PerformanceMetrics', (['self._get_feature_from_index'], {'report_gt_feature_n_positives': 'report_gt_feature_n_positives', 'metrics': 'metrics'}), '(self._get_feature_from_index,\n report_gt_feature_n_positives=report_gt_feature_n_positives, metrics=\n metrics)\n', (4288, 4405), False, 'from selene_sdk.utils import PerformanceMetrics, initialize_logger, load_model_from_state_dict\n'), ((5144, 5174), 'torch.utils.tensorboard.SummaryWriter', 'SummaryWriter', (['self.output_dir'], {}), '(self.output_dir)\n', (5157, 5174), False, 'from torch.utils.tensorboard import SummaryWriter\n'), ((5991, 6013), 'tqdm.tqdm', 'tqdm', (['self.data_loader'], {}), '(self.data_loader)\n', (5995, 6013), False, 'from tqdm import tqdm\n'), ((8565, 8589), 'numpy.average', 'np.average', (['batch_losses'], {}), '(batch_losses)\n', (8575, 8589), True, 'import numpy as np\n'), ((8781, 8834), 'os.path.join', 'os.path.join', (['self.output_dir', '"""test_performance.txt"""'], {}), "(self.output_dir, 'test_performance.txt')\n", (8793, 8834), False, 'import os\n'), ((2947, 2982), 'os.path.dirname', 'os.path.dirname', (['trained_model_path'], {}), '(trained_model_path)\n', (2962, 2982), False, 'import os\n'), ((3498, 3560), 'selene_sdk.utils.load_model_from_state_dict', 'load_model_from_state_dict', (["trained_model['state_dict']", 'model'], {}), "(trained_model['state_dict'], model)\n", (3524, 3560), False, 'from selene_sdk.utils import PerformanceMetrics, initialize_logger, load_model_from_state_dict\n'), ((3600, 3648), 'selene_sdk.utils.load_model_from_state_dict', 'load_model_from_state_dict', (['trained_model', 'model'], {}), '(trained_model, model)\n', (3626, 3648), False, 'from selene_sdk.utils import PerformanceMetrics, initialize_logger, load_model_from_state_dict\n'), ((3932, 3954), 'torch.nn.DataParallel', 'nn.DataParallel', (['model'], {}), '(model)\n', (3947, 3954), True, 'import torch.nn as nn\n'), ((4856, 4916), 'math.ceil', 'math.ceil', (['(total_val_target_size / MAX_TOTAL_VAL_TARGET_SIZE)'], {}), '(total_val_target_size / MAX_TOTAL_VAL_TARGET_SIZE)\n', (4865, 4916), False, 'import math\n'), ((8107, 8138), 'numpy.concatenate', 'np.concatenate', (['all_predictions'], {}), '(all_predictions)\n', (8121, 8138), True, 'import numpy as np\n'), ((8174, 8201), 'numpy.concatenate', 'np.concatenate', (['all_targets'], {}), '(all_targets)\n', (8188, 8201), True, 'import numpy as np\n'), ((6459, 6474), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6472, 6474), False, 'import torch\n'), ((6927, 6949), 'torch.sigmoid', 'torch.sigmoid', (['outputs'], {}), '(outputs)\n', (6940, 6949), False, 'import torch\n'), ((8278, 8310), 'numpy.concatenate', 'np.concatenate', (['all_target_masks'], {}), '(all_target_masks)\n', (8292, 8310), True, 'import numpy as np\n'), ((7435, 7497), 'numpy.random.choice', 'np.random.choice', (['predictions.shape[0]', 'reduced_val_batch_size'], {}), '(predictions.shape[0], reduced_val_batch_size)\n', (7451, 7497), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import numpy as np from scipy import signal from utils.generate_spikes import random_spikes # Pad output with a flat line for aesthetic purposes flat = np.array([0, 0, 0, 0, 0]) #output = flat #for s in np.random.random_integers(0, 4, 10): # impulse = signal.unit_impulse(5, s) # output = np.concatenate((output, impulse)) #output = np.concatenate((output, flat)) # Make several spikes and concatenate them out = random_spikes(50) out = np.concatenate((flat, out, flat)) # Plot the spikes plt.plot(np.arange(0, 60), out) plt.margins(0.1, 0.1) plt.xlabel('Time [ms]') plt.ylabel('Amplitude') plt.title('Several Neural Spikes') plt.grid(True) plt.show()
[ "matplotlib.pyplot.title", "matplotlib.pyplot.show", "matplotlib.pyplot.margins", "numpy.array", "numpy.arange", "matplotlib.pyplot.ylabel", "utils.generate_spikes.random_spikes", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.grid", "numpy.concatenate" ]
[((187, 212), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0]'], {}), '([0, 0, 0, 0, 0])\n', (195, 212), True, 'import numpy as np\n'), ((456, 473), 'utils.generate_spikes.random_spikes', 'random_spikes', (['(50)'], {}), '(50)\n', (469, 473), False, 'from utils.generate_spikes import random_spikes\n'), ((480, 513), 'numpy.concatenate', 'np.concatenate', (['(flat, out, flat)'], {}), '((flat, out, flat))\n', (494, 513), True, 'import numpy as np\n'), ((565, 586), 'matplotlib.pyplot.margins', 'plt.margins', (['(0.1)', '(0.1)'], {}), '(0.1, 0.1)\n', (576, 586), True, 'import matplotlib.pyplot as plt\n'), ((587, 610), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time [ms]"""'], {}), "('Time [ms]')\n", (597, 610), True, 'import matplotlib.pyplot as plt\n'), ((611, 634), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Amplitude"""'], {}), "('Amplitude')\n", (621, 634), True, 'import matplotlib.pyplot as plt\n'), ((635, 669), 'matplotlib.pyplot.title', 'plt.title', (['"""Several Neural Spikes"""'], {}), "('Several Neural Spikes')\n", (644, 669), True, 'import matplotlib.pyplot as plt\n'), ((670, 684), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (678, 684), True, 'import matplotlib.pyplot as plt\n'), ((685, 695), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (693, 695), True, 'import matplotlib.pyplot as plt\n'), ((542, 558), 'numpy.arange', 'np.arange', (['(0)', '(60)'], {}), '(0, 60)\n', (551, 558), True, 'import numpy as np\n')]
#!/usr/bin/env python """ Use forced alignments to separate digit sequences into individual digits. Author: <NAME> Contact: <EMAIL> Date: 2018 Edited: <NAME> Date: June 2018 """ from __future__ import absolute_import, division, print_function from os import path import argparse import sys import numpy as np #-----------------------------------------------------------------------------# # UTILITY FUNCTIONS # #-----------------------------------------------------------------------------# def check_argv(): """Check the command line arguments.""" parser = argparse.ArgumentParser( description=__doc__.strip().split("\n")[0], add_help=False ) parser.add_argument( "fadir", type=str, help="Directory containing forced alignments." ) parser.add_argument( "outdir", type=str, help="Diretory to write output individual segment files" ) parser.add_argument( "dataset", type=str, choices={"train", "test"}, help="Dataset to obtain segments for." ) if len(sys.argv) == 1: parser.print_help() sys.exit(1) return parser.parse_args() #-----------------------------------------------------------------------------# # MAIN FUNCTION # #-----------------------------------------------------------------------------# def main(): args = check_argv() segments = {} # Read forced alignment fa_dir = args.fadir fa_fn = path.join(fa_dir, args.dataset + "_word_align.ctm") print("Reading:", fa_fn) with open(fa_fn) as f: # Keep track of the number of each digit key added per utterance sequence (in case of duplicates with the same key) utt_digit_keys = {} # For each entry in the forced alignments for line in f: # Create a segments entry line = line.split() utt_key = line[0] digit_start = float(line[2]) digit_duration = float(line[3]) digit_key = line[4] # Keep track of the number of each digit key per utterance key (in case of duplicate digit keys in same sequence) if not utt_key in utt_digit_keys: utt_digit_keys[utt_key] = {} if not digit_key in utt_digit_keys[utt_key]: utt_digit_keys[utt_key][digit_key] = 0 else: utt_digit_keys[utt_key][digit_key] += 1 # Change digit key to be '<digit_key>a' for first occurence, '<digit_key>b' for second occurence, etc. digit_key = digit_key + chr(utt_digit_keys[utt_key][digit_key] + ord('a')) segments[utt_key + "_" + digit_key] = ( # NOTE: Previously used `extract-rows` Kaldi module to extract individual digit features with segment start/end specified in frames (time/[10 ms frame-shift] -> time * 100). # Kaldi now uses `extract-feature-segments` instead, with segment start/end specified in seconds. # Integer floor of (time*100) maintained to generate same feature segments as previously. utt_key, int(np.floor(digit_start*100))/100.0, int(np.floor((digit_start + digit_duration)*100))/100.0 ) # Write segments segments_fn = path.join(args.outdir, "segments_indiv") print("Writing:", segments_fn) with open(segments_fn, "w") as f: for segment_key in sorted(segments): utt_key, digit_start, digit_end = segments[segment_key] f.write( "{} {} {} {}\n".format(segment_key, utt_key, digit_start, digit_end) ) if __name__ == "__main__": main()
[ "numpy.floor", "os.path.join", "sys.exit" ]
[((1595, 1646), 'os.path.join', 'path.join', (['fa_dir', "(args.dataset + '_word_align.ctm')"], {}), "(fa_dir, args.dataset + '_word_align.ctm')\n", (1604, 1646), False, 'from os import path\n'), ((3419, 3459), 'os.path.join', 'path.join', (['args.outdir', '"""segments_indiv"""'], {}), "(args.outdir, 'segments_indiv')\n", (3428, 3459), False, 'from os import path\n'), ((1185, 1196), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (1193, 1196), False, 'import sys\n'), ((3255, 3282), 'numpy.floor', 'np.floor', (['(digit_start * 100)'], {}), '(digit_start * 100)\n', (3263, 3282), True, 'import numpy as np\n'), ((3309, 3355), 'numpy.floor', 'np.floor', (['((digit_start + digit_duration) * 100)'], {}), '((digit_start + digit_duration) * 100)\n', (3317, 3355), True, 'import numpy as np\n')]
""" Functions to add SNPs """ import numpy as np from semopy import Model as semopyModel # from semopy import ModelMeans as semopyModel from semopy.utils import calc_reduced_ml from pandas import DataFrame, concat from dataset import Data from utils import * from itertools import product from factor_analyzer import FactorAnalyzer class Hyperparams: thresh_mlr = 0.1 thresh_sign_snp = 0.05 thresh_abs_param = 0.1 def add_snps_residuals_cv(mod, data: Data, thresh_mlr=Hyperparams.thresh_mlr, thresh_sign_snp=Hyperparams.thresh_sign_snp, thresh_abs_param=Hyperparams.thresh_abs_param, snp_pref=None, n_iter=10): n_cv = 4 cv_data = CVset(dataset=data, n_cv=n_cv) thresh_mlr_var = [0.1, 0.05, 0.01] thresh_sign_snp_var = [0.05, 0.01] thresh_abs_param_var = [0.1, 0.01] gwas_cv = [] snps_added_cv = [] for thresh_mlr, thresh_sign_snp, thresh_abs_param in \ product(*[thresh_mlr_var, thresh_sign_snp_var, thresh_abs_param_var]): print(thresh_mlr, thresh_sign_snp, thresh_abs_param) gwas = [] snps_added = [] for i_cv in range(n_cv): gwas_tmp, snps_added_tmp = \ add_snps_residuals(mod=mod, data=cv_data.train[i_cv], thresh_mlr=thresh_mlr, thresh_sign_snp=thresh_sign_snp, thresh_abs_param=thresh_abs_param, snp_pref=snp_pref, n_iter=10) gwas += [gwas_tmp] snps_added += [snps_added_tmp] gwas_cv += [gwas] snps_added_cv += [snps_added] def add_snps_residuals(mod, data: Data, thresh_mlr=Hyperparams.thresh_mlr, thresh_sign_snp=Hyperparams.thresh_sign_snp, thresh_abs_param=Hyperparams.thresh_abs_param, snp_pref=None, n_iter=10): sem_mod = semopyModel(mod) sem_mod.fit(data.d_all) relations = sem_mod.inspect() relations = relations.loc[relations['op'] == '~', :] phens = [v for v in sem_mod.vars['all'] if v in data.phens] vars_ordered = sem_traversing(mod) vars_lat_ord = list(reversed([v for v in vars_ordered if v in sem_mod.vars['latent']])) new_var_names = [] for f in vars_lat_ord: phens_f = relations.loc[relations['rval'] == f, 'lval'] d = data.d_phens.loc[:, phens_f] fa = FactorAnalyzer(n_factors=1) fa.fit(d) f_val = fa.transform(d) f_val = f_val.transpose()[0] data.d_phens[f] = f_val new_var_names += [f] gwas = dict() snps_added = dict() # for variable in vars_lat_ord: for f in vars_lat_ord: print('-----------') mod_init = '' # print(variable) # print(mod_init) mod_fact, gwas[f], snps_added[f] = \ add_snps_for_variable(mod_init, data, f, thresh_mlr=thresh_mlr, thresh_sign_snp=thresh_sign_snp, thresh_abs_param=thresh_abs_param, # n_iter=n_iter, snp_pref=snp_pref) sem_mod_f = semopyModel(mod_fact) relations_f = sem_mod_f.inspect() relations_f = relations_f.loc[relations_f['op'] == '~', :] f_val = 0 for snp, snp_val in zip(relations_f['rval'], relations_f['Estimate']): f_val += data.d_snps[snp] * snp_val data.d_phens[f] = f_val print('-----------') return gwas, snps_added print(phens) for p in phens: relations_p = relations.loc[relations['lval'] == p, :] p_est = 0 for var, snp_val in zip(relations_p['rval'], relations_p['Estimate']): p_est += data.d_all[var] * snp_val p_val = d.loc[:, p] p_res = p_val - p_est * np.dot(p_est, p_val) / np.dot(p_est, p_est) p_res_name = f'residual_{p}' data.d_phens[p_res_name] = p_res new_var_names += [p_res_name] print('-----------') mod_init = '' mod_fact, gwas[p], snps_added[p] = \ add_snps_for_variable(mod_init, data, p_res_name, thresh_mlr=thresh_mlr, thresh_sign_snp=thresh_sign_snp, thresh_abs_param=thresh_abs_param, # n_iter=n_iter, snp_pref=snp_pref) print('-----------') data.d_phens = data.d_phens.loc[:, [v for v in data.d_phens.columns if v not in new_var_names]] return gwas, snps_added def add_snps(mod, data: Data, thresh_mlr=Hyperparams.thresh_mlr, thresh_sign_snp=Hyperparams.thresh_sign_snp, thresh_abs_param=Hyperparams.thresh_abs_param, snp_pref=None, n_iter=10): """ Add SNPs to the model :return: model and prior values of parameters """ sem_mod = fix_variances(semopyModel(mod, cov_diag=True)) vars_ordered = sem_traversing(mod) vars_lat_ord = [v for v in vars_ordered if v in sem_mod.vars['latent']] vars_phen_ord = [v for v in vars_ordered if v in data.phens] # Estimate init model and create new model with fixed parameters # sem_mod.fit(concat([data.d_phens, data.d_snps], axis=1)) sem_mod.fit(data.d_all) mod_init = '\n'.join(parse_descr(sem_mod=sem_mod)) # show(mod_init) sem_mod_init = fix_variances(semopyModel(mod_init, cov_diag=True)) sem_mod_init.fit(data.d_all) gwas = dict() snps_added = dict() # for variable in vars_lat_ord: for variable in vars_lat_ord + vars_phen_ord: # print(variable) # print(mod_init) print('-----------') mod_init, gwas[variable], snps_added[variable] = add_snps_for_variable(mod_init, data, variable, thresh_mlr=thresh_mlr, thresh_sign_snp=thresh_sign_snp, thresh_abs_param=thresh_abs_param, snp_pref=snp_pref, n_iter=n_iter) print('-----------') print('-----------') # form specific variables instead of latent ones return mod_init, gwas, snps_added def add_snps_for_variable(mod, data: Data, variable, thresh_mlr=Hyperparams.thresh_mlr, thresh_sign_snp=Hyperparams.thresh_sign_snp, thresh_abs_param=Hyperparams.thresh_abs_param, snp_pref=None, n_iter=100): snp_lists = [] snp_skip = [] mod_init = f'{mod}' snps_added = [] for _ in range(n_iter): show(mod_init) mod_new, snp_skip, snp_list = \ one_snp_for_variable(mod_init, data, variable, snp_skip=snp_skip, thresh_mlr=thresh_mlr, thresh_sign_snp=thresh_sign_snp, thresh_abs_param=thresh_abs_param, snp_pref=snp_pref, echo=True) snp_lists += [snp_list] if mod_new is None: print('NO SNPs added') break mod_init = mod_new snps_added += [snp_skip[-1]] return mod_init, snp_lists, snps_added def one_snp_for_variable(mod_init, data: Data, variable, snp_skip, thresh_mlr=Hyperparams.thresh_mlr, thresh_sign_snp=Hyperparams.thresh_sign_snp, thresh_abs_param=Hyperparams.thresh_abs_param, snp_pref=None, echo=False): """ This fucntion tests SNPs and add one SNP for a variable :param mod_init: model with some fixed parameters :param variable: a variable to add SNP for :param data: training dataset :param snp_skip: list of SNPs to skip :param tune: boolean flag to restrict the variance of random errors :param mx_cov: covariance matrix :return: model with the included SNP and list of SNPs to exclude in further consideration """ # Initialisation v_tmp = 'tmp' empty_mod = False if mod_init == '': empty_mod = True # New models mod_tmp = f'{mod_init}\n{variable} ~ {v_tmp}' mod_zero = f'{mod_init}\n{variable} ~ 0*{v_tmp}' # sem_mod_init = fix_variances(semopyModel(mod_init, cov_diag=True)) # without tmp dummy variable sem_mod_tmp = fix_variances(semopyModel(mod_tmp, cov_diag=True)) # with tmp variable sem_mod_zero = fix_variances(semopyModel(mod_zero, cov_diag=True)) # with tmp variable, but fixed influence to 0 # New data snp_all = data.snps if snp_pref is not None: snp_all = filter_by_pref(snp_all, snp_pref) snp_in = intersect(snp_all, sem_mod_tmp.vars['all']) phens_in = intersect(data.d_phens.columns, sem_mod_tmp.vars['all']) data_tmp = concat([data.d_phens[phens_in], data.d_snps[snp_in]], axis=1) data_tmp[v_tmp] = np.zeros(data.n_samples) snp = data.snps[0] #'Ca1_101073' # snp = 'Ca3_28437425' data_tmp[v_tmp] = data.d_snps[snp] # # Fit models # sem_mod_init.fit(data_tmp, clean_slate=True) sem_mod_zero.fit(data_tmp, clean_slate=True) # sem_mod_tmp.fit(data_tmp, clean_slate=True) # 11.896190990354398 # # # data_tmp[v_tmp] = data.d_snps['Ca3_28437425'] # # sem_mod_tmp.fit(data_tmp, clean_slate=True) # 12.96532468871669 # # # fit_init_reduced = calc_reduced_ml(sem_mod_init, phens_in) if empty_mod: fit_zero_reduced = 10 ** 10 else: fit_zero_reduced = calc_reduced_ml(sem_mod_zero, phens_in) # fit_tmp_reduced = calc_reduced_ml(sem_mod_tmp, data.phens) # # if echo: # print(fit_zero_reduced, fit_init_reduced) # # if abs(fit_zero_reduced - fit_init_reduced) > 0.01: # raise ValueError('Something is going wring') # Try all SNPs if echo: print(f'Skip {len(snp_skip)} SNPs') snp_list = [] for snp in snp_all: if snp in snp_skip: continue try: # print(snp) # Fit the model data_tmp[v_tmp] = data.d_snps[snp] obj = sem_mod_tmp.fit(data_tmp, clean_slate=True) if empty_mod: fit_tmp_reduced = obj.fun else: fit_tmp_reduced = calc_reduced_ml(sem_mod_tmp, phens_in) fit_delta = fit_zero_reduced - fit_tmp_reduced # print(fit_delta) effect = [[row['Estimate'], row['p-value']] for _, row in sem_mod_tmp.inspect().iterrows() if (row['lval'] == variable) and (row['rval'] == v_tmp) and (row['op'] == '~')] if len(effect) > 1: raise ValueError("S") param_val, pval = effect[0] snp_list += [(snp, fit_delta, param_val, pval)] # If the increment of MLR is small - stop considering the SNP if fit_delta < thresh_mlr: snp_skip += [snp] continue # If the influence is not significant - stop considering the SNP if pval > thresh_sign_snp: snp_skip += [snp] continue # If the influence is not high - stop considering the SNP if abs(param_val) < thresh_abs_param: snp_skip += [snp] continue except KeyboardInterrupt: raise except: snp_skip += [snp] snp_list += [(snp, 0, 0, 1)] continue # If no SNPs improves the model if len(snp_list) == 0: return None, snp_skip, snp_list # print(snp_list) # Get the best SNP snp_max, snp_val, fit_delta = get_best_snp([v for v in snp_list if v[0] not in snp_skip]) if snp_max is None: return None, snp_skip, snp_list snp_skip += [snp_max] # To remove from further consideration # Add SNP to the model mod_max = f'{mod_init}\n{variable} ~ {snp_val}*{snp_max}' if echo: data_tmp[snp_max] = data.d_snps[snp_max] sem_mod_max = fix_variances(semopyModel(mod_max, cov_diag=True)) sem_mod_max.fit(data_tmp, clean_slate=True) fit_max_reduced = calc_reduced_ml(sem_mod_max, phens_in) print(fit_zero_reduced - fit_max_reduced - fit_delta) return mod_max, snp_skip, snp_list def get_best_snp(snp_list): """ This function choses the best SNP from the tested list by the max values :param snp_list: list of SNPs with log-likelihood values :return: name of the best SNP anf its loading value """ if len(snp_list) == 0: return None, 0, 0 # Get the best SNP snp_max = '' snp_val = 0 delta_max = snp_list[0][1] for snp, delta, val, pval in snp_list: if delta >= delta_max: delta_max = delta snp_max = snp snp_val = val return snp_max, snp_val, delta_max def sem_var_order(descr): """ String description of the mtmlSEM model :param descr: string :return: lists of latent and phenotype variables """ descr_lines = descr.split('\n') sem_mod = fix_variances(semopyModel('\n'.join(descr_lines))) var_lat = list(sem_mod.vars['latent']) var_exo = list(sem_mod.vars['exogenous']) var_lat_exo = intersect(var_lat, var_exo) var_phen = diff(sem_mod.vars['observed'], var_exo) var_order = [] while len(var_lat) > 0: descr_lines = [line for line in descr_lines if all([line.find(lat) < 0 for lat in var_lat_exo])] sem_mod = fix_variances(semopyModel('\n'.join(descr_lines))) var_lat_new = list(sem_mod.vars['latent']) var_order += diff(var_lat, var_lat_new) var_lat = var_lat_new var_exo = list(sem_mod.vars['exogenous']) var_lat_exo = intersect(var_lat, var_exo) # print(var_order) return var_order, var_phen def sem_traversing(descr): """ String description of the mtmlSEM model :param descr: string :return: lists of latent and phenotype variables """ descr_lines = parse_descr(descr) sem_mod = fix_variances(semopyModel('\n'.join(descr_lines))) var_exo = list(sem_mod.vars['exogenous']) var_all = list(sem_mod.vars['all']) var_order = [] while len(var_exo) > 0: descr_lines = [line for line in descr_lines if all([line.find(lat) < 0 for lat in var_exo])] sem_mod = fix_variances(semopyModel('\n'.join(descr_lines))) var_exo_new = list(sem_mod.vars['exogenous']) var_order += diff(var_exo, var_exo_new) var_exo = var_exo_new var_order += diff(var_all, var_order) # showl(var_order) return var_order def parse_descr(descr=None, sem_mod=None): """ Translate the description of the model into interactions between pair of variables :param descr: String :return: """ # print(descr, sem_mod) if (descr is None) and (sem_mod is None): raise ValueError('Please provide arguments') if descr is None: descr = sem_mod.description effects = sem_mod.inspect() descr_lines = descr.split('\n') lines_spart = [line for line in descr_lines if (line.find('~') > 0) and (line.find('=~') < 0)] lines_mpart = [line for line in descr_lines if line.find('=~') > 0] descr_parse = [] for line in lines_spart: tmp = line.split('~') indicators = get_words_in_line(tmp[0]) predictors = get_words_in_line(tmp[1]) pairs = list(product(indicators, predictors)) if sem_mod is None: descr_parse += [f'{p[0]} ~ {p[1]}' for p in pairs] else: vals = [effects[(effects['lval'] == p[0]) & (effects['rval'] == p[1])].iloc[0]['Estimate'] for p in pairs] descr_parse += [f'{p[0]} ~ {v} * {p[1]}' for p, v in zip(pairs, vals)] for line in lines_mpart: tmp = line.split('=~') predictors = get_words_in_line(tmp[0]) indicators = get_words_in_line(tmp[1]) pairs = list(product(indicators, predictors)) if sem_mod is None: descr_parse += [f'{p[0]} ~ {p[1]}' for p in pairs] else: vals = [effects[(effects['lval'] == p[0]) & (effects['rval'] == p[1])].iloc[0]['Estimate'] for p in pairs] descr_parse += [f'{p[1]} =~ {v} * {p[0]}' for p, v in zip(pairs, vals)] # showl(descr_parse) return descr_parse def fix_variances(sem: semopyModel, var_cutoff=0.05): for k, v in sem.parameters.items(): if not k.startswith('_c'): continue v.bound = (0, var_cutoff) return sem
[ "factor_analyzer.FactorAnalyzer", "numpy.zeros", "semopy.Model", "semopy.utils.calc_reduced_ml", "itertools.product", "numpy.dot", "pandas.concat" ]
[((1069, 1138), 'itertools.product', 'product', (['*[thresh_mlr_var, thresh_sign_snp_var, thresh_abs_param_var]'], {}), '(*[thresh_mlr_var, thresh_sign_snp_var, thresh_abs_param_var])\n', (1076, 1138), False, 'from itertools import product\n'), ((2266, 2282), 'semopy.Model', 'semopyModel', (['mod'], {}), '(mod)\n', (2277, 2282), True, 'from semopy import Model as semopyModel\n'), ((9717, 9778), 'pandas.concat', 'concat', (['[data.d_phens[phens_in], data.d_snps[snp_in]]'], {'axis': '(1)'}), '([data.d_phens[phens_in], data.d_snps[snp_in]], axis=1)\n', (9723, 9778), False, 'from pandas import DataFrame, concat\n'), ((9801, 9825), 'numpy.zeros', 'np.zeros', (['data.n_samples'], {}), '(data.n_samples)\n', (9809, 9825), True, 'import numpy as np\n'), ((2789, 2816), 'factor_analyzer.FactorAnalyzer', 'FactorAnalyzer', ([], {'n_factors': '(1)'}), '(n_factors=1)\n', (2803, 2816), False, 'from factor_analyzer import FactorAnalyzer\n'), ((3608, 3629), 'semopy.Model', 'semopyModel', (['mod_fact'], {}), '(mod_fact)\n', (3619, 3629), True, 'from semopy import Model as semopyModel\n'), ((5498, 5529), 'semopy.Model', 'semopyModel', (['mod'], {'cov_diag': '(True)'}), '(mod, cov_diag=True)\n', (5509, 5529), True, 'from semopy import Model as semopyModel\n'), ((6022, 6058), 'semopy.Model', 'semopyModel', (['mod_init'], {'cov_diag': '(True)'}), '(mod_init, cov_diag=True)\n', (6033, 6058), True, 'from semopy import Model as semopyModel\n'), ((9274, 9309), 'semopy.Model', 'semopyModel', (['mod_tmp'], {'cov_diag': '(True)'}), '(mod_tmp, cov_diag=True)\n', (9285, 9309), True, 'from semopy import Model as semopyModel\n'), ((9365, 9401), 'semopy.Model', 'semopyModel', (['mod_zero'], {'cov_diag': '(True)'}), '(mod_zero, cov_diag=True)\n', (9376, 9401), True, 'from semopy import Model as semopyModel\n'), ((10423, 10462), 'semopy.utils.calc_reduced_ml', 'calc_reduced_ml', (['sem_mod_zero', 'phens_in'], {}), '(sem_mod_zero, phens_in)\n', (10438, 10462), False, 'from semopy.utils import calc_reduced_ml\n'), ((13159, 13197), 'semopy.utils.calc_reduced_ml', 'calc_reduced_ml', (['sem_mod_max', 'phens_in'], {}), '(sem_mod_max, phens_in)\n', (13174, 13197), False, 'from semopy.utils import calc_reduced_ml\n'), ((13044, 13079), 'semopy.Model', 'semopyModel', (['mod_max'], {'cov_diag': '(True)'}), '(mod_max, cov_diag=True)\n', (13055, 13079), True, 'from semopy import Model as semopyModel\n'), ((16542, 16573), 'itertools.product', 'product', (['indicators', 'predictors'], {}), '(indicators, predictors)\n', (16549, 16573), False, 'from itertools import product\n'), ((17089, 17120), 'itertools.product', 'product', (['indicators', 'predictors'], {}), '(indicators, predictors)\n', (17096, 17120), False, 'from itertools import product\n'), ((4306, 4326), 'numpy.dot', 'np.dot', (['p_est', 'p_est'], {}), '(p_est, p_est)\n', (4312, 4326), True, 'import numpy as np\n'), ((11187, 11225), 'semopy.utils.calc_reduced_ml', 'calc_reduced_ml', (['sem_mod_tmp', 'phens_in'], {}), '(sem_mod_tmp, phens_in)\n', (11202, 11225), False, 'from semopy.utils import calc_reduced_ml\n'), ((4283, 4303), 'numpy.dot', 'np.dot', (['p_est', 'p_val'], {}), '(p_est, p_val)\n', (4289, 4303), True, 'import numpy as np\n')]
# -------------------------------------------------------------------------------------------------- # Copyright (c) 2018 Microsoft Corporation # # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and # associated documentation files (the "Software"), to deal in the Software without restriction, # including without limitation the rights to use, copy, modify, merge, publish, distribute, # sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT # NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # -------------------------------------------------------------------------------------------------- """Module containing custom spaces used by malmopy environments.""" import numpy as np import gym from . import Command, History class DiscreteCommand(gym.spaces.Discrete, Command): """Space which has a fixed number of text commands.""" def __init__(self, verbs): """ Args: verbs -- a list of command verbs """ self._verbs = verbs super(DiscreteCommand, self).__init__(len(verbs)) @property def verbs(self): return self._verbs def to_commands(self, sample_n): if self.contains(sample_n): sample_n = [sample_n] commands = [] for sample in sample_n: assert self.contains(sample) commands.append(self._verbs[sample]) return commands def __repr__(self): return "Command(verbs: {})".format(self.verbs) class ContinuousTupleCommand(gym.spaces.Tuple, Command): """ Command space which uses a combination of a fixed number of verbs and a continuous argument. """ def __init__(self, verbs, low=-1.0, high=1.0): """ Args: verbs -- a list of command verbs Keyword Args: low -- the minimum command argument [-1.0] high -- the maximum command argument [1.0] """ self._verbs = verbs spaces = (gym.spaces.Discrete(len(verbs)), gym.spaces.Box(low, high, (1,), np.float32)) super(ContinuousTupleCommand, self).__init__(spaces) @property def verbs(self): return self._verbs def to_commands(self, sample_n): if self.contains(sample_n): sample_n = [sample_n] commands = [] for sample in sample_n: assert self.contains(sample) index, arg = sample commands.append("{0} {1:.2f}".format(self._verbs[index], arg[0])) return commands def __repr__(self): return "Command(verbs: {}, args: {})".format(self.verbs, self.spaces[1]) class ContinuousStepCommand(gym.spaces.Discrete, Command): """ Command space which uses a combination of a fixed number of verbs and a discretized continuous argument. """ def __init__(self, verbs, low=-1.0, high=1.0, steps=10): """ Args: verbs -- a list of command verbs Keyword Args: low -- the minimum command argument [-1.0] high -- the maximum command argument [1.0] steps -- the number of discretized steps to use [10] """ self._verbs = verbs self._low = low self._delta = (high - low)/steps self._dims = (len(verbs), steps) super(ContinuousStepCommand, self).__init__(np.prod(self._dims)) @property def verbs(self): return self._verbs def to_commands(self, sample_n): if self.contains(sample_n): sample_n = [sample_n] commands = [] for sample in sample_n: assert self.contains(sample) verb_index, arg_index = np.unravel_index(sample, self._dims) verb = self._verbs[verb_index] arg = self._low + arg_index*self._delta commands.append("{0} {1:.2f}".format(verb, arg)) return commands def __repr__(self): steps = self._dims[1] high = self._low + steps*self._delta return "Command(verbs: {}, args: {})".format(self.verbs, (self._low, high, steps)) class StringCommand(gym.Space, Command): """Space which allows arbitrary string commands prepended with set verbs.""" def __init__(self, verbs): """ Args: verbs -- the verbs which must prepend the string commands """ super(StringCommand, self).__init__((1,), 'U') self._verbs = verbs def sample(self): raise NotImplementedError def to_commands(self, sample_n): return list(sample_n) @property def verbs(self): return self._verbs def contains(self, x): if not x.dtype.kind in ('S', 'U'): return False startswith = np.zeros(x.shape, np.bool) for verb in self._verbs: startswith = startswith | np.char.startswith(x, verb) return startswith.all() def to_jsonable(self, sample_n): return np.array(sample_n).tolist() def from_jsonable(self, sample_n): return [np.asarray(sample) for sample in sample_n] def __repr__(self): return "StringCommand(verbs: {})".format(self.verbs) class BoxHistory(gym.spaces.Box, History): """Space which describes a history of Box observations.""" def __init__(self, length, space): """ Args: length -- the length of the history space -- a Box space """ assert isinstance(space, gym.spaces.Box) self._length = length self._inner = space shape = (length, ) + space.shape dtype = space.dtype low = np.zeros(shape, dtype) high = np.zeros(shape, dtype) low[:] = space.low high[:] = space.high super(BoxHistory, self).__init__(low=low, high=high, dtype=dtype) @property def inner(self): return self._inner @property def length(self): return self._length class MultiDiscreteHistory(gym.Space, History): """Space which describes a history of MultiDiscrete observations.""" def __init__(self, length, space): """ Args: length -- the length of the history space -- a MultiDiscrete space """ assert isinstance(space, gym.spaces.MultiDiscrete) self._length = length self._inner = space shape = (length, space.nvec.size) self.nvec = np.zeros(shape, space.dtype) self.nvec[:] = space.nvec super(MultiDiscreteHistory, self).__init__(shape, space.dtype) @property def inner(self): return self._inner @property def length(self): return self._length def sample(self): return (gym.spaces.np_random.random_sample(self.shape) * self.nvec).astype(self.dtype) def contains(self, x): return x.shape == self.shape and (x < self.nvec).all() and x.dtype.kind in 'ui' def to_jsonable(self, sample_n): return np.array(sample_n).tolist() def from_jsonable(self, sample_n): return [np.asarray(sample) for sample in sample_n] class MultiBinaryHistory(gym.Space, History): """Space which describes a history of MultiBinary observations.""" def __init__(self, length, space): """ Args: length -- the length of the history space -- a MultiBinary space """ assert isinstance(space, gym.spaces.MultiBinary) self._length = length self._inner = space super(MultiBinaryHistory, self).__init__((length, space.n), space.dtype) @property def inner(self): return self._inner @property def length(self): return self._length def sample(self): return gym.spaces.np_random.randint(0, 2, self.shape).astype(self.dtype) def contains(self, x): return x.shape == self.shape and ((x == 0) | (x == 1)).all() def to_jsonable(self, sample_n): return np.array(sample_n).tolist() def from_jsonable(self, sample_n): return [np.asarray(sample) for sample in sample_n] class DiscreteHistory(gym.Space, History): """Space which describes a history of Discrete observations.""" def __init__(self, length, space): """ Args: length -- the length of the history space -- a Discrete space """ assert isinstance(space, gym.spaces.Discrete) self._length = length self._inner = space super(DiscreteHistory, self).__init__((length, 1), space.dtype) @property def inner(self): return self._inner @property def length(self): return self._length def sample(self): return gym.spaces.np_random.randint(self._inner.n, size=self.shape).astype(self.dtype) def contains(self, x): return x.shape == self.shape and (x < self._inner.n).all() and x.dtype.kind in 'ui' def to_jsonable(self, sample_n): return np.array(sample_n).tolist() def from_jsonable(self, sample_n): return [np.asarray(sample) for sample in sample_n] def to_history_space(length, space): """Converts a space to a history space. Args: length -- the length of the history space -- the space from which observations are drawn Returns a space which represents a history of observations drawn from the original space """ if isinstance(space, gym.spaces.Box): return BoxHistory(length, space) if isinstance(space, gym.spaces.MultiDiscrete): return MultiDiscreteHistory(length, space) if isinstance(space, gym.spaces.MultiBinary): return MultiBinaryHistory(length, space) if isinstance(space, gym.spaces.Discrete): return DiscreteHistory(length, space) raise NotImplementedError
[ "gym.spaces.np_random.random_sample", "numpy.asarray", "numpy.zeros", "numpy.unravel_index", "numpy.array", "gym.spaces.Box", "numpy.char.startswith", "gym.spaces.np_random.randint", "numpy.prod" ]
[((5419, 5445), 'numpy.zeros', 'np.zeros', (['x.shape', 'np.bool'], {}), '(x.shape, np.bool)\n', (5427, 5445), True, 'import numpy as np\n'), ((6301, 6323), 'numpy.zeros', 'np.zeros', (['shape', 'dtype'], {}), '(shape, dtype)\n', (6309, 6323), True, 'import numpy as np\n'), ((6339, 6361), 'numpy.zeros', 'np.zeros', (['shape', 'dtype'], {}), '(shape, dtype)\n', (6347, 6361), True, 'import numpy as np\n'), ((7091, 7119), 'numpy.zeros', 'np.zeros', (['shape', 'space.dtype'], {}), '(shape, space.dtype)\n', (7099, 7119), True, 'import numpy as np\n'), ((2700, 2743), 'gym.spaces.Box', 'gym.spaces.Box', (['low', 'high', '(1,)', 'np.float32'], {}), '(low, high, (1,), np.float32)\n', (2714, 2743), False, 'import gym\n'), ((4033, 4052), 'numpy.prod', 'np.prod', (['self._dims'], {}), '(self._dims)\n', (4040, 4052), True, 'import numpy as np\n'), ((4357, 4393), 'numpy.unravel_index', 'np.unravel_index', (['sample', 'self._dims'], {}), '(sample, self._dims)\n', (4373, 4393), True, 'import numpy as np\n'), ((5715, 5733), 'numpy.asarray', 'np.asarray', (['sample'], {}), '(sample)\n', (5725, 5733), True, 'import numpy as np\n'), ((7724, 7742), 'numpy.asarray', 'np.asarray', (['sample'], {}), '(sample)\n', (7734, 7742), True, 'import numpy as np\n'), ((8715, 8733), 'numpy.asarray', 'np.asarray', (['sample'], {}), '(sample)\n', (8725, 8733), True, 'import numpy as np\n'), ((9722, 9740), 'numpy.asarray', 'np.asarray', (['sample'], {}), '(sample)\n', (9732, 9740), True, 'import numpy as np\n'), ((5517, 5544), 'numpy.char.startswith', 'np.char.startswith', (['x', 'verb'], {}), '(x, verb)\n', (5535, 5544), True, 'import numpy as np\n'), ((5631, 5649), 'numpy.array', 'np.array', (['sample_n'], {}), '(sample_n)\n', (5639, 5649), True, 'import numpy as np\n'), ((7640, 7658), 'numpy.array', 'np.array', (['sample_n'], {}), '(sample_n)\n', (7648, 7658), True, 'import numpy as np\n'), ((8415, 8461), 'gym.spaces.np_random.randint', 'gym.spaces.np_random.randint', (['(0)', '(2)', 'self.shape'], {}), '(0, 2, self.shape)\n', (8443, 8461), False, 'import gym\n'), ((8631, 8649), 'numpy.array', 'np.array', (['sample_n'], {}), '(sample_n)\n', (8639, 8649), True, 'import numpy as np\n'), ((9385, 9445), 'gym.spaces.np_random.randint', 'gym.spaces.np_random.randint', (['self._inner.n'], {'size': 'self.shape'}), '(self._inner.n, size=self.shape)\n', (9413, 9445), False, 'import gym\n'), ((9638, 9656), 'numpy.array', 'np.array', (['sample_n'], {}), '(sample_n)\n', (9646, 9656), True, 'import numpy as np\n'), ((7392, 7438), 'gym.spaces.np_random.random_sample', 'gym.spaces.np_random.random_sample', (['self.shape'], {}), '(self.shape)\n', (7426, 7438), False, 'import gym\n')]
import numpy as np import matplotlib.pyplot as plt from time import time # Global vars ------------------------------------------------------- n_users = 100 time_scale = 4*60 start_coord = np.array([0.5, 0.5]) speed = 0.02 window_duration = 60. alpha = 1. # heuristic coefficient beta = 1. # kernel coefficient # Global vars ------------------------------------------------------- def gantt_plot(window_time, window_duration=window_duration): x_gnt = [(t, window_duration) for t in window_time] y_gnt = [(i+0.5, 1) for i in range(len(window_time))] fig, gnt = plt.subplots(figsize=(14,9)) gnt.set_xlabel('seconds') gnt.set_ylabel('User') gnt.grid(True) gnt.set_yticks(np.arange(len(window_time))+1) for x, y in zip(x_gnt, y_gnt): gnt.broken_barh([x], y) plt.show() def user_plot(pos, path=None): plt.figure(1, figsize=(12,7)) plt.scatter(pos[:,0], pos[:,1]) if path is not None: from_pos = start_coord for p in path: p = p[0] plt.arrow(from_pos[0], from_pos[1], p[0]-from_pos[0], p[1]-from_pos[1], head_width=0.01, head_length=0.01, fc='r', ec='r') from_pos = p plt.show() def get_heuristics(pos, window_time, window_duration=window_duration, speed=speed, beta=beta): h = [] for i in range(len(window_time)): window_overlap = 1 - np.abs(np.minimum(window_time+window_duration, window_time[i]+window_duration) - np.maximum(window_time, window_time[i])) / window_duration time_dist = np.linalg.norm(pos - pos[i,:], axis=1) * window_overlap / speed h_i = np.exp(-beta*np.mean(time_dist)) h.append(h_i) return np.array(h) def solve(pos, window_time, alpha=alpha, beta=beta, time_scale=time_scale, window_duration=window_duration, speed=speed, start_coord=start_coord, verbose=False): remaining_time = time_scale + window_duration rem_pos = pos.copy() rem_win = window_time.copy() rem_ids = np.arange(pos.shape[0]) now_pos = start_coord path = [] total_elapsed = 0. start_time = time() while remaining_time > 0 and len(rem_pos) > 0: dist = np.linalg.norm(rem_pos - now_pos, axis=1) / speed w = np.array([(total_elapsed + dist[i]) > win and (total_elapsed + dist[i]) < (win + window_duration) for i, win in enumerate(rem_win)]) * 1 if np.sum(w) == 0: # if no users available future = [(win, dist[i]) for i, win in enumerate(rem_win) if (total_elapsed + dist[i]) < win] if len(future) == 0: break min_id = np.argmin([f[0] for f in future]) time_to_min = future[min_id][1] wait_time = future[min_id][0] - time_to_min - total_elapsed remaining_time = remaining_time - wait_time total_elapsed = total_elapsed + wait_time continue h = get_heuristics(rem_pos, rem_win, beta=beta) a_star = (np.exp(-beta*dist) + alpha*h) * w best = np.argmax(a_star) elapsed = dist[best] remaining_time = remaining_time - elapsed total_elapsed = total_elapsed + elapsed if total_elapsed >= time_scale + window_duration: break path.append((rem_pos[best], elapsed, total_elapsed, rem_ids[best])) now_pos = rem_pos[best] rem_pos = np.delete(rem_pos, best, axis=0) rem_win = np.delete(rem_win, best, axis=0) rem_ids = np.delete(rem_ids, best, axis=0) end_time = time() exec_time = end_time-start_time if verbose: print(f"execution time: {exec_time:.3f} s") print(f"users served: {len(path)}") return path, exec_time def verify_path(pos, window_time, path, speed=speed, start_coord=start_coord, time_scale=time_scale, window_duration=window_duration, verbose=False): if path[-1][2] > time_scale + window_duration: if verbose: print("Exeeded time limit") return False for p in path: if p[2] < window_time[p[3]] or p[2] > window_time[p[3]] + window_duration: if verbose: print("Visited user outside of the time window") return False return True if __name__ == '__main__': show_plots = True # Random initialization pos = np.random.random((n_users,2)) window_time = np.random.random(n_users)*time_scale if show_plots: user_plot(pos) gantt_plot(window_time) path, exec_time = solve(pos, window_time, verbose=True) print(f"Path ok: {verify_path(pos, window_time, path, verbose=True)}") # print(path) if show_plots: user_plot(pos, path)
[ "numpy.minimum", "matplotlib.pyplot.show", "numpy.sum", "numpy.maximum", "numpy.argmax", "matplotlib.pyplot.scatter", "numpy.argmin", "time.time", "matplotlib.pyplot.figure", "numpy.random.random", "numpy.array", "numpy.arange", "numpy.linalg.norm", "numpy.mean", "numpy.exp", "matplotl...
[((190, 210), 'numpy.array', 'np.array', (['[0.5, 0.5]'], {}), '([0.5, 0.5])\n', (198, 210), True, 'import numpy as np\n'), ((576, 605), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(14, 9)'}), '(figsize=(14, 9))\n', (588, 605), True, 'import matplotlib.pyplot as plt\n'), ((803, 813), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (811, 813), True, 'import matplotlib.pyplot as plt\n'), ((850, 880), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(12, 7)'}), '(1, figsize=(12, 7))\n', (860, 880), True, 'import matplotlib.pyplot as plt\n'), ((884, 917), 'matplotlib.pyplot.scatter', 'plt.scatter', (['pos[:, 0]', 'pos[:, 1]'], {}), '(pos[:, 0], pos[:, 1])\n', (895, 917), True, 'import matplotlib.pyplot as plt\n'), ((1180, 1190), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1188, 1190), True, 'import matplotlib.pyplot as plt\n'), ((1670, 1681), 'numpy.array', 'np.array', (['h'], {}), '(h)\n', (1678, 1681), True, 'import numpy as np\n'), ((1967, 1990), 'numpy.arange', 'np.arange', (['pos.shape[0]'], {}), '(pos.shape[0])\n', (1976, 1990), True, 'import numpy as np\n'), ((2072, 2078), 'time.time', 'time', ([], {}), '()\n', (2076, 2078), False, 'from time import time\n'), ((3481, 3487), 'time.time', 'time', ([], {}), '()\n', (3485, 3487), False, 'from time import time\n'), ((4271, 4301), 'numpy.random.random', 'np.random.random', (['(n_users, 2)'], {}), '((n_users, 2))\n', (4287, 4301), True, 'import numpy as np\n'), ((2982, 2999), 'numpy.argmax', 'np.argmax', (['a_star'], {}), '(a_star)\n', (2991, 2999), True, 'import numpy as np\n'), ((3330, 3362), 'numpy.delete', 'np.delete', (['rem_pos', 'best'], {'axis': '(0)'}), '(rem_pos, best, axis=0)\n', (3339, 3362), True, 'import numpy as np\n'), ((3381, 3413), 'numpy.delete', 'np.delete', (['rem_win', 'best'], {'axis': '(0)'}), '(rem_win, best, axis=0)\n', (3390, 3413), True, 'import numpy as np\n'), ((3432, 3464), 'numpy.delete', 'np.delete', (['rem_ids', 'best'], {'axis': '(0)'}), '(rem_ids, best, axis=0)\n', (3441, 3464), True, 'import numpy as np\n'), ((4319, 4344), 'numpy.random.random', 'np.random.random', (['n_users'], {}), '(n_users)\n', (4335, 4344), True, 'import numpy as np\n'), ((1028, 1158), 'matplotlib.pyplot.arrow', 'plt.arrow', (['from_pos[0]', 'from_pos[1]', '(p[0] - from_pos[0])', '(p[1] - from_pos[1])'], {'head_width': '(0.01)', 'head_length': '(0.01)', 'fc': '"""r"""', 'ec': '"""r"""'}), "(from_pos[0], from_pos[1], p[0] - from_pos[0], p[1] - from_pos[1],\n head_width=0.01, head_length=0.01, fc='r', ec='r')\n", (1037, 1158), True, 'import matplotlib.pyplot as plt\n'), ((2145, 2186), 'numpy.linalg.norm', 'np.linalg.norm', (['(rem_pos - now_pos)'], {'axis': '(1)'}), '(rem_pos - now_pos, axis=1)\n', (2159, 2186), True, 'import numpy as np\n'), ((2355, 2364), 'numpy.sum', 'np.sum', (['w'], {}), '(w)\n', (2361, 2364), True, 'import numpy as np\n'), ((2577, 2610), 'numpy.argmin', 'np.argmin', (['[f[0] for f in future]'], {}), '([f[0] for f in future])\n', (2586, 2610), True, 'import numpy as np\n'), ((1525, 1564), 'numpy.linalg.norm', 'np.linalg.norm', (['(pos - pos[i, :])'], {'axis': '(1)'}), '(pos - pos[i, :], axis=1)\n', (1539, 1564), True, 'import numpy as np\n'), ((1616, 1634), 'numpy.mean', 'np.mean', (['time_dist'], {}), '(time_dist)\n', (1623, 1634), True, 'import numpy as np\n'), ((2932, 2952), 'numpy.exp', 'np.exp', (['(-beta * dist)'], {}), '(-beta * dist)\n', (2938, 2952), True, 'import numpy as np\n'), ((1372, 1447), 'numpy.minimum', 'np.minimum', (['(window_time + window_duration)', '(window_time[i] + window_duration)'], {}), '(window_time + window_duration, window_time[i] + window_duration)\n', (1382, 1447), True, 'import numpy as np\n'), ((1446, 1485), 'numpy.maximum', 'np.maximum', (['window_time', 'window_time[i]'], {}), '(window_time, window_time[i])\n', (1456, 1485), True, 'import numpy as np\n')]
import keras import numpy as np import pandas as pd import cv2 import os import json import pdb import tensorflow as tf import keras.backend as K from keras.models import Model from keras.layers import Input, Dense from keras.utils.generic_utils import CustomObjectScope from keras.optimizers import SGD, Adam, RMSprop from keras.applications.inception_v3 import InceptionV3 from keras.applications.mobilenet import MobileNet, relu6, DepthwiseConv2D from keras.applications.resnet50 import ResNet50 from keras.applications.densenet import DenseNet121 from datagenerator import ImageDataGenerator def create_model(model_config, image_size, label_map, loss = None): model_map = { 'inception': InceptionV3, 'mobilenet': MobileNet, 'densenet': DenseNet121, 'resnet': ResNet50 } num_class = len(list(label_map.keys())) base_model = model_map[model_config['model_name']](include_top = False, input_shape = (image_size, image_size, 3), pooling = 'avg') x = base_model.output # x = Dense(base_model.output_shape[1], activation = 'relu')(x) predictions = Dense(num_class, activation = 'sigmoid')(x) model = Model(inputs = base_model.input, outputs = predictions) opt = model_config['optimizer'] if opt == 'SGD': optimizer = SGD(lr = model_config['initial_lr'], decay = 1e-6, momentum = 0.9, nesterov = True) elif opt == 'adam': optimizer = Adam(lr = model_config['initial_lr'], decay = 1e-6) else: optimizer = RMSprop(lr = model_config['initial_lr'], decay = 1e-6) # metrics = {value: AUC(int(key)) for key, value in label_map.items()} metrics = [AUC(i) for i in range(num_class)] metrics.append(mean_AUC(num_class)) if loss is None: model.compile(loss = 'binary_crossentropy', optimizer = optimizer, metrics = metrics) else: model.compile(loss = loss, optimizer = optimizer, metrics = metrics) return model def load_filelist(directory, split_name, partition_id, partition_num): path = os.path.join(directory, '{}_{:03}-of-{:03}.csv'.format(split_name, partition_id, partition_num)) df = pd.read_csv(path, delimiter = '\t', header = None, names = ['image', 'label']) labels = [map(float, label[1:-1].split(' ')) for label in df['label']] return df['image'].tolist(), labels def AUC(index): def auc(labels, predictions): score, up_opt = tf.metrics.auc(labels[:,index], predictions[:,index]) K.get_session().run(tf.local_variables_initializer()) with tf.control_dependencies([up_opt]): score = tf.identity(score) return score return auc def mean_AUC(num_class): def mauc(labels, predictions): scores = [] opts = [] for i in range(num_class): score, up_opt = tf.metrics.auc(labels[:,i], predictions[:,i]) scores.append(score) opts.append(up_opt) score = tf.add_n(scores) / float(num_class) K.get_session().run(tf.local_variables_initializer()) with tf.control_dependencies(opts): score = tf.identity(score) return score return mauc def load_model(model_dir, ckpt_path): with open(os.path.join(model_dir, 'model_config.json'), 'r') as f: model_config = json.load(f) epoch = ckpt_path.replace('-', '.').split('.') epoch = int(epoch[1]) model_config['epoch'] = epoch model_config['model_dir'] = model_dir custom_objects = {'auc': AUC(0), 'mauc': AUC(0), 'bp_mll_loss': bp_mll_loss, 'my_loss': weighted_binary_crossentropy(0.5)} if model_config['model_name'] == 'mobilenet': custom_objects['relu6'] = relu6 custom_objects['DepthwiseConv2D'] = DepthwiseConv2D model = keras.models.load_model(os.path.join(model_dir, ckpt_path), custom_objects = custom_objects) return model, model_config def aggregate_teachers(predictions): return np.mean(predictions, axis = 0) def weighted_binary_crossentropy(alpha): def weighted_loss(y_true, y_pred): num_class = tf.shape(y_pred)[1] hard = keras.losses.binary_crossentropy(y_true[:,:num_class], y_pred) soft = keras.losses.binary_crossentropy(y_true[:,num_class:], y_pred) return alpha * hard + (1 - alpha) * soft def loss(y_true, y_pred): return keras.losses.binary_crossentropy(y_true, y_pred) def my_loss(y_true, y_pred): return tf.cond(tf.equal(tf.shape(y_true)[1], tf.shape(y_pred)[1]), lambda: loss(y_true, y_pred), lambda: weighted_loss(y_true, y_pred)) return my_loss def calc_weights(labels): labels = np.array(labels).astype(np.float32) freq = np.mean(labels, axis = 0) inverse = 1. / freq weights = {key: value for key, value in enumerate(inverse)} return weights # bp mll loss function # y_true, y_pred must be 2D tensors of shape (batch dimension, number of labels) # y_true must satisfy y_true[i][j] == 1 iff sample i has label j def bp_mll_loss(y_true, y_pred): # get true and false labels y_i = K.equal(y_true, K.ones_like(y_true)) y_i_bar = K.not_equal(y_true, K.ones_like(y_true)) # cast to float as keras backend has no logical and y_i = K.cast(y_i, dtype='float32') y_i_bar = K.cast(y_i_bar, dtype='float32') # get indices to check truth_matrix = pairwise_and(y_i, y_i_bar) # calculate all exp'd differences sub_matrix = pairwise_sub(y_pred, y_pred) exp_matrix = K.exp(-sub_matrix) # check which differences to consider and sum them sparse_matrix = exp_matrix * truth_matrix sums = K.sum(sparse_matrix, axis=[1,2]) # get normalizing terms and apply them y_i_sizes = K.sum(y_i, axis=1) y_i_bar_sizes = K.sum(y_i_bar, axis=1) normalizers = y_i_sizes * y_i_bar_sizes results = sums / normalizers # sum over samples return K.mean(results) # compute pairwise differences between elements of the tensors a and b def pairwise_sub(a, b): column = K.expand_dims(a, 2) row = K.expand_dims(b, 1) return column - row # compute pairwise logical and between elements of the tensors a and b def pairwise_and(a, b): column = K.expand_dims(a, 2) row = K.expand_dims(b, 1) return K.minimum(column, row)
[ "pandas.read_csv", "tensorflow.identity", "keras.models.Model", "tensorflow.local_variables_initializer", "numpy.mean", "os.path.join", "keras.backend.cast", "tensorflow.add_n", "keras.optimizers.SGD", "keras.losses.binary_crossentropy", "keras.backend.ones_like", "tensorflow.control_dependenc...
[((1125, 1176), 'keras.models.Model', 'Model', ([], {'inputs': 'base_model.input', 'outputs': 'predictions'}), '(inputs=base_model.input, outputs=predictions)\n', (1130, 1176), False, 'from keras.models import Model\n'), ((2034, 2106), 'pandas.read_csv', 'pd.read_csv', (['path'], {'delimiter': '"""\t"""', 'header': 'None', 'names': "['image', 'label']"}), "(path, delimiter='\\t', header=None, names=['image', 'label'])\n", (2045, 2106), True, 'import pandas as pd\n'), ((3649, 3677), 'numpy.mean', 'np.mean', (['predictions'], {'axis': '(0)'}), '(predictions, axis=0)\n', (3656, 3677), True, 'import numpy as np\n'), ((4346, 4369), 'numpy.mean', 'np.mean', (['labels'], {'axis': '(0)'}), '(labels, axis=0)\n', (4353, 4369), True, 'import numpy as np\n'), ((4883, 4911), 'keras.backend.cast', 'K.cast', (['y_i'], {'dtype': '"""float32"""'}), "(y_i, dtype='float32')\n", (4889, 4911), True, 'import keras.backend as K\n'), ((4926, 4958), 'keras.backend.cast', 'K.cast', (['y_i_bar'], {'dtype': '"""float32"""'}), "(y_i_bar, dtype='float32')\n", (4932, 4958), True, 'import keras.backend as K\n'), ((5135, 5153), 'keras.backend.exp', 'K.exp', (['(-sub_matrix)'], {}), '(-sub_matrix)\n', (5140, 5153), True, 'import keras.backend as K\n'), ((5267, 5300), 'keras.backend.sum', 'K.sum', (['sparse_matrix'], {'axis': '[1, 2]'}), '(sparse_matrix, axis=[1, 2])\n', (5272, 5300), True, 'import keras.backend as K\n'), ((5360, 5378), 'keras.backend.sum', 'K.sum', (['y_i'], {'axis': '(1)'}), '(y_i, axis=1)\n', (5365, 5378), True, 'import keras.backend as K\n'), ((5399, 5421), 'keras.backend.sum', 'K.sum', (['y_i_bar'], {'axis': '(1)'}), '(y_i_bar, axis=1)\n', (5404, 5421), True, 'import keras.backend as K\n'), ((5534, 5549), 'keras.backend.mean', 'K.mean', (['results'], {}), '(results)\n', (5540, 5549), True, 'import keras.backend as K\n'), ((5659, 5678), 'keras.backend.expand_dims', 'K.expand_dims', (['a', '(2)'], {}), '(a, 2)\n', (5672, 5678), True, 'import keras.backend as K\n'), ((5689, 5708), 'keras.backend.expand_dims', 'K.expand_dims', (['b', '(1)'], {}), '(b, 1)\n', (5702, 5708), True, 'import keras.backend as K\n'), ((5842, 5861), 'keras.backend.expand_dims', 'K.expand_dims', (['a', '(2)'], {}), '(a, 2)\n', (5855, 5861), True, 'import keras.backend as K\n'), ((5872, 5891), 'keras.backend.expand_dims', 'K.expand_dims', (['b', '(1)'], {}), '(b, 1)\n', (5885, 5891), True, 'import keras.backend as K\n'), ((5903, 5925), 'keras.backend.minimum', 'K.minimum', (['column', 'row'], {}), '(column, row)\n', (5912, 5925), True, 'import keras.backend as K\n'), ((1071, 1109), 'keras.layers.Dense', 'Dense', (['num_class'], {'activation': '"""sigmoid"""'}), "(num_class, activation='sigmoid')\n", (1076, 1109), False, 'from keras.layers import Input, Dense\n'), ((1247, 1323), 'keras.optimizers.SGD', 'SGD', ([], {'lr': "model_config['initial_lr']", 'decay': '(1e-06)', 'momentum': '(0.9)', 'nesterov': '(True)'}), "(lr=model_config['initial_lr'], decay=1e-06, momentum=0.9, nesterov=True)\n", (1250, 1323), False, 'from keras.optimizers import SGD, Adam, RMSprop\n'), ((2290, 2345), 'tensorflow.metrics.auc', 'tf.metrics.auc', (['labels[:, index]', 'predictions[:, index]'], {}), '(labels[:, index], predictions[:, index])\n', (2304, 2345), True, 'import tensorflow as tf\n'), ((3048, 3060), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3057, 3060), False, 'import json\n'), ((3505, 3539), 'os.path.join', 'os.path.join', (['model_dir', 'ckpt_path'], {}), '(model_dir, ckpt_path)\n', (3517, 3539), False, 'import os\n'), ((3803, 3866), 'keras.losses.binary_crossentropy', 'keras.losses.binary_crossentropy', (['y_true[:, :num_class]', 'y_pred'], {}), '(y_true[:, :num_class], y_pred)\n', (3835, 3866), False, 'import keras\n'), ((3875, 3938), 'keras.losses.binary_crossentropy', 'keras.losses.binary_crossentropy', (['y_true[:, num_class:]', 'y_pred'], {}), '(y_true[:, num_class:], y_pred)\n', (3907, 3938), False, 'import keras\n'), ((4019, 4067), 'keras.losses.binary_crossentropy', 'keras.losses.binary_crossentropy', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (4051, 4067), False, 'import keras\n'), ((4736, 4755), 'keras.backend.ones_like', 'K.ones_like', (['y_true'], {}), '(y_true)\n', (4747, 4755), True, 'import keras.backend as K\n'), ((4791, 4810), 'keras.backend.ones_like', 'K.ones_like', (['y_true'], {}), '(y_true)\n', (4802, 4810), True, 'import keras.backend as K\n'), ((1366, 1414), 'keras.optimizers.Adam', 'Adam', ([], {'lr': "model_config['initial_lr']", 'decay': '(1e-06)'}), "(lr=model_config['initial_lr'], decay=1e-06)\n", (1370, 1414), False, 'from keras.optimizers import SGD, Adam, RMSprop\n'), ((1439, 1490), 'keras.optimizers.RMSprop', 'RMSprop', ([], {'lr': "model_config['initial_lr']", 'decay': '(1e-06)'}), "(lr=model_config['initial_lr'], decay=1e-06)\n", (1446, 1490), False, 'from keras.optimizers import SGD, Adam, RMSprop\n'), ((2366, 2398), 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), '()\n', (2396, 2398), True, 'import tensorflow as tf\n'), ((2407, 2440), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['[up_opt]'], {}), '([up_opt])\n', (2430, 2440), True, 'import tensorflow as tf\n'), ((2453, 2471), 'tensorflow.identity', 'tf.identity', (['score'], {}), '(score)\n', (2464, 2471), True, 'import tensorflow as tf\n'), ((2631, 2678), 'tensorflow.metrics.auc', 'tf.metrics.auc', (['labels[:, i]', 'predictions[:, i]'], {}), '(labels[:, i], predictions[:, i])\n', (2645, 2678), True, 'import tensorflow as tf\n'), ((2735, 2751), 'tensorflow.add_n', 'tf.add_n', (['scores'], {}), '(scores)\n', (2743, 2751), True, 'import tensorflow as tf\n'), ((2793, 2825), 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), '()\n', (2823, 2825), True, 'import tensorflow as tf\n'), ((2834, 2863), 'tensorflow.control_dependencies', 'tf.control_dependencies', (['opts'], {}), '(opts)\n', (2857, 2863), True, 'import tensorflow as tf\n'), ((2876, 2894), 'tensorflow.identity', 'tf.identity', (['score'], {}), '(score)\n', (2887, 2894), True, 'import tensorflow as tf\n'), ((2974, 3018), 'os.path.join', 'os.path.join', (['model_dir', '"""model_config.json"""'], {}), "(model_dir, 'model_config.json')\n", (2986, 3018), False, 'import os\n'), ((3774, 3790), 'tensorflow.shape', 'tf.shape', (['y_pred'], {}), '(y_pred)\n', (3782, 3790), True, 'import tensorflow as tf\n'), ((4301, 4317), 'numpy.array', 'np.array', (['labels'], {}), '(labels)\n', (4309, 4317), True, 'import numpy as np\n'), ((2346, 2361), 'keras.backend.get_session', 'K.get_session', ([], {}), '()\n', (2359, 2361), True, 'import keras.backend as K\n'), ((2773, 2788), 'keras.backend.get_session', 'K.get_session', ([], {}), '()\n', (2786, 2788), True, 'import keras.backend as K\n'), ((4127, 4143), 'tensorflow.shape', 'tf.shape', (['y_true'], {}), '(y_true)\n', (4135, 4143), True, 'import tensorflow as tf\n'), ((4148, 4164), 'tensorflow.shape', 'tf.shape', (['y_pred'], {}), '(y_pred)\n', (4156, 4164), True, 'import tensorflow as tf\n')]
""" Programmer: <NAME> Purpose: To provide functions to help create illustrative figures """ import numpy as np import matplotlib.pyplot as plt from persim import plot_diagrams from MergeTree import * def loadSVGPaths(filename = "paths.svg"): """ Given an SVG file, find all of the paths and load them into a dictionary of svg.path objects :param filename: Path to svg file :returns Paths: A dictionary of svg path objects indexed by ID specified in the svg file """ from svg.path import parse_path import xml.etree.ElementTree as ET tree = ET.parse(filename) root = tree.getroot() Paths = {} for c in root.getchildren(): if c.tag == '{http://www.w3.org/2000/svg}g': for elem in c.getchildren(): if elem.tag == '{http://www.w3.org/2000/svg}path': Paths[elem.attrib['id']] = parse_path(elem.attrib['d']) return Paths def paramSVGPath(P, t): """ Parameterize an SVG path and return it as a numpy array :param P: The SVG path object :param t: N values between [0, 1] for parameterizing path :returns X: An Nx2 array of path points """ N = t.size X = np.zeros((N, 2)) for i in range(N): res = P.point(t[i]) X[i, 0] = res.real X[i, 1] = res.imag return X def makeMergeTreeConceptFigure(): import scipy.interpolate as interp path = loadSVGPaths("curve.svg") path = path[list(path.keys())[0]] N = 40 x = paramSVGPath(path, np.linspace(0, 1, N)) x[:, 1] *= -1 x -= np.min(x, axis=0)[None, :] x[:, 1] /= np.max(x[:, 1]) x[:, 1] += 0.2 (MT, PS, I) = mergeTreeFrom1DTimeSeries(x[:, 1]) critidx = [k for k in MT.keys()] for k in MT.keys(): critidx += MT[k] critidx = np.unique(np.array(critidx)) T = wrapMergeTreeTimeSeries(MT, PS, x) T.render(offset=np.array([0, 0])) plt.plot(x[:, 0], x[:, 1]) plt.scatter(x[:, 0], x[:, 1]) plt.plot(x[:, 0], 0*x[:, 0]) plt.scatter(x[:, 0], 0*x[:, 0]) labels = [chr(ord('a')+i) for i in range(len(critidx))] plt.xticks(x[critidx, 0], labels) plt.yticks(x[critidx, 1], ['f(%s)'%a for a in labels]) plt.grid(linewidth=2, linestyle='--') plt.show() if __name__ == '__main__': makeMergeTreeConceptFigure()
[ "xml.etree.ElementTree.parse", "matplotlib.pyplot.show", "matplotlib.pyplot.plot", "matplotlib.pyplot.scatter", "matplotlib.pyplot.yticks", "numpy.zeros", "numpy.max", "numpy.min", "numpy.array", "numpy.linspace", "svg.path.parse_path", "matplotlib.pyplot.xticks", "matplotlib.pyplot.grid" ]
[((586, 604), 'xml.etree.ElementTree.parse', 'ET.parse', (['filename'], {}), '(filename)\n', (594, 604), True, 'import xml.etree.ElementTree as ET\n'), ((1197, 1213), 'numpy.zeros', 'np.zeros', (['(N, 2)'], {}), '((N, 2))\n', (1205, 1213), True, 'import numpy as np\n'), ((1610, 1625), 'numpy.max', 'np.max', (['x[:, 1]'], {}), '(x[:, 1])\n', (1616, 1625), True, 'import numpy as np\n'), ((1916, 1942), 'matplotlib.pyplot.plot', 'plt.plot', (['x[:, 0]', 'x[:, 1]'], {}), '(x[:, 0], x[:, 1])\n', (1924, 1942), True, 'import matplotlib.pyplot as plt\n'), ((1947, 1976), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x[:, 0]', 'x[:, 1]'], {}), '(x[:, 0], x[:, 1])\n', (1958, 1976), True, 'import matplotlib.pyplot as plt\n'), ((1981, 2011), 'matplotlib.pyplot.plot', 'plt.plot', (['x[:, 0]', '(0 * x[:, 0])'], {}), '(x[:, 0], 0 * x[:, 0])\n', (1989, 2011), True, 'import matplotlib.pyplot as plt\n'), ((2014, 2047), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x[:, 0]', '(0 * x[:, 0])'], {}), '(x[:, 0], 0 * x[:, 0])\n', (2025, 2047), True, 'import matplotlib.pyplot as plt\n'), ((2111, 2144), 'matplotlib.pyplot.xticks', 'plt.xticks', (['x[critidx, 0]', 'labels'], {}), '(x[critidx, 0], labels)\n', (2121, 2144), True, 'import matplotlib.pyplot as plt\n'), ((2149, 2207), 'matplotlib.pyplot.yticks', 'plt.yticks', (['x[critidx, 1]', "[('f(%s)' % a) for a in labels]"], {}), "(x[critidx, 1], [('f(%s)' % a) for a in labels])\n", (2159, 2207), True, 'import matplotlib.pyplot as plt\n'), ((2208, 2245), 'matplotlib.pyplot.grid', 'plt.grid', ([], {'linewidth': '(2)', 'linestyle': '"""--"""'}), "(linewidth=2, linestyle='--')\n", (2216, 2245), True, 'import matplotlib.pyplot as plt\n'), ((2251, 2261), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2259, 2261), True, 'import matplotlib.pyplot as plt\n'), ((1519, 1539), 'numpy.linspace', 'np.linspace', (['(0)', '(1)', 'N'], {}), '(0, 1, N)\n', (1530, 1539), True, 'import numpy as np\n'), ((1568, 1585), 'numpy.min', 'np.min', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (1574, 1585), True, 'import numpy as np\n'), ((1810, 1827), 'numpy.array', 'np.array', (['critidx'], {}), '(critidx)\n', (1818, 1827), True, 'import numpy as np\n'), ((1894, 1910), 'numpy.array', 'np.array', (['[0, 0]'], {}), '([0, 0])\n', (1902, 1910), True, 'import numpy as np\n'), ((887, 915), 'svg.path.parse_path', 'parse_path', (["elem.attrib['d']"], {}), "(elem.attrib['d'])\n", (897, 915), False, 'from svg.path import parse_path\n')]
from __future__ import print_function import numpy as np import matplotlib.pyplot as plt import xarray as xr import cartopy.crs as ccrs import cartopy.feature as cfeature import cartopy.io.shapereader as shapereader import seaborn as sns import shapely.geometry as sgeom from shapely.geometry import Point from datetime import datetime,timedelta from matplotlib.colors import ListedColormap from matplotlib.lines import Line2D as Line from matplotlib import cm from matplotlib.backends.backend_pdf import PdfPages from tkinter import * import re # import from mod_tctrack (change to util?) #from mod_tctrack import tc_plot import mod_tctrack as mtrack # import from local from mod_util import plot_legend, plot_features # Don't display FutureWarnings import sys if not sys.warnoptions: import warnings warnings.simplefilter("ignore") def plot_master(data_struct,plot_dict,plot_vars,operators,minmax): # Open a pdf to plot to with PdfPages(plot_dict['fig_name']+'.pdf') as pdf: # PLOT 2D MAP if plot_dict['plot_type']=="2dmap": # Plot each forecast step into its own pdf page for fcstep in plot_dict['fcsteps']: # Call plotting plot_data(fcstep,data_struct,plot_dict,plot_vars,minmax) # Save the plot to the pdf and open a new pdf page pdf.savefig() plt.close() # PLOT 2D MAP WITH MULTIPLE VARIABLES if plot_dict['plot_type']=="mvar": # Plot each forecast step into its own pdf page for fcstep in plot_dict['fcsteps']: # Call plotting plot_mvar(fcstep,data_struct,plot_dict,plot_vars,minmax) # Save the plot to the pdf and open a new pdf page pdf.savefig() plt.close() # PLOT TC TRACK elif plot_dict['plot_type']=="track": # Call plotting mtrack.plot_tctracks_and_pmin(data_struct,plot_dict,plot_vars) # Save the plot to the pdf and open a new pdf page pdf.savefig() plt.close() # PLOT SCORES elif plot_dict['plot_type']=="score": # If CRPS divide CRPS and fair-CRPS plots if plot_dict['crps']: data1=[] data2=[] #if for data in data_struct: print(data.name) # Construct a wildcard for crps and fair regex_crps=re.compile("crps_N.") regex_fair=re.compile("fair_N..") if re.match(regex_crps,data.name): data1.append(data) elif re.match(regex_fair,data.name): data2.append(data) # Or check for exact matches if data.name == 'crps': data1.append(data) elif data.name == 'fair': data2.append(data) elif data.name == 'rmse': data1.append(data) elif data.name == 'spread': data2.append(data) elif plot_dict['crps_detailed']: data1=data_struct data2=[] else: data1= data_struct[0] data2=[] nvars=4 dataX=data1 dataY=data2 for ivar in range(0,nvars): data1=dataX[ivar:len(dataX)+1:nvars] data2=dataY[ivar:len(dataX)+1:nvars] print(len(data1),len(data2)) # Call plotting plot_scores3(plot_dict['fcsteps'],data1,plot_dict,plot_vars,minmax) # Save the plot to the pdf and open a new pdf page pdf.savefig() plt.close() if data2: # Call plotting plot_scores3(plot_dict['fcsteps'],data2,plot_dict,plot_vars,minmax) # Save the plot to the pdf and open a new pdf page pdf.savefig() plt.close() # Plot date by date comparison of CPRS and FAIR elif plot_dict['plot_type']=="detail_comparison": data_crps=[] data_fair=[] for data in data_struct: data_crps.append(data[0]) data_fair.append(data[1]) plot_date_comparison(data_crps,data_fair,plot_dict,operators,plot_vars) # Save the plot to the pdf and open a new pdf page pdf.savefig() plt.close() # PLOT SCORES elif plot_dict['plot_type']=="score_rmse": data1=[] data2=[] for data in data_struct: print(data.name) # Or check for exact matches if data.name == 'rmse': data1.append(data) elif data.name == 'spread': data2.append(data) nvars=4 dataX=data1 dataY=data2 for ivar in range(0,nvars): data1=dataX[ivar:len(dataX)+1:nvars] data2=dataY[ivar:len(dataX)+1:nvars] # Call plotting plot_scores4(plot_dict['fcsteps'],data1,data2,plot_dict,plot_vars,minmax) # Save the plot to the pdf and open a new pdf page pdf.savefig() plt.close() elif plot_dict['plot_type']=="fair_exps": data1=[] for data in data_struct: # Construct a wildcard for crps and fair if plot_dict['crps']: regex_fair=re.compile("crps_N"+plot_dict['fair_count'][0]+"_..") else: regex_fair=re.compile("fair_N"+plot_dict['fair_count'][0]+"_..") if re.match(regex_fair,data.name): data1.append(data) nvars=4 dataX=data1 for ivar in range(0,nvars): data1=dataX[ivar:len(dataX)+1:nvars] for data in data1: print(data.name) plot_scores3(plot_dict['fcsteps'],data1,plot_dict,plot_vars,minmax) # Save the plot to the pdf and open a new pdf page pdf.savefig() plt.close() elif plot_dict['plot_type']=="score_diff": plot_score_comparison_detailed(data_struct,plot_dict,operators,plot_vars) # Save the plot to the pdf and open a new pdf page pdf.savefig() plt.close() elif plot_dict['plot_type']=="score_diff_avg": plot_score_comparison(data_struct,plot_dict,operators,plot_vars) # Save the plot to the pdf and open a new pdf page pdf.savefig() plt.close() def plot_data(itime,data_struct,plot_dict,plot_vars,minmax): "Plot 2D projections" # Generate color maps for data cmaps=col_maps_data(data_struct,plot_dict,plot_vars) # Create a figure fig,ax=create_figure(data_struct,plot_dict) # Loop over requested fields for idata in range(0,len(data_struct)): # Call plotting code layer call_plot(ax[idata],data_struct[idata],options=[itime],cmap=cmaps[idata],minmax=minmax[idata]) # Plot additional requested things call_plot_add(ax[idata],plot_dict) def plot_mvar(itime,data_struct,plot_dict,plot_vars,minmax): "Plot 2D projections" # Generate color maps for data cmaps=col_maps_data(data_struct,plot_dict,plot_vars) ccont1=[plot_dict['fig_c_col'],plot_dict['fig_c_levs']] ccont2=[cmaps[1] ,plot_dict['fig_cf_levs']] ccont3=[cmaps[0] ,plot_dict['fig_cf_levs']] # Enlarge fontsizes plt.rc('font', size=13) plt.rc('axes', labelsize=15) plt.rc('xtick',labelsize=15) plt.rc('ytick',labelsize=15) # Create a figure fig,ax=create_figure(data_struct,plot_dict) mim1=minmax[0][0] #min(minmax[0][0],minmax[2][0]) #,minmax[4][0]) mam1=minmax[0][1] #max(minmax[0][1],minmax[2][1]) #,minmax[4][1]) mim2=minmax[1][0] #min(minmax[1][0],minmax[3][0]) #,minmax[5][0]) mam2=minmax[1][1] #max(minmax[1][1],minmax[3][1]) #,minmax[5][1]) # Call plotting code layer call_plot(ax[0],data_struct[0],options=[itime],cmap=ccont1, minmax=[mim1,mam1],plottype='contour') call_plot(ax[0],data_struct[1],options=[itime],cmap=ccont2, minmax=[mim2,mam2]) # MOD FOR WIND BARBS #call_plot(ax[0],data_struct[0],options=[itime],cmap=ccont3, minmax=[mim1,mam1]) #call_plot(ax[0],data_struct[1],data2=data_struct[2],options=[itime],cmap=ccont2,minmax=[mim2,mam2],plottype='winds') #call_plot(ax[1],data_struct[2],options=[itime],cmap=ccont1, minmax=[mim1,mam1],plottype='contour') #call_plot(ax[1],data_struct[3],options=[itime],cmap=ccont2, minmax=[mim2,mam2]) #call_plot(ax[2],data_struct[4],options=[itime],cmap=ccont1 ,minmax=[mim1,mam1],plottype='contour') #call_plot(ax[2],data_struct[5],options=[itime],cmap=ccont2, minmax=[mim2,mam2]) # Plot additional requested things call_plot_add(ax[0],plot_dict) #call_plot_add(ax[1],plot_dict) #call_plot_add(ax[2],plot_dict) # Remove border whitespace fig.tight_layout() def plot_scores_crps_vs_fair(time,data_struct,plot_dict,plot_vars,minmax): "Plot scores values as a function of forecast lead time" print() print("CREATING FIGURE") # Create a figure fig,ax=plt.subplots(nrows=5,ncols=2,figsize=plot_dict['fig_size']) # Fix the axis handle to be simply ax[0] ax=fix_ax(ax) plt.tight_layout() cols=['r','b'] styles=['-','--'] names=['N=8','N=10','N=12','N=20','N=50'] area='glob' time=[range(0,21),range(21,41)] for icol in [0,1]: for i in range(0,5): # Loop over data idata=0 for data in data_struct[i*2:(i+1)*2]: call_score(ax[i*2+icol],data,area,time[icol],cols[idata],styles[idata]) idata+=1 def plot_scores2(time,data_struct,plot_dict,plot_vars,minmax): "Plot scores values as a function of forecast lead time" print() print("CREATING FIGURE") areas=['nh','tr','sh'] time=[range(0,9),range(9,21),range(21,41)] time=[range(0,5),range(5,11),range(11,21)] ntime=len(time) # Create a figure fig,ax=plt.subplots(nrows=len(areas),ncols=ntime,figsize=plot_dict['fig_size']) # Fix the axis handle to be simply ax[0] ax=fix_ax(ax) #plt.tight_layout() cols=['r','b','g','violet','k'] styles=['-','--',':','-.','-'] # Loop over FC lead times for itime in range(0,ntime): # Loop over areas for iarea in range(0,len(areas)): # Loop over data idata=0 for data in data_struct[0:2]: call_score(ax[iarea*ntime+itime],data,areas[iarea],time[itime],cols[0],styles[idata]) idata+=1 idata=0 for data in data_struct[8:10]: call_score(ax[iarea*ntime+itime],data,areas[iarea],time[itime],cols[1],styles[idata]) idata+=1 #plot_legend(cols[0:5],["8","25","50"],bbox_loc=(0.3,1.,0,0)) def plot_scores3(time,data_struct,plot_dict,plot_vars,minmax): "Plot scores values as a function of forecast lead time" print() print("CREATING FIGURE") areas=plot_dict['areas'] try: plot_dict['time'] except KeyError: time=[range(0,41)] else: time= plot_dict['time'] ntime=len(time) # Enlarge fontsizes plt.rc('font', size=13) plt.rc('axes', labelsize=15) plt.rc('xtick',labelsize=15) plt.rc('ytick',labelsize=15) # Create a figure fig,ax=plt.subplots(nrows=len(areas),ncols=ntime,figsize=plot_dict['fig_size']) # Fix the axis handle to be simply ax[0] ax=fix_ax(ax) #plt.tight_layout() cols= plot_dict['cols'] styles=plot_dict['styles'] legend_cols= plot_dict['legend_cols'] legend_names=plot_dict['legend_names'] legend_styles=plot_dict['legend_styles'] #for data in data_struct: # print(data.name,data.time) # Loop over FC lengths for itime in range(0,ntime): # Loop over areas for iarea in range(0,len(areas)): # Loop over data idata=0 for data in data_struct: call_score(ax[iarea*ntime+itime],data,areas[iarea],time[itime],cols[idata],styles[idata]) idata+=1 # Loop over data #idata=0 #for data in data_struct[1]: # call_score(ax[iarea*ntime+itime],data,areas[iarea],time[itime],cols[idata],styles[idata+5]) # idata+=1 if itime==0 and iarea==0: #plot_legend(legend_cols,legend_names,legend_styles,bbox_loc=(-1.45,0.3,0.,0.)) plot_legend(legend_cols,legend_names,legend_styles,bbox_loc=(0.27,1.,0,0)) #plot_legend(legend_cols,legend_names,legend_styles,bbox_loc=(0.18,1.,0,0)) if 1==1: ax[iarea*ntime+itime].set_xticks([0,24,48,72,96,120,144,168,192,216,240]) ax[iarea*ntime+itime].set_xticklabels([0,24,48,72,96,120,144,168,192,216,240]) #ax[iarea*ntime+itime].set_ylim(0,0.75) # LABELS ax[iarea*ntime+itime].set_title("") if 1==1: ax[iarea*ntime+itime].set_xlabel("FORECAST LENGTH IN HOURS") ax[iarea*ntime+itime].set_ylabel("RMSE/SPREAD") ax[iarea*ntime+itime].set_ylabel("FAIR CPRS") #ax[iarea*ntime+itime].set_ylabel("CPRS") # YLIMS if 1==0: ax[iarea*ntime+itime].set_title(areas[iarea]) #if itime==ntime-1: if 1==0: if itime == 0: #ax[iarea*ntime+itime].set_ylim(0.2,0.9) #ax[iarea*ntime+itime].set_ylim(0.2,0.95) ax[iarea*ntime+itime].set_ylim(0.2,0.8) elif itime == 1: #ax[iarea*ntime+itime].set_ylim(0.85,1.55) #ax[iarea*ntime+itime].set_ylim(0.85,1.7) ax[iarea*ntime+itime].set_ylim(0.65,1.4) elif itime == 2: #ax[iarea*ntime+itime].set_ylim(1.5,2.4) #ax[iarea*ntime+itime].set_ylim(1.5,2.55) ax[iarea*ntime+itime].set_ylim(1.15,2.2) if 1==0: if iarea == 0: ax[iarea*ntime+itime].set_ylim(0.2,0.85) elif iarea == 2: ax[iarea*ntime+itime].set_ylim(0.85,1.55) elif iarea==1: ax[iarea*ntime+itime].set_ylim(1.55,2.4) # Remove border whitespace fig.tight_layout() def plot_scores4(time,data_struct,data_struct2,plot_dict,plot_vars,minmax): "Plot scores values as a function of forecast lead time" print() print("CREATING FIGURE") areas=plot_dict['areas'] try: plot_dict['time'] except KeyError: time=[range(0,41)] else: time= plot_dict['time'] ntime=len(time) print(ntime,time,time[0]) # Enlarge fontsizes plt.rc('font', size=13) plt.rc('axes', labelsize=15) plt.rc('xtick',labelsize=15) plt.rc('ytick',labelsize=15) # Create a figure #fig,ax=plt.subplots(nrows=len(areas),ncols=ntime,figsize=plot_dict['fig_size']) fig,ax=plt.subplots(nrows=ntime,ncols=len(areas),figsize=plot_dict['fig_size']) # Fix the axis handle to be simply ax[0] ax=fix_ax(ax) #plt.tight_layout() cols= plot_dict['cols'] styles=plot_dict['styles'] legend_cols= plot_dict['legend_cols'] legend_names=plot_dict['legend_names'] legend_styles=plot_dict['legend_styles'] #for data in data_struct: # print(data.name,data.time) # Loop over FC lengths for itime in range(0,ntime): # Loop over areas for iarea in range(0,len(areas)): print(itime,iarea) # Loop over data idata=0 for data in data_struct: call_score(ax[iarea*ntime+itime],data,areas[iarea],time[itime],cols[idata],styles[idata]) idata+=1 # Loop over data idata=0 for data in data_struct2: call_score(ax[iarea*ntime+itime],data,areas[iarea],time[itime],cols[idata],'--') idata+=1 # Loop over data #idata=0 #for data in data_struct[1]: # call_score(ax[iarea*ntime+itime],data,areas[iarea],time[itime],cols[idata],styles[idata+5]) # idata+=1 if itime==0 and iarea==0: #plot_legend(legend_cols,legend_names,legend_styles,bbox_loc=(0.3,1.,0,0)) plot_legend(legend_cols,legend_names,legend_styles,bbox_loc=(0.25,1.,0,0)) ax[iarea*ntime+itime].set_title(areas[iarea]) if 1==1: ax[iarea*ntime+itime].set_xticks([0,24,48,72,96,120,144,168,192,216,240]) ax[iarea*ntime+itime].set_xticklabels([0,24,48,72,96,120,144,168,192,216,240]) # LABELS ax[iarea*ntime+itime].set_title("") if 1==1: ax[iarea*ntime+itime].set_xlabel("FORECAST LENGTH IN HOURS") ax[iarea*ntime+itime].set_ylabel("RMSE/SPREAD") #ax[iarea*ntime+itime].set_ylabel("FAIR CRPS2") # YLIMS if 1==0: #if itime==ntime-1: if iarea == 0: ax[iarea*ntime+itime].set_ylim(0.5,3.0) elif iarea == 2: ax[iarea*ntime+itime].set_ylim(0.5,4.0) elif iarea==1: ax[iarea*ntime+itime].set_ylim(0.2,1.) # Remove border whitespace fig.tight_layout() def plot_score_comparison_detailed(data_struct,plot_dict,operators,plot_vars): # Create plots fig2,ax2=plt.subplots(5,2,figsize=(15,15)) # Create colors cmap=plt.get_cmap('Set1') # Setup all_varis=[] all_times=[] # Areas areas=[[-90,-20],[-20,20],[20,90]] sareas=['SH', 'TR', 'NH'] # Time ranges time_ranges=[[1,8],[8,16],[16,24],[24,32],[32,41]] # Construct variable name list variable_list=[] for var in plot_vars: variable_list.append(str(var['vars'][0])+str(var['nlevs'][0])) var_size=len(variable_list) # Construct ensemble sizes sizes=[] for oper in operators: sizes.append(len(oper[2])) # Calculate size of input data data_size=int(len(sizes)*var_size) # Calculate number of dates date_size=int(len(data_struct)/(data_size)) print("SIZES") print(len(data_struct),len(sizes),var_size,data_size,date_size) isize=0 for M in sizes: for idate in range(0,date_size): # Set intentation to plots for better distinguishing between variables xintent=-0.003 for ivar in range(0,var_size): index = ivar + idate*var_size + isize*var_size*date_size print(isize,idate,ivar,index) ############ dd=data_struct[index][0] ee=data_struct[index][1] #print(data_struct[ivar*len(sizes) + isize][0]) iarea=0 for jj in [0,2]: # Do NOT take areal mean yet DD=dd.sel(lat=slice(areas[jj][0],areas[jj][1])) EE=ee.sel(lat=slice(areas[jj][0],areas[jj][1])) # Do division on grid by grid basis FF=DD/EE # Plot against ens size as 1+1/M mval=1+1./M # Setup 1-1-line x=range(0,3) itime=0 for time in time_ranges: #GG=FF.mean(['lon','lat']) GG=FF.isel(time=slice(time[0],time[1])).mean(['lon','lat']) HH=GG.mean(['time']).values GG=GG.values xx=[mval+xintent for i in GG.flatten()] XX=[mval for i in GG.flatten()] xx2=[mval+xintent for i in HH.flatten()] ax2[itime][iarea].plot(x,x,linestyle='-',color='gray',alpha=0.7) #ax2[itime][iarea].scatter(xx,GG.flatten(),color=cmap.colors[ivar],\ # alpha=0.6) ax2[itime][iarea].scatter(xx2,HH.flatten(),color=cmap.colors[ivar],\ alpha=0.6) ax2[itime][iarea].set_xlim(1,1.15) ax2[itime][iarea].set_ylim(1,1.24) # Display forecast window ax2[itime][iarea].set_ylabel(str(time[0]*6)+"-"+str(time[1]*6-6),fontsize=16) itime+=1 iarea+=1 xintent+=0.002 isize+=1 def plot_date_comparison(data_crps,data_fair,plot_dict,operators,plot_vars): fig3,ax3=plt.subplots(1,1) # FC-WINDOW length fclen=41 # Areas areas=[[-90,-20],[-20,20],[20,90]] sareas=['SH', 'TR', 'NH'] # Construct variable name list variable_list=[] for var in plot_vars: variable_list.append(str(var['vars'][0])+str(var['nlevs'][0])) var_size=len(variable_list) # Construct ensemble sizes sizes=[] for oper in operators: sizes.append(len(oper[2])) # Calculate size of input data data_size=int(len(sizes)*var_size) # Calculate number of dates date_size=int(len(data_crps)/(data_size)) print() print("SIZES") print(len(data_crps),len(sizes),var_size,data_size,date_size) # LOADED DATA ORDER # t639_eda+sv_2016120100_crps_N8_T4.nc # t639_eda+sv_2016120100_crps_N8_Z3.nc # ... # t639_eda+sv_2016120900_crps_N8_T4.nc # t639_eda+sv_2016120900_crps_N8_Z3.nc # ... # t639_eda+sv_2016120100_crps_N10_T4.nc # t639_eda+sv_2016120100_crps_N10_Z3.nc # ... # # Size of a single M-set is therefore date_size*var_size size_m=date_size*var_size index_m=[] index_mm=[] # CONSTRUCT M for x-axis for M in sizes: print(M) # index_m for idate in range(0,date_size): xintent=-0.0045 xintent=-0.009 for ivar in range(0,var_size): # include time xxint=-0.002 for itime in range(0,fclen): index_m.append(1+1./M+xintent+xxint) xxint+=0.0001 xintent+=0.003 xintent+=0.006 # index_mm xintent=-0.006 xintent=-0.009 index_var=[] for ivar in range(0,var_size): index_time=[] # include time xxint=-0.002 for itime in range(0,fclen): index_time.append(1+1./M+xintent+xxint) xxint+=0.0001 index_var.append(index_time) xintent+=0.004 xintent+=0.006 index_mm.append(index_var) #print(index_m) crps_avg=[] fair_avg=[] print(data_crps[0]) for ddata in data_crps: #crps_avg.append(ddata.sel(lat=slice(areas[0][0],areas[0][1])).mean(['lon','lat'])) crps_avg.append(ddata.isel(time=slice(0,42,1)).sel(lat=slice(areas[0][0],areas[0][1])).mean(['lon','lat'])) for ddata in data_fair: #fair_avg.append(ddata.sel(lat=slice(areas[0][0],areas[0][1])).mean(['lon','lat'])) fair_avg.append(ddata.isel(time=slice(0,42,1)).sel(lat=slice(areas[0][0],areas[0][1])).mean(['lon','lat'])) print(crps_avg[0]) #ratio_avg=[] #for idata in range(0,len(crps_avg)): # ratio_avg.append(crps_avg[idata]/fair_avg[idata]) #ax3.scatter(index_m,ratio_avg) # DATE MEAN crps_avg_dmean=[] fair_avg_dmean=[] index_date=0 ratio_fin=[] for isize in range(0,len(sizes)): ratio_vars=[] for ivar in range(0,var_size): index_dates=[] for idate in range(0,date_size): # INDEX for dates of same variable and M #print(isize,ivar,idate,isize*size_m+ivar+idate*var_size) index_dates.append(isize*size_m+ivar+idate*var_size) ratio_vars.append(np.mean([crps_avg[i]/fair_avg[i] for i in index_dates],axis=0)) ratio_fin.append(ratio_vars) print(index_dates) print(ratio_vars) #AA=[] #for i in index_dates: # AA.append(crps_avg[i]) #BB=np.mean(AA,axis=0) ratio_avg=[] for idata in range(0,len(crps_avg)): ratio_avg.append(crps_avg[idata]/fair_avg[idata]) #print(ratio_avg) print(len(ratio_avg),len(index_m)) ax3.scatter(index_m,ratio_avg,color='gray') print(len(ratio_fin[0])) print(ratio_fin[0]) print(index_mm[0]) # Colormap colmap=[] for i in range(0,var_size): colmap.append(cm.get_cmap('PuOr', fclen)) colmap=cm.get_cmap('PuOr', fclen) #print(colmap.shape) #print(np.squeeze(colmap).shape) for i in range(0,len(sizes)): for j in range(0,var_size): ax3.scatter(index_mm[i][j],ratio_fin[i][j],color=colmap(range(fclen)),alpha=0.7) # Setup 1-1-line x=range(0,3) ax3.plot(x,x,linestyle='-',color='gray',alpha=0.7) #ax3.set_xlim(1,1.15) #ax3.set_ylim(1,1.24) ax3.set_xlim(1.02,1.08) ax3.set_ylim(1,1.15) def plot_score_comparison(data_struct,plot_dict,operators,plot_vars): fig3,ax3=plt.subplots(1,2) # Areas areas=[[-90,-20],[-20,20],[20,90]] sareas=['SH', 'TR', 'NH'] # Cols cols=['c','r','b','g'] x=range(1,4) xmval=[1.,1+1./3.,1+1./2.] xmval=[1.,1+1./3.**2,1+1./2.**2] xmval=[1.,1+1./3*2.,1+1./2.*2] xxx=[1.0,1.5] yyy=[1.0,1.35] print(x,xmval) for data in data_struct: print(data.name) iarea=0 for jj in [0,2]: ioper=0 for M in [8,10,12,20,50]: # Plot against ens size as 1+1/M mval=1+1./M allFields=[] xint=-0.005 for ivar in range(0,len(plot_vars)): ############ print(jj,M,ivar,ioper*len(plot_vars),ivar+ioper*(len(plot_vars)+4)) print(jj,M,ivar,ioper*len(plot_vars),4+ivar+ioper*(len(plot_vars)+4)) dd=data_struct[0+ivar + ioper*(len(plot_vars)+4)] ee=data_struct[4+ivar + ioper*(len(plot_vars)+4)] # Average #DD=dd.sel(lat=slice(areas[jj][0],areas[jj][1])).mean(['lon','lat']) DD=dd.sel(lat=slice(areas[0][0],areas[0][1])).mean(['lon','lat']) EE=ee.sel(lat=slice(areas[0][0],areas[0][1])).mean(['lon','lat']) #print(ee.coords) ##EE=ee.mean(['lon','lat']) #EE=EE+ee.sel(lat=slice(areas[2][0],areas[2][1])).mean(['lon','lat']) # Do division on grid by grid basis FF=DD/EE #FF=FF.isel(time=slice(0,10)) allFields.append(FF) #xx=[mval for i in allFields[0]] xx=[mval+xint for i in FF.values] ax3[iarea].scatter(xx,FF.values,color=cols[ivar],\ alpha=0.25) xint+=0.0025 ax3[iarea].plot(x,x,linestyle='-',color='gray',alpha=0.7) ax3[iarea].plot(x,xmval,linestyle='--',color='gray',alpha=0.7) #ax3[iarea].scatter(xx,allFields[0],color='k',\ # alpha=0.6) ioper+=1 ax3[iarea].set_xlim(1,1.2) ax3[iarea].set_ylim(1,1.2) # Add titles for some plots ax3[iarea].set_title(sareas[jj]) # Remove ticks from all but bottom #if itime < len(ax2)-1: # ax3[iarea].tick_params(labelbottom=False) # Remove ticks from all but lefthandside figs #if iarea > 0: # ax3[iarea].tick_params(labelleft=False) iarea+=1 def call_score(ax,data,area,time,col,style): # Cut time if needed data=data.isel(time=time) # Check are latitudes rolling from North to South or other way sign=(data.coords['lat'].values[0]-data.coords['lat'].values[1]) # Do latitudal slicing of data if requested if area=='global': True elif area=='tr': data=data.sel(lat=slice(sign*20,-20*sign)) elif area=='nh': if sign==-1: lat1=20 lat2=80 else: lat1=80 lat2=20 data=data.sel(lat=slice(lat1,lat2)) elif area=='sh': if sign==-1: lat1=-80 lat2=-20 else: lat1=-20 lat2=-80 data=data.sel(lat=slice(lat1,lat2)) # Take the areal mean dd=data.mean(['lon','lat']) xr.plot.line(dd,ax=ax,color=col,linestyle=style,linewidth=2.5) def call_plot_add(ax,plot_dict): "Plot in additional features to the figure" # Plot Damrey track if plot_dict['fig_obs_track']: mtrack.tc_plot(ax,plot_dict['fig_obs_file'],plot_dict['fig_obs_col'],buff=plot_dict['fig_obs_buff'],fig_markers=plot_dict['fig_markers']) # Plot map features if plot_dict['fig_features']: plot_features(ax,country=True,lam=True,lonlat=plot_dict['lonlat']) # Plot labels if requested if plot_dict['fig_title']: ax.set_title(plot_dict['fig_title']) if plot_dict['fig_ylabel']: set_labels(ax,plot_dict['fig_ylabel']) if plot_dict['fig_xlabel']: set_labels(ax,plot_dict['fig_xlabel'],xory='x') def create_figure(data_struct,plot_dict): "Create figure and return figure and axis handles" # Single axis handle if (plot_dict['fig_ncol']==1 and plot_dict['fig_nrow']==1): # Create a figure fig,ax=plt.subplots(nrows=1,squeeze=0,figsize=plot_dict['fig_size'],\ subplot_kw={'projection': plot_dict['fig_proj']}) # Multiple axis handles else: # Create a figure fig,ax=plt.subplots(nrows=plot_dict['fig_nrow'],ncols=plot_dict['fig_ncol'],\ figsize=plot_dict['fig_size'],\ subplot_kw={'projection': plot_dict['fig_proj']}) # Fix the axis handle to be simply ax[0] ax=fix_ax(ax) return fig,ax def fix_ax(ax): "Correct the axis handle when opening a single subplot" try: ax[0][1] except IndexError: pass except TypeError: pass else: ax_tmp=[] for irow in range(0,len(ax)): for icol in range(0,len(ax[0])): ax_tmp.append(ax[irow][icol]) return ax_tmp try: ax[0][0] except TypeError: pass else: return ax[0] try: ax[0] except TypeError: ax_tmp=[] ax_tmp.append(ax) ax=ax_tmp return ax else: return ax def call_plot(ax,data,\ data2=xr.DataArray(data=None),\ data3=xr.DataArray(data=None),\ data4=xr.DataArray(data=None),\ plottype='contourf',options=[],\ cmap=[],minmax=[],contf=True): "Code layer for plotting" # Create an empty data structure # (multiple input data sources can be used to calculate # differences, RMSEs, etc. between the datasets) d=[xr.DataArray(data=None),xr.DataArray(data=None),\ xr.DataArray(data=None),xr.DataArray(data=None)] # Choose a timeinstance and level setting from the data #if get_varname(data)=='TP': # Precipitation is cumulative, get the diff of the last fcsteps # d[0]=data.isel(time=options[0])-data.isel(time=options[0]-1) #else: d[0]=data.isel(time=options[0]) # Get data information #dtime=d[0]['time'] # Select additional data according to first data set if data2.notnull().any(): d[1]=data2.isel(time=options[0]) if data3.notnull(): d[2]=data3.sel(time=dtime) if data4.notnull(): d[3]=data4.sel(time=dtime) # Contourf. if plottype=="contourf": contourf_cartopy(ax,d[0],minmax[0],minmax[1],cmap=cmap) if plottype=="contour": contour_cartopy(ax, d[0],minmax[0],minmax[1],cmap=cmap) if plottype=="winds": barb_cartopy(ax,d[0],d[1],minmax[0],minmax[1],cmap=cmap) def calc_stats(an,data): "Calculate global/regional statistics from the given data" # GLOBAL NON-WEIGHTED RMSE rmse=np.sqrt(((an-data)**2).mean()).values #print(np.linalg.norm(an-data)/np.sqrt(160*320)) return rmse def contourf_cartopy(ax,data,fmin,fmax,cmap): "Generate a 2D map with cartopy" # Cubehelix cmaps are missing len, set it manually try: len(cmap) except TypeError: ncolors=10 else: ncolors=len(cmap)-1 # mvar specific settings for ens spread if len(cmap)==2: ncolors=cmap[1] cmap=cmap[0] # Determine contour intervals if not fmin==[]: conts=np.arange(fmin,fmax,(fmax-fmin)/ncolors) else: fmin=data.min().values fmax=data.max().values conts=np.arange(fmin,fmax,(fmax-fmin)/ncolors) #conts=[998.,1000.,1002.,1004.,1006.,1008.,1010.,1012.,1014.,1016.,1018.] #conts=[0.,0.4,0.6,0.8,1.,1.2,1.4,1.6,1.8,2.,2.2] #conts=[0.,0.5,0.75,1.,1.25,1.5,1.75,2.,2.25,2.5,2.75] # Plot xr.plot.contourf(data, ax=ax, transform=ccrs.PlateCarree(), \ colors=cmap, levels=conts, extend='both') #colors=cmap, levels=conts, extend='min',cbar_kwargs=dict(label="MSLP")) #colors=cmap, levels=conts, extend='max',cbar_kwargs=dict(label="SDEV(MSLP)")) def contour_cartopy(ax,data,fmin,fmax,cmap): "Generate a 2D map with cartopy" ccol=cmap[0] clen=cmap[1] # Determine contour intervals if not fmin==[]: conts=np.arange(fmin,fmax,(fmax-fmin)/clen) else: fmin=data.min().values fmax=data.max().values conts=np.arange(fmin,fmax,(fmax-fmin)/clen) # Plot cs=xr.plot.contour(data, ax=ax, transform=ccrs.PlateCarree(), \ levels=conts,colors=ccol,alpha=0.65) ax.clabel(cs,fmt= '%1.0f',fontsize=14) def barb_cartopy(ax,data,data2,fmin,fmax,cmap): "Generate wind barbs with cartopy" ccol=cmap[0] clen=cmap[1] # Determine contour intervals if not fmin==[]: conts=np.arange(fmin,fmax,(fmax-fmin)/clen) else: fmin=data.min().values fmax=data.max().values conts=np.arange(fmin,fmax,(fmax-fmin)/clen) lats=data.lat.data lons=data.lon.data wind_slice = slice(3, -3, 3) # Plot ax.barbs(lons[wind_slice],lats[wind_slice],data[wind_slice,wind_slice],data2[wind_slice,wind_slice], \ transform=ccrs.PlateCarree(),color='b',length=7) #ax.clabel(cs,fmt= '%1.0f',fontsize=14) def set_labels(ax,xlabels,xory='y'): "Iterate over axis and set labels, need to create a text object for cartopy" try: len(ax) except TypeError: ax=[ax] xlabels=[xlabels] i=0 for axis in ax: if xory=='y': axis.text(-0.07, 0.55, xlabels[i], va='bottom', ha='center', rotation='vertical', rotation_mode='anchor', transform=axis.transAxes, fontsize=16) else: axis.text(0.47, -0.2, xlabels[i], va='bottom', ha='center', rotation='horizontal', rotation_mode='anchor', transform=axis.transAxes, fontsize=16) i+=1 def get_varname(data): " Find which variable is requested from the data \ (this is a bit awkward, since xarray is refusing to give \ the variable name out in taito-setup...)" if 'MSL' in str(data): vname='MSL' elif 'TP' in str(data): vname='TP' elif 'T2M' in str(data): vname='T2M' elif 'D2M' in str(data): vname='D2M' elif 'TCC' in str(data): vname='TCC' elif 'VO' in str(data): vname='VO' elif 'U10M' in str(data): vname='U10M' elif 'V10M' in str(data): vname='V10M' elif 'W10M' in str(data): vname='W10M' elif 'U' in str(data): vname='U' elif 'V' in str(data): vname='V' elif 'Q' in str(data): vname='Q' elif 'Z' in str(data): vname='Z' elif 'D' in str(data): vname='D' elif 'T' in str(data): vname='T' else: vname='T' # Probably working now, remove the above later on vname=data.name return vname def col_maps_data(data_struct,plot_dict,plot_vars=[]): "Set colormaps for each variable [physical units, standard deviation]" cmaps=[] clevs=plot_dict['fig_cf_levs'] idata=0 for data in data_struct: icol=0 if plot_vars: if plot_vars[idata]['ens']=='ensstd': icol=1 # TEMP SOLUTION FOR SCORES #icol=1 cmap=col_maps(get_varname(data),clevs)[icol] cmaps.append(cmap) idata+=1 return cmaps def col_maps(var,clevs): "Set colormaps for each variable [physical units, standard deviation]" if var=='MSL': cmap=[sns.color_palette("BrBG_r",clevs),sns.cubehelix_palette(n_colors=clevs,start=2.7, light=1, as_cmap=True)] elif var=='Z': cmap=[sns.color_palette("BrBG_r",clevs),sns.cubehelix_palette(start=2.7, light=1, as_cmap=True, n_colors=clevs)] elif var=='T': cmap=[sns.color_palette("RdBu_r",clevs),sns.cubehelix_palette(start=2.4, light=1, as_cmap=True, n_colors=clevs)] elif var=='Q': cmap=[sns.color_palette("PuBu",clevs),sns.cubehelix_palette(start=3.0, light=1, as_cmap=True, n_colors=clevs)] elif var=='U' or var=='V': cmap=[sns.color_palette("OrRd",clevs),sns.cubehelix_palette(start=2.7, light=1, as_cmap=True, n_colors=clevs)] elif var=='W10M': cmap=[sns.color_palette("cool",clevs),sns.cubehelix_palette(start=2.7, light=1, as_cmap=True, n_colors=clevs)] elif var=='TP': cmap=[sns.color_palette("viridis",clevs-10),sns.cubehelix_palette(start=2.7, light=1, as_cmap=True, n_colors=clevs)] elif var=='TESTI': cmap=[sns.color_palette("winter",clevs),sns.cubehelix_palette(start=2.7, light=1, as_cmap=True, n_colors=clevs)] elif var=='MYVARIABLE': cmap=[sns.color_palette("winter",clevs),sns.cubehelix_palette(start=2.7, light=1, as_cmap=True, n_colors=clevs)] else: cmap=[sns.color_palette("RdBu_r",clevs),sns.cubehelix_palette(start=2.7, light=1, as_cmap=True, n_colors=clevs)] return cmap
[ "matplotlib.backends.backend_pdf.PdfPages", "matplotlib.cm.get_cmap", "numpy.mean", "numpy.arange", "matplotlib.pyplot.tight_layout", "warnings.simplefilter", "matplotlib.pyplot.close", "mod_tctrack.plot_tctracks_and_pmin", "seaborn.cubehelix_palette", "matplotlib.pyplot.rc", "xarray.plot.line",...
[((816, 847), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (837, 847), False, 'import warnings\n'), ((8060, 8083), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(13)'}), "('font', size=13)\n", (8066, 8083), True, 'import matplotlib.pyplot as plt\n'), ((8088, 8116), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'labelsize': '(15)'}), "('axes', labelsize=15)\n", (8094, 8116), True, 'import matplotlib.pyplot as plt\n'), ((8121, 8150), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': '(15)'}), "('xtick', labelsize=15)\n", (8127, 8150), True, 'import matplotlib.pyplot as plt\n'), ((8154, 8183), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': '(15)'}), "('ytick', labelsize=15)\n", (8160, 8183), True, 'import matplotlib.pyplot as plt\n'), ((9792, 9853), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(5)', 'ncols': '(2)', 'figsize': "plot_dict['fig_size']"}), "(nrows=5, ncols=2, figsize=plot_dict['fig_size'])\n", (9804, 9853), True, 'import matplotlib.pyplot as plt\n'), ((9920, 9938), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (9936, 9938), True, 'import matplotlib.pyplot as plt\n'), ((11918, 11941), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(13)'}), "('font', size=13)\n", (11924, 11941), True, 'import matplotlib.pyplot as plt\n'), ((11946, 11974), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'labelsize': '(15)'}), "('axes', labelsize=15)\n", (11952, 11974), True, 'import matplotlib.pyplot as plt\n'), ((11979, 12008), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': '(15)'}), "('xtick', labelsize=15)\n", (11985, 12008), True, 'import matplotlib.pyplot as plt\n'), ((12012, 12041), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': '(15)'}), "('ytick', labelsize=15)\n", (12018, 12041), True, 'import matplotlib.pyplot as plt\n'), ((15640, 15663), 'matplotlib.pyplot.rc', 'plt.rc', (['"""font"""'], {'size': '(13)'}), "('font', size=13)\n", (15646, 15663), True, 'import matplotlib.pyplot as plt\n'), ((15668, 15696), 'matplotlib.pyplot.rc', 'plt.rc', (['"""axes"""'], {'labelsize': '(15)'}), "('axes', labelsize=15)\n", (15674, 15696), True, 'import matplotlib.pyplot as plt\n'), ((15701, 15730), 'matplotlib.pyplot.rc', 'plt.rc', (['"""xtick"""'], {'labelsize': '(15)'}), "('xtick', labelsize=15)\n", (15707, 15730), True, 'import matplotlib.pyplot as plt\n'), ((15734, 15763), 'matplotlib.pyplot.rc', 'plt.rc', (['"""ytick"""'], {'labelsize': '(15)'}), "('ytick', labelsize=15)\n", (15740, 15763), True, 'import matplotlib.pyplot as plt\n'), ((18429, 18465), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(5)', '(2)'], {'figsize': '(15, 15)'}), '(5, 2, figsize=(15, 15))\n', (18441, 18465), True, 'import matplotlib.pyplot as plt\n'), ((18493, 18513), 'matplotlib.pyplot.get_cmap', 'plt.get_cmap', (['"""Set1"""'], {}), "('Set1')\n", (18505, 18513), True, 'import matplotlib.pyplot as plt\n'), ((21647, 21665), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {}), '(1, 1)\n', (21659, 21665), True, 'import matplotlib.pyplot as plt\n'), ((25688, 25714), 'matplotlib.cm.get_cmap', 'cm.get_cmap', (['"""PuOr"""', 'fclen'], {}), "('PuOr', fclen)\n", (25699, 25714), False, 'from matplotlib import cm\n'), ((26233, 26251), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {}), '(1, 2)\n', (26245, 26251), True, 'import matplotlib.pyplot as plt\n'), ((29663, 29729), 'xarray.plot.line', 'xr.plot.line', (['dd'], {'ax': 'ax', 'color': 'col', 'linestyle': 'style', 'linewidth': '(2.5)'}), '(dd, ax=ax, color=col, linestyle=style, linewidth=2.5)\n', (29675, 29729), True, 'import xarray as xr\n'), ((31827, 31850), 'xarray.DataArray', 'xr.DataArray', ([], {'data': 'None'}), '(data=None)\n', (31839, 31850), True, 'import xarray as xr\n'), ((31873, 31896), 'xarray.DataArray', 'xr.DataArray', ([], {'data': 'None'}), '(data=None)\n', (31885, 31896), True, 'import xarray as xr\n'), ((31919, 31942), 'xarray.DataArray', 'xr.DataArray', ([], {'data': 'None'}), '(data=None)\n', (31931, 31942), True, 'import xarray as xr\n'), ((955, 995), 'matplotlib.backends.backend_pdf.PdfPages', 'PdfPages', (["(plot_dict['fig_name'] + '.pdf')"], {}), "(plot_dict['fig_name'] + '.pdf')\n", (963, 995), False, 'from matplotlib.backends.backend_pdf import PdfPages\n'), ((29882, 30027), 'mod_tctrack.tc_plot', 'mtrack.tc_plot', (['ax', "plot_dict['fig_obs_file']", "plot_dict['fig_obs_col']"], {'buff': "plot_dict['fig_obs_buff']", 'fig_markers': "plot_dict['fig_markers']"}), "(ax, plot_dict['fig_obs_file'], plot_dict['fig_obs_col'],\n buff=plot_dict['fig_obs_buff'], fig_markers=plot_dict['fig_markers'])\n", (29896, 30027), True, 'import mod_tctrack as mtrack\n'), ((30087, 30156), 'mod_util.plot_features', 'plot_features', (['ax'], {'country': '(True)', 'lam': '(True)', 'lonlat': "plot_dict['lonlat']"}), "(ax, country=True, lam=True, lonlat=plot_dict['lonlat'])\n", (30100, 30156), False, 'from mod_util import plot_legend, plot_features\n'), ((30662, 30780), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(1)', 'squeeze': '(0)', 'figsize': "plot_dict['fig_size']", 'subplot_kw': "{'projection': plot_dict['fig_proj']}"}), "(nrows=1, squeeze=0, figsize=plot_dict['fig_size'], subplot_kw=\n {'projection': plot_dict['fig_proj']})\n", (30674, 30780), True, 'import matplotlib.pyplot as plt\n'), ((30884, 31044), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': "plot_dict['fig_nrow']", 'ncols': "plot_dict['fig_ncol']", 'figsize': "plot_dict['fig_size']", 'subplot_kw': "{'projection': plot_dict['fig_proj']}"}), "(nrows=plot_dict['fig_nrow'], ncols=plot_dict['fig_ncol'],\n figsize=plot_dict['fig_size'], subplot_kw={'projection': plot_dict[\n 'fig_proj']})\n", (30896, 31044), True, 'import matplotlib.pyplot as plt\n'), ((32225, 32248), 'xarray.DataArray', 'xr.DataArray', ([], {'data': 'None'}), '(data=None)\n', (32237, 32248), True, 'import xarray as xr\n'), ((32249, 32272), 'xarray.DataArray', 'xr.DataArray', ([], {'data': 'None'}), '(data=None)\n', (32261, 32272), True, 'import xarray as xr\n'), ((32282, 32305), 'xarray.DataArray', 'xr.DataArray', ([], {'data': 'None'}), '(data=None)\n', (32294, 32305), True, 'import xarray as xr\n'), ((32306, 32329), 'xarray.DataArray', 'xr.DataArray', ([], {'data': 'None'}), '(data=None)\n', (32318, 32329), True, 'import xarray as xr\n'), ((33894, 33940), 'numpy.arange', 'np.arange', (['fmin', 'fmax', '((fmax - fmin) / ncolors)'], {}), '(fmin, fmax, (fmax - fmin) / ncolors)\n', (33903, 33940), True, 'import numpy as np\n'), ((34021, 34067), 'numpy.arange', 'np.arange', (['fmin', 'fmax', '((fmax - fmin) / ncolors)'], {}), '(fmin, fmax, (fmax - fmin) / ncolors)\n', (34030, 34067), True, 'import numpy as np\n'), ((34791, 34834), 'numpy.arange', 'np.arange', (['fmin', 'fmax', '((fmax - fmin) / clen)'], {}), '(fmin, fmax, (fmax - fmin) / clen)\n', (34800, 34834), True, 'import numpy as np\n'), ((34915, 34958), 'numpy.arange', 'np.arange', (['fmin', 'fmax', '((fmax - fmin) / clen)'], {}), '(fmin, fmax, (fmax - fmin) / clen)\n', (34924, 34958), True, 'import numpy as np\n'), ((35342, 35385), 'numpy.arange', 'np.arange', (['fmin', 'fmax', '((fmax - fmin) / clen)'], {}), '(fmin, fmax, (fmax - fmin) / clen)\n', (35351, 35385), True, 'import numpy as np\n'), ((35466, 35509), 'numpy.arange', 'np.arange', (['fmin', 'fmax', '((fmax - fmin) / clen)'], {}), '(fmin, fmax, (fmax - fmin) / clen)\n', (35475, 35509), True, 'import numpy as np\n'), ((25648, 25674), 'matplotlib.cm.get_cmap', 'cm.get_cmap', (['"""PuOr"""', 'fclen'], {}), "('PuOr', fclen)\n", (25659, 25674), False, 'from matplotlib import cm\n'), ((34310, 34328), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (34326, 34328), True, 'import cartopy.crs as ccrs\n'), ((35011, 35029), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (35027, 35029), True, 'import cartopy.crs as ccrs\n'), ((35726, 35744), 'cartopy.crs.PlateCarree', 'ccrs.PlateCarree', ([], {}), '()\n', (35742, 35744), True, 'import cartopy.crs as ccrs\n'), ((38188, 38222), 'seaborn.color_palette', 'sns.color_palette', (['"""BrBG_r"""', 'clevs'], {}), "('BrBG_r', clevs)\n", (38205, 38222), True, 'import seaborn as sns\n'), ((38222, 38293), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', ([], {'n_colors': 'clevs', 'start': '(2.7)', 'light': '(1)', 'as_cmap': '(True)'}), '(n_colors=clevs, start=2.7, light=1, as_cmap=True)\n', (38243, 38293), True, 'import seaborn as sns\n'), ((1398, 1409), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1407, 1409), True, 'import matplotlib.pyplot as plt\n'), ((1830, 1841), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (1839, 1841), True, 'import matplotlib.pyplot as plt\n'), ((1955, 2019), 'mod_tctrack.plot_tctracks_and_pmin', 'mtrack.plot_tctracks_and_pmin', (['data_struct', 'plot_dict', 'plot_vars'], {}), '(data_struct, plot_dict, plot_vars)\n', (1984, 2019), True, 'import mod_tctrack as mtrack\n'), ((2120, 2131), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (2129, 2131), True, 'import matplotlib.pyplot as plt\n'), ((13227, 13313), 'mod_util.plot_legend', 'plot_legend', (['legend_cols', 'legend_names', 'legend_styles'], {'bbox_loc': '(0.27, 1.0, 0, 0)'}), '(legend_cols, legend_names, legend_styles, bbox_loc=(0.27, 1.0, \n 0, 0))\n', (13238, 13313), False, 'from mod_util import plot_legend, plot_features\n'), ((17273, 17359), 'mod_util.plot_legend', 'plot_legend', (['legend_cols', 'legend_names', 'legend_styles'], {'bbox_loc': '(0.25, 1.0, 0, 0)'}), '(legend_cols, legend_names, legend_styles, bbox_loc=(0.25, 1.0, \n 0, 0))\n', (17284, 17359), False, 'from mod_util import plot_legend, plot_features\n'), ((25011, 25078), 'numpy.mean', 'np.mean', (['[(crps_avg[i] / fair_avg[i]) for i in index_dates]'], {'axis': '(0)'}), '([(crps_avg[i] / fair_avg[i]) for i in index_dates], axis=0)\n', (25018, 25078), True, 'import numpy as np\n'), ((38328, 38362), 'seaborn.color_palette', 'sns.color_palette', (['"""BrBG_r"""', 'clevs'], {}), "('BrBG_r', clevs)\n", (38345, 38362), True, 'import seaborn as sns\n'), ((38362, 38433), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', ([], {'start': '(2.7)', 'light': '(1)', 'as_cmap': '(True)', 'n_colors': 'clevs'}), '(start=2.7, light=1, as_cmap=True, n_colors=clevs)\n', (38383, 38433), True, 'import seaborn as sns\n'), ((38468, 38502), 'seaborn.color_palette', 'sns.color_palette', (['"""RdBu_r"""', 'clevs'], {}), "('RdBu_r', clevs)\n", (38485, 38502), True, 'import seaborn as sns\n'), ((38502, 38573), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', ([], {'start': '(2.4)', 'light': '(1)', 'as_cmap': '(True)', 'n_colors': 'clevs'}), '(start=2.4, light=1, as_cmap=True, n_colors=clevs)\n', (38523, 38573), True, 'import seaborn as sns\n'), ((3914, 3925), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3923, 3925), True, 'import matplotlib.pyplot as plt\n'), ((4723, 4734), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4732, 4734), True, 'import matplotlib.pyplot as plt\n'), ((38608, 38640), 'seaborn.color_palette', 'sns.color_palette', (['"""PuBu"""', 'clevs'], {}), "('PuBu', clevs)\n", (38625, 38640), True, 'import seaborn as sns\n'), ((38640, 38711), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', ([], {'start': '(3.0)', 'light': '(1)', 'as_cmap': '(True)', 'n_colors': 'clevs'}), '(start=3.0, light=1, as_cmap=True, n_colors=clevs)\n', (38661, 38711), True, 'import seaborn as sns\n'), ((2552, 2573), 're.compile', 're.compile', (['"""crps_N."""'], {}), "('crps_N.')\n", (2562, 2573), False, 'import re\n'), ((2605, 2627), 're.compile', 're.compile', (['"""fair_N.."""'], {}), "('fair_N..')\n", (2615, 2627), False, 'import re\n'), ((2652, 2683), 're.match', 're.match', (['regex_crps', 'data.name'], {}), '(regex_crps, data.name)\n', (2660, 2683), False, 'import re\n'), ((4203, 4214), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4212, 4214), True, 'import matplotlib.pyplot as plt\n'), ((38758, 38790), 'seaborn.color_palette', 'sns.color_palette', (['"""OrRd"""', 'clevs'], {}), "('OrRd', clevs)\n", (38775, 38790), True, 'import seaborn as sns\n'), ((38790, 38861), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', ([], {'start': '(2.7)', 'light': '(1)', 'as_cmap': '(True)', 'n_colors': 'clevs'}), '(start=2.7, light=1, as_cmap=True, n_colors=clevs)\n', (38811, 38861), True, 'import seaborn as sns\n'), ((2752, 2783), 're.match', 're.match', (['regex_fair', 'data.name'], {}), '(regex_fair, data.name)\n', (2760, 2783), False, 'import re\n'), ((5605, 5616), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5614, 5616), True, 'import matplotlib.pyplot as plt\n'), ((38899, 38931), 'seaborn.color_palette', 'sns.color_palette', (['"""cool"""', 'clevs'], {}), "('cool', clevs)\n", (38916, 38931), True, 'import seaborn as sns\n'), ((38931, 39002), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', ([], {'start': '(2.7)', 'light': '(1)', 'as_cmap': '(True)', 'n_colors': 'clevs'}), '(start=2.7, light=1, as_cmap=True, n_colors=clevs)\n', (38952, 39002), True, 'import seaborn as sns\n'), ((6054, 6085), 're.match', 're.match', (['regex_fair', 'data.name'], {}), '(regex_fair, data.name)\n', (6062, 6085), False, 'import re\n'), ((6538, 6549), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6547, 6549), True, 'import matplotlib.pyplot as plt\n'), ((6816, 6827), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (6825, 6827), True, 'import matplotlib.pyplot as plt\n'), ((39038, 39078), 'seaborn.color_palette', 'sns.color_palette', (['"""viridis"""', '(clevs - 10)'], {}), "('viridis', clevs - 10)\n", (39055, 39078), True, 'import seaborn as sns\n'), ((39076, 39147), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', ([], {'start': '(2.7)', 'light': '(1)', 'as_cmap': '(True)', 'n_colors': 'clevs'}), '(start=2.7, light=1, as_cmap=True, n_colors=clevs)\n', (39097, 39147), True, 'import seaborn as sns\n'), ((5873, 5930), 're.compile', 're.compile', (["('crps_N' + plot_dict['fair_count'][0] + '_..')"], {}), "('crps_N' + plot_dict['fair_count'][0] + '_..')\n", (5883, 5930), False, 'import re\n'), ((5980, 6037), 're.compile', 're.compile', (["('fair_N' + plot_dict['fair_count'][0] + '_..')"], {}), "('fair_N' + plot_dict['fair_count'][0] + '_..')\n", (5990, 6037), False, 'import re\n'), ((7089, 7100), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (7098, 7100), True, 'import matplotlib.pyplot as plt\n'), ((39186, 39220), 'seaborn.color_palette', 'sns.color_palette', (['"""winter"""', 'clevs'], {}), "('winter', clevs)\n", (39203, 39220), True, 'import seaborn as sns\n'), ((39220, 39291), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', ([], {'start': '(2.7)', 'light': '(1)', 'as_cmap': '(True)', 'n_colors': 'clevs'}), '(start=2.7, light=1, as_cmap=True, n_colors=clevs)\n', (39241, 39291), True, 'import seaborn as sns\n'), ((39335, 39369), 'seaborn.color_palette', 'sns.color_palette', (['"""winter"""', 'clevs'], {}), "('winter', clevs)\n", (39352, 39369), True, 'import seaborn as sns\n'), ((39369, 39440), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', ([], {'start': '(2.7)', 'light': '(1)', 'as_cmap': '(True)', 'n_colors': 'clevs'}), '(start=2.7, light=1, as_cmap=True, n_colors=clevs)\n', (39390, 39440), True, 'import seaborn as sns\n'), ((39466, 39500), 'seaborn.color_palette', 'sns.color_palette', (['"""RdBu_r"""', 'clevs'], {}), "('RdBu_r', clevs)\n", (39483, 39500), True, 'import seaborn as sns\n'), ((39500, 39571), 'seaborn.cubehelix_palette', 'sns.cubehelix_palette', ([], {'start': '(2.7)', 'light': '(1)', 'as_cmap': '(True)', 'n_colors': 'clevs'}), '(start=2.7, light=1, as_cmap=True, n_colors=clevs)\n', (39521, 39571), True, 'import seaborn as sns\n')]
from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import numpy as np import scipy as sp import scipy.interpolate def loadTimeFile(fileName): timeList = [] verticesList = [] kList = [] with open(fileName) as file: line = file.readline() while line: s1, s2, s3 = line.split(' ') n = int(s1) k = int(s2) time = float(s3) verticesList.append(n) kList.append(k) timeList.append(time) line = file.readline() return verticesList, kList, timeList x,y,z = loadTimeFile('complexityExecTimes.txt') X, Y = np.meshgrid(x,y) fig = plt.figure() ax = Axes3D(fig) ax.scatter(x,y,z,c=z) #surf = ax.plot_trisurf(x, y, z, linewidth=0, antialiased=False) plt.show()
[ "matplotlib.pyplot.figure", "numpy.meshgrid", "matplotlib.pyplot.show", "mpl_toolkits.mplot3d.Axes3D" ]
[((684, 701), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (695, 701), True, 'import numpy as np\n'), ((709, 721), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (719, 721), True, 'from matplotlib import pyplot as plt\n'), ((727, 738), 'mpl_toolkits.mplot3d.Axes3D', 'Axes3D', (['fig'], {}), '(fig)\n', (733, 738), False, 'from mpl_toolkits.mplot3d import Axes3D\n'), ((829, 839), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (837, 839), True, 'from matplotlib import pyplot as plt\n')]