code
stringlengths
31
1.05M
apis
list
extract_api
stringlengths
97
1.91M
import torch from torch import nn import torch.nn.functional as F import numpy as np from mlpipe import Model import os class NeuralNet(nn.Module): def __init__(self): super(NeuralNet, self).__init__() self.tdata_model = nn.Sequential( nn.Conv1d(1, 16, kernel_size=16), nn.ReLU(), nn.Conv1d(16, 16, kernel_size=16), nn.ReLU(), nn.MaxPool1d(kernel_size=16, stride=3), nn.Conv1d(16, 32, kernel_size=16), nn.ReLU(), nn.Conv1d(32, 32, kernel_size=16), nn.ReLU(), nn.MaxPool1d(kernel_size=16, stride=3), nn.Conv1d(32, 64, kernel_size=16), nn.ReLU(), nn.Conv1d(64, 64, kernel_size=16), nn.ReLU(), nn.MaxPool1d(kernel_size=16, stride=3), ) self.fdata_model = nn.Sequential( nn.Conv1d(1, 16, kernel_size=16), nn.ReLU(), nn.Conv1d(16, 16, kernel_size=16), nn.ReLU(), nn.MaxPool1d(kernel_size=16, stride=3), nn.Conv1d(16, 32, kernel_size=16), nn.ReLU(), nn.Conv1d(32, 32, kernel_size=16), nn.ReLU(), nn.MaxPool1d(kernel_size=16, stride=3), nn.Conv1d(32, 64, kernel_size=16), nn.ReLU(), nn.Conv1d(64, 64, kernel_size=16), nn.ReLU(), nn.MaxPool1d(kernel_size=16, stride=3), ) self.fc = nn.Sequential( nn.Linear(16*16*2+10, 256), nn.ReLU(), nn.Linear(256, 2), ) def forward(self, tdata, fdata, features): tout = self.tdata_model(tdata) fout = self.fdata_model(fdata) # contract the channel dimensions tout = torch.matmul(tout.transpose(1,2), tout) fout = torch.matmul(fout.transpose(1,2), fout) # flatten the output tout = tout.reshape(tout.size(0), -1) fout = fout.reshape(fout.size(0), -1) # concat results from time, freq and engineered features out = torch.cat((tout,fout,features), dim=1) out = self.fc(out) return out class CNNModel(Model): name = 'DeepCNN' def __init__(self, learning_rate=0.01): self.device = None self.model = None self.optimizer = None self.criterion = None self.learning_rate = learning_rate self.features = ['corrLive', 'rmsLive', 'kurtLive', 'DELive', 'MFELive', 'skewLive', 'normLive', 'darkRatioLive', 'jumpLive', 'gainLive'] self.model = NeuralNet() def setup(self, device): self.device = device self.model = self.model.to(device) # Loss and optimizer learning_rate = 0.01 self.criterion = nn.CrossEntropyLoss() self.optimizer = torch.optim.Adam(self.model.parameters(), lr=self.learning_rate) def train(self, data, labels, metadata): gpu = self.device # Get input data streams tdata = data[:, 0, None, ...] fdata = data[:, 1, None, ...] # and transform to torch tensor tdata = torch.from_numpy(tdata).type(torch.FloatTensor) fdata = torch.from_numpy(fdata).type(torch.FloatTensor) labels = torch.from_numpy(labels) # Obtain engineered features features = np.hstack([metadata[key] for key in self.features]) features = torch.from_numpy(features).type(torch.FloatTensor) # Transfer input data into device (gpu / cpu) tdata, fdata = tdata.to(gpu), fdata.to(gpu) labels, features = labels.to(gpu), features.to(gpu) # Model computations outputs = self.model(tdata, fdata, features) loss = self.criterion(outputs, labels) # Backward and optimize print("Loss: %f" % float(loss)) self.optimizer.zero_grad() loss.backward() self.optimizer.step() def validate(self, data, labels, metadata): gpu = self.device # Get input data streams tdata = data[:, 0, None, ...] fdata = data[:, 1, None, ...] # Transform to torch tensor tdata = torch.from_numpy(tdata).type(torch.FloatTensor) fdata = torch.from_numpy(fdata).type(torch.FloatTensor) labels = torch.from_numpy(labels) # Obtain engineered features features = np.hstack([metadata[key] for key in self.features]) features = torch.from_numpy(features).type(torch.FloatTensor) # Transfer input data into device (gpu / cpu) tdata, fdata = tdata.to(gpu), fdata.to(gpu) labels, features = labels.to(gpu), features.to(gpu) outputs = self.model(tdata, fdata, features) probas = F.softmax(outputs) _, predicted = torch.max(probas, 1) return predicted.cpu().numpy(), probas.cpu().detach().numpy() def save(self, filename): torch.save(self.model, filename) def load(self, filename): if os.path.isfile(filename): self.model = torch.load(filename) self.model.eval() print("Saved model loaded!")
[ "torch.nn.MaxPool1d", "torch.nn.Conv1d", "torch.nn.ReLU", "torch.nn.CrossEntropyLoss", "numpy.hstack", "torch.load", "torch.max", "torch.from_numpy", "os.path.isfile", "torch.save", "torch.nn.Linear", "torch.nn.functional.softmax", "torch.cat" ]
[((2102, 2142), 'torch.cat', 'torch.cat', (['(tout, fout, features)'], {'dim': '(1)'}), '((tout, fout, features), dim=1)\n', (2111, 2142), False, 'import torch\n'), ((2851, 2872), 'torch.nn.CrossEntropyLoss', 'nn.CrossEntropyLoss', ([], {}), '()\n', (2870, 2872), False, 'from torch import nn\n'), ((3382, 3406), 'torch.from_numpy', 'torch.from_numpy', (['labels'], {}), '(labels)\n', (3398, 3406), False, 'import torch\n'), ((3464, 3515), 'numpy.hstack', 'np.hstack', (['[metadata[key] for key in self.features]'], {}), '([metadata[key] for key in self.features])\n', (3473, 3515), True, 'import numpy as np\n'), ((4428, 4452), 'torch.from_numpy', 'torch.from_numpy', (['labels'], {}), '(labels)\n', (4444, 4452), False, 'import torch\n'), ((4510, 4561), 'numpy.hstack', 'np.hstack', (['[metadata[key] for key in self.features]'], {}), '([metadata[key] for key in self.features])\n', (4519, 4561), True, 'import numpy as np\n'), ((4870, 4888), 'torch.nn.functional.softmax', 'F.softmax', (['outputs'], {}), '(outputs)\n', (4879, 4888), True, 'import torch.nn.functional as F\n'), ((4912, 4932), 'torch.max', 'torch.max', (['probas', '(1)'], {}), '(probas, 1)\n', (4921, 4932), False, 'import torch\n'), ((5042, 5074), 'torch.save', 'torch.save', (['self.model', 'filename'], {}), '(self.model, filename)\n', (5052, 5074), False, 'import torch\n'), ((5117, 5141), 'os.path.isfile', 'os.path.isfile', (['filename'], {}), '(filename)\n', (5131, 5141), False, 'import os\n'), ((270, 302), 'torch.nn.Conv1d', 'nn.Conv1d', (['(1)', '(16)'], {'kernel_size': '(16)'}), '(1, 16, kernel_size=16)\n', (279, 302), False, 'from torch import nn\n'), ((316, 325), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (323, 325), False, 'from torch import nn\n'), ((339, 372), 'torch.nn.Conv1d', 'nn.Conv1d', (['(16)', '(16)'], {'kernel_size': '(16)'}), '(16, 16, kernel_size=16)\n', (348, 372), False, 'from torch import nn\n'), ((386, 395), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (393, 395), False, 'from torch import nn\n'), ((409, 447), 'torch.nn.MaxPool1d', 'nn.MaxPool1d', ([], {'kernel_size': '(16)', 'stride': '(3)'}), '(kernel_size=16, stride=3)\n', (421, 447), False, 'from torch import nn\n'), ((461, 494), 'torch.nn.Conv1d', 'nn.Conv1d', (['(16)', '(32)'], {'kernel_size': '(16)'}), '(16, 32, kernel_size=16)\n', (470, 494), False, 'from torch import nn\n'), ((508, 517), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (515, 517), False, 'from torch import nn\n'), ((531, 564), 'torch.nn.Conv1d', 'nn.Conv1d', (['(32)', '(32)'], {'kernel_size': '(16)'}), '(32, 32, kernel_size=16)\n', (540, 564), False, 'from torch import nn\n'), ((578, 587), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (585, 587), False, 'from torch import nn\n'), ((601, 639), 'torch.nn.MaxPool1d', 'nn.MaxPool1d', ([], {'kernel_size': '(16)', 'stride': '(3)'}), '(kernel_size=16, stride=3)\n', (613, 639), False, 'from torch import nn\n'), ((653, 686), 'torch.nn.Conv1d', 'nn.Conv1d', (['(32)', '(64)'], {'kernel_size': '(16)'}), '(32, 64, kernel_size=16)\n', (662, 686), False, 'from torch import nn\n'), ((700, 709), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (707, 709), False, 'from torch import nn\n'), ((723, 756), 'torch.nn.Conv1d', 'nn.Conv1d', (['(64)', '(64)'], {'kernel_size': '(16)'}), '(64, 64, kernel_size=16)\n', (732, 756), False, 'from torch import nn\n'), ((770, 779), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (777, 779), False, 'from torch import nn\n'), ((793, 831), 'torch.nn.MaxPool1d', 'nn.MaxPool1d', ([], {'kernel_size': '(16)', 'stride': '(3)'}), '(kernel_size=16, stride=3)\n', (805, 831), False, 'from torch import nn\n'), ((898, 930), 'torch.nn.Conv1d', 'nn.Conv1d', (['(1)', '(16)'], {'kernel_size': '(16)'}), '(1, 16, kernel_size=16)\n', (907, 930), False, 'from torch import nn\n'), ((944, 953), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (951, 953), False, 'from torch import nn\n'), ((967, 1000), 'torch.nn.Conv1d', 'nn.Conv1d', (['(16)', '(16)'], {'kernel_size': '(16)'}), '(16, 16, kernel_size=16)\n', (976, 1000), False, 'from torch import nn\n'), ((1014, 1023), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1021, 1023), False, 'from torch import nn\n'), ((1037, 1075), 'torch.nn.MaxPool1d', 'nn.MaxPool1d', ([], {'kernel_size': '(16)', 'stride': '(3)'}), '(kernel_size=16, stride=3)\n', (1049, 1075), False, 'from torch import nn\n'), ((1089, 1122), 'torch.nn.Conv1d', 'nn.Conv1d', (['(16)', '(32)'], {'kernel_size': '(16)'}), '(16, 32, kernel_size=16)\n', (1098, 1122), False, 'from torch import nn\n'), ((1136, 1145), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1143, 1145), False, 'from torch import nn\n'), ((1159, 1192), 'torch.nn.Conv1d', 'nn.Conv1d', (['(32)', '(32)'], {'kernel_size': '(16)'}), '(32, 32, kernel_size=16)\n', (1168, 1192), False, 'from torch import nn\n'), ((1206, 1215), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1213, 1215), False, 'from torch import nn\n'), ((1229, 1267), 'torch.nn.MaxPool1d', 'nn.MaxPool1d', ([], {'kernel_size': '(16)', 'stride': '(3)'}), '(kernel_size=16, stride=3)\n', (1241, 1267), False, 'from torch import nn\n'), ((1281, 1314), 'torch.nn.Conv1d', 'nn.Conv1d', (['(32)', '(64)'], {'kernel_size': '(16)'}), '(32, 64, kernel_size=16)\n', (1290, 1314), False, 'from torch import nn\n'), ((1328, 1337), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1335, 1337), False, 'from torch import nn\n'), ((1351, 1384), 'torch.nn.Conv1d', 'nn.Conv1d', (['(64)', '(64)'], {'kernel_size': '(16)'}), '(64, 64, kernel_size=16)\n', (1360, 1384), False, 'from torch import nn\n'), ((1398, 1407), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1405, 1407), False, 'from torch import nn\n'), ((1421, 1459), 'torch.nn.MaxPool1d', 'nn.MaxPool1d', ([], {'kernel_size': '(16)', 'stride': '(3)'}), '(kernel_size=16, stride=3)\n', (1433, 1459), False, 'from torch import nn\n'), ((1529, 1561), 'torch.nn.Linear', 'nn.Linear', (['(16 * 16 * 2 + 10)', '(256)'], {}), '(16 * 16 * 2 + 10, 256)\n', (1538, 1561), False, 'from torch import nn\n'), ((1569, 1578), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1576, 1578), False, 'from torch import nn\n'), ((1592, 1609), 'torch.nn.Linear', 'nn.Linear', (['(256)', '(2)'], {}), '(256, 2)\n', (1601, 1609), False, 'from torch import nn\n'), ((5168, 5188), 'torch.load', 'torch.load', (['filename'], {}), '(filename)\n', (5178, 5188), False, 'import torch\n'), ((3253, 3276), 'torch.from_numpy', 'torch.from_numpy', (['tdata'], {}), '(tdata)\n', (3269, 3276), False, 'import torch\n'), ((3317, 3340), 'torch.from_numpy', 'torch.from_numpy', (['fdata'], {}), '(fdata)\n', (3333, 3340), False, 'import torch\n'), ((3535, 3561), 'torch.from_numpy', 'torch.from_numpy', (['features'], {}), '(features)\n', (3551, 3561), False, 'import torch\n'), ((4299, 4322), 'torch.from_numpy', 'torch.from_numpy', (['tdata'], {}), '(tdata)\n', (4315, 4322), False, 'import torch\n'), ((4363, 4386), 'torch.from_numpy', 'torch.from_numpy', (['fdata'], {}), '(fdata)\n', (4379, 4386), False, 'import torch\n'), ((4581, 4607), 'torch.from_numpy', 'torch.from_numpy', (['features'], {}), '(features)\n', (4597, 4607), False, 'import torch\n')]
""" A set of general utility functions used across the codebase """ import numpy as np from contextlib import contextmanager import logging def exactly_one_specified(*inputs): """ Returns True if exactly one of *inputs is None Args: *inputs: One or more arguments to test against Returns: bool """ not_none = np.array(list(map(lambda x: x is not None, inputs))) return np.sum(not_none) == 1 def b_if_a_is_none(a, b): """ Returns 'b' if 'a' is None, otherwise returns 'a' """ if a is None: return b else: return a def assert_all_loaded(pairs, raise_=True): """ Returns True if all SleepStudy objects in 'pairs' have the 'loaded' property set to True, otherwise returns False. If raise_ is True, raises a NotImplementedError if one or more objects are not loaded. Otherwise, returns the value of the assessment. Temp. until queue functionality implemented """ loaded_pairs = [p for p in pairs if p.loaded] if len(loaded_pairs) != len(pairs): if raise_: raise NotImplementedError("BatchSequence currently requires all" " samples to be loaded") else: return False return True def ensure_list_or_tuple(obj): """ Takes some object and wraps it in a list - i.e. [obj] - unless the object is already a list or a tuple instance. In that case, simply returns 'obj' Args: obj: Any object Returns: [obj] if obj is not a list or tuple, else obj """ return [obj] if not isinstance(obj, (list, tuple)) else obj @contextmanager def cd_context(path): """ Context manager for changing directory and back in a context. E.g. usage is: with cd_context("my_path"): ... do something in "my_path" ... do something back at original path Args: path: A string, path Returns: yields inside the specified directory """ import os cur_dir = os.getcwd() try: os.chdir(path) yield finally: os.chdir(cur_dir) @contextmanager def mne_no_log_context(): """ Disables the logger of the mne module inside the context only """ log = logging.getLogger('mne') mem = log.disabled log.disabled = True try: yield finally: log.disabled = mem
[ "logging.getLogger", "numpy.sum", "os.chdir", "os.getcwd" ]
[((2028, 2039), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2037, 2039), False, 'import os\n'), ((2253, 2277), 'logging.getLogger', 'logging.getLogger', (['"""mne"""'], {}), "('mne')\n", (2270, 2277), False, 'import logging\n'), ((418, 434), 'numpy.sum', 'np.sum', (['not_none'], {}), '(not_none)\n', (424, 434), True, 'import numpy as np\n'), ((2057, 2071), 'os.chdir', 'os.chdir', (['path'], {}), '(path)\n', (2065, 2071), False, 'import os\n'), ((2107, 2124), 'os.chdir', 'os.chdir', (['cur_dir'], {}), '(cur_dir)\n', (2115, 2124), False, 'import os\n')]
"""Manages the imaging context. This take a string and returns a dictionary containing: * Predict function * Invert function * image_iterator function * vis_iterator function """ import logging import numpy from data_models.memory_data_models import Visibility, Image from ..image.gather_scatter import image_scatter_facets from ..image.operations import create_empty_image_like from ..imaging.base import normalize_sumwt from ..imaging.base import predict_2d, invert_2d from ..imaging.timeslice_single import predict_timeslice_single, invert_timeslice_single from ..imaging.wstack_single import predict_wstack_single, invert_wstack_single from ..visibility.base import copy_visibility, create_visibility_from_rows from ..visibility.coalesce import convert_blockvisibility_to_visibility, convert_visibility_to_blockvisibility from ..visibility.iterators import vis_timeslice_iter, vis_null_iter, vis_wslice_iter log = logging.getLogger(__name__) def imaging_contexts(): """Contains all the context information for imaging The fields are: predict: Predict function to be used invert: Invert function to be used image_iterator: Iterator for traversing images vis_iterator: Iterator for traversing visibilities inner: The innermost axis :return: """ contexts = {'2d': {'predict': predict_2d, 'invert': invert_2d, 'vis_iterator': vis_null_iter, 'inner': 'image'}, 'facets': {'predict': predict_2d, 'invert': invert_2d, 'vis_iterator': vis_null_iter, 'inner': 'image'}, 'facets_timeslice': {'predict': predict_timeslice_single, 'invert': invert_timeslice_single, 'vis_iterator': vis_timeslice_iter, 'inner': 'image'}, 'facets_wstack': {'predict': predict_wstack_single, 'invert': invert_wstack_single, 'vis_iterator': vis_wslice_iter, 'inner': 'image'}, 'timeslice': {'predict': predict_timeslice_single, 'invert': invert_timeslice_single, 'vis_iterator': vis_timeslice_iter, 'inner': 'image'}, 'wstack': {'predict': predict_wstack_single, 'invert': invert_wstack_single, 'vis_iterator': vis_wslice_iter, 'inner': 'image'}} return contexts def imaging_context(context='2d'): contexts = imaging_contexts() assert context in contexts.keys(), context return contexts[context] def invert_function(vis, im: Image, dopsf=False, normalize=True, context='2d', inner=None, vis_slices=1, facets=1, overlap=0, taper=None, **kwargs): """ Invert using algorithm specified by context: * 2d: Two-dimensional transform * wstack: wstacking with either vis_slices or wstack (spacing between w planes) set * wprojection: w projection with wstep (spacing between w places) set, also kernel='wprojection' * timeslice: snapshot imaging with either vis_slices or timeslice set. timeslice='auto' does every time * facets: Faceted imaging with facets facets on each axis * facets_wprojection: facets AND wprojection * facets_wstack: facets AND wstacking * wprojection_wstack: wprojection and wstacking :param vis: :param im: :param dopsf: Make the psf instead of the dirty image (False) :param normalize: Normalize by the sum of weights (True) :param context: Imaging context e.g. '2d', 'timeslice', etc. :param inner: Inner loop 'vis'|'image' :param kwargs: :return: Image, sum of weights """ c = imaging_context(context) vis_iter = c['vis_iterator'] invert = c['invert'] if inner is None: inner = c['inner'] if not isinstance(vis, Visibility): svis = convert_blockvisibility_to_visibility(vis) else: svis = vis resultimage = create_empty_image_like(im) if inner == 'image': totalwt = None for rows in vis_iter(svis, vis_slices=vis_slices): if numpy.sum(rows): visslice = create_visibility_from_rows(svis, rows) sumwt = 0.0 workimage = create_empty_image_like(im) for dpatch in image_scatter_facets(workimage, facets=facets, overlap=overlap, taper=taper): result, sumwt = invert(visslice, dpatch, dopsf, normalize=False, facets=facets, vis_slices=vis_slices, **kwargs) # Ensure that we fill in the elements of dpatch instead of creating a new numpy arrray dpatch.data[...] = result.data[...] # Assume that sumwt is the same for all patches if totalwt is None: totalwt = sumwt else: totalwt += sumwt resultimage.data += workimage.data else: # We assume that the weight is the same for all image iterations totalwt = None workimage = create_empty_image_like(im) for dpatch in image_scatter_facets(workimage, facets=facets, overlap=overlap, taper=taper): totalwt = None for rows in vis_iter(svis, vis_slices=vis_slices): if numpy.sum(rows): visslice = create_visibility_from_rows(svis, rows) result, sumwt = invert(visslice, dpatch, dopsf, normalize=False, **kwargs) # Ensure that we fill in the elements of dpatch instead of creating a new numpy arrray dpatch.data[...] += result.data[...] if totalwt is None: totalwt = sumwt else: totalwt += sumwt resultimage.data += workimage.data workimage.data[...] = 0.0 assert totalwt is not None, "No valid data found for imaging" if normalize: resultimage = normalize_sumwt(resultimage, totalwt) return resultimage, totalwt def predict_function(vis, model: Image, context='2d', inner=None, vis_slices=1, facets=1, overlap=0, taper=None, **kwargs) -> Visibility: """Predict visibilities using algorithm specified by context * 2d: Two-dimensional transform * wstack: wstacking with either vis_slices or wstack (spacing between w planes) set * wprojection: w projection with wstep (spacing between w places) set, also kernel='wprojection' * timeslice: snapshot imaging with either vis_slices or timeslice set. timeslice='auto' does every time * facets: Faceted imaging with facets facets on each axis * facets_wprojection: facets AND wprojection * facets_wstack: facets AND wstacking * wprojection_wstack: wprojection and wstacking :param vis: :param model: Model image, used to determine image characteristics :param context: Imaging context e.g. '2d', 'timeslice', etc. :param inner: Inner loop 'vis'|'image' :param kwargs: :return: """ c = imaging_context(context) vis_iter = c['vis_iterator'] predict = c['predict'] if inner is None: inner = c['inner'] if not isinstance(vis, Visibility): svis = convert_blockvisibility_to_visibility(vis) else: svis = vis result = copy_visibility(vis, zero=True) if inner == 'image': for rows in vis_iter(svis, vis_slices=vis_slices): if numpy.sum(rows): visslice = create_visibility_from_rows(svis, rows) visslice.data['vis'][...] = 0.0 for dpatch in image_scatter_facets(model, facets=facets, overlap=overlap, taper=taper): result.data['vis'][...] = 0.0 result = predict(visslice, dpatch, **kwargs) svis.data['vis'][rows] += result.data['vis'] else: for dpatch in image_scatter_facets(model, facets=facets, overlap=overlap, taper=taper): for rows in vis_iter(svis, vis_slices=vis_slices): if numpy.sum(rows): visslice = create_visibility_from_rows(svis, rows) result.data['vis'][...] = 0.0 result = predict(visslice, dpatch, **kwargs) svis.data['vis'][rows] += result.data['vis'] if not isinstance(vis, Visibility): svis = convert_visibility_to_blockvisibility(svis) return svis
[ "logging.getLogger", "numpy.sum" ]
[((928, 955), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (945, 955), False, 'import logging\n'), ((4438, 4453), 'numpy.sum', 'numpy.sum', (['rows'], {}), '(rows)\n', (4447, 4453), False, 'import numpy\n'), ((7875, 7890), 'numpy.sum', 'numpy.sum', (['rows'], {}), '(rows)\n', (7884, 7890), False, 'import numpy\n'), ((5662, 5677), 'numpy.sum', 'numpy.sum', (['rows'], {}), '(rows)\n', (5671, 5677), False, 'import numpy\n'), ((8479, 8494), 'numpy.sum', 'numpy.sum', (['rows'], {}), '(rows)\n', (8488, 8494), False, 'import numpy\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2021/8/8 16:21 # @Author : <NAME> # @File : utils.py import pandas as pd import numpy as np def load_data(adj, fea, lab, threshold=0.005): ''' :param adj: the similarity matrix filename :param fea: the omics vector features filename :param lab: sample labels filename :param threshold: the edge filter threshold ''' print('loading data...') adj_df = pd.read_csv(adj, header=0, index_col=None) fea_df = pd.read_csv(fea, header=0, index_col=None) label_df = pd.read_csv(lab, header=0, index_col=None) if adj_df.shape[0] != fea_df.shape[0] or adj_df.shape[0] != label_df.shape[0]: print('Input files must have same samples.') exit(1) adj_df.rename(columns={adj_df.columns.tolist()[0]: 'Sample'}, inplace=True) fea_df.rename(columns={fea_df.columns.tolist()[0]: 'Sample'}, inplace=True) label_df.rename(columns={label_df.columns.tolist()[0]: 'Sample'}, inplace=True) #align samples of different data adj_df.sort_values(by='Sample', ascending=True, inplace=True) fea_df.sort_values(by='Sample', ascending=True, inplace=True) label_df.sort_values(by='Sample', ascending=True, inplace=True) print('Calculating the laplace adjacency matrix...') adj_m = adj_df.iloc[:, 1:].values #The SNF matrix is a completed connected graph, it is better to filter edges with a threshold adj_m[adj_m<threshold] = 0 # adjacency matrix after filtering exist = (adj_m != 0) * 1.0 #np.savetxt('result/adjacency_matrix.csv', exist, delimiter=',', fmt='%d') #calculate the degree matrix factor = np.ones(adj_m.shape[1]) res = np.dot(exist, factor) #degree of each node diag_matrix = np.diag(res) #degree matrix #np.savetxt('result/diag.csv', diag_matrix, delimiter=',', fmt='%d') #calculate the laplace matrix d_inv = np.linalg.inv(diag_matrix) adj_hat = d_inv.dot(exist) return adj_hat, fea_df, label_df def accuracy(output, labels): pred = output.max(1)[1].type_as(labels) correct = pred.eq(labels).double() correct = correct.sum() return correct / len(labels)
[ "numpy.ones", "pandas.read_csv", "numpy.diag", "numpy.dot", "numpy.linalg.inv" ]
[((463, 505), 'pandas.read_csv', 'pd.read_csv', (['adj'], {'header': '(0)', 'index_col': 'None'}), '(adj, header=0, index_col=None)\n', (474, 505), True, 'import pandas as pd\n'), ((520, 562), 'pandas.read_csv', 'pd.read_csv', (['fea'], {'header': '(0)', 'index_col': 'None'}), '(fea, header=0, index_col=None)\n', (531, 562), True, 'import pandas as pd\n'), ((579, 621), 'pandas.read_csv', 'pd.read_csv', (['lab'], {'header': '(0)', 'index_col': 'None'}), '(lab, header=0, index_col=None)\n', (590, 621), True, 'import pandas as pd\n'), ((1705, 1728), 'numpy.ones', 'np.ones', (['adj_m.shape[1]'], {}), '(adj_m.shape[1])\n', (1712, 1728), True, 'import numpy as np\n'), ((1740, 1761), 'numpy.dot', 'np.dot', (['exist', 'factor'], {}), '(exist, factor)\n', (1746, 1761), True, 'import numpy as np\n'), ((1806, 1818), 'numpy.diag', 'np.diag', (['res'], {}), '(res)\n', (1813, 1818), True, 'import numpy as np\n'), ((1959, 1985), 'numpy.linalg.inv', 'np.linalg.inv', (['diag_matrix'], {}), '(diag_matrix)\n', (1972, 1985), True, 'import numpy as np\n')]
# Copyright (c) 2021 ING Wholesale Banking Advanced Analytics # # 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. import histogrammar as hg import numpy as np from ..analysis.hist_numpy import assert_similar_hists from ..base import Module class HistStitcher(Module): """Module stitches histograms by date""" def __init__( self, mode="add", time_axis=None, time_bin_idx=None, read_key=None, delta_key=None, store_key=None, ): """Stitching histograms by first axis. :param str mode: options for histogram stitching: "add" or "replace". default is "add". :param str time_axis: name of the first axis, to stitch on. :param str time_bin_idx: value of delta dataset used for stitching, in case delta or first dataset is a batch without time_axis. Should be an ordered string or integer. :param str read_key: key of input histogram-dict to read from data store. (only required when calling transform(datastore) as module) :param str delta_key: key of delta histogram-dict to read from data store. (only required when calling transform(datastore) as module) :param str store_key: key of output data to store in data store (only required when calling transform(datastore) as module) """ super().__init__() self.mode = mode self.time_axis = time_axis self.time_bin_idx = time_bin_idx self.read_key = read_key self.delta_key = delta_key self.store_key = store_key self.allowed_modes = ["add", "replace"] assert self.mode in self.allowed_modes def transform(self, datastore): # --- get input dict lists self.logger.info( f'Stitching histograms "{self.read_key}" and "{self.delta_key}" as "{self.store_key}"' ) hists_basis = self.get_datastore_object(datastore, self.read_key, dtype=dict) hists_delta = self.get_datastore_object(datastore, self.delta_key, dtype=dict) stitched = self.stitch_histograms(self.mode, hists_basis, hists_delta) datastore[self.store_key] = stitched return datastore def stitch_histograms( self, mode=None, hists_basis=None, hists_delta=None, hists_list=None, time_axis="", time_bin_idx=None, ): """Stitching histograms by first axis. Histograms in hists_delta are added to those in hists_basis. Bins are summed or replaced, set this with 'mode'. 'time_axis' specifies the name of the first axis. If the time_axis is not found, it is created, and histograms get inserted the time_bin_idx values. :param str mode: options for histogram stitching: "add" or "replace" bins. default is "add". :param dict hists_basis: input dict of basis histograms. :param dict hists_delta: delta dict of histograms to add to hists_basis. :param list hists_list: alternative for [hists_basis, hists_delta, etc]. can have multiple deltas. first item in list is taken as hists_basis (optional) :param str time_axis: time-axis used for stitching (optional). :param time_bin_idx: (list of) time-value(s) at which to insert hist-deltas into hist-basis. :return: dict with stitched histograms. If stitching is not possible, returns hists_basis. """ # set stitching mode mode = ( mode if isinstance(mode, str) and mode in self.allowed_modes else self.mode ) time_axis = ( time_axis if isinstance(time_axis, str) and len(time_axis) > 0 else self.time_axis ) time_bin_idx = ( time_bin_idx if isinstance(time_bin_idx, (str, int, list, tuple)) else self.time_bin_idx ) hists_list = hists_list or [] if time_bin_idx is not None: if isinstance(time_bin_idx, (str, int)): time_bin_idx = [time_bin_idx] if not isinstance(time_bin_idx, (list, tuple)): raise TypeError( "time_bin_idx should be a (list of) ordered integer(s) or string(s)" ) dts = [type(tv) for tv in time_bin_idx] if not dts.count(dts[0]) == len(dts): raise TypeError(f"time_bin_idxs have inconsistent datatypes: {dts}") # basic checks and conversions if isinstance(hists_basis, dict) and len(hists_basis) > 0: hists_list.insert(0, hists_basis) if isinstance(hists_delta, dict) and len(hists_delta) > 0: hists_list.append(hists_delta) elif isinstance(hists_delta, list): for hd in hists_delta: if isinstance(hd, dict) and len(hd) > 0: hists_list.append(hd) if not isinstance(hists_list, list) or len(hists_list) == 0: raise TypeError( "hists_list should be a filled list of histogram dictionaries." ) for hd in hists_list: if not isinstance(hd, dict) or len(hd) == 0: raise TypeError( "hists_list should be a list of filled histogram dictionaries." ) hists_basis = hists_list[0] hists_delta = hists_list[1:] # determine possible features, used for comparisons below if isinstance(time_axis, str) and len(time_axis) > 0: self.feature_begins_with = f"{time_axis}:" # Three possibilities # 1. if there are no basis hists starting with "time_axis:", assume that this the very first batch. # 2. if delta(s) do not start with "time_axis:", assume that this is a set of batches without time_axis # 3. deltas already have a time-axis. start stitching of histograms by using bins.update() features_basis = self.get_features( list(hists_basis.keys()) ) # basis keys that start with time_axis if len(features_basis) > 0: # pruning of keys not starting with time_axis hists_list[0] = hists_basis = { k: h for k, h in hists_basis.items() if k in features_basis } # 1. if there are no basis hists starting with "time_axis:", assume that this the very first batch. if ( len(features_basis) == 0 and time_axis and len(hists_basis) > 0 and time_axis ): if time_bin_idx is None: self.logger.info( f'Inserting basis histograms in axis "{time_axis}" at bin index 0.' ) time_bin_idx = [0] hists_basis_new = {} for k, hist in hists_basis.items(): feature = f"{time_axis}:{k}" self.logger.debug(f'Now creating histogram "{feature}"') hists_basis_new[feature] = self._create_hist_with_time_axis( hist, time_bin_idx[0] ) # reset hists_basis features_basis = self.get_features(list(hists_basis_new.keys())) hists_list[0] = hists_basis = hists_basis_new time_bin_idx = time_bin_idx[1:] # -- is there a need to continue? There need to be overlapping hists. delta_keys = set() if len(hists_delta) > 0: delta_keys = set(hists_delta[0].keys()) for hd in hists_delta[1:]: delta_keys &= set(hd.keys()) if len(hists_delta) == 0 or len(delta_keys) == 0 or len(hists_basis) == 0: self.logger.debug( "No overlapping delta features. returning pruned hists_basis." ) return hists_basis stitched = {} # 2. if delta(s) do not start with "time_axis:", assume that this is a set of batches without time_axis features_delta = self.get_features( list(delta_keys) ) # delta keys that start with time_axis if ( len(features_basis) > 0 and len(features_delta) == 0 and len(delta_keys) > 0 and time_axis ): if time_bin_idx is None or len(time_bin_idx) == 0: time_bin_idx = self._generate_time_bin_idx( hists_basis, features_basis, time_axis, len(hists_delta) ) if time_bin_idx is None: raise ValueError( "Request to insert delta hists but time_bin_idx not set or deductable. Please set manually." ) self.logger.info( f'Inserting delta histograms in axis "{time_axis}" at bin indices {time_bin_idx}.' ) if len(hists_delta) != len(time_bin_idx): raise ValueError( "Not enough time_bin_idxs set to insert delta histograms." ) for key in list(delta_keys): feature = f"{time_axis}:{key}" if feature not in features_basis: continue self.logger.debug(f'Now inserting into histogram "{feature}"') hist_list = [hd[key] for hd in hists_delta] stitched[feature] = self._insert_hists( hists_basis[feature], hist_list, time_bin_idx, mode ) # add basis hists without any overlap for feature in features_basis: if feature not in stitched: stitched[feature] = hists_basis[feature] return stitched # 3. deltas already have a time-axis. start stitching of histograms by using bins.update() overlapping_keys = set(hists_list[0].keys()) for hd in hists_list[1:]: overlapping_keys &= set(hd.keys()) features_overlap = self.get_features( list(overlapping_keys) ) # all overlapping keys that start with time_axis if len(features_overlap) == 0: # no overlap, then return basis histograms self.logger.warning( "No overlapping basis-delta features. returning pruned hists_basis." ) return hists_basis for feature in features_overlap: self.logger.debug(f'Now stitching histograms "{feature}"') hist_list = [hd[feature] for hd in hists_list] stitched[feature] = self._stitch_by_update(mode, hist_list) # add basis hists without any overlap for feature in features_basis: if feature not in stitched: stitched[feature] = hists_basis[feature] return stitched def _find_max_time_bin_index(self, hists_basis, features_basis, time_axis): """Find the maximum time-bin index in dict of basis histograms :param hists_basis: dict of basis histograms :param features_basis: list of features to look at :param time_axis: name of time-axis :return: maximum time-bin index found or None """ # basic checks assert isinstance(time_axis, str) and len(time_axis) > 0 assert len(features_basis) > 0 assert all([f.startswith(time_axis) for f in features_basis]) hist_list = list(hists_basis.values()) all_sparse = all([isinstance(h, hg.SparselyBin) for h in hist_list]) all_cat = ( all([isinstance(h, hg.Categorize) for h in hist_list]) if not all_sparse else False ) max_time_bin_idx = None if all_sparse or all_cat: max_time_bin_idx = max( max(h.bins.keys()) for h in hist_list if len(h.bins) > 0 ) return max_time_bin_idx def _generate_time_bin_idx(self, hists_basis, features_basis, time_axis, n): """Generate n consecutive time-bin indices beyond max existing time-bin index :param hists_basis: dict of basis histograms :param features_basis: list of features to look at :param time_axis: name of time-axis :param n: number of time-bin indices to generate :return: maximum time-bin index found or None """ assert n > 0 max_time_bin_idx = self._find_max_time_bin_index( hists_basis, features_basis, time_axis ) if max_time_bin_idx is not None: self.logger.info(f"Maximum time bin index found: {max_time_bin_idx}") time_bin_idx = None if isinstance(max_time_bin_idx, (int, np.integer)): start = max_time_bin_idx + 1 stop = start + n time_bin_idx = np.arange(start, stop) return time_bin_idx def _insert_hists(self, hbasis, hdelta_list, time_bin_idx, mode): """Add delta hist to hist_basis at time-value :param hbasis: basis histogram with time-axis :param hdelta_list: delta histogram without time-axis :param time_bin_idx: list of time-value at which to insert hdeltas into hbasis :param str mode: options for histogram stitching: "add" or "replace". default is "add". :return: stitched hbasis histogram """ # basic checks on time-values if len(hdelta_list) != len(time_bin_idx) or len(hdelta_list) == 0: raise ValueError( "hdelta_list and time_bin_idx should be filled and same size." ) dts = [type(tv) for tv in time_bin_idx] if not dts.count(dts[0]) == len(dts): raise TypeError(f"time_bin_idxs have inconsistent datatypes: {dts}") if not isinstance(time_bin_idx[0], (str, int, np.integer)): raise TypeError("time_bin_idxs should be an (ordered) string or integer.") # consistency checks on histogram definitions if not hasattr(hbasis, "bins"): raise ValueError( "basis histogram does not have bins attribute. cannot insert." ) if len(hbasis.bins) > 0: hbk0 = list(hbasis.bins.values())[0] assert_similar_hists([hbk0] + hdelta_list) else: assert_similar_hists(hdelta_list) # check consistency of hbasis and time-value type if isinstance(time_bin_idx[0], str): if not isinstance(hbasis, hg.Categorize): raise TypeError("hbasis does not accept string time-values.") elif isinstance(time_bin_idx[0], (int, np.integer)): if not isinstance(hbasis, hg.SparselyBin): raise TypeError("hbasis does not accept integer time-values.") # stitch all the hdeltas into hbasis hsum = hbasis.copy() for tv, hdelta in zip(time_bin_idx, hdelta_list): if tv in hsum.bins: # replace or sum? hbt = hsum.bins[tv] hbt_entries = hbt.entries if mode == "replace": hsum.bins[tv] = hdelta hsum.entries += hdelta.entries - hbt_entries else: hsum.bins[tv] += hdelta hsum.entries += hdelta.entries else: # insert at time_bin_idx hsum.bins[tv] = hdelta hsum.entries += hdelta.entries return hsum def _create_hist_with_time_axis(self, hist, time_bin_idx): """Create histogram with time-axis and place hist into it at time-value :param hist: input histogram to insert into histogram with time-axis :param str time_bin_idx: time-value at which to insert histogram :return: histogram with time-axis """ # basic checks if time_bin_idx is None or not isinstance(time_bin_idx, (str, int)): raise TypeError( "time_bin_idx not set. should be an (ordered) string or integer." ) ht = ( hg.SparselyBin(binWidth=1.0, origin=0.0, quantity=lambda x: x) if isinstance(time_bin_idx, int) else hg.Categorize(quantity=lambda x: x) ) # noqa ht.bins[time_bin_idx] = hist ht.entries = hist.entries return ht def _stitch_by_update(self, mode, hist_list): """Get sum of histograms using h1.bins.update(h2.bins), from first to last hist Get sum of list of histograms by using bins.update(), where the update is applied by iterating over the histogram list, from the first to the last histogram. Meaning the next bins can overwrite the previous bins. This is used for merging (bins of) histograms that can be topped up over time. :param str mode: options for histogram stitching: "add" or "replace". default is "add". :param list hist_list: list of input histogrammar histograms :return: list of consistent 1d numpy arrays with bin_entries for list of input histograms """ # --- basic checks if len(hist_list) == 0: raise ValueError("Input histogram list has zero length.") assert_similar_hists(hist_list) # --- loop over all histograms and update zeroed-original consecutively hsum = hist_list[0].zero() if mode == "replace": # check consistency of histogram bins attributes is_bins = all([hasattr(hist, "bins") for hist in hist_list]) if not is_bins: raise TypeError("Not all input histograms have bins attribute.") # update bins consecutively for each time-delta. for hist in hist_list: hsum.bins.update(hist.bins) hsum.entries = sum(b.entries for b in hsum.bins.values()) else: for hist in hist_list: hsum += hist return hsum def stitch_histograms( mode=None, hists_basis=None, hists_delta=None, hists_list=None, time_axis=None, time_bin_idx=None, ): """Stitching histograms by first axis. Histograms in hists_delta are added to those in hists_basis. Bins are summed or replaced, set this with 'mode'. 'time_axis' specifies the name of the first axis. If the time_axis is not found, it is created, and histograms get inserted the time_bin_idx values. :param str mode: options for histogram stitching: "add" or "replace" bins. default is "add". :param dict hists_basis: input dict of basis histograms. :param dict hists_delta: delta dict of histograms to add to hists_basis. :param list hists_list: alternative for [hists_basis, hists_delta, etc]. can have multiple deltas. first item in list is taken as hists_basis (optional) :param str time_axis: time-axis used for stitching (optional). :param time_bin_idx: (list of) time-value(s) at which to insert hist-deltas into hist-basis. :return: dict with stitched histograms. If stitching is not possible, returns hists_basis. """ stitcher = HistStitcher() return stitcher.stitch_histograms( mode=mode, hists_basis=hists_basis, hists_delta=hists_delta, hists_list=hists_list, time_axis=time_axis, time_bin_idx=time_bin_idx, )
[ "histogrammar.SparselyBin", "histogrammar.Categorize", "numpy.arange" ]
[((13751, 13773), 'numpy.arange', 'np.arange', (['start', 'stop'], {}), '(start, stop)\n', (13760, 13773), True, 'import numpy as np\n'), ((17003, 17065), 'histogrammar.SparselyBin', 'hg.SparselyBin', ([], {'binWidth': '(1.0)', 'origin': '(0.0)', 'quantity': '(lambda x: x)'}), '(binWidth=1.0, origin=0.0, quantity=lambda x: x)\n', (17017, 17065), True, 'import histogrammar as hg\n'), ((17128, 17163), 'histogrammar.Categorize', 'hg.Categorize', ([], {'quantity': '(lambda x: x)'}), '(quantity=lambda x: x)\n', (17141, 17163), True, 'import histogrammar as hg\n')]
# -*- coding: utf-8 -*- """ This module provide utilities for converting from any complex format that we can read to SICD or SIO format. The same conversion utility can be used to subset data. """ import os import sys import pkgutil import numpy import logging from typing import Union, List, Tuple from . import __path__ as _complex_package_path, __name__ as _complex_package_name from .base import BaseReader from .sicd import SICDWriter from .sio import SIOWriter from .sicd_elements.SICD import SICDType integer_types = (int, ) int_func = int if sys.version_info[0] < 3: # noinspection PyUnresolvedReferences int_func = long # to accommodate for 32-bit python 2 # noinspection PyUnresolvedReferences integer_types = (int, long) _writer_types = {'SICD': SICDWriter, 'SIO': SIOWriter} __classification__ = "UNCLASSIFIED" __author__ = ("<NAME>", "<NAME>") def open_complex(file_name): """ Given a file, try to find and return the appropriate reader object. Parameters ---------- file_name : str Returns ------- BaseReader Raises ------ IOError """ if not os.path.exists(file_name): raise IOError('File {} does not exist.'.format(file_name)) # Get a list of all the modules that describe SAR complex image file # formats. For this to work, all of the file format handling modules # must be in the top level of this package. mod_iter = pkgutil.iter_modules(path=_complex_package_path, prefix='{}.'.format(_complex_package_name)) module_names = [name for loader, name, ispkg in mod_iter if not ispkg] modules = [sys.modules[names] for names in module_names if __import__(names)] # Determine file format and return the proper file reader object for current_mod in modules: if hasattr(current_mod, 'is_a'): # Make sure its a file format handling module reader = current_mod.is_a(file_name) if reader is not None: return reader # If for loop completes, no matching file format was found. raise IOError('Unable to determine complex image format.') class Converter(object): """ This is a class for conversion (of a single frame) of one complex format to SICD or SIO format. Another use case is to create a (contiguous) subset of a given complex dataset. **This class is intended to be used as a context manager.** """ __slots__ = ('_reader', '_file_name', '_writer', '_frame', '_row_limits', '_col_limits') def __init__(self, reader, output_directory, output_file=None, frame=None, row_limits=None, col_limits=None, output_format='SICD'): """ Parameters ---------- reader : BaseReader The base reader instance. output_directory : str The output directory. **This must exist.** output_file : None|str The output file name. If not provided, then `reader.get_suggested_name(frame)` will be used. frame : None|int The frame (i.e. index into the reader's sicd collection) to convert. The default is 0. row_limits : None|Tuple[int, int] Row start/stop. Default is all. col_limits : None|Tuple[int, int] Column start/stop. Default is all. output_format : str The output file format to write, from {'SICD', 'SIO'}. Default is SICD. """ if not (os.path.exists(output_directory) and os.path.isdir(output_directory)): raise IOError('output directory {} must exist.'.format(output_directory)) if output_file is None: output_file = reader.get_suggestive_name(frame=frame) output_path = os.path.join(output_directory, output_file) if os.path.exists(output_path): raise IOError('The file {} already exists.'.format(output_path)) # validate the output format and fetch the writer type if output_format is None: output_format = 'SICD' output_format = output_format.upper() if output_format not in ['SICD', 'SIO']: raise ValueError('Got unexpected output_format {}'.format(output_format)) writer_type = _writer_types[output_format] if isinstance(reader, BaseReader): self._reader = reader # type: BaseReader else: raise ValueError( 'reader is expected to be a Reader instance. Got {}'.format(type(reader))) # fetch the appropriate sicd instance sicds = reader.get_sicds_as_tuple() shapes = reader.get_data_size_as_tuple() if frame is None: self._frame = 0 else: self._frame = int_func(frame) if not (0 <= self._frame < len(sicds)): raise ValueError( 'Got a frame {}, but it must be between 0 and {}'.format(frame, len(sicds))) this_sicd = sicds[self._frame] this_shape = shapes[self._frame] # validate row_limits and col_limits if row_limits is None: row_limits = (0, this_shape[0]) else: row_limits = (int_func(row_limits[0]), int_func(row_limits[1])) if not ((0 <= row_limits[0] < this_shape[0]) and (row_limits[0] < row_limits[1] <= this_shape[0])): raise ValueError( 'Entries of row_limits must be monotonically increasing ' 'and in the range [0, {}]'.format(this_shape[0])) if col_limits is None: col_limits = (0, this_shape[1]) else: col_limits = (int_func(col_limits[0]), int_func(col_limits[1])) if not ((0 <= col_limits[0] < this_shape[1]) and (col_limits[0] < col_limits[1] <= this_shape[1])): raise ValueError( 'Entries of col_limits must be monotonically increasing ' 'and in the range [0, {}]'.format(this_shape[1])) self._row_limits = row_limits # type: Tuple[int, int] self._col_limits = col_limits # type: Tuple[int, int] # redefine our sicd, as necessary this_sicd = self._update_sicd(this_sicd, this_shape) # set up our writer self._file_name = output_path self._writer = writer_type(output_path, this_sicd) def _update_sicd(self, sicd, t_size): # type: (SICDType, Tuple[int, int]) -> SICDType o_sicd = sicd.copy() if self._row_limits != (0, t_size[0]) or self._col_limits != (0, t_size[1]): o_sicd.ImageData.NumRows = self._row_limits[1] - self._row_limits[0] o_sicd.ImageData.NumCols = self._col_limits[1] - self._col_limits[0] o_sicd.ImageData.FirstRow = sicd.ImageData.FirstRow + self._row_limits[0] o_sicd.ImageData.FirstCol = sicd.ImageData.FirstCol + self._col_limits[0] o_sicd.define_geo_image_corners(override=True) return o_sicd def _get_rows_per_block(self, max_block_size): pixel_type = self._writer.sicd_meta.ImageData.PixelType cols = int_func(self._writer.sicd_meta.ImageData.NumCols) bytes_per_row = 8*cols if pixel_type == 'RE32F_IM32F': bytes_per_row = 8*cols elif pixel_type == 'RE16I_IM16I': bytes_per_row = 4*cols elif pixel_type == 'AMP8I_PHS8I': bytes_per_row = 2*cols return max(1, int_func(round(max_block_size/bytes_per_row))) @property def writer(self): # type: () -> Union[SICDWriter, SIOWriter] """SICDWriter|SIOWriter: The writer instance.""" return self._writer def write_data(self, max_block_size=None): r""" Assuming that the desired changes have been made to the writer instance nitf header tags, write the data. Parameters ---------- max_block_size : None|int (nominal) maximum block size in bytes. Minimum value is :math:`2^{20} = 1~\text{MB}`. Default value is :math:`2^{26} = 64~\text{MB}`. Returns ------- None """ # validate max_block_size if max_block_size is None: max_block_size = 2**26 else: max_block_size = int_func(max_block_size) if max_block_size < 2**20: max_block_size = 2**20 # now, write the data rows_per_block = self._get_rows_per_block(max_block_size) block_start = self._row_limits[0] while block_start < self._row_limits[1]: block_end = min(block_start + rows_per_block, self._row_limits[1]) data = self._reader[block_start:block_end, self._col_limits[0]:self._col_limits[1], self._frame] self._writer.write_chip(data, start_indices=(block_start - self._row_limits[0], 0)) logging.info('Done writing block {}-{} to file {}'.format(block_start, block_end, self._file_name)) block_start = block_end def __del__(self): if hasattr(self, '_writer'): self._writer.close() def __enter__(self): return self def __exit__(self, exception_type, exception_value, traceback): if exception_type is None: self._writer.close() else: logging.error( 'The {} file converter generated an exception during processing. The file {} may be ' 'only partially generated and corrupt.'.format(self.__class__.__name__, self._file_name)) # The exception will be reraised. # It's unclear how any exception could be caught. def conversion_utility( input_file, output_directory, output_files=None, frames=None, output_format='SICD', row_limits=None, column_limits=None, max_block_size=None): """ Copy SAR complex data to a file of the specified format. Parameters ---------- input_file : str|BaseReader Reader instance, or the name of file to convert. output_directory : str The output directory. **This must exist.** output_files : None|str|List[str] The name of the output file(s), or list of output files matching `frames`. If not provided, then `reader.get_suggested_name(frame)` will be used. frames : None|int|list Set of frames to convert. Default is all. output_format : str The output file format to write, from {'SICD', 'SIO'}, optional. Default is SICD. row_limits : None|Tuple[int, int]|List[Tuple[int, int]] Rows start/stop. Default is all. column_limits : None|Tuple[int, int]|List[Tuple[int, int]] Columns start/stop. Default is all. max_block_size : None|int (nominal) maximum block size in bytes. Passed through to the Converter class. Returns ------- None """ def validate_lims(lims, typ): # type: (Union[None, tuple, list, numpy.ndarray], str) -> Tuple[Tuple[int, int], ...] def validate_entry(st, ed, shap, i_fr): if not ((0 <= st < shap[ind]) and (st < ed <= shap[ind])): raise ValueError('{}_limits is {}, and frame {} has shape {}'.format(typ, lims, i_fr, shap)) ind = 0 if typ == 'row' else 1 if lims is None: return tuple((0, shp[ind]) for shp in sizes) else: o_lims = numpy.array(lims, dtype=numpy.int64) t_lims = [] if len(o_lims.shape) == 1: if o_lims.shape[0] != 2: raise ValueError( 'row{}_limits must be of the form (<start>, <end>), got {}'.format(typ, lims)) t_start = int_func(o_lims[0]) t_end = int_func(o_lims[1]) for i_frame, shp in zip(frames, sizes): validate_entry(t_start, t_end, shp, i_frame) t_lims.append((t_start, t_end)) else: if o_lims.shape[0] != len(frames): raise ValueError( '{0:s}_limits must either be of the form (<start>, <end>) applied to all frames, ' 'or a collection of such of the same length as frames. ' 'Got len({0:s}_limits) = {1:d} and len(frames) = {2:d}'.format(typ, o_lims.shape[0], len(frames))) for entry, i_frame, shp in zip(o_lims, frames, sizes): t_start = int_func(entry[0]) t_end = int_func(entry[1]) validate_entry(t_start, t_end, shp, i_frame) t_lims.append((t_start, t_end)) return tuple(t_lims) if isinstance(input_file, str): reader = open_complex(input_file) elif isinstance(input_file, BaseReader): reader = input_file else: raise ValueError( 'input_file is expected to be a file name or Reader instance. Got {}'.format(type(input_file))) if not (os.path.exists(output_directory) and os.path.isdir(output_directory)): raise IOError('output directory {} must exist.'.format(output_directory)) sicds = reader.get_sicds_as_tuple() sizes = reader.get_data_size_as_tuple() # check that frames is valid if frames is None: frames = tuple(range(len(sicds))) if isinstance(frames, int): frames = (frames, ) if not isinstance(frames, tuple): frames = tuple(int_func(entry) for entry in frames) if len(frames) == 0: raise ValueError('The list of frames is empty.') o_frames = [] for frame in frames: index = int_func(frame) if not (0 <= index < len(sicds)): raise ValueError( 'Got a frames entry {}, but it must be between 0 and {}'.format(index, len(sicds))) o_frames.append(index) frames = tuple(o_frames) # construct output_files list if output_files is None: output_files = [reader.get_suggestive_name(frame) for frame in frames] elif isinstance(output_files, str): if len(sicds) == 1: output_files = [output_files, ] else: digits = int_func(numpy.ceil(numpy.log10(len(sicds)))) frm_str = '{0:s}-1{:0' + str(digits) + 'd}{2:s}' fstem, fext = os.path.splitext(output_files) o_files = [] for index in frames: o_files.append(frm_str.format(fstem, index, fext)) output_files = tuple(o_files) if len(output_files) != len(frames): raise ValueError('The lengths of frames and output_files must match.') if len(set(output_files)) != len(output_files): raise ValueError( 'Entries in output_files (possibly constructed) must be unique, got {} for frames {}'.format(output_files, frames)) # construct validated row/column_limits row_limits = validate_lims(row_limits, 'row') column_limits = validate_lims(column_limits, 'column') for o_file, frame, row_lims, col_lims in zip(output_files, frames, row_limits, column_limits): logging.info('Converting frame {} from file {} to file {}'.format(frame, input_file, o_file)) with Converter( reader, output_directory, output_file=o_file, frame=frame, row_limits=row_lims, col_limits=col_lims, output_format=output_format) as converter: converter.write_data(max_block_size=max_block_size)
[ "os.path.exists", "os.path.join", "os.path.splitext", "numpy.array", "os.path.isdir" ]
[((1138, 1163), 'os.path.exists', 'os.path.exists', (['file_name'], {}), '(file_name)\n', (1152, 1163), False, 'import os\n'), ((3723, 3766), 'os.path.join', 'os.path.join', (['output_directory', 'output_file'], {}), '(output_directory, output_file)\n', (3735, 3766), False, 'import os\n'), ((3778, 3805), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (3792, 3805), False, 'import os\n'), ((11301, 11337), 'numpy.array', 'numpy.array', (['lims'], {'dtype': 'numpy.int64'}), '(lims, dtype=numpy.int64)\n', (11312, 11337), False, 'import numpy\n'), ((12890, 12922), 'os.path.exists', 'os.path.exists', (['output_directory'], {}), '(output_directory)\n', (12904, 12922), False, 'import os\n'), ((12927, 12958), 'os.path.isdir', 'os.path.isdir', (['output_directory'], {}), '(output_directory)\n', (12940, 12958), False, 'import os\n'), ((3446, 3478), 'os.path.exists', 'os.path.exists', (['output_directory'], {}), '(output_directory)\n', (3460, 3478), False, 'import os\n'), ((3483, 3514), 'os.path.isdir', 'os.path.isdir', (['output_directory'], {}), '(output_directory)\n', (3496, 3514), False, 'import os\n'), ((14197, 14227), 'os.path.splitext', 'os.path.splitext', (['output_files'], {}), '(output_files)\n', (14213, 14227), False, 'import os\n')]
import requests import cv2 import numpy as np import pandas as pd import matplotlib.pyplot as plt import io import logging import logging.handlers #Needed for Syslog import sys from pathlib import Path #Use this to check for file existence import paho.mqtt.publish as publish import yaml #Get configuration parameters from 'config.yaml' file # pass in directory of config.yaml as argument. defaults to './' if (len(sys.argv) == 1): config_dir = './' else: config_dir = sys.argv[1] #pass configuration directory as arg with open(config_dir + 'config.yaml', 'r') as file: config = yaml.safe_load(file) data_path = config['data_path'] gasmeter_camera_ip = config['gasmeter_camera_ip'] image_url_postfix = config['image_url_postfix'] ROTATE_IMAGE = config['rotate_image'] CIRCLE_RADIUS = config['dials']['circle_radius'] gauge_centers = [ (config['dials']['gauge_centers']['digit4']['x'], config['dials']['gauge_centers']['digit4']['y']), (config['dials']['gauge_centers']['digit3']['x'], config['dials']['gauge_centers']['digit3']['y']), (config['dials']['gauge_centers']['digit2']['x'], config['dials']['gauge_centers']['digit2']['y']), (config['dials']['gauge_centers']['digit1']['x'], config['dials']['gauge_centers']['digit1']['y']), ] readout_conventions = config['dials']['readout_conventions'] #MQTT Configs: client_name = config['mqtt']['client_name'] host_name = config['mqtt']['host_name'] #Set a username and optionally a password for broker authentication. username = config['mqtt']['username'] broker_auth = None if username is not None: password = config['mqtt']['password'] if password is not None: broker_auth = {'username':username, 'password':password} else: broker_auth = {'username':username, 'password':None} topic = config['mqtt']['topic'] retain = config['mqtt']['retain'] if (retain == 'True'): retain = True else: retain = False # Setup Logger level = config['logger']['level'] CONSOLE = config['logger']['console'] _LOGGER = logging.getLogger(__name__) if CONSOLE: formatter = \ logging.Formatter('%(message)s') #logging.Formatter('%(levelname)-8s %(message)s') handler1 = logging.StreamHandler(sys.stdout) handler1.setFormatter(formatter) handler1.setLevel(logging.NOTSET) _LOGGER.addHandler(handler1) else: formatter2 = \ logging.Formatter('%(filename)s %(levelname)-8s - %(message)s') #logging.Formatter('%(levelname)s %(asctime)s %(filename)s - %(message)s') handler2 = logging.handlers.SysLogHandler(address = '/dev/log') handler2.setFormatter(formatter2) handler2.setLevel(logging.NOTSET) _LOGGER.addHandler(handler2) if level == 'debug': _LOGGER.setLevel(logging.DEBUG) # _LOGGER.debug("The following Log levels are active:") # _LOGGER.critical(" Critical, ") # _LOGGER.error(" Error, ") # _LOGGER.warning(" Warning, ") # _LOGGER.info(" Info, ") # _LOGGER.debug(" Debug ") elif level == 'info': _LOGGER.setLevel(logging.INFO) else: _LOGGER.setLevel(logging.NOTSET) def http_get_image(gasmeter_url, gasmeter_timeout=10): try: resp = requests.get(gasmeter_url, timeout=gasmeter_timeout) http_code = resp.status_code resp.raise_for_status() #For HTTPError except requests.exceptions.ConnectTimeout: print("Could not connect to Gasmeter: Timeout") gasmeter_reachable = False return False except requests.exceptions.ConnectionError: print("Could not connect to Gasmeter: Connection Error") gasmeter_reachable = False return False except requests.exceptions.HTTPError as err: print("Hub - HTTP Error: %s", err) if http_code == 401: LOG.info("Bad username or password for Gasmeter") else: print("HTTP return code from Gasmeter %s", http_code) gasmeter_reachable = False return False except requests.exceptions.RequestException as e: print("Error on Gas Meter is: %s", e) gasmeter_reachable = False return False gasmeter_reachable = True return resp def rotate(image, angle, center = None, scale = 1.0): (h, w) = image.shape[:2] if center is None: center = (w / 2, h / 2) # Perform the rotation. Positive values rotate CCW M = cv2.getRotationMatrix2D(center, angle, scale) rotated = cv2.warpAffine(image, M, (w, h)) return rotated def find_needle(image, circ_col, circ_row, circ_rad): #The coordinates reference that we will use is that of the image # in which starts at the upper left (0,0), except that we will # work in (column,row) order rather than the image's native (row,column) order. # Start w. an all-0s blank image (same size as our image, but only 1 channel). # Draw a circle centered around the gauge center point. # Extract the pixel indices (col,row) of the drawn circle perimeter. blank = np.zeros(image.shape[:2], dtype=np.uint8) cv2.circle(blank, (circ_col, circ_row), circ_rad, 255, thickness=1) ind_row, ind_col = np.nonzero(blank) indices = list(zip(ind_col, ind_row)) #This contains the pixel coords of the drawn circle. # Get the top of the drawn circle's coordinates in (col,row) order. # We use this later as an index into a Panda's dataframe # to get at other important information. # Technically the top is located at "radius" rows above the gauge's column center. # We could assume the circle drawing tool will draw on this pixel, # but for now we'll search the drawn circle itself just in case it doesn't. top_yval = min([y for (x,y) in indices]) top_pixel = [(x, y) for (x, y) in indices if y == top_yval][0] # Translate Drawn Circle's absolute col, row cordinates # to have (0,0) referenced at Gauge Center. # This will allow us to use numpy vector math to # compute the angle between points on the circle perimeter translated = [] for (x, y) in indices: translated.append((x - circ_col, circ_row - y)) # Construct dataframe holding various coordinate representations and pixel values df = pd.DataFrame({"indices":indices, "trans": translated }) # Identify the pixel which is the topmost point of the drawn circle. # We can't assume the drawn circle starts at the top, so search the circle pixel coords. df["top_pixel"] = (df["indices"] == top_pixel) #Trick in Pandas: df.loc(row,col) # If you provide a list of booleans # (=True or False; non-string must start w. Capital)) that is the same size # as the number of rows in the dataframe, you can use the # position of "True" values as an index into the dataframe's rows. # Here the top_pixel column of the dataframe can also be used # to provide a list of booleans, and in this case, there will # only be one value that is true, and its position in the list # will be used to find the translated coordinate. # df.loc will return the row and the value at (row,col), so select # the value at (row,col) using .values[0] top_trans_pix = df.loc[df["top_pixel"], "trans"].values[0] # Compute "Angle" between top pixel vector ((0,0),top pixel) and # circle perimeter vector ((0,0), circle perimeter pixel pt) # The top pixel vector will be at 12 o'clock # Note: In numpy, if the circle perimeter vector is counter-clockwise # of the top pixel vector, the angle will be positive. angles = [] for vec in df["trans"].values: angles.append((180 / np.pi) * np.arccos(np.dot(top_trans_pix, vec) / \ (np.linalg.norm(top_trans_pix) * np.linalg.norm(vec)))) df["angle"] = angles # Compute "Clock Angle" which is computed as the "Angle" relative to 12 o'clock 0/360 degrees. # For example, since top pixel vector is same as 12 o'clock, a # circle perimeter vector that is slightly counter-clockwise to the top pixel vector # will be say +5 degrees. We want the clock angle to be 355 degrees. # Another example, if the circle perimeter vector is # slightly clockwise to the top pixel vector, say +5 degrees, we want the clock # angle to be +5 degrees. So clock angle has to determine if the # perimeter pixel of interest has a column coordinate that is negative or positive # relative to the gauge center's column coordinate. df["clock_angle"] = df["angle"] + \ (-2*df["angle"] + 360)*(df["trans"].apply(lambda x: x[0] < 0)).astype(int) # Draw lines between gauge center and perimeter pixels # and compute mean and std dev of pixels along lines stds = [] means = [] gray_values = [] #For each line to be drawn: #Start with a Blank all-0s image, same size as orginal. #Draw a line to each circle perimeter pixel and extract # line's drawn coordinates (will be non-zero). #Given the lines coordinates, find the original image's # corresponding coordinates and get the BGR values and compute gray values. # Compute mean and standard deviation for all the gray values. for (pt_col, pt_row) in df["indices"].values: blank = np.zeros(image.shape[:2], dtype=np.uint8) cv2.line(blank, (circ_col, circ_row), (pt_col, pt_row), 255, thickness=2) # Draw function wants center point in (col, row) order like coordinates ind_row, ind_col = np.nonzero(blank) b = image[:, :, 0][ind_row, ind_col] g = image[:, :, 1][ind_row, ind_col] r = image[:, :, 2][ind_row, ind_col] # Compute grayscale with naive equation. # This is done for all pixels making up the drawn line. grays = (b.astype(int) + g.astype(int) + r.astype(int))/3 stds.append(np.std(grays)) means.append(np.mean(grays)) gray_values.append(grays) #Add to Dataframe: Line's Standard Deviation, Mean, and all its Gray values df["stds"] = stds df["means"] = means df["gray_values"] = gray_values # Search DataFrame and find Line with smallest mean value. # (This will be the predicted Gauge Needle location) # The DataFrame index of this Line will also # provide the index to the corresponding needle clock angle. min_mean = df["means"].min() needle_angle = df.loc[df["means"] == min_mean, "clock_angle"].values[0] # Find needle angle return df, needle_angle def read_gauge(angle, convention): # Gauge readout according to convention if convention == "CW": readout = 10*angle/360 else: readout = 10 - (10*angle/360) #print("Readout= ", readout) #readout = round(readout,2) readout = float(np.round(readout, 2)) #print("Readout= ", readout) if readout >= 10.0: readout = 0 return readout def handle_readouts(readout_digit): #Define a tolerance value for how close a needle #has to be to a digit boundary for it to be checked for crossing. #tolerance = 0.25 #Around +/- 9 degress from a digit #tolerance = 0.50 #tolerance = 0.40 tolerance = 0.30 #Meter digits right to left are listed left to right #A few samples left here for testing purposes. #readout_digit = [0.72, 0.03, 9.97, 9.77] #readout_digit = [1.72, 2.03, 9.30, 6.90] #readout_digit = [2.59, 0.14, 0.18, 9.58] digit = [] number = 0.0 for i,v in enumerate(readout_digit): #digit.append(np.floor(readout_digit[i])) digit.append(readout_digit[i]) if i > 0: _LOGGER.debug("") _LOGGER.debug("readout digit [%i] is %.2f", i, readout_digit[i] ) if (np.ceil(readout_digit[i]) - readout_digit[i]) < tolerance: #Note: if readout_digit[i] is 1.00, np.ceiling(1.00) is also 1.00 _LOGGER.debug(" Between digits within tolerance in UPPER portion.") _LOGGER.debug(" Has it crossed a digit boundary? Check w. previous digit") _LOGGER.debug(" Previous digit is %.2f", digit[i-1]) if (digit[i-1] >= 0 and digit[i-1]) < 5.0: _LOGGER.debug(" Previous digit >= 0 && <5.") _LOGGER.debug(" This digit has crossed a digit boundary. Rounding UP") #Note Boundary Condition - Upper Portion # if digit[i] is 1.00 exactly, np.ceiling(1.00) is 1.00. # No need to round up/down further. digit[i] = np.ceil(readout_digit[i]) if digit[i] >= 10.0: digit[i] = 0.0 else: _LOGGER.debug(" No it has not crossed digit boundary. Rounding Down as normal") digit[i] = np.floor(readout_digit[i]) #Note Boundary Condition - Upper Portion at x.00 # Ex. readout_digit[i] = 1.00, np.floor(1.00) will also be 1.00. # So if it has not crossed digit boundary, np.floor will not round down. if (readout_digit[i] == np.floor(readout_digit[i]) ): digit[i] = digit[i] -1 else: if (readout_digit[i] - np.floor(readout_digit[i]) ) < tolerance: _LOGGER.debug(" Between digits within tolerance in LOWER Portion.") _LOGGER.debug(" Did it actually cross a digit boundary? Check with previous digit") _LOGGER.debug(" Previous digit is %.2f", digit[i-1]) if digit[i-1] >= 5.0 : _LOGGER.debug(" Previous digit >= 5. This digit has NOT yet crossed a digit. Rounding DOWN -1") #Note Boundary Condition - Lower Portion # if readout_digit = 1.00, np.floor(1.00) is 1.00. digit[i] = np.floor(readout_digit[i]) -1 if digit[i] < 0.0: digit[i] = 9.0 else: _LOGGER.debug(" Yes it did cross boundary. Rounding Down as normal") digit[i] = np.floor(readout_digit[i]) else: _LOGGER.debug(" OK as is. Rounding Down as normal") digit[i] = np.floor(readout_digit[i]) else: _LOGGER.debug("readout digit[0] is %.2f" % readout_digit[0] ) #digit[i] = np.floor(readout_digit[i]) digit[i] = readout_digit[i] number = number + digit[i]*10**(i) _LOGGER.debug(" digit[%i] is determined to be %.2f", i, digit[i]) #_LOGGER.debug("Final number is %.2f", number) return number #Start of Main program _LOGGER.info("Starting Gas Meter Analyzer") _LOGGER.debug("Getting camera image via HTTP GET....") #gasmeter_url = 'http://' + gasmeter_camera_ip + '/gasmeter_crop.jpg' gasmeter_url = 'http://' + gasmeter_camera_ip + image_url_postfix response = http_get_image(gasmeter_url,60) if (response != False): _LOGGER.debug(" http response is: %s", response) #print('body is ', response.text) #don't do this for images if ( gasmeter_url.endswith('.jpg') ): with open(data_path + 'image1_retrieved.jpg', 'wb') as f: f.write(response.content) image = cv2.imread(data_path + 'image1_retrieved.jpg') elif ( gasmeter_url.endswith('.png') ): with open(data_path + 'image1_retrieved.png', 'wb') as f: f.write(response.content) image = cv2.imread(data_path + 'image1_retrieved.png') elif ( gasmeter_url.endswith('.npy') ): io_buf = io.BytesIO(response.content) rgb_image = np.load(io_buf) #Assume retrieved file was saved in RGB order. image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR) cv2.imwrite(data_path + 'image1_retrieved.png', image) else: _LOGGER.error("Specified File extension unsupported") _LOGGER.debug("Rotating Image .....") imcopy_pre_rot = image.copy() imcopy = rotate(imcopy_pre_rot, ROTATE_IMAGE ) cv2.imwrite(data_path + 'image2_rotated.jpg', imcopy) circ_radius = CIRCLE_RADIUS _LOGGER.debug("Computing Gauge Angles and Values .....") readout_digit = [] # For each gauge, get gauge readout and visualize results for i, ((c, r), convention) in enumerate(zip(gauge_centers, readout_conventions)): # Find needle angle df, needle_angle = find_needle(image=image, circ_col=c, circ_row=r, circ_rad = circ_radius) # # Draw gauge needle radial line and circle onto the copy of original image. # (pt_col,pt_row) is coordinates for circle point the needle was found to point to # (pt_col, pt_row) = df.loc[df["clock_angle"] == needle_angle, "indices"].values[0] # Draw tiny Green circle for radial line start. Note: center point in (col, row) order cv2.circle(imcopy, (c, r), 5, (0, 255, 0), thickness=3) # Draw Green needle radial line itself cv2.line(imcopy, (c, r), (pt_col, pt_row), (0, 255, 0), thickness=2) # Draw Red circle cv2.circle(imcopy, (c, r), circ_radius, (0,0,255), thickness=4) # Gauge readout according to convention readout_digit.append( read_gauge(needle_angle, convention) ) _LOGGER.debug(" Gauge #%i angle is %.2f reading is %.2f", i+1, needle_angle, readout_digit[i] ) #Save to disk the image copy of original with drawn needle radial lines and circles cv2.imwrite(data_path + 'image3_pre_subplot.jpg', imcopy) #Create a plot showing y=row, x=columns of pre_subplot image plot_imcopy = cv2.cvtColor(imcopy, cv2.COLOR_BGR2RGB) fig, ax = plt.subplots(figsize=(18, 6)) ax.imshow(plot_imcopy) #plt.imsave('gauges_readout.png', plot_imcopy) #This writes the image w/o axis plt.savefig(data_path + 'gauges_readout.jpg') #This writes the image w. axis. _LOGGER.debug("Convert Gauge readout values to a single value number...") meter_value = handle_readouts(readout_digit) meter_value = np.round(meter_value, 2) _LOGGER.info("Meter value is %f", meter_value ) #Compare current value with previous. # To avoid a problem encountered a couple of times # when using floating point, we'll convert to int. int_meter_value = int(meter_value * 100 ) file = Path(data_path + 'last_read.txt') if (file.is_file() ): with open(data_path + 'last_read.txt', 'r+') as g: #rd/wr last_value = int(g.read()) _LOGGER.debug("Reading last_read.txt. Value: %i" , last_value) if (last_value > int_meter_value): _LOGGER.warning("Previously read value:%i > just read value:%i. Not using meter value.",last_value, int_meter_value) else: _LOGGER.debug("Previous value:%i vs curent value:%i ... check passes. Updating last_read.txt", last_value, int_meter_value) g.seek(0) #start at file beginning g.write(str(int_meter_value)) #if (len(broker_auth) == 0): # broker_auth = None _LOGGER.debug("Publishing to MQTT broker") publish.single(topic=topic, payload=meter_value, retain=retain, \ hostname=host_name,client_id=client_name,\ auth=broker_auth) else: _LOGGER.warning("last_read.txt does not exist. Creating it.") with open(data_path + 'last_read.txt', 'w') as g: g.write(str(int_meter_value)) else: _LOGGER.warning("HTTP response is false. Could not get camera image. Exiting")
[ "logging.getLogger", "logging.StreamHandler", "io.BytesIO", "numpy.linalg.norm", "logging.handlers.SysLogHandler", "numpy.mean", "pathlib.Path", "cv2.line", "numpy.dot", "pandas.DataFrame", "paho.mqtt.publish.single", "numpy.round", "numpy.ceil", "cv2.warpAffine", "matplotlib.pyplot.save...
[((2055, 2082), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (2072, 2082), False, 'import logging\n'), ((591, 611), 'yaml.safe_load', 'yaml.safe_load', (['file'], {}), '(file)\n', (605, 611), False, 'import yaml\n'), ((2121, 2153), 'logging.Formatter', 'logging.Formatter', (['"""%(message)s"""'], {}), "('%(message)s')\n", (2138, 2153), False, 'import logging\n'), ((2226, 2259), 'logging.StreamHandler', 'logging.StreamHandler', (['sys.stdout'], {}), '(sys.stdout)\n', (2247, 2259), False, 'import logging\n'), ((2401, 2464), 'logging.Formatter', 'logging.Formatter', (['"""%(filename)s %(levelname)-8s - %(message)s"""'], {}), "('%(filename)s %(levelname)-8s - %(message)s')\n", (2418, 2464), False, 'import logging\n'), ((2562, 2612), 'logging.handlers.SysLogHandler', 'logging.handlers.SysLogHandler', ([], {'address': '"""/dev/log"""'}), "(address='/dev/log')\n", (2592, 2612), False, 'import logging\n'), ((4487, 4532), 'cv2.getRotationMatrix2D', 'cv2.getRotationMatrix2D', (['center', 'angle', 'scale'], {}), '(center, angle, scale)\n', (4510, 4532), False, 'import cv2\n'), ((4547, 4579), 'cv2.warpAffine', 'cv2.warpAffine', (['image', 'M', '(w, h)'], {}), '(image, M, (w, h))\n', (4561, 4579), False, 'import cv2\n'), ((5111, 5152), 'numpy.zeros', 'np.zeros', (['image.shape[:2]'], {'dtype': 'np.uint8'}), '(image.shape[:2], dtype=np.uint8)\n', (5119, 5152), True, 'import numpy as np\n'), ((5158, 5225), 'cv2.circle', 'cv2.circle', (['blank', '(circ_col, circ_row)', 'circ_rad', '(255)'], {'thickness': '(1)'}), '(blank, (circ_col, circ_row), circ_rad, 255, thickness=1)\n', (5168, 5225), False, 'import cv2\n'), ((5249, 5266), 'numpy.nonzero', 'np.nonzero', (['blank'], {}), '(blank)\n', (5259, 5266), True, 'import numpy as np\n'), ((6335, 6390), 'pandas.DataFrame', 'pd.DataFrame', (["{'indices': indices, 'trans': translated}"], {}), "({'indices': indices, 'trans': translated})\n", (6347, 6390), True, 'import pandas as pd\n'), ((16208, 16261), 'cv2.imwrite', 'cv2.imwrite', (["(data_path + 'image2_rotated.jpg')", 'imcopy'], {}), "(data_path + 'image2_rotated.jpg', imcopy)\n", (16219, 16261), False, 'import cv2\n'), ((17709, 17766), 'cv2.imwrite', 'cv2.imwrite', (["(data_path + 'image3_pre_subplot.jpg')", 'imcopy'], {}), "(data_path + 'image3_pre_subplot.jpg', imcopy)\n", (17720, 17766), False, 'import cv2\n'), ((17855, 17894), 'cv2.cvtColor', 'cv2.cvtColor', (['imcopy', 'cv2.COLOR_BGR2RGB'], {}), '(imcopy, cv2.COLOR_BGR2RGB)\n', (17867, 17894), False, 'import cv2\n'), ((17909, 17938), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'figsize': '(18, 6)'}), '(figsize=(18, 6))\n', (17921, 17938), True, 'import matplotlib.pyplot as plt\n'), ((18053, 18098), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(data_path + 'gauges_readout.jpg')"], {}), "(data_path + 'gauges_readout.jpg')\n", (18064, 18098), True, 'import matplotlib.pyplot as plt\n'), ((18281, 18305), 'numpy.round', 'np.round', (['meter_value', '(2)'], {}), '(meter_value, 2)\n', (18289, 18305), True, 'import numpy as np\n'), ((18574, 18607), 'pathlib.Path', 'Path', (["(data_path + 'last_read.txt')"], {}), "(data_path + 'last_read.txt')\n", (18578, 18607), False, 'from pathlib import Path\n'), ((3201, 3253), 'requests.get', 'requests.get', (['gasmeter_url'], {'timeout': 'gasmeter_timeout'}), '(gasmeter_url, timeout=gasmeter_timeout)\n', (3213, 3253), False, 'import requests\n'), ((9351, 9392), 'numpy.zeros', 'np.zeros', (['image.shape[:2]'], {'dtype': 'np.uint8'}), '(image.shape[:2], dtype=np.uint8)\n', (9359, 9392), True, 'import numpy as np\n'), ((9401, 9474), 'cv2.line', 'cv2.line', (['blank', '(circ_col, circ_row)', '(pt_col, pt_row)', '(255)'], {'thickness': '(2)'}), '(blank, (circ_col, circ_row), (pt_col, pt_row), 255, thickness=2)\n', (9409, 9474), False, 'import cv2\n'), ((9575, 9592), 'numpy.nonzero', 'np.nonzero', (['blank'], {}), '(blank)\n', (9585, 9592), True, 'import numpy as np\n'), ((10850, 10870), 'numpy.round', 'np.round', (['readout', '(2)'], {}), '(readout, 2)\n', (10858, 10870), True, 'import numpy as np\n'), ((15450, 15496), 'cv2.imread', 'cv2.imread', (["(data_path + 'image1_retrieved.jpg')"], {}), "(data_path + 'image1_retrieved.jpg')\n", (15460, 15496), False, 'import cv2\n'), ((17087, 17142), 'cv2.circle', 'cv2.circle', (['imcopy', '(c, r)', '(5)', '(0, 255, 0)'], {'thickness': '(3)'}), '(imcopy, (c, r), 5, (0, 255, 0), thickness=3)\n', (17097, 17142), False, 'import cv2\n'), ((17205, 17273), 'cv2.line', 'cv2.line', (['imcopy', '(c, r)', '(pt_col, pt_row)', '(0, 255, 0)'], {'thickness': '(2)'}), '(imcopy, (c, r), (pt_col, pt_row), (0, 255, 0), thickness=2)\n', (17213, 17273), False, 'import cv2\n'), ((17315, 17380), 'cv2.circle', 'cv2.circle', (['imcopy', '(c, r)', 'circ_radius', '(0, 0, 255)'], {'thickness': '(4)'}), '(imcopy, (c, r), circ_radius, (0, 0, 255), thickness=4)\n', (17325, 17380), False, 'import cv2\n'), ((9932, 9945), 'numpy.std', 'np.std', (['grays'], {}), '(grays)\n', (9938, 9945), True, 'import numpy as np\n'), ((9968, 9982), 'numpy.mean', 'np.mean', (['grays'], {}), '(grays)\n', (9975, 9982), True, 'import numpy as np\n'), ((15661, 15707), 'cv2.imread', 'cv2.imread', (["(data_path + 'image1_retrieved.png')"], {}), "(data_path + 'image1_retrieved.png')\n", (15671, 15707), False, 'import cv2\n'), ((15769, 15797), 'io.BytesIO', 'io.BytesIO', (['response.content'], {}), '(response.content)\n', (15779, 15797), False, 'import io\n'), ((15818, 15833), 'numpy.load', 'np.load', (['io_buf'], {}), '(io_buf)\n', (15825, 15833), True, 'import numpy as np\n'), ((15898, 15940), 'cv2.cvtColor', 'cv2.cvtColor', (['rgb_image', 'cv2.COLOR_RGB2BGR'], {}), '(rgb_image, cv2.COLOR_RGB2BGR)\n', (15910, 15940), False, 'import cv2\n'), ((15949, 16003), 'cv2.imwrite', 'cv2.imwrite', (["(data_path + 'image1_retrieved.png')", 'image'], {}), "(data_path + 'image1_retrieved.png', image)\n", (15960, 16003), False, 'import cv2\n'), ((19438, 19567), 'paho.mqtt.publish.single', 'publish.single', ([], {'topic': 'topic', 'payload': 'meter_value', 'retain': 'retain', 'hostname': 'host_name', 'client_id': 'client_name', 'auth': 'broker_auth'}), '(topic=topic, payload=meter_value, retain=retain, hostname=\n host_name, client_id=client_name, auth=broker_auth)\n', (19452, 19567), True, 'import paho.mqtt.publish as publish\n'), ((11813, 11838), 'numpy.ceil', 'np.ceil', (['readout_digit[i]'], {}), '(readout_digit[i])\n', (11820, 11838), True, 'import numpy as np\n'), ((12646, 12671), 'numpy.ceil', 'np.ceil', (['readout_digit[i]'], {}), '(readout_digit[i])\n', (12653, 12671), True, 'import numpy as np\n'), ((12908, 12934), 'numpy.floor', 'np.floor', (['readout_digit[i]'], {}), '(readout_digit[i])\n', (12916, 12934), True, 'import numpy as np\n'), ((14444, 14470), 'numpy.floor', 'np.floor', (['readout_digit[i]'], {}), '(readout_digit[i])\n', (14452, 14470), True, 'import numpy as np\n'), ((7774, 7800), 'numpy.dot', 'np.dot', (['top_trans_pix', 'vec'], {}), '(top_trans_pix, vec)\n', (7780, 7800), True, 'import numpy as np\n'), ((13233, 13259), 'numpy.floor', 'np.floor', (['readout_digit[i]'], {}), '(readout_digit[i])\n', (13241, 13259), True, 'import numpy as np\n'), ((13367, 13393), 'numpy.floor', 'np.floor', (['readout_digit[i]'], {}), '(readout_digit[i])\n', (13375, 13393), True, 'import numpy as np\n'), ((14290, 14316), 'numpy.floor', 'np.floor', (['readout_digit[i]'], {}), '(readout_digit[i])\n', (14298, 14316), True, 'import numpy as np\n'), ((7816, 7845), 'numpy.linalg.norm', 'np.linalg.norm', (['top_trans_pix'], {}), '(top_trans_pix)\n', (7830, 7845), True, 'import numpy as np\n'), ((7848, 7867), 'numpy.linalg.norm', 'np.linalg.norm', (['vec'], {}), '(vec)\n', (7862, 7867), True, 'import numpy as np\n'), ((14019, 14045), 'numpy.floor', 'np.floor', (['readout_digit[i]'], {}), '(readout_digit[i])\n', (14027, 14045), True, 'import numpy as np\n')]
import copy import torch import numpy as np from torchvision.transforms import Compose from pytorch3d.transforms import RotateAxisAngle, Rotate, random_rotations _TRANSFORM_DICT = {} def register_transform(name): def decorator(cls): _TRANSFORM_DICT[name] = cls return cls return decorator def get_transform(cfg): if cfg is None or len(cfg) == 0: return None tfms = [] for t_dict in cfg: t_dict = copy.deepcopy(t_dict) cls = _TRANSFORM_DICT[t_dict.pop('type')] tfms.append(cls(**t_dict)) return Compose(tfms) @register_transform('rotation') class RandomRotation(object): def __init__(self, rot_type): super().__init__() assert rot_type is None or rot_type in ('x', 'y', 'z', 'so3') self.rot_type = rot_type def __call__(self, data): points = data['point'].unsqueeze(0) if self.rot_type in ('x', 'y', 'z'): trot = RotateAxisAngle(angle=torch.rand(points.shape[0])*360, axis=self.rot_type.upper(), degrees=True) elif self.rot_type == 'so3': trot = Rotate(R=random_rotations(points.shape[0])) else: return data points = trot.transform_points(points) # (1, N, 3) data['point'] = points[0] return data @register_transform('dropout') class RandomPointDropout(object): def __init__(self, max_dropout_ratio=0.875): super().__init__() self.max_dropout_ratio = max_dropout_ratio def __call__(self, data): point = data['point'].clone() # (N, 3) dropout_ratio = np.random.random() * self.max_dropout_ratio drop_idx = np.where(np.random.random([point.size(0)]) <= dropout_ratio)[0] if len(drop_idx) > 0: point[drop_idx] = point[0].clone() data['point'] = point return data @register_transform('scale') class RandomScalePointCloud(object): def __init__(self, scale_low=0.8, scale_high=1.25): super().__init__() self.scale_low = scale_low self.scale_high = scale_high def __call__(self, data): scale = np.random.uniform(self.scale_low, self.scale_high) data['point'] = data['point'] * scale return data @register_transform('shift') class RandomShiftPointCloud(object): def __init__(self, shift_range=0.1): super().__init__() self.shift_range = shift_range def __call__(self, data): shift = torch.FloatTensor(np.random.uniform(-self.shift_range, self.shift_range, size=[1, 3])) data['point'] = data['point'] + shift return data @register_transform('jitter') class JitterPointCloud(object): def __init__(self, sigma, clip): super().__init__() self.sigma = sigma self.clip = clip def __call__(self, data): noise = torch.clamp(torch.randn_like(data['point']) * self.sigma, min=-self.clip, max=+self.clip) data['point'] = data['point'] + noise return data
[ "pytorch3d.transforms.random_rotations", "copy.deepcopy", "numpy.random.random", "torch.randn_like", "numpy.random.uniform", "torchvision.transforms.Compose", "torch.rand" ]
[((572, 585), 'torchvision.transforms.Compose', 'Compose', (['tfms'], {}), '(tfms)\n', (579, 585), False, 'from torchvision.transforms import Compose\n'), ((454, 475), 'copy.deepcopy', 'copy.deepcopy', (['t_dict'], {}), '(t_dict)\n', (467, 475), False, 'import copy\n'), ((2141, 2191), 'numpy.random.uniform', 'np.random.uniform', (['self.scale_low', 'self.scale_high'], {}), '(self.scale_low, self.scale_high)\n', (2158, 2191), True, 'import numpy as np\n'), ((1612, 1630), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (1628, 1630), True, 'import numpy as np\n'), ((2499, 2566), 'numpy.random.uniform', 'np.random.uniform', (['(-self.shift_range)', 'self.shift_range'], {'size': '[1, 3]'}), '(-self.shift_range, self.shift_range, size=[1, 3])\n', (2516, 2566), True, 'import numpy as np\n'), ((2874, 2905), 'torch.randn_like', 'torch.randn_like', (["data['point']"], {}), "(data['point'])\n", (2890, 2905), False, 'import torch\n'), ((976, 1003), 'torch.rand', 'torch.rand', (['points.shape[0]'], {}), '(points.shape[0])\n', (986, 1003), False, 'import torch\n'), ((1116, 1149), 'pytorch3d.transforms.random_rotations', 'random_rotations', (['points.shape[0]'], {}), '(points.shape[0])\n', (1132, 1149), False, 'from pytorch3d.transforms import RotateAxisAngle, Rotate, random_rotations\n')]
import os import tensorflow as tf import matplotlib.pyplot as plt import random import pandas as pd import numpy as np import keras.initializers import keras.optimizers from networkx import Graph, find_cliques from sklearn.metrics import roc_curve, auc from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization from keras.layers.core import Dense, Dropout, Reshape from keras.models import load_model, model_from_json, model_from_yaml, Model from keras.utils.vis_utils import plot_model from keras.callbacks import TensorBoard from .datasets import DataSet from .importing_modules import * class NeuralNetworkConfig: def __init__(self, categorical_input: str="cat_input", continuous_input: str="cont_input", output: str="output", reshaped_output: str="reshaped_output", noisy_layer: str="noisy", kernel_initializer: str="uniform", hidden: str = "hidden", reshaped: str="reshaped", dropout: str="dropout", merge: str="merge", activation: str="relu", output_activation: str="sigmoid", batch_normalization: bool=False): self.kernel_initializer = kernel_initializer self.activation = activation self.output_activation = output_activation self.cont_input = continuous_input self.cat_input = categorical_input self.hidden = hidden self.noisy_layer = noisy_layer self.reshaped = reshaped self.merge = merge self.dropout = dropout self.output = output self.reshaped_output = reshaped_output self.batch_normalization = batch_normalization class NeuralNetwork: def __init__(self, model): self.__model = model def get_model(self): return self.__model @classmethod def from_file(cls, from_file: str): model = load_model(from_file) return cls(model) def get_layer(self, name): return self.__model.get_layer(name) def get_weights(self): return self.__model.get_weights() def set_weights(self, weights): self.__model.set_weights(weights) def get_weights_for_layer(self, feature): return self.__model.get_layer(feature).get_weights() def get_weights_with_name(self): model = self.__model names = [layer.name for layer in model.layers] weights = [] for name in names: weights.append(model.get_layer(name).get_weights()) return dict(zip(names, weights)) def set_weights_by_name(self, weights): for name, weight in weights.items(): self.__model.get_layer(name).set_weights(weight) def save_plot(self, to_file='model_plot.svg', shapes=False, layer_names=False): if to_file: plot_model(self.__model, to_file=to_file, show_shapes=shapes, show_layer_names=layer_names) def compile(self, loss='binary_crossentropy', lr=0.001): optimizer=keras.optimizers.Adam(lr=lr) self.__model.compile(loss=loss, optimizer=optimizer, metrics=['accuracy']) def export(self, to_file): if to_file: name, ext = os.path.splitext(to_file) if ext == '.h5': self.__model.save(to_file) elif ext == '.json': model_json = self.__model.to_json() with(to_file, 'w') as json_file: json_file.write(model_json) elif ext == '.yaml': model_yaml = self.__model.to_yaml() with(to_file, 'w') as yaml_file: yaml_file.write(model_yaml) class DenseNeuralNetwork(NeuralNetwork): @classmethod def from_scratch(cls, config: NeuralNetworkConfig, dataset, hidden_units: int, embedding_size: int = 10, dropout_rate: float = 0.0, output_units=1, embedding_layers_trainable=True): categorical_data = dataset.get_data(without_resulting_feature=True).select_dtypes(include='category') continuous_features = dataset.get_data(without_resulting_feature=True).select_dtypes( exclude='category').columns.size if isinstance(categorical_data, pd.DataFrame): categorical_data_categories = {} for column in categorical_data: categorical_data_categories[column] = categorical_data[column].cat.categories.size categorical_data = categorical_data_categories model = DenseNeuralNetwork._build(config, categorical_data, continuous_features, hidden_units, embedding_size, dropout_rate, output_units, embedding_layers_trainable) return cls(model) @staticmethod def _build(config, categorical_data_categories, continuous_features: int, hidden_units: int, embedding_size: int, dropout_rate, output_units: int, embedding_layers_trainable): # create input layer for continuous data continuous_input = Input(shape=(continuous_features,), name=config.cont_input) reshaped_continuous_input = Reshape((1, continuous_features), name=config.reshaped)(continuous_input) # create input layers complemented by embedding layers to handle categorical features embedding_layers = [] categorical_inputs = [] for feature, size in categorical_data_categories.items(): categorical_input = Input((1,), name=config.cat_input + "_" + feature) categorical_inputs.append(categorical_input) embedding_layer = Embedding(size, embedding_size, name=feature, trainable=embedding_layers_trainable)( categorical_input) embedding_layers.append(embedding_layer) # merge all inputs merge_layer = Concatenate(name=config.merge)(embedding_layers + [reshaped_continuous_input]) # hidden layers hidden_layer = Dense(hidden_units, kernel_initializer=config.kernel_initializer, name=config.hidden)(merge_layer) if config.batch_normalization: hidden_layer = BatchNormalization()(hidden_layer) hidden_layer = Activation(config.activation)(hidden_layer) dropout_layer = Dropout(dropout_rate, name=config.dropout)(hidden_layer) # output_layer output_layer = Dense(output_units, name=config.output)(dropout_layer) output_layer = Activation(config.output_activation)(output_layer) # add reshape layer since output should be vector output_layer = Reshape((1,), name=config.reshaped_output)(output_layer) # create final model model = Model(inputs=categorical_inputs + [continuous_input], outputs=output_layer) return model class OptimizedNeuralNetwork(NeuralNetwork): @classmethod def from_scratch(cls, config: NeuralNetworkConfig, dataset: DataSet, correlation_info: list, embedding_size: int=10, dropout_rate: float=0.0, output_units=1): flatten_correlation = [item for sublist in correlation_info for item in sublist] features = dataset.get_data(without_resulting_feature=True).columns if not all(elem in features for elem in flatten_correlation): return None diff = list(set(features) - set(flatten_correlation)) diff = [[item] for item in diff] correlation_info.extend(diff) categorical_data = dataset.get_data(without_resulting_feature=True).select_dtypes(include='category') continuous_features = dataset.get_data(without_resulting_feature=True).select_dtypes(exclude='category').columns if isinstance(categorical_data, pd.DataFrame): categorical_data_categories = {} for column in categorical_data: categorical_data_categories[column] = categorical_data[column].cat.categories.size categorical_data = categorical_data_categories model = OptimizedNeuralNetwork._build(config, categorical_data, continuous_features, correlation_info, embedding_size, dropout_rate, output_units) return cls(model) @staticmethod def _build(config: NeuralNetworkConfig, categorical_data_categories: dict, continuous_features: list, correlation_info: list,embedding_size: int, dropout_rate: float, output_units: int): feature_layers = {} hidden_layers = [] inputs = [] for feature, size in categorical_data_categories.items(): categorical_input = Input((1,), name=config.cat_input + "_" + feature) inputs.append(categorical_input) embedding_layer = Embedding(size, embedding_size, name=feature)(categorical_input) feature_layers[feature] = embedding_layer for feature in continuous_features: continuous_input = Input((1,), name=config.cont_input + "_" + feature) inputs.append(continuous_input) reshaped_continuous_input = Reshape((1, 1), name=feature)(continuous_input) feature_layers[feature] = reshaped_continuous_input for couple in correlation_info: coupled_layers = [feature_layers[feature] for feature in couple] if len(couple) > 1: merge_layer = Concatenate()(coupled_layers) hidden_layer = Dense(1, kernel_initializer=config.kernel_initializer)(merge_layer) if config.batch_normalization: hidden_layer = BatchNormalization()(hidden_layer) hidden_layer = Activation(config.activation)(hidden_layer) else: hidden_layer = Dense(1, kernel_initializer=config.kernel_initializer)(coupled_layers[0]) if config.batch_normalization: hidden_layer = BatchNormalization()(hidden_layer) hidden_layer = Activation(config.activation)(hidden_layer) hidden_layers.append(hidden_layer) merge_layer = Concatenate()(hidden_layers) dropout_layer = Dropout(dropout_rate, name=config.dropout)(merge_layer) # output_layer output_layer = Dense(1, name=config.output)(dropout_layer) output_layer = Activation(config.output_activation)(output_layer) # add reshape layer since output should be vector output_layer = Reshape((output_units,), name=config.reshaped_output)(output_layer) # create final model model = Model(inputs=inputs, outputs=output_layer) return model class Trainer: def __init__(self, nnet: NeuralNetwork, training_dataset, training_target, batch_size=32, epochs=1000): self.__nnet = nnet self.__training_dataset = training_dataset self.__training_target = training_target self.__batch_size = batch_size self.__epochs = epochs self.__score = None self._preprocess_dataset() def _preprocess_dataset(self): categorical_data = DataSet.dataframe_to_series(self.__training_dataset.get_data(without_resulting_feature=True).select_dtypes(include='category')) if isinstance(self.__nnet, OptimizedNeuralNetwork): continuous_data = DataSet.dataframe_to_series(self.__training_dataset.get_data(without_resulting_feature=True).select_dtypes(exclude='category')) self.__training_dataset = [*categorical_data, *continuous_data] else: continuous_data = self.__training_dataset.get_data().select_dtypes(exclude='category').values self.__training_dataset = [*categorical_data, continuous_data] def train(self, verbose=1): tensorboard = TensorBoard(log_dir="./logs") self.__nnet.get_model().fit(self.__training_dataset, self.__training_target, batch_size=self.__batch_size, epochs=self.__epochs, verbose=verbose, shuffle=False, callbacks=[tensorboard]) def evaluate(self, verbose=1): self.__score = self.__nnet.get_model().evaluate(self.__training_dataset, self.__training_target, batch_size=self.__batch_size, verbose=verbose) def get_score(self): return self.__score class Predictor: def __init__(self, nnet: NeuralNetwork, dataset: DataSet): self._nnet = nnet self._dataset = dataset self._score = {} self._prediction = [] self._preprocess() def _preprocess(self): categorical_data = DataSet.dataframe_to_series(self._dataset.get_data().select_dtypes(include='category')) if isinstance(self._nnet, OptimizedNeuralNetwork): continuous_data = DataSet.dataframe_to_series(self._dataset.get_data().select_dtypes(exclude='category')) self._dataset = [*categorical_data, *continuous_data] else: continuous_data = self._dataset.get_data().select_dtypes(exclude='category').values self._dataset = [*categorical_data, continuous_data] def predict(self): self._prediction = self._nnet.get_model().predict(self._dataset).flatten() return self._prediction def evaluate(self, real_values, show_plot: bool = False): if len(self._prediction) > 0: rounded_pred = np.round(self._prediction) tp = np.sum(np.logical_and(rounded_pred == 1, real_values == 1)) tn = np.sum(np.logical_and(rounded_pred == 0, real_values == 0)) fp = np.sum(np.logical_and(rounded_pred == 1, real_values == 0)) fn = np.sum(np.logical_and(rounded_pred == 0, real_values == 1)) accuracy = (tp + tn) / (tp + fp + fn + tn) self._score['ppv'] = tp / (tp + fp) self._score['npv'] = tn / (tn + fn) self._score['recall'] = tp / (tp + fn) self._score['specificity'] = tn / (tn + fp) self._score['accuracy'] = accuracy self._score['tp'] = tp self._score['tn'] = tn self._score['fp'] = fp self._score['fn'] = fn if show_plot: self._roc(real_values, np.unique(real_values).size) def _roc(self, real_values, n_classes): fpr = dict() tpr = dict() roc_auc = dict() for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(real_values, self._prediction) roc_auc[i] = auc(fpr[i], tpr[i]) plt.figure() lw = 1 plt.plot(fpr[1], tpr[1], color='darkorange', lw=lw, label='AUC = %0.2f' % roc_auc[1]) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.0]) plt.xlabel('Ложно-положительные решения') plt.ylabel('Истино-положительные решения') plt.title('Кривая ошибок') plt.legend(loc="lower right") plt.show() def get_score(self): return self._score def get_prediction(self): return self._prediction class FeatureSelector: def __init__(self, config: NeuralNetworkConfig, nnet: DenseNeuralNetwork, training_dataset): self._source_model = nnet self._config = config self._training_dataset = training_dataset categorical_columns = training_dataset.get_data(without_resulting_feature=True).select_dtypes(include='category').columns self._weights = self._source_model.get_weights_with_name() self._cat_input_shape = self._source_model.get_layer(config.cat_input + "_" + categorical_columns[0]).get_input_shape_at(0) self._cont_input_shape = self._source_model.get_layer(config.cont_input).get_input_shape_at(0)[-1] self._hid_size = self._source_model.get_layer(config.hidden).get_output_shape_at(0)[-1] self._emb_size = self._source_model.get_layer(categorical_columns[0]).get_output_shape_at(0)[-1] self._dropout_rate = self._source_model.get_layer(config.dropout).get_config()['rate'] self._cat_data = {} for x in categorical_columns: self._cat_data[x] = self._source_model.get_layer(x).get_config()["input_dim"] - 1 def _build_network(self, config, dataset, full_copy: bool = False): noisy_model = DenseNeuralNetwork.from_scratch(config=config, dataset=dataset, hidden_units=self._hid_size, embedding_size=self._emb_size, dropout_rate=self._dropout_rate,embedding_layers_trainable=False) return noisy_model def run(self, training_dataset, training_target, test_dataset, test_target, noise_rate=0.01, training_epochs=100, batch_size=8, lr=0.001): training_dataset = DataSet.copy(training_dataset) test_dataset = DataSet.copy(test_dataset) predictor = Predictor(self._source_model, test_dataset) prediction = predictor.predict() predictor.evaluate(test_target) prev_accuracy = predictor.get_score()['accuracy'] curr_accuracy = predictor.get_score()['accuracy'] features_to_remove = [] # noise_rate = random.uniform(0, noise_rate) while curr_accuracy >= prev_accuracy: for column in training_dataset.get_data().columns: if test_dataset.get_data()[column].dtype.name == 'category': noisy_dataset = DataSet.copy(test_dataset) noisy_dataset.add_noise_to_categorical_columns(column, noise_rate) noisy_model = self._source_model predictor = Predictor(noisy_model, noisy_dataset) else: noisy_dataset = DataSet.copy(test_dataset) noisy_dataset.add_noise_to_column(column, noise_rate) noisy_model = self._source_model predictor = Predictor(noisy_model, noisy_dataset) noisy_prediction = predictor.predict() sensitivity = abs(np.sum(noisy_prediction) - np.sum(prediction)) / len(noisy_prediction) test_dataset.get_features().set_sensitivity(column, sensitivity) training_dataset.get_features().set_sensitivity(column, sensitivity) print("Sensitivity of %s: %f" % (column, training_dataset.get_features().get_sensitivity(column))) less_sensitive_feature = test_dataset.get_features().get_less_sensitive_feature() features_to_remove.append(less_sensitive_feature) test_dataset.rm_less_sensitive() training_dataset.rm_less_sensitive() emb_weights = {feature: self._weights[feature] for feature in training_dataset.get_data().select_dtypes(include='category').columns.tolist()} self._source_model = self._build_network(self._config, training_dataset) self._source_model.compile(lr=lr) self._source_model.set_weights_by_name(emb_weights) trainer = Trainer(self._source_model, training_dataset, training_target, epochs=training_epochs, batch_size=batch_size) trainer.train() trainer.evaluate() self._weights = self._source_model.get_weights_with_name() predictor = Predictor(self._source_model, test_dataset) prediction = predictor.predict() predictor.evaluate(test_target) prev_accuracy, curr_accuracy = curr_accuracy, predictor.get_score()['accuracy'] print(prev_accuracy) print(curr_accuracy) return features_to_remove[:-1] class CorrelationAnalyzer: def __init__(self, config: NeuralNetworkConfig, nnet: DenseNeuralNetwork, training_dataset): self._source_model = nnet self._config = config self._training_dataset = training_dataset self._columns = self._training_dataset.get_data().columns categorical_columns = training_dataset.get_data(without_resulting_feature=True).select_dtypes( include='category').columns self._weights = None self._emb_weights = None self._cat_input_shape = self._source_model.get_layer(config.cat_input + "_" + categorical_columns[0]).get_input_shape_at(0) self._cont_input_shape = self._source_model.get_layer(config.cont_input).get_input_shape_at(0)[-1] self._hid_size = self._source_model.get_layer(config.hidden).get_output_shape_at(0)[-1] self._emb_size = self._source_model.get_layer(categorical_columns[0]).get_output_shape_at(0)[-1] self._dropout_rate = self._source_model.get_layer(config.dropout).get_config()['rate'] self._table = np.empty([len(categorical_columns)+self._cont_input_shape+1, len(categorical_columns)+self._cont_input_shape+1]) self._cat_data = {} for x in categorical_columns: self._cat_data[x] = self._source_model.get_layer(x).get_config()["input_dim"] - 1 def _build_network(self, config, dataset, full_copy: bool = False): noisy_model = DenseNeuralNetwork.from_scratch(config=config, dataset=dataset, hidden_units=self._hid_size, embedding_size=self._emb_size, dropout_rate=self._dropout_rate,embedding_layers_trainable=False) if not full_copy: noisy_model.set_weights_by_name(self._emb_weights) else: noisy_model.set_weights_by_name(self._weights) return noisy_model def run(self, test_dataset, training_dataset, training_target, noise_rate=0.01, training_epochs=100, batch_size=32, lr=0.03): training_dataset = DataSet.copy(training_dataset) trainer = Trainer(self._source_model, training_dataset, training_target, epochs=training_epochs) trainer.train() trainer.evaluate() self._weights = self._source_model.get_weights_with_name() self._emb_weights = {feature: self._weights[feature] for feature in list(self._cat_data.keys())} predictor = Predictor(self._source_model, test_dataset) self._table[0][0] = np.sum(predictor.predict()) # noise_rate = random.uniform(0, noise_rate) for idx, column in enumerate(self._columns): if training_dataset.get_data()[column].dtype.name == 'category': noisy_dataset = DataSet.copy(training_dataset) noisy_dataset.add_noise_to_categorical_columns(column, noise_rate) noisy_model = self._build_network(self._config, training_dataset) noisy_model.compile(lr=lr) trainer = Trainer(noisy_model, noisy_dataset, training_target, epochs=training_epochs, batch_size=batch_size) trainer.train() trainer.evaluate() predictor = Predictor(noisy_model, test_dataset) else: noisy_dataset = DataSet.copy(training_dataset) noisy_dataset.add_noise_to_column(column, noise_rate) noisy_model = self._build_network(self._config, training_dataset) noisy_model.compile(lr=lr) trainer = Trainer(noisy_model,noisy_dataset, training_target, epochs=training_epochs, batch_size=batch_size) trainer.train() trainer.evaluate() predictor = Predictor(noisy_model, test_dataset) noisy_prediction = predictor.predict() self._table[0][idx+1] = abs(np.sum(noisy_prediction) - self._table[0][0]) / len(noisy_prediction) for idx, column in enumerate(self._columns): if test_dataset.get_data()[column].dtype.name == 'category': noisy_dataset = DataSet.copy(test_dataset) noisy_dataset.add_noise_to_categorical_columns(column, noise_rate) noisy_model = self._source_model predictor = Predictor(noisy_model, test_dataset) else: noisy_dataset = DataSet.copy(test_dataset) noisy_dataset.add_noise_to_column(column, noise_rate) noisy_model = self._source_model predictor = Predictor(noisy_model, noisy_dataset) noisy_prediction = predictor.predict() self._table[idx + 1][0] = abs(np.sum(noisy_prediction) - self._table[0][0]) / len(noisy_prediction) for c in range(len(self._cat_data)+self._cont_input_shape): for idx in range(len(self._cat_data)+self._cont_input_shape): self._table[idx+1][c+1] = abs(self._table[idx+1][0] - self._table[0][c+1]) self._table = np.delete(self._table, 0, 0) self._table = np.delete(self._table, 0, 1) self._table = pd.DataFrame(data=self._table, index=self._columns, columns=self._columns) self._table.loc['mean'] = self._table.mean() return self._table def select_candidates(self): candidates = pd.DataFrame(columns=self._columns) fcandidates = [] for column in self._table: candidates[column] = pd.Series((self._table.loc[self._table[column] > self._table[column]['mean']]).index) for column in candidates: for row in range(candidates.shape[0]): if candidates[column][row] == candidates[column][row] and candidates[column][row] != column: if column in candidates[candidates[column][row]].tolist(): fcandidates.append([column, candidates[column][row]]) [l.sort() for l in fcandidates] fcandidates = [l for l in fcandidates if fcandidates.count(l) == 2] fcandidates = [tuple(x) for x in set(tuple(x) for x in fcandidates)] correlation_graph = Graph() correlation_graph.add_edges_from(fcandidates) fcandidates = list(find_cliques(correlation_graph)) return fcandidates
[ "networkx.find_cliques", "matplotlib.pyplot.ylabel", "sklearn.metrics.auc", "keras.utils.vis_utils.plot_model", "sklearn.metrics.roc_curve", "keras.layers.Activation", "keras.layers.core.Reshape", "numpy.delete", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "keras.models.Model", "kera...
[((1841, 1862), 'keras.models.load_model', 'load_model', (['from_file'], {}), '(from_file)\n', (1851, 1862), False, 'from keras.models import load_model, model_from_json, model_from_yaml, Model\n'), ((4958, 5017), 'keras.layers.Input', 'Input', ([], {'shape': '(continuous_features,)', 'name': 'config.cont_input'}), '(shape=(continuous_features,), name=config.cont_input)\n', (4963, 5017), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((6655, 6730), 'keras.models.Model', 'Model', ([], {'inputs': '(categorical_inputs + [continuous_input])', 'outputs': 'output_layer'}), '(inputs=categorical_inputs + [continuous_input], outputs=output_layer)\n', (6660, 6730), False, 'from keras.models import load_model, model_from_json, model_from_yaml, Model\n'), ((10479, 10521), 'keras.models.Model', 'Model', ([], {'inputs': 'inputs', 'outputs': 'output_layer'}), '(inputs=inputs, outputs=output_layer)\n', (10484, 10521), False, 'from keras.models import load_model, model_from_json, model_from_yaml, Model\n'), ((11663, 11692), 'keras.callbacks.TensorBoard', 'TensorBoard', ([], {'log_dir': '"""./logs"""'}), "(log_dir='./logs')\n", (11674, 11692), False, 'from keras.callbacks import TensorBoard\n'), ((14418, 14430), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (14428, 14430), True, 'import matplotlib.pyplot as plt\n'), ((14454, 14543), 'matplotlib.pyplot.plot', 'plt.plot', (['fpr[1]', 'tpr[1]'], {'color': '"""darkorange"""', 'lw': 'lw', 'label': "('AUC = %0.2f' % roc_auc[1])"}), "(fpr[1], tpr[1], color='darkorange', lw=lw, label='AUC = %0.2f' %\n roc_auc[1])\n", (14462, 14543), True, 'import matplotlib.pyplot as plt\n'), ((14565, 14626), 'matplotlib.pyplot.plot', 'plt.plot', (['[0, 1]', '[0, 1]'], {'color': '"""navy"""', 'lw': 'lw', 'linestyle': '"""--"""'}), "([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')\n", (14573, 14626), True, 'import matplotlib.pyplot as plt\n'), ((14635, 14655), 'matplotlib.pyplot.xlim', 'plt.xlim', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (14643, 14655), True, 'import matplotlib.pyplot as plt\n'), ((14664, 14684), 'matplotlib.pyplot.ylim', 'plt.ylim', (['[0.0, 1.0]'], {}), '([0.0, 1.0])\n', (14672, 14684), True, 'import matplotlib.pyplot as plt\n'), ((14693, 14734), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Ложно-положительные решения"""'], {}), "('Ложно-положительные решения')\n", (14703, 14734), True, 'import matplotlib.pyplot as plt\n'), ((14743, 14785), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Истино-положительные решения"""'], {}), "('Истино-положительные решения')\n", (14753, 14785), True, 'import matplotlib.pyplot as plt\n'), ((14794, 14820), 'matplotlib.pyplot.title', 'plt.title', (['"""Кривая ошибок"""'], {}), "('Кривая ошибок')\n", (14803, 14820), True, 'import matplotlib.pyplot as plt\n'), ((14829, 14858), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (14839, 14858), True, 'import matplotlib.pyplot as plt\n'), ((14867, 14877), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (14875, 14877), True, 'import matplotlib.pyplot as plt\n'), ((24547, 24575), 'numpy.delete', 'np.delete', (['self._table', '(0)', '(0)'], {}), '(self._table, 0, 0)\n', (24556, 24575), True, 'import numpy as np\n'), ((24598, 24626), 'numpy.delete', 'np.delete', (['self._table', '(0)', '(1)'], {}), '(self._table, 0, 1)\n', (24607, 24626), True, 'import numpy as np\n'), ((24649, 24723), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'self._table', 'index': 'self._columns', 'columns': 'self._columns'}), '(data=self._table, index=self._columns, columns=self._columns)\n', (24661, 24723), True, 'import pandas as pd\n'), ((24859, 24894), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': 'self._columns'}), '(columns=self._columns)\n', (24871, 24894), True, 'import pandas as pd\n'), ((25646, 25653), 'networkx.Graph', 'Graph', ([], {}), '()\n', (25651, 25653), False, 'from networkx import Graph, find_cliques\n'), ((2765, 2860), 'keras.utils.vis_utils.plot_model', 'plot_model', (['self.__model'], {'to_file': 'to_file', 'show_shapes': 'shapes', 'show_layer_names': 'layer_names'}), '(self.__model, to_file=to_file, show_shapes=shapes,\n show_layer_names=layer_names)\n', (2775, 2860), False, 'from keras.utils.vis_utils import plot_model\n'), ((3125, 3150), 'os.path.splitext', 'os.path.splitext', (['to_file'], {}), '(to_file)\n', (3141, 3150), False, 'import os\n'), ((5054, 5109), 'keras.layers.core.Reshape', 'Reshape', (['(1, continuous_features)'], {'name': 'config.reshaped'}), '((1, continuous_features), name=config.reshaped)\n', (5061, 5109), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((5427, 5477), 'keras.layers.Input', 'Input', (['(1,)'], {'name': "(config.cat_input + '_' + feature)"}), "((1,), name=config.cat_input + '_' + feature)\n", (5432, 5477), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((5788, 5818), 'keras.layers.Concatenate', 'Concatenate', ([], {'name': 'config.merge'}), '(name=config.merge)\n', (5799, 5818), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((5915, 6005), 'keras.layers.core.Dense', 'Dense', (['hidden_units'], {'kernel_initializer': 'config.kernel_initializer', 'name': 'config.hidden'}), '(hidden_units, kernel_initializer=config.kernel_initializer, name=\n config.hidden)\n', (5920, 6005), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((6168, 6197), 'keras.layers.Activation', 'Activation', (['config.activation'], {}), '(config.activation)\n', (6178, 6197), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((6237, 6279), 'keras.layers.core.Dropout', 'Dropout', (['dropout_rate'], {'name': 'config.dropout'}), '(dropout_rate, name=config.dropout)\n', (6244, 6279), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((6341, 6380), 'keras.layers.core.Dense', 'Dense', (['output_units'], {'name': 'config.output'}), '(output_units, name=config.output)\n', (6346, 6380), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((6419, 6455), 'keras.layers.Activation', 'Activation', (['config.output_activation'], {}), '(config.output_activation)\n', (6429, 6455), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((6552, 6594), 'keras.layers.core.Reshape', 'Reshape', (['(1,)'], {'name': 'config.reshaped_output'}), '((1,), name=config.reshaped_output)\n', (6559, 6594), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((8560, 8610), 'keras.layers.Input', 'Input', (['(1,)'], {'name': "(config.cat_input + '_' + feature)"}), "((1,), name=config.cat_input + '_' + feature)\n", (8565, 8610), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((8880, 8931), 'keras.layers.Input', 'Input', (['(1,)'], {'name': "(config.cont_input + '_' + feature)"}), "((1,), name=config.cont_input + '_' + feature)\n", (8885, 8931), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((10012, 10025), 'keras.layers.Concatenate', 'Concatenate', ([], {}), '()\n', (10023, 10025), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((10065, 10107), 'keras.layers.core.Dropout', 'Dropout', (['dropout_rate'], {'name': 'config.dropout'}), '(dropout_rate, name=config.dropout)\n', (10072, 10107), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((10167, 10195), 'keras.layers.core.Dense', 'Dense', (['(1)'], {'name': 'config.output'}), '(1, name=config.output)\n', (10172, 10195), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((10234, 10270), 'keras.layers.Activation', 'Activation', (['config.output_activation'], {}), '(config.output_activation)\n', (10244, 10270), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((10366, 10419), 'keras.layers.core.Reshape', 'Reshape', (['(output_units,)'], {'name': 'config.reshaped_output'}), '((output_units,), name=config.reshaped_output)\n', (10373, 10419), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((13271, 13297), 'numpy.round', 'np.round', (['self._prediction'], {}), '(self._prediction)\n', (13279, 13297), True, 'import numpy as np\n'), ((14324, 14364), 'sklearn.metrics.roc_curve', 'roc_curve', (['real_values', 'self._prediction'], {}), '(real_values, self._prediction)\n', (14333, 14364), False, 'from sklearn.metrics import roc_curve, auc\n'), ((14390, 14409), 'sklearn.metrics.auc', 'auc', (['fpr[i]', 'tpr[i]'], {}), '(fpr[i], tpr[i])\n', (14393, 14409), False, 'from sklearn.metrics import roc_curve, auc\n'), ((24988, 25076), 'pandas.Series', 'pd.Series', (["self._table.loc[self._table[column] > self._table[column]['mean']].index"], {}), "(self._table.loc[self._table[column] > self._table[column]['mean']\n ].index)\n", (24997, 25076), True, 'import pandas as pd\n'), ((25735, 25766), 'networkx.find_cliques', 'find_cliques', (['correlation_graph'], {}), '(correlation_graph)\n', (25747, 25766), False, 'from networkx import Graph, find_cliques\n'), ((5565, 5653), 'keras.layers.Embedding', 'Embedding', (['size', 'embedding_size'], {'name': 'feature', 'trainable': 'embedding_layers_trainable'}), '(size, embedding_size, name=feature, trainable=\n embedding_layers_trainable)\n', (5574, 5653), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((6110, 6130), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (6128, 6130), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((8686, 8731), 'keras.layers.Embedding', 'Embedding', (['size', 'embedding_size'], {'name': 'feature'}), '(size, embedding_size, name=feature)\n', (8695, 8731), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((9016, 9045), 'keras.layers.core.Reshape', 'Reshape', (['(1, 1)'], {'name': 'feature'}), '((1, 1), name=feature)\n', (9023, 9045), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((13322, 13373), 'numpy.logical_and', 'np.logical_and', (['(rounded_pred == 1)', '(real_values == 1)'], {}), '(rounded_pred == 1, real_values == 1)\n', (13336, 13373), True, 'import numpy as np\n'), ((13399, 13450), 'numpy.logical_and', 'np.logical_and', (['(rounded_pred == 0)', '(real_values == 0)'], {}), '(rounded_pred == 0, real_values == 0)\n', (13413, 13450), True, 'import numpy as np\n'), ((13476, 13527), 'numpy.logical_and', 'np.logical_and', (['(rounded_pred == 1)', '(real_values == 0)'], {}), '(rounded_pred == 1, real_values == 0)\n', (13490, 13527), True, 'import numpy as np\n'), ((13553, 13604), 'numpy.logical_and', 'np.logical_and', (['(rounded_pred == 0)', '(real_values == 1)'], {}), '(rounded_pred == 0, real_values == 1)\n', (13567, 13604), True, 'import numpy as np\n'), ((9307, 9320), 'keras.layers.Concatenate', 'Concatenate', ([], {}), '()\n', (9318, 9320), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((9368, 9422), 'keras.layers.core.Dense', 'Dense', (['(1)'], {'kernel_initializer': 'config.kernel_initializer'}), '(1, kernel_initializer=config.kernel_initializer)\n', (9373, 9422), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((9584, 9613), 'keras.layers.Activation', 'Activation', (['config.activation'], {}), '(config.activation)\n', (9594, 9613), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((9677, 9731), 'keras.layers.core.Dense', 'Dense', (['(1)'], {'kernel_initializer': 'config.kernel_initializer'}), '(1, kernel_initializer=config.kernel_initializer)\n', (9682, 9731), False, 'from keras.layers.core import Dense, Dropout, Reshape\n'), ((9899, 9928), 'keras.layers.Activation', 'Activation', (['config.activation'], {}), '(config.activation)\n', (9909, 9928), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((9518, 9538), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (9536, 9538), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((9833, 9853), 'keras.layers.BatchNormalization', 'BatchNormalization', ([], {}), '()\n', (9851, 9853), False, 'from keras.layers import Concatenate, Input, Embedding, Lambda, Activation, BatchNormalization\n'), ((14116, 14138), 'numpy.unique', 'np.unique', (['real_values'], {}), '(real_values)\n', (14125, 14138), True, 'import numpy as np\n'), ((23413, 23437), 'numpy.sum', 'np.sum', (['noisy_prediction'], {}), '(noisy_prediction)\n', (23419, 23437), True, 'import numpy as np\n'), ((24221, 24245), 'numpy.sum', 'np.sum', (['noisy_prediction'], {}), '(noisy_prediction)\n', (24227, 24245), True, 'import numpy as np\n'), ((17960, 17984), 'numpy.sum', 'np.sum', (['noisy_prediction'], {}), '(noisy_prediction)\n', (17966, 17984), True, 'import numpy as np\n'), ((17987, 18005), 'numpy.sum', 'np.sum', (['prediction'], {}), '(prediction)\n', (17993, 18005), True, 'import numpy as np\n')]
import numpy as np import string import os import sys import operator from nltk import pos_tag, word_tokenize from datetime import datetime relative_path = '../../data/' def init_weight(Mi, Mo): """Initializes weights so that they are randomly distributed and have small enough values to prevent gradient descent from going crazy. Takes in input size and output size. Returns an Mi x Mo matrix.""" return np.random.randn(Mi, Mo) / np.sqrt(Mi + Mo) def all_parity_pairs(nbit): """Takes in the number of bits, generates all possible combinations of bits.""" # total number of samples (Ntotal) will be a multiple of 100 # why did I make it this way? I don't remember. N = 2**nbit remainder = 100 - (N % 100) Ntotal = N + remainder X = np.zeros((Ntotal, nbit)) Y = np.zeros(Ntotal) for ii in range(Ntotal): i = ii % N # now generate the ith sample for j in range(nbit): if i % (2**(j+1)) != 0: i -= 2**j X[ii,j] = 1 Y[ii] = X[ii].sum() % 2 return X, Y def all_parity_pairs_with_sequence_labels(nbit): X, Y = all_parity_pairs(nbit) N, t = X.shape # we want every time step to have a label Y_t = np.zeros(X.shape, dtype=np.int32) for n in range(N): ones_count = 0 for i in range(t): if X[n,i] == 1: ones_count += 1 if ones_count % 2 == 1: Y_t[n,i] = 1 X = X.reshape(N, t, 1).astype(np.float32) return X, Y_t def remove_punctuation(s): return s.translate(str.maketrans('','',string.punctuation)) def get_robert_frost(): word2idx = {'START': 0, 'END': 1} current_idx = 2 sentences = [] for line in open(f'{relative_path}poems/robert_frost.txt'): line = line.strip() if line: tokens = remove_punctuation(line.lower()).split() sentence = [] for t in tokens: if t not in word2idx: word2idx[t] = current_idx current_idx += 1 idx = word2idx[t] sentence.append(idx) sentences.append(sentence) return sentences, word2idx def get_tags(s): tuples = pos_tag(word_tokenize(s)) return [y for x, y in tuples] def get_poetry_classifier_data(samples_per_class, loaded_cached=True, save_cached=True): datafile = 'poetry_classifier.npz' if loaded_cached and os.path.exists(datafile): npz = np.load(datafile) X = npz['arr_0'] # Data Y = npz['arr_1'] # Targets, 0 or 1 V = int(npz['arr_2']) # Vocabulary size return X, Y, V word2idx = {} current_idx = 0 X = [] Y = [] for fn, label in zip((f'{relative_path}poems/robert_frost.txt', f'{relative_path}poems/edgar_allan_poe.txt'), (0,1 )): count = 0 for line in open(fn): line = line.rstrip() if line: print(line) tokens = get_tags(line) if len(tokens) > 1: for token in tokens: if token not in word2idx: word2idx[token] = current_idx current_idx += 1 sequence = np.array([word2idx[w] for w in tokens]) X.append(sequence) Y.append(label) count += 1 print(count) if count >= samples_per_class: break if save_cached: np.savez(datafile, X, Y, current_idx) return X, Y, current_idx def my_tokenizer(s): s = remove_punctuation(s) s = s.lower() return s.split() def get_wikipedia_data(n_files, n_vocab, by_paragraph=False): """Converts Wikipedia txt files into correct format for Neural Network This function takes in a number of files that is too large to fit into memory if all data is loaded at once. 100 or less seems to be ideal. The vocabulary also needs to be limited, since it is a lot larger than the poetry dataset. We are going to have ~500,000-1,000,000 words. Note that the output target is the next word, so that is 1 million output classes, which is a lot of output classes. This makes it hard to get good accuracy, and it will make our output weight very large. To remedy this, the vocabulary size will be restricted to n_vocab. This is generally set to ~2000 most common words. Args: n_files: Number of input files taken in n_vocab: Vocabulary size by_paragraph: Returns: sentences: list of lists containing sentences mapped to index word2idx_small: word2index mapping reduced to size n_vocab """ wiki_relative_path = f'{relative_path}wikipedia/unzipped' input_files = [f for f in os.listdir(wiki_relative_path) if f.startswith('enwiki') and f.endswith('txt')] # Return Variables sentences = [] word2idx = {'START': 0, 'END': 1} idx2word = ['START', 'END'] current_idx = 2 word_idx_count = {0: float('inf'), 1: float('inf')} if n_files is not None: input_files = input_files[:n_files] for f in input_files: print('Reading: ', f ) for line in open(f'{wiki_relative_path}/{f}'): line = line.strip() # Don't count headers, structured data, lists, etc if line and line[0] not in ('[', '*', '-', '|', '=', '{', '}'): if by_paragraph: sentence_lines = [line] else: sentence_lines = line.split('. ') for sentence in sentence_lines: tokens = my_tokenizer(sentence) for t in tokens: if t not in word2idx: word2idx[t] = current_idx idx2word.append(t) current_idx += 1 idx = word2idx[t] word_idx_count[idx] = word_idx_count.get(idx, 0) + 1 sentence_by_idx = [word2idx[t] for t in tokens] sentences.append(sentence_by_idx) # Reduce vocabulary size to n_vocab sorted_word_idx_count = sorted(word_idx_count.items(), key=operator.itemgetter(1), reverse=True) word2idx_small = {} new_idx = 0 idx_new_idx_map = {} for idx, count in sorted_word_idx_count[:n_vocab]: word = idx2word[idx] print(word, count) word2idx_small[word] = new_idx idx_new_idx_map[idx] = new_idx new_idx += 1 # Let 'unknown' be last token word2idx_small['UNKNOWN'] = new_idx unknown = new_idx assert('START' in word2idx_small) assert('END' in word2idx_small) assert('king' in word2idx_small) assert('queen' in word2idx_small) assert('man' in word2idx_small) assert('woman' in word2idx_small) # Map old idx to new idx sentences_small = [] for sentence in sentences: if len(sentence) > 1: new_sentence = [idx_new_idx_map[idx] if idx in idx_new_idx_map else unknown for idx in sentence] sentences_small.append(new_sentence) return sentences_small, word2idx_small
[ "os.path.exists", "numpy.savez", "os.listdir", "numpy.sqrt", "nltk.word_tokenize", "numpy.array", "numpy.zeros", "operator.itemgetter", "numpy.load", "numpy.random.randn" ]
[((781, 805), 'numpy.zeros', 'np.zeros', (['(Ntotal, nbit)'], {}), '((Ntotal, nbit))\n', (789, 805), True, 'import numpy as np\n'), ((814, 830), 'numpy.zeros', 'np.zeros', (['Ntotal'], {}), '(Ntotal)\n', (822, 830), True, 'import numpy as np\n'), ((1246, 1279), 'numpy.zeros', 'np.zeros', (['X.shape'], {'dtype': 'np.int32'}), '(X.shape, dtype=np.int32)\n', (1254, 1279), True, 'import numpy as np\n'), ((424, 447), 'numpy.random.randn', 'np.random.randn', (['Mi', 'Mo'], {}), '(Mi, Mo)\n', (439, 447), True, 'import numpy as np\n'), ((450, 466), 'numpy.sqrt', 'np.sqrt', (['(Mi + Mo)'], {}), '(Mi + Mo)\n', (457, 466), True, 'import numpy as np\n'), ((2267, 2283), 'nltk.word_tokenize', 'word_tokenize', (['s'], {}), '(s)\n', (2280, 2283), False, 'from nltk import pos_tag, word_tokenize\n'), ((2474, 2498), 'os.path.exists', 'os.path.exists', (['datafile'], {}), '(datafile)\n', (2488, 2498), False, 'import os\n'), ((2514, 2531), 'numpy.load', 'np.load', (['datafile'], {}), '(datafile)\n', (2521, 2531), True, 'import numpy as np\n'), ((3581, 3618), 'numpy.savez', 'np.savez', (['datafile', 'X', 'Y', 'current_idx'], {}), '(datafile, X, Y, current_idx)\n', (3589, 3618), True, 'import numpy as np\n'), ((4874, 4904), 'os.listdir', 'os.listdir', (['wiki_relative_path'], {}), '(wiki_relative_path)\n', (4884, 4904), False, 'import os\n'), ((6327, 6349), 'operator.itemgetter', 'operator.itemgetter', (['(1)'], {}), '(1)\n', (6346, 6349), False, 'import operator\n'), ((3293, 3332), 'numpy.array', 'np.array', (['[word2idx[w] for w in tokens]'], {}), '([word2idx[w] for w in tokens])\n', (3301, 3332), True, 'import numpy as np\n')]
from __future__ import division import numpy as np from scipy.stats import mode from utilities import shuffle_in_unison from decisiontree import DecisionTreeClassifier class RandomForestClassifier(object): """ A random forest classifier. A random forest is a collection of decision trees that vote on a classification decision. Each tree is trained with a subset of the data and features. """ def __init__(self, n_estimators=32, max_features=np.sqrt, max_depth=10, min_samples_split=2, bootstrap=0.9): """ Args: n_estimators: The number of decision trees in the forest. max_features: Controls the number of features to randomly consider at each split. max_depth: The maximum number of levels that the tree can grow downwards before forcefully becoming a leaf. min_samples_split: The minimum number of samples needed at a node to justify a new node split. bootstrap: The fraction of randomly choosen data to fit each tree on. """ self.n_estimators = n_estimators self.max_features = max_features self.max_depth = max_depth self.min_samples_split = min_samples_split self.bootstrap = bootstrap self.forest = [] def fit(self, X, y): """ Creates a forest of decision trees using a random subset of data and features. """ self.forest = [] n_samples = len(y) n_sub_samples = round(n_samples*self.bootstrap) for i in xrange(self.n_estimators): shuffle_in_unison(X, y) X_subset = X[:n_sub_samples] y_subset = y[:n_sub_samples] tree = DecisionTreeClassifier(self.max_features, self.max_depth, self.min_samples_split) tree.fit(X_subset, y_subset) self.forest.append(tree) def predict(self, X): """ Predict the class of each sample in X. """ n_samples = X.shape[0] n_trees = len(self.forest) predictions = np.empty([n_trees, n_samples]) for i in xrange(n_trees): predictions[i] = self.forest[i].predict(X) return mode(predictions)[0][0] def score(self, X, y): """ Return the accuracy of the prediction of X compared to y. """ y_predict = self.predict(X) n_samples = len(y) correct = 0 for i in xrange(n_samples): if y_predict[i] == y[i]: correct = correct + 1 accuracy = correct/n_samples return accuracy
[ "scipy.stats.mode", "utilities.shuffle_in_unison", "numpy.empty", "decisiontree.DecisionTreeClassifier" ]
[((2135, 2165), 'numpy.empty', 'np.empty', (['[n_trees, n_samples]'], {}), '([n_trees, n_samples])\n', (2143, 2165), True, 'import numpy as np\n'), ((1634, 1657), 'utilities.shuffle_in_unison', 'shuffle_in_unison', (['X', 'y'], {}), '(X, y)\n', (1651, 1657), False, 'from utilities import shuffle_in_unison\n'), ((1760, 1846), 'decisiontree.DecisionTreeClassifier', 'DecisionTreeClassifier', (['self.max_features', 'self.max_depth', 'self.min_samples_split'], {}), '(self.max_features, self.max_depth, self.\n min_samples_split)\n', (1782, 1846), False, 'from decisiontree import DecisionTreeClassifier\n'), ((2271, 2288), 'scipy.stats.mode', 'mode', (['predictions'], {}), '(predictions)\n', (2275, 2288), False, 'from scipy.stats import mode\n')]
from ximea import xiapi import cv2 import time import numpy as np import matplotlib.pyplot as plt import pandas as pd #create instance for first connected camera cam = xiapi.Camera() #start communication print('Opening first camera...') cam.open_device() #settings cam.set_exposure(2000) cam.set_gain(10) cam.set_imgdataformat('XI_RGB24') #create instance of Image to store image data and metadata cap = xiapi.Image() #start data acquisition print('Starting data acquisition...') cam.start_acquisition() #initialize time to display diameter t0 = time.time() i = 0 igraph = 0 #create empty array for diameter saving diam_arr = np.zeros((100000000,3)) #initialize matplotlib image #initialize graphic windows cv2.namedWindow('Processed Frame') cv2.namedWindow('Lined Feed') #define empty function for trackbars def nothing(x): pass #iniatilize trackbar for P parameter cv2.createTrackbar('P Selector','Processed Frame',8,100,nothing) #initialize trackbar for array saving cv2.createTrackbar('Save Array','Lined Feed',0,1,nothing) #iniatilize trackbar for event positioning cv2.createTrackbar('Event Location','Lined Feed',0,1,nothing) #initialize graphing window fig, ax = plt.subplots() ax.set_xlabel('Time (s)') ax.set_ylabel('Fiber Diameter (um)') points, = ax.plot(0, 0, 'kx', label='Diameter') mean, = ax.plot(0, 0, 'b-', label='Rolling Avg') flag, = ax.plot(0, 0, 'go', label='Events') ax.set_xlim(0, 3600) ax.set_ylim(0,500) ax.legend() plt.ion() plt.show() try: print('Starting video. Press CTRL+C to exit.') while True: #get data and pass them from camera to img cam.get_image(cap) #create numpy array with data from camera. Dimensions of the array are #determined by imgdataformat img = cap.get_image_data_numpy() gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) #image thresholding P = cv2.getTrackbarPos('P Selector', 'Processed Frame'); retval,imgthresh = cv2.threshold(gray,P,255,cv2.THRESH_BINARY) # plt.imshow(imgthresh) #image edging edges = cv2.Canny(imgthresh,250,255) edgesblur = cv2.GaussianBlur(edges,(5,5),0) # plt.imshow(edgesblur) # plt.imshow(edges) #apply hough transform lines = cv2.HoughLines(edgesblur,1,np.pi/60,500) if lines is None : lines = np.ones((2,2)) lines = np.reshape(lines,(len(lines),2)) #select appropiate lines for fiber edge lines_selected = np.zeros((2,2)) lines_selected[0] = lines.max(0) lines_selected[1] = lines.min(0) #represent lines overimposed on original img. for rho,theta in lines_selected: a = np.cos(theta) b = np.sin(theta) x0 = a*rho y0 = b*rho x1 = int(x0 + len(img[0])*(-b)) y1 = int(y0 + len(img[1])*(a)) x2 = int(x0 - len(img[0])*(-b)) y2 = int(y0 - len(img[1])*(a)) cv2.line(edgesblur,(x1,y1),(x2,y2),(255,255,255),1) #add center line of fiber diameter x3 = int(len(img[0])/2) y3 = int(-np.cos(lines_selected[0,1])/(np.sin(lines_selected[0,1]+0.01))*x3 + lines_selected[0,0]/(np.sin(lines_selected[0,1])+0.01)) y4 = int((-np.cos(lines_selected[1,1])/(np.sin(lines_selected[1,1])+0.01)*x3 + lines_selected[1,0]/(np.sin(lines_selected[1,1])+0.01))) cv2.line(img,(x3,y3),(x3,y4),(0,0,255),2) #compute fiber diameter and show fiber_diam_pixels = (y3-y4) fiber_diam_micras = str(np.round(203/464 * fiber_diam_pixels, decimals = 0)) cv2.putText(img,r'Fiber Diameter = %s um'% fiber_diam_micras, (50,1000),cv2.FONT_HERSHEY_SIMPLEX,2,(0,0,255),2) #save fiber diameter to array if saved array flag is 1 save_flag = cv2.getTrackbarPos('Save Array', 'Lined Feed'); event_flag = cv2.getTrackbarPos('Event Location', 'Lined Feed') if save_flag == 1: diam_arr[i,0] = time.time()-t0 diam_arr[i,1] = fiber_diam_micras diam_arr[i,2] = event_flag i += 1 if i == len(diam_arr): i = 0 # resize images and show scale = 50 rszx = int(img.shape[1]*scale/100) rszy = int(img.shape[0]*scale/100) imgrsz = cv2.resize(img, (rszx,rszy)) edgesrsz = cv2.resize(edgesblur, (rszx, rszy)) cv2.imshow('Processed Frame',edgesrsz) cv2.imshow('Lined Feed',imgrsz) #data analysis and plotting if igraph == 10: #delete 0 values from array and transform to pandas dataframe mod_diam_arr = diam_arr[diam_arr[:,1] != 0] clean_arr = pd.DataFrame(data = mod_diam_arr, columns = ['Time','Diameter','Event Flag']) #perform rolling average on pandas dataframe of clean data interval = 20 clean_arr['Average'] = clean_arr['Diameter'].rolling(window = interval, center = True, min_periods = 1).mean() clean_arr['Std'] = clean_arr['Diameter'].rolling(window = interval, center = True, min_periods = 1).std() clean_arr['Clean'] = clean_arr.Diameter[(clean_arr['Diameter'] >= clean_arr['Average']-clean_arr['Std']) & (clean_arr['Diameter'] <= clean_arr['Average']+clean_arr['Std'])] clean_arr['Dirty'] = clean_arr.Diameter[(clean_arr['Diameter'] <= clean_arr['Average']-clean_arr['Std']) | (clean_arr['Diameter'] >= clean_arr['Average']+clean_arr['Std'])] clean_arr['CAverage'] = clean_arr['Clean'].rolling(window = interval, center = True, min_periods = 1).mean() clean_arr['Marked'] = clean_arr.Time[clean_arr['Event Flag'] == 1] #plot diameter array points.set_xdata(clean_arr['Time']) points.set_ydata(clean_arr['Clean']) mean.set_xdata(clean_arr['Time']) mean.set_ydata(clean_arr['CAverage']) flag.set_xdata(clean_arr['Marked']) flag.set_ydata(clean_arr['Event Flag']) fig.canvas.draw() igraph = 0 cv2.waitKey(80) igraph = igraph + 1 except KeyboardInterrupt: cv2.destroyAllWindows() #delete 0 values from array and transform to pandas dataframe mod_diam_arr = diam_arr[diam_arr[:,1] != 0] clean_arr = pd.DataFrame(data = mod_diam_arr, columns = ['Time','Diameter','Event Flag']) #perform rolling average on pandas dataframe of clean data interval = 20 clean_arr['Average'] = clean_arr['Diameter'].rolling(window = interval, center = True, min_periods = 1).mean() clean_arr['Std'] = clean_arr['Diameter'].rolling(window = interval, center = True, min_periods = 1).std() clean_arr['Clean'] = clean_arr.Diameter[(clean_arr['Diameter'] >= clean_arr['Average']-clean_arr['Std']) & (clean_arr['Diameter'] <= clean_arr['Average']+clean_arr['Std'])] clean_arr['Dirty'] = clean_arr.Diameter[(clean_arr['Diameter'] <= clean_arr['Average']-clean_arr['Std']) | (clean_arr['Diameter'] >= clean_arr['Average']+clean_arr['Std'])] clean_arr['CAverage'] = clean_arr['Clean'].rolling(window = interval, center = True, min_periods = 1).mean() clean_arr['Marked'] = clean_arr.Time[clean_arr['Event Flag'] == 1] #plot diameter array stflag = 1 if stflag == 1: plt.plot(clean_arr['Time'],clean_arr['Clean'],'kx') plt.plot(clean_arr['Time'],clean_arr['CAverage'],'b-') plt.plot(clean_arr['Marked'], clean_arr['Event Flag'], 'go') else: plt.plot(clean_arr['Time'],clean_arr['Clean'],'kx') plt.plot(clean_arr['Time'],clean_arr['CAverage'],'b-') plt.plot(clean_arr['Marked'], clean_arr['Event Flag'], 'go') plt.plot(clean_arr['Time'],clean_arr['Average']-clean_arr['Std'],'r--') plt.plot(clean_arr['Time'],clean_arr['Average']+clean_arr['Std'],'r--') plt.plot(clean_arr['Time'],clean_arr['Dirty'],'rx') plt.xlabel('Time (s)') plt.ylabel('Fiber Diameter (um)') plt.show() #save array to csv, plot file filename = input('Input filename: ') clean_arr.to_csv('%s.csv'%filename) plt.savefig(filename+'_plot.jpg') #stop data acquisition print('Stopping acquisition...') cam.stop_acquisition() #stop communication cam.close_device() print('Done.')
[ "matplotlib.pyplot.ylabel", "cv2.imshow", "cv2.HoughLines", "cv2.destroyAllWindows", "numpy.sin", "cv2.threshold", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "cv2.line", "pandas.DataFrame", "cv2.waitKey", "numpy.round", "ximea.xiapi.Camera", "matplotlib.pyplot.savefig", "numpy...
[((178, 192), 'ximea.xiapi.Camera', 'xiapi.Camera', ([], {}), '()\n', (190, 192), False, 'from ximea import xiapi\n'), ((423, 436), 'ximea.xiapi.Image', 'xiapi.Image', ([], {}), '()\n', (434, 436), False, 'from ximea import xiapi\n'), ((570, 581), 'time.time', 'time.time', ([], {}), '()\n', (579, 581), False, 'import time\n'), ((654, 678), 'numpy.zeros', 'np.zeros', (['(100000000, 3)'], {}), '((100000000, 3))\n', (662, 678), True, 'import numpy as np\n'), ((740, 774), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Processed Frame"""'], {}), "('Processed Frame')\n", (755, 774), False, 'import cv2\n'), ((776, 805), 'cv2.namedWindow', 'cv2.namedWindow', (['"""Lined Feed"""'], {}), "('Lined Feed')\n", (791, 805), False, 'import cv2\n'), ((910, 978), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""P Selector"""', '"""Processed Frame"""', '(8)', '(100)', 'nothing'], {}), "('P Selector', 'Processed Frame', 8, 100, nothing)\n", (928, 978), False, 'import cv2\n'), ((1015, 1076), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Save Array"""', '"""Lined Feed"""', '(0)', '(1)', 'nothing'], {}), "('Save Array', 'Lined Feed', 0, 1, nothing)\n", (1033, 1076), False, 'import cv2\n'), ((1118, 1183), 'cv2.createTrackbar', 'cv2.createTrackbar', (['"""Event Location"""', '"""Lined Feed"""', '(0)', '(1)', 'nothing'], {}), "('Event Location', 'Lined Feed', 0, 1, nothing)\n", (1136, 1183), False, 'import cv2\n'), ((1224, 1238), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1236, 1238), True, 'import matplotlib.pyplot as plt\n'), ((1512, 1521), 'matplotlib.pyplot.ion', 'plt.ion', ([], {}), '()\n', (1519, 1521), True, 'import matplotlib.pyplot as plt\n'), ((1523, 1533), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1531, 1533), True, 'import matplotlib.pyplot as plt\n'), ((6714, 6789), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'mod_diam_arr', 'columns': "['Time', 'Diameter', 'Event Flag']"}), "(data=mod_diam_arr, columns=['Time', 'Diameter', 'Event Flag'])\n", (6726, 6789), True, 'import pandas as pd\n'), ((8286, 8308), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (s)"""'], {}), "('Time (s)')\n", (8296, 8308), True, 'import matplotlib.pyplot as plt\n'), ((8310, 8343), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Fiber Diameter (um)"""'], {}), "('Fiber Diameter (um)')\n", (8320, 8343), True, 'import matplotlib.pyplot as plt\n'), ((8347, 8357), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (8355, 8357), True, 'import matplotlib.pyplot as plt\n'), ((8471, 8506), 'matplotlib.pyplot.savefig', 'plt.savefig', (["(filename + '_plot.jpg')"], {}), "(filename + '_plot.jpg')\n", (8482, 8506), True, 'import matplotlib.pyplot as plt\n'), ((7688, 7741), 'matplotlib.pyplot.plot', 'plt.plot', (["clean_arr['Time']", "clean_arr['Clean']", '"""kx"""'], {}), "(clean_arr['Time'], clean_arr['Clean'], 'kx')\n", (7696, 7741), True, 'import matplotlib.pyplot as plt\n'), ((7745, 7801), 'matplotlib.pyplot.plot', 'plt.plot', (["clean_arr['Time']", "clean_arr['CAverage']", '"""b-"""'], {}), "(clean_arr['Time'], clean_arr['CAverage'], 'b-')\n", (7753, 7801), True, 'import matplotlib.pyplot as plt\n'), ((7805, 7865), 'matplotlib.pyplot.plot', 'plt.plot', (["clean_arr['Marked']", "clean_arr['Event Flag']", '"""go"""'], {}), "(clean_arr['Marked'], clean_arr['Event Flag'], 'go')\n", (7813, 7865), True, 'import matplotlib.pyplot as plt\n'), ((7890, 7943), 'matplotlib.pyplot.plot', 'plt.plot', (["clean_arr['Time']", "clean_arr['Clean']", '"""kx"""'], {}), "(clean_arr['Time'], clean_arr['Clean'], 'kx')\n", (7898, 7943), True, 'import matplotlib.pyplot as plt\n'), ((7947, 8003), 'matplotlib.pyplot.plot', 'plt.plot', (["clean_arr['Time']", "clean_arr['CAverage']", '"""b-"""'], {}), "(clean_arr['Time'], clean_arr['CAverage'], 'b-')\n", (7955, 8003), True, 'import matplotlib.pyplot as plt\n'), ((8007, 8067), 'matplotlib.pyplot.plot', 'plt.plot', (["clean_arr['Marked']", "clean_arr['Event Flag']", '"""go"""'], {}), "(clean_arr['Marked'], clean_arr['Event Flag'], 'go')\n", (8015, 8067), True, 'import matplotlib.pyplot as plt\n'), ((8073, 8148), 'matplotlib.pyplot.plot', 'plt.plot', (["clean_arr['Time']", "(clean_arr['Average'] - clean_arr['Std'])", '"""r--"""'], {}), "(clean_arr['Time'], clean_arr['Average'] - clean_arr['Std'], 'r--')\n", (8081, 8148), True, 'import matplotlib.pyplot as plt\n'), ((8150, 8225), 'matplotlib.pyplot.plot', 'plt.plot', (["clean_arr['Time']", "(clean_arr['Average'] + clean_arr['Std'])", '"""r--"""'], {}), "(clean_arr['Time'], clean_arr['Average'] + clean_arr['Std'], 'r--')\n", (8158, 8225), True, 'import matplotlib.pyplot as plt\n'), ((8227, 8280), 'matplotlib.pyplot.plot', 'plt.plot', (["clean_arr['Time']", "clean_arr['Dirty']", '"""rx"""'], {}), "(clean_arr['Time'], clean_arr['Dirty'], 'rx')\n", (8235, 8280), True, 'import matplotlib.pyplot as plt\n'), ((1884, 1921), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (1896, 1921), False, 'import cv2\n'), ((1969, 2020), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""P Selector"""', '"""Processed Frame"""'], {}), "('P Selector', 'Processed Frame')\n", (1987, 2020), False, 'import cv2\n'), ((2050, 2096), 'cv2.threshold', 'cv2.threshold', (['gray', 'P', '(255)', 'cv2.THRESH_BINARY'], {}), '(gray, P, 255, cv2.THRESH_BINARY)\n', (2063, 2096), False, 'import cv2\n'), ((2177, 2207), 'cv2.Canny', 'cv2.Canny', (['imgthresh', '(250)', '(255)'], {}), '(imgthresh, 250, 255)\n', (2186, 2207), False, 'import cv2\n'), ((2228, 2262), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['edges', '(5, 5)', '(0)'], {}), '(edges, (5, 5), 0)\n', (2244, 2262), False, 'import cv2\n'), ((2381, 2426), 'cv2.HoughLines', 'cv2.HoughLines', (['edgesblur', '(1)', '(np.pi / 60)', '(500)'], {}), '(edgesblur, 1, np.pi / 60, 500)\n', (2395, 2426), False, 'import cv2\n'), ((2635, 2651), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (2643, 2651), True, 'import numpy as np\n'), ((3603, 3652), 'cv2.line', 'cv2.line', (['img', '(x3, y3)', '(x3, y4)', '(0, 0, 255)', '(2)'], {}), '(img, (x3, y3), (x3, y4), (0, 0, 255), 2)\n', (3611, 3652), False, 'import cv2\n'), ((3829, 3952), 'cv2.putText', 'cv2.putText', (['img', "('Fiber Diameter = %s um' % fiber_diam_micras)", '(50, 1000)', 'cv2.FONT_HERSHEY_SIMPLEX', '(2)', '(0, 0, 255)', '(2)'], {}), "(img, 'Fiber Diameter = %s um' % fiber_diam_micras, (50, 1000),\n cv2.FONT_HERSHEY_SIMPLEX, 2, (0, 0, 255), 2)\n", (3840, 3952), False, 'import cv2\n'), ((4036, 4082), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Save Array"""', '"""Lined Feed"""'], {}), "('Save Array', 'Lined Feed')\n", (4054, 4082), False, 'import cv2\n'), ((4106, 4156), 'cv2.getTrackbarPos', 'cv2.getTrackbarPos', (['"""Event Location"""', '"""Lined Feed"""'], {}), "('Event Location', 'Lined Feed')\n", (4124, 4156), False, 'import cv2\n'), ((4603, 4632), 'cv2.resize', 'cv2.resize', (['img', '(rszx, rszy)'], {}), '(img, (rszx, rszy))\n', (4613, 4632), False, 'import cv2\n'), ((4652, 4687), 'cv2.resize', 'cv2.resize', (['edgesblur', '(rszx, rszy)'], {}), '(edgesblur, (rszx, rszy))\n', (4662, 4687), False, 'import cv2\n'), ((4707, 4746), 'cv2.imshow', 'cv2.imshow', (['"""Processed Frame"""', 'edgesrsz'], {}), "('Processed Frame', edgesrsz)\n", (4717, 4746), False, 'import cv2\n'), ((4755, 4787), 'cv2.imshow', 'cv2.imshow', (['"""Lined Feed"""', 'imgrsz'], {}), "('Lined Feed', imgrsz)\n", (4765, 4787), False, 'import cv2\n'), ((6480, 6495), 'cv2.waitKey', 'cv2.waitKey', (['(80)'], {}), '(80)\n', (6491, 6495), False, 'import cv2\n'), ((6557, 6580), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (6578, 6580), False, 'import cv2\n'), ((2471, 2486), 'numpy.ones', 'np.ones', (['(2, 2)'], {}), '((2, 2))\n', (2478, 2486), True, 'import numpy as np\n'), ((2859, 2872), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (2865, 2872), True, 'import numpy as np\n'), ((2890, 2903), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (2896, 2903), True, 'import numpy as np\n'), ((3153, 3212), 'cv2.line', 'cv2.line', (['edgesblur', '(x1, y1)', '(x2, y2)', '(255, 255, 255)', '(1)'], {}), '(edgesblur, (x1, y1), (x2, y2), (255, 255, 255), 1)\n', (3161, 3212), False, 'import cv2\n'), ((3767, 3818), 'numpy.round', 'np.round', (['(203 / 464 * fiber_diam_pixels)'], {'decimals': '(0)'}), '(203 / 464 * fiber_diam_pixels, decimals=0)\n', (3775, 3818), True, 'import numpy as np\n'), ((5031, 5106), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'mod_diam_arr', 'columns': "['Time', 'Diameter', 'Event Flag']"}), "(data=mod_diam_arr, columns=['Time', 'Diameter', 'Event Flag'])\n", (5043, 5106), True, 'import pandas as pd\n'), ((4234, 4245), 'time.time', 'time.time', ([], {}), '()\n', (4243, 4245), False, 'import time\n'), ((3333, 3368), 'numpy.sin', 'np.sin', (['(lines_selected[0, 1] + 0.01)'], {}), '(lines_selected[0, 1] + 0.01)\n', (3339, 3368), True, 'import numpy as np\n'), ((3393, 3421), 'numpy.sin', 'np.sin', (['lines_selected[0, 1]'], {}), '(lines_selected[0, 1])\n', (3399, 3421), True, 'import numpy as np\n'), ((3537, 3565), 'numpy.sin', 'np.sin', (['lines_selected[1, 1]'], {}), '(lines_selected[1, 1])\n', (3543, 3565), True, 'import numpy as np\n'), ((3304, 3332), 'numpy.cos', 'np.cos', (['lines_selected[0, 1]'], {}), '(lines_selected[0, 1])\n', (3310, 3332), True, 'import numpy as np\n'), ((3448, 3476), 'numpy.cos', 'np.cos', (['lines_selected[1, 1]'], {}), '(lines_selected[1, 1])\n', (3454, 3476), True, 'import numpy as np\n'), ((3477, 3505), 'numpy.sin', 'np.sin', (['lines_selected[1, 1]'], {}), '(lines_selected[1, 1])\n', (3483, 3505), True, 'import numpy as np\n')]
import numpy as np class SistemaLinear: def __init__(self, matriz = None , vetor_constante = None, dimensao = None, tipo = 'C'): self.matriz = matriz #Recebe a matriz dos coeficientes self.vetor_constante = vetor_constante # Recebe o vetor de constantates, tambem conhecido como vetor b self.dimensao = matriz.shape #Recebe uma tupla-ordenada com as dimensões do sistema self.tipo = tipo #Rece o tipo de sistema, se a instancia possui a matriz de coeficientes e o vetor constante (C), ou se estao numa mesma matriz ,que recebe o nome de matriz extendida (E) if np.any(vetor_constante) == None and tipo != 'E': # Caso nao seja informado o vetor constante é criado um vetor com zeros no lugar self.vetor_constante = np.zeros(shape=(self.matriz.shape[0],1)) if tipo == 'E': self.matriz = matriz[:,:-1] #Recebe a matriz dos coeficientes self.vetor_constante = matriz[:,-1].reshape((dimensao[0],1)) # Recebe o vetor de constantates, tambem conhecido como vetor b def cramer(self): print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Método: Cramer <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() print(f'Sistema:') print(f'{self.matriz}') #Exibe a matriz de coeficientes do sistema print() if (np.linalg.det(self.matriz) != 0): matriz_transicao = np.copy(self.matriz) #Esta matriz_transição recebe uma copia da matriz original para nao alterar seus dados dets = [np.linalg.det(matriz_transicao)] #Armazena o valor das determinantes que são necessarias para a reolução do sistema. A determinante da matriz dos coeficientes já está adicionada vetor_incognitas = np.zeros_like(self.vetor_constante) #Criamos um vetor com as dimensões do vetor constante print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Determinantes <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') for i in range(0,self.dimensao[0],1): #Loop responsável pelo calculo e armazenamento das determinantes matriz_transicao[:,i] = self.vetor_constante.reshape((self.dimensao[0],)) #Substitui a coluna da matriz pelo vetor constante na coluna de x_i dets.append(np.linalg.det(matriz_transicao)) #Armazena o calculo da determinante print() print(f'Dx[{i+1}]: {dets[i+1]}')#Exibe o resultado do determinante calculado print() matriz_transicao[:,i] = np.copy(self.matriz[:,i]) # Retorna o valor original da culuna subistituida pelo vetor constante print() print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Soluções <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() for s in range(0,self.dimensao[0],1): #Loop responsavel por armazenar e calcular os valores de x vetor_incognitas[s] = dets[s+1]/dets[0] #Armazena os resultados de x print() print(f'x[{s+1}]: {vetor_incognitas[s]}')#Exibe os valroes de x print() print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fim do Método: Cramer <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') return vetor_incognitas #retorna os valores de x, podendo ser utilizados ou armazenados em uma variavel else: return print("determinante é igual a 0. Não há solução para o sistema, utilizando este método.") def triangular_matriz(self): print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Triangulando Sistema <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() print(f'Sistema:') print(f'{self.matriz}') #Exibe a matriz dos coeficientes print() print(f'Vetor Solução:') print(f'{self.vetor_constante}') #Exibe o vetor constante print() for k in range(0,self.matriz.shape[0]-1,1): #Loop responsável pelas iterações necessarias para trinagular a matriz #print(f'k: {k + 1}') for i in range(k + 1,self.matriz.shape[0],1): #Loop responsável pelos calculos das tranformações da matriz m = self.matriz[i,k]/self.matriz[k,k] #constante utilizada na multiplicação da linha anterior a que será subitraida. Exemplo L_2 = L_2 - m*L_1 self.matriz[i,k] = 0 #Zeramos o elemento abaixo da diagonal principal #print(f'i: {i+1}') for j in range(k + 1,self.matriz.shape[0],1): self.matriz[i,j] = self.matriz[i,j] - (m*(self.matriz[k,j])) #Realiza um proceso de operação de um elemento da matriz com outro que se encontra uma linha abaixo. EX: a_12 = a_12 - m*a_22 #print(f'j: {j+1}') print(f'Triangulando.....') print(f'{self.matriz}') #Exibe a matriz triangulada, dependendo do passo, não estará completamente triangulada. print() self.vetor_constante[i,0] = self.vetor_constante[i,0] - (m*(self.vetor_constante[k,0])) #Realiza um proceso de operação de um elemento do vetor constante com outro que se encontra uma linha abaixo. EX: b_2 = b_2 - m*b_1 print(f'Vetor Solução:') print(f'{self.vetor_constante}')#Exibe o vetor constante print() print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fim da Triangulação <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') def eliminacao_gaussiana(self): self.triangular_matriz() #É necessário triangular o sistema para utilizar esse método print() print() print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Método: Eliminação Gaussiana <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() print(f'Sistema:') print(f'{self.matriz}')#Exibe a matriz print() print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Soluções <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() x = np.zeros_like(self.vetor_constante)#Vetor incógnita, ou vetor x x[-1 ,0] = self.vetor_constante[-1,0]/self.matriz[-1,-1] #O ultimao valor é xn = b_n/ann, a partir disso é possivel substituir o valor de xn nas outras linhas para obter x_(n-1) até x_1 for i in range(self.dimensao[0]-1,-1,-1): #Loop responsavel por armazenar x_(n-1) até x_1. Como x_1 é na verdade x_0, range possui intervalo aberto [a,b[ então é preciso ir até -1 para i ser igual a 0 e preencher x soma = 0 for j in range(i+1,self.dimensao[0],1): #Loop responsavel por realizar os calculos de x soma += self.matriz[i,j]*x[j,0] #Somando a_ij*x_j de i entre [n-1,-1[ com j = i +1 entre [i+1,n] x[i] = (self.vetor_constante[i] - soma)/matriz[i,i] #Calulo de x, x_(n-1) = (b_(n-1) - soma)/a_(n-1,n-1) print('vetor x:') print(f'{x}') #Exibindo x print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fim do Método <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') return x def convergencia_linhas(self): print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Teste de convergencia: Critéro de linha <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() alfas = np.zeros_like(self.vetor_constante)#Vetor que armazena os valores de alfa print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Alfas <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() for i in range(self.dimensao[0]):#Loop para armazenar os valores de alfa soma = 0 for j in range(self.dimensao[0]-1):#Loop responsavel pela soma dos elementos da linha i if (i==0): soma += np.abs(self.matriz[i,j+1])#Caso a estejamos na peimeira linha não poderemos utilizar seu primeira elemento, pois ele faz parte da diagonal principal. Entao somamos a partir do proximo elemento elif (i == j): soma += np.abs(self.matriz[i,j+1])#Caso o nº da linha coincidir com o nº da coluna entao, ou seja, caso seja elemento da diagonal principal, somamos o proximo elemento da linha else: soma += np.abs(self.matriz[i,j])#Para qualquer outro caso realize a soma do elementos da linha alfas[i,0] = soma/np.abs(self.matriz[i,i])#Armazena o valor de alfa na linha i até n print(f'alfa[{i+1}]: {alfas[i,0]}')#Exibe os valores do vetor alfa print() max_alpha = np.max(alfas) #Armazeno o maior valor de alfa em módulo print(f'Alfa máximo: {max_alpha}') #Exibe o maior valor de alfa em módulo if max_alpha < 1: #Se o maior valor de alfa em módulo for menor do que 1 ele converge, e então, o sistema pode ser resolvido com o método de Gauss-Jacobi print("O método de Gauss-Jacobi pode ser usado neste Sistema Linear") return True else: #Caso dele nao convergir o método de Gauss-Jacobi nao convirgirá para as soluções desse sistema print() print("O método não converge para este sistema") print("O método de Gauss-Jacobi pode ser usado neste Sistema Linear") print() def gauss_jacobi(self,tol = 10**(-3),iteracoes=30): if self.convergencia_linhas() == True: #Caso o sistema convirja suas soluções podem ser calculadas a partir desse método iterativo iteracao = 1 print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Método: Gauss-Jacobi <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() print(f'Sistema:') print(f'{self.matriz}')# Exibe o sistema print() x = np.zeros_like(self.vetor_constante)#Irá receber as aproxiamações do método for i in range(0,self.dimensao[0],1):#Loop responsável por nos dar o valor de um 'chute'inicial para x que segue a regra: x_i = b_i/a_ii x[i,0] = self.vetor_constante[i,0]/self.matriz[i,i] x_next = np.zeros(shape = x.shape)#Irá receber os valores das novas aproximações de x while iteracao <= iteracoes: #Este método será iterado até um valor limite de iterações que pode ser alterado ná hora de utilizar o método(da classe Sistema Linear), ou utilizar o limite pradrao do método print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> {iteracao}ª iteração. <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() print(f'Nº máximo de iterações {iteracoes}') #Exibe o valor máximo de iterações print(f'{iteracao}ª iteração de x') #Exibe em qual iteração de x estamos print(f'{x}') #Exibe o valor de x print() print() print(f'Nova aproximação:') print() for i in range(self.matriz.shape[0]): #Loop responsável por atribuir os valores para nossa proxima aproxima para x, que se chama: x_next soma = self.vetor_constante[i,0] #Primeiro é adicionado o valor de b_i que será utilizado para a proxima apraximação de x^(k)_i, ou seja x^(k+1) for j in range(self.matriz.shape[1]):#Loop responsável por realizar o somatório if (i != j): #Caso o elemento da matriz dos coeficientes não pertença a diagonal principal realize a soma soma -= self.matriz[i,j]*x[j,0]#Ele decrementa o valor da soma a_ij*x^(k)_(j), pois esta variavél soma é na verdade a seguinte espressão: b_i - Somatorio de a_ij*x^(k)_j quando i é diferente de j x_next[i,0] = soma/self.matriz[i,i]#É adicionado a próxima valor de x^(k+1)_j que é (b_i - Somatorio de a_ij*x^(k)_j quando i é diferente de j) dividido por a_ii print(f'x_next[{i+1}] = {x_next[i,0]}')#exibe o vetor de x^(k+1)_i erro = np.max(np.abs(x_next-x)) #Calcula o erro em módolo entre x^(k+1) e x^(k) e seleciona o maior valor print() print(f'Dados sobre a iteração ') print(f'erro: {erro}') #Exibe o erro print() print(f'x_next:') print(x_next)##exibe o vetor de x^(k+1) print() if erro < tol: #Caso o erro seja menor do que a tolerância, temos a solução do sistema sendo x^(k + 1) print() print('Solunção final') print(x_next)#Exibe x^(k+1) print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fim desta iteração <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fim do Método <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') break else:#Caso o erro seja maior do que a tolerância, temos que x assumirá os valores de x^(k+1), e assim até ele satisfazer a condição de parada ou atingir o limite de iterações x = np.copy(x_next) #x recebe os valores de x^(k+1) desta iteração print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fim desta iteração <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() iteracao += 1 #Acrescentar mais um ao nosso iterador else: #Caso o sistema não atenda a convegencia de linhas print() print("O método não converge para este sistema") print("O método de Gauss-Jacobi pode ser usado neste Sistema Linear") print() def convergencia_sassenfeld(self): print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Teste de convergencia: Critério de Sassenfeld <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() betas = np.zeros_like(self.vetor_constante)#Armazena os valores de betas print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Betas <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() for i in range(self.dimensao[0]):#Loop responsavel por adicionar os valores de beta_i no vetor betas soma = 0 for j in range(self.dimensao[1]):#Loop responsavel pelo calculo dos betas if (i != j ) and (i == 0) or (i<j):#Caso i seja diferente de j e a_ij com i e j são iguais ao primeiro elemento da diagonal principal ou i menor que j faça: soma += (np.abs(self.matriz[i,j])) #Somando |a_ij| elif (i!=j) and (i != 0): soma += (np.abs(self.matriz[i,j]))*betas[j]#Somando |a_ij|*beta_j betas[i,0] = soma/(np.abs(self.matriz[i,i]))#Adicionando b_i no vetor betas na posição i print(f'beta[{i+1}]: {betas[i,0]}')#Exibindo beta_i print() max_beta = np.max(betas) print(f'Beta máximo: {max_beta}')#Exibe o beta máximo print() if max_beta < 1: #Caso o beta máximo seja menor que 1 então o sistema converge print("O método de Gauss-Seidel pode ser usado neste Sistema Linear") print() print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fim do Método <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') return True else: print() print("O método não converge para este sistema") print("O método de Gauss-Seidel pode ser usado neste Sistema Linear") print() print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fim do Método <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() def gauss_seidel(self,iteracoes=30,tol = 10**(-3)): if self.convergencia_sassenfeld() == True: #Caso o sistema convirja então a solução do sistema pode ser calculada com este método print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Método: Gauss-Seidel <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() print(f'Sistema:') print(f'{self.matriz}')#Exibe a Matriz print() iteracao = 1 #Setando nosso iterador para 1, pois este será usado no laço while x = np.zeros_like(self.vetor_constante)#Irá receber as aproxiamações do método for i in range(0,self.matriz.shape[0],1):#Loop responsável por nos dar o valor de um 'chute'inicial para x que segue a regra: x_i = b_i/a_ii x[i,0] = self.vetor_constante[i,0]/self.matriz[i,i] #x_i = b_i/a_ii x_next = np.zeros_like(x)#Irá receber os valores das novas aproximações de x while iteracao <= iteracoes: #Este método será iterado até um valor limite de iterações que pode ser alterado ná hora de utilizar o método(da classe Sistema Linear), ou utilizar o limite pradrao do método print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> {iteracao}ª iteração. <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() print(f'Nº máximo de iterações {iteracoes}') #Exibe o valor máximo de iterações print(f'{iteracao}ª iteração de x')#Exibe em qual iteração de x estamos print(f'{x}') #Exibe o valor de x print() print() print(f'Nova aproximação:') print() for i in range(self.matriz.shape[0]):#Loop responsavel por adicionar x^(k+1)_i soma = self.vetor_constante[i,0] #Primeiro é adicionado o valor de b_i que será utilizado para a proxima apraximação de x^(k)_i, ou seja x^(k+1) for j in range(self.matriz.shape[1]): #Loop responsável por realizar os somatórios if (i > j): #Caso i seja maior que j será decrementado a_ij*x^(k+1) soma -= self.matriz[i,j]*x_next[j,0] #Entende-se por - somatoriio de i > j de a_ij com a aproximação de x^(k+1)_j, caso já haja um x^(k+1)_j nesta iteração elif (i < j): #Caso i seja menor que j será decrementado a_ij*x^(k) soma -= self.matriz[i,j]*x[j,0]#Entende-se por - somatoriio de i > j de a_ij com a aproximação de x^(k)_j, para ques seja utilizado x^(k+1)_j na próxima iteração x_next[i,0] = soma/self.matriz[i,i] # entende-se por (b_i - somatoriio de i > j de a_ij com a aproximação de x^(k+1)_j - somatoriio de i > j de a_ij com a aproximação de x^(k)_j)/a_ii print(f'x_next[{i+1}] = {x_next[i,0]}')#exibe o vetor de x^(k+1)_i erro = np.max(np.abs(x_next - x))#Calcula o erro em módolo entre x^(k+1) e x^(k) e seleciona o maior valor print() print(f'Dados sobre a iteração ') print(f'erro: {erro}') print() print(f'x_next:') print(x_next) print() if erro > tol:#Caso o erro seja maior do que a tolerância, temos que x assumirá os valores de x^(k+1), e assim até ele satisfazer a condição de parada ou atingir o limite de iterações x = np.copy(x_next)#x recebe os valores de x^(k+1) desta iteração print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fim desta iteração <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print() iteracao += 1 else: print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Solução <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') print(x_next)#Exibe x^(k+1) print() print(f'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Fim do Método <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<') break
[ "numpy.copy", "numpy.abs", "numpy.any", "numpy.linalg.det", "numpy.max", "numpy.zeros", "numpy.zeros_like" ]
[((6268, 6303), 'numpy.zeros_like', 'np.zeros_like', (['self.vetor_constante'], {}), '(self.vetor_constante)\n', (6281, 6303), True, 'import numpy as np\n'), ((7572, 7607), 'numpy.zeros_like', 'np.zeros_like', (['self.vetor_constante'], {}), '(self.vetor_constante)\n', (7585, 7607), True, 'import numpy as np\n'), ((8887, 8900), 'numpy.max', 'np.max', (['alfas'], {}), '(alfas)\n', (8893, 8900), True, 'import numpy as np\n'), ((14435, 14470), 'numpy.zeros_like', 'np.zeros_like', (['self.vetor_constante'], {}), '(self.vetor_constante)\n', (14448, 14470), True, 'import numpy as np\n'), ((15463, 15476), 'numpy.max', 'np.max', (['betas'], {}), '(betas)\n', (15469, 15476), True, 'import numpy as np\n'), ((781, 822), 'numpy.zeros', 'np.zeros', ([], {'shape': '(self.matriz.shape[0], 1)'}), '(shape=(self.matriz.shape[0], 1))\n', (789, 822), True, 'import numpy as np\n'), ((1423, 1449), 'numpy.linalg.det', 'np.linalg.det', (['self.matriz'], {}), '(self.matriz)\n', (1436, 1449), True, 'import numpy as np\n'), ((1489, 1509), 'numpy.copy', 'np.copy', (['self.matriz'], {}), '(self.matriz)\n', (1496, 1509), True, 'import numpy as np\n'), ((1828, 1863), 'numpy.zeros_like', 'np.zeros_like', (['self.vetor_constante'], {}), '(self.vetor_constante)\n', (1841, 1863), True, 'import numpy as np\n'), ((10119, 10154), 'numpy.zeros_like', 'np.zeros_like', (['self.vetor_constante'], {}), '(self.vetor_constante)\n', (10132, 10154), True, 'import numpy as np\n'), ((10444, 10467), 'numpy.zeros', 'np.zeros', ([], {'shape': 'x.shape'}), '(shape=x.shape)\n', (10452, 10467), True, 'import numpy as np\n'), ((16876, 16911), 'numpy.zeros_like', 'np.zeros_like', (['self.vetor_constante'], {}), '(self.vetor_constante)\n', (16889, 16911), True, 'import numpy as np\n'), ((17212, 17228), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (17225, 17228), True, 'import numpy as np\n'), ((615, 638), 'numpy.any', 'np.any', (['vetor_constante'], {}), '(vetor_constante)\n', (621, 638), True, 'import numpy as np\n'), ((1618, 1649), 'numpy.linalg.det', 'np.linalg.det', (['matriz_transicao'], {}), '(matriz_transicao)\n', (1631, 1649), True, 'import numpy as np\n'), ((2620, 2646), 'numpy.copy', 'np.copy', (['self.matriz[:, i]'], {}), '(self.matriz[:, i])\n', (2627, 2646), True, 'import numpy as np\n'), ((8694, 8719), 'numpy.abs', 'np.abs', (['self.matriz[i, i]'], {}), '(self.matriz[i, i])\n', (8700, 8719), True, 'import numpy as np\n'), ((15283, 15308), 'numpy.abs', 'np.abs', (['self.matriz[i, i]'], {}), '(self.matriz[i, i])\n', (15289, 15308), True, 'import numpy as np\n'), ((2366, 2397), 'numpy.linalg.det', 'np.linalg.det', (['matriz_transicao'], {}), '(matriz_transicao)\n', (2379, 2397), True, 'import numpy as np\n'), ((8097, 8126), 'numpy.abs', 'np.abs', (['self.matriz[i, j + 1]'], {}), '(self.matriz[i, j + 1])\n', (8103, 8126), True, 'import numpy as np\n'), ((12385, 12403), 'numpy.abs', 'np.abs', (['(x_next - x)'], {}), '(x_next - x)\n', (12391, 12403), True, 'import numpy as np\n'), ((13573, 13588), 'numpy.copy', 'np.copy', (['x_next'], {}), '(x_next)\n', (13580, 13588), True, 'import numpy as np\n'), ((15078, 15103), 'numpy.abs', 'np.abs', (['self.matriz[i, j]'], {}), '(self.matriz[i, j])\n', (15084, 15103), True, 'import numpy as np\n'), ((19342, 19360), 'numpy.abs', 'np.abs', (['(x_next - x)'], {}), '(x_next - x)\n', (19348, 19360), True, 'import numpy as np\n'), ((19895, 19910), 'numpy.copy', 'np.copy', (['x_next'], {}), '(x_next)\n', (19902, 19910), True, 'import numpy as np\n'), ((8355, 8384), 'numpy.abs', 'np.abs', (['self.matriz[i, j + 1]'], {}), '(self.matriz[i, j + 1])\n', (8361, 8384), True, 'import numpy as np\n'), ((8576, 8601), 'numpy.abs', 'np.abs', (['self.matriz[i, j]'], {}), '(self.matriz[i, j])\n', (8582, 8601), True, 'import numpy as np\n'), ((15194, 15219), 'numpy.abs', 'np.abs', (['self.matriz[i, j]'], {}), '(self.matriz[i, j])\n', (15200, 15219), True, 'import numpy as np\n')]
import pywt import numpy as np import matplotlib.pyplot as plt from scripts.dwt_multiresolution import dwt_multiresolution def dwt_no_edge_effects(data, padding_type='mirror', pad_size=0.5, wtype='sym2', nlevels=5): # --- PAD SIGNAL dataL = len(data) if type(pad_size) is float: # relative window size pad_size = int(pad_size * dataL) if padding_type is 'mirror': data_p = (data[:pad_size][::-1], data[-pad_size:][::-1]) elif padding_type is 'zeros': data_p = (np.zeros(pad_size), np.zeros(pad_size)) data_p = np.vstack( (data_p[0], data, data_p[1]) ) # --- COMPUTE DWT dwt = dwt_multiresolution(data_p, wtype, nlevels) # --- UN-PAD SIGNAL padsz = np.divide(dataL, np.power(2, range(2, nlevels + 2))) padsz = np.insert(padsz, -1, padsz[-1]) dwt = np.vstack( [x[int(y):-int(y)] for x,y in zip(dwt, padsz)] ) assert len(dwt)==len(data) return dwt def test_dwt_no_edge_effects(): # generate random signal sig = np.random.random(1000) # Decompose dwt_m = dwt_no_edge_effects(sig, 'mirror') sig_m = np.sum(dwt_m, axis=0) dwt_z = dwt_no_edge_effects(sig, 'zeros') sig_z = np.sum(dwt_z, axis=0) # Plot plt.figure() plt.plot(sig, label='original signal') plt.plot(sig_m, '--r', label='Mirror padding') plt.plot(sig_z, '--g', label='Zero padding') plt.legend() if __name__=='__main__': test_dwt_no_edge_effects()
[ "numpy.insert", "numpy.random.random", "matplotlib.pyplot.plot", "scripts.dwt_multiresolution.dwt_multiresolution", "numpy.sum", "matplotlib.pyplot.figure", "numpy.zeros", "numpy.vstack", "matplotlib.pyplot.legend" ]
[((594, 633), 'numpy.vstack', 'np.vstack', (['(data_p[0], data, data_p[1])'], {}), '((data_p[0], data, data_p[1]))\n', (603, 633), True, 'import numpy as np\n'), ((675, 718), 'scripts.dwt_multiresolution.dwt_multiresolution', 'dwt_multiresolution', (['data_p', 'wtype', 'nlevels'], {}), '(data_p, wtype, nlevels)\n', (694, 718), False, 'from scripts.dwt_multiresolution import dwt_multiresolution\n'), ((829, 860), 'numpy.insert', 'np.insert', (['padsz', '(-1)', 'padsz[-1]'], {}), '(padsz, -1, padsz[-1])\n', (838, 860), True, 'import numpy as np\n'), ((1062, 1084), 'numpy.random.random', 'np.random.random', (['(1000)'], {}), '(1000)\n', (1078, 1084), True, 'import numpy as np\n'), ((1168, 1189), 'numpy.sum', 'np.sum', (['dwt_m'], {'axis': '(0)'}), '(dwt_m, axis=0)\n', (1174, 1189), True, 'import numpy as np\n'), ((1256, 1277), 'numpy.sum', 'np.sum', (['dwt_z'], {'axis': '(0)'}), '(dwt_z, axis=0)\n', (1262, 1277), True, 'import numpy as np\n'), ((1293, 1305), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1303, 1305), True, 'import matplotlib.pyplot as plt\n'), ((1310, 1348), 'matplotlib.pyplot.plot', 'plt.plot', (['sig'], {'label': '"""original signal"""'}), "(sig, label='original signal')\n", (1318, 1348), True, 'import matplotlib.pyplot as plt\n'), ((1353, 1399), 'matplotlib.pyplot.plot', 'plt.plot', (['sig_m', '"""--r"""'], {'label': '"""Mirror padding"""'}), "(sig_m, '--r', label='Mirror padding')\n", (1361, 1399), True, 'import matplotlib.pyplot as plt\n'), ((1404, 1448), 'matplotlib.pyplot.plot', 'plt.plot', (['sig_z', '"""--g"""'], {'label': '"""Zero padding"""'}), "(sig_z, '--g', label='Zero padding')\n", (1412, 1448), True, 'import matplotlib.pyplot as plt\n'), ((1453, 1465), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1463, 1465), True, 'import matplotlib.pyplot as plt\n'), ((538, 556), 'numpy.zeros', 'np.zeros', (['pad_size'], {}), '(pad_size)\n', (546, 556), True, 'import numpy as np\n'), ((558, 576), 'numpy.zeros', 'np.zeros', (['pad_size'], {}), '(pad_size)\n', (566, 576), True, 'import numpy as np\n')]
""" This Module handles aspects of the agent architecture's decision-making and gameplay. """ # pylint: disable=import-error import random from ..RobotBehaviorList.RobotBehaviorList import RobotRoles from ..RobotBehaviorList.RobotBehaviorList import RobotRolesBehaviorsMap import numpy as np import os import pandas as pd import math import itertools import sys import sklearn.pipeline import sklearn.preprocessing from sklearn.externals import joblib import pickle import os.path if "../" not in sys.path: sys.path.append("../") from sklearn.linear_model import SGDRegressor from sklearn.kernel_approximation import RBFSampler from sklearn.externals import joblib RL_FOLDER = "iSpyGameController/saved_rl/" class EnvBuilder(): def __init__(self,child_id): self.A_map = {'EXPERT':0, 'NOVICE':1} #.name .value self.S_features = ['s1_total_turns','s2_prev_expert_roles','s3_child_correct_answers'] self.reward_label = 'rl_reward_scores' self.nA = len(self.A_map.keys()) self.nS = len(self.S_features) self.child_id = child_id self.S_dict = pickle.load( open( RL_FOLDER + "s_dict.p", "rb" ) ) self.scaler = joblib.load(RL_FOLDER + 'scaler.pkl') def get_rl_state(self,features): i = '-'.join([str(i) for i in list(features)]) print("rl state: {}".format(i)) if not i in self.S_dict.keys(): print("cannot find {} in s dict".format(i)) self.S_dict.update({i:len(self.S_dict)}) return self.S_dict[i] def get_state_features(self,state): def quadratic(arr): arr = arr.tolist() qual =list(map(lambda x: math.pow(x,2),arr)) ilist =arr + qual + [arr[0]*arr[1]*arr[2], qual[0]*qual[1]*qual[2]] for each in itertools.permutations(arr,2): ilist += [math.pow(each[0],2)*each[1], math.pow(each[1],2)*each[0]] for each in itertools.combinations(arr,2): ilist += [each[0]*each[1], math.pow(each[0],2)*math.pow(each[1],2)] return ilist def val(ar): return [ar[0], ar[1], ar[2], ar[0]*ar[1],ar[0]*ar[2],ar[1]*ar[2], ar[0]*ar[1]*ar[2], math.pow(ar[0],2)*ar[1],math.pow(ar[1],2)*ar[0],math.pow(ar[0],2)*ar[2],math.pow(ar[1],2)*ar[2], math.pow(ar[2],2)*ar[1],math.pow(ar[2],2)*ar[0]] def generate_features(ar): return val(ar) for i,v in self.S_dict.items(): if state == v: return generate_features(self.scaler.transform([[float(m) for m in i.split('-')]])[0]) break print("cannot find state features!!! {}".format(state)) return "nan" class Estimator(): """ Value Function approximator. """ def __init__(self,env,reset= False): def retrive_regressor_models(): if os.path.isfile(self.model_names[0]) and reset == False: model_0 = joblib.load(self.model_names[0]) model_1 = joblib.load(self.model_names[1]) return [model_0, model_1] else: model_0 = joblib.load(RL_FOLDER + 'pretrained_regressor_model_0.pkl') model_1 = joblib.load(RL_FOLDER + 'pretrained_regressor_model_1.pkl') return [model_0, model_1] self.model_names = [RL_FOLDER+env.child_id+'_regressor_model_0.pkl', RL_FOLDER+env.child_id+'_regressor_model_1.pkl'] self.models = retrive_regressor_models() self.env = env def save_updated_regressor_models(self): '''called at the end of each task mission''' for i in range(len(self.model_names)): joblib.dump(self.models[i], self.model_names[i]) def featurize_state(self, state): return self.env.get_state_features(state) def predict(self, s, a=None): """ Makes value function predictions """ features = self.featurize_state(s) if not a: return np.array([m.predict([features])[0] for m in self.models]) else: return self.models[a].predict([features])[0] def update(self, s, a, y): """ Updates the estimator parameters for a given state and action towards the target y. """ features = self.featurize_state(s) self.models[a].partial_fit([features], [y]) def get_weights(self): for i in self.models: print("model weights: {}".format(i.coef_ )) class QModel(): def initialize_q_learning(self, env, estimator, initial_features, reset=False, discount_factor=0.5, epsilon=0.25, epsilon_decay=1.0): '''''' self.env = env self.estimator = estimator self.discount_factor = discount_factor self.epsilon = epsilon self.epsilon_decay = epsilon_decay try: self.i_episode = pickle.load( open( RL_FOLDER+self.env.child_id+"_i_episode.pkl", "rb" ) ) if reset == False else 0 self.action_history = pickle.load(open(RL_FOLDER+self.env.child_id+"_action_history.pkl","rb")) if reset == False else dict() except: self.i_episode = 0 self.action_history = dict() ## load self.i_time = 0 self.start_state = self.env.get_rl_state(initial_features) def save_rl(self): '''save after each timestamp''' pickle.dump(self.action_history, open(RL_FOLDER+self.env.child_id+"_action_history.pkl","wb")) pickle.dump(self.i_episode, open(RL_FOLDER+self.env.child_id+"_i_episode.pkl","wb")) self.estimator.save_updated_regressor_models() def q_new_episode(self,initial_features): '''called when the child finishes the first turn for a given task. then call q_get_action''' self.i_episode += 1 # Reset the environment and pick the first action self.start_state = self.env.get_rl_state(initial_features) self.action_history.update({self.i_episode:{}}) def q_get_action(self): def make_epsilon_greedy_policy( epsilon): def policy_fn(observation): print("observation: {}".format(observation)) A = np.ones(self.env.nA, dtype=float) * epsilon / self.env.nA q_values = self.estimator.predict(observation) best_action = np.argmax(q_values) A[best_action] += (1.0 - epsilon) print("++++++++++++~~cur epsilon: {} : best action: {}".format(epsilon,best_action)) return A return policy_fn # The policy we're following policy = make_epsilon_greedy_policy( self.epsilon * self.epsilon_decay**self.i_episode) next_action = None # Choose an action to take # If we're using SARSA we already decided in the previous step if next_action is None: action_probs = policy(self.start_state) self.action = np.random.choice(np.arange(len(action_probs)), p=action_probs) print("~action probs: {}:{}. action: {}".format(action_probs[0],action_probs[1],self.action)) else: self.action = next_action return self.action def q_learning_evaluate(self,next_state,reward,vocab_word): print("\n=======current episode: {}=========".format(self.i_episode)) print("+++++++++++++++++++++++reward++++++++++++: {}".format(reward)) if isinstance(next_state, list): next_state = self.env.get_rl_state(next_state) self.i_time += 1 # TD Update q_values_next = self.estimator.predict(next_state) cur_q_values = self.estimator.predict(self.start_state) print("q values next: {} | current q values: {}".format(q_values_next,cur_q_values)) # Use this code for Q-Learning # Q-Value TD Target td_target = reward + self.discount_factor * np.max(q_values_next) print("timeframe: {} cur state: {}, next state: {}, action: {}, reward: {}, max: {}, td target: {}".format(self.i_time, self.start_state, next_state, self.action, reward,np.max(q_values_next),td_target)) if not self.i_episode in self.action_history.keys(): self.action_history.update({self.i_episode:{}}) self.action_history[self.i_episode].update({self.i_time: [vocab_word,self.start_state, next_state, self.action, reward,np.max(cur_q_values), np.max(q_values_next),td_target]}) # Use this code for SARSA TD Target for on policy-training: # next_action_probs = policy(next_state) # next_action = np.random.choice(np.arange(len(next_action_probs)), p=next_action_probs) # td_target = reward + discount_factor * q_values_next[next_action] # Update the function approximator using our target self.estimator.update(self.start_state, self.action, td_target) print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") self.start_state = next_state
[ "numpy.ones", "math.pow", "sklearn.externals.joblib.load", "numpy.argmax", "numpy.max", "itertools.combinations", "os.path.isfile", "sklearn.externals.joblib.dump", "itertools.permutations", "sys.path.append" ]
[((511, 533), 'sys.path.append', 'sys.path.append', (['"""../"""'], {}), "('../')\n", (526, 533), False, 'import sys\n'), ((1200, 1237), 'sklearn.externals.joblib.load', 'joblib.load', (["(RL_FOLDER + 'scaler.pkl')"], {}), "(RL_FOLDER + 'scaler.pkl')\n", (1211, 1237), False, 'from sklearn.externals import joblib\n'), ((1829, 1859), 'itertools.permutations', 'itertools.permutations', (['arr', '(2)'], {}), '(arr, 2)\n', (1851, 1859), False, 'import itertools\n'), ((1968, 1998), 'itertools.combinations', 'itertools.combinations', (['arr', '(2)'], {}), '(arr, 2)\n', (1990, 1998), False, 'import itertools\n'), ((3766, 3814), 'sklearn.externals.joblib.dump', 'joblib.dump', (['self.models[i]', 'self.model_names[i]'], {}), '(self.models[i], self.model_names[i])\n', (3777, 3814), False, 'from sklearn.externals import joblib\n'), ((2937, 2972), 'os.path.isfile', 'os.path.isfile', (['self.model_names[0]'], {}), '(self.model_names[0])\n', (2951, 2972), False, 'import os\n'), ((3019, 3051), 'sklearn.externals.joblib.load', 'joblib.load', (['self.model_names[0]'], {}), '(self.model_names[0])\n', (3030, 3051), False, 'from sklearn.externals import joblib\n'), ((3078, 3110), 'sklearn.externals.joblib.load', 'joblib.load', (['self.model_names[1]'], {}), '(self.model_names[1])\n', (3089, 3110), False, 'from sklearn.externals import joblib\n'), ((3198, 3257), 'sklearn.externals.joblib.load', 'joblib.load', (["(RL_FOLDER + 'pretrained_regressor_model_0.pkl')"], {}), "(RL_FOLDER + 'pretrained_regressor_model_0.pkl')\n", (3209, 3257), False, 'from sklearn.externals import joblib\n'), ((3285, 3344), 'sklearn.externals.joblib.load', 'joblib.load', (["(RL_FOLDER + 'pretrained_regressor_model_1.pkl')"], {}), "(RL_FOLDER + 'pretrained_regressor_model_1.pkl')\n", (3296, 3344), False, 'from sklearn.externals import joblib\n'), ((6452, 6471), 'numpy.argmax', 'np.argmax', (['q_values'], {}), '(q_values)\n', (6461, 6471), True, 'import numpy as np\n'), ((8084, 8105), 'numpy.max', 'np.max', (['q_values_next'], {}), '(q_values_next)\n', (8090, 8105), True, 'import numpy as np\n'), ((8284, 8305), 'numpy.max', 'np.max', (['q_values_next'], {}), '(q_values_next)\n', (8290, 8305), True, 'import numpy as np\n'), ((2247, 2265), 'math.pow', 'math.pow', (['ar[0]', '(2)'], {}), '(ar[0], 2)\n', (2255, 2265), False, 'import math\n'), ((2271, 2289), 'math.pow', 'math.pow', (['ar[1]', '(2)'], {}), '(ar[1], 2)\n', (2279, 2289), False, 'import math\n'), ((2295, 2313), 'math.pow', 'math.pow', (['ar[0]', '(2)'], {}), '(ar[0], 2)\n', (2303, 2313), False, 'import math\n'), ((2319, 2337), 'math.pow', 'math.pow', (['ar[1]', '(2)'], {}), '(ar[1], 2)\n', (2327, 2337), False, 'import math\n'), ((2365, 2383), 'math.pow', 'math.pow', (['ar[2]', '(2)'], {}), '(ar[2], 2)\n', (2373, 2383), False, 'import math\n'), ((2389, 2407), 'math.pow', 'math.pow', (['ar[2]', '(2)'], {}), '(ar[2], 2)\n', (2397, 2407), False, 'import math\n'), ((8574, 8594), 'numpy.max', 'np.max', (['cur_q_values'], {}), '(cur_q_values)\n', (8580, 8594), True, 'import numpy as np\n'), ((8596, 8617), 'numpy.max', 'np.max', (['q_values_next'], {}), '(q_values_next)\n', (8602, 8617), True, 'import numpy as np\n'), ((1705, 1719), 'math.pow', 'math.pow', (['x', '(2)'], {}), '(x, 2)\n', (1713, 1719), False, 'import math\n'), ((1886, 1906), 'math.pow', 'math.pow', (['each[0]', '(2)'], {}), '(each[0], 2)\n', (1894, 1906), False, 'import math\n'), ((1915, 1935), 'math.pow', 'math.pow', (['each[1]', '(2)'], {}), '(each[1], 2)\n', (1923, 1935), False, 'import math\n'), ((2042, 2062), 'math.pow', 'math.pow', (['each[0]', '(2)'], {}), '(each[0], 2)\n', (2050, 2062), False, 'import math\n'), ((2062, 2082), 'math.pow', 'math.pow', (['each[1]', '(2)'], {}), '(each[1], 2)\n', (2070, 2082), False, 'import math\n'), ((6301, 6334), 'numpy.ones', 'np.ones', (['self.env.nA'], {'dtype': 'float'}), '(self.env.nA, dtype=float)\n', (6308, 6334), True, 'import numpy as np\n')]
# This code is part of Qiskit. # # (C) Copyright IBM 2017, 2018. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Test StateVectorSimulatorPy.""" import unittest import numpy as np from qiskit.providers.basicaer import StatevectorSimulatorPy from qiskit.test import ReferenceCircuits from qiskit.test import providers from qiskit import QuantumRegister, QuantumCircuit, execute from qiskit.quantum_info.random import random_unitary from qiskit.quantum_info import state_fidelity class StatevectorSimulatorTest(providers.BackendTestCase): """Test BasicAer statevector simulator.""" backend_cls = StatevectorSimulatorPy circuit = None def test_run_circuit(self): """Test final state vector for single circuit run.""" # Set test circuit self.circuit = ReferenceCircuits.bell_no_measure() # Execute result = super().test_run_circuit() actual = result.get_statevector(self.circuit) # state is 1/sqrt(2)|00> + 1/sqrt(2)|11>, up to a global phase self.assertAlmostEqual((abs(actual[0])) ** 2, 1 / 2) self.assertEqual(actual[1], 0) self.assertEqual(actual[2], 0) self.assertAlmostEqual((abs(actual[3])) ** 2, 1 / 2) def test_measure_collapse(self): """Test final measurement collapses statevector""" # Set test circuit self.circuit = ReferenceCircuits.bell() # Execute result = super().test_run_circuit() actual = result.get_statevector(self.circuit) # The final state should be EITHER |00> OR |11> diff_00 = np.linalg.norm(np.array([1, 0, 0, 0]) - actual) ** 2 diff_11 = np.linalg.norm(np.array([0, 0, 0, 1]) - actual) ** 2 success = np.allclose([diff_00, diff_11], [0, 2]) or np.allclose([diff_00, diff_11], [2, 0]) # state is 1/sqrt(2)|00> + 1/sqrt(2)|11>, up to a global phase self.assertTrue(success) def test_unitary(self): """Test unitary gate instruction""" num_trials = 10 max_qubits = 3 # Test 1 to max_qubits for random n-qubit unitary gate for i in range(max_qubits): num_qubits = i + 1 psi_init = np.zeros(2**num_qubits) psi_init[0] = 1.0 qr = QuantumRegister(num_qubits, "qr") for _ in range(num_trials): # Create random unitary unitary = random_unitary(2**num_qubits) # Compute expected output state psi_target = unitary.data.dot(psi_init) # Simulate output on circuit circuit = QuantumCircuit(qr) circuit.unitary(unitary, qr) job = execute(circuit, self.backend) result = job.result() psi_out = result.get_statevector(0) fidelity = state_fidelity(psi_target, psi_out) self.assertGreater(fidelity, 0.999) def test_global_phase(self): """Test global_phase""" n_qubits = 4 qr = QuantumRegister(n_qubits) circ = QuantumCircuit(qr) circ.x(qr) circ.global_phase = 0.5 self.circuit = circ result = super().test_run_circuit() actual = result.get_statevector(self.circuit) expected = np.exp(1j * circ.global_phase) * np.repeat([[0], [1]], [n_qubits**2 - 1, 1]) self.assertTrue(np.allclose(actual, expected)) def test_global_phase_composite(self): """Test global_phase""" n_qubits = 4 qr = QuantumRegister(n_qubits) circ = QuantumCircuit(qr) circ.x(qr) circ.global_phase = 0.5 gate = circ.to_gate() comp = QuantumCircuit(qr) comp.append(gate, qr) comp.global_phase = 0.1 self.circuit = comp result = super().test_run_circuit() actual = result.get_statevector(self.circuit) expected = np.exp(1j * 0.6) * np.repeat([[0], [1]], [n_qubits**2 - 1, 1]) self.assertTrue(np.allclose(actual, expected)) if __name__ == "__main__": unittest.main()
[ "qiskit.quantum_info.random.random_unitary", "numpy.allclose", "numpy.repeat", "qiskit.execute", "qiskit.test.ReferenceCircuits.bell", "qiskit.test.ReferenceCircuits.bell_no_measure", "numpy.exp", "qiskit.quantum_info.state_fidelity", "numpy.zeros", "numpy.array", "unittest.main", "qiskit.Quan...
[((4427, 4442), 'unittest.main', 'unittest.main', ([], {}), '()\n', (4440, 4442), False, 'import unittest\n'), ((1168, 1203), 'qiskit.test.ReferenceCircuits.bell_no_measure', 'ReferenceCircuits.bell_no_measure', ([], {}), '()\n', (1201, 1203), False, 'from qiskit.test import ReferenceCircuits\n'), ((1739, 1763), 'qiskit.test.ReferenceCircuits.bell', 'ReferenceCircuits.bell', ([], {}), '()\n', (1761, 1763), False, 'from qiskit.test import ReferenceCircuits\n'), ((3395, 3420), 'qiskit.QuantumRegister', 'QuantumRegister', (['n_qubits'], {}), '(n_qubits)\n', (3410, 3420), False, 'from qiskit import QuantumRegister, QuantumCircuit, execute\n'), ((3436, 3454), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['qr'], {}), '(qr)\n', (3450, 3454), False, 'from qiskit import QuantumRegister, QuantumCircuit, execute\n'), ((3893, 3918), 'qiskit.QuantumRegister', 'QuantumRegister', (['n_qubits'], {}), '(n_qubits)\n', (3908, 3918), False, 'from qiskit import QuantumRegister, QuantumCircuit, execute\n'), ((3934, 3952), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['qr'], {}), '(qr)\n', (3948, 3952), False, 'from qiskit import QuantumRegister, QuantumCircuit, execute\n'), ((4050, 4068), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['qr'], {}), '(qr)\n', (4064, 4068), False, 'from qiskit import QuantumRegister, QuantumCircuit, execute\n'), ((2097, 2136), 'numpy.allclose', 'np.allclose', (['[diff_00, diff_11]', '[0, 2]'], {}), '([diff_00, diff_11], [0, 2])\n', (2108, 2136), True, 'import numpy as np\n'), ((2140, 2179), 'numpy.allclose', 'np.allclose', (['[diff_00, diff_11]', '[2, 0]'], {}), '([diff_00, diff_11], [2, 0])\n', (2151, 2179), True, 'import numpy as np\n'), ((2557, 2582), 'numpy.zeros', 'np.zeros', (['(2 ** num_qubits)'], {}), '(2 ** num_qubits)\n', (2565, 2582), True, 'import numpy as np\n'), ((2628, 2661), 'qiskit.QuantumRegister', 'QuantumRegister', (['num_qubits', '"""qr"""'], {}), "(num_qubits, 'qr')\n", (2643, 2661), False, 'from qiskit import QuantumRegister, QuantumCircuit, execute\n'), ((3651, 3683), 'numpy.exp', 'np.exp', (['(1.0j * circ.global_phase)'], {}), '(1.0j * circ.global_phase)\n', (3657, 3683), True, 'import numpy as np\n'), ((3684, 3729), 'numpy.repeat', 'np.repeat', (['[[0], [1]]', '[n_qubits ** 2 - 1, 1]'], {}), '([[0], [1]], [n_qubits ** 2 - 1, 1])\n', (3693, 3729), True, 'import numpy as np\n'), ((3752, 3781), 'numpy.allclose', 'np.allclose', (['actual', 'expected'], {}), '(actual, expected)\n', (3763, 3781), True, 'import numpy as np\n'), ((4276, 4294), 'numpy.exp', 'np.exp', (['(1.0j * 0.6)'], {}), '(1.0j * 0.6)\n', (4282, 4294), True, 'import numpy as np\n'), ((4295, 4340), 'numpy.repeat', 'np.repeat', (['[[0], [1]]', '[n_qubits ** 2 - 1, 1]'], {}), '([[0], [1]], [n_qubits ** 2 - 1, 1])\n', (4304, 4340), True, 'import numpy as np\n'), ((4363, 4392), 'numpy.allclose', 'np.allclose', (['actual', 'expected'], {}), '(actual, expected)\n', (4374, 4392), True, 'import numpy as np\n'), ((2768, 2799), 'qiskit.quantum_info.random.random_unitary', 'random_unitary', (['(2 ** num_qubits)'], {}), '(2 ** num_qubits)\n', (2782, 2799), False, 'from qiskit.quantum_info.random import random_unitary\n'), ((2973, 2991), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['qr'], {}), '(qr)\n', (2987, 2991), False, 'from qiskit import QuantumRegister, QuantumCircuit, execute\n'), ((3059, 3089), 'qiskit.execute', 'execute', (['circuit', 'self.backend'], {}), '(circuit, self.backend)\n', (3066, 3089), False, 'from qiskit import QuantumRegister, QuantumCircuit, execute\n'), ((3207, 3242), 'qiskit.quantum_info.state_fidelity', 'state_fidelity', (['psi_target', 'psi_out'], {}), '(psi_target, psi_out)\n', (3221, 3242), False, 'from qiskit.quantum_info import state_fidelity\n'), ((1970, 1992), 'numpy.array', 'np.array', (['[1, 0, 0, 0]'], {}), '([1, 0, 0, 0])\n', (1978, 1992), True, 'import numpy as np\n'), ((2041, 2063), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {}), '([0, 0, 0, 1])\n', (2049, 2063), True, 'import numpy as np\n')]
''' Socket-based multicopter class Copyright(C) 2021 <NAME> MIT License ''' from threading import Thread import socket import numpy as np from sys import stdout from time import sleep import cv2 class Multicopter(object): # See Bouabdallah (2004) (STATE_X, STATE_DX, STATE_Y, STATE_DY, STATE_Z, STATE_DZ, STATE_PHI, STATE_DPHI, STATE_THETA, STATE_DTHETA, STATE_PSI, STATE_DPSI) = range(12) def __init__( self, host='127.0.0.1', motor_port=5000, telem_port=5001, image_port=5002, image_rows=480, image_cols=640): self.host = host self.motor_port = motor_port self.telem_port = telem_port self.image_port = image_port self.image_rows = image_rows self.image_cols = image_cols self.telem = None self.image = None def start(self): done = [False] # Telemetry in and motors out run on their own thread motorClientSocket = Multicopter._make_udpsocket() telemetryServerSocket = Multicopter._make_udpsocket() telemetryServerSocket.bind((self.host, self.telem_port)) Multicopter.debug('Hit the Play button ...') telemetryThread = Thread(target=self._run_telemetry, args=( telemetryServerSocket, motorClientSocket, done)) # Serve a socket with a maximum of one client imageServerSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) imageServerSocket.bind((self.host, self.image_port)) imageServerSocket.listen(1) # This will block (wait) until a client connets imageConn, _ = imageServerSocket.accept() imageConn.settimeout(1) Multicopter.debug('Got a connection!') telemetryThread.start() while not done[0]: try: imgbytes = imageConn.recv(self.image_rows*self.image_cols*4) except Exception: # likely a timeout from sim quitting break if len(imgbytes) == self.image_rows*self.image_cols*4: rgba_image = np.reshape(np.frombuffer(imgbytes, 'uint8'), (self.image_rows, self.image_cols, 4)) image = cv2.cvtColor(rgba_image, cv2.COLOR_RGBA2RGB) self.handleImage(image) sleep(.001) def handleImage(self, image): ''' Override for your application ''' cv2.imshow('Image', image) cv2.waitKey(1) def getMotors(self, time, state): ''' Override for your application ''' return np.array([0.6, 0.6, 0.6, 0.6]) @staticmethod def debug(msg): print(msg) stdout.flush() def _run_telemetry(self, telemetryServerSocket, motorClientSocket, done): running = False while True: try: data, _ = telemetryServerSocket.recvfrom(8*13) except Exception: done[0] = True break telemetryServerSocket.settimeout(.1) telem = np.frombuffer(data) if not running: Multicopter.debug('Running') running = True if telem[0] < 0: motorClientSocket.close() telemetryServerSocket.close() break motorvals = self.getMotors(telem[0], telem[1:]) motorClientSocket.sendto(np.ndarray.tobytes(motorvals), (self.host, self.motor_port)) sleep(.001) @staticmethod def _make_udpsocket(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) return sock
[ "numpy.frombuffer", "numpy.ndarray.tobytes", "socket.socket", "time.sleep", "cv2.imshow", "numpy.array", "cv2.cvtColor", "threading.Thread", "sys.stdout.flush", "cv2.waitKey" ]
[((1315, 1408), 'threading.Thread', 'Thread', ([], {'target': 'self._run_telemetry', 'args': '(telemetryServerSocket, motorClientSocket, done)'}), '(target=self._run_telemetry, args=(telemetryServerSocket,\n motorClientSocket, done))\n', (1321, 1408), False, 'from threading import Thread\n'), ((1639, 1688), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (1652, 1688), False, 'import socket\n'), ((2682, 2708), 'cv2.imshow', 'cv2.imshow', (['"""Image"""', 'image'], {}), "('Image', image)\n", (2692, 2708), False, 'import cv2\n'), ((2717, 2731), 'cv2.waitKey', 'cv2.waitKey', (['(1)'], {}), '(1)\n', (2728, 2731), False, 'import cv2\n'), ((2848, 2878), 'numpy.array', 'np.array', (['[0.6, 0.6, 0.6, 0.6]'], {}), '([0.6, 0.6, 0.6, 0.6])\n', (2856, 2878), True, 'import numpy as np\n'), ((2945, 2959), 'sys.stdout.flush', 'stdout.flush', ([], {}), '()\n', (2957, 2959), False, 'from sys import stdout\n'), ((3869, 3917), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (3882, 3917), False, 'import socket\n'), ((2565, 2577), 'time.sleep', 'sleep', (['(0.001)'], {}), '(0.001)\n', (2570, 2577), False, 'from time import sleep\n'), ((3320, 3339), 'numpy.frombuffer', 'np.frombuffer', (['data'], {}), '(data)\n', (3333, 3339), True, 'import numpy as np\n'), ((3795, 3807), 'time.sleep', 'sleep', (['(0.001)'], {}), '(0.001)\n', (3800, 3807), False, 'from time import sleep\n'), ((2466, 2510), 'cv2.cvtColor', 'cv2.cvtColor', (['rgba_image', 'cv2.COLOR_RGBA2RGB'], {}), '(rgba_image, cv2.COLOR_RGBA2RGB)\n', (2478, 2510), False, 'import cv2\n'), ((3684, 3713), 'numpy.ndarray.tobytes', 'np.ndarray.tobytes', (['motorvals'], {}), '(motorvals)\n', (3702, 3713), True, 'import numpy as np\n'), ((2328, 2360), 'numpy.frombuffer', 'np.frombuffer', (['imgbytes', '"""uint8"""'], {}), "(imgbytes, 'uint8')\n", (2341, 2360), True, 'import numpy as np\n')]
import numpy as np import pandas as pd import random import math import itertools from sklearn.model_selection import train_test_split from sklearn import tree from sklearn.metrics import accuracy_score, r2_score from sklearn.metrics import confusion_matrix #review_data = pd.read_csv("./preprocessed_googleplaystore.csv", usecols=["Price", "Installs", "Reviews", "Rating"]) #review_data = review_data.sample(frac=1).reset_index(drop=True)#shuffle def chunks(arr, m): n = int(math.ceil(len(arr) / float(m))) return [arr[i:i + n] for i in range(0, len(arr), n)] def DecisionTree(train_data, feature_selected): # First separate feature and target train_x = train_data[feature_selected] train_y = train_data.loc[:, "class"] classifier = tree.DecisionTreeClassifier(criterion="entropy", max_depth=3, random_state=None) iris_clr = classifier.fit(train_x, train_y) return iris_clr def BootstrapResample(train_data): n = len(train_data) resample_i = np.floor(np.random.rand(n)*len(train_data)).astype(int) train_resampled = train.iloc[resample_i] df_train = pd.DataFrame(train_resampled, columns=(iris.columns)) return df_train def VoteResult(lst): return max(lst, key=lst.count) iris_data = pd.read_csv("./preprocessed_iris.csv") mapping = {"Iris-setosa": "0", "Iris-versicolor": "1", "Iris-virginica": "2"} iris = iris_data.replace(mapping) iris = iris.sample(frac=1).reset_index(drop=True)#shuffle #K-fold validation K = 1 divided_data = chunks(iris, K) feature_list = list(iris.columns[:-1]) select_list = [] for L in range(1, len(feature_list)+1): for subset in itertools.combinations(feature_list, L): select_list.append(list(subset)) confusion_matrix_iris = np.zeros((3, 3), dtype=np.int) for i in range(K): ########################### choosing train_data and test_data x_train = iris[["sepal length", "sepal width", "petal length", "petal width"]] y_train = iris["class"] x_test = x_train y_test = y_train train = pd.concat([x_train, y_train], axis=1) ###########################train pred_list = [] # Build 100 trees for t in range(100): # Randomly select features and resample rng = np.random.randint(0, 15) select = select_list[rng] train_data = train[select] #print(train) single_tree_train = BootstrapResample(train_data) # test data also need to be reshaped x_test_reshaped = x_test[select] # Build tree clr = DecisionTree(single_tree_train, select) y_pred = clr.predict(x_test_reshaped) # First iteration, build empty 2d-list if(t == 0): for j in range(len(x_test)): pred_list.append([y_pred[j]]) else: for j in range(len(x_test)): pred_list[j].append(y_pred[j]) vote_list = [] for lst in pred_list: vote_list.append(VoteResult(lst)) ########################### build confusion_matrix arr = confusion_matrix(vote_list, y_test, labels=['0', '1', '2']) confusion_matrix_iris = confusion_matrix_iris + arr; ########################### print("\n","class =",["Iris-setosa", "Iris-versicolor", "Iris-virginica"],"\n") print(confusion_matrix_iris) precision = np.zeros(3) recall = np.zeros(3) accurate = 0 for i in range(0, 3): precision[i] = confusion_matrix_iris[i][i] / sum(confusion_matrix_iris[i]) recall[i] = confusion_matrix_iris[i][i] / sum([row[i] for row in confusion_matrix_iris]) accurate += confusion_matrix_iris[i][i] accuracy = accurate/sum(sum(confusion_matrix_iris)) print("precision =", precision) print("recall =", recall) print("accuracy =", accuracy)
[ "numpy.random.rand", "pandas.read_csv", "sklearn.tree.DecisionTreeClassifier", "itertools.combinations", "numpy.zeros", "numpy.random.randint", "pandas.DataFrame", "pandas.concat", "sklearn.metrics.confusion_matrix" ]
[((1258, 1296), 'pandas.read_csv', 'pd.read_csv', (['"""./preprocessed_iris.csv"""'], {}), "('./preprocessed_iris.csv')\n", (1269, 1296), True, 'import pandas as pd\n'), ((1761, 1791), 'numpy.zeros', 'np.zeros', (['(3, 3)'], {'dtype': 'np.int'}), '((3, 3), dtype=np.int)\n', (1769, 1791), True, 'import numpy as np\n'), ((3342, 3353), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (3350, 3353), True, 'import numpy as np\n'), ((3363, 3374), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (3371, 3374), True, 'import numpy as np\n'), ((765, 850), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {'criterion': '"""entropy"""', 'max_depth': '(3)', 'random_state': 'None'}), "(criterion='entropy', max_depth=3, random_state=None\n )\n", (792, 850), False, 'from sklearn import tree\n'), ((1111, 1162), 'pandas.DataFrame', 'pd.DataFrame', (['train_resampled'], {'columns': 'iris.columns'}), '(train_resampled, columns=iris.columns)\n', (1123, 1162), True, 'import pandas as pd\n'), ((1653, 1692), 'itertools.combinations', 'itertools.combinations', (['feature_list', 'L'], {}), '(feature_list, L)\n', (1675, 1692), False, 'import itertools\n'), ((2042, 2079), 'pandas.concat', 'pd.concat', (['[x_train, y_train]'], {'axis': '(1)'}), '([x_train, y_train], axis=1)\n', (2051, 2079), True, 'import pandas as pd\n'), ((3075, 3134), 'sklearn.metrics.confusion_matrix', 'confusion_matrix', (['vote_list', 'y_test'], {'labels': "['0', '1', '2']"}), "(vote_list, y_test, labels=['0', '1', '2'])\n", (3091, 3134), False, 'from sklearn.metrics import confusion_matrix\n'), ((2246, 2270), 'numpy.random.randint', 'np.random.randint', (['(0)', '(15)'], {}), '(0, 15)\n', (2263, 2270), True, 'import numpy as np\n'), ((1004, 1021), 'numpy.random.rand', 'np.random.rand', (['n'], {}), '(n)\n', (1018, 1021), True, 'import numpy as np\n')]
from __future__ import division from PyTorch_YOLOv3.utils.utils import * from PyTorch_YOLOv3.utils.datasets import * from PyTorch_YOLOv3.models import * from PyTorch_YOLOv3.utils.parse_config import * from VertebraSegmentation.coordinate import * from VertebraSegmentation.filp_and_rotate import * from VertebraSegmentation.net.data import VertebraDataset from VertebraSegmentation.net.model.unet import Unet from VertebraSegmentation.net.model.resunet import ResidualUNet import cv2 import math import os import sys import time import datetime import argparse import shutil from skimage.measure import label, regionprops from skimage.morphology import binary_dilation, binary_erosion, square from skimage.filters import sobel from skimage.color import gray2rgb from skimage import morphology from os.path import splitext, exists, join from PIL import Image import torch import torch.nn as nn import numpy as np from torch.utils.data import DataLoader from torchvision import datasets from torch.autograd import Variable from tqdm import tqdm from skimage import io import torch.nn.functional as F import matplotlib.pyplot as plt import matplotlib.patches as patches from matplotlib.ticker import NullLocator import os Max_H = 110 Max_W = 190 def preprocess(img): img = rgb2gray(img) bound = img.shape[0] // 3 up = exposure.equalize_adapthist(img[:bound, :]) down = exposure.equalize_adapthist(img[bound:, :]) enhance = np.append(up, down, axis=0) edge = sobel(gaussian(enhance, 2)) enhance = enhance + edge * 3 return np.where(enhance > 1, 1, enhance) def clahe_hist(img): clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8)) cl1 = clahe.apply(img) return cl1 def resize(image, size): image = F.interpolate(image.unsqueeze(0), size=size, mode="nearest").squeeze(0) return image def delete_gap_dir(dir): if os.path.isdir(dir): for d in os.listdir(dir): delete_gap_dir(os.path.join(dir, d)) if not os.listdir(dir): os.rmdir(dir) delete_gap_dir(os.getcwd()) def detect_one(img_path, modelSelcet="PyTorch_YOLOv3/checkpoints/yolov3_ckpt_best_f01.pth"): parser = argparse.ArgumentParser() parser.add_argument("--image_path", type=str, default=f"{img_path}", help="path to dataset") parser.add_argument("--model_def", type=str, default="PyTorch_YOLOv3/config/yolov3-custom.cfg", help="path to model definition file") parser.add_argument("--class_path", type=str, default="PyTorch_YOLOv3/data/custom/classes.names", help="path to class label file") parser.add_argument("--conf_thres", type=float, default=0.8, help="object confidence threshold") # 0.8 parser.add_argument("--nms_thres", type=float, default=0.3, help="iou thresshold for non-maximum suppression") # 0.25 parser.add_argument("--n_cpu", type=int, default=0, help="number of cpu threads to use during batch generation") parser.add_argument("--img_size", type=int, default=416, help="size of each image dimension") parser.add_argument("--checkpoint_model", type=str, default=f"{modelSelcet}", help="path to checkpoint model") opt = parser.parse_args() print(opt.checkpoint_model) device = torch.device("cuda" if torch.cuda.is_available() else "cpu") os.makedirs("./output", exist_ok=True) os.makedirs("./coordinate", exist_ok=True) # Set up model model = Darknet(opt.model_def, img_size=opt.img_size).to(device) # Load checkpoint weights model.load_state_dict(torch.load(opt.checkpoint_model)) classes = load_classes(opt.class_path) # Extracts class labels from file Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor print(opt.image_path + ".png") img = cv2.imread(opt.image_path + ".png", 0) img = clahe_hist(img) img = preprocess(img/255) img = transforms.ToTensor()(img).float() img, _ = pad_to_square(img, 0) img = resize(img, opt.img_size) print("\nPerforming object detection:") input_imgs = Variable(img.type(Tensor)).unsqueeze(0) detections = None with torch.no_grad(): detections = model(input_imgs) detections = non_max_suppression(detections, opt.conf_thres, opt.nms_thres) plt.set_cmap('gray') rewrite = True img = np.array(Image.open(img_path + ".png").convert('L')) plt.figure() fig, ax = plt.subplots(1) ax.imshow(img) # print(img.shape) filename = img_path[-4:] if detections is not None: # Rescale boxes to original image detections = rescale_boxes(detections[0], opt.img_size, img.shape[:2]) for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: box_w = x2 - x1 box_h = y2 - y1 x1, y1, x2, y2 = math.floor(x1), math.floor(y1), math.ceil(x2), math.ceil(y2) box_w, box_h = x2-x1, y2-y1 if rewrite: f1 = open(f"./coordinate/{filename}.txt", 'w') f1.write("{:d} {:d} {:d} {:d} {:d} {:d}\n".format(x1, y1, x2, y2, box_w, box_h) ) rewrite = False else: f1 = open(f"./coordinate/{filename}.txt", 'a') f1.write("{:d} {:d} {:d} {:d} {:d} {:d}\n".format(x1, y1, x2, y2, box_w, box_h) ) bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=0.5, edgecolor='red', facecolor="none") ax.add_patch(bbox) plt.axis("off") plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) plt.savefig(f"./output/{filename}.png", bbox_inches="tight", pad_inches=0.0, facecolor="none") plt.close() print("\nImage has saved") f1.close() path1 = join("./coordinate", filename) path2 = join("./GT_coordinate", filename) Sort_coordinate(f"{path1}.txt", flag=True) Sort_coordinate(f"{path2}.txt", flag=False) def detect(): parser = argparse.ArgumentParser() parser.add_argument("--image_folder", type=str, default="PyTorch_YOLOv3/data/custom/images/valid/", help="path to dataset") parser.add_argument("--model_def", type=str, default="PyTorch_YOLOv3/config/yolov3-custom.cfg", help="path to model definition file") parser.add_argument("--class_path", type=str, default="PyTorch_YOLOv3/data/custom/classes.names", help="path to class label file") parser.add_argument("--conf_thres", type=float, default=0.8, help="object confidence threshold") # 0.8 parser.add_argument("--nms_thres", type=float, default=0.3, help="iou thresshold for non-maximum suppression") # 0.25 parser.add_argument("--batch_size", type=int, default=1, help="size of the batches") parser.add_argument("--n_cpu", type=int, default=0, help="number of cpu threads to use during batch generation") parser.add_argument("--img_size", type=int, default=416, help="size of each image dimension") parser.add_argument("--checkpoint_model", type=str, default="PyTorch_YOLOv3/checkpoints/yolov3_ckpt_best_f01.pth", help="path to checkpoint model") opt = parser.parse_args() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") os.makedirs("PyTorch_YOLOv3/output", exist_ok=True) os.makedirs("PyTorch_YOLOv3/pre_img", exist_ok=True) os.makedirs("PyTorch_YOLOv3/coordinate", exist_ok=True) fname_list = [] for file in os.listdir(opt.image_folder): file_name = splitext(file)[0] fname_list.append(f"{file_name}.txt") fname_list = sorted(fname_list) # Set up model model = Darknet(opt.model_def, img_size=opt.img_size).to(device) # Load checkpoint weights model.load_state_dict(torch.load(opt.checkpoint_model)) model.eval() # Set in evaluation mode dataloader = DataLoader( ImageFolder(opt.image_folder, img_size=opt.img_size), batch_size=opt.batch_size, shuffle=False, num_workers=opt.n_cpu, ) classes = load_classes(opt.class_path) # Extracts class labels from file Tensor = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor imgs = [] # Stores image paths img_detections = [] # Stores detections for each image index print("\nPerforming object detection:") prev_time = time.time() for batch_i, (img_paths, input_imgs) in tqdm(enumerate(dataloader), total=len(dataloader), desc="Batch Inference Time"): # Configure input input_imgs = Variable(input_imgs.type(Tensor)) # Get detections with torch.no_grad(): detections = model(input_imgs) detections = non_max_suppression(detections, opt.conf_thres, opt.nms_thres) # Log progress current_time = time.time() inference_time = datetime.timedelta(seconds=current_time - prev_time) prev_time = current_time # print("\t+ Batch %d, Inference Time: %s" % (batch_i, inference_time)) # Save image and detections imgs.extend(img_paths) img_detections.extend(detections) plt.set_cmap('gray') rewrite = True print("\nSaving images:") for img_i, (path, detections) in enumerate(zip(imgs, img_detections)): print("(%d) Image: '%s'" % (img_i, path)) # Create plot img = np.array(Image.open(path).convert('L')) plt.figure() fig, ax = plt.subplots(1) ax.imshow(img) # Draw bounding boxes and labels of detections if detections is not None: # Rescale boxes to original image detections = rescale_boxes(detections, opt.img_size, img.shape[:2]) rewrite = True for x1, y1, x2, y2, conf, cls_conf, cls_pred in detections: # print("\t+ Label: %s, Conf: %.5f" % (classes[int(cls_pred)], cls_conf.item())) # x1 = x1 - 10 y1 = y1 - 5 y2 = y2 + 5 x1 = x1 - 50 x2 = x2 + 50 box_w = x2 - x1 box_h = y2 - y1 x1, y1, x2, y2 = math.floor(x1), math.floor(y1), math.ceil(x2), math.ceil(y2) box_w, box_h = x2-x1, y2-y1 if rewrite: f1 = open(f"VertebraSegmentation/coordinate/{fname_list[img_i]}", 'w') f2 = open(f"PyTorch_YOLOv3/coordinate/{fname_list[img_i]}", 'w') f1.write("{:d} {:d} {:d} {:d} {:d} {:d}\n".format(x1, y1, x2, y2, box_w, box_h) ) f2.write("{:d} {:d} {:d} {:d} {:d} {:d}\n".format(x1, y1, x2, y2, box_w, box_h) ) rewrite = False else: f1 = open(f"VertebraSegmentation/coordinate/{fname_list[img_i]}", 'a') f2 = open(f"PyTorch_YOLOv3/coordinate/{fname_list[img_i]}", 'a') f1.write("{:d} {:d} {:d} {:d} {:d} {:d}\n".format(x1, y1, x2, y2, box_w, box_h) ) f2.write("{:d} {:d} {:d} {:d} {:d} {:d}\n".format(x1, y1, x2, y2, box_w, box_h) ) # color = bbox_colors[int(np.where(unique_labels == int(cls_pred))[0])] # Create a Rectangle patch bbox = patches.Rectangle((x1, y1), box_w, box_h, linewidth=0.5, edgecolor='red', facecolor="none") # Add the bbox to the plot ax.add_patch(bbox) # Save generated image with detections plt.axis("off") plt.gca().xaxis.set_major_locator(NullLocator()) plt.gca().yaxis.set_major_locator(NullLocator()) # plt.set_cmap('gray') filename = path.split("/")[-1].split(".")[0] plt.savefig(f"PyTorch_YOLOv3/output/{filename}.png", bbox_inches="tight", pad_inches=0.0, facecolor="none") plt.close() # print(f"Max_Height={Max_H}", f"Max_Width={Max_W}") def create_valid_return_len(coordinate_path, save_path, source_path): os.makedirs(save_path, exist_ok=True) os.makedirs("VertebraSegmentation/test/valid", exist_ok=True) box_num = [] for file in tqdm(sorted(listdir(source_path)), desc=f"{save_path}"): img = cv2.imread(join(source_path, file), 0) boxes = get_information(file, coordinate_path) box_num.append(len(boxes)) for id, box in enumerate(boxes): box = list(map(int, box)) x1, y1, x2, y2 = box[0], box[1], box[2], box[3] width, height = box[4], box[5] detect_region = np.zeros((height, width)) detect_region = img[y1:y2+1, x1:x2+1] cv2.imwrite(join("VertebraSegmentation", "valid_data", f"{splitext(file)[0]}_{id}.png"), detect_region) return box_num def normalize_data(output, threshold=0.6): return np.where(output > threshold, 1, 0) def predict(model, loader, numOfEachImg, save_path="VertebraSegmentation//test//valid"): model.eval() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") result = np.zeros((1, 1200, 500), dtype=int) count = 0 with torch.no_grad(): for _, (img, filename) in tqdm(enumerate(loader), total=len(loader), desc="Predict"): index = int((splitext(filename[0])[0])[:4]) - 1 # 0, 1, 2, 3, ... , 19 id = int((splitext(filename[0])[0])[5:]) count += 1 img = img.to(device) output = model(img) output = torch.sigmoid(output)[0, :] output = (normalize_data(output.cpu().numpy())*255).astype(np.uint8) boxes = get_information(f"{(splitext(filename[0])[0])[:4]}.png", "VertebraSegmentation/coordinate") box = boxes[id] x1, y1, x2, y2 = int(box[0]), int(box[1]), int(box[2]), int(box[3]) result[:, y1:y2+1, x1:x2+1] = output if count == numOfEachImg[index]: result = result.astype(np.uint8) for dim in range(result.shape[0]): io.imsave(f"{save_path}//p{(splitext(filename[0])[0])[:4]}.png", result[dim]) result = np.zeros((1, 1200, 500), dtype=int) count = 0 def dice_coef(target, truth, empty=False, smooth=1.0): if not empty: target = target.flatten() truth = truth.flatten() union = np.sum(target) + np.sum(truth) intersection = np.sum(target * truth) dice = (2 * intersection + smooth) / (union + smooth) return dice else: print("aaaa") return 0 def create_valid_return_len_one(coordinate_path, save_path, source_path, target): os.makedirs(save_path, exist_ok=True) os.makedirs(source_path, exist_ok=True) img = cv2.imread(join(source_path, target), 0) boxes = get_information(target, coordinate_path) for id, box in enumerate(boxes): box = list(map(int, box)) x1, y1, x2, y2 = box[0], box[1], box[2], box[3] width, height = box[4], box[5] detect_region = np.zeros((height, width)) detect_region = img[y1:y2+1, x1:x2+1] cv2.imwrite(join(save_path, f"{splitext(target)[0]}_{id}.png"), detect_region) return len(boxes) def predict_one(model, loader, numOfImg, img, save_path=".//result"): os.makedirs(save_path, exist_ok=True) model.eval() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") result = np.zeros((1, 1200, 500), dtype=int) GT_path = join("./source/label", img) label_img = cv2.imread(GT_path, 0) # 2-dimension Dice_list = [None for _ in range(20)] bone_num = 0 GT_id = 0 id = 0 with torch.no_grad(): for _, (img, filename) in tqdm(enumerate(loader), total=len(loader), desc="Predict"): id = int((splitext(filename[0])[0])[5:]) img = img.to(device) # img is 4-dimension output = model(img) output = torch.sigmoid(output)[0, :] output = (normalize_data(output.cpu().numpy())*255).astype(np.uint8) boxes = get_information(f"{(splitext(filename[0])[0])[:4]}.png", "./coordinate") output = (output==255).astype(bool) output = morphology.remove_small_objects(output, min_size=2000, connectivity=2) output = output.astype(int) output = np.where(output==1, 255, 0) box = boxes[id] # print(id) x1, y1, x2, y2 = int(box[0]), int(box[1]), int(box[2]), int(box[3]) result[:, y1:y2+1, x1:x2+1] = output GT_boxes = get_information(f"{(splitext(filename[0])[0])[:4]}.png", "./GT_coordinate") flag = True while flag: GT_box = GT_boxes[GT_id] GT_x1, GT_y1, GT_x2, GT_y2 = int(GT_box[0]), int(GT_box[1]), int(GT_box[2]), int(GT_box[3]) result_label = label_img[GT_y1: GT_y2+1, GT_x1: GT_x2+1] Dice = 0 if (abs(y1 - GT_y1) > 35 and len(boxes) != len(GT_boxes)): Dice = dice_coef(None, None, empty=True) else: # intersection_x1 = min(x1, GT_x1) # intersection_y1 = min(y1, GT_y1) # intersection_x2 = max(x2, GT_x2) # intersection_y2 = max(y2, GT_y2) # intersection_h = intersection_y2-intersection_y1+1 # intersection_w = intersection_x2-intersection_x1+1 intersection_result = np.zeros((1200, 500), dtype=int) intersection_result_label = np.zeros((1200, 500), dtype=int) intersection_result[y1:y2+1, x1:x2+1] = result[:, y1:y2+1, x1:x2+1] intersection_result_label[GT_y1:GT_y2+1, GT_x1:GT_x2+1] = result_label Dice = dice_coef(intersection_result/255, intersection_result_label/255) Dice = round(float(Dice), 2) id += 1 flag = False Dice_list[GT_id] = Dice GT_id += 1 # result_label = np.zeros((y2-y1, x2-x1), dtype=int) # result_label = label_img[y1:y2+1, x1:x2+1] # Dice = dice_coef(result[0, y1:y2+1, x1:x2+1]/255, result_label/255) # Dice = round(float(Dice), 2) # Dice_list[id] = Dice bone_num += 1 if _+1 == numOfImg: result = result.astype(np.uint8) for dim in range(result.shape[0]): io.imsave(f"{save_path}//p{(splitext(filename[0])[0])[:4]}.png", result[dim]) return Dice_list, bone_num def Segmentation_one(target): # create splitting dataset numOfImg = create_valid_return_len_one("./coordinate", "./valid_data", "./source/image", target) # target must be xxxx.png # recombine each sepertated img device = torch.device("cuda" if torch.cuda.is_available() else "cpu") dataset = VertebraDataset(".//valid_data//") model = ResidualUNet(n_channels=1, n_classes=1) checkpoint = torch.load("VertebraSegmentation/net/save/best_detect_f03.pt") model.load_state_dict(checkpoint["state_dict"]) loader = DataLoader(dataset, batch_size=1) model = model.to(device) return predict_one(model, loader, numOfImg, target) # return Dice_list and bone_num print("Done.") def Segmentation(): # create splitting dataset numOfEachImg = create_valid_return_len("VertebraSegmentation/coordinate", "VertebraSegmentation/valid_data", "VertebraSegmentation/original_data/f01/image") # recombine each sepertated img device = torch.device("cuda" if torch.cuda.is_available() else "cpu") dataset = VertebraDataset("VertebraSegmentation//valid_data//") model = ResidualUNet(n_channels=1, n_classes=1) checkpoint = torch.load("VertebraSegmentation//net//save//best_test_f01.pt") # checkpoint = torch.load("save//last_detect.pt") model.load_state_dict(checkpoint["state_dict"]) loader = DataLoader(dataset, batch_size=1) model = model.to(device) predict(model, loader, numOfEachImg) print("Done.") def delete_valid_data(path): try: shutil.rmtree(path) except OSError as e: print(e) else: print("The directory is deleted successfully") def Sort_coordinate(path, flag): # path = join("./coordinate", filename) f = open(path, 'r') lines = f.readlines() f.close() list_of_list = [] for i, line in enumerate(lines): lines[i] = line.replace("\n", "") L = list(map(lambda x: int(x), lines[i].split(' '))) list_of_list.append(L) list_of_list.sort(key=lambda x: x[1]) f1 = open(path, 'w') f2 = open(path, 'a') for i, line in enumerate(list_of_list): if flag: if i == 0: f1.write("{:d} {:d} {:d} {:d} {:d} {:d}\n".format(line[0], line[1], line[2], line[3], line[4], line[5]) ) f1.close() else: f2.write("{:d} {:d} {:d} {:d} {:d} {:d}\n".format(line[0], line[1], line[2], line[3], line[4], line[5]) ) else: if i == 0: f1.write("{:d} {:d} {:d} {:d}\n".format(line[0], line[1], line[2], line[3]) ) f1.close() else: f2.write("{:d} {:d} {:d} {:d}\n".format(line[0], line[1], line[2], line[3]) ) f2.close() return len(list_of_list) def main(): delete_valid_data(r"VertebraSegmentation/valid_data") # create coordinate of each boxes detect() Segmentation() if __name__ == "__main__": main()
[ "VertebraSegmentation.net.data.VertebraDataset", "math.floor", "matplotlib.ticker.NullLocator", "torch.cuda.is_available", "VertebraSegmentation.net.model.resunet.ResidualUNet", "datetime.timedelta", "os.listdir", "argparse.ArgumentParser", "numpy.where", "matplotlib.pyplot.close", "os.path.isdi...
[((1451, 1478), 'numpy.append', 'np.append', (['up', 'down'], {'axis': '(0)'}), '(up, down, axis=0)\n', (1460, 1478), True, 'import numpy as np\n'), ((1562, 1595), 'numpy.where', 'np.where', (['(enhance > 1)', '(1)', 'enhance'], {}), '(enhance > 1, 1, enhance)\n', (1570, 1595), True, 'import numpy as np\n'), ((1630, 1681), 'cv2.createCLAHE', 'cv2.createCLAHE', ([], {'clipLimit': '(2.0)', 'tileGridSize': '(8, 8)'}), '(clipLimit=2.0, tileGridSize=(8, 8))\n', (1645, 1681), False, 'import cv2\n'), ((1883, 1901), 'os.path.isdir', 'os.path.isdir', (['dir'], {}), '(dir)\n', (1896, 1901), False, 'import os\n'), ((2175, 2200), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2198, 2200), False, 'import argparse\n'), ((3272, 3310), 'os.makedirs', 'os.makedirs', (['"""./output"""'], {'exist_ok': '(True)'}), "('./output', exist_ok=True)\n", (3283, 3310), False, 'import os\n'), ((3315, 3357), 'os.makedirs', 'os.makedirs', (['"""./coordinate"""'], {'exist_ok': '(True)'}), "('./coordinate', exist_ok=True)\n", (3326, 3357), False, 'import os\n'), ((3751, 3789), 'cv2.imread', 'cv2.imread', (["(opt.image_path + '.png')", '(0)'], {}), "(opt.image_path + '.png', 0)\n", (3761, 3789), False, 'import cv2\n'), ((4251, 4271), 'matplotlib.pyplot.set_cmap', 'plt.set_cmap', (['"""gray"""'], {}), "('gray')\n", (4263, 4271), True, 'import matplotlib.pyplot as plt\n'), ((4363, 4375), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4373, 4375), True, 'import matplotlib.pyplot as plt\n'), ((4390, 4405), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (4402, 4405), True, 'import matplotlib.pyplot as plt\n'), ((5450, 5465), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (5458, 5465), True, 'import matplotlib.pyplot as plt\n'), ((5576, 5674), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""./output/{filename}.png"""'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.0)', 'facecolor': '"""none"""'}), "(f'./output/{filename}.png', bbox_inches='tight', pad_inches=0.0,\n facecolor='none')\n", (5587, 5674), True, 'import matplotlib.pyplot as plt\n'), ((5675, 5686), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (5684, 5686), True, 'import matplotlib.pyplot as plt\n'), ((5746, 5776), 'os.path.join', 'join', (['"""./coordinate"""', 'filename'], {}), "('./coordinate', filename)\n", (5750, 5776), False, 'from os.path import splitext, exists, join\n'), ((5789, 5822), 'os.path.join', 'join', (['"""./GT_coordinate"""', 'filename'], {}), "('./GT_coordinate', filename)\n", (5793, 5822), False, 'from os.path import splitext, exists, join\n'), ((5950, 5975), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (5973, 5975), False, 'import argparse\n'), ((7172, 7223), 'os.makedirs', 'os.makedirs', (['"""PyTorch_YOLOv3/output"""'], {'exist_ok': '(True)'}), "('PyTorch_YOLOv3/output', exist_ok=True)\n", (7183, 7223), False, 'import os\n'), ((7228, 7280), 'os.makedirs', 'os.makedirs', (['"""PyTorch_YOLOv3/pre_img"""'], {'exist_ok': '(True)'}), "('PyTorch_YOLOv3/pre_img', exist_ok=True)\n", (7239, 7280), False, 'import os\n'), ((7285, 7340), 'os.makedirs', 'os.makedirs', (['"""PyTorch_YOLOv3/coordinate"""'], {'exist_ok': '(True)'}), "('PyTorch_YOLOv3/coordinate', exist_ok=True)\n", (7296, 7340), False, 'import os\n'), ((7378, 7406), 'os.listdir', 'os.listdir', (['opt.image_folder'], {}), '(opt.image_folder)\n', (7388, 7406), False, 'import os\n'), ((8288, 8299), 'time.time', 'time.time', ([], {}), '()\n', (8297, 8299), False, 'import time\n'), ((9077, 9097), 'matplotlib.pyplot.set_cmap', 'plt.set_cmap', (['"""gray"""'], {}), "('gray')\n", (9089, 9097), True, 'import matplotlib.pyplot as plt\n'), ((11973, 12010), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (11984, 12010), False, 'import os\n'), ((12015, 12076), 'os.makedirs', 'os.makedirs', (['"""VertebraSegmentation/test/valid"""'], {'exist_ok': '(True)'}), "('VertebraSegmentation/test/valid', exist_ok=True)\n", (12026, 12076), False, 'import os\n'), ((12830, 12864), 'numpy.where', 'np.where', (['(output > threshold)', '(1)', '(0)'], {}), '(output > threshold, 1, 0)\n', (12838, 12864), True, 'import numpy as np\n'), ((13066, 13101), 'numpy.zeros', 'np.zeros', (['(1, 1200, 500)'], {'dtype': 'int'}), '((1, 1200, 500), dtype=int)\n', (13074, 13101), True, 'import numpy as np\n'), ((14728, 14765), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (14739, 14765), False, 'import os\n'), ((14770, 14809), 'os.makedirs', 'os.makedirs', (['source_path'], {'exist_ok': '(True)'}), '(source_path, exist_ok=True)\n', (14781, 14809), False, 'import os\n'), ((15381, 15418), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (15392, 15418), False, 'import os\n'), ((15523, 15558), 'numpy.zeros', 'np.zeros', (['(1, 1200, 500)'], {'dtype': 'int'}), '((1, 1200, 500), dtype=int)\n', (15531, 15558), True, 'import numpy as np\n'), ((15574, 15601), 'os.path.join', 'join', (['"""./source/label"""', 'img'], {}), "('./source/label', img)\n", (15578, 15601), False, 'from os.path import splitext, exists, join\n'), ((15618, 15640), 'cv2.imread', 'cv2.imread', (['GT_path', '(0)'], {}), '(GT_path, 0)\n', (15628, 15640), False, 'import cv2\n'), ((19352, 19386), 'VertebraSegmentation.net.data.VertebraDataset', 'VertebraDataset', (['""".//valid_data//"""'], {}), "('.//valid_data//')\n", (19367, 19386), False, 'from VertebraSegmentation.net.data import VertebraDataset\n'), ((19399, 19438), 'VertebraSegmentation.net.model.resunet.ResidualUNet', 'ResidualUNet', ([], {'n_channels': '(1)', 'n_classes': '(1)'}), '(n_channels=1, n_classes=1)\n', (19411, 19438), False, 'from VertebraSegmentation.net.model.resunet import ResidualUNet\n'), ((19456, 19518), 'torch.load', 'torch.load', (['"""VertebraSegmentation/net/save/best_detect_f03.pt"""'], {}), "('VertebraSegmentation/net/save/best_detect_f03.pt')\n", (19466, 19518), False, 'import torch\n'), ((19584, 19617), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': '(1)'}), '(dataset, batch_size=1)\n', (19594, 19617), False, 'from torch.utils.data import DataLoader\n'), ((20190, 20243), 'VertebraSegmentation.net.data.VertebraDataset', 'VertebraDataset', (['"""VertebraSegmentation//valid_data//"""'], {}), "('VertebraSegmentation//valid_data//')\n", (20205, 20243), False, 'from VertebraSegmentation.net.data import VertebraDataset\n'), ((20256, 20295), 'VertebraSegmentation.net.model.resunet.ResidualUNet', 'ResidualUNet', ([], {'n_channels': '(1)', 'n_classes': '(1)'}), '(n_channels=1, n_classes=1)\n', (20268, 20295), False, 'from VertebraSegmentation.net.model.resunet import ResidualUNet\n'), ((20313, 20376), 'torch.load', 'torch.load', (['"""VertebraSegmentation//net//save//best_test_f01.pt"""'], {}), "('VertebraSegmentation//net//save//best_test_f01.pt')\n", (20323, 20376), False, 'import torch\n'), ((20497, 20530), 'torch.utils.data.DataLoader', 'DataLoader', (['dataset'], {'batch_size': '(1)'}), '(dataset, batch_size=1)\n', (20507, 20530), False, 'from torch.utils.data import DataLoader\n'), ((1920, 1935), 'os.listdir', 'os.listdir', (['dir'], {}), '(dir)\n', (1930, 1935), False, 'import os\n'), ((1997, 2012), 'os.listdir', 'os.listdir', (['dir'], {}), '(dir)\n', (2007, 2012), False, 'import os\n'), ((2022, 2035), 'os.rmdir', 'os.rmdir', (['dir'], {}), '(dir)\n', (2030, 2035), False, 'import os\n'), ((2055, 2066), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2064, 2066), False, 'import os\n'), ((3503, 3535), 'torch.load', 'torch.load', (['opt.checkpoint_model'], {}), '(opt.checkpoint_model)\n', (3513, 3535), False, 'import torch\n'), ((3655, 3680), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3678, 3680), False, 'import torch\n'), ((4106, 4121), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4119, 4121), False, 'import torch\n'), ((5504, 5517), 'matplotlib.ticker.NullLocator', 'NullLocator', ([], {}), '()\n', (5515, 5517), False, 'from matplotlib.ticker import NullLocator\n'), ((5557, 5570), 'matplotlib.ticker.NullLocator', 'NullLocator', ([], {}), '()\n', (5568, 5570), False, 'from matplotlib.ticker import NullLocator\n'), ((7687, 7719), 'torch.load', 'torch.load', (['opt.checkpoint_model'], {}), '(opt.checkpoint_model)\n', (7697, 7719), False, 'import torch\n'), ((8075, 8100), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (8098, 8100), False, 'import torch\n'), ((8753, 8764), 'time.time', 'time.time', ([], {}), '()\n', (8762, 8764), False, 'import time\n'), ((8790, 8842), 'datetime.timedelta', 'datetime.timedelta', ([], {'seconds': '(current_time - prev_time)'}), '(seconds=current_time - prev_time)\n', (8808, 8842), False, 'import datetime\n'), ((9370, 9382), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (9380, 9382), True, 'import matplotlib.pyplot as plt\n'), ((9401, 9416), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)'], {}), '(1)\n', (9413, 9416), True, 'import matplotlib.pyplot as plt\n'), ((11489, 11504), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (11497, 11504), True, 'import matplotlib.pyplot as plt\n'), ((11711, 11822), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""PyTorch_YOLOv3/output/{filename}.png"""'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.0)', 'facecolor': '"""none"""'}), "(f'PyTorch_YOLOv3/output/{filename}.png', bbox_inches='tight',\n pad_inches=0.0, facecolor='none')\n", (11722, 11822), True, 'import matplotlib.pyplot as plt\n'), ((11827, 11838), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (11836, 11838), True, 'import matplotlib.pyplot as plt\n'), ((13130, 13145), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (13143, 13145), False, 'import torch\n'), ((14479, 14501), 'numpy.sum', 'np.sum', (['(target * truth)'], {}), '(target * truth)\n', (14485, 14501), True, 'import numpy as np\n'), ((14836, 14861), 'os.path.join', 'join', (['source_path', 'target'], {}), '(source_path, target)\n', (14840, 14861), False, 'from os.path import splitext, exists, join\n'), ((15114, 15139), 'numpy.zeros', 'np.zeros', (['(height, width)'], {}), '((height, width))\n', (15122, 15139), True, 'import numpy as np\n'), ((15753, 15768), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (15766, 15768), False, 'import torch\n'), ((20678, 20697), 'shutil.rmtree', 'shutil.rmtree', (['path'], {}), '(path)\n', (20691, 20697), False, 'import shutil\n'), ((3230, 3255), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (3253, 3255), False, 'import torch\n'), ((5322, 5417), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(x1, y1)', 'box_w', 'box_h'], {'linewidth': '(0.5)', 'edgecolor': '"""red"""', 'facecolor': '"""none"""'}), "((x1, y1), box_w, box_h, linewidth=0.5, edgecolor='red',\n facecolor='none')\n", (5339, 5417), True, 'import matplotlib.patches as patches\n'), ((7130, 7155), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (7153, 7155), False, 'import torch\n'), ((7437, 7451), 'os.path.splitext', 'splitext', (['file'], {}), '(file)\n', (7445, 7451), False, 'from os.path import splitext, exists, join\n'), ((8558, 8573), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8571, 8573), False, 'import torch\n'), ((11547, 11560), 'matplotlib.ticker.NullLocator', 'NullLocator', ([], {}), '()\n', (11558, 11560), False, 'from matplotlib.ticker import NullLocator\n'), ((11604, 11617), 'matplotlib.ticker.NullLocator', 'NullLocator', ([], {}), '()\n', (11615, 11617), False, 'from matplotlib.ticker import NullLocator\n'), ((12199, 12222), 'os.path.join', 'join', (['source_path', 'file'], {}), '(source_path, file)\n', (12203, 12222), False, 'from os.path import splitext, exists, join\n'), ((12545, 12570), 'numpy.zeros', 'np.zeros', (['(height, width)'], {}), '((height, width))\n', (12553, 12570), True, 'import numpy as np\n'), ((13010, 13035), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (13033, 13035), False, 'import torch\n'), ((14425, 14439), 'numpy.sum', 'np.sum', (['target'], {}), '(target)\n', (14431, 14439), True, 'import numpy as np\n'), ((14442, 14455), 'numpy.sum', 'np.sum', (['truth'], {}), '(truth)\n', (14448, 14455), True, 'import numpy as np\n'), ((15472, 15497), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (15495, 15497), False, 'import torch\n'), ((16310, 16380), 'skimage.morphology.remove_small_objects', 'morphology.remove_small_objects', (['output'], {'min_size': '(2000)', 'connectivity': '(2)'}), '(output, min_size=2000, connectivity=2)\n', (16341, 16380), False, 'from skimage import morphology\n'), ((16442, 16471), 'numpy.where', 'np.where', (['(output == 1)', '(255)', '(0)'], {}), '(output == 1, 255, 0)\n', (16450, 16471), True, 'import numpy as np\n'), ((19300, 19325), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (19323, 19325), False, 'import torch\n'), ((20138, 20163), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (20161, 20163), False, 'import torch\n'), ((1964, 1984), 'os.path.join', 'os.path.join', (['dir', 'd'], {}), '(dir, d)\n', (1976, 1984), False, 'import os\n'), ((4315, 4344), 'PIL.Image.open', 'Image.open', (["(img_path + '.png')"], {}), "(img_path + '.png')\n", (4325, 4344), False, 'from PIL import Image\n'), ((4804, 4818), 'math.floor', 'math.floor', (['x1'], {}), '(x1)\n', (4814, 4818), False, 'import math\n'), ((4820, 4834), 'math.floor', 'math.floor', (['y1'], {}), '(y1)\n', (4830, 4834), False, 'import math\n'), ((4836, 4849), 'math.ceil', 'math.ceil', (['x2'], {}), '(x2)\n', (4845, 4849), False, 'import math\n'), ((4851, 4864), 'math.ceil', 'math.ceil', (['y2'], {}), '(y2)\n', (4860, 4864), False, 'import math\n'), ((5470, 5479), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5477, 5479), True, 'import matplotlib.pyplot as plt\n'), ((5523, 5532), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (5530, 5532), True, 'import matplotlib.pyplot as plt\n'), ((11264, 11359), 'matplotlib.patches.Rectangle', 'patches.Rectangle', (['(x1, y1)', 'box_w', 'box_h'], {'linewidth': '(0.5)', 'edgecolor': '"""red"""', 'facecolor': '"""none"""'}), "((x1, y1), box_w, box_h, linewidth=0.5, edgecolor='red',\n facecolor='none')\n", (11281, 11359), True, 'import matplotlib.patches as patches\n'), ((13527, 13548), 'torch.sigmoid', 'torch.sigmoid', (['output'], {}), '(output)\n', (13540, 13548), False, 'import torch\n'), ((14207, 14242), 'numpy.zeros', 'np.zeros', (['(1, 1200, 500)'], {'dtype': 'int'}), '((1, 1200, 500), dtype=int)\n', (14215, 14242), True, 'import numpy as np\n'), ((16030, 16051), 'torch.sigmoid', 'torch.sigmoid', (['output'], {}), '(output)\n', (16043, 16051), False, 'import torch\n'), ((9331, 9347), 'PIL.Image.open', 'Image.open', (['path'], {}), '(path)\n', (9341, 9347), False, 'from PIL import Image\n'), ((10123, 10137), 'math.floor', 'math.floor', (['x1'], {}), '(x1)\n', (10133, 10137), False, 'import math\n'), ((10139, 10153), 'math.floor', 'math.floor', (['y1'], {}), '(y1)\n', (10149, 10153), False, 'import math\n'), ((10155, 10168), 'math.ceil', 'math.ceil', (['x2'], {}), '(x2)\n', (10164, 10168), False, 'import math\n'), ((10170, 10183), 'math.ceil', 'math.ceil', (['y2'], {}), '(y2)\n', (10179, 10183), False, 'import math\n'), ((11513, 11522), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (11520, 11522), True, 'import matplotlib.pyplot as plt\n'), ((11570, 11579), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (11577, 11579), True, 'import matplotlib.pyplot as plt\n'), ((17664, 17696), 'numpy.zeros', 'np.zeros', (['(1200, 500)'], {'dtype': 'int'}), '((1200, 500), dtype=int)\n', (17672, 17696), True, 'import numpy as np\n'), ((17745, 17777), 'numpy.zeros', 'np.zeros', (['(1200, 500)'], {'dtype': 'int'}), '((1200, 500), dtype=int)\n', (17753, 17777), True, 'import numpy as np\n'), ((13359, 13380), 'os.path.splitext', 'splitext', (['filename[0]'], {}), '(filename[0])\n', (13367, 13380), False, 'from os.path import splitext, exists, join\n'), ((15886, 15907), 'os.path.splitext', 'splitext', (['filename[0]'], {}), '(filename[0])\n', (15894, 15907), False, 'from os.path import splitext, exists, join\n'), ((13279, 13300), 'os.path.splitext', 'splitext', (['filename[0]'], {}), '(filename[0])\n', (13287, 13300), False, 'from os.path import splitext, exists, join\n'), ((15226, 15242), 'os.path.splitext', 'splitext', (['target'], {}), '(target)\n', (15234, 15242), False, 'from os.path import splitext, exists, join\n'), ((12704, 12718), 'os.path.splitext', 'splitext', (['file'], {}), '(file)\n', (12712, 12718), False, 'from os.path import splitext, exists, join\n'), ((13681, 13702), 'os.path.splitext', 'splitext', (['filename[0]'], {}), '(filename[0])\n', (13689, 13702), False, 'from os.path import splitext, exists, join\n'), ((16183, 16204), 'os.path.splitext', 'splitext', (['filename[0]'], {}), '(filename[0])\n', (16191, 16204), False, 'from os.path import splitext, exists, join\n'), ((16717, 16738), 'os.path.splitext', 'splitext', (['filename[0]'], {}), '(filename[0])\n', (16725, 16738), False, 'from os.path import splitext, exists, join\n'), ((14128, 14149), 'os.path.splitext', 'splitext', (['filename[0]'], {}), '(filename[0])\n', (14136, 14149), False, 'from os.path import splitext, exists, join\n'), ((18812, 18833), 'os.path.splitext', 'splitext', (['filename[0]'], {}), '(filename[0])\n', (18820, 18833), False, 'from os.path import splitext, exists, join\n')]
import os import sys import matplotlib.pyplot as plt import numpy as np import scipy.optimize as optimize import pandas as pd from datetime import datetime from scipy.stats import pearsonr from lmfit import Minimizer, Parameters from sklearn.neural_network import MLPRegressor from sklearn import preprocessing import random from data_management import * from gs_models import * from et_models import * from information_metrics import * def min_model(params, x, obs_var, fit_var_name): [vpd_l, co2, gpp, k1, k2, gamma_star, s, psi_pd, psi_l, ga, rad, t_air, vpd_air, p_air, rho_air_dry] = x if fit_var_name == 'LE_F_MDS': g_surf_mod, g_soil_mod, g_canopy_mod, mwue = cal_g_surf(params, x) mod_var = cal_LE(g_surf_mod, ga, rad, vpd_air, p_air, t_air, rho_air_dry) elif fit_var_name == 'ET_obs': g_surf_mod, g_soil_mod, g_canopy_mod, mwue = cal_g_surf(params, x) mod_var = cal_E(g_surf_mod, ga, vpd_l) elif fit_var_name == 'G_surf_mol': g_surf_mod, g_soil_mod, g_canopy_mod, mwue = cal_g_surf(params, x) mod_var = g_surf_mod return (obs_var - mod_var) ** 2 def cal_g_surf(params, x, leaf=None): if leaf is None: [vpd_l, co2, gpp, k1, k2, gamma_star, s, psi_pd, psi_l, ga, rad, t_air, vpd_air, p_air, rho_air_dry] = x else: [vpd_l, co2, gpp, k1, k2, gamma_star, s, psi_pd, psi_l, ga, rad, t_air, vpd_air, p_air, rho_air_dry, lai] = x tag = [k for k in params.keys() if k.startswith('tag')][0] tag = tag.strip('tag') if (tag == '0_d') or tag.startswith('WUE_d') or tag.startswith('E_d'): mwue = WUE_mwue(psi_pd, params['lww'].value, params['b'].value) elif tag.startswith('WUE_i'): mwue = WUE_mwue(psi_l, params['lww'].value, params['b'].value) elif tag.startswith('CM_d'): mwue = CM_mwue(psi_pd, psi_pd, params['b2'].value, params['b1'].value, params['psi_50'].value, params['a'].value) elif tag.startswith('CM_i'): mwue = CM_mwue(psi_pd, psi_l, params['b2'].value, params['b1'].value, params['psi_50'].value, params['a'].value) elif tag.startswith('SOX_d') and (leaf is None): mwue = SOX_mwue(psi_pd, psi_pd, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value) elif tag.startswith('SOX_i') and (leaf is None): mwue = SOX_mwue(psi_pd, psi_l, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value) elif tag.startswith('SOXa_d') and (leaf is None): mwue = aSOX_mwue(psi_pd, psi_pd, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value) elif tag.startswith('SOXa_i') and (leaf is None): mwue = aSOX_mwue(psi_pd, psi_l, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value) elif tag.startswith('SOXait_d'): mwue = aSOX_mwue_it(psi_pd, psi_pd, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value, vpd_l, co2, k1, k2, gamma_star) elif tag.startswith('SOXait_i'): mwue = aSOX_mwue_it(psi_pd, psi_l, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value, vpd_l, co2, k1, k2, gamma_star) elif tag.startswith('SOXit_d'): mwue = SOX_mwue_it(psi_pd, psi_pd, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value, vpd_l, co2, k1, k2, gamma_star) elif tag.startswith('SOXit_i'): mwue = SOX_mwue_it(psi_pd, psi_l, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value, vpd_l, co2, k1, k2, gamma_star) elif tag.startswith('SOX_d') and (leaf==1): mwue = SOX_mwue_it(psi_pd, psi_pd, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value, vpd_l, co2, k1, k2, gamma_star) elif tag.startswith('SOX_i') and (leaf==1): mwue = SOX_mwue_it(psi_pd, psi_l, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value, vpd_l, co2, k1, k2, gamma_star) elif tag.startswith('SOXa_d') and (leaf==1): mwue = aSOX_mwue_it(psi_pd, psi_pd, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value, vpd_l, co2, k1, k2, gamma_star) elif tag.startswith('SOXa_i') and (leaf==1): mwue = aSOX_mwue_it(psi_pd, psi_l, gpp, params['kmax'].value, params['psi_50'].value, params['a'].value, vpd_l, co2, k1, k2, gamma_star) if leaf is None: g_canopy_mod = gs_opt_canopy(gpp, co2, vpd_l, k2, gamma_star, mwue) else: gs_mod = gs_opt_leaf(mwue, vpd_l, co2, k1, k2, gamma_star) g_canopy_mod = gs_mod * lai if tag == 'E_d': beta = model_beta(s, params['s_star'].value, params['s_w'].value) g_canopy_mod = beta * g_canopy_mod g_soil_mod = model_g_soil_lin(s, params['gsoil_max'].value) g_surf_mod = g_soil_mod + g_canopy_mod return g_surf_mod, g_soil_mod, g_canopy_mod, mwue def setup_params(data_i, tag): g_soil_lim = [10**-3, 0.1] # mol m-2 s-2 MPa-1 lww_lims = [0.001*10**-3, 5*10**-3] # mol mol-1 b1_lims = [0.001*10**-3, 5*10**-3] # mol mol-1 k_lim = [0.001*10**-3, 5*10**-3] # mol m-2 s-2 MPa-1 b2_lims = [0.01*10**-3, 5*10**-3] # mol mol-1 MPa-1 b_lims = [0.01, 5] # MPa-1 a_lim = [0.01, 10] # unitless p50_lim = [-10, -0.01] # MPa params = Parameters() params.add('tag%s' % tag, value=0, vary=False) if (tag == '0_d') or tag.endswith('p'): params.add('gsoil_max', value=0.01, min=g_soil_lim[0], max=g_soil_lim[1], vary=True) else: params.add('gsoil_max', value=data_i['gsoil_max_0_d'].values[0], vary=False) if tag == 'E_d': params.add('s_star', value=0.8, min=0.01, max=1, vary=True) params.add('dws', value=0.2, min=0.01, max=1, vary=True) params.add('s_w', expr='s_star - dws', min=0.01, max=1) else: params.add('s_star', value=np.nan, vary=False) params.add('dws', value=np.nan, vary=False) params.add('s_w', value=np.nan, vary=False) if (tag == '0_d') or (tag == 'E_d') or tag.startswith('WUE'): params.add('b2', value=np.nan, vary=False) params.add('b1', value=np.nan, vary=False) params.add('a', value=np.nan, vary=False) params.add('psi_50', value=np.nan, vary=False) params.add('kmax', value=np.nan, vary=False) elif tag.startswith('CM'): params.add('kmax', value=np.nan, vary=False) params.add('lww', value=np.nan, vary=False) params.add('b', value=np.nan, vary=False) elif tag.startswith('SOX'): params.add('b2', value=np.nan, vary=False) params.add('b1', value=np.nan, vary=False) params.add('lww', value=np.nan, vary=False) params.add('b', value=np.nan, vary=False) if (tag == '0_d') or (tag == 'E_d'): params.add('lww', value=random.uniform(lww_lims[0], lww_lims[1]), min=lww_lims[0], max=lww_lims[1]*10, vary=True) params.add('b', value=0, vary=False) elif tag.startswith('WUE'): params.add('lww', value=random.uniform(lww_lims[0], lww_lims[1]), min=lww_lims[0], max=lww_lims[1], vary=True) params.add('b', value=random.uniform(b_lims[0], b_lims[1]), min=b_lims[0], max=b_lims[1], vary=True) elif tag.startswith('CM'): params.add('b2', value=random.uniform(b2_lims[0], b2_lims[1]), min=b2_lims[0], max=b2_lims[1], vary=True) params.add('b1', value=random.uniform(b1_lims[0], b1_lims[1]), min=b1_lims[0], max=b1_lims[1], vary=True) if tag.endswith('2') or tag.endswith('2_p'): params.add('a', value=data_i['a_ref'].values[0], vary=False) params.add('psi_50', value=data_i['psi_50_ref'].values[0], vary=False) elif tag.endswith('3a') or tag.endswith('3a_p'): params.add('a', value=random.uniform(a_lim[0], a_lim[1]), min=a_lim[0], max=a_lim[1], vary=True) params.add('psi_50', value=data_i['psi_50_ref'].values[0], vary=False) elif tag.endswith('3b') or tag.endswith('3b_p'): params.add('a', value=data_i['a_ref'].values[0], vary=False) params.add('psi_50', value=random.uniform(p50_lim[0], p50_lim[1]), min=p50_lim[0], max=p50_lim[1], vary=True) elif tag.endswith('4') or tag.endswith('4_p'): params.add('a', value=random.uniform(a_lim[0], a_lim[1]), min=a_lim[0], max=a_lim[1], vary=True) params.add('psi_50', value=random.uniform(p50_lim[0], p50_lim[1]), min=p50_lim[0], max=p50_lim[1], vary=True) elif tag.startswith('SOX'): params.add('kmax', value=random.uniform(k_lim[0], k_lim[1]), min=k_lim[0], max=k_lim[1], vary=True) if tag.endswith('1') or tag.endswith('1_p'): params.add('a', value=data_i['a_ref'].values[0], vary=False) params.add('psi_50', value=data_i['psi_50_ref'].values[0], vary=False) elif tag.endswith('2a') or tag.endswith('2a_p'): params.add('a', value=random.uniform(a_lim[0], a_lim[1]), min=a_lim[0], max=a_lim[1], vary=True) params.add('psi_50', value=data_i['psi_50_ref'].values[0], vary=False) elif tag.endswith('2b') or tag.endswith('2b_p'): params.add('a', value=data_i['a_ref'].values[0], vary=False) params.add('psi_50', value=random.uniform(p50_lim[0], p50_lim[1]), min=p50_lim[0], max=p50_lim[1], vary=True) elif tag.endswith('3') or tag.endswith('3_p'): params.add('a', value=random.uniform(a_lim[0], a_lim[1]), min=a_lim[0], max=a_lim[1], vary=True) params.add('psi_50', value=random.uniform(p50_lim[0], p50_lim[1]), min=p50_lim[0], max=p50_lim[1], vary=True) return params def fit_gsurf_params(data_i, tag, min_fit_var='LE_F_MDS'): params = setup_params(data_i, tag) xx = [data_i['VPD_l'].values, data_i['CO2'].values, data_i['GPP'].values, data_i['k1'].values, data_i['k2'].values, data_i['gamma_star'].values, data_i['S'].values, data_i['canopy_water_pot_pd'].values, data_i['leaf_water_pot'].values, data_i['Ga_mol'].values, data_i['Rn-G'].values, data_i['TA_F_MDS'].values, data_i['VPD_a'].values, data_i['P_air'].values, data_i['rho_air_d']] minner = Minimizer(min_model, params, fcn_args=(xx, data_i[min_fit_var].values, min_fit_var)) fit = minner.minimize() g_surf_mod, g_soil_mod, g_canopy_mod, mwue =cal_g_surf(fit.params, xx) return g_surf_mod, g_soil_mod, g_canopy_mod, mwue, fit.params def fit_gsurf_params_bs(data_i, tag, fitting_results, min_fit_var='LE_F_MDS', bs=200, nbins=15, norm=1): n = np.int(np.float(len(data_i.index)) / 4.) fitting_results[tag] = {} all_params = [] all_fit_diagnostics_val = [] all_fit_diagnostics_cal = [] m_params = Parameters() pnames = ['gsoil_max', 'lww', 'b', 'b2', 'b1', 'a', 'psi_50', 'kmax', 's_star', 's_w'] for i in range(bs): sel_random = random.sample(list(data_i.index), n) data_cal = data_i.loc[sel_random] data_val = data_i.loc[~data_i.index.isin(sel_random)] sel_random_val = random.sample(list(data_val.index), n) data_val = data_val.loc[sel_random_val] g_surf_mod_cal, g_soil_cal, g_canopy_cal, mwue_cal, params = fit_gsurf_params(data_cal, tag, min_fit_var=min_fit_var) all_params.append([params[k].value for k in pnames]) LE_cal, nse_LE_cal, mape_LE_cal = cal_models_LE(data_cal, g_surf_mod_cal) data_cal['LE_cal'] = LE_cal a_p_cal, a_fu1_cal, a_fu2_cal,\ a_fs_cal, a_fr_cal, a_ft_cal, a_f_cal = cal_it_performance(data_cal, 'LE_cal', 'LE_F_MDS', 'S', 'VPD_a', nbins=nbins, norm=norm) all_fit_diagnostics_cal.append([nse_LE_cal, mape_LE_cal, a_p_cal, a_fu1_cal, a_fu2_cal, a_fs_cal, a_fr_cal, a_ft_cal]) xx_val = [data_val['VPD_l'].values, data_val['CO2'].values, data_val['GPP'].values, data_val['k1'].values, data_val['k2'].values, data_val['gamma_star'].values, data_val['S'].values, data_val['canopy_water_pot_pd'].values, data_val['leaf_water_pot'].values, data_val['Ga_mol'].values, data_val['Rn-G'].values, data_val['TA_F_MDS'].values, data_val['VPD_a'].values, data_val['P_air'].values, data_val['rho_air_d']] g_surf_mod_val, g_soil_mod_val, g_canopy_mod_val, mwue_val =cal_g_surf(params, xx_val) LE_val, nse_LE_val, mape_LE_val = cal_models_LE(data_val, g_surf_mod_val) data_val['LE_val'] = LE_val a_p_val, a_fu1_val, a_fu2_val,\ a_fs_val, a_fr_val, a_ft_val, a_f_val = cal_it_performance(data_val, 'LE_val', 'LE_F_MDS', 'S', 'VPD_a', nbins=nbins, norm=norm) all_fit_diagnostics_val.append([nse_LE_val, mape_LE_val, a_p_val, a_fu1_val, a_fu2_val, a_fs_val, a_fr_val, a_ft_val]) all_fit_diagnostics_val = list(zip(*all_fit_diagnostics_val)) fitting_results[tag]['nse_LE_val'] = all_fit_diagnostics_val[0] fitting_results[tag]['mape_LE_val'] = all_fit_diagnostics_val[1] fitting_results[tag]['a_p_val'] = all_fit_diagnostics_val[2] fitting_results[tag]['a_fu1_val'] = all_fit_diagnostics_val[3] fitting_results[tag]['a_fu2_val'] = all_fit_diagnostics_val[4] fitting_results[tag]['a_fs_val'] = all_fit_diagnostics_val[5] fitting_results[tag]['a_fr_val'] = all_fit_diagnostics_val[6] fitting_results[tag]['a_ft_val'] = all_fit_diagnostics_val[7] all_fit_diagnostics_cal = list(zip(*all_fit_diagnostics_cal)) fitting_results[tag]['nse_LE_cal'] = all_fit_diagnostics_cal[0] fitting_results[tag]['mape_LE_cal'] = all_fit_diagnostics_cal[1] fitting_results[tag]['a_p_cal'] = all_fit_diagnostics_cal[2] fitting_results[tag]['a_fu1_cal'] = all_fit_diagnostics_cal[3] fitting_results[tag]['a_fu2_cal'] = all_fit_diagnostics_cal[4] fitting_results[tag]['a_fs_cal'] = all_fit_diagnostics_cal[5] fitting_results[tag]['a_fr_cal'] = all_fit_diagnostics_cal[6] fitting_results[tag]['a_ft_cal'] = all_fit_diagnostics_cal[7] all_params = list(zip(*all_params)) m_params.add('tag%s' % tag, value=0, vary=False) for k, param in zip(pnames, all_params): m_params.add(k, value = np.nanmedian(param), vary=False) fitting_results[tag][k] = param xx = [data_i['VPD_l'].values, data_i['CO2'].values, data_i['GPP'].values, data_i['k1'].values, data_i['k2'].values, data_i['gamma_star'].values, data_i['S'].values, data_i['canopy_water_pot_pd'].values, data_i['leaf_water_pot'].values, data_i['Ga_mol'].values, data_i['Rn-G'].values, data_i['TA_F_MDS'].values, data_i['VPD_a'].values, data_i['P_air'].values, data_i['rho_air_d']] g_surf_mod, g_soil_mod, g_canopy_mod, mwue = cal_g_surf(m_params, xx) return g_surf_mod, g_soil_mod, g_canopy_mod, mwue, m_params, fitting_results def cal_models_LE(data_i, g_surf_mol_mod): G_surf_mod = g_from_mol(g_surf_mol_mod, data_i['P_air'], data_i['TA_F_MDS']) LE = cal_LE(g_surf_mol_mod, data_i['Ga_mol'], data_i['Rn-G'], \ data_i['VPD_a'], data_i['P_air'], data_i['TA_F_MDS'], data_i['rho_air_d']) try: nse_LE = cal_nse(data_i['LE_F_MDS'], LE) mape_LE = cal_mape(data_i['LE_F_MDS'], LE) except: xx, yy = list(zip(*[[xi, yi] for xi, yi in zip(data_i['LE_F_MDS'], LE) if (np.isnan(yi)==0)])) nse_LE = cal_nse(xx, yy) mape_LE = cal_mape(xx, yy) return LE, nse_LE, mape_LE def process_model_alternative(data_i, tag): g_surf_mod, g_soil_mod, g_canopy_mod, mwue, params = fit_gsurf_params(data_i, tag) for p in ['gsoil_max','lww', 'b', 'b1', 'b2', 'a', 'psi_50', 'kmax', 's_star', 's_w']: data_i['%s_%s' % (p, tag)] = params[p].value data_i['g_soil_%s' % tag] = g_soil_mod data_i['g_canopy_%s' % tag] = g_canopy_mod data_i['g_surf_mod_%s' % tag] = g_surf_mod data_i['E/ET %s' % tag] = g_soil_mod / g_surf_mod data_i['mwue_%s' % tag] = mwue gs_leaf = gs_opt_leaf(mwue, data_i['VPD_l'], data_i['CO2'], data_i['k1_0'], data_i['k2_0'], data_i['gamma_star_0']) data_i['g_canopy_leaf_%s' % tag] = gs_leaf * data_i['LAI'] data_i['g_leaf_%s' % tag] = gs_leaf data_i['eLAI_%s' % tag] = data_i['g_canopy_%s' % tag] / data_i['g_leaf_%s' % tag] LE, nse_LE, mape_LE = cal_models_LE(data_i, g_surf_mod) data_i['LE_%s' % tag] = LE data_i['nse_LE_%s' % tag] = nse_LE data_i['mape_LE_%s' % tag] = mape_LE print('%s\t\t%-3.2f\t%3.2f\t\t%3.2f\t%-3.2f\t%-3.2f\t%-3.2f\t%-3.2f\t%-3.2f\t%-3.2f\t%-3.2f\t%-3.2f'% (tag, np.nanmedian(data_i['eLAI_%s' % tag]), np.nanmedian(data_i['mwue_%s' % tag]*10**3), data_i['lww_%s' % tag].values[0]*10**3, data_i['b_%s' % tag].values[0], data_i['b2_%s' % tag].values[0]*10**3, data_i['b1_%s' % tag].values[0]*10**3, data_i['kmax_%s' % tag].values[0]*10**3, data_i['a_%s' % tag].values[0], data_i['psi_50_%s' % tag].values[0], nse_LE, mape_LE)) return data_i def process_model_alternative_bs(data_i, tag, fitting_results, nbins=15, norm=1): d0 = datetime.now() print(tag, datetime.now()) g_surf_mod, g_soil_mod, g_canopy_mod, mwue,\ params, fitting_results = fit_gsurf_params_bs(data_i, tag, fitting_results) for p in ['gsoil_max','lww', 'b', 'b1', 'b2', 'a', 'psi_50', 'kmax', 's_star', 's_w']: fitting_results[tag]['%s_med' % p] = params[p].value data_i['g_soil_%s' % tag] = g_soil_mod data_i['g_canopy_%s' % tag] = g_canopy_mod data_i['g_surf_mod_%s' % tag] = g_surf_mod data_i['E/ET %s' % tag] = g_soil_mod / g_surf_mod data_i['mwue_%s' % tag] = mwue gs_leaf = gs_opt_leaf(mwue, data_i['VPD_l'], data_i['CO2'], data_i['k1_0'], data_i['k2_0'], data_i['gamma_star_0']) data_i['g_canopy_leaf_%s' % tag] = gs_leaf * data_i['LAI'] data_i['g_leaf_%s' % tag] = gs_leaf data_i['eLAI_%s' % tag] = data_i['g_canopy_%s' % tag] / data_i['g_leaf_%s' % tag] LE, nse_LE, mape_LE = cal_models_LE(data_i, g_surf_mod) data_i['LE_%s' % tag] = LE fitting_results[tag]['nse_LE_med'] = nse_LE fitting_results[tag]['mape_LE_med'] = mape_LE a_p_med, a_fu1_med,\ a_fu2_med, a_fs_med,\ a_fr_med, a_ft_med, a_f_med = cal_it_performance(data_i, 'LE_%s' % tag, 'LE_F_MDS', 'S', 'VPD_a', nbins=nbins, norm=norm) fitting_results[tag]['a_p_med'] = a_p_med fitting_results[tag]['a_fu1_med'] = a_fu1_med fitting_results[tag]['a_fu2_med'] = a_fu2_med fitting_results[tag]['a_fs_med'] = a_fs_med fitting_results[tag]['a_fr_med'] = a_fr_med fitting_results[tag]['a_ft_med'] = a_ft_med print(tag, datetime.now() - d0) return data_i, fitting_results def fit_nn(data_i, y_var='LE_F_MDS', x_vars = ['VPD_a', 'SWC_F_MDS', 'CO2', 'GPP', 'PARin', 'TA_F_MDS', 'Ga', 'Rn-G']): x_scaled = preprocessing.scale(data_i[x_vars].values) nn = MLPRegressor(solver='lbfgs') nn.fit(x_scaled, data_i[y_var].values) y_ann = nn.predict(x_scaled) r_nn = pearsonr(y_ann, data_i[y_var].values)[0] nse_nn = cal_nse(y_ann, data_i[y_var].values) mape_nn = cal_mape(y_ann, data_i[y_var].values) return y_ann, r_nn, nse_nn, mape_nn def fit_plots_checks(): out_figures_directory = '../../PROJECTS/Stomatal_conductance_eval/result_figures/lmfit_test_plots' sites_params = pd.read_csv( '../../DATA/EEGS/sel2_sites_params.csv') pft_params = pd.read_csv( '../../DATA/EEGS/selected_pft_params.csv') fig_suffix = '_test' data_directory = '../../DATA/EEGS/HH_data_revision_w5' sites_files = [os.path.join(data_directory, f) for f in os.listdir(data_directory)] sites_sel = sites_params['site_id'].values for f_site in sites_files: site_name = f_site.split('/')[-1][:-4] site = site_name[:-3] swc_i = np.int(site_name[-1]) sites_params_i = sites_params[(sites_params['site_id'] == site) & (sites_params['z_sel'] == swc_i)] pft = sites_params_i['pft'].values[0] pft_params_i = pft_params[pft_params['PFT'] == pft] zm = sites_params_i['zs'].values[0] fig_name = os.path.join(out_figures_directory, '%s_fit%s.png' % (site_name, fig_suffix)) data = pd.read_csv(f_site, header = 0, index_col = 0, parse_dates = True, infer_datetime_format = True,) print(site_name, pft, zm, np.max(data.index.year) - np.min(data.index.year) + 1) data['k2'] = data['k2_Tl'] # change for Tl or 0 data['k1'] = data['k1_Tl'] # change for Tl or 0 data['gamma_star'] = data['gamma_star_Tl'] # change for Tl or 0 data['leaf_water_pot'] = data['leaf_water_pot_invET'] # placeholder until invT LE_ann, r_nn, nse_LE_nn, mape_LE_nn = fit_nn(data, y_var='LE_F_MDS') data['LE_NN'] = LE_ann data['nse_LE_NN'] = nse_LE_nn data['mape_LE_NN'] = mape_LE_nn model_alternatives_d_p = ['WUE_d_p', 'CM_d4_p', 'SOX_d3_p'] model_alternatives_d = [ 'WUE_d', 'WUE_i', 'CM_d4', 'CM_i4', 'SOX_d3', 'SOX_i3', ] model_alternatives_plot = [ 'WUE_d', 'WUE_i', 'CM_d4', 'CM_i4', 'SOX_d3', 'SOX_i3', ] print('tag\t\tlc\tmwue\t\tlww\tb\tb2\tb1\tKmax\ta\tp50\tNSE_LE\tMAPE_LE') for tag in model_alternatives_d_p: data = process_model_alternative(data, tag) avg_gsoil_max = np.sum([data['gsoil_max_WUE_d_p'][0], data['gsoil_max_CM_d4_p'][0], data['gsoil_max_SOX_d3_p'][0]]) / 3. data['gsoil_max_0_d'] = avg_gsoil_max data['g_soil_0_d'] = data['S'] * avg_gsoil_max data['T'] = data['ET_obs'] * (1 - data['g_soil_0_d'] / data['G_surf_mol']) data['leaf_water_pot'] = cal_psi_leaf(data['canopy_water_pot_pd'], pft_params_i['psi_50'].values[0], pft_params_i['kmax'].values[0] * np.max(data['LAI']), pft_params_i['a'].values[0], data['T']) print(np.nanmin(data['leaf_water_pot']), np.nanmax(data['leaf_water_pot'])) for tag in model_alternatives_d: data = process_model_alternative(data, tag) fig = plt.figure(figsize=(15, 10)) data['G_surf_n'] = data['G_surf_mol'] / np.nanmax(data['G_surf_mol']) data['VPD_n'] = data['VPD_l'] / np.nanmax(data['VPD_l']) n_vars = ['VPD_n', 'G_surf_n', 'S', 'LAI', 'G_surf_mol', 'g_soil_0_d', 'soil_water_pot', 'leaf_water_pot_invET', 'leaf_water_pot_invET1', 'leaf_water_pot'] for tag in model_alternatives_plot: n_vars.append('eLAI_%s' % tag) data_d = data[n_vars].resample('D').mean().dropna() ax = fig.add_subplot(4, 2, 1) data_d[['VPD_n', 'G_surf_n', 'S']].plot(ax=ax, lw=0, marker='.', legend=False) ax.set_ylim([0, 1]) title = '%s; %s; [%sd; %shh]; %sz; %5.1fLAI ; %5.2fpsmin' % (site, pft, len(data_d.index), len(data.index), zm, np.nanmax(data['LAI']), np.nanmin(data['soil_water_pot'])) plt.legend() plt.title(title) ax = fig.add_subplot(4, 2, 3) data_d['soil_water_pot_'] = -data_d['soil_water_pot'] data_d['leaf_water_pot_0'] = -data_d['leaf_water_pot_invET'] data_d['leaf_water_pot_'] = -data_d['leaf_water_pot'] data_d[['soil_water_pot_', 'leaf_water_pot_0', 'leaf_water_pot_']].plot(ax=ax, lw=0, marker='.', legend=False) ax.axhline(1, color='k', linestyle=':') ax.set_yscale('log') plt.legend() ax = fig.add_subplot(4, 2, 5) elai_l = [] for tag in model_alternatives_plot: elai_l.append('eLAI_%s' % tag) elai_l.append('LAI') data_d[elai_l].plot(ax=ax, lw=0, marker='.', legend=False) ax.set_ylim([0, np.nanmax(data_d['LAI'])*1.1]) ax = fig.add_subplot(4, 2, 7) E_r_T = 'T/ET%-5.1f' % (np.round(np.nanmedian(data['g_soil_0_d'] / data['G_surf_mol']) * 100., 1)) data_d[['G_surf_mol', 'g_soil_0_d']].plot(ax=ax, lw=0, marker='.', legend=False) plt.legend() ax.set_ylabel(E_r_T) print(title, E_r_T) ax = fig.add_subplot(1, 2, 2) max_v = np.nanmax([data['LE_F_MDS'] * 1.2]) for tag in model_alternatives_plot: ax.scatter(data['LE_%s' % tag], data['LE_F_MDS'], alpha=0.1, label= '%s: %-5.2f' % (tag, data['nse_LE_%s' % tag].values[0])) plt.title('%s / gsoilmax: %-5.4f %-5.4f / lww: %-5.2f %-5.2f / b: %-5.2f %-5.2f' % ( np.max(data.index.year) - np.min(data.index.year) + 1, data['gsoil_max_WUE_d_p'].values[0], data['gsoil_max_0_d'].values[0], data['lww_WUE_d_p'].values[0]*10**3, data['lww_WUE_d'].values[0]*10**3, data['b_WUE_d_p'].values[0], data['b_WUE_d'].values[0])) plt.legend() ax.set_ylim([0, max_v]) ax.set_xlim([0, max_v]) ax.set_xlabel('LE mod') ax.set_ylabel('LE obs') plt.savefig(fig_name) print(' ') plt.close() if __name__ == "__main__": sites_params = pd.read_csv( '../../DATA/EEGS/sel2_sites_params.csv') pft_params = pd.read_csv( '../../DATA/EEGS/selected_pft_params.csv') out_data_directory = '../../DATA/EEGS/fitted_models_revision_0' fig_suffix = '' data_directory = '../../DATA/EEGS/HH_data_revision_w5' sites_files = [os.path.join(data_directory, f) for f in os.listdir(data_directory)] sites_sel = sites_params['site_id'].values print(len(sites_files)) for f_site in sites_files: site_name = f_site.split('/')[-1][:-4] site = site_name[:-3] sites_params_i = sites_params[(sites_params['site_id'] == site)] pft = sites_params_i['pft'].values[0] pft_params_i = pft_params[pft_params['PFT'] == pft] data = pd.read_csv(f_site, header = 0, index_col = 0, parse_dates = True, infer_datetime_format = True,) print(site_name) fitting_results = {} out_file_m = os.path.join(out_data_directory, '%s_fitted_models_bs.csv' % (site_name)) out_file_r = os.path.join(out_data_directory, '%s_fitting_results_bs.pickle' % (site_name)) data['k2'] = data['k2_0'] # change for Tl or 0 data['k1'] = data['k1_0'] # change for Tl or 0 data['gamma_star'] = data['gamma_star_0'] # change for Tl or 0 data['leaf_water_pot'] = data['leaf_water_pot_invET'] # placeholder until invT nn_x_vars = ['VPD_a', 'SWC_F_MDS', 'CO2', 'GPP', 'PARin', 'TA_F_MDS', 'Ga', 'Rn-G'] LE_ann, r_nn, nse_LE_nn, mape_LE_nn = fit_nn(data, y_var='LE_F_MDS', x_vars=nn_x_vars) data['LE_NN'] = LE_ann data['nse_LE_NN'] = nse_LE_nn data['mape_LE_NN'] = mape_LE_nn fitting_results['LE_NN'] = {'NSE': nse_LE_nn, 'mape': mape_LE_nn} model_alternatives_d_p = ['WUE_d_p', 'CM_d4_p', 'SOX_d3_p'] model_alternatives_d = ['WUE_d', 'WUE_i', 'CM_d2', 'CM_d4', 'CM_i4', 'SOX_d1', 'SOX_d3', 'SOX_i3'] for tag in model_alternatives_d_p: data = process_model_alternative(data, tag) avg_gsoil_max = np.sum([data['gsoil_max_WUE_d_p'][0], data['gsoil_max_CM_d4_p'][0], data['gsoil_max_SOX_d3_p'][0]]) / 3. data['gsoil_max_0_d'] = avg_gsoil_max data['g_soil_0_d'] = data['S'] * avg_gsoil_max data['T'] = data['ET_obs'] * (1 - data['g_soil_0_d'] / data['G_surf_mol']) data['leaf_water_pot'] = cal_psi_leaf(data['canopy_water_pot_pd'], pft_params_i['psi_50'].values[0], pft_params_i['kmax'].values[0] * np.max(data['LAI']), pft_params_i['a'].values[0], data['T']) drop_v = [k for k in data.keys() if k.endswith('_p')==0] data = data[drop_v] for tag in model_alternatives_d: data, fitting_results = process_model_alternative_bs(data, tag, fitting_results) with open(out_file_r, 'wb') as f: dump(fitting_results, f) data.to_csv(out_file_m) print(site_name, 'done') print(' ')
[ "sklearn.neural_network.MLPRegressor", "pandas.read_csv", "scipy.stats.pearsonr", "numpy.nanmin", "lmfit.Parameters", "os.listdir", "lmfit.Minimizer", "numpy.max", "matplotlib.pyplot.close", "numpy.nanmax", "numpy.min", "random.uniform", "matplotlib.pyplot.savefig", "numpy.isnan", "matpl...
[((5647, 5659), 'lmfit.Parameters', 'Parameters', ([], {}), '()\n', (5657, 5659), False, 'from lmfit import Minimizer, Parameters\n'), ((10545, 10633), 'lmfit.Minimizer', 'Minimizer', (['min_model', 'params'], {'fcn_args': '(xx, data_i[min_fit_var].values, min_fit_var)'}), '(min_model, params, fcn_args=(xx, data_i[min_fit_var].values,\n min_fit_var))\n', (10554, 10633), False, 'from lmfit import Minimizer, Parameters\n'), ((11087, 11099), 'lmfit.Parameters', 'Parameters', ([], {}), '()\n', (11097, 11099), False, 'from lmfit import Minimizer, Parameters\n'), ((17623, 17637), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (17635, 17637), False, 'from datetime import datetime\n'), ((19517, 19559), 'sklearn.preprocessing.scale', 'preprocessing.scale', (['data_i[x_vars].values'], {}), '(data_i[x_vars].values)\n', (19536, 19559), False, 'from sklearn import preprocessing\n'), ((19569, 19597), 'sklearn.neural_network.MLPRegressor', 'MLPRegressor', ([], {'solver': '"""lbfgs"""'}), "(solver='lbfgs')\n", (19581, 19597), False, 'from sklearn.neural_network import MLPRegressor\n'), ((20027, 20079), 'pandas.read_csv', 'pd.read_csv', (['"""../../DATA/EEGS/sel2_sites_params.csv"""'], {}), "('../../DATA/EEGS/sel2_sites_params.csv')\n", (20038, 20079), True, 'import pandas as pd\n'), ((20098, 20152), 'pandas.read_csv', 'pd.read_csv', (['"""../../DATA/EEGS/selected_pft_params.csv"""'], {}), "('../../DATA/EEGS/selected_pft_params.csv')\n", (20109, 20152), True, 'import pandas as pd\n'), ((26620, 26672), 'pandas.read_csv', 'pd.read_csv', (['"""../../DATA/EEGS/sel2_sites_params.csv"""'], {}), "('../../DATA/EEGS/sel2_sites_params.csv')\n", (26631, 26672), True, 'import pandas as pd\n'), ((26691, 26745), 'pandas.read_csv', 'pd.read_csv', (['"""../../DATA/EEGS/selected_pft_params.csv"""'], {}), "('../../DATA/EEGS/selected_pft_params.csv')\n", (26702, 26745), True, 'import pandas as pd\n'), ((17653, 17667), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (17665, 17667), False, 'from datetime import datetime\n'), ((19695, 19732), 'scipy.stats.pearsonr', 'pearsonr', (['y_ann', 'data_i[y_var].values'], {}), '(y_ann, data_i[y_var].values)\n', (19703, 19732), False, 'from scipy.stats import pearsonr\n'), ((20262, 20293), 'os.path.join', 'os.path.join', (['data_directory', 'f'], {}), '(data_directory, f)\n', (20274, 20293), False, 'import os\n'), ((20534, 20555), 'numpy.int', 'np.int', (['site_name[-1]'], {}), '(site_name[-1])\n', (20540, 20555), True, 'import numpy as np\n'), ((20833, 20910), 'os.path.join', 'os.path.join', (['out_figures_directory', "('%s_fit%s.png' % (site_name, fig_suffix))"], {}), "(out_figures_directory, '%s_fit%s.png' % (site_name, fig_suffix))\n", (20845, 20910), False, 'import os\n'), ((20927, 21019), 'pandas.read_csv', 'pd.read_csv', (['f_site'], {'header': '(0)', 'index_col': '(0)', 'parse_dates': '(True)', 'infer_datetime_format': '(True)'}), '(f_site, header=0, index_col=0, parse_dates=True,\n infer_datetime_format=True)\n', (20938, 21019), True, 'import pandas as pd\n'), ((23397, 23425), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(15, 10)'}), '(figsize=(15, 10))\n', (23407, 23425), True, 'import matplotlib.pyplot as plt\n'), ((24414, 24426), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (24424, 24426), True, 'import matplotlib.pyplot as plt\n'), ((24435, 24451), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (24444, 24451), True, 'import matplotlib.pyplot as plt\n'), ((24890, 24902), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (24900, 24902), True, 'import matplotlib.pyplot as plt\n'), ((25451, 25463), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (25461, 25463), True, 'import matplotlib.pyplot as plt\n'), ((25576, 25611), 'numpy.nanmax', 'np.nanmax', (["[data['LE_F_MDS'] * 1.2]"], {}), "([data['LE_F_MDS'] * 1.2])\n", (25585, 25611), True, 'import numpy as np\n'), ((26346, 26358), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (26356, 26358), True, 'import matplotlib.pyplot as plt\n'), ((26496, 26517), 'matplotlib.pyplot.savefig', 'plt.savefig', (['fig_name'], {}), '(fig_name)\n', (26507, 26517), True, 'import matplotlib.pyplot as plt\n'), ((26554, 26565), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (26563, 26565), True, 'import matplotlib.pyplot as plt\n'), ((26918, 26949), 'os.path.join', 'os.path.join', (['data_directory', 'f'], {}), '(data_directory, f)\n', (26930, 26949), False, 'import os\n'), ((27387, 27479), 'pandas.read_csv', 'pd.read_csv', (['f_site'], {'header': '(0)', 'index_col': '(0)', 'parse_dates': '(True)', 'infer_datetime_format': '(True)'}), '(f_site, header=0, index_col=0, parse_dates=True,\n infer_datetime_format=True)\n', (27398, 27479), True, 'import pandas as pd\n'), ((27593, 27664), 'os.path.join', 'os.path.join', (['out_data_directory', "('%s_fitted_models_bs.csv' % site_name)"], {}), "(out_data_directory, '%s_fitted_models_bs.csv' % site_name)\n", (27605, 27664), False, 'import os\n'), ((27688, 27764), 'os.path.join', 'os.path.join', (['out_data_directory', "('%s_fitting_results_bs.pickle' % site_name)"], {}), "(out_data_directory, '%s_fitting_results_bs.pickle' % site_name)\n", (27700, 27764), False, 'import os\n'), ((19323, 19337), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (19335, 19337), False, 'from datetime import datetime\n'), ((20324, 20350), 'os.listdir', 'os.listdir', (['data_directory'], {}), '(data_directory)\n', (20334, 20350), False, 'import os\n'), ((22424, 22528), 'numpy.sum', 'np.sum', (["[data['gsoil_max_WUE_d_p'][0], data['gsoil_max_CM_d4_p'][0], data[\n 'gsoil_max_SOX_d3_p'][0]]"], {}), "([data['gsoil_max_WUE_d_p'][0], data['gsoil_max_CM_d4_p'][0], data[\n 'gsoil_max_SOX_d3_p'][0]])\n", (22430, 22528), True, 'import numpy as np\n'), ((23197, 23230), 'numpy.nanmin', 'np.nanmin', (["data['leaf_water_pot']"], {}), "(data['leaf_water_pot'])\n", (23206, 23230), True, 'import numpy as np\n'), ((23232, 23265), 'numpy.nanmax', 'np.nanmax', (["data['leaf_water_pot']"], {}), "(data['leaf_water_pot'])\n", (23241, 23265), True, 'import numpy as np\n'), ((23475, 23504), 'numpy.nanmax', 'np.nanmax', (["data['G_surf_mol']"], {}), "(data['G_surf_mol'])\n", (23484, 23504), True, 'import numpy as np\n'), ((23545, 23569), 'numpy.nanmax', 'np.nanmax', (["data['VPD_l']"], {}), "(data['VPD_l'])\n", (23554, 23569), True, 'import numpy as np\n'), ((26980, 27006), 'os.listdir', 'os.listdir', (['data_directory'], {}), '(data_directory)\n', (26990, 27006), False, 'import os\n'), ((28907, 29011), 'numpy.sum', 'np.sum', (["[data['gsoil_max_WUE_d_p'][0], data['gsoil_max_CM_d4_p'][0], data[\n 'gsoil_max_SOX_d3_p'][0]]"], {}), "([data['gsoil_max_WUE_d_p'][0], data['gsoil_max_CM_d4_p'][0], data[\n 'gsoil_max_SOX_d3_p'][0]])\n", (28913, 29011), True, 'import numpy as np\n'), ((7162, 7202), 'random.uniform', 'random.uniform', (['lww_lims[0]', 'lww_lims[1]'], {}), '(lww_lims[0], lww_lims[1])\n', (7176, 7202), False, 'import random\n'), ((14694, 14713), 'numpy.nanmedian', 'np.nanmedian', (['param'], {}), '(param)\n', (14706, 14713), True, 'import numpy as np\n'), ((17096, 17133), 'numpy.nanmedian', 'np.nanmedian', (["data_i['eLAI_%s' % tag]"], {}), "(data_i['eLAI_%s' % tag])\n", (17108, 17133), True, 'import numpy as np\n'), ((17143, 17190), 'numpy.nanmedian', 'np.nanmedian', (["(data_i['mwue_%s' % tag] * 10 ** 3)"], {}), "(data_i['mwue_%s' % tag] * 10 ** 3)\n", (17155, 17190), True, 'import numpy as np\n'), ((23026, 23045), 'numpy.max', 'np.max', (["data['LAI']"], {}), "(data['LAI'])\n", (23032, 23045), True, 'import numpy as np\n'), ((24264, 24286), 'numpy.nanmax', 'np.nanmax', (["data['LAI']"], {}), "(data['LAI'])\n", (24273, 24286), True, 'import numpy as np\n'), ((24371, 24404), 'numpy.nanmin', 'np.nanmin', (["data['soil_water_pot']"], {}), "(data['soil_water_pot'])\n", (24380, 24404), True, 'import numpy as np\n'), ((29508, 29527), 'numpy.max', 'np.max', (["data['LAI']"], {}), "(data['LAI'])\n", (29514, 29527), True, 'import numpy as np\n'), ((7370, 7410), 'random.uniform', 'random.uniform', (['lww_lims[0]', 'lww_lims[1]'], {}), '(lww_lims[0], lww_lims[1])\n', (7384, 7410), False, 'import random\n'), ((7487, 7523), 'random.uniform', 'random.uniform', (['b_lims[0]', 'b_lims[1]'], {}), '(b_lims[0], b_lims[1])\n', (7501, 7523), False, 'import random\n'), ((21082, 21105), 'numpy.max', 'np.max', (['data.index.year'], {}), '(data.index.year)\n', (21088, 21105), True, 'import numpy as np\n'), ((21108, 21131), 'numpy.min', 'np.min', (['data.index.year'], {}), '(data.index.year)\n', (21114, 21131), True, 'import numpy as np\n'), ((25169, 25193), 'numpy.nanmax', 'np.nanmax', (["data_d['LAI']"], {}), "(data_d['LAI'])\n", (25178, 25193), True, 'import numpy as np\n'), ((25288, 25341), 'numpy.nanmedian', 'np.nanmedian', (["(data['g_soil_0_d'] / data['G_surf_mol'])"], {}), "(data['g_soil_0_d'] / data['G_surf_mol'])\n", (25300, 25341), True, 'import numpy as np\n'), ((7629, 7667), 'random.uniform', 'random.uniform', (['b2_lims[0]', 'b2_lims[1]'], {}), '(b2_lims[0], b2_lims[1])\n', (7643, 7667), False, 'import random\n'), ((7743, 7781), 'random.uniform', 'random.uniform', (['b1_lims[0]', 'b1_lims[1]'], {}), '(b1_lims[0], b1_lims[1])\n', (7757, 7781), False, 'import random\n'), ((8901, 8935), 'random.uniform', 'random.uniform', (['k_lim[0]', 'k_lim[1]'], {}), '(k_lim[0], k_lim[1])\n', (8915, 8935), False, 'import random\n'), ((25951, 25974), 'numpy.max', 'np.max', (['data.index.year'], {}), '(data.index.year)\n', (25957, 25974), True, 'import numpy as np\n'), ((25977, 26000), 'numpy.min', 'np.min', (['data.index.year'], {}), '(data.index.year)\n', (25983, 26000), True, 'import numpy as np\n'), ((8126, 8160), 'random.uniform', 'random.uniform', (['a_lim[0]', 'a_lim[1]'], {}), '(a_lim[0], a_lim[1])\n', (8140, 8160), False, 'import random\n'), ((8453, 8491), 'random.uniform', 'random.uniform', (['p50_lim[0]', 'p50_lim[1]'], {}), '(p50_lim[0], p50_lim[1])\n', (8467, 8491), False, 'import random\n'), ((9277, 9311), 'random.uniform', 'random.uniform', (['a_lim[0]', 'a_lim[1]'], {}), '(a_lim[0], a_lim[1])\n', (9291, 9311), False, 'import random\n'), ((15853, 15865), 'numpy.isnan', 'np.isnan', (['yi'], {}), '(yi)\n', (15861, 15865), True, 'import numpy as np\n'), ((8625, 8659), 'random.uniform', 'random.uniform', (['a_lim[0]', 'a_lim[1]'], {}), '(a_lim[0], a_lim[1])\n', (8639, 8659), False, 'import random\n'), ((8739, 8777), 'random.uniform', 'random.uniform', (['p50_lim[0]', 'p50_lim[1]'], {}), '(p50_lim[0], p50_lim[1])\n', (8753, 8777), False, 'import random\n'), ((9606, 9644), 'random.uniform', 'random.uniform', (['p50_lim[0]', 'p50_lim[1]'], {}), '(p50_lim[0], p50_lim[1])\n', (9620, 9644), False, 'import random\n'), ((9778, 9812), 'random.uniform', 'random.uniform', (['a_lim[0]', 'a_lim[1]'], {}), '(a_lim[0], a_lim[1])\n', (9792, 9812), False, 'import random\n'), ((9893, 9931), 'random.uniform', 'random.uniform', (['p50_lim[0]', 'p50_lim[1]'], {}), '(p50_lim[0], p50_lim[1])\n', (9907, 9931), False, 'import random\n')]
import numpy as np import matplotlib.pyplot as plt from grid_world import standard_grid, negative_grid from policy_iterative_evaluation import print_policy, print_values THRESHOLD = 1e-3 GAMMA = 0.9 ALL_POSSIBLE_ACTIONS = ('U', 'D', 'L', 'R') if __name__ == '__main__': grid = negative_grid(step_cost = -0.1) States = grid.all_states() print("Rewards:") print_values(grid.rewards, grid) #Intial Value Function V = {} for s in States: if s == grid.actions: V[s] = np.random.random() else: #Terminal States V[s] = 0 #Initial policy Policy = {} for s in grid.actions.keys(): Policy[s] = np.random.choice(ALL_POSSIBLE_ACTIONS) print('Print Policy: ') print_policy(Policy, grid) while True: while True:# k : iteration #Setting delta to say the new Value #is the policy True Value or Not delta = 0 for s in States: old_v = V[s] new_v = 0 if s in Policy: #Check all the Posible actions for a in ALL_POSSIBLE_ACTIONS: #If the action is the action that the agent #want to take then the probability is 0.5 otherwise #the probability is 0.5/3 for each ofther actions if a == Policy[s]: p_a = 0.5 else: p_a = 0.5/3 #Set the state be the current_state grid.set_state(s) #Experience the action to update the value Function #of particular state r = grid.move(a) #Update Value Function V(k+1)(s) base on the old V(k)(s') new_v += p_a * (r + GAMMA * V[grid.current_state()]) #Assign the new Value to the current State S(k+1) V[s] = new_v #Set delta to be the V(k)(s) - V(k+1)(s) delta = max(delta, np.abs(old_v - V[s])) #Check if the Value function is the True Value of the Policy or Not if delta < THRESHOLD: break is_policy_converged = True for s in States: if s in Policy: old_a = Policy[s] new_a = None best_value = float('-inf') #Test through all Actions and choose the one that have the highest #Value Function for a in ALL_POSSIBLE_ACTIONS: v = 0 #The Probability that the wind might blow the agent to #other states for a2 in ALL_POSSIBLE_ACTIONS: if a == a2: p_a = 0.5 else: p_a = 0.5/3 #Set the state to be the current state grid.set_state(s) #Experience the action r = grid.move(a) #Set Value Function for that action v += p_a * (r + GAMMA * V[grid.current_state()]) #Check which action have the best value function if v > best_value: best_value = v new_a = a #Set the action at particular state to be the highest action Policy[s] = new_a #Check if the new action and the old action is the same or not #If these actions are the same #then the MDP is solved (Found Optimal Policy) if new_a != old_a: is_policy_converged = False if is_policy_converged: break print("values:") print_values(V, grid) print("policy:") print_policy(Policy, grid)
[ "numpy.abs", "policy_iterative_evaluation.print_policy", "numpy.random.choice", "numpy.random.random", "policy_iterative_evaluation.print_values", "grid_world.negative_grid" ]
[((285, 314), 'grid_world.negative_grid', 'negative_grid', ([], {'step_cost': '(-0.1)'}), '(step_cost=-0.1)\n', (298, 314), False, 'from grid_world import standard_grid, negative_grid\n'), ((376, 408), 'policy_iterative_evaluation.print_values', 'print_values', (['grid.rewards', 'grid'], {}), '(grid.rewards, grid)\n', (388, 408), False, 'from policy_iterative_evaluation import print_policy, print_values\n'), ((766, 792), 'policy_iterative_evaluation.print_policy', 'print_policy', (['Policy', 'grid'], {}), '(Policy, grid)\n', (778, 792), False, 'from policy_iterative_evaluation import print_policy, print_values\n'), ((3993, 4014), 'policy_iterative_evaluation.print_values', 'print_values', (['V', 'grid'], {}), '(V, grid)\n', (4005, 4014), False, 'from policy_iterative_evaluation import print_policy, print_values\n'), ((4040, 4066), 'policy_iterative_evaluation.print_policy', 'print_policy', (['Policy', 'grid'], {}), '(Policy, grid)\n', (4052, 4066), False, 'from policy_iterative_evaluation import print_policy, print_values\n'), ((694, 732), 'numpy.random.choice', 'np.random.choice', (['ALL_POSSIBLE_ACTIONS'], {}), '(ALL_POSSIBLE_ACTIONS)\n', (710, 732), True, 'import numpy as np\n'), ((518, 536), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (534, 536), True, 'import numpy as np\n'), ((2176, 2196), 'numpy.abs', 'np.abs', (['(old_v - V[s])'], {}), '(old_v - V[s])\n', (2182, 2196), True, 'import numpy as np\n')]
import numpy as np import pandas as pd from scipy import stats import pdb from ..utils import ClassUtils def default_params(): ''' :param n_bins: hard upper bound on the number of bins in the continuous component of the shmistogram :param prebin_maxbins: (int) pre-bin the points as you would in a standard histogram with at most `prebin_maxbins` bins to limit the computational cost ''' return { 'n_bins': None, 'prebin_maxbins': 100, 'verbose': False } def rate_similarity(n1, w1, n2, w2): ''' Estimate the statistical significance of the difference between two rates; return a p-value adjusted for small sample size. :param n1: Count of obs in first bin :param w1: Width of first bin :param n2: Count of obs in second bin :param w2: Width of second bin :return: An estimate of the statistical significance of the difference in empirical height (or 'rate') between the two bins ''' n_trials = n1 + n2 h0_bin1_rate = w1/(w1+w2) bernoulli_variance = h0_bin1_rate * (1 - h0_bin1_rate) binomial_mean = h0_bin1_rate*n_trials binomial_sdev = np.sqrt(n_trials * bernoulli_variance) zscore = -np.absolute(n1 - binomial_mean)/(2*binomial_sdev) p = 2*stats.norm.cdf(zscore) # TODO: use something more principled as a correction to the gaussian # approximation when counts are small: geom = np.sqrt(n1 * n2) return p + (1-p)/(1 + np.exp(0.1*geom - 1.5)) def forward_merge_score(bins): ''' A heuristic score of the relative suitability of a merge for every bin with its right-side neighbor Combines several preference-for-merging factors: - rate sameness: bins that share approximately the same height should be merged - balanced mass: the largest bin is ideally not more than several times larger than the smallest bin, in probability mass - balanced width: the widest bin is ideally not more than several times wider than the narrowest bin :param bins: (pandas.DataFrame) contains columns 'freq', 'width', and 'rate'; each row is a bin ''' # rate sameness s = np.array([ rate_similarity( bins.freq[k], bins.width[k], bins.freq[k+1], bins.width[k+1] ) for k in range(bins.shape[0]-1) ]) # contribution to mass balance mr = bins.freq.rank(pct=True).values m = 1 - mr[1:] * mr[:-1] # contribution to width balance wr = bins.width.rank(pct=True).values w = 1 - wr[1:] * wr[:-1] # combine all 3 scores into one, as an elementwise vector product return s*m*w def collapse_one(bins, k): ''' :param bins: (pandas.DataFrame) contains columns 'freq', 'width', and 'rate'; each row is a bin :param k: Index of row to collapse with (k+1)th row :return: same as bins but one fewer row due to collapsing ''' # Here 'dfm' stands for 2-row Data Frame to be Merged dfm = bins.iloc[k:k+2] df = pd.DataFrame({ 'freq': dfm.freq.sum(), 'lb': dfm.lb.values[0], 'ub': dfm.ub.values[-1] }, index=[0]) assert (df.ub - df.lb).min() > 0 df['width'] = df.ub - df.lb df['rate'] = df.freq / df.width bins_minus_one = pd.concat([ bins.iloc[:k], df, bins.iloc[k + 2:] ]).reset_index(drop=True) return bins_minus_one class Agglomerator(ClassUtils): def __init__(self, params=None): self.params = default_params() if params is not None: self.params.update(params) self.verbose = self.params.pop('verbose') def fit(self, df): self.N = df.n_obs.sum() self.df = df self._bins_init() if self.params['n_bins'] is None: nrow = self.df.shape[0] self.params['n_bins'] = round(np.log(nrow+1) ** 1.5) while self.bins.shape[0] > self.params['n_bins']: fms = forward_merge_score(self.bins) self.bins = collapse_one(self.bins, np.argmax(fms)) return self.bins def _bin_init(self, xs): df = self.df.iloc[xs] stats_dict = { 'lb': df.index.min(), 'ub': df.index.max(), 'freq': df.n_obs.sum() } return stats_dict def _bins_init(self): # Prior to beginning any agglomeration routine, we do a coarse pre-binning # by simple dividing the data into approximately equal-sized groups (leading # to non-uniform bin widths) nc = self.df.shape[0] if nc == 0: return pd.DataFrame({ 'freq': [], 'lb': [], 'ub': [], 'width': [], 'rate': [] }) prebin_maxbins = min(nc, self.params['prebin_maxbins']) bin_idxs = np.array_split(np.arange(nc), prebin_maxbins) bins = pd.DataFrame([self._bin_init(xs) for xs in bin_idxs]) gap_margin = (bins.lb.values[1:] - bins.ub.values[:-1])/2 cuts = (bins.lb.values[1:] - gap_margin).tolist() bins.lb = [bins.lb.values[0]] + cuts bins.ub = cuts + [bins.ub.values[-1]] bins['width'] = bins.ub - bins.lb if nc > 1: # else, nc=1 and the bin has a single value with lb=ub, so width=0 try: assert bins.width.min() > 0 except: raise Exception("The bin width is 0, which should not be possible") bins['rate'] = bins.freq/bins.width self.bins = bins
[ "numpy.sqrt", "numpy.absolute", "numpy.log", "numpy.argmax", "numpy.exp", "pandas.DataFrame", "scipy.stats.norm.cdf", "pandas.concat", "numpy.arange" ]
[((1163, 1201), 'numpy.sqrt', 'np.sqrt', (['(n_trials * bernoulli_variance)'], {}), '(n_trials * bernoulli_variance)\n', (1170, 1201), True, 'import numpy as np\n'), ((1428, 1444), 'numpy.sqrt', 'np.sqrt', (['(n1 * n2)'], {}), '(n1 * n2)\n', (1435, 1444), True, 'import numpy as np\n'), ((1276, 1298), 'scipy.stats.norm.cdf', 'stats.norm.cdf', (['zscore'], {}), '(zscore)\n', (1290, 1298), False, 'from scipy import stats\n'), ((1216, 1247), 'numpy.absolute', 'np.absolute', (['(n1 - binomial_mean)'], {}), '(n1 - binomial_mean)\n', (1227, 1247), True, 'import numpy as np\n'), ((3245, 3294), 'pandas.concat', 'pd.concat', (['[bins.iloc[:k], df, bins.iloc[k + 2:]]'], {}), '([bins.iloc[:k], df, bins.iloc[k + 2:]])\n', (3254, 3294), True, 'import pandas as pd\n'), ((4544, 4615), 'pandas.DataFrame', 'pd.DataFrame', (["{'freq': [], 'lb': [], 'ub': [], 'width': [], 'rate': []}"], {}), "({'freq': [], 'lb': [], 'ub': [], 'width': [], 'rate': []})\n", (4556, 4615), True, 'import pandas as pd\n'), ((4808, 4821), 'numpy.arange', 'np.arange', (['nc'], {}), '(nc)\n', (4817, 4821), True, 'import numpy as np\n'), ((1471, 1495), 'numpy.exp', 'np.exp', (['(0.1 * geom - 1.5)'], {}), '(0.1 * geom - 1.5)\n', (1477, 1495), True, 'import numpy as np\n'), ((3976, 3990), 'numpy.argmax', 'np.argmax', (['fms'], {}), '(fms)\n', (3985, 3990), True, 'import numpy as np\n'), ((3798, 3814), 'numpy.log', 'np.log', (['(nrow + 1)'], {}), '(nrow + 1)\n', (3804, 3814), True, 'import numpy as np\n')]
# Copyright 2021 NREL # 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. # See https://floris.readthedocs.io for documentation import numpy as np import pandas as pd import matplotlib.pyplot as plt def gaussian(x, mu, sig): """ Compute gaussian function, from https://stackoverflow.com/questions/14873203/plotting-of-1-dimensional-gaussian-distribution-function. Args: x (np.array): Input variable to Gaussian. mu (float): Mean value. sig (float): Standard deviation. Returns: np.array: The resulting Gaussian distribution. """ return np.exp(-np.power(x - mu, 2.0) / (2 * np.power(sig, 2.0))) def _convert_to_numpy_array(series): """ Convert an input series to NumPy array. Currently, this function checks if an object has a `values` attribute and returns that if it does. Otherwise, it returns the given input if that input is a `np.ndarray`. Args: series (pd.Series): Series to convert. Returns: np.array: Converted Series. """ if hasattr(series, "values"): return series.values elif isinstance(series, np.ndarray): return series def _calculate_bootstrap_iterations(n): """ Calculate number of bootstrap iterations given length. # TODO: What are `bootstrap iterations`? Args: n (int): Number of points. Returns: int: Number of bootstrap iterations. """ maximum = 10000 minimum = 2000 return int(np.round(max(min(n * np.log10(n), maximum), minimum))) def _calculate_lower_and_upper_bound( bootstrap_array, percentiles, central_estimate=None, method="simple_percentile" ): """ Given resultant bootstrap output array, compute lower and upper bound of confidence interval. Args: bootstrap_array (np.array): array of bootrapped results percentiles (np.array): percentile values central_estimate (float, optional): if not using simple percentile, need to provide the central estimated result. Defaults to None. method (str, optional): method for computing bounds. Defaults to 'simple_percentile'. Returns: float, float: - lower ci bound - upper ci bound """ if method == "simple_percentile": upper, lower = np.percentile(bootstrap_array, percentiles) else: lower, upper = 2 * central_estimate - np.percentile( bootstrap_array, percentiles ) return lower, upper def _get_confidence_bounds(confidence): """ Get the upper and lower confidence bounds given a desired confidence level. Args: confidence (float): [description] # TODO: ^^ Returns: float, float: - upper confidence bound - lower confidence bound """ return [50 + 0.5 * confidence, 50 - 0.5 * confidence] def energy_ratio(ref_pow_base, test_pow_base): """ Compute the balanced energy ratio for a single binned wind direction Single version, not comparing controller on controller off This function is called to compute a single balanced energy ratio calculation for a particular wind direction bin. Note the reference turbine should not be the turbine implementing control, but should be an unaffected nearby turbine, or a synthetic power estimate from a measurement. See :cite:`ers-fleming2019initial` and :cite:`ers-fleming2019continued` for more information. References: .. bibliography:: /source/zrefs.bib :style: unsrt :filter: docname in docnames :keyprefix: ers- Args: ref_pow_base (np.array): Array of baseline reference turbine power. test_pow_base (np.array): Array of baseline test turbine power. Returns: tuple: tuple containing: - **ratio_base** (*float*): Baseline energy ratio. - **counts_base** (*float*): Number of points in baseline. """ if len(ref_pow_base) == 0: return np.nan, np.nan # Weighted sums weight_sum_ref_base = np.sum(ref_pow_base) weight_sum_test_base = np.sum(test_pow_base) if (weight_sum_ref_base == 0) or (weight_sum_test_base == 0): return np.nan, np.nan ratio_base = weight_sum_test_base / weight_sum_ref_base # Get the counts counts_base = len(ref_pow_base) return ratio_base, counts_base def calculate_balanced_energy_ratio( reference_power_baseline, test_power_baseline, wind_direction_array_baseline, wind_direction_bins, confidence=95, n_boostrap=None, wind_direction_bin_p_overlap=None, ): """ Calculate a balanced energy ratio for each wind direction bin. Single version, not divided into baseline and controlled Calculate a balanced energy ratio for each wind direction bin. A reference and test turbine are provided for the ratio, as well as wind speed and wind directions. These data are further divided into baseline and controlled conditions. The balanced energy ratio function is called and used to ensure a similar distribution of wind speeds is used in the computation, per wind direction bin, for baseline and controlled results. Resulting arrays, including upper and lower uncertainty bounds computed through bootstrapping, are returned. Note the reference turbine should not be the turbine implementing control, but should be an unaffected nearby turbine, or a synthetic power estimate from a measurement See :cite:`ers-fleming2019initial` and :cite:`ers-fleming2019continued` for more information. References: .. bibliography:: /source/zrefs.bib :style: unsrt :filter: docname in docnames :keyprefix: ers- Args: reference_power_baseline (np.array): Array of power of reference turbine in baseline conditions. test_power_baseline (np.array): Array of power of test turbine in baseline conditions. wind_speed_array_baseline (np.array): Array of wind speeds in baseline conditions. wind_direction_array_baseline (np.array): Array of wind directions in baseline case. wind_direction_bins (np.array): Wind directions bins. confidence (int, optional): Confidence level to use. Defaults to 95. n_boostrap (int, optional): Number of bootstaps, if none, _calculate_bootstrap_iterations is called. Defaults to None. wind_direction_bin_p_overlap (np.array, optional): Percentage overlap between wind direction bin. Defaults to None. Returns: tuple: tuple containing: **ratio_array_base** (*np.array*): Baseline energy ratio at each wind direction bin. **lower_ratio_array_base** (*np.array*): Lower confidence bound of baseline energy ratio at each wind direction bin. **upper_ratio_array_base** (*np.array*): Upper confidence bound of baseline energy ratio at each wind direction bin. **counts_ratio_array_base** (*np.array*): Counts per wind direction bin in baseline. """ # Ensure that input arrays are np.ndarray reference_power_baseline = _convert_to_numpy_array(reference_power_baseline) test_power_baseline = _convert_to_numpy_array(test_power_baseline) wind_direction_array_baseline = _convert_to_numpy_array( wind_direction_array_baseline ) # Handle no overlap specificed (assume non-overlap) if wind_direction_bin_p_overlap is None: wind_direction_bin_p_overlap = 0 # Compute binning radius (is this right?) wind_direction_bin_radius = ( (1.0 + wind_direction_bin_p_overlap / 100.0) * (wind_direction_bins[1] - wind_direction_bins[0]) / 2.0 ) ratio_array_base = np.zeros(len(wind_direction_bins)) * np.nan lower_ratio_array_base = np.zeros(len(wind_direction_bins)) * np.nan upper_ratio_array_base = np.zeros(len(wind_direction_bins)) * np.nan counts_ratio_array_base = np.zeros(len(wind_direction_bins)) * np.nan for i, wind_direction_bin in enumerate(wind_direction_bins): wind_dir_mask_baseline = ( wind_direction_array_baseline >= wind_direction_bin - wind_direction_bin_radius ) & ( wind_direction_array_baseline < wind_direction_bin + wind_direction_bin_radius ) reference_power_baseline_wd = reference_power_baseline[wind_dir_mask_baseline] test_power_baseline_wd = test_power_baseline[wind_dir_mask_baseline] wind_dir_array_baseline_wd = wind_direction_array_baseline[ wind_dir_mask_baseline ] baseline_weight = gaussian( wind_dir_array_baseline_wd, wind_direction_bin, wind_direction_bin_radius / 2.0, ) baseline_weight = baseline_weight / np.sum(baseline_weight) if len(reference_power_baseline_wd) == 0: continue # compute the energy ratio # ratio_array_base[i], counts_ratio_array_base[i] = energy_ratio(reference_power_baseline_wd, test_power_baseline_wd) # Get the bounds through boot strapping # determine the number of bootstrap iterations if not given if n_boostrap is None: n_boostrap = _calculate_bootstrap_iterations( len(reference_power_baseline_wd) ) ratio_base_bs = np.zeros(n_boostrap) for i_bs in range(n_boostrap): # random resampling w/ replacement # ind_bs = np.random.randint( # len(reference_power_baseline_wd), size=len(reference_power_baseline_wd)) ind_bs = np.random.choice( len(reference_power_baseline_wd), size=len(reference_power_baseline_wd), p=baseline_weight, ) reference_power_binned_baseline = reference_power_baseline_wd[ind_bs] test_power_binned_baseline = test_power_baseline_wd[ind_bs] # compute the energy ratio ratio_base_bs[i_bs], _ = energy_ratio( reference_power_binned_baseline, test_power_binned_baseline ) # Get the confidence bounds percentiles = _get_confidence_bounds(confidence) # Compute the central over from the bootstrap runs ratio_array_base[i] = np.mean(ratio_base_bs) ( lower_ratio_array_base[i], upper_ratio_array_base[i], ) = _calculate_lower_and_upper_bound( ratio_base_bs, percentiles, central_estimate=ratio_array_base[i], method="simple_percentile", ) return ( ratio_array_base, lower_ratio_array_base, upper_ratio_array_base, counts_ratio_array_base, ) def plot_energy_ratio( reference_power_baseline, test_power_baseline, wind_speed_array_baseline, wind_direction_array_baseline, wind_direction_bins, confidence=95, n_boostrap=None, wind_direction_bin_p_overlap=None, ax=None, base_color="b", label_array=None, label_pchange=None, plot_simple=False, plot_ratio_scatter=False, marker_scale=1.0, show_count=True, hide_controlled_case=False, ): """ Plot the single energy ratio. Function mainly acts as a wrapper to call calculate_balanced_energy_ratio and plot the results. Args: reference_power_baseline (np.array): Array of power of reference turbine in baseline conditions. test_power_baseline (np.array): Array of power of test turbine in baseline conditions. wind_speed_array_baseline (np.array): Array of wind speeds in baseline conditions. wind_direction_array_baseline (np.array): Array of wind directions in baseline case. wind_direction_bins (np.array): Wind directions bins. confidence (int, optional): Confidence level to use. Defaults to 95. n_boostrap (int, optional): Number of bootstaps, if none, _calculate_bootstrap_iterations is called. Defaults to None. wind_direction_bin_p_overlap (np.array, optional): Percentage overlap between wind direction bin. Defaults to None. axarr ([axes], optional): list of axes to plot to. Defaults to None. base_color (str, optional): Color of baseline in plots. Defaults to 'b'. label_array ([str], optional): List of labels to apply Defaults to None. label_pchange ([type], optional): Label for percentage change. Defaults to None. plot_simple (bool, optional): Plot only the ratio, no confidence. Defaults to False. plot_ratio_scatter (bool, optional): Include scatter plot of values, sized to indicate counts. Defaults to False. marker_scale ([type], optional): Marker scale. Defaults to 1. show_count (bool, optional): Show the counts as scatter plot hide_controlled_case (bool, optional): Option to hide the control case from plots, for demonstration """ if ax is None: fig, ax = plt.subplots(1, 1, sharex=True) if label_array is None: label_array = ["Baseline"] if label_pchange is None: label_pchange = "Energy Gain" ( ratio_array_base, lower_ratio_array_base, upper_ratio_array_base, counts_ratio_array_base, ) = calculate_balanced_energy_ratio( reference_power_baseline, test_power_baseline, wind_direction_array_baseline, wind_direction_bins, confidence=95, n_boostrap=None, wind_direction_bin_p_overlap=wind_direction_bin_p_overlap, ) if plot_simple: ax.plot( wind_direction_bins, ratio_array_base, label=label_array[0], color=base_color, ls="--", ) ax.axhline(1, color="k") ax.set_ylabel("Energy Ratio (-)") else: ax.plot( wind_direction_bins, ratio_array_base, label=label_array[0], color=base_color, ls="-", marker=".", ) ax.fill_between( wind_direction_bins, lower_ratio_array_base, upper_ratio_array_base, alpha=0.3, color=base_color, label="_nolegend_", ) if show_count: ax.scatter( wind_direction_bins, ratio_array_base, s=counts_ratio_array_base, label="_nolegend_", color=base_color, marker="o", alpha=0.2, ) ax.axhline(1, color="k") ax.set_ylabel("Energy Ratio (-)") ax.grid(True) ax.set_xlabel("Wind Direction (Deg)")
[ "numpy.mean", "numpy.log10", "numpy.power", "numpy.sum", "numpy.zeros", "numpy.percentile", "matplotlib.pyplot.subplots" ]
[((4633, 4653), 'numpy.sum', 'np.sum', (['ref_pow_base'], {}), '(ref_pow_base)\n', (4639, 4653), True, 'import numpy as np\n'), ((4681, 4702), 'numpy.sum', 'np.sum', (['test_pow_base'], {}), '(test_pow_base)\n', (4687, 4702), True, 'import numpy as np\n'), ((2828, 2871), 'numpy.percentile', 'np.percentile', (['bootstrap_array', 'percentiles'], {}), '(bootstrap_array, percentiles)\n', (2841, 2871), True, 'import numpy as np\n'), ((10050, 10070), 'numpy.zeros', 'np.zeros', (['n_boostrap'], {}), '(n_boostrap)\n', (10058, 10070), True, 'import numpy as np\n'), ((11003, 11025), 'numpy.mean', 'np.mean', (['ratio_base_bs'], {}), '(ratio_base_bs)\n', (11010, 11025), True, 'import numpy as np\n'), ((13879, 13910), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(1)'], {'sharex': '(True)'}), '(1, 1, sharex=True)\n', (13891, 13910), True, 'import matplotlib.pyplot as plt\n'), ((2928, 2971), 'numpy.percentile', 'np.percentile', (['bootstrap_array', 'percentiles'], {}), '(bootstrap_array, percentiles)\n', (2941, 2971), True, 'import numpy as np\n'), ((9498, 9521), 'numpy.sum', 'np.sum', (['baseline_weight'], {}), '(baseline_weight)\n', (9504, 9521), True, 'import numpy as np\n'), ((1095, 1116), 'numpy.power', 'np.power', (['(x - mu)', '(2.0)'], {}), '(x - mu, 2.0)\n', (1103, 1116), True, 'import numpy as np\n'), ((1124, 1142), 'numpy.power', 'np.power', (['sig', '(2.0)'], {}), '(sig, 2.0)\n', (1132, 1142), True, 'import numpy as np\n'), ((1998, 2009), 'numpy.log10', 'np.log10', (['n'], {}), '(n)\n', (2006, 2009), True, 'import numpy as np\n')]
''' ***************************************************************************************** * * =============================================== * Nirikshak Bot (NB) Theme (eYRC 2020-21) * =============================================== * * This script is to implement Task 1B of Nirikshak Bot (NB) Theme (eYRC 2020-21). * * This software is made available on an "AS IS WHERE IS BASIS". * Licensee/end user indemnifies and will keep e-Yantra indemnified from * any and all claim(s) that emanate from the use of the Software or * breach of the terms of this agreement. * * e-Yantra - An MHRD project under National Mission on Education using ICT (NMEICT) * ***************************************************************************************** ''' # Team ID: [ Team-ID ] # Author List: [ Names of team members worked on this file separated by Comma: Name1, Name2, ... ] # Filename: task_1b.py # Functions: applyPerspectiveTransform, detectMaze, writeToCsv # [ Comma separated list of functions in this file ] # Global variables: # [ List of global variables defined in this file ] ####################### IMPORT MODULES ####################### ## You are not allowed to make any changes in this section. ## ## You have to implement this task with the three available ## ## modules for this task (numpy, opencv, csv) ## ############################################################## import numpy as np import cv2 import csv ############################################################## ################# ADD UTILITY FUNCTIONS HERE ################# ## You can define any utility functions for your code. ## ## Please add proper comments to ensure that your code is ## ## readable and easy to understand. ## ############################################################## ############################################################## def applyPerspectiveTransform(input_img): """ Purpose: --- takes a maze test case image as input and applies a Perspective Transfrom on it to isolate the maze Input Arguments: --- `input_img` : [ numpy array ] maze image in the form of a numpy array Returns: --- `warped_img` : [ numpy array ] resultant warped maze image after applying Perspective Transform Example call: --- warped_img = applyPerspectiveTransform(input_img) """ bgr_img = cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY) ret,mask = cv2.threshold(bgr_img,100,255,cv2.THRESH_BINARY) # cv2.imshow("task", mask) # cv2.imshow("bgr", bgr_img) ############## ADD YOUR CODE HERE ############## contours, heirarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) if len(contours)!=0: bigcvt = contours[0] areas = [] maxarea = 0 #Isolating the biggest contour for cvt in contours: area = cv2.contourArea(cvt) areas.append(area) for cvt in contours: area = cv2.contourArea(cvt) #print(area) areas.append(area) if area>maxarea and area!= max(areas): bigcvt = cvt maxarea = area max_xplusy = 0 for i in range(len(bigcvt)): if (bigcvt[i][0][0] + bigcvt[i][0][1]) > max_xplusy: max_xplusy = (bigcvt[i][0][0] + bigcvt[i][0][1]) index_lr = i min_xplusy = max_xplusy for i in range(len(bigcvt)): if (bigcvt[i][0][0] + bigcvt[i][0][1]) < min_xplusy: min_xplusy = (bigcvt[i][0][0] + bigcvt[i][0][1]) index_ul = i max_yminusx = 0 for i in range(len(bigcvt)): if (-bigcvt[i][0][0] + bigcvt[i][0][1]) > max_yminusx: max_yminusx = (-bigcvt[i][0][0] + bigcvt[i][0][1]) index_ll = i max_xminusy = 0 for i in range(len(bigcvt)): if (bigcvt[i][0][0] - bigcvt[i][0][1]) > max_xminusy: max_xminusy = (bigcvt[i][0][0] - bigcvt[i][0][1]) index_ur = i #img = cv2.circle(input_img, (bigcvt[index_lr][0][0], bigcvt[index_lr][0][1]), 1, (0,0,255), 2) #img = cv2.circle(input_img, (bigcvt[index_ul][0][0], bigcvt[index_ul][0][1]), 1, (0,0,255), 2) #img = cv2.circle(input_img, (bigcvt[index_ll][0][0], bigcvt[index_ll][0][1]), 1, (0,0,255), 2) #img = cv2.circle(input_img, (bigcvt[index_ur][0][0], bigcvt[index_ur][0][1]), 1, (0,0,255), 2) #img = cv2.drawContours(input_img, bigcvt, -1, (0,255,0), 3) width,height = 500,500 pts1 = np.float32([[586,45],[788,163],[411,348],[615,464]]) pts1 = np.float32([bigcvt[index_ul], bigcvt[index_ur], bigcvt[index_ll], bigcvt[index_lr]]) pts2 = np.float32([[0,0],[width,0],[0,height],[width,height]]) matrix = cv2.getPerspectiveTransform(pts1,pts2) imgOutput = cv2.warpPerspective(input_img,matrix,(width,height)) #cv2.imshow("warp", imgOutput) #cv2.waitKey(0) warped_img = imgOutput ################################################## return warped_img def detectMaze(warped_img): """ Purpose: --- takes the warped maze image as input and returns the maze encoded in form of a 2D array Input Arguments: --- `warped_img` : [ numpy array ] resultant warped maze image after applying Perspective Transform Returns: --- `maze_array` : [ nested list of lists ] encoded maze in the form of a 2D array Example call: --- maze_array = detectMaze(warped_img) """ maze_array = [] ############## ADD YOUR CODE HERE ############## for j in range(10): row_list = [] for i in range(10): num = 0 roi = warped_img[j*50:(j+1)*50, i*50:(i+1)*50] roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY) ret,mask = cv2.threshold(roi,100,255,cv2.THRESH_BINARY) if mask[1, 24] == 0: num = num + 2 if mask[24, 1] == 0: num = num + 1 if mask[24, 48] == 0: num = num + 4 if mask[48, 24] == 0: num = num + 8 row_list.append(num) #cv2.imshow("mask", mask) #cv2.waitKey(0) maze_array.append(row_list) ################################################## return maze_array # NOTE: YOU ARE NOT ALLOWED TO MAKE ANY CHANGE TO THIS FUNCTION def writeToCsv(csv_file_path, maze_array): """ Purpose: --- takes the encoded maze array and csv file name as input and writes the encoded maze array to the csv file Input Arguments: --- `csv_file_path` : [ str ] file path with name for csv file to write `maze_array` : [ nested list of lists ] encoded maze in the form of a 2D array Example call: --- warped_img = writeToCsv('test_cases/maze00.csv', maze_array) """ with open(csv_file_path, 'w', newline='') as file: writer = csv.writer(file) writer.writerows(maze_array) # NOTE: YOU ARE NOT ALLOWED TO MAKE ANY CHANGE TO THIS FUNCTION # # Function Name: main # Inputs: None # Outputs: None # Purpose: This part of the code is only for testing your solution. The function first takes 'maze00.jpg' # as input, applies Perspective Transform by calling applyPerspectiveTransform function, # encodes the maze input in form of 2D array by calling detectMaze function and writes this data to csv file # by calling writeToCsv function, it then asks the user whether to repeat the same on all maze images # present in 'test_cases' folder or not. Write your solution ONLY in the space provided in the above # applyPerspectiveTransform and detectMaze functions. if __name__ == "__main__": # path directory of images in 'test_cases' folder img_dir_path = 'test_cases/' # path to 'maze00.jpg' image file file_num = 0 img_file_path = img_dir_path + 'maze0' + str(file_num) + '.jpg' print('\n============================================') print('\nFor maze0' + str(file_num) + '.jpg') # path for 'maze00.csv' output file csv_file_path = img_dir_path + 'maze0' + str(file_num) + '.csv' # read the 'maze00.jpg' image file input_img = cv2.imread(img_file_path) # get the resultant warped maze image after applying Perspective Transform warped_img = applyPerspectiveTransform(input_img) if type(warped_img) is np.ndarray: # get the encoded maze in the form of a 2D array maze_array = detectMaze(warped_img) if (type(maze_array) is list) and (len(maze_array) == 10): print('\nEncoded Maze Array = %s' % (maze_array)) print('\n============================================') # writes the encoded maze array to the csv file writeToCsv(csv_file_path, maze_array) cv2.imshow('warped_img_0' + str(file_num), warped_img) cv2.waitKey(0) cv2.destroyAllWindows() else: print('\n[ERROR] maze_array returned by detectMaze function is not complete. Check the function in code.\n') exit() else: print('\n[ERROR] applyPerspectiveTransform function is not returning the warped maze image in expected format! Check the function in code.\n') exit() choice = input('\nDo you want to run your script on all maze images ? => "y" or "n": ') if choice == 'y': for file_num in range(1, 10): # path to image file img_file_path = img_dir_path + 'maze0' + str(file_num) + '.jpg' print('\n============================================') print('\nFor maze0' + str(file_num) + '.jpg') # path for csv output file csv_file_path = img_dir_path + 'maze0' + str(file_num) + '.csv' # read the image file input_img = cv2.imread(img_file_path) # get the resultant warped maze image after applying Perspective Transform warped_img = applyPerspectiveTransform(input_img) if type(warped_img) is np.ndarray: # get the encoded maze in the form of a 2D array maze_array = detectMaze(warped_img) if (type(maze_array) is list) and (len(maze_array) == 10): print('\nEncoded Maze Array = %s' % (maze_array)) print('\n============================================') # writes the encoded maze array to the csv file writeToCsv(csv_file_path, maze_array) cv2.imshow('warped_img_0' + str(file_num), warped_img) cv2.waitKey(0) cv2.destroyAllWindows() else: print('\n[ERROR] maze_array returned by detectMaze function is not complete. Check the function in code.\n') exit() else: print('\n[ERROR] applyPerspectiveTransform function is not returning the warped maze image in expected format! Check the function in code.\n') exit() else: print('')
[ "cv2.getPerspectiveTransform", "cv2.threshold", "csv.writer", "cv2.contourArea", "cv2.warpPerspective", "cv2.waitKey", "cv2.destroyAllWindows", "cv2.cvtColor", "cv2.findContours", "cv2.imread", "numpy.float32" ]
[((2499, 2542), 'cv2.cvtColor', 'cv2.cvtColor', (['input_img', 'cv2.COLOR_BGR2GRAY'], {}), '(input_img, cv2.COLOR_BGR2GRAY)\n', (2511, 2542), False, 'import cv2\n'), ((2559, 2610), 'cv2.threshold', 'cv2.threshold', (['bgr_img', '(100)', '(255)', 'cv2.THRESH_BINARY'], {}), '(bgr_img, 100, 255, cv2.THRESH_BINARY)\n', (2572, 2610), False, 'import cv2\n'), ((2756, 2818), 'cv2.findContours', 'cv2.findContours', (['mask', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (2772, 2818), False, 'import cv2\n'), ((4636, 4695), 'numpy.float32', 'np.float32', (['[[586, 45], [788, 163], [411, 348], [615, 464]]'], {}), '([[586, 45], [788, 163], [411, 348], [615, 464]])\n', (4646, 4695), True, 'import numpy as np\n'), ((4701, 4790), 'numpy.float32', 'np.float32', (['[bigcvt[index_ul], bigcvt[index_ur], bigcvt[index_ll], bigcvt[index_lr]]'], {}), '([bigcvt[index_ul], bigcvt[index_ur], bigcvt[index_ll], bigcvt[\n index_lr]])\n', (4711, 4790), True, 'import numpy as np\n'), ((4798, 4860), 'numpy.float32', 'np.float32', (['[[0, 0], [width, 0], [0, height], [width, height]]'], {}), '([[0, 0], [width, 0], [0, height], [width, height]])\n', (4808, 4860), True, 'import numpy as np\n'), ((4868, 4907), 'cv2.getPerspectiveTransform', 'cv2.getPerspectiveTransform', (['pts1', 'pts2'], {}), '(pts1, pts2)\n', (4895, 4907), False, 'import cv2\n'), ((4924, 4979), 'cv2.warpPerspective', 'cv2.warpPerspective', (['input_img', 'matrix', '(width, height)'], {}), '(input_img, matrix, (width, height))\n', (4943, 4979), False, 'import cv2\n'), ((8347, 8372), 'cv2.imread', 'cv2.imread', (['img_file_path'], {}), '(img_file_path)\n', (8357, 8372), False, 'import cv2\n'), ((3005, 3025), 'cv2.contourArea', 'cv2.contourArea', (['cvt'], {}), '(cvt)\n', (3020, 3025), False, 'import cv2\n'), ((3102, 3122), 'cv2.contourArea', 'cv2.contourArea', (['cvt'], {}), '(cvt)\n', (3117, 3122), False, 'import cv2\n'), ((7041, 7057), 'csv.writer', 'csv.writer', (['file'], {}), '(file)\n', (7051, 7057), False, 'import csv\n'), ((5848, 5885), 'cv2.cvtColor', 'cv2.cvtColor', (['roi', 'cv2.COLOR_BGR2GRAY'], {}), '(roi, cv2.COLOR_BGR2GRAY)\n', (5860, 5885), False, 'import cv2\n'), ((5910, 5957), 'cv2.threshold', 'cv2.threshold', (['roi', '(100)', '(255)', 'cv2.THRESH_BINARY'], {}), '(roi, 100, 255, cv2.THRESH_BINARY)\n', (5923, 5957), False, 'import cv2\n'), ((8980, 8994), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (8991, 8994), False, 'import cv2\n'), ((8999, 9022), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (9020, 9022), False, 'import cv2\n'), ((9839, 9864), 'cv2.imread', 'cv2.imread', (['img_file_path'], {}), '(img_file_path)\n', (9849, 9864), False, 'import cv2\n'), ((10526, 10540), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (10537, 10540), False, 'import cv2\n'), ((10547, 10570), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (10568, 10570), False, 'import cv2\n')]
#pip install matplotlib | pip install numpy | Gera Grafico de Pizza import matplotlib.pyplot as plt import numpy as np y = np.array([35,25,25,15]) #Valores mylabels = ["Maça","Banana","Laranja","Melancia"] #Itens myexplode = [0.2,0,0,0] #Margim plt.pie(y, labels = mylabels, explode = myexplode, shadow = True) plt.show()
[ "numpy.array", "matplotlib.pyplot.pie", "matplotlib.pyplot.show" ]
[((130, 156), 'numpy.array', 'np.array', (['[35, 25, 25, 15]'], {}), '([35, 25, 25, 15])\n', (138, 156), True, 'import numpy as np\n'), ((257, 316), 'matplotlib.pyplot.pie', 'plt.pie', (['y'], {'labels': 'mylabels', 'explode': 'myexplode', 'shadow': '(True)'}), '(y, labels=mylabels, explode=myexplode, shadow=True)\n', (264, 316), True, 'import matplotlib.pyplot as plt\n'), ((324, 334), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (332, 334), True, 'import matplotlib.pyplot as plt\n')]
import io import pytest import numpy from unittest import mock from gym.spaces import Box def test_attributes(basic_env): assert basic_env.action_space.n == 2 ** 2 assert basic_env.observation_space == Box(low=1., high=float('Inf'), shape=(1, 2)) assert basic_env.starting_bank == 10 assert basic_env.balance == basic_env.starting_bank assert basic_env.current_step == 0 assert numpy.array_equal(basic_env.bet_size_matrix, numpy.ones(shape=(1, 2))) @pytest.mark.parametrize("action,expected_reward", [numpy.array((0, 0)), numpy.array((1, 1)), numpy.array((2, -1)), numpy.array((3, 0))]) def test_step(basic_env, action, expected_reward): odds, reward, done, _ = basic_env.step(action) assert reward == expected_reward assert not done assert basic_env.current_step == 1 def test_reset(basic_env): odds, reward, done, info = basic_env.step(1) assert reward == 1 assert basic_env.balance == basic_env.starting_bank + 1 assert not done assert basic_env.current_step == 1 assert info['legal_bet'] assert info['results'] == 1 assert info['reward'] == 1 assert not info['done'] odds, reward, done, _ = basic_env.step(2) assert reward == 2 assert done basic_env.reset() assert basic_env.balance == basic_env.starting_bank def test_info(basic_env): info = basic_env.create_info(1) assert info['current_step'] == 0 numpy.testing.assert_array_equal(info['odds'], numpy.array([[1, 2]])) assert info['verbose_action'] == [['l']] assert info['action'] == 1 assert info['balance'] == 10 assert info['reward'] == 0 assert not info['legal_bet'] assert info['results'] is None assert not info['done'] basic_env.pretty_print_info(info) def test_render(basic_env): with mock.patch('sys.stdout', new=io.StringIO()) as fake_stdout: basic_env.render() assert fake_stdout.getvalue() == 'Current balance at step 0: 10\n' @pytest.mark.parametrize("action", range(4)) def test_step_when_balance_is_0(basic_env, action): basic_env.balance = 0 odds, reward, done, _ = basic_env.step(action) assert reward == 0 assert done assert basic_env.current_step == 0 def test_step_illegal_action(basic_env): basic_env.balance = 1 odds, reward, done, _ = basic_env.step(3) # illegal - making a double when when the balance is 1 assert reward == -2 assert not done assert basic_env.current_step == 1 @pytest.mark.parametrize("current_step,expected_results", [(0, numpy.array([[0, 1]], dtype=numpy.float64)), (1, numpy.array([[1, 0]], dtype=numpy.float64))]) def test_get_results(basic_env, current_step, expected_results): basic_env.current_step = current_step results = basic_env.get_results() assert numpy.array_equal(results, expected_results)
[ "numpy.array", "io.StringIO", "numpy.array_equal", "numpy.ones" ]
[((3002, 3046), 'numpy.array_equal', 'numpy.array_equal', (['results', 'expected_results'], {}), '(results, expected_results)\n', (3019, 3046), False, 'import numpy\n'), ((450, 474), 'numpy.ones', 'numpy.ones', ([], {'shape': '(1, 2)'}), '(shape=(1, 2))\n', (460, 474), False, 'import numpy\n'), ((530, 549), 'numpy.array', 'numpy.array', (['(0, 0)'], {}), '((0, 0))\n', (541, 549), False, 'import numpy\n'), ((603, 622), 'numpy.array', 'numpy.array', (['(1, 1)'], {}), '((1, 1))\n', (614, 622), False, 'import numpy\n'), ((676, 696), 'numpy.array', 'numpy.array', (['(2, -1)'], {}), '((2, -1))\n', (687, 696), False, 'import numpy\n'), ((750, 769), 'numpy.array', 'numpy.array', (['(3, 0)'], {}), '((3, 0))\n', (761, 769), False, 'import numpy\n'), ((1625, 1646), 'numpy.array', 'numpy.array', (['[[1, 2]]'], {}), '([[1, 2]])\n', (1636, 1646), False, 'import numpy\n'), ((2692, 2734), 'numpy.array', 'numpy.array', (['[[0, 1]]'], {'dtype': 'numpy.float64'}), '([[0, 1]], dtype=numpy.float64)\n', (2703, 2734), False, 'import numpy\n'), ((2800, 2842), 'numpy.array', 'numpy.array', (['[[1, 0]]'], {'dtype': 'numpy.float64'}), '([[1, 0]], dtype=numpy.float64)\n', (2811, 2842), False, 'import numpy\n'), ((1990, 2003), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (2001, 2003), False, 'import io\n')]
import warnings import itertools import torch import math import networkx as nx import numpy as np import pandas as pd import matplotlib.pyplot as plt # Set Torch tensor type default for consistency torch.set_default_tensor_type(torch.DoubleTensor) class CausalModel(object): """A class for building and handling Structural Causal Models. An SCM contains: - A graph G, made of a NetworkX DiGraph - Endogenous nodes X1, ..., Xn -- representing observable variables - Exogenous nodes U1, ..., Un -- one for each endogenous node - Functions f1, ..., fn -- that set Xi = fi(PAi, Ui) where PAi are the endogenous parents of Xi Has the ability to handle and operate on Twin Networks. Example: ``` scm = CausalModel() scm.create(method="backward", n_nodes=5, max_parents=5) scm.create_twin_network() scm.do({"N3tn": 1}) ``` """ def __init__(self, continuous=False, noise_coeff=1.): """Initialize a CausalModel instance. Args: continuous (bool): whether or not the graph is continuous or binary-valued. (Different inference schemes) noise_coeff (int/float): hyperparameter that scales the variance of noise. """ self.twin_exists = False self.merged = False self.functions_assigned = False self.G = None self.G_original = None # store an extra version of the original graph for resetting. self.continuous = continuous self.num_hidden = 20 # default number of hidden nodes per layer if using a neural network for functions. if noise_coeff < 0: self.noise_coeff = 1. warnings.warn("Noise coefficient was negative. Defaulting to 1.") else: self.noise_coeff = noise_coeff def create(self, method, n_nodes, **kwargs): """Creates a new random DAG according to the desired method. Use **kwargs to supply appropriate parameters to chosen `method`. Args: method: one of 'backward' (parameter: 'max_parents'), 'density' (parameter: 'prob'), or 'MCMC' (no params) n_nodes: number of nodes desired in the graph. """ assert method in ('backward', 'density', 'MCMC'), "method not in ('backward', 'density', 'MCMC')" if method == "backward": self.G = self.generate_DAG_backward(n_nodes, **kwargs) elif method == "density": self.G = self.generate_DAG_density(n_nodes, **kwargs) elif method == "MCMC": self.G = self.MCMC_generate_DAG(n_nodes, **kwargs) self._make_valid_graph() def generate_DAG_backward(self, n_nodes, max_parents): """ Args: n_nodes: number of nodes desired in the graph. max_parents: the maximum number of parents per node in the graph. Returns: networkx.DiGraph: a networkx directed, acyclic graph (DAG). """ nodes = ["N" + str(n) for n in range(n_nodes)] graph = nx.DiGraph() graph.add_nodes_from(nodes) for i, node in enumerate(nodes[1:], start=1): nb_parents = np.random.randint(0, min([max_parents, i]) + 1) print(node, i, nb_parents) parent_nodes = [nodes[j] for j in np.random.choice(range(0, i), nb_parents, replace=False)] edges = [(pa, node) for pa in parent_nodes] graph.add_edges_from(edges) return graph def generate_DAG_density(self, n_nodes, prob): """Creates a graph from the RandomDAG algorithm given some neighbourhood connection probability. (Source: https://rdrr.io/cran/pcalg/man/randomDAG.html) Args: n_nodes (int): number of nodes in graph. prob (float): probability of downstream connections. """ assert abs(prob) <= 1, "`prob` has to be in [0, 1]." nodes = ["N" + str(n) for n in range(n_nodes)] graph = nx.DiGraph() graph.add_nodes_from(nodes) for i, node in enumerate(nodes): remaining_nodes = nodes[i + 1:] k = len(remaining_nodes) n_neighbours = np.random.binomial(k, prob) neighbours = np.random.choice(remaining_nodes, size=n_neighbours, replace=False) graph.add_edges_from([(node, n) for n in neighbours]) return graph def MCMC_generate_DAG(self, n_nodes, **kwargs): """Creates a DAG by randomly adding or removing edges. Args: n_nodes: **kwargs: Returns: """ nodes = ["N" + str(n) for n in range(n_nodes)] all_poss_edges = [] for edge in itertools.permutations(nodes, 2): all_poss_edges.append(edge) graph = nx.DiGraph() graph.add_nodes_from(nodes) loops = 5000 for i in range(loops): idx_sample = np.random.randint(low=0, high=len(all_poss_edges)) edge_chosen = all_poss_edges[idx_sample] if edge_chosen in list(graph.edges): graph.remove_edge(*edge_chosen) else: graph.add_edge(*edge_chosen) if not nx.is_directed_acyclic_graph(graph): graph.remove_edge(*edge_chosen) else: pass return graph def create_from_DAG(self, G): """Create from an already existing DAG encoded as NetworkX graph. Args: G (nx graph): a networkx DAG. """ assert nx.is_directed_acyclic_graph(G), "Graph is not a directed acyclic graph." self.G = G self._make_valid_graph() def _make_valid_graph(self): """Calls a sequence of functions that endows a NetworkX DAG with properties useful for a Structural Causal Model: 1. Labels current nodes as endogenous 2. Gives each endogenous variable an exogenous (noise) variable. 3. Resets nodes to be unintervened with a null value. 4. Gives all nodes their generating function. 5. Store a copy of the graph for future reference. 6. Labels the graph as a non-twin graph. 7. Stores the original node order. """ self._label_all_endogenous() self._add_noise_terms() self._label_all_nonintervened() self._label_all_valueless() self.ordering = sorted(self._get_exog_nodes(), key=lambda x: int(x[2:])) + self._get_endog_nodes() self._generate_all_functions() self.G_original = self.G.copy() self.G.is_twin = False def _label_all_endogenous(self): """Labels all nodes in the graph as endogenous.""" for node in self.G.nodes: self.G.nodes[node]["endog"] = True def _label_all_nonintervened(self): """Labels all nodes in the graph as non-intervened.""" for node in self.G.nodes: self.G.nodes[node]['intervened'] = False def _add_noise_terms(self): """Assign each endogenous variable an exogenous noise parent.""" for node in list(self.G.nodes): noise_name = "U{}".format(str(node)) self.G.add_node(noise_name) self.G.add_edge(noise_name, node) self.G.nodes[noise_name]["endog"] = False def _label_all_valueless(self): """Labels all nodes in the graph as without a value.""" for node in self.G.nodes: self.G.nodes[node]['value'] = None def _create_twin_nodes(self): """Create the non-noise counterpart nodes in the Twin Network. This copies all attribute values -- i.e. endogeneity and functional form -- over to the new network. """ endog_nodes = [n for n in list(self.G.nodes.data()) if n[0] in self._get_endog_nodes()] endog_nodes = [(self._add_tn(n), d) for n, d in endog_nodes] self.twin_G.add_nodes_from(endog_nodes) def _create_twin_edges(self): """Creates the counterpart exogeneous and endogenous edges in the Twin Network. """ shared_exog_edges = [(e[0], self._add_tn(e[1])) for e in self._get_exog_edges()] # create the non-noise counterpart edges in the Twin network endog_edges = [(self._add_tn(e[0]), self._add_tn(e[1])) for e in self._get_endog_edges()] self.twin_G.add_edges_from(endog_edges) self.twin_G.add_edges_from(shared_exog_edges) def create_twin_network(self): """Create a twin network by mirroring the original network, only sharing the noise terms. """ assert self.functions_assigned, "Assign functions before creating TN." if not self.twin_exists: self.twin_G = self.G.copy() self._create_twin_nodes() self._create_twin_edges() self.twin_exists = True self.twin_G.is_twin = True def merge_in_twin(self, node_of_interest, intervention): """Merge nodes in the Twin Counterfactual network. In place creates & modifies `self.twin_G`. """ # find every non-descendant of the intervention nodes if not self.merged: nondescendant_sets = [] all_nodes = set([i for i in list(self.G.nodes) if i[0] != 'U']) for node in intervention: nondescendant_sets.append(all_nodes.difference(set(nx.descendants(self.G, node)))) dont_merge = [node_of_interest] + list(intervention.keys()) shared_nondescendants = set.intersection(*nondescendant_sets) - set(dont_merge) # now modify twin network to replace all _tn variables with their regular counterpart ordered_nondescendants = [n for n in nx.topological_sort(self.G) if n in list(shared_nondescendants)] for node in ordered_nondescendants: # start with the oldest nodes twin_node = node + "tn" tn_children = self.twin_G.successors(twin_node) # TODO: This changes the ordering of nodes going into a node. This is currently fixed by a cheap hack # TODO: which sorts edges alphabetically by when called. This should be fixed. self.twin_G.add_edges_from([(node, c) for c in tn_children]) self.twin_G.remove_node(twin_node) print("Merging removed {} nodes.".format(len(ordered_nondescendants))) self.merged = True def draw(self, twin=False): """Draws/plots the network. Args: twin (bool): if true, plots the Twin Network. """ G = self.twin_G if twin else self.G pos = nx.spring_layout(G) # get layout positions for all nodes endog_nodes = self._get_endog_nodes(twin) exog_nodes = self._get_exog_nodes(twin) # draw nodes nx.draw_networkx_nodes(G, pos, nodelist=exog_nodes, node_color='r', node_size=500, alpha=0.4, label=exog_nodes) nx.draw_networkx_nodes(G, pos, nodelist=endog_nodes, node_color='b', node_size=800, alpha=0.8) # draw edges nx.draw_networkx_edges(G, pos, width=1.0, alpha=0.5, arrowsize=20, with_labels=True) # draw labels nx.draw_networkx_labels(G, pos, font_size=16, font_color='white') plt.show() def _add_tn(self, node_name): """Helper function to modify the name of a node to its Twin Network version. Args: node_name (str): the name of the node. """ return "{}tn".format(node_name) def _is_exog(self, node, g=None): """Checks if `node` is endogenous in graph `g`. Args: node (str): the name of the node g (nx.DiGraph): the graph """ g = self.G if g is None else g return len(list(g.predecessors(node))) == 0 and not g.nodes[node]['endog'] def _get_endog_nodes(self, twin=False): """Returns a list of the ids of endogenous nodes. Args: twin (bool): if True, use twin graph. """ g = self.twin_G if self.twin_exists & twin else self.G return [node for node in nx.topological_sort(g) if not self._is_exog(node, g)] def _get_endog_edges(self): """Returns a list of the edges involving endogenous nodes.""" return [e for e in filter(lambda x: self.G.nodes[x[0]]["endog"], self.G.edges)] def _get_exog_nodes(self, twin=False): """Returns a list of the ids of exogenous nodes. Args: twin (bool): if True, use twin graph. """ g = self.twin_G if self.twin_exists & twin else self.G return [node for node in g.nodes if self._is_exog(node, g)] def _get_exog_edges(self): """Returns a list of edges involving exogenous nodes.""" return [e for e in filter(lambda x: not self.G.nodes[x[0]]["endog"], self.G.edges)] def _get_twin_nodes(self): """Returns an ordered set of twin nodes.""" if not self.twin_exists: raise ValueError("Twin Network not yet created. Create one using .create_twin_network() first.") else: return [node for node in nx.topological_sort(self.twin_G) if "tn" in node] def _get_non_twin_endog_nodes(self): """Get endogenous nodes that are not twin nodes.""" return [n for n in self._get_endog_nodes() if n[-2:] != "tn"] def _weave_sort_endog(self, evidence={}): """Weaves twin and non-twin nodes together ensuring primacy of observed nodes for inference. Args: evidence (dict): a dictionary of observed values formatted as {node_name: val} """ twin_nodes = self._get_twin_nodes() non_twin = self._get_non_twin_endog_nodes() ordering = [] for (nt, tw) in zip(non_twin, twin_nodes): if tw in evidence and nt not in evidence: ordering += [tw, nt] else: ordering += [nt, tw] return ordering def get_endog_order(self, evidence={}, twin=False): """Returns the order of endogenous nodes for probabilistic model creation in inference. Args: evidence (dict): a dictionary of observed values formatted as {node_name: val} """ if twin: return self._weave_sort_endog(evidence) else: return self._get_endog_nodes() def _do_surgery(self, nodes): """ Performs the do-operator graph surgery by removing all edges into each node in `nodes`. Args: nodes (nx node or list): a node, or a list of nodes, to perform the surgery on. """ nodes = [nodes] if not isinstance(nodes, list) else nodes for node in nodes: parent_edges = [(pa, node) for pa in sorted(list(self.G.predecessors(node)))] self.G.remove_edges_from(parent_edges) def do(self, interventions): """ Performs the intervention specified by the dictionary `interventions`. Args: interventions (dict): a dictionary of interventions of form {node_name: value} """ nodes_to_intervene = list(interventions.keys()) self._do_surgery(nodes_to_intervene) for node in nodes_to_intervene: self.G.nodes[node]['value'] = interventions[node] self.G.nodes[node]['intervened'] = True def _get_node_exog_parent(self, node): """ Returns the name of the node's exogenous variable. Args: node (str): the name of the node. """ parents = [p for p in sorted(list(self.G.predecessors(node))) if self.G.nodes[p]['endog'] == False] assert len(parents) == 1, "More than one latent variable for node {node}. Should be an error; fix." return parents[0] def _generate_fn(self, node): """ Generates a function for a given node. If not self.continuous: For endogenous nodes, the model is a logistic regression with parameters drawn from a standard normal. For exogenous nodes, the model is just the standard normal. else: Generates a 2 layer, tanh-activated neural network with `self.num_hidden` hidden layer nodes. Args: `node` (nx node): the index of the node to give a function """ if self._is_exog(node, self.G): if self.continuous: self.G.nodes[node]['mu'] = np.random.normal(0, 0.3) self.G.nodes[node]['std'] = np.random.gamma(1, 0.4) else: self.G.nodes[node]['p'] = np.random.uniform(0.3, 0.7) else: n_parents = len([i for i in self.G.predecessors(node)]) if self.continuous: if n_parents == 1: self.G.nodes[node]['fn'] = lambda x: x else: self.G.nodes[node]['fn'] = self._nn_function(n_parents) # self._nn_function(n_parents else: theta = np.random.beta(5, 5, size=n_parents - 1) # risk factors are positive & similar, thus beta. theta = theta / np.sum(theta) self.G.nodes[node]['parameters'] = theta def _nn_function(self, n_parents): """A helper function that generates a torch neural network model. Args: n_parents (int): the number of parents of a node. Returns: torch.nn.Sequential: the neural network. """ layers = [] num_hidden = self.num_hidden layers.append(torch.nn.modules.Linear(n_parents - 1, num_hidden)) layers.append(torch.nn.Tanh()) layers.append(torch.nn.modules.Linear(num_hidden, 1)) for l in layers: try: l.weight = torch.nn.Parameter(torch.randn(l.weight.shape, requires_grad=False)) except: pass for p in l.parameters(): p.requires_grad = False return torch.nn.Sequential(*layers) def _polynomial_function(self, n_parents, node): """Generates arbitrary polynomials of the form $\Sigma b_{n}x_{n}^c_{n}$ Args: n_parents (int): the number of parents of a node. node (str): the node in question. """ self.G.nodes[node]['betas'] = np.random.normal(size=n_parents - 1) self.G.nodes[node]['coefs'] = np.random.choice([1, 2, 4], size=n_parents-1, replace=True) return lambda x: (np.sum((self.G.nodes[node]['betas']*x) ** self.G.nodes[node]['coefs'], axis=1)\ - self.G.nodes[node]['mu_norm']) / self.G.nodes[node]['std_norm'] def _calibrate_functions(self): """Calibrates the normalizers for use with the polynomial functional form.""" for node in self._get_endog_nodes(): samples = self.sample(200, return_pandas=True) self.G.nodes[node]['mu_norm'] = samples[node].mean() self.G.nodes[node]['std_norm'] = samples[node].std() def _generate_all_functions(self): """Gives all nodes a function.""" for node in self.G.nodes: self.G.nodes[node]['mu_norm'] = np.array([0.]) self.G.nodes[node]['std_norm'] = np.array([1.]) self._generate_fn(node) self._calibrate_functions() self.functions_assigned = True def _sample_node(self, node, n_samples=1, graph=None): """Sample a value for the node. Args: node (str): the node to sample. n_samples (int): the number of samples to take. graph (nx.DiGraph): the graph to operate on (optional) """ graph = self.G if graph is None else graph if graph.nodes[node]['intervened']: pass else: if self._is_exog(node, graph): # if exogenous node if self.continuous: mu = graph.nodes[node]['mu'] std = graph.nodes[node]['std'] graph.nodes[node]['value'] = self.noise_coeff * np.random.normal(mu, std, size=n_samples) else: p = graph.nodes[node]['p'] graph.nodes[node]['value'] = np.random.binomial(1, p, size=n_samples) else: # if an endogenous node parents = sorted(list(graph.predecessors(node))) endog_parents = [graph.nodes[n]['value'] for n in parents if n[0] != "U"] exog_parent = [graph.nodes[n]['value'] for n in parents if n[0] == "U"][0] if not endog_parents: graph.nodes[node]['value'] = exog_parent # take value from exogenous parent else: fn = self._continuous_fn if self.continuous else self._binary_fn val = fn(node, endog_parents, exog_parent, graph) graph.nodes[node]['value'] = val return graph.nodes[node]['value'] def _continuous_fn(self, node, parent_values, exog_value, graph=None): """A helper function that generates values for endogenous `node` given `parent_values` in the continuous case. Args: node (str): the node of interest. parent_values (list): the list of numpy arrays of parent values. graph (nx.DiGraph): the graph to operate on (optional) """ if graph is None: graph = self.G X = np.hstack([pa.astype('float64').reshape(-1, 1) for pa in parent_values]) X = torch.from_numpy(X) X_fn = graph.nodes[node]['fn'] pred = X_fn(X).flatten().numpy() return pred + exog_value # this is the additive noise function def _binary_fn(self, node, parent_values, exog_value, graph=None): """A helper function that generates values for endogenous `node` given `parent_values` in the binary case. Args: node (str): the node of interest. parent_values (list): the list of numpy arrays of parent values. graph (nx.DiGraph): the graph to operate on (optional) """ if graph is None: graph = self.G thetas = graph.nodes[node]['parameters'] v = np.dot(thetas, parent_values) if not isinstance(v, np.ndarray): v = 1. if v > 0.5 else 0. else: v = (v > 0.5).astype(np.float64) if not isinstance(v, np.ndarray): return v if not exog_value else 1. - v else: v[exog_value == 1] = 1 - v[exog_value == 1] return v def reset_graph(self): """Reset the graph to its original and destroy its twin companion.""" self.G = self.G_original.copy() self.twin_G = None self.twin_exists = False def sample(self, n_samples=1, return_pandas=False, twin=False, evidence={}): """Sample from the full model. Args: n_samples (int): the number of samples to take. return_pandas (bool): whether to return a Pandas DF or not. twin (bool): whether to operate on the twin network graph. evidence (dict): a dictionary of observed values formatted as {node_name: val} Returns: samples: either a pandas dataframe or numpy array of samples. """ graph = self.twin_G if (twin and self.twin_exists) else self.G if twin: ordering = self._get_exog_nodes() + self._weave_sort_endog(evidence) else: ordering = self.ordering for node in ordering: self._sample_node(node=node, n_samples=n_samples, graph=graph) samples = self._collect_samples(graph, ordering) if return_pandas: return pd.DataFrame(samples, columns=ordering) else: return samples def sample_observable_dict(self, n_samples, n_vars=None): """Return a dictionary of samples of (potentially partial) endogenous variables. Useful for generating arbitrary evidence sets for testing inference. Args: n_samples (int): the number of samples. n_vars (int): the number of randomly-chosen variables. If unset, it defaults to all endogenous vars. Returns: """ d = self.sample(n_samples, return_pandas=True) d = d[self._get_exog_nodes()].to_dict("series") d = {k: torch.from_numpy(np.array(d[k], dtype=np.float64)) for k in d.keys()} if isinstance(n_vars, int): random_keys = np.random.choice(list(d.keys()), size=n_vars, replace=False) return {k: d[k] for k in d if k in random_keys} else: return d def _collect_samples(self, graph=None, ordering=None): """A helper function for ordering and stacking samples. Args: graph (nx.DiGraph): the graph to operate on. ordering: Returns: np.ndarray: an array of samples in the coorrect order. """ ordering = self.ordering if ordering is None else ordering graph = self.G if graph is None else graph return np.vstack([graph.nodes[n]['value'] for n in ordering]).T def _sigmoid(self, x): """The sigmoid helper function. Args: x (numeric/array/etc.): input to sigmoid function. """ return 1 / (1 + np.exp(-x)) def middle_node(self, node_of_interest): """Finds the node closest to the middle of the topological order that is an ancestor of `node_of_interest`. Useful for generating a node to intervene on for experimenting. Args: node_of_interest: the node of interest (i.e. the counterfactual outcome node) """ endog_nodes = self._get_endog_nodes() limit = endog_nodes.index(node_of_interest) endog_nodes = endog_nodes[:limit] n = len(endog_nodes) ancestors = [a for a in nx.ancestors(self.G, node_of_interest) if a[0] != "U"] idx = np.argmin([abs(endog_nodes.index(a) - math.floor(n/2)) for a in ancestors]) return ancestors[idx]
[ "torch.nn.Tanh", "math.floor", "torch.nn.Sequential", "torch.from_numpy", "networkx.draw_networkx_nodes", "numpy.array", "networkx.is_directed_acyclic_graph", "networkx.draw_networkx_labels", "numpy.random.binomial", "networkx.DiGraph", "networkx.spring_layout", "torch.set_default_tensor_type"...
[((200, 249), 'torch.set_default_tensor_type', 'torch.set_default_tensor_type', (['torch.DoubleTensor'], {}), '(torch.DoubleTensor)\n', (229, 249), False, 'import torch\n'), ((3055, 3067), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (3065, 3067), True, 'import networkx as nx\n'), ((3989, 4001), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (3999, 4001), True, 'import networkx as nx\n'), ((4798, 4830), 'itertools.permutations', 'itertools.permutations', (['nodes', '(2)'], {}), '(nodes, 2)\n', (4820, 4830), False, 'import itertools\n'), ((4889, 4901), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (4899, 4901), True, 'import networkx as nx\n'), ((5655, 5686), 'networkx.is_directed_acyclic_graph', 'nx.is_directed_acyclic_graph', (['G'], {}), '(G)\n', (5683, 5686), True, 'import networkx as nx\n'), ((10859, 10878), 'networkx.spring_layout', 'nx.spring_layout', (['G'], {}), '(G)\n', (10875, 10878), True, 'import networkx as nx\n'), ((11045, 11160), 'networkx.draw_networkx_nodes', 'nx.draw_networkx_nodes', (['G', 'pos'], {'nodelist': 'exog_nodes', 'node_color': '"""r"""', 'node_size': '(500)', 'alpha': '(0.4)', 'label': 'exog_nodes'}), "(G, pos, nodelist=exog_nodes, node_color='r',\n node_size=500, alpha=0.4, label=exog_nodes)\n", (11067, 11160), True, 'import networkx as nx\n'), ((11352, 11450), 'networkx.draw_networkx_nodes', 'nx.draw_networkx_nodes', (['G', 'pos'], {'nodelist': 'endog_nodes', 'node_color': '"""b"""', 'node_size': '(800)', 'alpha': '(0.8)'}), "(G, pos, nodelist=endog_nodes, node_color='b',\n node_size=800, alpha=0.8)\n", (11374, 11450), True, 'import networkx as nx\n'), ((11632, 11720), 'networkx.draw_networkx_edges', 'nx.draw_networkx_edges', (['G', 'pos'], {'width': '(1.0)', 'alpha': '(0.5)', 'arrowsize': '(20)', 'with_labels': '(True)'}), '(G, pos, width=1.0, alpha=0.5, arrowsize=20,\n with_labels=True)\n', (11654, 11720), True, 'import networkx as nx\n'), ((11903, 11968), 'networkx.draw_networkx_labels', 'nx.draw_networkx_labels', (['G', 'pos'], {'font_size': '(16)', 'font_color': '"""white"""'}), "(G, pos, font_size=16, font_color='white')\n", (11926, 11968), True, 'import networkx as nx\n'), ((12074, 12084), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (12082, 12084), True, 'import matplotlib.pyplot as plt\n'), ((19044, 19072), 'torch.nn.Sequential', 'torch.nn.Sequential', (['*layers'], {}), '(*layers)\n', (19063, 19072), False, 'import torch\n'), ((19389, 19425), 'numpy.random.normal', 'np.random.normal', ([], {'size': '(n_parents - 1)'}), '(size=n_parents - 1)\n', (19405, 19425), True, 'import numpy as np\n'), ((19464, 19525), 'numpy.random.choice', 'np.random.choice', (['[1, 2, 4]'], {'size': '(n_parents - 1)', 'replace': '(True)'}), '([1, 2, 4], size=n_parents - 1, replace=True)\n', (19480, 19525), True, 'import numpy as np\n'), ((22577, 22596), 'torch.from_numpy', 'torch.from_numpy', (['X'], {}), '(X)\n', (22593, 22596), False, 'import torch\n'), ((23267, 23296), 'numpy.dot', 'np.dot', (['thetas', 'parent_values'], {}), '(thetas, parent_values)\n', (23273, 23296), True, 'import numpy as np\n'), ((1703, 1768), 'warnings.warn', 'warnings.warn', (['"""Noise coefficient was negative. Defaulting to 1."""'], {}), "('Noise coefficient was negative. Defaulting to 1.')\n", (1716, 1768), False, 'import warnings\n'), ((4187, 4214), 'numpy.random.binomial', 'np.random.binomial', (['k', 'prob'], {}), '(k, prob)\n', (4205, 4214), True, 'import numpy as np\n'), ((4240, 4307), 'numpy.random.choice', 'np.random.choice', (['remaining_nodes'], {'size': 'n_neighbours', 'replace': '(False)'}), '(remaining_nodes, size=n_neighbours, replace=False)\n', (4256, 4307), True, 'import numpy as np\n'), ((18620, 18670), 'torch.nn.modules.Linear', 'torch.nn.modules.Linear', (['(n_parents - 1)', 'num_hidden'], {}), '(n_parents - 1, num_hidden)\n', (18643, 18670), False, 'import torch\n'), ((18694, 18709), 'torch.nn.Tanh', 'torch.nn.Tanh', ([], {}), '()\n', (18707, 18709), False, 'import torch\n'), ((18733, 18771), 'torch.nn.modules.Linear', 'torch.nn.modules.Linear', (['num_hidden', '(1)'], {}), '(num_hidden, 1)\n', (18756, 18771), False, 'import torch\n'), ((20239, 20254), 'numpy.array', 'np.array', (['[0.0]'], {}), '([0.0])\n', (20247, 20254), True, 'import numpy as np\n'), ((20299, 20314), 'numpy.array', 'np.array', (['[1.0]'], {}), '([1.0])\n', (20307, 20314), True, 'import numpy as np\n'), ((24796, 24835), 'pandas.DataFrame', 'pd.DataFrame', (['samples'], {'columns': 'ordering'}), '(samples, columns=ordering)\n', (24808, 24835), True, 'import pandas as pd\n'), ((26180, 26234), 'numpy.vstack', 'np.vstack', (["[graph.nodes[n]['value'] for n in ordering]"], {}), "([graph.nodes[n]['value'] for n in ordering])\n", (26189, 26234), True, 'import numpy as np\n'), ((12941, 12963), 'networkx.topological_sort', 'nx.topological_sort', (['g'], {}), '(g)\n', (12960, 12963), True, 'import networkx as nx\n'), ((17503, 17527), 'numpy.random.normal', 'np.random.normal', (['(0)', '(0.3)'], {}), '(0, 0.3)\n', (17519, 17527), True, 'import numpy as np\n'), ((17572, 17595), 'numpy.random.gamma', 'np.random.gamma', (['(1)', '(0.4)'], {}), '(1, 0.4)\n', (17587, 17595), True, 'import numpy as np\n'), ((17656, 17683), 'numpy.random.uniform', 'np.random.uniform', (['(0.3)', '(0.7)'], {}), '(0.3, 0.7)\n', (17673, 17683), True, 'import numpy as np\n'), ((18063, 18103), 'numpy.random.beta', 'np.random.beta', (['(5)', '(5)'], {'size': '(n_parents - 1)'}), '(5, 5, size=n_parents - 1)\n', (18077, 18103), True, 'import numpy as np\n'), ((25461, 25493), 'numpy.array', 'np.array', (['d[k]'], {'dtype': 'np.float64'}), '(d[k], dtype=np.float64)\n', (25469, 25493), True, 'import numpy as np\n'), ((26419, 26429), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (26425, 26429), True, 'import numpy as np\n'), ((26983, 27021), 'networkx.ancestors', 'nx.ancestors', (['self.G', 'node_of_interest'], {}), '(self.G, node_of_interest)\n', (26995, 27021), True, 'import networkx as nx\n'), ((5305, 5340), 'networkx.is_directed_acyclic_graph', 'nx.is_directed_acyclic_graph', (['graph'], {}), '(graph)\n', (5333, 5340), True, 'import networkx as nx\n'), ((9936, 9963), 'networkx.topological_sort', 'nx.topological_sort', (['self.G'], {}), '(self.G)\n', (9955, 9963), True, 'import networkx as nx\n'), ((14059, 14091), 'networkx.topological_sort', 'nx.topological_sort', (['self.twin_G'], {}), '(self.twin_G)\n', (14078, 14091), True, 'import networkx as nx\n'), ((18187, 18200), 'numpy.sum', 'np.sum', (['theta'], {}), '(theta)\n', (18193, 18200), True, 'import numpy as np\n'), ((18861, 18909), 'torch.randn', 'torch.randn', (['l.weight.shape'], {'requires_grad': '(False)'}), '(l.weight.shape, requires_grad=False)\n', (18872, 18909), False, 'import torch\n'), ((19550, 19635), 'numpy.sum', 'np.sum', (["((self.G.nodes[node]['betas'] * x) ** self.G.nodes[node]['coefs'])"], {'axis': '(1)'}), "((self.G.nodes[node]['betas'] * x) ** self.G.nodes[node]['coefs'], axis=1\n )\n", (19556, 19635), True, 'import numpy as np\n'), ((21277, 21317), 'numpy.random.binomial', 'np.random.binomial', (['(1)', 'p'], {'size': 'n_samples'}), '(1, p, size=n_samples)\n', (21295, 21317), True, 'import numpy as np\n'), ((21117, 21158), 'numpy.random.normal', 'np.random.normal', (['mu', 'std'], {'size': 'n_samples'}), '(mu, std, size=n_samples)\n', (21133, 21158), True, 'import numpy as np\n'), ((27090, 27107), 'math.floor', 'math.floor', (['(n / 2)'], {}), '(n / 2)\n', (27100, 27107), False, 'import math\n'), ((9593, 9621), 'networkx.descendants', 'nx.descendants', (['self.G', 'node'], {}), '(self.G, node)\n', (9607, 9621), True, 'import networkx as nx\n')]
import os, sys sys.path.append(os.path.dirname(os.path.abspath(os.getcwd()))) from data import goes16s3 from tools import utils, inference_tools, plotting from slomo import unet import matplotlib #matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import datetime as dt import time import os import seaborn as sns sns.set_context("paper", font_scale=1.6) year = 2017 month = 9 day = 8 n_channels = 8 t = 1.0 product = 'ABI-L1b-RadC' data_directory = '/nex/datapoolne/goes16' #product = 'ABI-L1b-RadM' #data_directory = '/nobackupp10/tvandal/data/goes16' zoom=False nn_model = unet.UNetMedium discard = 64 dayofyear = dt.datetime(year, month, day).timetuple().tm_yday multivariate = True checkpoint = '../saved-models/1.4.1-unet-medium/9Min-%iChannels-MV/' % n_channels if product == 'ABI-L1b-RadC': down = 20 frame_directory = 'figures/animation-conus' min_hour = 15 else: down = 7 frame_directory = 'figures/animation-mesoscale' min_hour = 16 if zoom: frame_directory += '-zoom' if not os.path.exists(frame_directory): os.makedirs(frame_directory) flownet, interpnet, warper= inference_tools.load_models(n_channels, checkpoint, multivariate=multivariate, nn_model=nn_model) noaadata = goes16s3.NOAAGOESS3(product=product, channels=range(1,n_channels+1), save_directory=data_directory, skip_connection=True) channel_idxs = [c-1 for c in noaadata.channels] files = noaadata.local_files(year=year, dayofyear=dayofyear) files = files.dropna() counter = 0 I0 = None for j, row in enumerate(files.values): # (2017, 251, 0, 2, 168, 'RadC') year, dayofyear, hour, minute, dsecond, spatial = files.iloc[j].name if (product == 'ABI-L1b-RadM') and (spatial != 'RadM1'): continue if (product == 'ABI-L1b-RadM') and (minute % 5 != 0): continue if (hour < min_hour) or (hour > 22): I0 = None continue if I0 is None: I0 = goes16s3._open_and_merge_2km(row[channel_idxs]) continue print("Frame: {}".format(counter)) timestamp = dt.datetime(year, 1, 1, hour, minute) + dt.timedelta(days=dayofyear-1) I1 = goes16s3._open_and_merge_2km(row[channel_idxs]) vector_data = inference_tools.single_inference_split(I0.values, I1.values, 1., flownet, interpnet, multivariate, overlap=128, block_size=256+128, discard=discard) total_flow = vector_data['f_01'] + vector_data['delta_f_t1'] c = 0 u = total_flow[2*c] * -1. v = total_flow[2*c+1] RGB = I0.values[[1,2,0]] RGB = np.transpose(RGB, (1,2,0))[discard:-discard,discard:-discard] #RGB = I0.values[7][discard:-discard,discard:-discard] if zoom: u = u[180:250, 180:250] v = v[180:250, 180:250] RGB = RGB[180:250, 180:250] down = 2 ax = plotting.flow_quiver_plot(u, v, down=down, vmax=0.60, background_img=RGB) ax.text(0.07*total_flow.shape[0], 0.95*total_flow.shape[1], timestamp, fontsize=14, color='white') plt.savefig("{}/quiver_plot_band{}-{}-{:03d}.png".format(frame_directory, c+1, product, counter), dpi=300, pad_inches=0) plt.show() plt.close() ax = plotting.plot_3channel_image(I0.values) plt.savefig("{}/rbg-{:03d}.png".format(frame_directory, counter), dpi=300, pad_inches=0) plt.close() I0 = I1 counter += 1
[ "datetime.datetime", "os.path.exists", "numpy.transpose", "os.makedirs", "tools.plotting.flow_quiver_plot", "data.goes16s3._open_and_merge_2km", "seaborn.set_context", "tools.inference_tools.load_models", "os.getcwd", "matplotlib.pyplot.close", "tools.inference_tools.single_inference_split", "...
[((341, 381), 'seaborn.set_context', 'sns.set_context', (['"""paper"""'], {'font_scale': '(1.6)'}), "('paper', font_scale=1.6)\n", (356, 381), True, 'import seaborn as sns\n'), ((1151, 1253), 'tools.inference_tools.load_models', 'inference_tools.load_models', (['n_channels', 'checkpoint'], {'multivariate': 'multivariate', 'nn_model': 'nn_model'}), '(n_channels, checkpoint, multivariate=\n multivariate, nn_model=nn_model)\n', (1178, 1253), False, 'from tools import utils, inference_tools, plotting\n'), ((1056, 1087), 'os.path.exists', 'os.path.exists', (['frame_directory'], {}), '(frame_directory)\n', (1070, 1087), False, 'import os\n'), ((1093, 1121), 'os.makedirs', 'os.makedirs', (['frame_directory'], {}), '(frame_directory)\n', (1104, 1121), False, 'import os\n'), ((2298, 2345), 'data.goes16s3._open_and_merge_2km', 'goes16s3._open_and_merge_2km', (['row[channel_idxs]'], {}), '(row[channel_idxs])\n', (2326, 2345), False, 'from data import goes16s3\n'), ((2365, 2525), 'tools.inference_tools.single_inference_split', 'inference_tools.single_inference_split', (['I0.values', 'I1.values', '(1.0)', 'flownet', 'interpnet', 'multivariate'], {'overlap': '(128)', 'block_size': '(256 + 128)', 'discard': 'discard'}), '(I0.values, I1.values, 1.0, flownet,\n interpnet, multivariate, overlap=128, block_size=256 + 128, discard=discard\n )\n', (2403, 2525), False, 'from tools import utils, inference_tools, plotting\n'), ((3118, 3190), 'tools.plotting.flow_quiver_plot', 'plotting.flow_quiver_plot', (['u', 'v'], {'down': 'down', 'vmax': '(0.6)', 'background_img': 'RGB'}), '(u, v, down=down, vmax=0.6, background_img=RGB)\n', (3143, 3190), False, 'from tools import utils, inference_tools, plotting\n'), ((3436, 3446), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3444, 3446), True, 'import matplotlib.pyplot as plt\n'), ((3451, 3462), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3460, 3462), True, 'import matplotlib.pyplot as plt\n'), ((3473, 3512), 'tools.plotting.plot_3channel_image', 'plotting.plot_3channel_image', (['I0.values'], {}), '(I0.values)\n', (3501, 3512), False, 'from tools import utils, inference_tools, plotting\n'), ((3610, 3621), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (3619, 3621), True, 'import matplotlib.pyplot as plt\n'), ((2096, 2143), 'data.goes16s3._open_and_merge_2km', 'goes16s3._open_and_merge_2km', (['row[channel_idxs]'], {}), '(row[channel_idxs])\n', (2124, 2143), False, 'from data import goes16s3\n'), ((2218, 2255), 'datetime.datetime', 'dt.datetime', (['year', '(1)', '(1)', 'hour', 'minute'], {}), '(year, 1, 1, hour, minute)\n', (2229, 2255), True, 'import datetime as dt\n'), ((2258, 2290), 'datetime.timedelta', 'dt.timedelta', ([], {'days': '(dayofyear - 1)'}), '(days=dayofyear - 1)\n', (2270, 2290), True, 'import datetime as dt\n'), ((2856, 2884), 'numpy.transpose', 'np.transpose', (['RGB', '(1, 2, 0)'], {}), '(RGB, (1, 2, 0))\n', (2868, 2884), True, 'import numpy as np\n'), ((63, 74), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (72, 74), False, 'import os\n'), ((647, 676), 'datetime.datetime', 'dt.datetime', (['year', 'month', 'day'], {}), '(year, month, day)\n', (658, 676), True, 'import datetime as dt\n')]
import numpy as np from surpyval.utils import xcnt_to_xrd from surpyval.nonparametric.nonparametric_fitter import NonParametricFitter def km(r, d): R = 1 - (d / r) R[np.isnan(R)] = 0 old_err_state = np.seterr(under='raise') try: R = np.cumprod(R) except FloatingPointError: R = np.cumsum(np.log(1 - (d / r))) R = np.exp(R) np.seterr(**old_err_state) return R def kaplan_meier(x, c, n, t): xrd = xcnt_to_xrd(x, c, n, t) out = {k: v for k, v in zip(['x', 'r', 'd'], xrd)} out['R'] = km(out['r'], out['d']) return out class KaplanMeier_(NonParametricFitter): r""" Kaplan-Meier estimator class. Calculates the Non-Parametric estimate of the survival function using: .. math:: R(x) = \prod_{i:x_{i} \leq x}^{} \left ( 1 - \frac{d_{i} }{r_{i}} \right ) Examples -------- >>> import numpy as np >>> from surpyval import KaplanMeier >>> x = np.array([1, 2, 3, 4, 5]) >>> model = KaplanMeier.fit(x) >>> model.R array([0.8, 0.6, 0.4, 0.2, 0. ]) """ def __init__(self): self.how = 'Kaplan-Meier' KaplanMeier = KaplanMeier_()
[ "surpyval.utils.xcnt_to_xrd", "numpy.log", "numpy.exp", "numpy.isnan", "numpy.seterr", "numpy.cumprod" ]
[((213, 237), 'numpy.seterr', 'np.seterr', ([], {'under': '"""raise"""'}), "(under='raise')\n", (222, 237), True, 'import numpy as np\n'), ((375, 401), 'numpy.seterr', 'np.seterr', ([], {}), '(**old_err_state)\n', (384, 401), True, 'import numpy as np\n'), ((457, 480), 'surpyval.utils.xcnt_to_xrd', 'xcnt_to_xrd', (['x', 'c', 'n', 't'], {}), '(x, c, n, t)\n', (468, 480), False, 'from surpyval.utils import xcnt_to_xrd\n'), ((176, 187), 'numpy.isnan', 'np.isnan', (['R'], {}), '(R)\n', (184, 187), True, 'import numpy as np\n'), ((260, 273), 'numpy.cumprod', 'np.cumprod', (['R'], {}), '(R)\n', (270, 273), True, 'import numpy as np\n'), ((360, 369), 'numpy.exp', 'np.exp', (['R'], {}), '(R)\n', (366, 369), True, 'import numpy as np\n'), ((327, 344), 'numpy.log', 'np.log', (['(1 - d / r)'], {}), '(1 - d / r)\n', (333, 344), True, 'import numpy as np\n')]
import cv2 import numpy as np from ...src.move import horizontally, vertically from ..mocks.image_mock import image tranlated_image = horizontally(image, -100) (height, width) = image.shape[:2] translation_matrix = np.float32([[1, 0, -100], [0, 1, 1]]) translated_image_mock = cv2.warpAffine(image, translation_matrix, (width, height)) assert np.allclose(translated_image_mock, tranlated_image), "Should translate image horizontally with success" tranlated_image = vertically(image, 30) (height, width) = image.shape[:2] translation_matrix = np.float32([[1, 0, 30], [0, 1, 1]]) translated_image_mock = cv2.warpAffine(image, translation_matrix, (width, height)) assert np.allclose(translated_image_mock, tranlated_image), "Should translate image vertically with success"
[ "cv2.warpAffine", "numpy.float32", "numpy.allclose" ]
[((217, 254), 'numpy.float32', 'np.float32', (['[[1, 0, -100], [0, 1, 1]]'], {}), '([[1, 0, -100], [0, 1, 1]])\n', (227, 254), True, 'import numpy as np\n'), ((279, 337), 'cv2.warpAffine', 'cv2.warpAffine', (['image', 'translation_matrix', '(width, height)'], {}), '(image, translation_matrix, (width, height))\n', (293, 337), False, 'import cv2\n'), ((345, 396), 'numpy.allclose', 'np.allclose', (['translated_image_mock', 'tranlated_image'], {}), '(translated_image_mock, tranlated_image)\n', (356, 396), True, 'import numpy as np\n'), ((545, 580), 'numpy.float32', 'np.float32', (['[[1, 0, 30], [0, 1, 1]]'], {}), '([[1, 0, 30], [0, 1, 1]])\n', (555, 580), True, 'import numpy as np\n'), ((605, 663), 'cv2.warpAffine', 'cv2.warpAffine', (['image', 'translation_matrix', '(width, height)'], {}), '(image, translation_matrix, (width, height))\n', (619, 663), False, 'import cv2\n'), ((671, 722), 'numpy.allclose', 'np.allclose', (['translated_image_mock', 'tranlated_image'], {}), '(translated_image_mock, tranlated_image)\n', (682, 722), True, 'import numpy as np\n')]
""" Compare commercial models with mean, std, CI over the original test set split. """ from ser_evaluation.evaluate import get_test_set_filenames, preprocess_crema, scores from pathlib import Path import numpy as np import pandas as pd from tqdm import tqdm def get_metrics(pred_path): #bootstrap_path = 'predictions_bootstrap' #pred_path = "predictions/commercial_results/results_csv" target_intended_observed_ls = [] model_ls = [] subset_ls = [] f1_score = [] f1_score_anger = [] f1_score_happy = [] f1_score_neutral = [] f1_score_sad = [] recall = [] recall_anger = [] recall_happy = [] recall_neutral = [] recall_sad = [] data_path = Path(pred_path) paths = [path for path in data_path.glob('**/*') if path.is_file()] paths.sort() for path in tqdm(paths): model = path.stem emotions = [ 'Filename', 'Anger', 'Happy', 'Neutral', 'Sad'] pred_df = pd.read_csv( path, usecols=(emotions) ) col_names = {k: "{}_pred".format(k[:3].upper()) if k != 'Filename' else k.lower() for k in pred_df.columns} pred_df.rename(columns = col_names, inplace = True) #Convert probabilities to 0s and 1s for col in pred_df.drop(['filename'], axis = 1).columns: pred_df[col] = np.where(pred_df[col] >= 0.5, 1, 0) test_file_name = get_test_set_filenames(path) crema = preprocess_crema(demographics_path = 'Data/VideoDemographics.csv', ratings_path = 'Data/processedResults/summaryTable.csv', test_file_names= test_file_name) for key, cat in crema.items(): subset = key.split("_")[-1] if 'observed' in key: target_intended_observed = 'observed' else: target_intended_observed = 'intended' cat_pred_df = cat.merge(pred_df, on = 'filename') cat_pred_df.columns y_true = cat_pred_df[cat_pred_df.filter(regex="{}_".format(target_intended_observed)) .columns]. \ drop(columns = ['{}_DIS'.format(target_intended_observed), '{}_FEA'.format(target_intended_observed)]). \ to_numpy() y_pred = cat_pred_df[cat_pred_df.filter(regex='pred').columns].to_numpy() target_intended_observed_ls.append(target_intended_observed) model_ls.append(model) subset_ls.append(subset) scores_dict = scores(y_true, y_pred) f1_score.append(scores_dict['macro avg']['f1-score']) f1_score_anger.append(scores_dict['0']['f1-score']) f1_score_happy.append(scores_dict['1']['f1-score']) f1_score_neutral.append(scores_dict['2']['f1-score']) f1_score_sad.append(scores_dict['3']['f1-score']) recall.append(scores_dict['macro avg']['recall']) recall_anger.append(scores_dict['0']['recall']) recall_happy.append(scores_dict['1']['recall']) recall_neutral.append(scores_dict['2']['recall']) recall_sad.append(scores_dict['3']['recall']) f1_df = pd.DataFrame( data=zip( target_intended_observed_ls, model_ls, subset_ls, f1_score, f1_score_anger, f1_score_happy, f1_score_neutral, f1_score_sad, recall, recall_anger, recall_happy, recall_neutral, recall_sad), columns=[ 'target_intended_observed', 'model', 'subset', 'f1_score', 'f1_score_anger', 'f1_score_happy', 'f1_score_neutral', 'f1_score_sad', 'recall', 'recall_anger', 'recall_happy', 'recall_neutral', 'recall_sad']) return f1_df if __name__ == '__main__': df = get_metrics("predictions/commercial_results/results_csv") output_path = Path('bias_results/commercial/commercial_models.csv') output_path.parent.mkdir(parents=True, exist_ok=True) df.to_csv(output_path, index = False, float_format='%.5f')
[ "ser_evaluation.evaluate.preprocess_crema", "pandas.read_csv", "pathlib.Path", "numpy.where", "tqdm.tqdm", "ser_evaluation.evaluate.scores", "ser_evaluation.evaluate.get_test_set_filenames" ]
[((707, 722), 'pathlib.Path', 'Path', (['pred_path'], {}), '(pred_path)\n', (711, 722), False, 'from pathlib import Path\n'), ((829, 840), 'tqdm.tqdm', 'tqdm', (['paths'], {}), '(paths)\n', (833, 840), False, 'from tqdm import tqdm\n'), ((4340, 4393), 'pathlib.Path', 'Path', (['"""bias_results/commercial/commercial_models.csv"""'], {}), "('bias_results/commercial/commercial_models.csv')\n", (4344, 4393), False, 'from pathlib import Path\n'), ((1026, 1061), 'pandas.read_csv', 'pd.read_csv', (['path'], {'usecols': 'emotions'}), '(path, usecols=emotions)\n', (1037, 1061), True, 'import pandas as pd\n'), ((1523, 1551), 'ser_evaluation.evaluate.get_test_set_filenames', 'get_test_set_filenames', (['path'], {}), '(path)\n', (1545, 1551), False, 'from ser_evaluation.evaluate import get_test_set_filenames, preprocess_crema, scores\n'), ((1568, 1728), 'ser_evaluation.evaluate.preprocess_crema', 'preprocess_crema', ([], {'demographics_path': '"""Data/VideoDemographics.csv"""', 'ratings_path': '"""Data/processedResults/summaryTable.csv"""', 'test_file_names': 'test_file_name'}), "(demographics_path='Data/VideoDemographics.csv',\n ratings_path='Data/processedResults/summaryTable.csv', test_file_names=\n test_file_name)\n", (1584, 1728), False, 'from ser_evaluation.evaluate import get_test_set_filenames, preprocess_crema, scores\n'), ((1453, 1488), 'numpy.where', 'np.where', (['(pred_df[col] >= 0.5)', '(1)', '(0)'], {}), '(pred_df[col] >= 0.5, 1, 0)\n', (1461, 1488), True, 'import numpy as np\n'), ((2788, 2810), 'ser_evaluation.evaluate.scores', 'scores', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (2794, 2810), False, 'from ser_evaluation.evaluate import get_test_set_filenames, preprocess_crema, scores\n')]
# -*- coding: utf-8 -*- # Função de decisão: # Onde: w^T.x+b = w1.x1 +...+ wn.xn + b é o termo de polarização, é o vetor de peso das características. # Interpretação do resultado: # Se o resultado for positivo a classe será prevista como classe positiva (1) Caso contrário a classe será prevista como classe negativa (0) import numpy as np from sklearn import datasets from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import LinearSVC #Carga de dataset iris = datasets.load_iris() X = iris['data'][:, (2,3)] y = (iris['target'] == 2).astype(np.float64) # É gerado um pipeline para normalização das características e criação de um objeto com o modelo SVM. Em seguida é executado o pipeline que realiza estas etapas. #Criação do Pipeline para normalização das características e treinamento do SVM svm_clf = Pipeline([ ('scaler', StandardScaler()), ('linear_svc', LinearSVC(C=1, loss='hinge')) ]) # O modelo gerado é treinado com os dados carregados anteriormente. #Treinamento do modelo svm_clf.fit(X, y) # 1.2 Aplicação do modelo treinado # Previsão do classificador SVM linear # Equação: svm_clf.predict([[5.5, 1.7]]) # 2 Classificação SVM Não Linear # 2.1 Mapeamento de features, criação, treinamento e aplicação do modelo from matplotlib import pyplot as plt import seaborn as sns #Criação de valores entre -4 e 4 (sem separação linear) x1 = np.linspace(-4, 4, 9).reshape(-1, 1) #Criando uma segunda característica quadrática x2 = x1**2 #Conjuntos de dados separado linearmente X2D = np.c_[x1, x2] y = np.array([0, 0, 1, 1, 1, 1, 1, 0, 0]) plt.figure(figsize=(10,6)) plt.plot(x1[:, 0][y==0], np.zeros(4), "bs") plt.plot(x1[:, 0][y==1], np.zeros(5), "g^") plt.title('Dados não separáveis linearmente') sns.despine() # Na visualização acima os dados originais de são plotados, mas percebe-se que não há como separá-los linearmente em diferentes classes. # A seguir os dados com uma característica correspondente ao quadrado da mesma são plotados, demonstrando a possibilidade de separá-los linearmente. plt.figure(figsize=(10,6)) plt.plot(x1, x2, 'o') plt.title('Dados transformados: separáveis linearmente') sns.despine() # O gráfico a seguir demonstra a separação mencionada anteriormente. plt.grid(True, which='both') plt.axhline(y=0, color='k') plt.axvline(x=0, color='k') plt.plot(X2D[:, 0][y==0], X2D[:, 1][y==0], "bs") plt.plot(X2D[:, 0][y==1], X2D[:, 1][y==1], "g^") plt.xlabel(r"$x_1$", fontsize=20) plt.ylabel(r"$x_2$ ", fontsize=20, rotation=0) plt.gca().get_yaxis().set_ticks([0, 4, 8, 12, 16]) plt.plot([-4.5, 4.5], [6.5, 6.5], "r--", linewidth=3) plt.axis([-4.5, 4.5, -1, 17]) # A seguir carregamos o dataset de exemplo make_moon, cuja visualização demonstra a impossibilidade de separação linear. #Conjunto de dados de exemplo do livro from sklearn.datasets import make_moons X, y = make_moons(n_samples=100, noise=0.15, random_state=42) def plot_dataset(X, y, axes): plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs") plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^") plt.axis(axes) plt.grid(True, which='both') plt.xlabel(r"$x_1$", fontsize=20) plt.ylabel(r"$x_2$", fontsize=20, rotation=0) plot_dataset(X, y, [-1.5, 2.5, -1, 1.5]) plt.show() # Nas etapas seguintes é gerado um pipeline para criação de novas características, baseadas nos polinômios de grau 3, realizada a normalização z-Score e a criação do modelo SVM. from sklearn.preprocessing import PolynomialFeatures #Criação do Pipeline (mapeamento de features, escalonamento e modelo) polynomial_svm_clf = Pipeline([ ('poly_features', PolynomialFeatures(degree=3)), ('scaler', StandardScaler()), ('svm_clf', LinearSVC(C=10, loss='hinge')) ]) # Agora o pipeline é executado no conjunto de dados e em seguida realizadas predições cuja plotagem demonstra a classificação realizada. #Execução do pipeline polynomial_svm_clf.fit(X, y) def plot_predictions(clf, axes): x0s = np.linspace(axes[0], axes[1], 100) x1s = np.linspace(axes[2], axes[3], 100) x0, x1 = np.meshgrid(x0s, x1s) X = np.c_[x0.ravel(), x1.ravel()] y_pred = clf.predict(X).reshape(x0.shape) y_decision = clf.decision_function(X).reshape(x0.shape) plt.contourf(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2) plt.contourf(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1) plot_predictions(polynomial_svm_clf, [-1.5, 2.5, -1, 1.5]) plot_dataset(X, y, [-1.5, 2.5, -1, 1.5]) # 2.2 Uso de Kernels # A abordagem de uso de kernels permite a geração de modelos considerando a adição de novas características com dimensões diferentes, por exemplo polinomiais, sem a necessidade de efetivamente adicioná-las ao conjunto de dados. # Isso ocorre porque com aplicação de funções denominadas kernels é possível calcular o produto escalar com base nos vetores originais e sem precisar calcular a transformação . # O que possibilita esta técnica é que a transformação é igual ao produto escalar dos dados originais: Função do Kernel Polinomial K(a,b) = (a^T.b)^2 # Aplicação usando Scikit-Learn from sklearn.svm import SVC #Criação do pipeline para uso do kernel polinomial poly_kernel_svm_clf = Pipeline([ ('scaler', StandardScaler()), ('svm_clf', SVC(kernel='poly', degree=3, coef0=1, C=5)) ]) #Execução do pipeline poly_kernel_svm_clf.fit(X, y) #Criação de outro pipeline (10 graus e coef = 100) poly100_kernel_svm_clf = Pipeline([ ("scaler", StandardScaler()), ("svm_clf", SVC(kernel="poly", degree=10, coef0=100, C=5)) ]) poly100_kernel_svm_clf.fit(X, y) fig, axes = plt.subplots(ncols=2, figsize=(12, 4), sharey=True) plt.sca(axes[0]) plot_predictions(poly_kernel_svm_clf, [-1.5, 2.45, -1, 1.5]) plot_dataset(X, y, [-1.5, 2.4, -1, 1.5]) plt.title(r"$d=3, r=1, C=5$", fontsize=18) plt.sca(axes[1]) plot_predictions(poly100_kernel_svm_clf, [-1.5, 2.45, -1, 1.5]) plot_dataset(X, y, [-1.5, 2.4, -1, 1.5]) plt.title(r"$d=10, r=100, C=5$", fontsize=18) plt.ylabel("") # Kernel RBF Gaussiano # Além do kernel polinomial visto na subseção anterior, há outras formas de aplicação desta técnica. A partir de agora é apresentada sua aplicação para kernel gaussiano. rbf_kernel_svm_clf = Pipeline([ ("scaler", StandardScaler()), ("svm_clf", SVC(kernel="rbf", gamma=5, C=0.001)) ]) rbf_kernel_svm_clf.fit(X, y) from sklearn.svm import SVC gamma1, gamma2 = 0.1, 5 C1, C2 = 0.001, 1000 hyperparams = (gamma1, C1), (gamma1, C2), (gamma2, C1), (gamma2, C2) svm_clfs = [] for gamma, C in hyperparams: rbf_kernel_svm_clf = Pipeline([ ("scaler", StandardScaler()), ("svm_clf", SVC(kernel="rbf", gamma=gamma, C=C)) ]) rbf_kernel_svm_clf.fit(X, y) svm_clfs.append(rbf_kernel_svm_clf) fig, axes = plt.subplots(nrows=2, ncols=2, figsize=(10.5, 7), sharex=True, sharey=True) for i, svm_clf in enumerate(svm_clfs): plt.sca(axes[i // 2, i % 2]) plot_predictions(svm_clf, [-1.5, 2.45, -1, 1.5]) plot_dataset(X, y, [-1.5, 2.45, -1, 1.5]) gamma, C = hyperparams[i] plt.title(r"$\gamma = {}, C = {}$".format(gamma, C), fontsize=16) if i in (0, 1): plt.xlabel("") if i in (1, 3): plt.ylabel("") # 3 Regressão SVM # O algoritmo SVM também pode ser usado para regressão, prevendo valores de , dada uma instância de , ao invés de uma classe. # 3.1 Regressão Linear usando SVM #Dados de exemplo np.random.seed(42) m = 50 X = 2 * np.random.rand(m, 1) y = (4 + 3 * X + np.random.randn(m, 1)).ravel() # Criação e aplicação de predições com o um modelo SVM linear. from sklearn.svm import LinearSVR svm_reg = LinearSVR(epsilon=1.5) svm_reg.fit(X, y) # 3.2 Regressão Polinomial usando SVM Geração de dados aleatórios com escalonamento quadrático. np.random.seed(42) m = 100 X = 2 * np.random.rand(m, 1) - 1 y = (0.2 + 0.1 * X + 0.5 * X**2 + np.random.randn(m, 1)/10).ravel() # Criação de um modelo SVM polinomial com técnica de kernel e sua aplicação nos dados acima. from sklearn.svm import SVR svm_poly_reg = SVR(kernel="poly", degree=2, C=100, epsilon=0.1, gamma="scale") svm_poly_reg.fit(X, y) # Criação de dois modelos com mudança nos parâmetros e plotagem dos resultados para comparação. from sklearn.svm import SVR svm_poly_reg1 = SVR(kernel="poly", degree=2, C=100, epsilon=0.1, gamma="scale") svm_poly_reg2 = SVR(kernel="poly", degree=2, C=0.01, epsilon=0.1, gamma="scale") svm_poly_reg1.fit(X, y) svm_poly_reg2.fit(X, y) def plot_svm_regression(svm_reg, X, y, axes): x1s = np.linspace(axes[0], axes[1], 100).reshape(100, 1) y_pred = svm_reg.predict(x1s) plt.plot(x1s, y_pred, "k-", linewidth=2, label=r"$\hat{y}$") plt.plot(x1s, y_pred + svm_reg.epsilon, "k--") plt.plot(x1s, y_pred - svm_reg.epsilon, "k--") plt.scatter(X[svm_reg.support_], y[svm_reg.support_], s=180, facecolors='#FFAAAA') plt.plot(X, y, "bo") plt.xlabel(r"$x_1$", fontsize=18) plt.legend(loc="upper left", fontsize=18) plt.axis(axes) fig, axes = plt.subplots(ncols=2, figsize=(9, 4), sharey=True) plt.sca(axes[0]) plot_svm_regression(svm_poly_reg1, X, y, [-1, 1, 0, 1]) plt.title(r"$degree={}, C={}, \epsilon = {}$".format(svm_poly_reg1.degree, svm_poly_reg1.C, svm_poly_reg1.epsilon), fontsize=18) plt.ylabel(r"$y$", fontsize=18, rotation=0) plt.sca(axes[1]) plot_svm_regression(svm_poly_reg2, X, y, [-1, 1, 0, 1]) plt.title(r"$degree={}, C={}, \epsilon = {}$".format(svm_poly_reg2.degree, svm_poly_reg2.C, svm_poly_reg2.epsilon), fontsize = 18)
[ "matplotlib.pyplot.grid", "sklearn.preprocessing.PolynomialFeatures", "numpy.random.rand", "matplotlib.pyplot.ylabel", "numpy.array", "matplotlib.pyplot.axvline", "matplotlib.pyplot.contourf", "seaborn.despine", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "matplotlib.pyplot.axhline", ...
[((538, 558), 'sklearn.datasets.load_iris', 'datasets.load_iris', ([], {}), '()\n', (556, 558), False, 'from sklearn import datasets\n'), ((1676, 1713), 'numpy.array', 'np.array', (['[0, 0, 1, 1, 1, 1, 1, 0, 0]'], {}), '([0, 0, 1, 1, 1, 1, 1, 0, 0])\n', (1684, 1713), True, 'import numpy as np\n'), ((1717, 1744), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 6)'}), '(figsize=(10, 6))\n', (1727, 1744), True, 'from matplotlib import pyplot as plt\n'), ((1837, 1882), 'matplotlib.pyplot.title', 'plt.title', (['"""Dados não separáveis linearmente"""'], {}), "('Dados não separáveis linearmente')\n", (1846, 1882), True, 'from matplotlib import pyplot as plt\n'), ((1884, 1897), 'seaborn.despine', 'sns.despine', ([], {}), '()\n', (1895, 1897), True, 'import seaborn as sns\n'), ((2193, 2220), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(10, 6)'}), '(figsize=(10, 6))\n', (2203, 2220), True, 'from matplotlib import pyplot as plt\n'), ((2221, 2242), 'matplotlib.pyplot.plot', 'plt.plot', (['x1', 'x2', '"""o"""'], {}), "(x1, x2, 'o')\n", (2229, 2242), True, 'from matplotlib import pyplot as plt\n'), ((2244, 2300), 'matplotlib.pyplot.title', 'plt.title', (['"""Dados transformados: separáveis linearmente"""'], {}), "('Dados transformados: separáveis linearmente')\n", (2253, 2300), True, 'from matplotlib import pyplot as plt\n'), ((2302, 2315), 'seaborn.despine', 'sns.despine', ([], {}), '()\n', (2313, 2315), True, 'import seaborn as sns\n'), ((2391, 2419), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'which': '"""both"""'}), "(True, which='both')\n", (2399, 2419), True, 'from matplotlib import pyplot as plt\n'), ((2421, 2448), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': '(0)', 'color': '"""k"""'}), "(y=0, color='k')\n", (2432, 2448), True, 'from matplotlib import pyplot as plt\n'), ((2450, 2477), 'matplotlib.pyplot.axvline', 'plt.axvline', ([], {'x': '(0)', 'color': '"""k"""'}), "(x=0, color='k')\n", (2461, 2477), True, 'from matplotlib import pyplot as plt\n'), ((2479, 2531), 'matplotlib.pyplot.plot', 'plt.plot', (['X2D[:, 0][y == 0]', 'X2D[:, 1][y == 0]', '"""bs"""'], {}), "(X2D[:, 0][y == 0], X2D[:, 1][y == 0], 'bs')\n", (2487, 2531), True, 'from matplotlib import pyplot as plt\n'), ((2529, 2581), 'matplotlib.pyplot.plot', 'plt.plot', (['X2D[:, 0][y == 1]', 'X2D[:, 1][y == 1]', '"""g^"""'], {}), "(X2D[:, 0][y == 1], X2D[:, 1][y == 1], 'g^')\n", (2537, 2581), True, 'from matplotlib import pyplot as plt\n'), ((2579, 2611), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$x_1$"""'], {'fontsize': '(20)'}), "('$x_1$', fontsize=20)\n", (2589, 2611), True, 'from matplotlib import pyplot as plt\n'), ((2614, 2660), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$x_2$ """'], {'fontsize': '(20)', 'rotation': '(0)'}), "('$x_2$ ', fontsize=20, rotation=0)\n", (2624, 2660), True, 'from matplotlib import pyplot as plt\n'), ((2715, 2768), 'matplotlib.pyplot.plot', 'plt.plot', (['[-4.5, 4.5]', '[6.5, 6.5]', '"""r--"""'], {'linewidth': '(3)'}), "([-4.5, 4.5], [6.5, 6.5], 'r--', linewidth=3)\n", (2723, 2768), True, 'from matplotlib import pyplot as plt\n'), ((2770, 2799), 'matplotlib.pyplot.axis', 'plt.axis', (['[-4.5, 4.5, -1, 17]'], {}), '([-4.5, 4.5, -1, 17])\n', (2778, 2799), True, 'from matplotlib import pyplot as plt\n'), ((3015, 3069), 'sklearn.datasets.make_moons', 'make_moons', ([], {'n_samples': '(100)', 'noise': '(0.15)', 'random_state': '(42)'}), '(n_samples=100, noise=0.15, random_state=42)\n', (3025, 3069), False, 'from sklearn.datasets import make_moons\n'), ((3392, 3402), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3400, 3402), True, 'from matplotlib import pyplot as plt\n'), ((6056, 6107), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'ncols': '(2)', 'figsize': '(12, 4)', 'sharey': '(True)'}), '(ncols=2, figsize=(12, 4), sharey=True)\n', (6068, 6107), True, 'from matplotlib import pyplot as plt\n'), ((6111, 6127), 'matplotlib.pyplot.sca', 'plt.sca', (['axes[0]'], {}), '(axes[0])\n', (6118, 6127), True, 'from matplotlib import pyplot as plt\n'), ((6233, 6274), 'matplotlib.pyplot.title', 'plt.title', (['"""$d=3, r=1, C=5$"""'], {'fontsize': '(18)'}), "('$d=3, r=1, C=5$', fontsize=18)\n", (6242, 6274), True, 'from matplotlib import pyplot as plt\n'), ((6279, 6295), 'matplotlib.pyplot.sca', 'plt.sca', (['axes[1]'], {}), '(axes[1])\n', (6286, 6295), True, 'from matplotlib import pyplot as plt\n'), ((6404, 6448), 'matplotlib.pyplot.title', 'plt.title', (['"""$d=10, r=100, C=5$"""'], {'fontsize': '(18)'}), "('$d=10, r=100, C=5$', fontsize=18)\n", (6413, 6448), True, 'from matplotlib import pyplot as plt\n'), ((6451, 6465), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['""""""'], {}), "('')\n", (6461, 6465), True, 'from matplotlib import pyplot as plt\n'), ((7276, 7351), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(2)', 'figsize': '(10.5, 7)', 'sharex': '(True)', 'sharey': '(True)'}), '(nrows=2, ncols=2, figsize=(10.5, 7), sharex=True, sharey=True)\n', (7288, 7351), True, 'from matplotlib import pyplot as plt\n'), ((7936, 7954), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (7950, 7954), True, 'import numpy as np\n'), ((8156, 8178), 'sklearn.svm.LinearSVR', 'LinearSVR', ([], {'epsilon': '(1.5)'}), '(epsilon=1.5)\n', (8165, 8178), False, 'from sklearn.svm import LinearSVR\n'), ((8302, 8320), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (8316, 8320), True, 'import numpy as np\n'), ((8578, 8641), 'sklearn.svm.SVR', 'SVR', ([], {'kernel': '"""poly"""', 'degree': '(2)', 'C': '(100)', 'epsilon': '(0.1)', 'gamma': '"""scale"""'}), "(kernel='poly', degree=2, C=100, epsilon=0.1, gamma='scale')\n", (8581, 8641), False, 'from sklearn.svm import SVR\n'), ((8813, 8876), 'sklearn.svm.SVR', 'SVR', ([], {'kernel': '"""poly"""', 'degree': '(2)', 'C': '(100)', 'epsilon': '(0.1)', 'gamma': '"""scale"""'}), "(kernel='poly', degree=2, C=100, epsilon=0.1, gamma='scale')\n", (8816, 8876), False, 'from sklearn.svm import SVR\n'), ((8894, 8958), 'sklearn.svm.SVR', 'SVR', ([], {'kernel': '"""poly"""', 'degree': '(2)', 'C': '(0.01)', 'epsilon': '(0.1)', 'gamma': '"""scale"""'}), "(kernel='poly', degree=2, C=0.01, epsilon=0.1, gamma='scale')\n", (8897, 8958), False, 'from sklearn.svm import SVR\n'), ((9586, 9636), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'ncols': '(2)', 'figsize': '(9, 4)', 'sharey': '(True)'}), '(ncols=2, figsize=(9, 4), sharey=True)\n', (9598, 9636), True, 'from matplotlib import pyplot as plt\n'), ((9638, 9654), 'matplotlib.pyplot.sca', 'plt.sca', (['axes[0]'], {}), '(axes[0])\n', (9645, 9654), True, 'from matplotlib import pyplot as plt\n'), ((9843, 9885), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$y$"""'], {'fontsize': '(18)', 'rotation': '(0)'}), "('$y$', fontsize=18, rotation=0)\n", (9853, 9885), True, 'from matplotlib import pyplot as plt\n'), ((9888, 9904), 'matplotlib.pyplot.sca', 'plt.sca', (['axes[1]'], {}), '(axes[1])\n', (9895, 9904), True, 'from matplotlib import pyplot as plt\n'), ((1772, 1783), 'numpy.zeros', 'np.zeros', (['(4)'], {}), '(4)\n', (1780, 1783), True, 'import numpy as np\n'), ((1817, 1828), 'numpy.zeros', 'np.zeros', (['(5)'], {}), '(5)\n', (1825, 1828), True, 'import numpy as np\n'), ((3108, 3156), 'matplotlib.pyplot.plot', 'plt.plot', (['X[:, 0][y == 0]', 'X[:, 1][y == 0]', '"""bs"""'], {}), "(X[:, 0][y == 0], X[:, 1][y == 0], 'bs')\n", (3116, 3156), True, 'from matplotlib import pyplot as plt\n'), ((3158, 3206), 'matplotlib.pyplot.plot', 'plt.plot', (['X[:, 0][y == 1]', 'X[:, 1][y == 1]', '"""g^"""'], {}), "(X[:, 0][y == 1], X[:, 1][y == 1], 'g^')\n", (3166, 3206), True, 'from matplotlib import pyplot as plt\n'), ((3208, 3222), 'matplotlib.pyplot.axis', 'plt.axis', (['axes'], {}), '(axes)\n', (3216, 3222), True, 'from matplotlib import pyplot as plt\n'), ((3228, 3256), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {'which': '"""both"""'}), "(True, which='both')\n", (3236, 3256), True, 'from matplotlib import pyplot as plt\n'), ((3262, 3294), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$x_1$"""'], {'fontsize': '(20)'}), "('$x_1$', fontsize=20)\n", (3272, 3294), True, 'from matplotlib import pyplot as plt\n'), ((3301, 3345), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""$x_2$"""'], {'fontsize': '(20)', 'rotation': '(0)'}), "('$x_2$', fontsize=20, rotation=0)\n", (3311, 3345), True, 'from matplotlib import pyplot as plt\n'), ((4208, 4242), 'numpy.linspace', 'np.linspace', (['axes[0]', 'axes[1]', '(100)'], {}), '(axes[0], axes[1], 100)\n', (4219, 4242), True, 'import numpy as np\n'), ((4254, 4288), 'numpy.linspace', 'np.linspace', (['axes[2]', 'axes[3]', '(100)'], {}), '(axes[2], axes[3], 100)\n', (4265, 4288), True, 'import numpy as np\n'), ((4303, 4324), 'numpy.meshgrid', 'np.meshgrid', (['x0s', 'x1s'], {}), '(x0s, x1s)\n', (4314, 4324), True, 'import numpy as np\n'), ((4477, 4533), 'matplotlib.pyplot.contourf', 'plt.contourf', (['x0', 'x1', 'y_pred'], {'cmap': 'plt.cm.brg', 'alpha': '(0.2)'}), '(x0, x1, y_pred, cmap=plt.cm.brg, alpha=0.2)\n', (4489, 4533), True, 'from matplotlib import pyplot as plt\n'), ((4539, 4599), 'matplotlib.pyplot.contourf', 'plt.contourf', (['x0', 'x1', 'y_decision'], {'cmap': 'plt.cm.brg', 'alpha': '(0.1)'}), '(x0, x1, y_decision, cmap=plt.cm.brg, alpha=0.1)\n', (4551, 4599), True, 'from matplotlib import pyplot as plt\n'), ((7399, 7427), 'matplotlib.pyplot.sca', 'plt.sca', (['axes[i // 2, i % 2]'], {}), '(axes[i // 2, i % 2])\n', (7406, 7427), True, 'from matplotlib import pyplot as plt\n'), ((7972, 7992), 'numpy.random.rand', 'np.random.rand', (['m', '(1)'], {}), '(m, 1)\n', (7986, 7992), True, 'import numpy as np\n'), ((9186, 9246), 'matplotlib.pyplot.plot', 'plt.plot', (['x1s', 'y_pred', '"""k-"""'], {'linewidth': '(2)', 'label': '"""$\\\\hat{y}$"""'}), "(x1s, y_pred, 'k-', linewidth=2, label='$\\\\hat{y}$')\n", (9194, 9246), True, 'from matplotlib import pyplot as plt\n'), ((9252, 9298), 'matplotlib.pyplot.plot', 'plt.plot', (['x1s', '(y_pred + svm_reg.epsilon)', '"""k--"""'], {}), "(x1s, y_pred + svm_reg.epsilon, 'k--')\n", (9260, 9298), True, 'from matplotlib import pyplot as plt\n'), ((9304, 9350), 'matplotlib.pyplot.plot', 'plt.plot', (['x1s', '(y_pred - svm_reg.epsilon)', '"""k--"""'], {}), "(x1s, y_pred - svm_reg.epsilon, 'k--')\n", (9312, 9350), True, 'from matplotlib import pyplot as plt\n'), ((9356, 9443), 'matplotlib.pyplot.scatter', 'plt.scatter', (['X[svm_reg.support_]', 'y[svm_reg.support_]'], {'s': '(180)', 'facecolors': '"""#FFAAAA"""'}), "(X[svm_reg.support_], y[svm_reg.support_], s=180, facecolors=\n '#FFAAAA')\n", (9367, 9443), True, 'from matplotlib import pyplot as plt\n'), ((9444, 9464), 'matplotlib.pyplot.plot', 'plt.plot', (['X', 'y', '"""bo"""'], {}), "(X, y, 'bo')\n", (9452, 9464), True, 'from matplotlib import pyplot as plt\n'), ((9470, 9502), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""$x_1$"""'], {'fontsize': '(18)'}), "('$x_1$', fontsize=18)\n", (9480, 9502), True, 'from matplotlib import pyplot as plt\n'), ((9509, 9550), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper left"""', 'fontsize': '(18)'}), "(loc='upper left', fontsize=18)\n", (9519, 9550), True, 'from matplotlib import pyplot as plt\n'), ((9556, 9570), 'matplotlib.pyplot.axis', 'plt.axis', (['axes'], {}), '(axes)\n', (9564, 9570), True, 'from matplotlib import pyplot as plt\n'), ((1505, 1526), 'numpy.linspace', 'np.linspace', (['(-4)', '(4)', '(9)'], {}), '(-4, 4, 9)\n', (1516, 1526), True, 'import numpy as np\n'), ((7661, 7675), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['""""""'], {}), "('')\n", (7671, 7675), True, 'from matplotlib import pyplot as plt\n'), ((7706, 7720), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['""""""'], {}), "('')\n", (7716, 7720), True, 'from matplotlib import pyplot as plt\n'), ((8339, 8359), 'numpy.random.rand', 'np.random.rand', (['m', '(1)'], {}), '(m, 1)\n', (8353, 8359), True, 'import numpy as np\n'), ((935, 951), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (949, 951), False, 'from sklearn.preprocessing import StandardScaler\n'), ((990, 1018), 'sklearn.svm.LinearSVC', 'LinearSVC', ([], {'C': '(1)', 'loss': '"""hinge"""'}), "(C=1, loss='hinge')\n", (999, 1018), False, 'from sklearn.svm import LinearSVC\n'), ((3796, 3824), 'sklearn.preprocessing.PolynomialFeatures', 'PolynomialFeatures', ([], {'degree': '(3)'}), '(degree=3)\n', (3814, 3824), False, 'from sklearn.preprocessing import PolynomialFeatures\n'), ((3870, 3886), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (3884, 3886), False, 'from sklearn.preprocessing import StandardScaler\n'), ((3933, 3962), 'sklearn.svm.LinearSVC', 'LinearSVC', ([], {'C': '(10)', 'loss': '"""hinge"""'}), "(C=10, loss='hinge')\n", (3942, 3962), False, 'from sklearn.svm import LinearSVC\n'), ((5486, 5502), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (5500, 5502), False, 'from sklearn.preprocessing import StandardScaler\n'), ((5550, 5592), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""poly"""', 'degree': '(3)', 'coef0': '(1)', 'C': '(5)'}), "(kernel='poly', degree=3, coef0=1, C=5)\n", (5553, 5592), False, 'from sklearn.svm import SVC\n'), ((5912, 5928), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (5926, 5928), False, 'from sklearn.preprocessing import StandardScaler\n'), ((5952, 5997), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""poly"""', 'degree': '(10)', 'coef0': '(100)', 'C': '(5)'}), "(kernel='poly', degree=10, coef0=100, C=5)\n", (5955, 5997), False, 'from sklearn.svm import SVC\n'), ((6720, 6736), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (6734, 6736), False, 'from sklearn.preprocessing import StandardScaler\n'), ((6760, 6795), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""rbf"""', 'gamma': '(5)', 'C': '(0.001)'}), "(kernel='rbf', gamma=5, C=0.001)\n", (6763, 6795), False, 'from sklearn.svm import SVC\n'), ((8011, 8032), 'numpy.random.randn', 'np.random.randn', (['m', '(1)'], {}), '(m, 1)\n', (8026, 8032), True, 'import numpy as np\n'), ((9095, 9129), 'numpy.linspace', 'np.linspace', (['axes[0]', 'axes[1]', '(100)'], {}), '(axes[0], axes[1], 100)\n', (9106, 9129), True, 'import numpy as np\n'), ((2663, 2672), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (2670, 2672), True, 'from matplotlib import pyplot as plt\n'), ((7093, 7109), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (7107, 7109), False, 'from sklearn.preprocessing import StandardScaler\n'), ((7137, 7172), 'sklearn.svm.SVC', 'SVC', ([], {'kernel': '"""rbf"""', 'gamma': 'gamma', 'C': 'C'}), "(kernel='rbf', gamma=gamma, C=C)\n", (7140, 7172), False, 'from sklearn.svm import SVC\n'), ((8399, 8420), 'numpy.random.randn', 'np.random.randn', (['m', '(1)'], {}), '(m, 1)\n', (8414, 8420), True, 'import numpy as np\n')]
from __future__ import absolute_import from collections import deque import gym import tensorflow as tf import numpy as np from src.image_processing import stack_frames env = gym.make("airsim_gym:airsim-regular-v0") STATE_SIZE = [256, 256, 4] ACTION_SIZE = env.action_space.n STACK_SIZE = 64 env.reset() model = tf.keras.models.load_model("model") stacked_frames = deque([np.zeros(STATE_SIZE[:2], dtype=np.int) for i in range(STACK_SIZE)], maxlen=4) for i in range(1): done = False env.reset() observation, position = env.get_state() observation, stacked_frames = stack_frames(stacked_frames, observation, True) while not done: # Take the biggest Q value (= the best action) observation = np.array(observation) position = np.array(position) observation = observation.reshape(1, *observation.shape) position = position.reshape(1, *position.shape) Qs = model.predict([observation, position]) # Take the biggest Q value (= the best action) action = np.argmax(Qs) state, position, reward, done = env.step(action) if not done: next_observation, position = env.step(action) next_observation, stacked_frames = stack_frames( stacked_frames, next_observation, False) state = next_observation
[ "numpy.argmax", "numpy.array", "numpy.zeros", "tensorflow.keras.models.load_model", "src.image_processing.stack_frames", "gym.make" ]
[((178, 218), 'gym.make', 'gym.make', (['"""airsim_gym:airsim-regular-v0"""'], {}), "('airsim_gym:airsim-regular-v0')\n", (186, 218), False, 'import gym\n'), ((318, 353), 'tensorflow.keras.models.load_model', 'tf.keras.models.load_model', (['"""model"""'], {}), "('model')\n", (344, 353), True, 'import tensorflow as tf\n'), ((589, 636), 'src.image_processing.stack_frames', 'stack_frames', (['stacked_frames', 'observation', '(True)'], {}), '(stacked_frames, observation, True)\n', (601, 636), False, 'from src.image_processing import stack_frames\n'), ((378, 416), 'numpy.zeros', 'np.zeros', (['STATE_SIZE[:2]'], {'dtype': 'np.int'}), '(STATE_SIZE[:2], dtype=np.int)\n', (386, 416), True, 'import numpy as np\n'), ((735, 756), 'numpy.array', 'np.array', (['observation'], {}), '(observation)\n', (743, 756), True, 'import numpy as np\n'), ((776, 794), 'numpy.array', 'np.array', (['position'], {}), '(position)\n', (784, 794), True, 'import numpy as np\n'), ((1042, 1055), 'numpy.argmax', 'np.argmax', (['Qs'], {}), '(Qs)\n', (1051, 1055), True, 'import numpy as np\n'), ((1241, 1294), 'src.image_processing.stack_frames', 'stack_frames', (['stacked_frames', 'next_observation', '(False)'], {}), '(stacked_frames, next_observation, False)\n', (1253, 1294), False, 'from src.image_processing import stack_frames\n')]
#!/usr/bin/env python3 import pytest import isce3.ext.isce3.geometry as m from isce3.ext.isce3.core import DataInterpMethod from isce3.geometry import DEMInterpolator from isce3.io import Raster import iscetest import os import collections as cl import numpy.testing as npt from osgeo import gdal def dem_info_from_gdal(file_raster: str) -> cl.namedtuple: """Get shape, min, max, mean of dem""" dset = gdal.Open(file_raster, gdal.GA_ReadOnly) band = dset.GetRasterBand(1) dem = band.ReadAsArray() return cl.namedtuple('dem_info', 'shape min max mean')( dem.shape, dem.min(), dem.max(), dem.mean()) def test_constructor_ref_height(): href = 10. dem = DEMInterpolator() dem.ref_height = href assert dem.ref_height == href dem = DEMInterpolator(href) assert dem.ref_height == href assert dem.interpolate_xy(0, 0) == href assert dem.interpolate_lonlat(0, 0) == href npt.assert_equal(dem.have_raster, False) def test_constructor_raster_obj(): # filename of the DEM ratster filename_dem = 'dem_himalayas_E81p5_N28p3_short.tiff' file_raster = os.path.join(iscetest.data, filename_dem) # get some DEM info via gdal to be used as a reference for V&V dem_info = dem_info_from_gdal(file_raster) # build DEM object raster_obj = Raster(file_raster) dem_obj = DEMInterpolator(raster_obj) # validate existence and details of DEM data npt.assert_equal(dem_obj.have_raster, True, err_msg='No DEM ratser data') npt.assert_equal(dem_obj.data.shape, dem_info.shape, err_msg='Wrong shape of DEM ratser data') npt.assert_allclose(dem_obj.data.min(), dem_info.min, err_msg='Wrong min DEM height') npt.assert_allclose(dem_obj.data.max(), dem_info.max, err_msg='Wrong max DEM height') npt.assert_allclose(dem_obj.data.mean(), dem_info.mean, err_msg='Wrong mean DEM height') def test_methods(): # pybind11::enum_ is not iterable for name in "SINC BILINEAR BICUBIC NEAREST BIQUINTIC".split(): # enum constructor method = getattr(DataInterpMethod, name) dem = DEMInterpolator(method=method) assert dem.interp_method == method # string constructor dem = DEMInterpolator(method=name) assert dem.interp_method == method dem = DEMInterpolator(method="bicubic") assert dem.interp_method == DataInterpMethod.BICUBIC dem = DEMInterpolator(method="biCUBic") assert dem.interp_method == DataInterpMethod.BICUBIC with pytest.raises(ValueError): dem = DEMInterpolator(method="TigerKing")
[ "osgeo.gdal.Open", "isce3.io.Raster", "collections.namedtuple", "numpy.testing.assert_equal", "os.path.join", "isce3.geometry.DEMInterpolator", "pytest.raises" ]
[((414, 454), 'osgeo.gdal.Open', 'gdal.Open', (['file_raster', 'gdal.GA_ReadOnly'], {}), '(file_raster, gdal.GA_ReadOnly)\n', (423, 454), False, 'from osgeo import gdal\n'), ((693, 710), 'isce3.geometry.DEMInterpolator', 'DEMInterpolator', ([], {}), '()\n', (708, 710), False, 'from isce3.geometry import DEMInterpolator\n'), ((782, 803), 'isce3.geometry.DEMInterpolator', 'DEMInterpolator', (['href'], {}), '(href)\n', (797, 803), False, 'from isce3.geometry import DEMInterpolator\n'), ((936, 976), 'numpy.testing.assert_equal', 'npt.assert_equal', (['dem.have_raster', '(False)'], {}), '(dem.have_raster, False)\n', (952, 976), True, 'import numpy.testing as npt\n'), ((1124, 1165), 'os.path.join', 'os.path.join', (['iscetest.data', 'filename_dem'], {}), '(iscetest.data, filename_dem)\n', (1136, 1165), False, 'import os\n'), ((1320, 1339), 'isce3.io.Raster', 'Raster', (['file_raster'], {}), '(file_raster)\n', (1326, 1339), False, 'from isce3.io import Raster\n'), ((1354, 1381), 'isce3.geometry.DEMInterpolator', 'DEMInterpolator', (['raster_obj'], {}), '(raster_obj)\n', (1369, 1381), False, 'from isce3.geometry import DEMInterpolator\n'), ((1435, 1508), 'numpy.testing.assert_equal', 'npt.assert_equal', (['dem_obj.have_raster', '(True)'], {'err_msg': '"""No DEM ratser data"""'}), "(dem_obj.have_raster, True, err_msg='No DEM ratser data')\n", (1451, 1508), True, 'import numpy.testing as npt\n'), ((1513, 1612), 'numpy.testing.assert_equal', 'npt.assert_equal', (['dem_obj.data.shape', 'dem_info.shape'], {'err_msg': '"""Wrong shape of DEM ratser data"""'}), "(dem_obj.data.shape, dem_info.shape, err_msg=\n 'Wrong shape of DEM ratser data')\n", (1529, 1612), True, 'import numpy.testing as npt\n'), ((2391, 2424), 'isce3.geometry.DEMInterpolator', 'DEMInterpolator', ([], {'method': '"""bicubic"""'}), "(method='bicubic')\n", (2406, 2424), False, 'from isce3.geometry import DEMInterpolator\n'), ((2493, 2526), 'isce3.geometry.DEMInterpolator', 'DEMInterpolator', ([], {'method': '"""biCUBic"""'}), "(method='biCUBic')\n", (2508, 2526), False, 'from isce3.geometry import DEMInterpolator\n'), ((528, 575), 'collections.namedtuple', 'cl.namedtuple', (['"""dem_info"""', '"""shape min max mean"""'], {}), "('dem_info', 'shape min max mean')\n", (541, 575), True, 'import collections as cl\n'), ((2191, 2221), 'isce3.geometry.DEMInterpolator', 'DEMInterpolator', ([], {'method': 'method'}), '(method=method)\n', (2206, 2221), False, 'from isce3.geometry import DEMInterpolator\n'), ((2308, 2336), 'isce3.geometry.DEMInterpolator', 'DEMInterpolator', ([], {'method': 'name'}), '(method=name)\n', (2323, 2336), False, 'from isce3.geometry import DEMInterpolator\n'), ((2594, 2619), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2607, 2619), False, 'import pytest\n'), ((2635, 2670), 'isce3.geometry.DEMInterpolator', 'DEMInterpolator', ([], {'method': '"""TigerKing"""'}), "(method='TigerKing')\n", (2650, 2670), False, 'from isce3.geometry import DEMInterpolator\n')]
import os import tensorflow as tf import numpy as np class DataLoader: def __init__(self, dataset_info, alternate_source=None, batch_size=16): self.batch_size = batch_size self.dataset_info = dataset_info self._load_data(alternate_source) def _load_data(self, alternate_source): found = True for file in self.dataset_info.filenames: if not os.path.isfile(file): found = False print("TFRecords not found for file: " + file) if not found: (train_x, train_y), (test_x, test_y) = alternate_source() train_x = train_x.astype(np.float32) test_x = test_x.astype(np.float32) n_mean = np.mean(train_x) n_max = np.max(train_x) n_min = np.min(train_x) train_x = (train_x - n_mean) / (n_max - n_min) test_x = (test_x - n_mean) / (n_max - n_min) DataLoader._create_tf_record(images=train_x, labels=train_y, path=self.dataset_info.filenames[0]) DataLoader._create_tf_record(images=test_x, labels=test_y, path=self.dataset_info.filenames[1]) def get_dataset(self): train = tf.data.TFRecordDataset(self.dataset_info.filenames[0]) test = tf.data.TFRecordDataset(self.dataset_info.filenames[1]) train = train.shuffle(10000, seed=10) train = train.apply( tf.data.experimental.map_and_batch(self._parse_example, batch_size=self.batch_size, num_parallel_batches=3) ) train = train.prefetch(100) test = test.shuffle(10000, seed=10) test = test.apply( tf.data.experimental.map_and_batch(self._parse_example, batch_size=self.batch_size, num_parallel_batches=3) ) test = test.prefetch(100) return train, test @staticmethod def _create_tf_record(images, labels, path): with tf.python_io.TFRecordWriter(path) as writer: for i in range(images.shape[0]): img = images[i].tostring() label = labels[i] features = tf.train.Features( feature={ 'image': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img])), 'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[label])) } ) example = tf.train.Example(features=features) serialized = example.SerializeToString() writer.write(serialized) def _parse_example(self, serialized): features = {'image': (tf.FixedLenFeature((), tf.string, default_value="")), 'label': (tf.FixedLenFeature((), tf.int64, default_value=0))} parsed = tf.parse_single_example(serialized=serialized, features=features) raw_image = parsed['image'] image = tf.decode_raw(raw_image, tf.float32) label = tf.one_hot(parsed['label'], self.dataset_info.num_labels) return tf.reshape(image, self.dataset_info.shapes), label
[ "tensorflow.data.TFRecordDataset", "numpy.mean", "tensorflow.one_hot", "tensorflow.data.experimental.map_and_batch", "tensorflow.train.Example", "tensorflow.reshape", "tensorflow.parse_single_example", "tensorflow.decode_raw", "tensorflow.python_io.TFRecordWriter", "numpy.max", "os.path.isfile",...
[((1198, 1253), 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['self.dataset_info.filenames[0]'], {}), '(self.dataset_info.filenames[0])\n', (1221, 1253), True, 'import tensorflow as tf\n'), ((1269, 1324), 'tensorflow.data.TFRecordDataset', 'tf.data.TFRecordDataset', (['self.dataset_info.filenames[1]'], {}), '(self.dataset_info.filenames[1])\n', (1292, 1324), True, 'import tensorflow as tf\n'), ((2774, 2839), 'tensorflow.parse_single_example', 'tf.parse_single_example', ([], {'serialized': 'serialized', 'features': 'features'}), '(serialized=serialized, features=features)\n', (2797, 2839), True, 'import tensorflow as tf\n'), ((2892, 2928), 'tensorflow.decode_raw', 'tf.decode_raw', (['raw_image', 'tf.float32'], {}), '(raw_image, tf.float32)\n', (2905, 2928), True, 'import tensorflow as tf\n'), ((2945, 3002), 'tensorflow.one_hot', 'tf.one_hot', (["parsed['label']", 'self.dataset_info.num_labels'], {}), "(parsed['label'], self.dataset_info.num_labels)\n", (2955, 3002), True, 'import tensorflow as tf\n'), ((730, 746), 'numpy.mean', 'np.mean', (['train_x'], {}), '(train_x)\n', (737, 746), True, 'import numpy as np\n'), ((767, 782), 'numpy.max', 'np.max', (['train_x'], {}), '(train_x)\n', (773, 782), True, 'import numpy as np\n'), ((803, 818), 'numpy.min', 'np.min', (['train_x'], {}), '(train_x)\n', (809, 818), True, 'import numpy as np\n'), ((1413, 1525), 'tensorflow.data.experimental.map_and_batch', 'tf.data.experimental.map_and_batch', (['self._parse_example'], {'batch_size': 'self.batch_size', 'num_parallel_batches': '(3)'}), '(self._parse_example, batch_size=self.\n batch_size, num_parallel_batches=3)\n', (1447, 1525), True, 'import tensorflow as tf\n'), ((1651, 1763), 'tensorflow.data.experimental.map_and_batch', 'tf.data.experimental.map_and_batch', (['self._parse_example'], {'batch_size': 'self.batch_size', 'num_parallel_batches': '(3)'}), '(self._parse_example, batch_size=self.\n batch_size, num_parallel_batches=3)\n', (1685, 1763), True, 'import tensorflow as tf\n'), ((1912, 1945), 'tensorflow.python_io.TFRecordWriter', 'tf.python_io.TFRecordWriter', (['path'], {}), '(path)\n', (1939, 1945), True, 'import tensorflow as tf\n'), ((2620, 2671), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['()', 'tf.string'], {'default_value': '""""""'}), "((), tf.string, default_value='')\n", (2638, 2671), True, 'import tensorflow as tf\n'), ((2704, 2753), 'tensorflow.FixedLenFeature', 'tf.FixedLenFeature', (['()', 'tf.int64'], {'default_value': '(0)'}), '((), tf.int64, default_value=0)\n', (2722, 2753), True, 'import tensorflow as tf\n'), ((3018, 3061), 'tensorflow.reshape', 'tf.reshape', (['image', 'self.dataset_info.shapes'], {}), '(image, self.dataset_info.shapes)\n', (3028, 3061), True, 'import tensorflow as tf\n'), ((404, 424), 'os.path.isfile', 'os.path.isfile', (['file'], {}), '(file)\n', (418, 424), False, 'import os\n'), ((2413, 2448), 'tensorflow.train.Example', 'tf.train.Example', ([], {'features': 'features'}), '(features=features)\n', (2429, 2448), True, 'import tensorflow as tf\n'), ((2217, 2248), 'tensorflow.train.BytesList', 'tf.train.BytesList', ([], {'value': '[img]'}), '(value=[img])\n', (2235, 2248), True, 'import tensorflow as tf\n'), ((2312, 2345), 'tensorflow.train.Int64List', 'tf.train.Int64List', ([], {'value': '[label]'}), '(value=[label])\n', (2330, 2345), True, 'import tensorflow as tf\n')]
import csv import json import numpy as np import pandas as pd from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics import accuracy_score, classification_report from sklearn.model_selection import train_test_split from sklearn.multiclass import OneVsRestClassifier from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline from sklearn.preprocessing import MultiLabelBinarizer with open('index_to_code.json') as f: index_to_code = json.load(f) with open('index_to_topics.json') as f: index_to_topics = json.load(f) with open('all_topics.json') as f: topics = json.load(f) index_to_code = {int(k): v for k, v in index_to_code.items()} index_to_topics = {int(k): v for k, v in index_to_topics.items()} code_train, code_test, topic_train, topic_test = train_test_split(index_to_code, index_to_topics, random_state=42, test_size=0.33, shuffle=True) train_df = pd.DataFrame({'code': pd.Series(code_train), 'topic': pd.Series(topic_train)}) test_df = pd.DataFrame({'code': pd.Series(code_test), 'topic': pd.Series(topic_test)}) tr = train_df.drop_duplicates() OneVsTheRest = Pipeline([ ('tfidf', TfidfVectorizer()), ('clf', OneVsRestClassifier(MultinomialNB( fit_prior=False, class_prior=None))), ]) topicss = dict.fromkeys(topics, 0) k = 0 for topic in topicss.keys(): topicss[topic] = k k += 1 topics_train = list(train_df['topic']) topics_test = list(test_df['topic']) codes = np.array(train_df['code']) MLB = MultiLabelBinarizer() topics_train = MLB.fit_transform(topics_train) OneVsTheRest.fit(codes, topics_train) prediction = OneVsTheRest.predict(np.array(test_df['code'])) print('Test accuracy: {}'.format(accuracy_score(MultiLabelBinarizer().fit_transform(topics_test), prediction))) target_names = [t for t in topicss.values()] print(classification_report(MultiLabelBinarizer().fit_transform(topics_test), prediction), labels=target_names) # print(MLB.inverse_transform(prediction)) # print('-------') # print(test_df['topic']) prediction = MLB.inverse_transform(prediction) # prediction = [list(elem) for elem in prediction] # print(classification_report(topics_test, prediction)) with open("predicted.txt", "w") as f: wr = csv.writer(f) wr.writerows(prediction) with open("actual.txt", "w") as f: wr = csv.writer(f) wr.writerows(topics_test) def intersect(a, b): sb = set(b) bs = [val for val in a if val in sb] return bs # if (predicted intersection with test) >= 80% of test value then True def moreThan80Percents(list1, list2): list1 = sorted(list1) list2 = sorted(list2) list3 = intersect(list1, list2) leninter = len(list3) if leninter >= 0.8 * len(list2): return True return False matches = 0 for pred, val in zip(prediction, topics_test): if (moreThan80Percents(pred, val)): matches += 1 print("Test accuracy (80%) : " + str(matches / len(prediction)))
[ "pandas.Series", "sklearn.model_selection.train_test_split", "csv.writer", "numpy.array", "sklearn.feature_extraction.text.TfidfVectorizer", "sklearn.naive_bayes.MultinomialNB", "json.load", "sklearn.preprocessing.MultiLabelBinarizer" ]
[((817, 917), 'sklearn.model_selection.train_test_split', 'train_test_split', (['index_to_code', 'index_to_topics'], {'random_state': '(42)', 'test_size': '(0.33)', 'shuffle': '(True)'}), '(index_to_code, index_to_topics, random_state=42, test_size\n =0.33, shuffle=True)\n', (833, 917), False, 'from sklearn.model_selection import train_test_split\n'), ((1537, 1563), 'numpy.array', 'np.array', (["train_df['code']"], {}), "(train_df['code'])\n", (1545, 1563), True, 'import numpy as np\n'), ((1571, 1592), 'sklearn.preprocessing.MultiLabelBinarizer', 'MultiLabelBinarizer', ([], {}), '()\n', (1590, 1592), False, 'from sklearn.preprocessing import MultiLabelBinarizer\n'), ((490, 502), 'json.load', 'json.load', (['f'], {}), '(f)\n', (499, 502), False, 'import json\n'), ((565, 577), 'json.load', 'json.load', (['f'], {}), '(f)\n', (574, 577), False, 'import json\n'), ((626, 638), 'json.load', 'json.load', (['f'], {}), '(f)\n', (635, 638), False, 'import json\n'), ((1712, 1737), 'numpy.array', 'np.array', (["test_df['code']"], {}), "(test_df['code'])\n", (1720, 1737), True, 'import numpy as np\n'), ((2299, 2312), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (2309, 2312), False, 'import csv\n'), ((2387, 2400), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (2397, 2400), False, 'import csv\n'), ((1013, 1034), 'pandas.Series', 'pd.Series', (['code_train'], {}), '(code_train)\n', (1022, 1034), True, 'import pandas as pd\n'), ((1045, 1067), 'pandas.Series', 'pd.Series', (['topic_train'], {}), '(topic_train)\n', (1054, 1067), True, 'import pandas as pd\n'), ((1102, 1122), 'pandas.Series', 'pd.Series', (['code_test'], {}), '(code_test)\n', (1111, 1122), True, 'import pandas as pd\n'), ((1133, 1154), 'pandas.Series', 'pd.Series', (['topic_test'], {}), '(topic_test)\n', (1142, 1154), True, 'import pandas as pd\n'), ((1231, 1248), 'sklearn.feature_extraction.text.TfidfVectorizer', 'TfidfVectorizer', ([], {}), '()\n', (1246, 1248), False, 'from sklearn.feature_extraction.text import TfidfVectorizer\n'), ((1283, 1331), 'sklearn.naive_bayes.MultinomialNB', 'MultinomialNB', ([], {'fit_prior': '(False)', 'class_prior': 'None'}), '(fit_prior=False, class_prior=None)\n', (1296, 1331), False, 'from sklearn.naive_bayes import MultinomialNB\n'), ((1924, 1945), 'sklearn.preprocessing.MultiLabelBinarizer', 'MultiLabelBinarizer', ([], {}), '()\n', (1943, 1945), False, 'from sklearn.preprocessing import MultiLabelBinarizer\n'), ((1787, 1808), 'sklearn.preprocessing.MultiLabelBinarizer', 'MultiLabelBinarizer', ([], {}), '()\n', (1806, 1808), False, 'from sklearn.preprocessing import MultiLabelBinarizer\n')]
import glob import json import itertools import numpy as np import tifffile import zarr from numcodecs import Blosc import os import tqdm """ Default chunk size is (64, 64, 64) """ class ZarrStack: def __init__(self, src, dest, compressor=None): """ :param src: glob for tiffs or a zarr store :param dest: the destination folder for zarr arrays :param compressor: numcodecs compressor to use on eachj chunk. Default is Zstd level 1 with bitshuffle """ self.files = None self.z_arr = None if isinstance(src, str): # Assume it's a glob if src is a string self.files = sorted(glob.glob(src)) self.z_extent = len(self.files) img0 = tifffile.imread(self.files[0]) self.y_extent, self.x_extent = img0.shape self.dtype = img0.dtype elif isinstance(src, zarr.NestedDirectoryStore): self.z_arr = zarr.open(src, mode='r') self.z_extent, self.y_extent, self.x_extent = self.z_arr.shape self.dtype = self.z_arr.dtype else: raise ValueError('Unrecognized data source for ZarrStack') self.dest = dest if compressor is None: self.compressor = Blosc(cname='zstd', clevel=1, shuffle=Blosc.BITSHUFFLE) else: self.compressor = compressor def resolution(self, level): """The pixel resolution at a given level :param level: 1 to N, the mipmap level :returns: the number of pixels at the base level per pixel at this level """ return 2 ** (level - 1) def n_x(self, level): """The number of blocks in the X direction at the given level :param level: mipmap level, starting at 1 :return: # of blocks in the X direction """ resolution = self.resolution(level) return (self.x_extent // resolution + 63) // 64 def x0(self, level): """The starting X coordinates at a particular level :param level: 1 to N :return: an array of starting X coordinates """ resolution = self.resolution(level) return np.arange(0, (self.x_extent + resolution - 1) // resolution, 64) def x1(self, level): """The ending X coordinates at a particular level :param level: the mipmap level (1 to N) :return: an array of ending X coordinates """ resolution = self.resolution(level) x1 = self.x0(level) + 64 x1[-1] = (self.x_extent + resolution - 1) // resolution return x1 def n_y(self, level): """The number of blocks in the Y direction at the given level :param level: mipmap level, starting at 1 :return: # of blocks in the Y direction """ resolution = self.resolution(level) return (self.y_extent // resolution + 63) // 64 def y0(self, level): """The starting Y coordinates at a particular level :param level: 1 to N :return: an array of starting Y coordinates """ resolution = self.resolution(level) return np.arange(0, (self.y_extent + resolution - 1) // resolution, 64) def y1(self, level): """The ending Y coordinates at a particular level :param level: the mipmap level (1 to N) :return: an array of ending Y coordinates """ resolution = self.resolution(level) y1 = self.y0(level) + 64 y1[-1] = (self.y_extent + resolution - 1) // resolution return y1 def n_z(self, level): """The number of blocks in the Z direction at the given level :param level: mipmap level, starting at 1 :return: # of blocks in the Z direction """ resolution = self.resolution(level) return (self.z_extent // resolution + 63) // 64 def z0(self, level): """The starting Z coordinates at a particular level :param level: 1 to N :return: an array of starting Z coordinates """ resolution = self.resolution(level) return np.arange(0, (self.z_extent + resolution - 1) // resolution, 64) def z1(self, level): """The ending Z coordinates at a particular level :param level: the mipmap level (1 to N) :return: an array of ending Z coordinates """ resolution = self.resolution(level) z1 = self.z0(level) + 64 z1[-1] = (self.z_extent + resolution - 1) // resolution return z1 def write_info_file(self, n_levels, voxel_size=(1800, 1800, 2000)): """Write the precomputed info file that defines the volume :param n_levels: the number of levels to be written """ if not os.path.exists(self.dest): os.mkdir(self.dest) d = dict(data_type = self.dtype.name, mesh="mesh", num_channels=1, type="image") scales = [] z_extent = self.z_extent y_extent = self.y_extent x_extent = self.x_extent for level in range(1, n_levels + 1): resolution = self.resolution(level) scales.append( dict(chunk_sizes=[[64, 64, 64]], encoding="raw", key="%d_%d_%d" % (resolution, resolution, resolution), resolution=[resolution * _ for _ in voxel_size], size=[x_extent, y_extent, z_extent], voxel_offset=[0, 0, 0])) z_extent = (z_extent + 1) // 2 y_extent = (y_extent + 1) // 2 x_extent = (x_extent + 1) // 2 d["scales"] = scales with open(os.path.join(self.dest, "info"), "w") as fd: json.dump(d, fd, indent=2, sort_keys=True) def write_level_1(self, silent=False): """Write the first mipmap level, loading from tiff planes""" dest_lvl1 = os.path.join(self.dest, "1_1_1") store = zarr.NestedDirectoryStore(dest_lvl1) z_arr_1 = zarr.open(store, mode='w', chunks=(64, 64, 64), dtype=self.dtype, shape=(self.z_extent, self.y_extent, self.x_extent), compression=self.compressor) z0 = self.z0(1) z1 = self.z1(1) y0 = self.y0(1) y1 = self.y1(1) x0 = self.x0(1) x1 = self.x1(1) if self.files is not None: for z0a, z1a in tqdm.tqdm(zip(z0, z1), total=len(z0), disable=silent): img = np.zeros((z1a-z0a, y1[-1], x1[-1]), self.dtype) for z in range(z0a, z1a): img[z-z0a] = tifffile.imread(self.files[z]) z_arr_1[z0a:z1a] = img elif self.z_arr is not None: # need to decompress to re-chunk the original store for z0a, z1a in tqdm.tqdm(zip(z0, z1), total=len(z0), disable=silent): z_arr_1[z0a:z1a] = self.z_arr[z0a:z1a] def write_level_n(self, level, silent=False): src_resolution = self.resolution(level - 1) dest_resolution = self.resolution(level) src = os.path.join( self.dest, "%d_%d_%d" % (src_resolution, src_resolution, src_resolution)) dest = os.path.join( self.dest, "%d_%d_%d" % (dest_resolution, dest_resolution, dest_resolution)) src_store = zarr.NestedDirectoryStore(src) src_zarr = zarr.open(src_store, mode='r') dest_store = zarr.NestedDirectoryStore(dest) dest_zarr = zarr.open(dest_store, mode='w', chunks=(64, 64, 64), dtype=self.dtype, shape=(self.z1(level)[-1], self.y1(level)[-1], self.x1(level)[-1]), compression=self.compressor) z0s = self.z0(level - 1) # source block coordinates z1s = self.z1(level - 1) y0s = self.y0(level - 1) y1s = self.y1(level - 1) x0s = self.x0(level - 1) x1s = self.x1(level - 1) z0d = self.z0(level) # dest block coordinates z1d = self.z1(level) y0d = self.y0(level) y1d = self.y1(level) x0d = self.x0(level) x1d = self.x1(level) for xidx, yidx, zidx in tqdm.tqdm(list(itertools.product( range(self.n_x(level)), range(self.n_y(level)), range(self.n_z(level)))), disable=silent): # looping over destination block indicies (fewer blocks than source) block = np.zeros((z1d[zidx] - z0d[zidx], y1d[yidx] - y0d[yidx], x1d[xidx] - x0d[xidx]), np.uint64) hits = np.zeros((z1d[zidx] - z0d[zidx], y1d[yidx] - y0d[yidx], x1d[xidx] - x0d[xidx]), np.uint64) for xsi1, ysi1, zsi1 in itertools.product((0, 1), (0, 1), (0, 1)): # looping over source blocks for this destination xsi = xsi1 + xidx * 2 if xsi == self.n_x(level-1): # Check for any source blocks that are out-of-bounds continue ysi = ysi1 + yidx * 2 if ysi == self.n_y(level-1): continue zsi = zsi1 + zidx * 2 if zsi == self.n_z(level-1): continue src_block = src_zarr[z0s[zsi]:z1s[zsi], y0s[ysi]:y1s[ysi], x0s[xsi]:x1s[xsi]] for offx, offy, offz in \ itertools.product((0, 1), (0, 1), (0,1)): dsblock = src_block[offz::2, offy::2, offx::2] block[zsi1*32:zsi1*32 + dsblock.shape[0], ysi1*32:ysi1*32 + dsblock.shape[1], xsi1*32:xsi1*32 + dsblock.shape[2]] += \ dsblock.astype(block.dtype) # 32 is half-block size of source hits[zsi1*32:zsi1*32 + dsblock.shape[0], ysi1*32:ysi1*32 + dsblock.shape[1], xsi1*32:xsi1*32 + dsblock.shape[2]] += 1 block[hits > 0] = block[hits > 0] // hits[hits > 0] dest_zarr[z0d[zidx]:z1d[zidx], y0d[yidx]:y1d[yidx], x0d[xidx]:x1d[xidx]] = block
[ "os.path.exists", "tifffile.imread", "zarr.NestedDirectoryStore", "json.dump", "os.path.join", "itertools.product", "numpy.zeros", "zarr.open", "os.mkdir", "glob.glob", "numcodecs.Blosc", "numpy.arange" ]
[((2184, 2248), 'numpy.arange', 'np.arange', (['(0)', '((self.x_extent + resolution - 1) // resolution)', '(64)'], {}), '(0, (self.x_extent + resolution - 1) // resolution, 64)\n', (2193, 2248), True, 'import numpy as np\n'), ((3150, 3214), 'numpy.arange', 'np.arange', (['(0)', '((self.y_extent + resolution - 1) // resolution)', '(64)'], {}), '(0, (self.y_extent + resolution - 1) // resolution, 64)\n', (3159, 3214), True, 'import numpy as np\n'), ((4116, 4180), 'numpy.arange', 'np.arange', (['(0)', '((self.z_extent + resolution - 1) // resolution)', '(64)'], {}), '(0, (self.z_extent + resolution - 1) // resolution, 64)\n', (4125, 4180), True, 'import numpy as np\n'), ((5946, 5978), 'os.path.join', 'os.path.join', (['self.dest', '"""1_1_1"""'], {}), "(self.dest, '1_1_1')\n", (5958, 5978), False, 'import os\n'), ((5995, 6031), 'zarr.NestedDirectoryStore', 'zarr.NestedDirectoryStore', (['dest_lvl1'], {}), '(dest_lvl1)\n', (6020, 6031), False, 'import zarr\n'), ((6051, 6203), 'zarr.open', 'zarr.open', (['store'], {'mode': '"""w"""', 'chunks': '(64, 64, 64)', 'dtype': 'self.dtype', 'shape': '(self.z_extent, self.y_extent, self.x_extent)', 'compression': 'self.compressor'}), "(store, mode='w', chunks=(64, 64, 64), dtype=self.dtype, shape=(\n self.z_extent, self.y_extent, self.x_extent), compression=self.compressor)\n", (6060, 6203), False, 'import zarr\n'), ((7213, 7303), 'os.path.join', 'os.path.join', (['self.dest', "('%d_%d_%d' % (src_resolution, src_resolution, src_resolution))"], {}), "(self.dest, '%d_%d_%d' % (src_resolution, src_resolution,\n src_resolution))\n", (7225, 7303), False, 'import os\n'), ((7340, 7433), 'os.path.join', 'os.path.join', (['self.dest', "('%d_%d_%d' % (dest_resolution, dest_resolution, dest_resolution))"], {}), "(self.dest, '%d_%d_%d' % (dest_resolution, dest_resolution,\n dest_resolution))\n", (7352, 7433), False, 'import os\n'), ((7476, 7506), 'zarr.NestedDirectoryStore', 'zarr.NestedDirectoryStore', (['src'], {}), '(src)\n', (7501, 7506), False, 'import zarr\n'), ((7526, 7556), 'zarr.open', 'zarr.open', (['src_store'], {'mode': '"""r"""'}), "(src_store, mode='r')\n", (7535, 7556), False, 'import zarr\n'), ((7579, 7610), 'zarr.NestedDirectoryStore', 'zarr.NestedDirectoryStore', (['dest'], {}), '(dest)\n', (7604, 7610), False, 'import zarr\n'), ((746, 776), 'tifffile.imread', 'tifffile.imread', (['self.files[0]'], {}), '(self.files[0])\n', (761, 776), False, 'import tifffile\n'), ((1262, 1317), 'numcodecs.Blosc', 'Blosc', ([], {'cname': '"""zstd"""', 'clevel': '(1)', 'shuffle': 'Blosc.BITSHUFFLE'}), "(cname='zstd', clevel=1, shuffle=Blosc.BITSHUFFLE)\n", (1267, 1317), False, 'from numcodecs import Blosc\n'), ((4763, 4788), 'os.path.exists', 'os.path.exists', (['self.dest'], {}), '(self.dest)\n', (4777, 4788), False, 'import os\n'), ((4802, 4821), 'os.mkdir', 'os.mkdir', (['self.dest'], {}), '(self.dest)\n', (4810, 4821), False, 'import os\n'), ((5770, 5812), 'json.dump', 'json.dump', (['d', 'fd'], {'indent': '(2)', 'sort_keys': '(True)'}), '(d, fd, indent=2, sort_keys=True)\n', (5779, 5812), False, 'import json\n'), ((8762, 8857), 'numpy.zeros', 'np.zeros', (['(z1d[zidx] - z0d[zidx], y1d[yidx] - y0d[yidx], x1d[xidx] - x0d[xidx])', 'np.uint64'], {}), '((z1d[zidx] - z0d[zidx], y1d[yidx] - y0d[yidx], x1d[xidx] - x0d[\n xidx]), np.uint64)\n', (8770, 8857), True, 'import numpy as np\n'), ((8932, 9027), 'numpy.zeros', 'np.zeros', (['(z1d[zidx] - z0d[zidx], y1d[yidx] - y0d[yidx], x1d[xidx] - x0d[xidx])', 'np.uint64'], {}), '((z1d[zidx] - z0d[zidx], y1d[yidx] - y0d[yidx], x1d[xidx] - x0d[\n xidx]), np.uint64)\n', (8940, 9027), True, 'import numpy as np\n'), ((9117, 9158), 'itertools.product', 'itertools.product', (['(0, 1)', '(0, 1)', '(0, 1)'], {}), '((0, 1), (0, 1), (0, 1))\n', (9134, 9158), False, 'import itertools\n'), ((667, 681), 'glob.glob', 'glob.glob', (['src'], {}), '(src)\n', (676, 681), False, 'import glob\n'), ((949, 973), 'zarr.open', 'zarr.open', (['src'], {'mode': '"""r"""'}), "(src, mode='r')\n", (958, 973), False, 'import zarr\n'), ((5713, 5744), 'os.path.join', 'os.path.join', (['self.dest', '"""info"""'], {}), "(self.dest, 'info')\n", (5725, 5744), False, 'import os\n'), ((6625, 6674), 'numpy.zeros', 'np.zeros', (['(z1a - z0a, y1[-1], x1[-1])', 'self.dtype'], {}), '((z1a - z0a, y1[-1], x1[-1]), self.dtype)\n', (6633, 6674), True, 'import numpy as np\n'), ((9837, 9878), 'itertools.product', 'itertools.product', (['(0, 1)', '(0, 1)', '(0, 1)'], {}), '((0, 1), (0, 1), (0, 1))\n', (9854, 9878), False, 'import itertools\n'), ((6748, 6778), 'tifffile.imread', 'tifffile.imread', (['self.files[z]'], {}), '(self.files[z])\n', (6763, 6778), False, 'import tifffile\n')]
import numpy as np import cv2 import pickle class LoadData: ''' Class to laod the data ''' def __init__(self, data_dir, classes, h): ''' :param data_dir: directory where the dataset is kept :param classes: number of classes in the dataset :param cached_data_file: location where cached file has to be stored :param normVal: normalization value, as defined in ERFNet paper ''' self.data_dir = data_dir self.classes = classes self.h = h def compute_class_weights(self, histogram): ''' Helper function to compute the class weights :param histogram: distribution of class samples :return: None, but updates the classWeights variable ''' print(" original histogram " + str(histogram)) normHist = histogram / np.sum(histogram) print(normHist) return normHist def readFile(self, fileName): ''' Function to read the data :param fileName: file that stores the image locations :param trainStg: if processing training or validation data :return: 0 if successful ''' global_hist = np.zeros(self.classes, dtype=np.float32) with open(self.data_dir + '/' + fileName, 'r') as textFile: for line in textFile: # we expect the text file to contain the data in following format # <RGB Image>, <Label Image> line_arr = line.split(',') label_file = ((self.data_dir).strip() + '/' + line_arr[1].strip()).strip() label_img = cv2.imread(label_file, 0) label_img = cv2.resize(label_img, (self.h*2, self.h), interpolation=cv2.INTER_NEAREST) hist = np.histogram(label_img, self.classes) global_hist += hist[0] #compute the class imbalance information return self.compute_class_weights(global_hist) def processData(self): ''' main_multiscale.py calls this function We expect train.txt and val.txt files to be inside the data directory. :return: ''' print('Processing training data') return self.readFile('train.txt') if __name__ == "__main__": ld =LoadData('D:\DATA\cityscape', 20, 256) print(ld.processData())
[ "numpy.histogram", "numpy.sum", "numpy.zeros", "cv2.resize", "cv2.imread" ]
[((1235, 1275), 'numpy.zeros', 'np.zeros', (['self.classes'], {'dtype': 'np.float32'}), '(self.classes, dtype=np.float32)\n', (1243, 1275), True, 'import numpy as np\n'), ((879, 896), 'numpy.sum', 'np.sum', (['histogram'], {}), '(histogram)\n', (885, 896), True, 'import numpy as np\n'), ((1678, 1703), 'cv2.imread', 'cv2.imread', (['label_file', '(0)'], {}), '(label_file, 0)\n', (1688, 1703), False, 'import cv2\n'), ((1733, 1809), 'cv2.resize', 'cv2.resize', (['label_img', '(self.h * 2, self.h)'], {'interpolation': 'cv2.INTER_NEAREST'}), '(label_img, (self.h * 2, self.h), interpolation=cv2.INTER_NEAREST)\n', (1743, 1809), False, 'import cv2\n'), ((1832, 1869), 'numpy.histogram', 'np.histogram', (['label_img', 'self.classes'], {}), '(label_img, self.classes)\n', (1844, 1869), True, 'import numpy as np\n')]
import abc from typing import Any, Callable, Dict, List, Optional, Tuple, Union import numexpr as ne import numpy as np import pandas as pd import scipy.sparse import scipy.spatial from sklearn.gaussian_process.kernels import Kernel from sklearn.preprocessing import normalize from sklearn.utils import check_scalar from datafold.pcfold.distance import compute_distance_matrix from datafold.pcfold.timeseries.accessor import TSCAccessor from datafold.utils.general import ( df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix, ) KernelType = Union[pd.DataFrame, np.ndarray, scipy.sparse.csr_matrix] def _apply_kernel_function(distance_matrix, kernel_function): if scipy.sparse.issparse(distance_matrix): kernel = distance_matrix # NOTE: applies on stored data, it is VERY important, that real distance zeros are # included in 'distance_matrix' (E.g. normalized kernels have to have a 1.0 on # the diagonal) are included in the sparse matrix! kernel.data = kernel_function(kernel.data) else: kernel = kernel_function(distance_matrix) return kernel def _apply_kernel_function_numexpr(distance_matrix, expr, expr_dict=None): expr_dict = expr_dict or {} assert "D" not in expr_dict.keys() if scipy.sparse.issparse(distance_matrix): # copy because the distance matrix may be used further by the user distance_matrix = distance_matrix.copy() expr_dict["D"] = distance_matrix.data ne.evaluate(expr, expr_dict, out=distance_matrix.data) return distance_matrix # returns actually the kernel else: expr_dict["D"] = distance_matrix return ne.evaluate(expr, expr_dict) def _symmetric_matrix_division( matrix: Union[np.ndarray, scipy.sparse.spmatrix], vec: np.ndarray, vec_right: Optional[np.ndarray] = None, scalar: float = 1.0, value_zero_division: Union[str, float] = "raise", ) -> Union[np.ndarray, scipy.sparse.csr_matrix,]: r"""Symmetric division, often appearing in kernels. .. math:: \frac{M_{i, j}}{a v^(l)_i v^(r)_j} where :math:`M` is a (kernel-) matrix and its elements are divided by the (left and right) vector elements :math:`v` and scalar :math:`a`. .. warning:: The implementation is in-place and can overwrites the input matrix. Make a copy beforehand if the matrix values are still required. Parameters ---------- matrix Matrix of shape `(n_rows, n_columns)` to apply symmetric division on. If matrix is square and ``vec_right=None``, then `matrix` is assumed to be symmetric (this enables removing numerical noise to return a perfectly symmetric matrix). vec Vector of shape `(n_rows,)` in the denominator (Note, the reciprocal is is internal of the function). vec_right Vector of shape `(n_columns,)`. If matrix is non-square or matrix input is not symmetric, then this input is required. If None, it is set to ``vec_right=vec``. scalar Scalar ``a`` in the denominator. Returns ------- """ if matrix.ndim != 2: raise ValueError("Parameter 'matrix' must be a two dimensional array.") if matrix.shape[0] != matrix.shape[1] and vec_right is None: raise ValueError( "If 'matrix' is non-square, then 'vec_right' must be provided." ) vec = vec.astype(float) if (vec == 0.0).any(): if value_zero_division == "raise": raise ZeroDivisionError( f"Encountered zero values in division in {(vec == 0).sum()} points." ) else: # division results into 'nan' without raising a ZeroDivisionWarning. The # nan values will be replaced later vec[vec == 0.0] = np.nan vec_inv_left = np.reciprocal(vec) if vec_right is None: vec_inv_right = vec_inv_left.view() else: vec_right = vec_right.astype(float) if (vec_right == 0.0).any(): if value_zero_division == "raise": raise ZeroDivisionError( f"Encountered zero values in division in {(vec == 0).sum()}" ) else: vec_right[vec_right == 0.0] = np.inf vec_inv_right = np.reciprocal(vec_right.astype(float)) if vec_inv_left.ndim != 1 or vec_inv_left.shape[0] != matrix.shape[0]: raise ValueError( f"Invalid input: 'vec.shape={vec.shape}' is not compatible with " f"'matrix.shape={matrix.shape}'." ) if vec_inv_right.ndim != 1 or vec_inv_right.shape[0] != matrix.shape[1]: raise ValueError( f"Invalid input: 'vec_right.shape={vec_inv_right.shape}' is not compatible " f"with 'matrix.shape={matrix.shape}'." ) if scipy.sparse.issparse(matrix): left_inv_diag_sparse = scipy.sparse.spdiags( vec_inv_left, 0, m=matrix.shape[0], n=matrix.shape[0] ) right_inv_diag_sparse = scipy.sparse.spdiags( vec_inv_right, 0, m=matrix.shape[1], n=matrix.shape[1] ) # The performance of DIA-sparse matrices is good if the matrix is actually # sparse. I.e. the performance drops for a sparse-dense-sparse multiplication. # The zeros are removed in the matrix multiplication, but because 'matrix' is # usually a distance matrix we need to preserve the "true zeros"! matrix.data[matrix.data == 0] = np.inf matrix = left_inv_diag_sparse @ matrix @ right_inv_diag_sparse matrix.data[np.isinf(matrix.data)] = 0 # this imposes precedence order # --> np.inf/np.nan -> np.nan # i.e. for cases with 0/0, set 'value_zero_division' if isinstance(value_zero_division, (int, float)): matrix.data[np.isnan(matrix.data)] = value_zero_division else: # This computes efficiently: # np.diag(1/vector_elements) @ matrix @ np.diag(1/vector_elements) matrix = diagmat_dot_mat(vec_inv_left, matrix, out=matrix) matrix = mat_dot_diagmat(matrix, vec_inv_right, out=matrix) if isinstance(value_zero_division, (int, float)): matrix[np.isnan(matrix)] = value_zero_division # sparse and dense if vec_right is None: matrix = remove_numeric_noise_symmetric_matrix(matrix) if scalar != 1.0: scalar = 1.0 / scalar matrix = np.multiply(matrix, scalar, out=matrix) return matrix def _conjugate_stochastic_kernel_matrix( kernel_matrix: Union[np.ndarray, scipy.sparse.spmatrix] ) -> Tuple[Union[np.ndarray, scipy.sparse.spmatrix], scipy.sparse.dia_matrix]: r"""Conjugate transformation to obtain symmetric (conjugate) kernel matrix with same spectrum properties. Rabin et al. :cite:`rabin_heterogeneous_2012` states in equation Eq. 3.1 \ (notation adapted): .. math:: P = D^{-1} K the standard row normalization. Eq. 3.3 shows that matrix :math:`P` has a similar matrix with .. math:: A = D^{1/2} P D^{-1/2} Replacing :math:`P` from above we get: .. math:: A = D^{1/2} D^{-1} K D^{-1/2} A = D^{-1/2} K D^{-1/2} Where the last equation is the conjugate transformation performed in this function. The matrix :math:`A` has the same eigenvalues to :math:`P` and the eigenvectors can be recovered (Eq. 3.4. in reference): .. math:: \Psi = D^{-1/2} V where :math:`V` are the eigenvectors of :math:`A` and :math:`\Psi` from matrix \ :math:`P`. .. note:: The conjugate-stochastic matrix is not stochastic, but still has the trivial eigenvalue 1 (i.e. the row-sums are not equal to 1). Parameters ---------- kernel_matrix non-symmetric kernel matrix Returns ------- Tuple[Union[np.ndarray, scipy.sparse.spmatrix], scipy.sparse.dia_matrix] conjugate matrix (tpye as `kernel_matrix`) and (sparse) diagonal matrix to recover eigenvectors References ---------- :cite:`rabin_heterogeneous_2012` """ left_vec = kernel_matrix.sum(axis=1) if scipy.sparse.issparse(kernel_matrix): # to np.ndarray in case it is depricated format np.matrix left_vec = left_vec.A1 if left_vec.dtype.kind != "f": left_vec = left_vec.astype(float) left_vec = np.sqrt(left_vec, out=left_vec) kernel_matrix = _symmetric_matrix_division( kernel_matrix, vec=left_vec, vec_right=None ) # This is D^{-1/2} in sparse matrix form. basis_change_matrix = scipy.sparse.diags(np.reciprocal(left_vec, out=left_vec)) return kernel_matrix, basis_change_matrix def _stochastic_kernel_matrix(kernel_matrix: Union[np.ndarray, scipy.sparse.spmatrix]): """Normalizes matrix rows. This function performs .. math:: M = D^{-1} K where matrix :math:`M` is the row-normalized kernel from :math:`K` by the matrix :math:`D` with the row sums of :math:`K` on the diagonal. .. note:: If the kernel matrix is evaluated component wise (points compared to reference points), then outliers can have a row sum close to zero. In this case the respective element on the diagonal is set to zero. For a pairwise kernel (pdist) this can not happen, as the diagonal element must be non-zero. Parameters ---------- kernel_matrix kernel matrix (square or rectangular) to normalize Returns ------- Union[np.ndarray, scipy.sparse.spmatrix] normalized kernel matrix with type same as `kernel_matrix` """ if scipy.sparse.issparse(kernel_matrix): # in a microbenchmark this turned out to be the fastest solution for sparse # matrices kernel_matrix = normalize(kernel_matrix, copy=False, norm="l1") else: # dense normalize_diagonal = np.sum(kernel_matrix, axis=1) with np.errstate(divide="ignore", over="ignore"): # especially in cdist computations there can be far away outliers # (or very small scale/epsilon). This results in elements near 0 and # the reciprocal can then # - be inf # - overflow (resulting in negative values) # these cases are catched with 'bool_invalid' below normalize_diagonal = np.reciprocal( normalize_diagonal, out=normalize_diagonal ) bool_invalid = np.logical_or( np.isinf(normalize_diagonal), normalize_diagonal < 0 ) normalize_diagonal[bool_invalid] = 0 kernel_matrix = diagmat_dot_mat(normalize_diagonal, kernel_matrix) return kernel_matrix def _kth_nearest_neighbor_dist( distance_matrix: Union[np.ndarray, scipy.sparse.csr_matrix], k ) -> np.ndarray: """Compute the distance to the `k`-th nearest neighbor. Parameters ---------- distance_matrix Distance matrix of shape `(n_samples_Y, n_samples_X)` from which to find the `k`-th nearest neighbor and its corresponding distance to return. If the matrix is sparse each point must have a minimum number of `k` neighbours (i.e. non-zero elements per row). k The distance of the `k`-th nearest neighbor. Returns ------- numpy.ndarray distance values """ if not is_integer(k): raise ValueError(f"parameter 'k={k}' must be a positive integer") else: # make sure we deal with Python built-in k = int(k) if not (0 <= k <= distance_matrix.shape[1]): raise ValueError( "'k' must be an integer between 1 and " f"distance_matrix.shape[1]={distance_matrix.shape[1]}" ) if isinstance(distance_matrix, np.ndarray): dist_knn = np.partition(distance_matrix, k - 1, axis=1)[:, k - 1] elif isinstance(distance_matrix, scipy.sparse.csr_matrix): # see mircobenchmark_kth_nn.py for a comparison of implementations for the # sparse case def _get_kth_largest_elements_sparse( data: np.ndarray, indptr: np.ndarray, row_nnz, k_neighbor: int, ): dist_knn = np.zeros(len(row_nnz)) for i in range(len(row_nnz)): start_row = indptr[i] dist_knn[i] = np.partition( data[start_row : start_row + row_nnz[i]], k_neighbor - 1 )[k_neighbor - 1] return dist_knn row_nnz = distance_matrix.getnnz(axis=1) if (row_nnz < k).any(): raise ValueError( f"There are {(row_nnz < k).sum()} points that " f"do not have at least k_neighbor={k}." ) dist_knn = _get_kth_largest_elements_sparse( distance_matrix.data, distance_matrix.indptr, row_nnz, k, ) else: raise TypeError(f"type {type(distance_matrix)} not supported") return dist_knn class BaseManifoldKernel(Kernel): @abc.abstractmethod def __call__(self, X, Y=None, *, dist_kwargs=None, **kernel_kwargs): """Compute kernel matrix. If `Y=None`, then the pairwise-kernel is computed with `Y=X`. If `Y` is given, then the kernel matrix is computed component-wise with `X` being the reference and `Y` the query point cloud. Because the kernel can return a variable number of return values, this is unified with :meth:`PCManifoldKernel.read_kernel_output`. Parameters ---------- args kwargs See parameter documentation in subclasses. Returns ------- """ def diag(self, X): """(Not implemented, not used in datafold) Raises ------ NotImplementedError this is only to overwrite abstract method in super class """ raise NotImplementedError("base class") def is_stationary(self): """(Not implemented, not used in datafold) Raises ------ NotImplementedError this is only to overwrite abstract method in super class """ # in datafold there is no handling of this attribute, if required this has to # be implemented raise NotImplementedError("base class") def __repr__(self): param_str = ", ".join( [f"{name}={val}" for name, val in self.get_params().items()] ) return f"{self.__class__.__name__}({param_str})" def _read_kernel_kwargs(self, attrs: Optional[List[str]], kernel_kwargs: dict): return_values: List[Any] = [] if attrs is not None: for attr in attrs: return_values.append(kernel_kwargs.pop(attr, None)) if kernel_kwargs != {}: raise KeyError( f"kernel_kwargs.keys = {kernel_kwargs.keys()} are not " f"supported" ) if len(return_values) == 0: return None elif len(return_values) == 1: return return_values[0] else: return return_values @staticmethod def read_kernel_output( kernel_output: Union[Union[np.ndarray, scipy.sparse.csr_matrix], Tuple] ) -> Tuple[Union[np.ndarray, scipy.sparse.csr_matrix], Dict, Dict]: """Unifies kernel output for all possible return scenarios of a kernel. This is required for models that allow generic kernels to be set where the number of outputs of the internal kernel are not known *apriori*. A kernel must return a computed kernel matrix in the first position. The two other places are optional: 2. A dictionary containing keys that are required for a component-wise kernel computation (and set in `**kernel_kwargs`, see also below). Examples are computed density values. 3. A dictionary that containes additional information computed during the computation. These extra information must always be at the third return position. .. code-block:: python # we don't know how the exact kernel and therefore not how many return # values are contained in kernel_output kernel_output = compute_kernel_matrix(X) # we read the output and obtain the three psossible places kernel_matrix, cdist_kwargs, extra_info = \ PCManifold.read_kernel_output(kernel_output) # we can compute a follow up component-wise kernel matrix cdist_kernel_output = compute_kernel_matrix(X,Y, **cdist_kwargs) Parameters ---------- kernel_output Output from an generic kernel, from which we don't know if it contains one, two or three return values. Returns ------- Union[numpy.ndarray, scipy.sparse.csr_matrix] Kernel matrix. Dict Data required for follow-up component-wise computation. The dictionary should contain keys that can be included as `**kernel_kwargs` to the follow-up ``__call__``. Dictionary is empty if no data is contained in kernel output. Dict Quantities of interest with keys specific of the respective kernel. Dictionary is empty if no data is contained in kernel output. """ if isinstance( kernel_output, (pd.DataFrame, np.ndarray, scipy.sparse.csr_matrix) ): # easiest case, we simply return the kernel matrix kernel_matrix, ret_cdist, ret_extra = [kernel_output, None, None] elif isinstance(kernel_output, tuple): if len(kernel_output) == 1: kernel_matrix, ret_cdist, ret_extra = [kernel_output[0], None, None] elif len(kernel_output) == 2: kernel_matrix, ret_cdist, ret_extra = ( kernel_output[0], kernel_output[1], None, ) elif len(kernel_output) == 3: kernel_matrix, ret_cdist, ret_extra = kernel_output else: raise ValueError( "kernel_output must has more than three elements. " "Please report bug" ) else: raise TypeError( "'kernel_output' must be either pandas.DataFrame (incl. TSCDataFrame), " "numpy.ndarray or tuple. Please report bug." ) ret_cdist = ret_cdist or {} ret_extra = ret_extra or {} if not isinstance( kernel_matrix, (pd.DataFrame, np.ndarray, scipy.sparse.csr_matrix) ): raise TypeError( f"Illegal type of kernel_matrix (type={type(kernel_matrix)}. " f"Please report bug." ) return kernel_matrix, ret_cdist, ret_extra class PCManifoldKernel(BaseManifoldKernel): """Abstract base class for kernels acting on point clouds. See Also -------- :py:class:`PCManifold` """ @abc.abstractmethod def __call__( self, X: np.ndarray, Y: Optional[np.ndarray] = None, *, dist_kwargs: Optional[Dict[str, object]] = None, **kernel_kwargs, ): """Abstract method to compute the kernel matrix from a point cloud. Parameters ---------- X Data of shape `(n_samples_X, n_features)`. Y Reference data of shape `(n_samples_y, n_features_y)` dist_kwargs Keyword arguments for the distance computation. **kernel_kwargs Keyword arguments for the kernel algorithm. Returns ------- numpy.ndarray Kernel matrix of shape `(n_samples_X, n_samples_X)` for the pairwise case or `(n_samples_y, n_samples_X)` for component-wise kernels Optional[Dict] For the pairwise computation, a kernel can return data that is required for a follow-up component-wise computation. The dictionary should contain keys that can be included as `**kernel_kwargs` to a follow-up ``__call__``. Note that if a kernel has no such values, this is empty (i.e. not even `None` is returned). Optional[Dict] If the kernel computes quantities of interest, then these quantities can be included in this dictionary. If this is returned, then this must be at the third return position (with a possible `None` return at the second position). If a kernel has no such values, this can be empty (i.e. not even `None` is returned). """ raise NotImplementedError("base class") @abc.abstractmethod def eval( self, distance_matrix: Union[np.ndarray, scipy.sparse.csr_matrix] ) -> Union[np.ndarray, scipy.sparse.csr_matrix]: """Evaluate kernel on pre-computed distance matrix. For return values see :meth:`.__call__`. .. note:: In this function there are no checks of whether the distance matrix was computed with the correct metric required by the kernel. Parameters ---------- distance_matrix Matrix of shape `(n_samples_Y, n_samples_X)`. For the sparse matrix case note that the kernel acts only on stored data, i.e. distance values with exactly zero (duplicates and self distance) must be stored explicitly in the matrix. Only large distance values exceeding a cut-off should not be stored. Returns ------- """ raise NotImplementedError("base class") class TSCManifoldKernel(BaseManifoldKernel): """Abstract base class for kernels acting on time series collections. See Also -------- :py:class:`.TSCDataFrame` """ @abc.abstractmethod def __call__( self, X: pd.DataFrame, Y: Optional[pd.DataFrame] = None, *, dist_kwargs: Optional[Dict[str, object]] = None, **kernel_kwargs, ): """Abstract method to compute the kernel matrix from a time series collection. Parameters ---------- X Data of shape `(n_samples_X, n_features)`. Y Data of shape `(n_samples_Y, n_features)`. dist_kwargs Keyword arguments for the distance computation. **kernel_kwargs Keyword arguments for the kernel algorithm. Returns ------- Union[TSCDataFrame, pd.DataFrame] The computed kernel matrix as ``TSCDataFrame`` (or fallback ``pandas.DataFrame``, if not regular time series). The basis shape of the kernel matrix `(n_samples_Y, n_samples_X)`. However, the kernel may not be evaluated at all given input time values and is then reduced accordingly. Optional[Dict] For the pairwise computation, a kernel can return data that is required for a follow-up component-wise computation. The dictionary should contain keys that can be included as `**kernel_kwargs` to a follow-up ``__call__``. Note that if a kernel has no such values, this is empty (i.e. not even `None` is returned). Optional[Dict] If the kernel computes quantities of interest, then these quantities can be included in this dictionary. If this is returned, then this must be at the third return position (with a possible `None` return at the second position). If a kernel has no such values, this can be empty (i.e. not even `None` is returned). """ raise NotImplementedError("base class") class RadialBasisKernel(PCManifoldKernel, metaclass=abc.ABCMeta): """Abstract base class for radial basis kernels. "A radial basis function (RBF) is a real-valued function whose value depends \ only on the distance between the input and some fixed point." from `Wikipedia <https://en.wikipedia.org/wiki/Radial_basis_function>`_ Parameters ---------- distance_metric metric required for kernel """ def __init__(self, distance_metric): self.distance_metric = distance_metric super(RadialBasisKernel, self).__init__() @classmethod def _check_bandwidth_parameter(cls, parameter, name) -> float: check_scalar( parameter, name=name, target_type=(float, np.floating, int, np.integer), min_val=np.finfo(float).eps, ) return float(parameter) def __call__( self, X, Y=None, *, dist_kwargs=None, **kernel_kwargs ) -> Union[np.ndarray, scipy.sparse.csr_matrix]: """Compute kernel matrix. Parameters ---------- X Reference point cloud of shape `(n_samples_X, n_features_X)`. Y Query point cloud of shape `(n_samples_Y, n_features_Y)`. If not given, then `Y=X`. dist_kwargs, Keyword arguments passed to the distance matrix computation. See :py:meth:`datafold.pcfold.compute_distance_matrix` for parameter arguments. **kernel_kwargs None Returns ------- Union[np.ndarray, scipy.sparse.csr_matrix] Kernel matrix of shape `(n_samples_Y, n_samples_X)`. If cut-off is specified in `dist_kwargs`, then the matrix is sparse. """ self._read_kernel_kwargs(attrs=None, kernel_kwargs=kernel_kwargs) X = np.atleast_2d(X) if Y is not None: Y = np.atleast_2d(Y) distance_matrix = compute_distance_matrix( X, Y, metric=self.distance_metric, **dist_kwargs or {}, ) kernel_matrix = self.eval(distance_matrix) return kernel_matrix class GaussianKernel(RadialBasisKernel): r"""Gaussian radial basis kernel. .. math:: K = \exp(\frac{-1}{2\varepsilon} \cdot D) where :math:`D` is the squared euclidean distance matrix. See also super classes :class:`RadialBasisKernel` and :class:`PCManifoldKernel` for more functionality and documentation. Parameters ---------- epsilon The kernel scale as a positive float value. Alternatively, a a callable can be passed. After computing the distance matrix, the distance matrix will be passed to this function i.e. ``function(distance_matrix)``. The result of this function must be a again a positive float to describe the kernel scale. """ def __init__(self, epsilon: Union[float, Callable] = 1.0): self.epsilon = epsilon super(GaussianKernel, self).__init__(distance_metric="sqeuclidean") def eval( self, distance_matrix: Union[np.ndarray, scipy.sparse.csr_matrix] ) -> Union[np.ndarray, scipy.sparse.csr_matrix]: """Evaluate the kernel on pre-computed distance matrix. Parameters ---------- distance_matrix Matrix of pairwise distances of shape `(n_samples_Y, n_samples_X)`. Returns ------- Union[np.ndarray, scipy.sparse.csr_matrix] Kernel matrix of same shape and type as `distance_matrix`. """ # Security copy, the distance matrix is maybe required again (for gradient, # or other computations...) if callable(self.epsilon): if isinstance(distance_matrix, scipy.sparse.csr_matrix): self.epsilon = self.epsilon(distance_matrix.data) elif isinstance(distance_matrix, np.ndarray): self.epsilon = self.epsilon(distance_matrix) else: raise TypeError( f"Invalid type: type(distance_matrix)={type(distance_matrix)}." f"Please report bug." ) self.epsilon = self._check_bandwidth_parameter( parameter=self.epsilon, name="epsilon" ) kernel_matrix = _apply_kernel_function_numexpr( distance_matrix, expr="exp((- 1 / (2*eps)) * D)", expr_dict={"eps": self.epsilon}, ) return kernel_matrix class MultiquadricKernel(RadialBasisKernel): r"""Multiquadric radial basis kernel. .. math:: K = \sqrt(\frac{1}{2 \varepsilon} \cdot D + 1) where :math:`D` is the squared euclidean distance matrix. See also super classes :class:`RadialBasisKernel` and :class:`PCManifoldKernel` for more functionality and documentation. Parameters ---------- epsilon kernel scale """ def __init__(self, epsilon: float = 1.0): self.epsilon = epsilon super(MultiquadricKernel, self).__init__(distance_metric="sqeuclidean") def eval( self, distance_matrix: Union[np.ndarray, scipy.sparse.csr_matrix] ) -> Union[np.ndarray, scipy.sparse.csr_matrix]: """Evaluate the kernel on pre-computed distance matrix. Parameters ---------- distance_matrix Matrix of pairwise distances of shape `(n_samples_Y, n_samples_X)`. Returns ------- Union[np.ndarray, scipy.sparse.csr_matrix] Kernel matrix of same shape and type as `distance_matrix`. """ self.epsilon = self._check_bandwidth_parameter( parameter=self.epsilon, name="epsilon" ) return _apply_kernel_function_numexpr( distance_matrix, expr="sqrt(1.0 / (2*eps) * D + 1.0)", expr_dict={"eps": self.epsilon}, ) class InverseMultiquadricKernel(RadialBasisKernel): r"""Inverse multiquadric radial basis kernel. .. math:: K = \sqrt(\frac{1}{2\varepsilon} \cdot D + 1)^{-1} where :math:`D` is the squared Euclidean distance matrix. See also super classes :class:`RadialBasisKernel` and :class:`PCManifoldKernel` for more functionality and documentation. Parameters ---------- epsilon kernel scale """ def __init__(self, epsilon: float = 1.0): self.epsilon = epsilon super(InverseMultiquadricKernel, self).__init__(distance_metric="sqeuclidean") def eval( self, distance_matrix: Union[np.ndarray, scipy.sparse.csr_matrix] ) -> Union[np.ndarray, scipy.sparse.csr_matrix]: """Evaluate the kernel on pre-computed distance matrix. Parameters ---------- distance_matrix Matrix of pairwise distances of shape `(n_samples_Y, n_samples_X)`. Returns ------- Union[np.ndarray, scipy.sparse.csr_matrix] Kernel matrix of same shape and type as `distance_matrix`. """ self.epsilon = self._check_bandwidth_parameter( parameter=self.epsilon, name="epsilon" ) return _apply_kernel_function_numexpr( distance_matrix, expr="1.0 / sqrt(1.0 / (2*eps) * D + 1.0)", expr_dict={"eps": self.epsilon}, ) class CubicKernel(RadialBasisKernel): r"""Cubic radial basis kernel. .. math:: K= D^{3} where :math:`D` is the Euclidean distance matrix. See also super classes :class:`RadialBasisKernel` and :class:`PCManifoldKernel` for more functionality and documentation. """ def __init__(self): super(CubicKernel, self).__init__(distance_metric="euclidean") def eval( self, distance_matrix: Union[np.ndarray, scipy.sparse.csr_matrix] ) -> Union[np.ndarray, scipy.sparse.csr_matrix]: """Evaluate the kernel on pre-computed distance matrix. Parameters ---------- distance_matrix Matrix of pairwise distances of shape `(n_samples_Y, n_samples_X)`. Returns ------- Union[np.ndarray, scipy.sparse.csr_matrix] Kernel matrix of same shape and type as `distance_matrix`. """ # return r ** 3 return _apply_kernel_function_numexpr(distance_matrix, expr="D ** 3") class QuinticKernel(RadialBasisKernel): r"""Quintic radial basis kernel. .. math:: K= D^{5} where :math:`D` is the Euclidean distance matrix. See also super classes :class:`RadialBasisKernel` and :class:`PCManifoldKernel` for more functionality and documentation. """ def __init__(self): super(QuinticKernel, self).__init__(distance_metric="euclidean") def eval( self, distance_matrix: Union[np.ndarray, scipy.sparse.csr_matrix] ) -> Union[np.ndarray, scipy.sparse.csr_matrix]: """Evaluate the kernel on pre-computed distance matrix. Parameters ---------- distance_matrix Matrix of pairwise distances of shape `(n_samples_Y, n_samples_X)`. Returns ------- Union[np.ndarray, scipy.sparse.csr_matrix] Kernel matrix of same shape and type as `distance_matrix`. """ # r**5 return _apply_kernel_function_numexpr(distance_matrix, "D ** 5") class ContinuousNNKernel(PCManifoldKernel): """Compute the continuous `k` nearest-neighbor adjacency graph. The continuous `k` nearest neighbor (C-kNN) graph is an adjacency (i.e. unweighted) graph for which the (un-normalized) graph Laplacian converges spectrally to a Laplace-Beltrami operator on the manifold in the large data limit. Parameters ---------- k_neighbor For each point the distance to the `k_neighbor` nearest neighbor is computed. If a sparse matrix is computed (with cut-off distance), then each point must have a minimum of `k` stored neighbors. (see `kmin` parameter in :meth:`pcfold.distance.compute_distance_matrix`). delta Unit-less scale parameter. References ---------- :cite:`berry_consistent_2019` """ def __init__(self, k_neighbor: int, delta: float): if not is_integer(k_neighbor): raise TypeError("n_neighbors must be an integer") else: # make sure to only use Python built-in self.k_neighbor = int(k_neighbor) if not is_float(delta): if is_integer(delta): self.delta = float(delta) else: raise TypeError("delta must be of type float") else: # make sure to only use Python built-in self.delta = float(delta) if self.k_neighbor < 1: raise ValueError( f"parameter 'k_neighbor={self.k_neighbor}' must be a positive integer" ) if self.delta <= 0.0: raise ValueError( f"parrameter 'delta={self.delta}' must be a positive float" ) super(ContinuousNNKernel, self).__init__() def _validate_reference_dist_knn(self, is_pdist, reference_dist_knn): if is_pdist and reference_dist_knn is None: raise ValueError("For the 'cdist' case 'reference_dist_knn' must be given") def __call__( self, X: np.ndarray, Y: Optional[np.ndarray] = None, *, dist_kwargs: Optional[Dict] = None, **kernel_kwargs, ): """Compute (sparse) adjacency graph to describes a point neighborhood. Parameters ---------- X Reference point cloud of shape `(n_samples_X, n_features_X)`. Y Query point cloud of shape `(n_samples_Y, n_features_Y)`. If not given, then `Y=X`. dist_kwargs Keyword arguments passed to the internal distance matrix computation. See :py:meth:`datafold.pcfold.compute_distance_matrix` for parameter arguments. **kernel_kwargs: Dict[str, object] - reference_dist_knn: Optional[np.ndarray] Distances to the `k`-th nearest neighbor for each point in `X`. The parameter is mandatory if `Y` is not `None`. Returns ------- scipy.sparse.csr_matrix Sparse adjacency matrix describing the unweighted, undirected continuous nearest neighbor graph. Optional[Dict[str, numpy.ndarray]] For a pair-wise kernel evaluation, a dictionary with key `reference_dist_knn` with the `k`-the nearest neighbors for each point is returned. """ is_pdist = Y is None reference_dist_knn = self._read_kernel_kwargs( attrs=["reference_dist_knn"], kernel_kwargs=kernel_kwargs ) dist_kwargs = dist_kwargs or {} # minimum number of neighbors required in sparse case! dist_kwargs.setdefault("kmin", self.k_neighbor) distance_matrix = compute_distance_matrix( X, Y, metric="euclidean", **dist_kwargs ) return self.eval( distance_matrix, is_pdist=is_pdist, reference_dist_knn=reference_dist_knn ) def _validate(self, distance_matrix, is_pdist, reference_dist_knn): if distance_matrix.ndim != 2: raise ValueError("distance_matrix must be a two-dimensional array") n_samples_Y, n_samples_X = distance_matrix.shape if is_pdist: if n_samples_Y != n_samples_X: raise ValueError( "If is_pdist=True, the distance matrix must be square and symmetric." ) if isinstance(distance_matrix, np.ndarray): diagonal = np.diag(distance_matrix) else: diagonal = np.asarray(distance_matrix.diagonal(0)) if (diagonal != 0).all(): raise ValueError( "If is_pdist=True, distance_matrix must have zeros on diagonal." ) else: if reference_dist_knn is None: raise ValueError( "If is_pdist=False, 'reference_dist_knn' (=None) must be provided." ) if not isinstance(reference_dist_knn, np.ndarray): raise TypeError("cdist_reference_k_nn must be of type numpy.ndarray") if reference_dist_knn.ndim != 1: raise ValueError("cdist_reference_k_nn must be 1 dim.") if reference_dist_knn.shape[0] != n_samples_X: raise ValueError( f"len(cdist_reference_k_nn)={reference_dist_knn.shape[0]} " f"must be distance.shape[1]={n_samples_X}" ) if self.k_neighbor < 1 or self.k_neighbor > n_samples_X - 1: raise ValueError( "'n_neighbors' must be in a range between 1 to the number of samples." ) def eval( self, distance_matrix, is_pdist=False, reference_dist_knn=None ) -> Tuple[scipy.sparse.csr_matrix, Optional[Dict[Any, np.ndarray]]]: """Evaluate kernel on pre-computed distance matrix. For return values see :meth:`.__call__`. Parameters ---------- distance_matrix Pre-computed matrix. is_pdist If True, the `distance_matrix` is assumed to be symmetric and with zeros on the diagonal (self distances). Note, that there are no checks to validate the distance matrix. reference_dist_knn An input is required for a component-wise evaluation of the kernel. This is the case if the distance matrix is rectangular or non-symmetric (i.e., ``is_pdist=False``). The required values are returned for a pre-evaluation of the pair-wise evaluation. """ self._validate( distance_matrix=distance_matrix, is_pdist=is_pdist, reference_dist_knn=reference_dist_knn, ) dist_knn = _kth_nearest_neighbor_dist(distance_matrix, self.k_neighbor) distance_factors = _symmetric_matrix_division( distance_matrix, vec=np.sqrt(dist_knn), vec_right=np.sqrt(reference_dist_knn) if reference_dist_knn is not None else None, ) if isinstance(distance_factors, np.ndarray): kernel_matrix = scipy.sparse.csr_matrix( distance_factors < self.delta, dtype=bool ) else: assert isinstance(distance_factors, scipy.sparse.csr_matrix) distance_factors.data = (distance_factors.data < self.delta).astype(bool) distance_factors.eliminate_zeros() kernel_matrix = distance_factors # return dist_knn, which is required for cdist_k_nearest_neighbor in # order to do a follow-up cdist request (then as reference_dist_knn as input). if is_pdist: ret_cdist: Optional[Dict[str, np.ndarray]] = dict( reference_dist_knn=dist_knn ) else: ret_cdist = None return kernel_matrix, ret_cdist class DmapKernelFixed(BaseManifoldKernel): """Diffusion map kernel with fixed kernel bandwidth. This kernel wraps an kernel to describe a diffusion process. Parameters ---------- internal_kernel Kernel that describes the proximity between data points. is_stochastic If True, the kernel matrix is row-normalized. alpha Degree of re-normalization of sampling density in point cloud. `alpha` must be inside the interval [0, 1] (inclusive). symmetrize_kernel If True, performs a conjugate transformation which can improve numerical stability for matrix operations (such as computing eigenpairs). The matrix to change the basis back is provided as a quantity of interest (see possible return values in :meth:`PCManifoldKernel.__call__`). See Also -------- :py:class:`DiffusionMaps` References ---------- :cite:`coifman_diffusion_2006` """ def __init__( self, internal_kernel: PCManifoldKernel = GaussianKernel(epsilon=1.0), is_stochastic: bool = True, alpha: float = 1.0, symmetrize_kernel: bool = True, ): self.is_stochastic = is_stochastic if not (0 <= alpha <= 1): raise ValueError(f"alpha has to be between [0, 1]. Got alpha={alpha}") self.alpha = alpha self.symmetrize_kernel = symmetrize_kernel self.internal_kernel = internal_kernel # i) not stochastic -> if the kernel is symmetric the kernel is always # symmetric # `symmetrize_kernel` indicates if the user wants the kernel to use # similarity transformations to solve the # eigenproblem on a symmetric kernel (if required). # NOTE: a necessary condition to symmetrize the kernel is that the kernel # is evaluated pairwise # (i.e. is_pdist = True) # self._is_symmetric = True # else: # self._is_symmetric = False self.row_sums_init = None super(DmapKernelFixed, self).__init__() @property def is_symmetric(self): return self.symmetrize_kernel or not self.is_stochastic def is_symmetric_transform(self) -> bool: """Indicates whether a symmetric conjugate kernel matrix was computed. Returns ------- """ # If the kernel is made stochastic, it looses the symmetry, if symmetric_kernel # is set to True, then apply the the symmetry transformation return self.is_stochastic and self.is_symmetric def _normalize_sampling_density( self, kernel_matrix: Union[np.ndarray, scipy.sparse.csr_matrix], row_sums_alpha_fit: np.ndarray, ) -> Tuple[Union[np.ndarray, scipy.sparse.csr_matrix], Optional[np.ndarray]]: """Normalize (sparse/dense) kernels with positive `alpha` value. This is also referred to a 'renormalization' of sampling density.""" if row_sums_alpha_fit is None: assert is_symmetric_matrix(kernel_matrix) else: assert row_sums_alpha_fit.shape[0] == kernel_matrix.shape[1] row_sums = kernel_matrix.sum(axis=1) if scipy.sparse.issparse(kernel_matrix): # np.matrix to np.ndarray # (np.matrix is deprecated but still used in scipy.sparse) row_sums = row_sums.A1 if self.alpha < 1: if row_sums.dtype.kind != "f": # This is required for case when 'row_sums' contains boolean or integer # values; for inplace operations the type has to be the same row_sums = row_sums.astype(float) row_sums_alpha = np.power(row_sums, self.alpha, out=row_sums) else: # no need to power with 1 row_sums_alpha = row_sums normalized_kernel = _symmetric_matrix_division( matrix=kernel_matrix, vec=row_sums_alpha, vec_right=row_sums_alpha_fit, ) if row_sums_alpha_fit is not None: # Set row_sums_alpha to None for security, because in a cdist-case (if # row_sums_alpha_fit) there is no need to further process row_sums_alpha, yet. row_sums_alpha = None return normalized_kernel, row_sums_alpha def _normalize( self, internal_kernel: KernelType, row_sums_alpha_fit: np.ndarray, is_pdist: bool, ): # only required for symmetric kernel, return None if not used basis_change_matrix = None # required if alpha>0 and _normalize is called later for a cdist case # set in the pdist, alpha > 0 case row_sums_alpha = None if self.is_stochastic: if self.alpha > 0: # if pdist: kernel is still symmetric after this function call (internal_kernel, row_sums_alpha,) = self._normalize_sampling_density( internal_kernel, row_sums_alpha_fit ) if is_pdist and self.is_symmetric_transform(): # Increases numerical stability when solving the eigenproblem # Note1: when using the (symmetric) conjugate matrix, the eigenvectors # have to be transformed back to match the original # Note2: the similarity transform only works for the is_pdist case # (for cdist, there is no symmetric kernel in the first place, # because it is generally rectangular and does not include self # points) ( internal_kernel, basis_change_matrix, ) = _conjugate_stochastic_kernel_matrix(internal_kernel) else: internal_kernel = _stochastic_kernel_matrix(internal_kernel) # check that if "is symmetric pdist" -> require basis change # else no basis change assert not ( (is_pdist and self.is_symmetric_transform()) ^ (basis_change_matrix is not None) ) if is_pdist and self.is_symmetric: assert is_symmetric_matrix(internal_kernel) return internal_kernel, basis_change_matrix, row_sums_alpha def _validate_row_alpha_fit(self, is_pdist, row_sums_alpha_fit): if ( self.is_stochastic and self.alpha > 0 and not is_pdist and row_sums_alpha_fit is None ): raise ValueError( "cdist request can not be carried out, if 'row_sums_alpha_fit=None'" "Please consider to report bug." ) def _eval(self, kernel_output, is_pdist, row_sums_alpha_fit): self._validate_row_alpha_fit( is_pdist=is_pdist, row_sums_alpha_fit=row_sums_alpha_fit ) kernel_matrix, internal_ret_cdist, _ = PCManifoldKernel.read_kernel_output( kernel_output=kernel_output ) if isinstance(kernel_matrix, pd.DataFrame): # store indices and cast to same type later _type = type(kernel_matrix) rows_idx, columns_idx = kernel_matrix.index, kernel_matrix.columns kernel_matrix = kernel_matrix.to_numpy() else: _type, rows_idx, columns_idx = None, None, None kernel_matrix, basis_change_matrix, row_sums_alpha = self._normalize( kernel_matrix, row_sums_alpha_fit=row_sums_alpha_fit, is_pdist=is_pdist, ) if rows_idx is not None and columns_idx is not None: kernel_matrix = _type(kernel_matrix, index=rows_idx, columns=columns_idx) if is_pdist: ret_cdist = dict( row_sums_alpha_fit=row_sums_alpha, internal_kernel_kwargs=internal_ret_cdist, ) ret_extra = dict(basis_change_matrix=basis_change_matrix) else: # no need for row_sums_alpha or the basis change matrix in the cdist case ret_cdist = None ret_extra = None return kernel_matrix, ret_cdist, ret_extra def __call__( self, X: np.ndarray, Y: Optional[np.ndarray] = None, *, dist_kwargs: Optional[Dict] = None, **kernel_kwargs, ) -> Tuple[ Union[np.ndarray, scipy.sparse.csr_matrix], Optional[Dict], Optional[Dict] ]: """Compute the diffusion map kernel. Parameters ---------- X Reference point cloud of shape `(n_samples_X, n_features_X)`. Y Query point cloud of shape `(n_samples_Y, n_features_Y)`. If not given, then `Y=X`. dist_kwargs Keyword arguments passed to the internal distance matrix computation. See :py:meth:`datafold.pcfold.compute_distance_matrix` for parameter arguments. **kernel_kwargs: Dict[str, object] - internal_kernel_kwargs: Optional[Dict] Keyword arguments passed to the set internal kernel. - row_sums_alpha_fit: Optional[np.ndarray] Row sum values during re-normalization computed during pair-wise kernel computation. The parameter is mandatory for the compontent-wise kernel computation and if `alpha>0`. Returns ------- numpy.ndarray`, `scipy.sparse.csr_matrix` kernel matrix (or conjugate of it) with same type and shape as `distance_matrix` Optional[Dict[str, numpy.ndarray]] Row sums from re-normalization in key 'row_sums_alpha_fit', only returned for pairwise computations. The values are required for follow up out-of-sample kernel evaluations (`Y is not None`). Optional[Dict[str, scipy.sparse.dia_matrix]] Basis change matrix (sparse diagonal) if `is_symmetrize=True` and only returned if the kernel matrix is a symmetric conjugate of the true diffusion kernel matrix. Required to recover the diffusion map eigenvectors from the symmetric conjugate matrix. """ is_pdist = Y is None internal_kernel_kwargs, row_sums_alpha_fit = self._read_kernel_kwargs( attrs=["internal_kernel_kwargs", "row_sums_alpha_fit"], kernel_kwargs=kernel_kwargs, ) kernel_output = self.internal_kernel( X, Y=Y, dist_kwargs=dist_kwargs or {}, **internal_kernel_kwargs or {} ) return self._eval( kernel_output=kernel_output, is_pdist=is_pdist, row_sums_alpha_fit=row_sums_alpha_fit, ) def eval( self, distance_matrix: Union[np.ndarray, scipy.sparse.csr_matrix], is_pdist=False, row_sums_alpha_fit=None, ): """Evaluate kernel on pre-computed distance matrix. For return values see :meth:`.__call__`. Parameters ---------- distance_matrix Matrix of shape `(n_samples_Y, n_samples_X)`. is_pdist: If True, the distance matrix must be square Returns ------- """ kernel_output = self.internal_kernel.eval(distance_matrix) return self._eval( kernel_output=kernel_output, is_pdist=is_pdist, row_sums_alpha_fit=row_sums_alpha_fit, ) class ConeKernel(TSCManifoldKernel): r"""Compute a dynamics adapted cone kernel for time series collection data. The equations below describe the kernel evaluation and are taken from the referenced paper below. A single kernel evaluation between samples :math:`x` and :math:`y` is computed with .. math:: K(x, y) = \exp \left( -\frac{\vert\vert \omega_{ij}\vert\vert^2} {\varepsilon \delta t^2 \vert\vert \xi_i \vert\vert \vert\vert \xi_j \vert\vert } \left[ (1-\zeta \cos^2 \theta_i)(1-\zeta \cos^2 \theta_j) \right]^{0.5} \right) where, .. math:: \cos \theta_i = \frac{(\xi_i, \omega_{ij})} {\vert\vert \xi_i \vert\vert \vert\vert \omega_{ij} \vert\vert} is the angle between samples, .. math:: \omega_{ij} = y - x is a difference vector between the point pairs, .. math:: \delta t is the (constant) time sampling in the time series, .. math:: \varepsilon is an additional scaling parameter of the kernel bandwidth, .. math:: \zeta is the parameter to control the angular influence, and .. math:: \xi_i = \delta_p x_i = \sum_{j=-p/2}^{p/2} w_j x_{i+j} is the approximation of the dynamical vector field. The approximation is carried out with :math:`\delta_p`, a :math:`p`-th order accurate central finite difference (in a sense that :math:`\frac{\xi}{\delta t} + \mathcal{O}(\delta t^p)`) with associated weights :math:`w`. .. note:: In the centered finite difference the time values are shifted such that no samples are taken from the future. For exmaple, for the scheme :math:`x_{t+1} - x_{t-1}`, at time :math:`t`, then the new assigned time value is `t+1`. See also :py:meth:`.TSCAccessor.time_derivative`. Parameters ---------- zeta A scalar between :math:`[0, 1)` that controls the angular influence . The weight from one point to a neighboring point is increased if the relative displacement vector is aligned with the dynamical flow. The special case of `zeta=0`, corresponds to the so-called "Non-Linear Laplacian Spectral Analysis" kernel (NLSA). epsilon An additional scaling parameter with which the kernel scale can be adapted to the actual time sampling frequency. fd_accuracy The accuracy of the centered finite difference scheme (:math:`p` in the description). Note, that the higher the order the more smaples are required in a warm-up phase, where the centered scheme cannot be evaluated with the given accuracy. All samples from this warm-up phase are dropped in the kernel evaluation. References ---------- :cite:`giannakis_dynamics-adapted_2015` (the equations are taken from the `arXiv version <https://arxiv.org/abs/1403.0361>`__) """ def __init__(self, zeta: float = 0.0, epsilon: float = 1.0, fd_accuracy: int = 4): self.zeta = zeta self.epsilon = epsilon self.fd_accuracy = fd_accuracy def _validate_setting(self, X, Y): # cannot import in top of file, because this creates circular imports from datafold.pcfold.timeseries.collection import TSCDataFrame, TSCException check_scalar( self.zeta, name="zeta", target_type=(float, np.floating, int, np.integer), min_val=0.0, max_val=1.0 - np.finfo(float).eps, ) check_scalar( self.epsilon, name="epsilon", target_type=(float, np.floating, int, np.integer), min_val=np.finfo(float).eps, max_val=None, ) check_scalar( self.fd_accuracy, "fd_accuracy", target_type=(int, np.integer), min_val=1, max_val=None, ) # make sure to only deal with Python built-in types self.zeta = float(self.zeta) self.epsilon = float(self.epsilon) self.fd_accuracy = int(self.fd_accuracy) if not isinstance(X, TSCDataFrame): raise TypeError(f"X must be a TSCDataFrame (got: {type(X)})") if Y is not None and not isinstance(Y, TSCDataFrame): raise TypeError(f"Y must be a TSCDataFrame (got: {type(X)}") if Y is not None: is_df_same_index(X, Y, check_index=False, check_column=True, handle="raise") # checks that if scalar, if yes returns delta_time if Y is None: X_dt = X.tsc.check_const_time_delta() else: X_dt, _ = TSCAccessor.check_equal_delta_time( X, Y, atol=1e-15, require_const=True, ) # return here to not compute delta_time again return X_dt def _compute_distance_and_cosinus_matrix( self, Y_numpy: np.ndarray, timederiv_Y: np.ndarray, norm_timederiv_Y: np.ndarray, X_numpy: Optional[np.ndarray] = None, distance_matrix=None, ): if X_numpy is None: X_numpy = Y_numpy is_compute_distance = distance_matrix is None # pre-allocate cosine- and distance-matrix cos_matrix = np.zeros((Y_numpy.shape[0], X_numpy.shape[0])) if is_compute_distance: distance_matrix = np.zeros_like(cos_matrix) # define names and init as None to already to use in "out" diff_matrix, denominator, zero_mask = [None] * 3 for row_idx in range(cos_matrix.shape[0]): diff_matrix = np.subtract(X_numpy, Y_numpy[row_idx, :], out=diff_matrix) # distance matrix is not computed via "compute_distance_matrix" function if is_compute_distance: distance_matrix[row_idx, :] = scipy.linalg.norm( diff_matrix, axis=1, check_finite=False ) # norm of time_derivative * norm_difference denominator = np.multiply( norm_timederiv_Y[row_idx], distance_matrix[row_idx, :], out=denominator ) # nominator: scalar product (time_derivative, differences) # in paper: (\xi, \omega) cos_matrix[row_idx, :] = np.dot( timederiv_Y[row_idx, :], diff_matrix.T, out=cos_matrix[row_idx, :], ) # special handling of (almost) duplicates -> denominator by zero leads to nan zero_mask = np.less_equal(denominator, 1e-14, out=zero_mask) cos_matrix[row_idx, zero_mask] = 0.0 # -> np.cos(0) = 1 later cos_matrix[row_idx, ~zero_mask] /= denominator[~zero_mask] # memory and cache efficient solving with no intermediate memory allocations: # cos_matrix = 1 - self.zeta * np.square(np.cos(cos_matrix)) cos_matrix = np.cos(cos_matrix, out=cos_matrix) cos_matrix = np.square(cos_matrix, out=cos_matrix) cos_matrix = np.multiply(self.zeta, cos_matrix, out=cos_matrix) cos_matrix = np.subtract(1.0, cos_matrix, out=cos_matrix) if not np.isfinite(cos_matrix).all(): raise ValueError("not all finite") return cos_matrix, distance_matrix def _approx_dynflow(self, X): timederiv = X.tsc.time_derivative( scheme="center", diff_order=1, accuracy=self.fd_accuracy, shift_index=True ) norm_timederiv = df_type_and_indices_from( timederiv, values=np.linalg.norm(timederiv, axis=1), except_columns=["fd_norm"], ) return timederiv, norm_timederiv def __call__( self, X: pd.DataFrame, Y: Optional[pd.DataFrame] = None, *, dist_kwargs: Optional[Dict[str, object]] = None, **kernel_kwargs, ): """Compute kernel matrix. Parameters ---------- X The reference time series collection of shape `(n_samples_X, n_features_X)`. Y The query time series collection of shape `(n_samples_Y, n_features_Y)`. If `Y` is not provided, then ``Y=X``. dist_kwargs ignored `(The distance matrix is computed as part of the kernel evaluation. For now this can only be a dense matrix).` **kernel_kwargs: Dict[str, object] - timederiv_X The time derivative from a finite difference scheme. Required for a component-wise evaluation. - norm_timederiv_X Norm of the time derivative. Required for a component-wise evaluation. Returns ------- TSCDataFrame The kernel matrix with time information. """ delta_time = self._validate_setting(X, Y) timederiv_X, norm_timederiv_X = self._read_kernel_kwargs( attrs=["timederiv_X", "norm_timederiv_X"], kernel_kwargs=kernel_kwargs ) is_pdist = Y is None if is_pdist: timederiv_X, norm_timederiv_X = self._approx_dynflow(X=X) else: if timederiv_X is None or norm_timederiv_X is None: raise ValueError( "For component wise computation the parameters 'timederiv_X' " "and 'norm_timederiv_X' must be provided. " ) # NOTE: samples are dropped here which are at the time series boundaries. How # many, depends on the accuracy level of the time derivative. X_numpy = X.loc[timederiv_X.index].to_numpy() if is_pdist: timederiv_Y = timederiv_X if self.zeta != 0.0: ( cos_matrix_Y_X, distance_matrix, ) = self._compute_distance_and_cosinus_matrix( Y_numpy=X_numpy, # query (Y) = reference (X) timederiv_Y=timederiv_X.to_numpy(), norm_timederiv_Y=norm_timederiv_X.to_numpy(), ) cos_matrix = np.multiply( cos_matrix_Y_X, cos_matrix_Y_X.T, out=cos_matrix_Y_X ) cos_matrix = np.sqrt(cos_matrix, out=cos_matrix) # squared Euclidean metric distance_matrix = np.square(distance_matrix, out=distance_matrix) else: distance_matrix = compute_distance_matrix(X_numpy, metric="sqeuclidean") cos_matrix = np.ones((X_numpy.shape[0], X_numpy.shape[0])) factor_matrix = _symmetric_matrix_division( cos_matrix, vec=norm_timederiv_X.to_numpy().ravel(), vec_right=None, scalar=(delta_time ** 2) * self.epsilon, value_zero_division=0, ) else: assert isinstance(Y, pd.DataFrame) # mypy timederiv_Y, norm_timederiv_Y = self._approx_dynflow(X=Y) Y_numpy = Y.loc[timederiv_Y.index].to_numpy() if self.zeta != 0.0: ( cos_matrix_Y_X, distance_matrix, ) = self._compute_distance_and_cosinus_matrix( Y_numpy=Y_numpy, timederiv_Y=timederiv_Y.to_numpy(), norm_timederiv_Y=norm_timederiv_Y.to_numpy(), X_numpy=X_numpy, ) # because of the time derivative cos_matrix is not symmetric between # reference / query set # cos_matrix(i,j) != cos_matrix.T(j,i) # --> compute from the other way cos_matrix_X_Y, _ = self._compute_distance_and_cosinus_matrix( X_numpy, timederiv_Y=timederiv_X.to_numpy(), norm_timederiv_Y=norm_timederiv_X.to_numpy(), X_numpy=Y_numpy, distance_matrix=distance_matrix.T, ) cos_matrix = np.multiply( cos_matrix_Y_X, cos_matrix_X_Y.T, out=cos_matrix_Y_X ) cos_matrix = np.sqrt(cos_matrix, out=cos_matrix) # squared Euclidean metric distance_matrix = np.square(distance_matrix, out=distance_matrix) else: distance_matrix = compute_distance_matrix( X_numpy, Y_numpy, metric="sqeuclidean" ) cos_matrix = np.ones((Y_numpy.shape[0], X_numpy.shape[0])) factor_matrix = _symmetric_matrix_division( cos_matrix, vec=norm_timederiv_Y.to_numpy().ravel(), vec_right=norm_timederiv_X.to_numpy().ravel(), scalar=(delta_time ** 2) * self.epsilon, value_zero_division=0, ) assert np.isfinite(factor_matrix).all() kernel_matrix = _apply_kernel_function_numexpr( distance_matrix=distance_matrix, expr="exp(-1.0 * D * factor_matrix)", expr_dict={"factor_matrix": factor_matrix}, ) kernel_matrix = df_type_and_indices_from( indices_from=timederiv_Y, values=kernel_matrix, except_columns=[f"X{i}" for i in np.arange(X_numpy.shape[0])], ) if is_pdist: ret_cdist: Optional[Dict[str, Any]] = dict( timederiv_X=timederiv_X, norm_timederiv_X=norm_timederiv_X ) else: ret_cdist = None return kernel_matrix, ret_cdist class DmapKernelVariable(BaseManifoldKernel): # pragma: no cover """Diffusion maps kernel with variable kernel bandwidth. .. warning:: This class is not documented. Contributions are welcome * documentation * unit- or functional-testing References ---------- :cite:`berry_nonparametric_2015` :cite:`berry_variable_2016` See Also -------- :py:class:`DiffusionMapsVariable` """ def __init__(self, epsilon, k, expected_dim, beta, symmetrize_kernel): if expected_dim <= 0 and not is_integer(expected_dim): raise ValueError("expected_dim has to be a non-negative integer.") if epsilon < 0 and not not is_float(expected_dim): raise ValueError("epsilon has to be positive float.") if k <= 0 and not is_integer(expected_dim): raise ValueError("k has to be a non-negative integer.") self.beta = beta self.epsilon = epsilon self.k = k self.expected_dim = expected_dim # variable 'd' in paper if symmetrize_kernel: # allows to later on include a stochastic option... self.is_symmetric = True else: self.is_symmetric = False self.alpha = -self.expected_dim / 4 c2 = ( 1 / 2 - 2 * self.alpha + 2 * self.expected_dim * self.alpha + self.expected_dim * self.beta / 2 + self.beta ) if c2 >= 0: raise ValueError( "Theory requires c2 to be negative:\n" "c2 = 1/2 - 2 * alpha + 2 * expected_dim * alpha + expected_dim * " f"beta/2 + beta \n but is {c2}" ) def is_symmetric_transform(self, is_pdist): # If the kernel is made stochastic, it looses the symmetry, if symmetric_kernel # is set to True, then apply the the symmetry transformation return is_pdist and self.is_symmetric def _compute_rho0(self, distance_matrix): """Ad hoc bandwidth function.""" nr_samples = distance_matrix.shape[1] # both modes are equivalent, MODE=1 allows to easier compare with ref3. MODE = 1 if MODE == 1: # according to Berry code # keep only nearest neighbors distance_matrix = np.sort(np.sqrt(distance_matrix), axis=1)[ :, 1 : self.k + 1 ] rho0 = np.sqrt(np.mean(distance_matrix ** 2, axis=1)) else: # MODE == 2: , more performant if required if self.k < nr_samples: # TODO: have to revert setting the inf # -> check that the diagonal is all zeros # -> set to inf # -> after computation set all infs back to zero # -> this is also very similar to continous-nn in PCManifold # this allows to ignore the trivial distance=0 to itself np.fill_diagonal(distance_matrix, np.inf) # more efficient than sorting, everything distance_matrix.partition(self.k, axis=1) distance_matrix = np.sort(distance_matrix[:, : self.k], axis=1) distance_matrix = distance_matrix * distance_matrix else: # self.k == self.N np.fill_diagonal(distance_matrix, np.nan) bool_mask = ~np.diag(np.ones(nr_samples)).astype(bool) distance_matrix = distance_matrix[bool_mask].reshape( distance_matrix.shape[0], distance_matrix.shape[1] - 1 ) # experimental: -------------------------------------------------------------- # paper: in var-bw paper (ref2) pdfp. 7 # it is mentioned to IGNORE non-zero entries -- this is not detailed more. # a consequence is that the NN and kernel looses symmetry, so does (K+K^T) / 2 # This is with a cut-off rate: # val = 1E-2 # distance_matrix[distance_matrix < val] = np.nan # experimental END ----------------------------------------------------------- # nanmean only for the experimental part, if leaving this out, np.mean # suffices rho0 = np.sqrt(np.nanmean(distance_matrix, axis=1)) return rho0 def _compute_q0(self, distance_matrix, rho0): """The sampling density.""" meanrho0 = np.mean(rho0) rho0tilde = rho0 / meanrho0 # TODO: eps0 could also be optimized (see Berry Code + paper ref2) eps0 = meanrho0 ** 2 expon_matrix = _symmetric_matrix_division( matrix=-distance_matrix, vec=rho0tilde, scalar=2 * eps0 ) nr_samples = distance_matrix.shape[0] # according to eq. (10) in ref1 q0 = ( np.power(2 * np.pi * eps0, -self.expected_dim / 2) / (np.power(rho0, self.expected_dim) * nr_samples) * np.sum(np.exp(expon_matrix), axis=1) ) return q0 def _compute_rho(self, q0): """The bandwidth function for K_eps_s""" rho = np.power(q0, self.beta) # Division by rho-mean is not in papers, but in berry code (ref3) return rho / np.mean(rho) def _compute_kernel_eps_s(self, distance_matrix, rho): expon_matrix = _symmetric_matrix_division( matrix=distance_matrix, vec=rho, scalar=-4 * self.epsilon ) kernel_eps_s = np.exp(expon_matrix, out=expon_matrix) return kernel_eps_s def _compute_q_eps_s(self, kernel_eps_s, rho): rho_power_dim = np.power(rho, self.expected_dim)[:, np.newaxis] q_eps_s = np.sum(kernel_eps_s / rho_power_dim, axis=1) return q_eps_s def _compute_kernel_eps_alpha_s(self, kernel_eps_s, q_eps_s): kernel_eps_alpha_s = _symmetric_matrix_division( matrix=kernel_eps_s, vec=np.power(q_eps_s, self.alpha) ) return kernel_eps_alpha_s def _compute_matrix_l(self, kernel_eps_alpha_s, rho): rhosq = np.square(rho)[:, np.newaxis] n_samples = rho.shape[0] matrix_l = (kernel_eps_alpha_s - np.eye(n_samples)) / (self.epsilon * rhosq) return matrix_l def _compute_matrix_s_inv(self, rho, q_eps_alpha_s): s_diag = np.reciprocal(rho * np.sqrt(q_eps_alpha_s)) return scipy.sparse.diags(s_diag) def _compute_matrix_l_conjugate(self, kernel_eps_alpha_s, rho, q_eps_alpha_s): basis_change_matrix = self._compute_matrix_s_inv(rho, q_eps_alpha_s) p_sq_inv = scipy.sparse.diags(np.reciprocal(np.square(rho))) matrix_l_hat = ( basis_change_matrix @ kernel_eps_alpha_s @ basis_change_matrix - (p_sq_inv - scipy.sparse.diags(np.ones(kernel_eps_alpha_s.shape[0]))) ) matrix_l_hat = remove_numeric_noise_symmetric_matrix(matrix_l_hat) return matrix_l_hat, basis_change_matrix def __call__(self, X, Y=None, *, dist_kwargs=None, **kernel_kwargs): dist_kwargs = dist_kwargs or {} cut_off = dist_kwargs.pop("cut_off", None) self._read_kernel_kwargs(attrs=None, kernel_kwargs=kernel_kwargs) if cut_off is not None and not np.isinf(cut_off): raise NotImplementedError("Handling sparsity is currently not implemented!") if Y is not None: raise NotImplementedError("cdist case is currently not implemented!") if self.k > X.shape[0]: raise ValueError( f"nr of nearest neighbors (self.k={self.k}) " f"is larger than number of samples (={X.shape[0]})" ) distance_matrix = compute_distance_matrix( X, Y, metric="sqeuclidean", **dist_kwargs, ) operator_l_matrix, basis_change_matrix, rho0, rho, q0, q_eps_s = self.eval( distance_matrix ) # TODO: this is not yet aligned to the kernel_matrix, cdist_dict, extra_dict return ( operator_l_matrix, basis_change_matrix, rho0, rho, q0, q_eps_s, ) def eval(self, distance_matrix: Union[np.ndarray, scipy.sparse.csr_matrix]): if scipy.sparse.issparse(distance_matrix): raise NotImplementedError( "Currently DmapKernelVariable is only implemented to handle a dense " "distance matrix." ) assert ( is_symmetric_matrix(distance_matrix) and (np.diag(distance_matrix) == 0).all() ), "only pdist case supported at the moment" rho0 = self._compute_rho0(distance_matrix) q0 = self._compute_q0(distance_matrix, rho0) rho = self._compute_rho(q0) kernel_eps_s = self._compute_kernel_eps_s(distance_matrix, rho) q_eps_s = self._compute_q_eps_s(kernel_eps_s, rho) kernel_eps_alpha_s = self._compute_kernel_eps_alpha_s(kernel_eps_s, q_eps_s) # can be expensive assert is_symmetric_matrix(kernel_eps_alpha_s) if self.is_symmetric: q_eps_alpha_s = kernel_eps_alpha_s.sum(axis=1) operator_l_matrix, basis_change_matrix = self._compute_matrix_l_conjugate( kernel_eps_alpha_s, rho, q_eps_alpha_s ) else: basis_change_matrix = None operator_l_matrix = self._compute_matrix_l(kernel_eps_alpha_s, rho) return ( operator_l_matrix, basis_change_matrix, rho0, rho, q0, q_eps_s, )
[ "numpy.sqrt", "datafold.utils.general.remove_numeric_noise_symmetric_matrix", "numpy.less_equal", "numpy.nanmean", "numpy.isfinite", "datafold.utils.general.is_df_same_index", "numpy.linalg.norm", "numpy.arange", "numpy.atleast_2d", "numpy.multiply", "numpy.mean", "numpy.sort", "datafold.uti...
[((3995, 4013), 'numpy.reciprocal', 'np.reciprocal', (['vec'], {}), '(vec)\n', (4008, 4013), True, 'import numpy as np\n'), ((8562, 8593), 'numpy.sqrt', 'np.sqrt', (['left_vec'], {'out': 'left_vec'}), '(left_vec, out=left_vec)\n', (8569, 8593), True, 'import numpy as np\n'), ((1627, 1681), 'numexpr.evaluate', 'ne.evaluate', (['expr', 'expr_dict'], {'out': 'distance_matrix.data'}), '(expr, expr_dict, out=distance_matrix.data)\n', (1638, 1681), True, 'import numexpr as ne\n'), ((1810, 1838), 'numexpr.evaluate', 'ne.evaluate', (['expr', 'expr_dict'], {}), '(expr, expr_dict)\n', (1821, 1838), True, 'import numexpr as ne\n'), ((6195, 6244), 'datafold.utils.general.diagmat_dot_mat', 'diagmat_dot_mat', (['vec_inv_left', 'matrix'], {'out': 'matrix'}), '(vec_inv_left, matrix, out=matrix)\n', (6210, 6244), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((6262, 6312), 'datafold.utils.general.mat_dot_diagmat', 'mat_dot_diagmat', (['matrix', 'vec_inv_right'], {'out': 'matrix'}), '(matrix, vec_inv_right, out=matrix)\n', (6277, 6312), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((6498, 6543), 'datafold.utils.general.remove_numeric_noise_symmetric_matrix', 'remove_numeric_noise_symmetric_matrix', (['matrix'], {}), '(matrix)\n', (6535, 6543), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((6614, 6653), 'numpy.multiply', 'np.multiply', (['matrix', 'scalar'], {'out': 'matrix'}), '(matrix, scalar, out=matrix)\n', (6625, 6653), True, 'import numpy as np\n'), ((8793, 8830), 'numpy.reciprocal', 'np.reciprocal', (['left_vec'], {'out': 'left_vec'}), '(left_vec, out=left_vec)\n', (8806, 8830), True, 'import numpy as np\n'), ((9981, 10028), 'sklearn.preprocessing.normalize', 'normalize', (['kernel_matrix'], {'copy': '(False)', 'norm': '"""l1"""'}), "(kernel_matrix, copy=False, norm='l1')\n", (9990, 10028), False, 'from sklearn.preprocessing import normalize\n'), ((10078, 10107), 'numpy.sum', 'np.sum', (['kernel_matrix'], {'axis': '(1)'}), '(kernel_matrix, axis=1)\n', (10084, 10107), True, 'import numpy as np\n'), ((10821, 10871), 'datafold.utils.general.diagmat_dot_mat', 'diagmat_dot_mat', (['normalize_diagonal', 'kernel_matrix'], {}), '(normalize_diagonal, kernel_matrix)\n', (10836, 10871), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((11563, 11576), 'datafold.utils.general.is_integer', 'is_integer', (['k'], {}), '(k)\n', (11573, 11576), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((25951, 25967), 'numpy.atleast_2d', 'np.atleast_2d', (['X'], {}), '(X)\n', (25964, 25967), True, 'import numpy as np\n'), ((26055, 26134), 'datafold.pcfold.distance.compute_distance_matrix', 'compute_distance_matrix', (['X', 'Y'], {'metric': 'self.distance_metric'}), '(X, Y, metric=self.distance_metric, **dist_kwargs or {})\n', (26078, 26134), False, 'from datafold.pcfold.distance import compute_distance_matrix\n'), ((37166, 37230), 'datafold.pcfold.distance.compute_distance_matrix', 'compute_distance_matrix', (['X', 'Y'], {'metric': '"""euclidean"""'}), "(X, Y, metric='euclidean', **dist_kwargs)\n", (37189, 37230), False, 'from datafold.pcfold.distance import compute_distance_matrix\n'), ((56677, 56782), 'sklearn.utils.check_scalar', 'check_scalar', (['self.fd_accuracy', '"""fd_accuracy"""'], {'target_type': '(int, np.integer)', 'min_val': '(1)', 'max_val': 'None'}), "(self.fd_accuracy, 'fd_accuracy', target_type=(int, np.integer),\n min_val=1, max_val=None)\n", (56689, 56782), False, 'from sklearn.utils import check_scalar\n'), ((58237, 58283), 'numpy.zeros', 'np.zeros', (['(Y_numpy.shape[0], X_numpy.shape[0])'], {}), '((Y_numpy.shape[0], X_numpy.shape[0]))\n', (58245, 58283), True, 'import numpy as np\n'), ((59870, 59904), 'numpy.cos', 'np.cos', (['cos_matrix'], {'out': 'cos_matrix'}), '(cos_matrix, out=cos_matrix)\n', (59876, 59904), True, 'import numpy as np\n'), ((59926, 59963), 'numpy.square', 'np.square', (['cos_matrix'], {'out': 'cos_matrix'}), '(cos_matrix, out=cos_matrix)\n', (59935, 59963), True, 'import numpy as np\n'), ((59985, 60035), 'numpy.multiply', 'np.multiply', (['self.zeta', 'cos_matrix'], {'out': 'cos_matrix'}), '(self.zeta, cos_matrix, out=cos_matrix)\n', (59996, 60035), True, 'import numpy as np\n'), ((60057, 60101), 'numpy.subtract', 'np.subtract', (['(1.0)', 'cos_matrix'], {'out': 'cos_matrix'}), '(1.0, cos_matrix, out=cos_matrix)\n', (60068, 60101), True, 'import numpy as np\n'), ((71028, 71041), 'numpy.mean', 'np.mean', (['rho0'], {}), '(rho0)\n', (71035, 71041), True, 'import numpy as np\n'), ((71718, 71741), 'numpy.power', 'np.power', (['q0', 'self.beta'], {}), '(q0, self.beta)\n', (71726, 71741), True, 'import numpy as np\n'), ((72065, 72103), 'numpy.exp', 'np.exp', (['expon_matrix'], {'out': 'expon_matrix'}), '(expon_matrix, out=expon_matrix)\n', (72071, 72103), True, 'import numpy as np\n'), ((72274, 72318), 'numpy.sum', 'np.sum', (['(kernel_eps_s / rho_power_dim)'], {'axis': '(1)'}), '(kernel_eps_s / rho_power_dim, axis=1)\n', (72280, 72318), True, 'import numpy as np\n'), ((73437, 73488), 'datafold.utils.general.remove_numeric_noise_symmetric_matrix', 'remove_numeric_noise_symmetric_matrix', (['matrix_l_hat'], {}), '(matrix_l_hat)\n', (73474, 73488), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((74271, 74337), 'datafold.pcfold.distance.compute_distance_matrix', 'compute_distance_matrix', (['X', 'Y'], {'metric': '"""sqeuclidean"""'}), "(X, Y, metric='sqeuclidean', **dist_kwargs)\n", (74294, 74337), False, 'from datafold.pcfold.distance import compute_distance_matrix\n'), ((75651, 75690), 'datafold.utils.general.is_symmetric_matrix', 'is_symmetric_matrix', (['kernel_eps_alpha_s'], {}), '(kernel_eps_alpha_s)\n', (75670, 75690), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((5758, 5779), 'numpy.isinf', 'np.isinf', (['matrix.data'], {}), '(matrix.data)\n', (5766, 5779), True, 'import numpy as np\n'), ((10122, 10165), 'numpy.errstate', 'np.errstate', ([], {'divide': '"""ignore"""', 'over': '"""ignore"""'}), "(divide='ignore', over='ignore')\n", (10133, 10165), True, 'import numpy as np\n'), ((10550, 10607), 'numpy.reciprocal', 'np.reciprocal', (['normalize_diagonal'], {'out': 'normalize_diagonal'}), '(normalize_diagonal, out=normalize_diagonal)\n', (10563, 10607), True, 'import numpy as np\n'), ((10689, 10717), 'numpy.isinf', 'np.isinf', (['normalize_diagonal'], {}), '(normalize_diagonal)\n', (10697, 10717), True, 'import numpy as np\n'), ((12003, 12047), 'numpy.partition', 'np.partition', (['distance_matrix', '(k - 1)'], {'axis': '(1)'}), '(distance_matrix, k - 1, axis=1)\n', (12015, 12047), True, 'import numpy as np\n'), ((26011, 26027), 'numpy.atleast_2d', 'np.atleast_2d', (['Y'], {}), '(Y)\n', (26024, 26027), True, 'import numpy as np\n'), ((34377, 34399), 'datafold.utils.general.is_integer', 'is_integer', (['k_neighbor'], {}), '(k_neighbor)\n', (34387, 34399), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((34591, 34606), 'datafold.utils.general.is_float', 'is_float', (['delta'], {}), '(delta)\n', (34599, 34606), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((34623, 34640), 'datafold.utils.general.is_integer', 'is_integer', (['delta'], {}), '(delta)\n', (34633, 34640), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((44428, 44462), 'datafold.utils.general.is_symmetric_matrix', 'is_symmetric_matrix', (['kernel_matrix'], {}), '(kernel_matrix)\n', (44447, 44462), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((45106, 45150), 'numpy.power', 'np.power', (['row_sums', 'self.alpha'], {'out': 'row_sums'}), '(row_sums, self.alpha, out=row_sums)\n', (45114, 45150), True, 'import numpy as np\n'), ((47606, 47642), 'datafold.utils.general.is_symmetric_matrix', 'is_symmetric_matrix', (['internal_kernel'], {}), '(internal_kernel)\n', (47625, 47642), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((57334, 57410), 'datafold.utils.general.is_df_same_index', 'is_df_same_index', (['X', 'Y'], {'check_index': '(False)', 'check_column': '(True)', 'handle': '"""raise"""'}), "(X, Y, check_index=False, check_column=True, handle='raise')\n", (57350, 57410), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((57579, 57651), 'datafold.pcfold.timeseries.accessor.TSCAccessor.check_equal_delta_time', 'TSCAccessor.check_equal_delta_time', (['X', 'Y'], {'atol': '(1e-15)', 'require_const': '(True)'}), '(X, Y, atol=1e-15, require_const=True)\n', (57613, 57651), False, 'from datafold.pcfold.timeseries.accessor import TSCAccessor\n'), ((58347, 58372), 'numpy.zeros_like', 'np.zeros_like', (['cos_matrix'], {}), '(cos_matrix)\n', (58360, 58372), True, 'import numpy as np\n'), ((58576, 58634), 'numpy.subtract', 'np.subtract', (['X_numpy', 'Y_numpy[row_idx, :]'], {'out': 'diff_matrix'}), '(X_numpy, Y_numpy[row_idx, :], out=diff_matrix)\n', (58587, 58634), True, 'import numpy as np\n'), ((58983, 59072), 'numpy.multiply', 'np.multiply', (['norm_timederiv_Y[row_idx]', 'distance_matrix[row_idx, :]'], {'out': 'denominator'}), '(norm_timederiv_Y[row_idx], distance_matrix[row_idx, :], out=\n denominator)\n', (58994, 59072), True, 'import numpy as np\n'), ((59245, 59319), 'numpy.dot', 'np.dot', (['timederiv_Y[row_idx, :]', 'diff_matrix.T'], {'out': 'cos_matrix[row_idx, :]'}), '(timederiv_Y[row_idx, :], diff_matrix.T, out=cos_matrix[row_idx, :])\n', (59251, 59319), True, 'import numpy as np\n'), ((59498, 59546), 'numpy.less_equal', 'np.less_equal', (['denominator', '(1e-14)'], {'out': 'zero_mask'}), '(denominator, 1e-14, out=zero_mask)\n', (59511, 59546), True, 'import numpy as np\n'), ((71838, 71850), 'numpy.mean', 'np.mean', (['rho'], {}), '(rho)\n', (71845, 71850), True, 'import numpy as np\n'), ((72208, 72240), 'numpy.power', 'np.power', (['rho', 'self.expected_dim'], {}), '(rho, self.expected_dim)\n', (72216, 72240), True, 'import numpy as np\n'), ((72653, 72667), 'numpy.square', 'np.square', (['rho'], {}), '(rho)\n', (72662, 72667), True, 'import numpy as np\n'), ((75107, 75143), 'datafold.utils.general.is_symmetric_matrix', 'is_symmetric_matrix', (['distance_matrix'], {}), '(distance_matrix)\n', (75126, 75143), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((6010, 6031), 'numpy.isnan', 'np.isnan', (['matrix.data'], {}), '(matrix.data)\n', (6018, 6031), True, 'import numpy as np\n'), ((6391, 6407), 'numpy.isnan', 'np.isnan', (['matrix'], {}), '(matrix)\n', (6399, 6407), True, 'import numpy as np\n'), ((37916, 37940), 'numpy.diag', 'np.diag', (['distance_matrix'], {}), '(distance_matrix)\n', (37923, 37940), True, 'import numpy as np\n'), ((40413, 40430), 'numpy.sqrt', 'np.sqrt', (['dist_knn'], {}), '(dist_knn)\n', (40420, 40430), True, 'import numpy as np\n'), ((60508, 60541), 'numpy.linalg.norm', 'np.linalg.norm', (['timederiv'], {'axis': '(1)'}), '(timederiv, axis=1)\n', (60522, 60541), True, 'import numpy as np\n'), ((63055, 63120), 'numpy.multiply', 'np.multiply', (['cos_matrix_Y_X', 'cos_matrix_Y_X.T'], {'out': 'cos_matrix_Y_X'}), '(cos_matrix_Y_X, cos_matrix_Y_X.T, out=cos_matrix_Y_X)\n', (63066, 63120), True, 'import numpy as np\n'), ((63188, 63223), 'numpy.sqrt', 'np.sqrt', (['cos_matrix'], {'out': 'cos_matrix'}), '(cos_matrix, out=cos_matrix)\n', (63195, 63223), True, 'import numpy as np\n'), ((63301, 63348), 'numpy.square', 'np.square', (['distance_matrix'], {'out': 'distance_matrix'}), '(distance_matrix, out=distance_matrix)\n', (63310, 63348), True, 'import numpy as np\n'), ((63401, 63455), 'datafold.pcfold.distance.compute_distance_matrix', 'compute_distance_matrix', (['X_numpy'], {'metric': '"""sqeuclidean"""'}), "(X_numpy, metric='sqeuclidean')\n", (63424, 63455), False, 'from datafold.pcfold.distance import compute_distance_matrix\n'), ((63485, 63530), 'numpy.ones', 'np.ones', (['(X_numpy.shape[0], X_numpy.shape[0])'], {}), '((X_numpy.shape[0], X_numpy.shape[0]))\n', (63492, 63530), True, 'import numpy as np\n'), ((65018, 65083), 'numpy.multiply', 'np.multiply', (['cos_matrix_Y_X', 'cos_matrix_X_Y.T'], {'out': 'cos_matrix_Y_X'}), '(cos_matrix_Y_X, cos_matrix_X_Y.T, out=cos_matrix_Y_X)\n', (65029, 65083), True, 'import numpy as np\n'), ((65151, 65186), 'numpy.sqrt', 'np.sqrt', (['cos_matrix'], {'out': 'cos_matrix'}), '(cos_matrix, out=cos_matrix)\n', (65158, 65186), True, 'import numpy as np\n'), ((65264, 65311), 'numpy.square', 'np.square', (['distance_matrix'], {'out': 'distance_matrix'}), '(distance_matrix, out=distance_matrix)\n', (65273, 65311), True, 'import numpy as np\n'), ((65364, 65427), 'datafold.pcfold.distance.compute_distance_matrix', 'compute_distance_matrix', (['X_numpy', 'Y_numpy'], {'metric': '"""sqeuclidean"""'}), "(X_numpy, Y_numpy, metric='sqeuclidean')\n", (65387, 65427), False, 'from datafold.pcfold.distance import compute_distance_matrix\n'), ((65495, 65540), 'numpy.ones', 'np.ones', (['(Y_numpy.shape[0], X_numpy.shape[0])'], {}), '((Y_numpy.shape[0], X_numpy.shape[0]))\n', (65502, 65540), True, 'import numpy as np\n'), ((65872, 65898), 'numpy.isfinite', 'np.isfinite', (['factor_matrix'], {}), '(factor_matrix)\n', (65883, 65898), True, 'import numpy as np\n'), ((67150, 67174), 'datafold.utils.general.is_integer', 'is_integer', (['expected_dim'], {}), '(expected_dim)\n', (67160, 67174), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((67408, 67432), 'datafold.utils.general.is_integer', 'is_integer', (['expected_dim'], {}), '(expected_dim)\n', (67418, 67432), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((69030, 69067), 'numpy.mean', 'np.mean', (['(distance_matrix ** 2)'], {'axis': '(1)'}), '(distance_matrix ** 2, axis=1)\n', (69037, 69067), True, 'import numpy as np\n'), ((69549, 69590), 'numpy.fill_diagonal', 'np.fill_diagonal', (['distance_matrix', 'np.inf'], {}), '(distance_matrix, np.inf)\n', (69565, 69590), True, 'import numpy as np\n'), ((69742, 69786), 'numpy.sort', 'np.sort', (['distance_matrix[:, :self.k]'], {'axis': '(1)'}), '(distance_matrix[:, :self.k], axis=1)\n', (69749, 69786), True, 'import numpy as np\n'), ((69910, 69951), 'numpy.fill_diagonal', 'np.fill_diagonal', (['distance_matrix', 'np.nan'], {}), '(distance_matrix, np.nan)\n', (69926, 69951), True, 'import numpy as np\n'), ((70863, 70898), 'numpy.nanmean', 'np.nanmean', (['distance_matrix'], {'axis': '(1)'}), '(distance_matrix, axis=1)\n', (70873, 70898), True, 'import numpy as np\n'), ((71428, 71478), 'numpy.power', 'np.power', (['(2 * np.pi * eps0)', '(-self.expected_dim / 2)'], {}), '(2 * np.pi * eps0, -self.expected_dim / 2)\n', (71436, 71478), True, 'import numpy as np\n'), ((71563, 71583), 'numpy.exp', 'np.exp', (['expon_matrix'], {}), '(expon_matrix)\n', (71569, 71583), True, 'import numpy as np\n'), ((72503, 72532), 'numpy.power', 'np.power', (['q_eps_s', 'self.alpha'], {}), '(q_eps_s, self.alpha)\n', (72511, 72532), True, 'import numpy as np\n'), ((72757, 72774), 'numpy.eye', 'np.eye', (['n_samples'], {}), '(n_samples)\n', (72763, 72774), True, 'import numpy as np\n'), ((72920, 72942), 'numpy.sqrt', 'np.sqrt', (['q_eps_alpha_s'], {}), '(q_eps_alpha_s)\n', (72927, 72942), True, 'import numpy as np\n'), ((73201, 73215), 'numpy.square', 'np.square', (['rho'], {}), '(rho)\n', (73210, 73215), True, 'import numpy as np\n'), ((73820, 73837), 'numpy.isinf', 'np.isinf', (['cut_off'], {}), '(cut_off)\n', (73828, 73837), True, 'import numpy as np\n'), ((24919, 24934), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (24927, 24934), True, 'import numpy as np\n'), ((40454, 40481), 'numpy.sqrt', 'np.sqrt', (['reference_dist_knn'], {}), '(reference_dist_knn)\n', (40461, 40481), True, 'import numpy as np\n'), ((56611, 56626), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (56619, 56626), True, 'import numpy as np\n'), ((60118, 60141), 'numpy.isfinite', 'np.isfinite', (['cos_matrix'], {}), '(cos_matrix)\n', (60129, 60141), True, 'import numpy as np\n'), ((67291, 67313), 'datafold.utils.general.is_float', 'is_float', (['expected_dim'], {}), '(expected_dim)\n', (67299, 67313), False, 'from datafold.utils.general import df_type_and_indices_from, diagmat_dot_mat, is_df_same_index, is_float, is_integer, is_symmetric_matrix, mat_dot_diagmat, remove_numeric_noise_symmetric_matrix\n'), ((68920, 68944), 'numpy.sqrt', 'np.sqrt', (['distance_matrix'], {}), '(distance_matrix)\n', (68927, 68944), True, 'import numpy as np\n'), ((71494, 71527), 'numpy.power', 'np.power', (['rho0', 'self.expected_dim'], {}), '(rho0, self.expected_dim)\n', (71502, 71527), True, 'import numpy as np\n'), ((73364, 73400), 'numpy.ones', 'np.ones', (['kernel_eps_alpha_s.shape[0]'], {}), '(kernel_eps_alpha_s.shape[0])\n', (73371, 73400), True, 'import numpy as np\n'), ((12552, 12620), 'numpy.partition', 'np.partition', (['data[start_row:start_row + row_nnz[i]]', '(k_neighbor - 1)'], {}), '(data[start_row:start_row + row_nnz[i]], k_neighbor - 1)\n', (12564, 12620), True, 'import numpy as np\n'), ((56420, 56435), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (56428, 56435), True, 'import numpy as np\n'), ((66291, 66318), 'numpy.arange', 'np.arange', (['X_numpy.shape[0]'], {}), '(X_numpy.shape[0])\n', (66300, 66318), True, 'import numpy as np\n'), ((75161, 75185), 'numpy.diag', 'np.diag', (['distance_matrix'], {}), '(distance_matrix)\n', (75168, 75185), True, 'import numpy as np\n'), ((69989, 70008), 'numpy.ones', 'np.ones', (['nr_samples'], {}), '(nr_samples)\n', (69996, 70008), True, 'import numpy as np\n')]
## # @file plot_lqg.py # @author <NAME> # @date Apr 2018 # import matplotlib.pyplot as plt import numpy as np import re import glob def read(filename, cumulative_flag): print("reading %s" % (filename)) data = [] with open(filename, "r") as f: count = 1 epoch = None cost = None for line in f: search_cost = re.search(r"at epoch (\d+), the current policy has cost ([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)", line) if search_cost: epoch = float(search_cost.group(1)) cost = float(search_cost.group(2)) assert epoch is not None assert cost is not None data.append([epoch, cost]) if cumulative_flag and len(data) > 1: # use current best reward data[-1][1] = min(data[-1][1], data[-2][1]) count += 1 return np.array(data) seed_array = [29784, 15851, 12955, 1498, 21988, 7706, 31727, 2774, 8287, 20590] alg_array = ["Plain_GD", "Natural_GD", "Newton_Natural_GD"] env = "LQG" cumulative_flag = True data_map = {} for alg in alg_array: data = [] for seed in seed_array: entry = read("log/%s.%s.seed%d.log" % (env, alg, seed), cumulative_flag) print(entry.shape) data.append(entry) data = np.array(data) data_map[alg] = data # plot ret_all for alg in alg_array: data = data_map[alg] avg_data = np.mean(data, axis=0) std_data = np.std(data, axis=0) print(avg_data) print(std_data) p = plt.semilogy(avg_data[:, 0], avg_data[:, 1], label=alg) plt.fill_between(avg_data[:, 0], avg_data[:, 1]-std_data[:, 1], avg_data[:, 1]+std_data[:, 1], where=avg_data[:, 1]-std_data[:, 1] > 0, color=p[-1].get_color(), alpha=0.4) plt.legend() plt.xlabel("Epoch") plt.ylabel("cumulative cost" if cumulative_flag else "cost") plt.title("%s" % env) plt.tight_layout() filename = "log/%s.%s.cost.png" % (env, alg) print("save to %s" % (filename)) plt.savefig(filename, pad_inches=0.0) filename = filename.replace("png", "pdf") print("save to %s" % (filename)) plt.savefig(filename, pad_inches=0.0)
[ "numpy.mean", "matplotlib.pyplot.semilogy", "matplotlib.pyplot.savefig", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "numpy.array", "matplotlib.pyplot.tight_layout", "numpy.std", "matplotlib.pyplot.title", "matplotlib.pyplot.legend", "re.search" ]
[((1795, 1807), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (1805, 1807), True, 'import matplotlib.pyplot as plt\n'), ((1808, 1827), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epoch"""'], {}), "('Epoch')\n", (1818, 1827), True, 'import matplotlib.pyplot as plt\n'), ((1828, 1888), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (["('cumulative cost' if cumulative_flag else 'cost')"], {}), "('cumulative cost' if cumulative_flag else 'cost')\n", (1838, 1888), True, 'import matplotlib.pyplot as plt\n'), ((1889, 1910), 'matplotlib.pyplot.title', 'plt.title', (["('%s' % env)"], {}), "('%s' % env)\n", (1898, 1910), True, 'import matplotlib.pyplot as plt\n'), ((1911, 1929), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (1927, 1929), True, 'import matplotlib.pyplot as plt\n'), ((2008, 2045), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'pad_inches': '(0.0)'}), '(filename, pad_inches=0.0)\n', (2019, 2045), True, 'import matplotlib.pyplot as plt\n'), ((2121, 2158), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename'], {'pad_inches': '(0.0)'}), '(filename, pad_inches=0.0)\n', (2132, 2158), True, 'import matplotlib.pyplot as plt\n'), ((918, 932), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (926, 932), True, 'import numpy as np\n'), ((1334, 1348), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (1342, 1348), True, 'import numpy as np\n'), ((1454, 1475), 'numpy.mean', 'np.mean', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (1461, 1475), True, 'import numpy as np\n'), ((1491, 1511), 'numpy.std', 'np.std', (['data'], {'axis': '(0)'}), '(data, axis=0)\n', (1497, 1511), True, 'import numpy as np\n'), ((1562, 1617), 'matplotlib.pyplot.semilogy', 'plt.semilogy', (['avg_data[:, 0]', 'avg_data[:, 1]'], {'label': 'alg'}), '(avg_data[:, 0], avg_data[:, 1], label=alg)\n', (1574, 1617), True, 'import matplotlib.pyplot as plt\n'), ((377, 498), 're.search', 're.search', (['"""at epoch (\\\\d+), the current policy has cost ([+-]?(\\\\d+(\\\\.\\\\d*)?|\\\\.\\\\d+)([eE][+-]?\\\\d+)?)"""', 'line'], {}), "(\n 'at epoch (\\\\d+), the current policy has cost ([+-]?(\\\\d+(\\\\.\\\\d*)?|\\\\.\\\\d+)([eE][+-]?\\\\d+)?)'\n , line)\n", (386, 498), False, 'import re\n')]
import numpy as np from skimage import draw image_shape = (512, 512) polygon = np.array([[80, 111, 146, 234, 407, 300, 187, 45], [465, 438, 499, 380, 450, 287, 210, 167]]).T def test_polygon2mask(): mask = draw.polygon2mask(image_shape, polygon) assert mask.shape == image_shape assert mask.sum() == 57653
[ "numpy.array", "skimage.draw.polygon2mask" ]
[((82, 178), 'numpy.array', 'np.array', (['[[80, 111, 146, 234, 407, 300, 187, 45], [465, 438, 499, 380, 450, 287, 210,\n 167]]'], {}), '([[80, 111, 146, 234, 407, 300, 187, 45], [465, 438, 499, 380, 450,\n 287, 210, 167]])\n', (90, 178), True, 'import numpy as np\n'), ((235, 274), 'skimage.draw.polygon2mask', 'draw.polygon2mask', (['image_shape', 'polygon'], {}), '(image_shape, polygon)\n', (252, 274), False, 'from skimage import draw\n')]
from numba import types from numba.core.extending import typeof_impl, type_callable from numba.core.typing import signature from numba.core.extending import models, register_model, lower_builtin from numba.core import cgutils from numba.cpython import mathimpl from numba.cuda.cudadecl import registry as decl_registry from numba.cuda.cudaimpl import registry as impl_registry from numba.core.typing.templates import ConcreteTemplate, AttributeTemplate import operator from .vectortype import ( char2, short2, int2, long2, uchar2, ushort2, uint2, ulong2, float2, double2, char3, short3, int3, long3, uchar3, ushort3, uint3, ulong3, float3, double3) from .vectordecl import VectorType, Vector2Type, Vector3Type from .vectordecl import (char2_t, short2_t, int2_t, long2_t, uchar2_t, ushort2_t, uint2_t, ulong2_t, float2_t, double2_t, char3_t, short3_t, int3_t, long3_t, uchar3_t, ushort3_t, uint3_t, ulong3_t, float3_t, double3_t) from llvmlite import ir from .. import mathfuncs import numpy as np #for loop example #https://github.com/numba/numba/blob/7df40d2e36d15c4965b849b109c06593d6cc7b64/numba/core/cgutils.py#L487 #generic libfunc helper function for unary and binary vector ops def libfunc_helper_wrapper(cuda_op): def libfunc_helper(context, builder, sig, args): # types = [sig.return_type._member_t] # for typ in sig.args: # if isinstance(typ, VectorType): # types.append(sig.return_type._member_t) # else: # types.append(sig.return_type.__precision__) types = [sig.return_type._member_t]*(len(sig.args) + 1) sig = signature(*types) return context.get_function(cuda_op, sig), libfunc_op_caller return libfunc_helper ##################### #op caller functions# ##################### #these are returned from a helper function along with the op(s) that the caller function will call. #builder, mathimpl, and libfunc each have their own calling convention so a unique caller is required for each. def builder_op_caller(op, builder, out, *args): for n, attr in enumerate(out._fe_type._fields): setattr(out, attr, op(*[arg[n] for arg in args])) return out._getvalue() def mathimpl_op_caller(op, builder, out, *args): for n, attr in enumerate(out._fe_type._fields): setattr(out, attr, op(builder, *[arg[n] for arg in args])) return out._getvalue() def libfunc_op_caller(op, builder, out, *args): for n, attr in enumerate(out._fe_type._fields): setattr(out, attr, op(builder, [arg[n] for arg in args])) return out._getvalue() ########### #UNARY OPS# ########### def unary_op_factory(op, vec_t, op_helper): @impl_registry.lower(op, vec_t) def cuda_op_vec(context, builder, sig, args): f = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = args[0]) members = [getattr(f, attr) for attr in sig.return_type._fields] out_ptr = cgutils.alloca_once(builder, args[0].type.pointee, size = 1) out = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = out_ptr) op, caller = op_helper(context, builder, sig, args) caller(op, builder, out, members) return out_ptr ######################### #unary callers functions# ######################### ######################## #unary helper functions# ######################## #a helper function defines the operation(s) to be called on the vector as well as returns the caller that will execute the operation(s) # def neg_helper(context, builder, sig, args): # # neg = builder.neg # # caller = builder_op_caller # # if isinstance(sig.return_type._member_t, types.Float): # # neg = mathimpl.negate_real # # caller = mathimpl_op_caller # # return neg, caller # # # #for when fneg is supported # # # neg = builder.neg # # # if isinstance(sig.return_type._member_t, types.Float): # # # neg = builder.fneg # # # return neg, builder_op_caller # libsig = signature(sig.args[0]._member_t, # sig.args[0]._member_t) # neg = context.get_function(operator.neg, libsig) # return neg, libfunc_op_caller ############ #BINARY OPS# ############ def binary_op_factory_vec_vec(op, vec_t, op_helper): @impl_registry.lower(op, vec_t, vec_t) def cuda_op_vec_vec(context, builder, sig, args): a = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) b = cgutils.create_struct_proxy(sig.args[1], 'data')(context, builder, ref = args[1]) #need to convert numba type to llvmlite type # temp = ir.LiteralStructType([vec_t._member_t for _ in range(len(sig.return_type._fields))]) # print(temp) # _be_type # print(vec_t, sig.return_type) # vec_ptr = cgutils.alloca_once(builder, args[0].type.pointee, size = 1) vec_ptr = cgutils.alloca_once(builder, args[0].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) # print(args[0]) # print(args[0].type) # print(args[0].type.pointee) a_members = [getattr(a, attr) for attr in sig.return_type._fields] b_members = [getattr(b, attr) for attr in sig.return_type._fields] op, caller = op_helper(context, builder, sig, args) caller(op, builder, vec, a_members, b_members) return vec_ptr #note: mtv = member to vector (converts a scalar to a vector containing the scalar for every entry) def binary_op_factory_vec_mtv(op, vec_t, op_helper): #converts scalar argument to a vector of the same length as the other argument @impl_registry.lower(op, vec_t, types.Number) def cuda_op_vec_mtv(context, builder, sig, args): a = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) b = context.cast(builder, args[1], sig.args[1], sig.return_type._member_t) vec_ptr = cgutils.alloca_once(builder, args[0].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) a_members = [getattr(a, attr) for attr in sig.return_type._fields] b_members = [b for attr in sig.return_type._fields] op_, caller = op_helper(context, builder, sig, args) caller(op_, builder, vec, a_members, b_members) return vec_ptr @impl_registry.lower(op, types.Number, vec_t) def cuda_op_mtv_vec(context, builder, sig, args): a = context.cast(builder, args[0], sig.args[0], sig.return_type._member_t) b = cgutils.create_struct_proxy(sig.args[1], 'data')(context, builder, ref = args[1]) vec_ptr = cgutils.alloca_once(builder, args[1].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) a_members = [a for attr in sig.return_type._fields] b_members = [getattr(b, attr) for attr in sig.return_type._fields] op, caller = op_helper(context, builder, sig, args) caller(op, builder, vec, a_members, b_members) return vec_ptr def binary_op_factory(op, vec_t, op_helper): binary_op_factory_vec_vec(op, vec_t, op_helper) binary_op_factory_vec_mtv(op, vec_t, op_helper) def binary_op_factory_vec_scalar(op, vec_t, op_helper, scalar_type = types.Number): @impl_registry.lower(op, vec_t, scalar_type) def cuda_op_vec_scalar(context, builder, sig, args): vec = cgutils.create_struct_proxy(vec_t, 'data')(context, builder, ref = args[0]) scalar = args[1] vec_members = [getattr(vec, attr) for attr in sig.args[0]._fields] vec_ptr = cgutils.alloca_once(builder, args[0].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) caller = op_helper(context, builder, sig, args) caller(vec, vec_members, scalar) return vec_ptr ######################### #binary callers functions# ######################### #first argument is vector, second argument is integer # #hard coded conditionals for up to a length 4 vector. For support of any length this will need to be a for loop # first = builder.icmp_signed('==', n, one) # with builder.if_else(first) as (true, false): # with true: # for m in range(member_count): # setattr(out, member_names[(n + 1)%member_count], getattr(vec, member_names[m])) # with false: # second = builder.icmp_signed('==', n, two) # with builder.if_else(second) as (true, false): # with true: # for m in range(member_count): # setattr(out, member_names[(n + 2)%member_count], getattr(vec, member_names[m])) # with false: # third = builder.icmp_signed('==', n, three) # with builder.if_else(third) as (true, false): # with true: # for m in range(member_count): # setattr(out, member_names[(n + 3)%member_count], getattr(vec, member_names[m])) # with false: # fourth = builder.icmp_signed('==', n, four) # with builder.if_else(fourth) as (true, false): # with true: # for m in range(member_count): # setattr(out, member_names[(n + 4)%member_count], getattr(vec, member_names[m])) # with false: # return out # else_ = builder.append_basic_block("shift.else") # end_ = builder.append_basic_block("shift.end") # switch = builder.switch(scalar, else_) # with # loop(scalar) # out.x = vec.z # out.y = vec.x # out.z = vec.y # vec = out # # builder.icmp_signed() # # with builder.if_then(): # # with true: # # pass # # with false: # # pass # # add, mul, sqrt = ops # # val = mul(builder, [vec[0], vec[0]]) # # for n in range(len(vec) - 1): # # val = add(builder, [val, mul(builder, [vec[n + 1], vec[n + 1]])]) # # return sqrt(builder, [val]) ######################## #binary helper functions# ######################## def shift_impl(context, builder, sig, out, vec, n, member_current): member_names = out._fe_type._fields member_count = len(member_names) idx = context.get_constant(types.int8, np.int8(member_current)) if member_current < member_count: with builder.if_else(builder.icmp_unsigned('==', n, idx)) as (true, false): with true: for m in range(member_count): setattr(out, member_names[(m + member_current)%member_count], vec[m]) with false: shift_impl(context, builder, sig, out, vec, n, member_current + 1) return out def shift_helper(context, builder, sig, args): # scalar = args[1] # zero = context.get_constant(scalar.type, 0) # one = context.get_constant(scalar.type, 1) # two = context.get_constant(scalar.type, 2) # three = context.get_constant(scalar.type, 3) # four = context.get_constant(scalar.type, 4) # libsig = signature(args[1].type, args[1].type, args[1].type) # minimum = context.get_function(min, libsig) # maximum = context.get_function(max, libsig) # def shift_caller(ops, out, vec, scalar): # #scalar.type # libsig = signature(types.int32, types.int32, types.int32) # minimum = context.get_function(min, libsig) # maximum = context.get_function(max, libsig) # member_names = out._fe_type._fields # member_count = len(member_names) # scalar = context.cast(builder, scalar, sig.args[1], types.int32) # #clip scalar to length of vec # zero = context.get_constant(types.int32, 0) # length = context.get_constant(types.int32, member_count - 1) # n = minimum(builder, [length, maximum(builder, [zero, scalar])]) # return shift_impl(context, builder, out, vec, scalar, n, 0)._getvalue() def shift_caller(out, vec, n): modulo = context.get_function(operator.mod, signature(types.int8, types.int8, types.int8)) member_names = out._fe_type._fields member_count = len(member_names) n = context.cast(builder, n, sig.args[1], types.int8) length = context.get_constant(types.int8, member_count) # out.x = context.cast(builder, n, types.uint32, types.float32) # out.y = context.cast(builder, n, types.uint32, types.float32) # out.z = context.cast(builder, n, types.uint32, types.float32) n = modulo(builder, [n, length]) out = shift_impl(context, builder, sig, out, vec, n, 0) return out._getvalue() return shift_caller # def add_helper(context, builder, sig, args): # add = builder.add # if isinstance(sig.return_type._member_t, types.Float): # add = builder.fadd # return add, builder_op_caller # def sub_helper(context, builder, sig, args): # sub = builder.sub # if isinstance(sig.return_type._member_t, types.Float): # sub = builder.fsub # return sub, builder_op_caller # def mul_helper(context, builder, sig, args): # mul = builder.mul # if isinstance(sig.return_type._member_t, types.Float): # mul = builder.fmul # return mul, builder_op_caller # def div_helper(context, builder, sig, args): # div = builder.udiv # if isinstance(sig.return_type._member_t, types.Float): # div = builder.fdiv # elif sig.return_type._member_t._member_t.signed: # div = builder.sdiv # return div, builder_op_caller # def mod_helper(context, builder, sig, args): # libfunc_impl = context.get_function(cuda_op, sig) # # mod = # # for n, attr in enumerate(vec_t._fields): # # setattr(out, attr, libfunc_impl(builder, [getattr(a, attr)])) # # # out.x = libfunc_impl(builder, [a.x]) # # # out.y = libfunc_impl(builder, [a.y]) # def pow_helper(context, builder, sig, args): # pass #DONT WANT TO CAST SCALAR VALUE USED FOR POWER # out = cgutils.create_struct_proxy(vec_t)(context, builder) # libfunc_impl = context.get_function(operator.pow, signature(ax, ax, ax)) # out.x = libfunc_impl(builder, [ax, bx]) # out.y = libfunc_impl(builder, [ay, by]) # return out._getvalue() ############# #TERNARY OPS# ############# def ternary_op_factory_vec_vec_vec(op, vec_t, op_helper): @impl_registry.lower(op, vec_t, vec_t, vec_t) def cuda_op_vec_vec_vec(context, builder, sig, args): a = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) b = cgutils.create_struct_proxy(sig.args[1], 'data')(context, builder, ref = args[1]) c = cgutils.create_struct_proxy(sig.args[2], 'data')(context, builder, ref = args[2]) vec_ptr = cgutils.alloca_once(builder, args[0].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) a_members = [getattr(a, attr) for attr in sig.return_type._fields] b_members = [getattr(b, attr) for attr in sig.return_type._fields] c_members = [getattr(c, attr) for attr in sig.return_type._fields] op, caller = op_helper(context, builder, sig, args) caller(op, builder, vec, a_members, b_members, c_members) return vec_ptr #note: mtv = member to vector (converts a scalar to a vector containing the scalar for every entry) def ternary_op_factory_vec_vec_mtv(op, vec_t, op_helper): @impl_registry.lower(op, vec_t, vec_t, types.Number) def cuda_op_vec_vec_mtv(context, builder, sig, args): a = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) b = cgutils.create_struct_proxy(sig.args[1], 'data')(context, builder, ref = args[1]) c = context.cast(builder, args[2], sig.args[2], vec_t._member_t) vec_ptr = cgutils.alloca_once(builder, args[0].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) a_members = [getattr(a, attr) for attr in sig.return_type._fields] b_members = [getattr(b, attr) for attr in sig.return_type._fields] c_members = [c for attr in sig.return_type._fields] op, caller = op_helper(context, builder, sig, args) caller(op, builder, vec, a_members, b_members, c_members) return vec_ptr @impl_registry.lower(op, vec_t, types.Number, vec_t) def cuda_op_vec_mtv_vec(context, builder, sig, args): a = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) b = context.cast(builder, args[1], sig.args[1], vec_t._member_t) c = cgutils.create_struct_proxy(sig.args[2], 'data')(context, builder, ref = args[2]) vec_ptr = cgutils.alloca_once(builder, args[0].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) a_members = [getattr(a, attr) for attr in sig.return_type._fields] b_members = [b for attr in sig.return_type._fields] c_members = [getattr(c, attr) for attr in sig.return_type._fields] op, caller = op_helper(context, builder, sig, args) caller(op, builder, vec, a_members, b_members, c_members) return vec_ptr @impl_registry.lower(op, types.Number, vec_t, vec_t) def cuda_op_mtv_vec_vec(context, builder, sig, args): a = context.cast(builder, args[0], sig.args[0], vec_t._member_t) b = cgutils.create_struct_proxy(sig.args[1], 'data')(context, builder, ref = args[1]) c = cgutils.create_struct_proxy(sig.args[2], 'data')(context, builder, ref = args[2]) vec_ptr = cgutils.alloca_once(builder, args[1].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) a_members = [a for attr in sig.return_type._fields] b_members = [getattr(b, attr) for attr in sig.return_type._fields] c_members = [getattr(c, attr) for attr in sig.return_type._fields] op, caller = op_helper(context, builder, sig, args) caller(op, builder, vec, a_members, b_members, c_members) return vec_ptr def ternary_op_factory_vec_mtv_mtv(op, vec_t, op_helper): @impl_registry.lower(op, vec_t, types.Number, types.Number) def cuda_op_vec_mtv_mtv(context, builder, sig, args): a = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) b = context.cast(builder, args[1], sig.args[1], vec_t._member_t) c = context.cast(builder, args[2], sig.args[2], vec_t._member_t) vec_ptr = cgutils.alloca_once(builder, args[0].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) a_members = [getattr(a, attr) for attr in sig.return_type._fields] b_members = [b for attr in sig.return_type._fields] c_members = [c for attr in sig.return_type._fields] op, caller = op_helper(context, builder, sig, args) caller(op, builder, vec, a_members, b_members, c_members) return vec_ptr @impl_registry.lower(op, types.Number, vec_t, types.Number) def cuda_op_mtv_vec_mtv(context, builder, sig, args): a = context.cast(builder, args[0], sig.args[0], vec_t._member_t) b = cgutils.create_struct_proxy(sig.args[1], 'data')(context, builder, ref = args[1]) c = context.cast(builder, args[2], sig.args[2], vec_t._member_t) vec_ptr = cgutils.alloca_once(builder, args[1].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) a_members = [a for attr in sig.return_type._fields] b_members = [getattr(b, attr) for attr in sig.return_type._fields] c_members = [c for attr in sig.return_type._fields] op, caller = op_helper(context, builder, sig, args) caller(op, builder, vec, a_members, b_members, c_members) return vec_ptr @impl_registry.lower(op, types.Number, types.Number, vec_t) def cuda_op_mtv_mtv_vec(context, builder, sig, args): a = context.cast(builder, args[0], sig.args[0], vec_t._member_t) b = context.cast(builder, args[1], sig.args[1], vec_t._member_t) c = cgutils.create_struct_proxy(sig.args[2], 'data')(context, builder, ref = args[2]) vec_ptr = cgutils.alloca_once(builder, args[2].type.pointee, size = 1) vec = cgutils.create_struct_proxy(sig.return_type, 'data')(context, builder, ref = vec_ptr) a_members = [a for attr in sig.return_type._fields] b_members = [b for attr in sig.return_type._fields] c_members = [getattr(c, attr) for attr in sig.return_type._fields] op, caller = op_helper(context, builder, sig, args) caller(op, builder, vec, a_members, b_members, c_members) return vec_ptr def ternary_op_factory(op, vec_t, op_helper): #sig ternary_op_factory_vec_vec_vec(op, vec_t, op_helper) ternary_op_factory_vec_vec_mtv(op, vec_t, op_helper) ternary_op_factory_vec_mtv_mtv(op, vec_t, op_helper) # # @impl_registry.lower(op, vec_t, vec_t, vec_t) # # @impl_registry.lower(op, vec_t, vec_t, member_type) # # @impl_registry.lower(op, vec_t, member_type, vec_t) # # @impl_registry.lower(op, member_type, vec_t, vec_t) # # @impl_registry.lower(op, vec_t, member_type, member_type) # # @impl_registry.lower(op, member_type, vec_t, member_type) # # @impl_registry.lower(op, member_type, member_type, vec_t) # def cuda_op_ternary(context, builder, sig, args): # pointee = None # vals = [] # members = [] # for typ, arg in zip(sig.args, args): # if typ == vec_t: # vals.append(cgutils.create_struct_proxy(typ)(context, builder, ref = arg)) # members.append([getattr(val, attr) for attr in arg._fields]) # if not pointee: # pointee = arg.type.pointee # else: # vals.append(context.cast(builder, arg, typ, member_type)) # members.append([val for attr in sig.return_type._fields]) # vec_ptr = cgutils.alloca_once(builder, pointee, size = 1) # vec = cgutils.create_struct_proxy(sig.return_type)(context, builder, ref = vec_ptr) # op, caller = op_helper(context, builder, sig, args) # caller(op, builder, vec, *members) # return vec_ptr ######################### #ternary callers functions# ######################### ######################## #ternary helper functions# ######################## ############### #REDUCTION OPS# (ops that take in a vector and return a scalar) ############### def reduction_op_factory(op, vec_t, op_helper): #functions that reduce a vector input to a scalar output by applying op to each element of the input vector @impl_registry.lower(op, vec_t) def cuda_op_vec(context, builder, sig, args): a = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) a_members = [getattr(a, attr) for attr in sig.args[0]._fields] op, caller = op_helper(context, builder, sig, args) return caller(op,builder, a_members) ############################# #reduction callers functions# ############################# def reduction_builder_op_caller(op, builder, vec): val = vec[0] for n in range(len(vec) - 1): val = op(val, vec[n + 1]) return val def reduction_libfunc_op_caller(op, builder, vec): val = vec[0] for n in range(len(vec) - 1): val = op(builder, [val, vec[n + 1]]) return val def length_caller(ops, builder, vec): add, mul, sqrt = ops val = mul(builder, [vec[0], vec[0]]) for n in range(len(vec) - 1): val = add(builder, [val, mul(builder, [vec[n + 1], vec[n + 1]])]) return sqrt(builder, [val]) ####################################### #reduction op helper functions# ####################################### def sum_helper(context, builder, sig, args): # add = builder.add # if isinstance(sig.args[0]._member_t, types.Float): # add = builder.fadd # return add, reduction_builder_op_caller libsig = signature(sig.args[0]._member_t, sig.args[0]._member_t, sig.args[0]._member_t) add = context.get_function(operator.add, libsig) return add, reduction_libfunc_op_caller def length_helper(context, builder, sig, args): libsig = signature(sig.args[0]._member_t, sig.args[0]._member_t) sqrt = context.get_function(mathfuncs.sqrt, libsig) libsig = signature(sig.args[0]._member_t, sig.args[0]._member_t, sig.args[0]._member_t) mul = context.get_function(operator.mul, libsig) add = context.get_function(operator.add, libsig) return [add, mul, sqrt], length_caller def reduction_libfunc_helper_wrapper(cuda_op): def reduction_libfunc_helper(context, builder, sig, args): sig = signature(sig.args[0]._member_t, sig.args[0]._member_t, sig.args[0]._member_t) return context.get_function(cuda_op, sig), reduction_libfunc_op_caller return reduction_libfunc_helper # def getitem_vec_factory(vec_t): # #numba/numba/cpython/tupleobj.py # #def getitem_unituple(context, builder, sig, args): # @impl_registry.lower(operator.getitem, vec_t, types.Integer) # def vec_getitem(context, builder, sig, args): # vec = cgutils.create_struct_proxy(sig.args[0])(context, builder, value = args[0]) # idx = args[1] # # vec_len = len(vec_t._fields) # # zero = const_zero(context) # # one = const_nan(context) # # one_64 = context.get_constant(types.float64, np.float64(1)) # # negative = builder.fcmp_unordered('<', idx, zero) # # with builder.if_else(negative) as (true, false): # return vec.x ################## #VECTOR FUNCTIONS# ################## from . import vectorfuncs from ..mathdecl import register_op, unary_op_fixed_type_factory, binary_op_fixed_type_factory #inject/insert functions into mathfuncs if they don't already exist (because functions aren't typed only a single instance of a function with the given name needs to exist within core) vec_funcs = [(vectorfuncs.sum, unary_op_fixed_type_factory, None), (vectorfuncs.dot, binary_op_fixed_type_factory, None), (vectorfuncs.length, unary_op_fixed_type_factory, None), (vectorfuncs.shift, binary_op_fixed_type_factory, None)] for vec_func in vec_funcs: func, factory, *factory_args = vec_func name = func.__name__ libfunc = getattr(mathfuncs, name, None) #only register a vector function if a stub doesn't already exist within core if libfunc is None: setattr(mathfuncs, name, func) #note: None is set as default return type for some of the vec_funcs so that a typer_ method must be defined to use the op on input types register_op(name, factory, *factory_args) def vec_decl(vec, vec_t, Vec): # typ_a.is_internal #use this to decend until an internal type is found # double_t = ir.DoubleType() # __ir_member_t__ # ir_vec_t = ir.LiteralStructType([double_t, double_t]) ########################################## #Define Vector Type ########################################## #note: the typer function must have the same number of arguments as inputs given to the struct so each initialize style needs its own typer @typeof_impl.register(vec) def typeof_vec(val, c): return vec_t def vec_typer(*attrs): if all([isinstance(attr, vec_t.__input_type__) for attr in attrs]): return vec_t else: raise ValueError(f"Input to {vec.__name__} not understood") #vector length specific initialization if Vec == Vector2Type: #initialize: vec2(x,y) @type_callable(vec) def type_vec2(context): def typer(x, y): return vec_typer(x,y) return typer elif Vec == Vector3Type: #initialize: vec3(x,y,z) @type_callable(vec) def type_vec3(context): def typer(x, y, z): return vec_typer(x,y,z) return typer #initialize: vec3(vec2,y) or vec3(x,vec2) @type_callable(vec) def type_vec3(context): def typer(vec_or_input_t_a, vec_or_input_t_b): if isinstance(vec_or_input_t_a, vec_t.__input_type__) and isinstance(vec_or_input_t_b, Vector2Type): return vec_t elif isinstance(vec_or_input_t_a, Vector2Type) and isinstance(vec_or_input_t_b, vec_t.__input_type__): return vec_t else: raise ValueError(f"Input to {vec.__name__} not understood") return typer #initialize: vec(x) or vec(vec) @type_callable(vec) def type_vec(context): def typer(vec_or_input_t): if isinstance(vec_or_input_t, vec_t.__input_type__) or isinstance(vec_or_input_t, Vec): return vec_t else: raise ValueError(f"Input to {vec.__name__} not understood") return typer #initialize: vec() @type_callable(vec) def type_vec(context): def typer(): return vec_t return typer @register_model(type(vec_t)) class VecModel(models.StructModel): def __init__(self, dmm, fe_type): models.StructModel.__init__(self, dmm, fe_type, vec_t._members) def get_value_type(self): return super().get_value_type().as_pointer() # def get_argument_type(self): # print("get_argument_type") # return super().get_argument_type() def as_argument(self, builder, value): #defines how the arguments are extacted from the object and puts them into the function args #example: # %"extracted.x" = extractvalue {float, float, float} %".23", 0 # %"extracted.y" = extractvalue {float, float, float} %".23", 1 # %"extracted.z" = extractvalue {float, float, float} %".23", 2 return super().as_argument(builder, builder.load(value)) def from_argument(self, builder, value): #defines the argument output (the object operated on within the function) and how the input arguments get mapped on to this object. vec_ptr = cgutils.alloca_once(builder, self.get_data_type(), size = 1) for i, (dm, val) in enumerate(zip(self._models, value)): v = getattr(dm, "from_argument")(builder, val) i_ptr = cgutils.gep_inbounds(builder, vec_ptr, 0, i) builder.store(v, i_ptr) return vec_ptr def as_return(self, builder, value): # as_return START # %".23" = load {float, float, float}, {float, float, float}* %".15" # as_return END return super().as_return(builder, builder.load(value)) def from_return(self, builder, value): vec_ptr = cgutils.alloca_once(builder, self.get_data_type(), size = 1) builder.store(value, vec_ptr) return vec_ptr # def get(self, builder, val, pos): # if isinstance(pos, str): # pos = self.get_field_position(pos) # return builder.extract_value(val, [pos], name="extracted." + self._fields[pos]) # def set(self, builder, stval, val, pos): # if isinstance(pos, str): # pos = self.get_field_position(pos) # return builder.insert_value(stval, val, [pos], name="inserted." + self._fields[pos]) ########################################## #Initializer/Constructor Methods ########################################## #initialize: vec(vec) @lower_builtin(vec, Vec) def impl_vec(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) OutProxy = cgutils.create_struct_proxy(sig.return_type, 'data') datamodel = context.data_model_manager[OutProxy._fe_type] out_ptr = cgutils.alloca_once(builder, datamodel.get_data_type(), size = 1) out = OutProxy(context, builder, ref = out_ptr) for n, attr in enumerate(datamodel._fields): setattr(out, attr, context.cast(builder, getattr(vec, attr), sig.args[0]._member_t, sig.return_type._member_t)) return out_ptr #initialize: vec(x,y,...) @lower_builtin(vec, *[vec_t.__input_type__]*len(vec_t._members)) def impl_vec(context, builder, sig, args): OutProxy = cgutils.create_struct_proxy(sig.return_type, 'data') datamodel = context.data_model_manager[OutProxy._fe_type] out_ptr = cgutils.alloca_once(builder, datamodel.get_data_type(), size = 1) out = OutProxy(context, builder, ref = out_ptr) # context._get_constants.find((types.float32,)) print(type()) for n, attr in enumerate(datamodel._fields): setattr(vec, attr, context.cast(builder, args[n], sig.args[n], sig.return_type._member_t)) return out_ptr #initialize: vec(x) @lower_builtin(vec, vec_t.__input_type__) def impl_vec(context, builder, sig, args): OutProxy = cgutils.create_struct_proxy(sig.return_type, 'data') datamodel = context.data_model_manager[OutProxy._fe_type] out_ptr = cgutils.alloca_once(builder, datamodel.get_data_type(), size = 1) out = OutProxy(context, builder, ref = out_ptr) for n, attr in enumerate(datamodel._fields): setattr(vec, attr, context.cast(builder, args[0], sig.args[0], sig.return_type._member_t)) return out_ptr #initialize: vec() @lower_builtin(vec) def impl_vec(context, builder, sig, args): OutProxy = cgutils.create_struct_proxy(sig.return_type, 'data') datamodel = context.data_model_manager[OutProxy._fe_type] out_ptr = cgutils.alloca_once(builder, datamodel.get_data_type(), size = 1) out = OutProxy(context, builder, ref = out_ptr) for n, attr in enumerate(datamodel._fields): setattr(vec, attr, context.get_constant(sig.return_type._member_t, 0)) return out_ptr if Vec == Vector3Type: #initialize: vec(x, vec2) @lower_builtin(vec, vec_t.__input_type__, Vector2Type) def impl_vec(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig.args[1], 'data')(context, builder, ref = args[1]) vals = [context.cast(builder, args[0], sig.args[0], sig.return_type._member_t), context.cast(builder, vec.x, sig.args[1]._member_t, sig.return_type._member_t), context.cast(builder, vec.y, sig.args[1]._member_t, sig.return_type._member_t)] OutProxy = cgutils.create_struct_proxy(sig.return_type, 'data') datamodel = context.data_model_manager[OutProxy._fe_type] out_ptr = cgutils.alloca_once(builder, datamodel.get_data_type(), size = 1) out = OutProxy(context, builder, ref = out_ptr) for n, attr in enumerate(datamodel._fields): setattr(out, attr, vals[n]) return out_ptr #initialize: vec(vec2, x) @lower_builtin(vec, Vector2Type, vec_t.__input_type__) def impl_vec(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) vals = [context.cast(builder, vec.x, sig.args[0]._member_t, sig.return_type._member_t), context.cast(builder, vec.y, sig.args[0]._member_t, sig.return_type._member_t), context.cast(builder, args[1], sig.args[1], sig.return_type._member_t)] OutProxy = cgutils.create_struct_proxy(sig.return_type, 'data') datamodel = context.data_model_manager[OutProxy._fe_type] out_ptr = cgutils.alloca_once(builder, datamodel.get_data_type(), size = 1) out = OutProxy(context, builder, ref = out_ptr) for n, attr in enumerate(datamodel._fields): setattr(out, attr, vals[n]) return out_ptr ########################################## #Define Vector Attributes ########################################## @decl_registry.register_attr class Vec_attrs(AttributeTemplate): key = vec_t def resolve_x(self, mod): return vec_t._member_t def resolve_y(self, mod): return vec_t._member_t def resolve_z(self, mod): return vec_t._member_t # def resolve___get_item__(self, mod): # return vec_t._member_t #def resolve_length(self): #pass @impl_registry.lower_getattr(vec_t, 'x') def vec_get_x(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig, 'data')(context, builder, ref = args) return vec.x @impl_registry.lower_setattr(vec_t, 'x') def vec_set_x(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) x = context.cast(builder, args[1], sig.args[1], sig.args[0]._member_t) setattr(vec, 'x', x) @impl_registry.lower_getattr(vec_t, 'y') def vec_get_y(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig, 'data')(context, builder, ref = args) return vec.y @impl_registry.lower_setattr(vec_t, 'y') def vec_set_y(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) y = context.cast(builder, args[1], sig.args[1], sig.args[0]._member_t) setattr(vec, 'y', y) @impl_registry.lower_getattr(vec_t, 'z') def vec_get_z(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig, 'data')(context, builder, ref = args) return vec.z @impl_registry.lower_setattr(vec_t, 'z') def vec_set_z(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) z = context.cast(builder, args[1], sig.args[1], sig.args[0]._member_t) setattr(vec, 'z', z) #.xy, .xz, .yz methods if Vec == Vector3Type: @decl_registry.register_attr class Vector3Type_attrs(AttributeTemplate): key = vec_t def resolve_xy(self, mod): return vec_t._vec2_t def resolve_xz(self, mod): return vec_t._vec2_t def resolve_yz(self, mod): return vec_t._vec2_t @impl_registry.lower_getattr(vec_t, 'xy') def vec3_get_xy(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig, 'data')(context, builder, ref = args) XYProxy = cgutils.create_struct_proxy(sig.return_type, 'data') datamodel = context.data_model_manager[XYProxy._fe_type] xy_ptr = cgutils.alloca_once(builder, datamodel.get_data_type(), size = 1) xy = XYProxy(context, builder, ref = xy_ptr) for n, attr in enumerate(['x', 'y']): setattr(xy, attr, getattr(vec, attr)) return xy_ptr @impl_registry.lower_setattr(vec_t, 'xy') def vec3_set_xy(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) xy = cgutils.create_struct_proxy(sig.args[1], 'data')(context, builder, ref = args[1]) vec.x = xy.x vec.y = xy.y @impl_registry.lower_getattr(vec_t, 'xz') def vec3_get_xz(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig, 'data')(context, builder, ref = args) XZProxy = cgutils.create_struct_proxy(sig.return_type, 'data') datamodel = context.data_model_manager[XZProxy._fe_type] xz_ptr = cgutils.alloca_once(builder, datamodel.get_data_type(), size = 1) xz = XZProxy(context, builder, ref = xz_ptr) for attr2, attr3 in zip(['x', 'y'], ['x', 'z']): setattr(xz, attr2, getattr(vec, attr3)) return xz_ptr @impl_registry.lower_setattr(vec_t, 'xz') def vec3_set_xz(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) xz = cgutils.create_struct_proxy(sig.args[1], 'data')(context, builder, ref = args[1]) vec.x = xz.x vec.z = xz.y @impl_registry.lower_getattr(vec_t, 'yz') def vec3_get_yz(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig, 'data')(context, builder, ref = args) YZProxy = cgutils.create_struct_proxy(sig.return_type, 'data') datamodel = context.data_model_manager[YZProxy._fe_type] yz_ptr = cgutils.alloca_once(builder, datamodel.get_data_type(), size = 1) yz = YZProxy(context, builder, ref = yz_ptr) for attr2, attr3 in zip(['x', 'y'], ['y', 'z']): setattr(xz, attr2, getattr(vec, attr3)) return yz_ptr @impl_registry.lower_setattr(vec_t, 'yz') def vec3_set_yz(context, builder, sig, args): vec = cgutils.create_struct_proxy(sig.args[0], 'data')(context, builder, ref = args[0]) yz = cgutils.create_struct_proxy(sig.args[1], 'data')(context, builder, ref = args[1]) vec.y = yz.x vec.z = yz.y ########################################## #Register Vector Methods ########################################## ##### #+, -, *, / # +=, -=, *=, /= (iadd,isub,imul,idiv) ##### class vec_op_template(ConcreteTemplate): cases = [signature(vec_t, vec_t, vec_t), signature(vec_t, vec_t._member_t, vec_t), signature(vec_t, vec_t, vec_t._member_t)] #OLD METHOD # ops = [(operator.add, add_helper), # (operator.sub, sub_helper), # (operator.mul, mul_helper), # (operator.truediv, div_helper)] # for op, helper in ops: # decl_registry.register_global(op)(vec_op_template) # binary_op_factory(op, vec_t, helper) ########### ops = [operator.add, operator.sub, operator.mul, operator.truediv] # operator.iadd, operator.isub, operator.imul, operator.itruediv] for op in ops: decl_registry.register_global(op)(vec_op_template) binary_op_factory(op, vec_t, libfunc_helper_wrapper(op)) ##### #% (should this be vec_t specific?) ##### ##### #** (should this be vec_t specific?) ##### #TO DO #"pow", "powi" ##### #**=, %= (ipow,imod) ##### #TO DO ##### #min, max, sum ##### class vec_op_template(ConcreteTemplate): #binary cases = [signature(vec_t, vec_t, vec_t), signature(vec_t, vec_t._member_t, vec_t), signature(vec_t, vec_t, vec_t._member_t), #reduction signature(vec_t._member_t, vec_t)] decl_registry.register_global(min)(vec_op_template) decl_registry.register_global(max)(vec_op_template) decl_registry.register_global(sum)(vec_op_template) min_helper = libfunc_helper_wrapper(min) max_helper = libfunc_helper_wrapper(max) binary_op_factory(min, vec_t, min_helper) binary_op_factory(max, vec_t, max_helper) # binary_op_factory(mathfuncs.min, vec_t, min_helper) # binary_op_factory(mathfuncs.max, vec_t, max_helper) min_helper = reduction_libfunc_helper_wrapper(min) max_helper = reduction_libfunc_helper_wrapper(max) reduction_op_factory(min, vec_t, min_helper) reduction_op_factory(max, vec_t, max_helper) # reduction_op_factory(mathfuncs.min, vec_t, min_helper) # reduction_op_factory(mathfuncs.max, vec_t, max_helper) reduction_op_factory(sum, vec_t, sum_helper) reduction_op_factory(mathfuncs.sum, vec_t, sum_helper) binary_op_factory_vec_vec(mathfuncs.dot, vec_t, libfunc_helper_wrapper(operator.mul)) class vec_getitem_template(ConcreteTemplate): #binary cases = [signature(vec_t._member_t, vec_t, types.intp), signature(vec_t._member_t, vec_t, types.uintp)] decl_registry.register_global(operator.getitem)(vec_getitem_template) # getitem_vec_factory(vec_t) ##### #shift ##### for scalar_type in [types.uint8, types.uint16, types.uint32, types.uint64, types.int8, types.int16, types.int32, types.int64]: binary_op_factory_vec_scalar(mathfuncs.shift, vec_t, shift_helper, scalar_type = scalar_type) #vectorized ops unary_floating_ops = ["sin", "cos", "tan", "sinh", "cosh", "tanh", "asin", "acos", "atan", "asinh", "acosh", "atanh", "sqrt", #"rsqrt", "cbrt", "rcbrt", "exp" , "exp10", "exp2", #"expm1", "log", "log10", "log2", #"log1p", "logb", "floor", "ceil"] binary_floating_ops = ["fmod"] ternary_floating_ops = ["clamp", "lerp", "param", "smooth_step"] def floating_vec_decl(vec, vec_t): ##### #- (neg), abs ##### class vec_unary_op(ConcreteTemplate): cases = [signature(vec_t, vec_t)] neg_helper = libfunc_helper_wrapper(operator.neg) decl_registry.register_global(operator.neg)(vec_unary_op) unary_op_factory(operator.neg, vec_t, neg_helper) abs_helper = libfunc_helper_wrapper(abs) #libfunc_helper_wrapper(mathfuncs.abs) decl_registry.register_global(abs)(vec_unary_op) unary_op_factory(abs, vec_t, abs_helper) # unary_op_factory(mathfuncs.abs, vec_t, abs_helper) ##### #unary functions ##### #float/double vector for op in unary_floating_ops: libop = getattr(mathfuncs, op) unary_op_factory(libop, vec_t, libfunc_helper_wrapper(libop)) ##### #round ##### class vec_unary_op(ConcreteTemplate): cases = [signature(vec_t, vec_t)] round_helper = libfunc_helper_wrapper(mathfuncs.round) decl_registry.register_global(round)(vec_unary_op) unary_op_factory(round, vec_t, round_helper) unary_op_factory(mathfuncs.round, vec_t, round_helper) reduction_op_factory(mathfuncs.length, vec_t, length_helper) ##### #binary functions ##### for op in binary_floating_ops: libop = getattr(mathfuncs, op) binary_op_factory(libop, vec_t, libfunc_helper_wrapper(libop)) #non-vectorized ops # atan2, cross, etc. ##### #ternary functions ##### for op in ternary_floating_ops: libop = getattr(mathfuncs, op) ternary_op_factory(libop, vec_t, libfunc_helper_wrapper(libop)) def float_vec_decl(vec, vec_t): for op in floating_ops: libopf = getattr(mathfuncs, op + 'f') unary_op_factory(libopf, vec_t, libfunc_helper_wrapper(libopf)) unary_op_factory(mathfuncs.fabs, vec_t, libfunc_helper_wrapper(mathfuncs.fabsf)) binary_op_factory(mathfuncs.fminf, vec_t, libfunc_helper_wrapper(mathfuncs.fminf)) binary_op_factory(mathfuncs.fmaxf, vec_t, libfunc_helper_wrapper(mathfuncs.fmaxf)) def double_vec_decl(vec, vec_t): unary_op_factory(mathfuncs.fabs, vec_t, libfunc_helper_wrapper(mathfuncs.fabs)) binary_op_factory(mathfuncs.fmin, vec_t, libfunc_helper_wrapper(mathfuncs.fmin)) binary_op_factory(mathfuncs.fmax, vec_t, libfunc_helper_wrapper(mathfuncs.fmax)) def integer_vec_decl(vec, vec_t): class vec_op_template(ConcreteTemplate): cases = [signature(vec_t, vec_t, vec_t), signature(vec_t, vec_t._member_t, vec_t), signature(vec_t, vec_t, vec_t._member_t)] # cases = [signature(vec_t, vec_t, vec_t), # signature(vec_t, vec_t._member_t, vec_t), # signature(vec_t, vec_t, vec_t._member_t)] ops = [operator.and_, operator.or_] for op in ops: decl_registry.register_global(op)(vec_op_template) binary_op_factory(op, vec_t, libfunc_helper_wrapper(op)) def signed_vec_decl(vec, vec_t): ##### #- (neg), abs ##### class vec_unary_op(ConcreteTemplate): cases = [signature(vec_t, vec_t)] neg_helper = libfunc_helper_wrapper(operator.neg) decl_registry.register_global(operator.neg)(vec_unary_op) unary_op_factory(operator.neg, vec_t, neg_helper) abs_helper = libfunc_helper_wrapper(abs)#libfunc_helper_wrapper(mathfuncs.abs) decl_registry.register_global(abs)(vec_unary_op) unary_op_factory(abs, vec_t, abs_helper) # unary_op_factory(mathfuncs.abs, vec_t, abs_helper) def int_vec_decl(vec, vec_t): pass def long_vec_decl(vec, vec_t): unary_op_factory(mathfuncs.llabs, vec_t, libfunc_helper_wrapper(mathfuncs.llabs)) binary_op_factory(mathfuncs.llmin, vec_t, libfunc_helper_wrapper(mathfuncs.llmin)) binary_op_factory(mathfuncs.llmax, vec_t, libfunc_helper_wrapper(mathfuncs.llmax)) def unsigned_vec_decl(vec, vec_t): pass def uint_vec_decl(vec, vec_t): binary_op_factory(mathfuncs.umin, vec_t, libfunc_helper_wrapper(mathfuncs.umin)) binary_op_factory(mathfuncs.umax, vec_t, libfunc_helper_wrapper(mathfuncs.umax)) def ulong_vec_decl(vec, vec_t): binary_op_factory(mathfuncs.ullmin, vec_t, libfunc_helper_wrapper(mathfuncs.ullmin)) binary_op_factory(mathfuncs.ullmax, vec_t, libfunc_helper_wrapper(mathfuncs.ullmax)) #python classes vec2s = [uchar2, ushort2, uint2, ulong2, char2, short2, int2, long2, float2, double2] vec3s = [uchar3, ushort3, uint3, ulong3, char3, short3, int3, long3, float3, double3] #initialized numba type classes vec2s_t = [uchar2_t, ushort2_t, uint2_t, ulong2_t, char2_t, short2_t, int2_t, long2_t, float2_t, double2_t] vec3s_t = [uchar3_t, ushort3_t, uint3_t, ulong3_t, char3_t, short3_t, int3_t, long3_t, float3_t, double3_t] vec_groups = [vec2s, vec3s] vec_t_groups = [vec2s_t, vec3s_t] Vecs = [Vector2Type, Vector3Type] for vecs, vecs_t, Vec in zip(vec_groups, vec_t_groups, Vecs): for vec, vec_t in zip(vecs, vecs_t): vec_decl(vec, vec_t, Vec) ########################################## #Vector Type Specific Methods ########################################## vec2s = [float2, double2] vec3s = [float3, double3] vec2s_t = [float2_t, double2_t] vec3s_t = [float3_t, double3_t] vec_groups = [vec2s, vec3s] vec_t_groups = [vec2s_t, vec3s_t] for vecs, vecs_t in zip(vec_groups, vec_t_groups): for vec, vec_t in zip(vecs, vecs_t): floating_vec_decl(vec, vec_t) # float_vec_decl(vec, vec_t) # double_vec_decl(vec, vec_t) vec2s = [char2, short2, int2, long2, uchar2, ushort2, uint2, ulong2] vec3s = [char3, short3, int3, long3, uchar3, ushort3, uint3, ulong3] vec2s_t = [char2_t, short2_t, int2_t, long2_t, uchar2_t, ushort2_t, uint2_t, ulong2_t] vec3s_t = [char3_t, short3_t, int3_t, long3_t, char3_t, short3_t, int3_t, long3_t] vec_groups = [vec2s, vec3s] vec_t_groups = [vec2s_t, vec3s_t] for vecs, vecs_t in zip(vec_groups, vec_t_groups): for vec, vec_t in zip(vecs, vecs_t): integer_vec_decl(vec, vec_t) vec_groups = [vec2s[:4], vec3s[:4]] vec_t_groups = [vec2s_t[:4], vec3s_t[:4]] for vecs, vecs_t in zip(vec_groups, vec_t_groups): for vec, vec_t in zip(vecs, vecs_t): signed_vec_decl(vec, vec_t) # int_vec_decl(vec, vec_ts) # long_vec_decl(vec, vec_ts) # vec_groups = [vec2s[4:], vec3s[4:]] # vec_t_groups = [vec2s_t[4:], vec3s_t[4:]] # for vecs, vec_ts in zip(vec_groups, vec_t_groups): # for vec, vec_t in zip(vecs, vec_ts): # unsigned_vec_decl(vec, vec_ts) # # uint_vec_decl(vec, vec_ts) # # ulong_vec_decl(vec, vec_ts)
[ "numpy.int8", "numba.core.extending.models.StructModel.__init__", "numba.cuda.cudaimpl.registry.lower", "numba.core.cgutils.gep_inbounds", "numba.cuda.cudaimpl.registry.lower_getattr", "numba.core.typing.signature", "numba.cuda.cudaimpl.registry.lower_setattr", "numba.core.extending.typeof_impl.regist...
[((2646, 2676), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'vec_t'], {}), '(op, vec_t)\n', (2665, 2676), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((4159, 4196), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'vec_t', 'vec_t'], {}), '(op, vec_t, vec_t)\n', (4178, 4196), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((5452, 5496), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'vec_t', 'types.Number'], {}), '(op, vec_t, types.Number)\n', (5471, 5496), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((6131, 6175), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'types.Number', 'vec_t'], {}), '(op, types.Number, vec_t)\n', (6150, 6175), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((7036, 7079), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'vec_t', 'scalar_type'], {}), '(op, vec_t, scalar_type)\n', (7055, 7079), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((13481, 13525), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'vec_t', 'vec_t', 'vec_t'], {}), '(op, vec_t, vec_t, vec_t)\n', (13500, 13525), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((14514, 14565), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'vec_t', 'vec_t', 'types.Number'], {}), '(op, vec_t, vec_t, types.Number)\n', (14533, 14565), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((15360, 15411), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'vec_t', 'types.Number', 'vec_t'], {}), '(op, vec_t, types.Number, vec_t)\n', (15379, 15411), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((16206, 16257), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'types.Number', 'vec_t', 'vec_t'], {}), '(op, types.Number, vec_t, vec_t)\n', (16225, 16257), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((17110, 17168), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'vec_t', 'types.Number', 'types.Number'], {}), '(op, vec_t, types.Number, types.Number)\n', (17129, 17168), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((17927, 17985), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'types.Number', 'vec_t', 'types.Number'], {}), '(op, types.Number, vec_t, types.Number)\n', (17946, 17985), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((18744, 18802), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'types.Number', 'types.Number', 'vec_t'], {}), '(op, types.Number, types.Number, vec_t)\n', (18763, 18802), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((21377, 21407), 'numba.cuda.cudaimpl.registry.lower', 'impl_registry.lower', (['op', 'vec_t'], {}), '(op, vec_t)\n', (21396, 21407), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((22616, 22694), 'numba.core.typing.signature', 'signature', (['sig.args[0]._member_t', 'sig.args[0]._member_t', 'sig.args[0]._member_t'], {}), '(sig.args[0]._member_t, sig.args[0]._member_t, sig.args[0]._member_t)\n', (22625, 22694), False, 'from numba.core.typing import signature\n'), ((22862, 22917), 'numba.core.typing.signature', 'signature', (['sig.args[0]._member_t', 'sig.args[0]._member_t'], {}), '(sig.args[0]._member_t, sig.args[0]._member_t)\n', (22871, 22917), False, 'from numba.core.typing import signature\n'), ((22990, 23068), 'numba.core.typing.signature', 'signature', (['sig.args[0]._member_t', 'sig.args[0]._member_t', 'sig.args[0]._member_t'], {}), '(sig.args[0]._member_t, sig.args[0]._member_t, sig.args[0]._member_t)\n', (22999, 23068), False, 'from numba.core.typing import signature\n'), ((25717, 25742), 'numba.core.extending.typeof_impl.register', 'typeof_impl.register', (['vec'], {}), '(vec)\n', (25737, 25742), False, 'from numba.core.extending import typeof_impl, type_callable\n'), ((26852, 26870), 'numba.core.extending.type_callable', 'type_callable', (['vec'], {}), '(vec)\n', (26865, 26870), False, 'from numba.core.extending import typeof_impl, type_callable\n'), ((27143, 27161), 'numba.core.extending.type_callable', 'type_callable', (['vec'], {}), '(vec)\n', (27156, 27161), False, 'from numba.core.extending import typeof_impl, type_callable\n'), ((29393, 29416), 'numba.core.extending.lower_builtin', 'lower_builtin', (['vec', 'Vec'], {}), '(vec, Vec)\n', (29406, 29416), False, 'from numba.core.extending import models, register_model, lower_builtin\n'), ((30631, 30671), 'numba.core.extending.lower_builtin', 'lower_builtin', (['vec', 'vec_t.__input_type__'], {}), '(vec, vec_t.__input_type__)\n', (30644, 30671), False, 'from numba.core.extending import models, register_model, lower_builtin\n'), ((31153, 31171), 'numba.core.extending.lower_builtin', 'lower_builtin', (['vec'], {}), '(vec)\n', (31166, 31171), False, 'from numba.core.extending import models, register_model, lower_builtin\n'), ((33777, 33816), 'numba.cuda.cudaimpl.registry.lower_getattr', 'impl_registry.lower_getattr', (['vec_t', '"""x"""'], {}), "(vec_t, 'x')\n", (33804, 33816), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((33959, 33998), 'numba.cuda.cudaimpl.registry.lower_setattr', 'impl_registry.lower_setattr', (['vec_t', '"""x"""'], {}), "(vec_t, 'x')\n", (33986, 33998), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((34233, 34272), 'numba.cuda.cudaimpl.registry.lower_getattr', 'impl_registry.lower_getattr', (['vec_t', '"""y"""'], {}), "(vec_t, 'y')\n", (34260, 34272), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((34415, 34454), 'numba.cuda.cudaimpl.registry.lower_setattr', 'impl_registry.lower_setattr', (['vec_t', '"""y"""'], {}), "(vec_t, 'y')\n", (34442, 34454), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((34689, 34728), 'numba.cuda.cudaimpl.registry.lower_getattr', 'impl_registry.lower_getattr', (['vec_t', '"""z"""'], {}), "(vec_t, 'z')\n", (34716, 34728), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((34871, 34910), 'numba.cuda.cudaimpl.registry.lower_setattr', 'impl_registry.lower_setattr', (['vec_t', '"""z"""'], {}), "(vec_t, 'z')\n", (34898, 34910), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((1637, 1654), 'numba.core.typing.signature', 'signature', (['*types'], {}), '(*types)\n', (1646, 1654), False, 'from numba.core.typing import signature\n'), ((2896, 2954), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[0].type.pointee'], {'size': '(1)'}), '(builder, args[0].type.pointee, size=1)\n', (2915, 2954), False, 'from numba.core import cgutils\n'), ((4725, 4783), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[0].type.pointee'], {'size': '(1)'}), '(builder, args[0].type.pointee, size=1)\n', (4744, 4783), False, 'from numba.core import cgutils\n'), ((5726, 5784), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[0].type.pointee'], {'size': '(1)'}), '(builder, args[0].type.pointee, size=1)\n', (5745, 5784), False, 'from numba.core import cgutils\n'), ((6405, 6463), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[1].type.pointee'], {'size': '(1)'}), '(builder, args[1].type.pointee, size=1)\n', (6424, 6463), False, 'from numba.core import cgutils\n'), ((7320, 7378), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[0].type.pointee'], {'size': '(1)'}), '(builder, args[0].type.pointee, size=1)\n', (7339, 7378), False, 'from numba.core import cgutils\n'), ((9734, 9757), 'numpy.int8', 'np.int8', (['member_current'], {}), '(member_current)\n', (9741, 9757), True, 'import numpy as np\n'), ((13858, 13916), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[0].type.pointee'], {'size': '(1)'}), '(builder, args[0].type.pointee, size=1)\n', (13877, 13916), False, 'from numba.core import cgutils\n'), ((14877, 14935), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[0].type.pointee'], {'size': '(1)'}), '(builder, args[0].type.pointee, size=1)\n', (14896, 14935), False, 'from numba.core import cgutils\n'), ((15723, 15781), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[0].type.pointee'], {'size': '(1)'}), '(builder, args[0].type.pointee, size=1)\n', (15742, 15781), False, 'from numba.core import cgutils\n'), ((16569, 16627), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[1].type.pointee'], {'size': '(1)'}), '(builder, args[1].type.pointee, size=1)\n', (16588, 16627), False, 'from numba.core import cgutils\n'), ((17459, 17517), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[0].type.pointee'], {'size': '(1)'}), '(builder, args[0].type.pointee, size=1)\n', (17478, 17517), False, 'from numba.core import cgutils\n'), ((18276, 18334), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[1].type.pointee'], {'size': '(1)'}), '(builder, args[1].type.pointee, size=1)\n', (18295, 18334), False, 'from numba.core import cgutils\n'), ((19093, 19151), 'numba.core.cgutils.alloca_once', 'cgutils.alloca_once', (['builder', 'args[2].type.pointee'], {'size': '(1)'}), '(builder, args[2].type.pointee, size=1)\n', (19112, 19151), False, 'from numba.core import cgutils\n'), ((23342, 23420), 'numba.core.typing.signature', 'signature', (['sig.args[0]._member_t', 'sig.args[0]._member_t', 'sig.args[0]._member_t'], {}), '(sig.args[0]._member_t, sig.args[0]._member_t, sig.args[0]._member_t)\n', (23351, 23420), False, 'from numba.core.typing import signature\n'), ((26058, 26076), 'numba.core.extending.type_callable', 'type_callable', (['vec'], {}), '(vec)\n', (26071, 26076), False, 'from numba.core.extending import typeof_impl, type_callable\n'), ((29565, 29617), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (29592, 29617), False, 'from numba.core import cgutils\n'), ((30138, 30190), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (30165, 30190), False, 'from numba.core import cgutils\n'), ((30729, 30781), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (30756, 30781), False, 'from numba.core import cgutils\n'), ((31229, 31281), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (31256, 31281), False, 'from numba.core import cgutils\n'), ((31666, 31719), 'numba.core.extending.lower_builtin', 'lower_builtin', (['vec', 'vec_t.__input_type__', 'Vector2Type'], {}), '(vec, vec_t.__input_type__, Vector2Type)\n', (31679, 31719), False, 'from numba.core.extending import models, register_model, lower_builtin\n'), ((32500, 32553), 'numba.core.extending.lower_builtin', 'lower_builtin', (['vec', 'Vector2Type', 'vec_t.__input_type__'], {}), '(vec, Vector2Type, vec_t.__input_type__)\n', (32513, 32553), False, 'from numba.core.extending import models, register_model, lower_builtin\n'), ((35455, 35495), 'numba.cuda.cudaimpl.registry.lower_getattr', 'impl_registry.lower_getattr', (['vec_t', '"""xy"""'], {}), "(vec_t, 'xy')\n", (35482, 35495), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((35983, 36023), 'numba.cuda.cudaimpl.registry.lower_setattr', 'impl_registry.lower_setattr', (['vec_t', '"""xy"""'], {}), "(vec_t, 'xy')\n", (36010, 36023), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((36289, 36329), 'numba.cuda.cudaimpl.registry.lower_getattr', 'impl_registry.lower_getattr', (['vec_t', '"""xz"""'], {}), "(vec_t, 'xz')\n", (36316, 36329), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((36830, 36870), 'numba.cuda.cudaimpl.registry.lower_setattr', 'impl_registry.lower_setattr', (['vec_t', '"""xz"""'], {}), "(vec_t, 'xz')\n", (36857, 36870), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((37136, 37176), 'numba.cuda.cudaimpl.registry.lower_getattr', 'impl_registry.lower_getattr', (['vec_t', '"""yz"""'], {}), "(vec_t, 'yz')\n", (37163, 37176), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((37677, 37717), 'numba.cuda.cudaimpl.registry.lower_setattr', 'impl_registry.lower_setattr', (['vec_t', '"""yz"""'], {}), "(vec_t, 'yz')\n", (37704, 37717), True, 'from numba.cuda.cudaimpl import registry as impl_registry\n'), ((39366, 39400), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['min'], {}), '(min)\n', (39395, 39400), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((39419, 39453), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['max'], {}), '(max)\n', (39448, 39453), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((39472, 39506), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['sum'], {}), '(sum)\n', (39501, 39506), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((40485, 40532), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['operator.getitem'], {}), '(operator.getitem)\n', (40514, 40532), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((41439, 41482), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['operator.neg'], {}), '(operator.neg)\n', (41468, 41482), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((41631, 41665), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['abs'], {}), '(abs)\n', (41660, 41665), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((42117, 42153), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['round'], {}), '(round)\n', (42146, 42153), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((44124, 44167), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['operator.neg'], {}), '(operator.neg)\n', (44153, 44167), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((44315, 44349), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['abs'], {}), '(abs)\n', (44344, 44349), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((2730, 2782), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (2757, 2782), False, 'from numba.core import cgutils\n'), ((2965, 3017), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (2992, 3017), False, 'from numba.core import cgutils\n'), ((4254, 4302), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (4281, 4302), False, 'from numba.core import cgutils\n'), ((4342, 4390), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[1]', '"""data"""'], {}), "(sig.args[1], 'data')\n", (4369, 4390), False, 'from numba.core import cgutils\n'), ((4794, 4846), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (4821, 4846), False, 'from numba.core import cgutils\n'), ((5554, 5602), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (5581, 5602), False, 'from numba.core import cgutils\n'), ((5795, 5847), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (5822, 5847), False, 'from numba.core import cgutils\n'), ((6310, 6358), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[1]', '"""data"""'], {}), "(sig.args[1], 'data')\n", (6337, 6358), False, 'from numba.core import cgutils\n'), ((6474, 6526), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (6501, 6526), False, 'from numba.core import cgutils\n'), ((7142, 7184), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['vec_t', '"""data"""'], {}), "(vec_t, 'data')\n", (7169, 7184), False, 'from numba.core import cgutils\n'), ((7389, 7441), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (7416, 7441), False, 'from numba.core import cgutils\n'), ((11296, 11341), 'numba.core.typing.signature', 'signature', (['types.int8', 'types.int8', 'types.int8'], {}), '(types.int8, types.int8, types.int8)\n', (11305, 11341), False, 'from numba.core.typing import signature\n'), ((13587, 13635), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (13614, 13635), False, 'from numba.core import cgutils\n'), ((13675, 13723), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[1]', '"""data"""'], {}), "(sig.args[1], 'data')\n", (13702, 13723), False, 'from numba.core import cgutils\n'), ((13763, 13811), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[2]', '"""data"""'], {}), "(sig.args[2], 'data')\n", (13790, 13811), False, 'from numba.core import cgutils\n'), ((13927, 13979), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (13954, 13979), False, 'from numba.core import cgutils\n'), ((14627, 14675), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (14654, 14675), False, 'from numba.core import cgutils\n'), ((14715, 14763), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[1]', '"""data"""'], {}), "(sig.args[1], 'data')\n", (14742, 14763), False, 'from numba.core import cgutils\n'), ((14946, 14998), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (14973, 14998), False, 'from numba.core import cgutils\n'), ((15473, 15521), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (15500, 15521), False, 'from numba.core import cgutils\n'), ((15628, 15676), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[2]', '"""data"""'], {}), "(sig.args[2], 'data')\n", (15655, 15676), False, 'from numba.core import cgutils\n'), ((15792, 15844), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (15819, 15844), False, 'from numba.core import cgutils\n'), ((16386, 16434), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[1]', '"""data"""'], {}), "(sig.args[1], 'data')\n", (16413, 16434), False, 'from numba.core import cgutils\n'), ((16474, 16522), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[2]', '"""data"""'], {}), "(sig.args[2], 'data')\n", (16501, 16522), False, 'from numba.core import cgutils\n'), ((16638, 16690), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (16665, 16690), False, 'from numba.core import cgutils\n'), ((17230, 17278), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (17257, 17278), False, 'from numba.core import cgutils\n'), ((17528, 17580), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (17555, 17580), False, 'from numba.core import cgutils\n'), ((18114, 18162), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[1]', '"""data"""'], {}), "(sig.args[1], 'data')\n", (18141, 18162), False, 'from numba.core import cgutils\n'), ((18345, 18397), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (18372, 18397), False, 'from numba.core import cgutils\n'), ((18998, 19046), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[2]', '"""data"""'], {}), "(sig.args[2], 'data')\n", (19025, 19046), False, 'from numba.core import cgutils\n'), ((19162, 19214), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (19189, 19214), False, 'from numba.core import cgutils\n'), ((21461, 21509), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (21488, 21509), False, 'from numba.core import cgutils\n'), ((26222, 26240), 'numba.core.extending.type_callable', 'type_callable', (['vec'], {}), '(vec)\n', (26235, 26240), False, 'from numba.core.extending import typeof_impl, type_callable\n'), ((26382, 26400), 'numba.core.extending.type_callable', 'type_callable', (['vec'], {}), '(vec)\n', (26395, 26400), False, 'from numba.core.extending import typeof_impl, type_callable\n'), ((27340, 27403), 'numba.core.extending.models.StructModel.__init__', 'models.StructModel.__init__', (['self', 'dmm', 'fe_type', 'vec_t._members'], {}), '(self, dmm, fe_type, vec_t._members)\n', (27367, 27403), False, 'from numba.core.extending import models, register_model, lower_builtin\n'), ((29469, 29517), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (29496, 29517), False, 'from numba.core import cgutils\n'), ((32124, 32176), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (32151, 32176), False, 'from numba.core import cgutils\n'), ((32958, 33010), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (32985, 33010), False, 'from numba.core import cgutils\n'), ((33870, 33910), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig', '"""data"""'], {}), "(sig, 'data')\n", (33897, 33910), False, 'from numba.core import cgutils\n'), ((34052, 34100), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (34079, 34100), False, 'from numba.core import cgutils\n'), ((34326, 34366), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig', '"""data"""'], {}), "(sig, 'data')\n", (34353, 34366), False, 'from numba.core import cgutils\n'), ((34508, 34556), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (34535, 34556), False, 'from numba.core import cgutils\n'), ((34782, 34822), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig', '"""data"""'], {}), "(sig, 'data')\n", (34809, 34822), False, 'from numba.core import cgutils\n'), ((34964, 35012), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (34991, 35012), False, 'from numba.core import cgutils\n'), ((35638, 35690), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (35665, 35690), False, 'from numba.core import cgutils\n'), ((36472, 36524), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (36499, 36524), False, 'from numba.core import cgutils\n'), ((37319, 37371), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.return_type', '"""data"""'], {}), "(sig.return_type, 'data')\n", (37346, 37371), False, 'from numba.core import cgutils\n'), ((38218, 38248), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t', 'vec_t'], {}), '(vec_t, vec_t, vec_t)\n', (38227, 38248), False, 'from numba.core.typing import signature\n'), ((38255, 38295), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t._member_t', 'vec_t'], {}), '(vec_t, vec_t._member_t, vec_t)\n', (38264, 38295), False, 'from numba.core.typing import signature\n'), ((38302, 38342), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t', 'vec_t._member_t'], {}), '(vec_t, vec_t, vec_t._member_t)\n', (38311, 38342), False, 'from numba.core.typing import signature\n'), ((38798, 38831), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['op'], {}), '(op)\n', (38827, 38831), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((39182, 39212), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t', 'vec_t'], {}), '(vec_t, vec_t, vec_t)\n', (39191, 39212), False, 'from numba.core.typing import signature\n'), ((39219, 39259), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t._member_t', 'vec_t'], {}), '(vec_t, vec_t._member_t, vec_t)\n', (39228, 39259), False, 'from numba.core.typing import signature\n'), ((39266, 39306), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t', 'vec_t._member_t'], {}), '(vec_t, vec_t, vec_t._member_t)\n', (39275, 39306), False, 'from numba.core.typing import signature\n'), ((39329, 39362), 'numba.core.typing.signature', 'signature', (['vec_t._member_t', 'vec_t'], {}), '(vec_t._member_t, vec_t)\n', (39338, 39362), False, 'from numba.core.typing import signature\n'), ((40383, 40428), 'numba.core.typing.signature', 'signature', (['vec_t._member_t', 'vec_t', 'types.intp'], {}), '(vec_t._member_t, vec_t, types.intp)\n', (40392, 40428), False, 'from numba.core.typing import signature\n'), ((40435, 40481), 'numba.core.typing.signature', 'signature', (['vec_t._member_t', 'vec_t', 'types.uintp'], {}), '(vec_t._member_t, vec_t, types.uintp)\n', (40444, 40481), False, 'from numba.core.typing import signature\n'), ((41361, 41384), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t'], {}), '(vec_t, vec_t)\n', (41370, 41384), False, 'from numba.core.typing import signature\n'), ((42034, 42057), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t'], {}), '(vec_t, vec_t)\n', (42043, 42057), False, 'from numba.core.typing import signature\n'), ((43496, 43526), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t', 'vec_t'], {}), '(vec_t, vec_t, vec_t)\n', (43505, 43526), False, 'from numba.core.typing import signature\n'), ((43533, 43573), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t._member_t', 'vec_t'], {}), '(vec_t, vec_t._member_t, vec_t)\n', (43542, 43573), False, 'from numba.core.typing import signature\n'), ((43580, 43620), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t', 'vec_t._member_t'], {}), '(vec_t, vec_t, vec_t._member_t)\n', (43589, 43620), False, 'from numba.core.typing import signature\n'), ((43822, 43855), 'numba.cuda.cudadecl.registry.register_global', 'decl_registry.register_global', (['op'], {}), '(op)\n', (43851, 43855), True, 'from numba.cuda.cudadecl import registry as decl_registry\n'), ((44046, 44069), 'numba.core.typing.signature', 'signature', (['vec_t', 'vec_t'], {}), '(vec_t, vec_t)\n', (44055, 44069), False, 'from numba.core.typing import signature\n'), ((28382, 28426), 'numba.core.cgutils.gep_inbounds', 'cgutils.gep_inbounds', (['builder', 'vec_ptr', '(0)', 'i'], {}), '(builder, vec_ptr, 0, i)\n', (28402, 28426), False, 'from numba.core import cgutils\n'), ((31774, 31822), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[1]', '"""data"""'], {}), "(sig.args[1], 'data')\n", (31801, 31822), False, 'from numba.core import cgutils\n'), ((32608, 32656), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (32635, 32656), False, 'from numba.core import cgutils\n'), ((35553, 35593), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig', '"""data"""'], {}), "(sig, 'data')\n", (35580, 35593), False, 'from numba.core import cgutils\n'), ((36081, 36129), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (36108, 36129), False, 'from numba.core import cgutils\n'), ((36171, 36219), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[1]', '"""data"""'], {}), "(sig.args[1], 'data')\n", (36198, 36219), False, 'from numba.core import cgutils\n'), ((36387, 36427), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig', '"""data"""'], {}), "(sig, 'data')\n", (36414, 36427), False, 'from numba.core import cgutils\n'), ((36928, 36976), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (36955, 36976), False, 'from numba.core import cgutils\n'), ((37018, 37066), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[1]', '"""data"""'], {}), "(sig.args[1], 'data')\n", (37045, 37066), False, 'from numba.core import cgutils\n'), ((37234, 37274), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig', '"""data"""'], {}), "(sig, 'data')\n", (37261, 37274), False, 'from numba.core import cgutils\n'), ((37775, 37823), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[0]', '"""data"""'], {}), "(sig.args[0], 'data')\n", (37802, 37823), False, 'from numba.core import cgutils\n'), ((37865, 37913), 'numba.core.cgutils.create_struct_proxy', 'cgutils.create_struct_proxy', (['sig.args[1]', '"""data"""'], {}), "(sig.args[1], 'data')\n", (37892, 37913), False, 'from numba.core import cgutils\n')]
import matplotlib.pyplot as plt2 import numpy as np4 import matplotlib as mpl import matplotlib as mpl2 mpl.rcParams['font.family'] = 'sans-serif' mpl.rcParams['font.sans-serif'] = 'NSimSun,Times New Roman' (t, test_x, test_y) = np4.loadtxt('/home/abner/UFO/ecl/EKF/build/data/gps_test.txt', unpack=True) fig2 = plt2.figure() cx1 = fig2.add_subplot(131) cx1.plot(t, test_x) cx2 = fig2.add_subplot(132) cx2.plot(t, test_y) cx3 = fig2.add_subplot(133) cx3.plot(test_x, test_y) plt2.show()
[ "numpy.loadtxt", "matplotlib.pyplot.figure", "matplotlib.pyplot.show" ]
[((237, 312), 'numpy.loadtxt', 'np4.loadtxt', (['"""/home/abner/UFO/ecl/EKF/build/data/gps_test.txt"""'], {'unpack': '(True)'}), "('/home/abner/UFO/ecl/EKF/build/data/gps_test.txt', unpack=True)\n", (248, 312), True, 'import numpy as np4\n'), ((326, 339), 'matplotlib.pyplot.figure', 'plt2.figure', ([], {}), '()\n', (337, 339), True, 'import matplotlib.pyplot as plt2\n'), ((496, 507), 'matplotlib.pyplot.show', 'plt2.show', ([], {}), '()\n', (505, 507), True, 'import matplotlib.pyplot as plt2\n')]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Sat Sep 29 21:55:06 2018 @author: leandrodemarcovedelago """ import numpy as np import numpy.matlib as npmatlib import math import Utils class Acor: def __init__(self, alg_variant, uses_log): """ * alg_variant should be one of the following strings: 'ContinuoLibre', 'ContinuoFijo', 'Vecinos', 'DiscretoPuro' * uses_log: boolean indicating whether or not to use logarithm of components instead of their regular value """ self.alg_variant = alg_variant self.uses_log = uses_log self.utils = Utils.Utils() self.num_dimensions = 5 if alg_variant == 'ContinuoLibre' else 4 self.num_resistors = 3 if alg_variant == 'ContinuoLibre' else 2 def _calc_comp_val_discrete(self, means, sigmas, comp_idx, p): """ This function is used to discretize the value of a filter component from a continuous calculalted value by ACOR when using the variant 'DiscretoPuro' * means: array of means * sigmas: array of standard deviations * comp_idx: index of the component to discretize * p: probabilities array """ i = comp_idx res_vals, cap_vals = self.utils.res_vals, self.utils.cap_vals log_res_vals = self.utils.log_res_vals log_cap_vals = self.utils.log_cap_vals # Select Gaussian Kernel l = Utils.wheel_selection(p) # Generate Gaussian Random Variable aux = means[l][i] + sigmas[l][i] * np.random.randn() is_resistor = i < self.num_resistors if (is_resistor and not self.uses_log): vals_to_use = res_vals elif (is_resistor and self.uses_log): vals_to_use = log_res_vals elif (not is_resistor and not self.uses_log): vals_to_use = cap_vals else: vals_to_use = log_cap_vals idx = np.abs(vals_to_use - aux).argmin() return vals_to_use[idx] def _initialize_archive(self, R1): res_min, res_max = self.utils.res_min, self.utils.res_max cap_min, cap_max = self.utils.cap_min, self.utils.cap_max num_dim = self.num_dimensions archive_size = self.utils.archive_size cost = self.utils.cost empty_ant = np.empty([num_dim + 1]) archive = npmatlib.repmat(empty_ant, archive_size, 1) for i in range(0, archive_size): for j in range(0, num_dim + 1): if (j < self.num_resistors): # Resistor low = math.log(res_min) if self.uses_log else res_min high = math.log(res_max) if self.uses_log else res_max archive[i][j] = np.random.uniform(low, high) elif (j < num_dim): # Capacitor low = math.log(cap_min) if self.uses_log else cap_min high = math.log(cap_max) if self.uses_log else cap_max archive[i][j] = np.random.uniform(low, high) else: # Cost archive[i][j] = cost(archive[i][0:num_dim], self.uses_log, R1) return archive def main_loop(self, R1 = None): archive_size = self.utils.archive_size num_dim = self.num_dimensions max_iterations = self.utils.max_iterations int_factor = self.utils.intensification_factor zeta = self.utils.zeta sample_size = self.utils.sample_size cost = self.utils.cost use_log = self.uses_log # Hold data of evolution for cost and variables through execution self.best_cost = np.zeros([max_iterations]) self.best_r1 = np.zeros([max_iterations]) self.best_r2 = np.zeros([max_iterations]) self.best_r3 = np.zeros([max_iterations]) self.best_c4 = np.zeros([max_iterations]) self.best_c5 = np.zeros([max_iterations]) archive = self._initialize_archive(R1) archive = archive[archive[:,num_dim].argsort()] # Weights array w = np.empty([archive_size]) for l in range(0, archive_size): f_factor = 1/(math.sqrt(2*math.pi)*int_factor*archive_size) s_factor = math.exp(-0.5*(l/(int_factor*archive_size))**2) w[l] = f_factor * s_factor # Selection probabilities p = w / np.sum(w) # ACOR Main Loop empty_ant = np.empty([num_dim + 1]) for it in range(0, max_iterations): # Means s = np.zeros([archive_size, num_dim]) for l in range(0, archive_size): s[l] = archive[l][0:num_dim] # Standard deviations sigma = np.zeros([archive_size, num_dim]) for l in range(0, archive_size): D = 0 for r in range(0, archive_size): D += abs(s[l]-s[r]) sigma[l] = zeta * D / (archive_size - 1) # Create new population array new_population = np.matlib.repmat(empty_ant, sample_size, 1) # Initialize solution for each new ant for t in range(0, sample_size): new_population[t][0:num_dim] = np.zeros([num_dim]) for i in range(0, num_dim): if (self.alg_variant == 'DiscretoPuro'): comp_val = self._calc_comp_val_discrete(s, sigma, i, p) new_population[t][i] = comp_val else: # Select Gaussian Kernel l = Utils.wheel_selection(p) # Generate Gaussian Random Variable new_population[t][i] = (s[l][i] + sigma[l][i]*np.random.randn()) # Evaluation of built solution filter_comps = new_population[t][0:num_dim] new_population[t][num_dim] = cost(filter_comps, use_log, R1) # Merge old population (archive) with new one merged_pop = np.concatenate([archive, new_population]) # And sort it again merged_pop = merged_pop[merged_pop[:,num_dim].argsort()] # Store the bests in the archive and update best sol archive = merged_pop[:archive_size] best_sol = archive[0][0:num_dim] # Current best solution, NO cost self.best_cost[it] = archive[0][num_dim] # Current best cost self.best_r1[it] = R1 if R1 != None else best_sol[0] if self.uses_log and R1 != None: self.best_r1[it] = math.log(R1) self.best_r2[it] = best_sol[0] if R1 != None else best_sol[1] self.best_r3[it] = best_sol[1] if R1 != None else best_sol[2] self.best_c4[it] = best_sol[2] if R1 != None else best_sol[3] self.best_c5[it] = best_sol[3] if R1 != None else best_sol[4] return archive[0] # Best population and cost
[ "Utils.wheel_selection", "Utils.Utils", "numpy.abs", "numpy.matlib.repmat", "math.sqrt", "math.log", "numpy.sum", "numpy.zeros", "numpy.empty", "numpy.concatenate", "numpy.random.uniform", "math.exp", "numpy.random.randn" ]
[((664, 677), 'Utils.Utils', 'Utils.Utils', ([], {}), '()\n', (675, 677), False, 'import Utils\n'), ((1533, 1557), 'Utils.wheel_selection', 'Utils.wheel_selection', (['p'], {}), '(p)\n', (1554, 1557), False, 'import Utils\n'), ((2429, 2452), 'numpy.empty', 'np.empty', (['[num_dim + 1]'], {}), '([num_dim + 1])\n', (2437, 2452), True, 'import numpy as np\n'), ((2471, 2514), 'numpy.matlib.repmat', 'npmatlib.repmat', (['empty_ant', 'archive_size', '(1)'], {}), '(empty_ant, archive_size, 1)\n', (2486, 2514), True, 'import numpy.matlib as npmatlib\n'), ((3906, 3932), 'numpy.zeros', 'np.zeros', (['[max_iterations]'], {}), '([max_iterations])\n', (3914, 3932), True, 'import numpy as np\n'), ((3956, 3982), 'numpy.zeros', 'np.zeros', (['[max_iterations]'], {}), '([max_iterations])\n', (3964, 3982), True, 'import numpy as np\n'), ((4006, 4032), 'numpy.zeros', 'np.zeros', (['[max_iterations]'], {}), '([max_iterations])\n', (4014, 4032), True, 'import numpy as np\n'), ((4056, 4082), 'numpy.zeros', 'np.zeros', (['[max_iterations]'], {}), '([max_iterations])\n', (4064, 4082), True, 'import numpy as np\n'), ((4106, 4132), 'numpy.zeros', 'np.zeros', (['[max_iterations]'], {}), '([max_iterations])\n', (4114, 4132), True, 'import numpy as np\n'), ((4156, 4182), 'numpy.zeros', 'np.zeros', (['[max_iterations]'], {}), '([max_iterations])\n', (4164, 4182), True, 'import numpy as np\n'), ((4340, 4364), 'numpy.empty', 'np.empty', (['[archive_size]'], {}), '([archive_size])\n', (4348, 4364), True, 'import numpy as np\n'), ((4711, 4734), 'numpy.empty', 'np.empty', (['[num_dim + 1]'], {}), '([num_dim + 1])\n', (4719, 4734), True, 'import numpy as np\n'), ((4501, 4556), 'math.exp', 'math.exp', (['(-0.5 * (l / (int_factor * archive_size)) ** 2)'], {}), '(-0.5 * (l / (int_factor * archive_size)) ** 2)\n', (4509, 4556), False, 'import math\n'), ((4647, 4656), 'numpy.sum', 'np.sum', (['w'], {}), '(w)\n', (4653, 4656), True, 'import numpy as np\n'), ((4815, 4848), 'numpy.zeros', 'np.zeros', (['[archive_size, num_dim]'], {}), '([archive_size, num_dim])\n', (4823, 4848), True, 'import numpy as np\n'), ((5006, 5039), 'numpy.zeros', 'np.zeros', (['[archive_size, num_dim]'], {}), '([archive_size, num_dim])\n', (5014, 5039), True, 'import numpy as np\n'), ((5341, 5384), 'numpy.matlib.repmat', 'np.matlib.repmat', (['empty_ant', 'sample_size', '(1)'], {}), '(empty_ant, sample_size, 1)\n', (5357, 5384), True, 'import numpy as np\n'), ((6415, 6456), 'numpy.concatenate', 'np.concatenate', (['[archive, new_population]'], {}), '([archive, new_population])\n', (6429, 6456), True, 'import numpy as np\n'), ((1645, 1662), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (1660, 1662), True, 'import numpy as np\n'), ((2041, 2066), 'numpy.abs', 'np.abs', (['(vals_to_use - aux)'], {}), '(vals_to_use - aux)\n', (2047, 2066), True, 'import numpy as np\n'), ((5527, 5546), 'numpy.zeros', 'np.zeros', (['[num_dim]'], {}), '([num_dim])\n', (5535, 5546), True, 'import numpy as np\n'), ((6967, 6979), 'math.log', 'math.log', (['R1'], {}), '(R1)\n', (6975, 6979), False, 'import math\n'), ((2870, 2898), 'numpy.random.uniform', 'np.random.uniform', (['low', 'high'], {}), '(low, high)\n', (2887, 2898), True, 'import numpy as np\n'), ((2711, 2728), 'math.log', 'math.log', (['res_min'], {}), '(res_min)\n', (2719, 2728), False, 'import math\n'), ((2786, 2803), 'math.log', 'math.log', (['res_max'], {}), '(res_max)\n', (2794, 2803), False, 'import math\n'), ((3152, 3180), 'numpy.random.uniform', 'np.random.uniform', (['low', 'high'], {}), '(low, high)\n', (3169, 3180), True, 'import numpy as np\n'), ((4432, 4454), 'math.sqrt', 'math.sqrt', (['(2 * math.pi)'], {}), '(2 * math.pi)\n', (4441, 4454), False, 'import math\n'), ((5908, 5932), 'Utils.wheel_selection', 'Utils.wheel_selection', (['p'], {}), '(p)\n', (5929, 5932), False, 'import Utils\n'), ((2993, 3010), 'math.log', 'math.log', (['cap_min'], {}), '(cap_min)\n', (3001, 3010), False, 'import math\n'), ((3068, 3085), 'math.log', 'math.log', (['cap_max'], {}), '(cap_max)\n', (3076, 3085), False, 'import math\n'), ((6111, 6128), 'numpy.random.randn', 'np.random.randn', ([], {}), '()\n', (6126, 6128), True, 'import numpy as np\n')]
import numpy as np import time class TimeLogger(): def __init__(self, log_names, num_cycles=1): self.log_names = log_names self.num_loggers = len(log_names) self.num_cycles = num_cycles self.reset() def reset(self): self.loggers = np.zeros(self.num_loggers) self.start_time = time.time() def log(self, logger_id): current_time = time.time() self.loggers[logger_id] += current_time - self.start_time self.start_time = current_time def print_logs(self): print("-- Time Logs --") for log_name, logger in zip(self.log_names, self.loggers): print("| {}: {} |".format(log_name, logger/self.num_cycles))
[ "numpy.zeros", "time.time" ]
[((281, 307), 'numpy.zeros', 'np.zeros', (['self.num_loggers'], {}), '(self.num_loggers)\n', (289, 307), True, 'import numpy as np\n'), ((334, 345), 'time.time', 'time.time', ([], {}), '()\n', (343, 345), False, 'import time\n'), ((408, 419), 'time.time', 'time.time', ([], {}), '()\n', (417, 419), False, 'import time\n')]
import numpy as np import scipy.signal, scipy.linalg from .utils import * from .signal import * from .wavelets import * __all__ = ["allpass", "leja", "sfact", "selesnick_hwlet", "evenbly_white_hwlet"] def allpass(tau, L): """ Return the filter d[n] such that A(z) = z^{-L} D(1/z) / D(z) approximates A(z) = z^{-tau}. The length of the filter d[n] is L+1. """ n = np.arange(L) x = np.r_[1, (L - n) * (L - n - tau) / (n + 1) / (n + 1 + tau)] return np.cumprod(x) def leja(a): """ Leja ordering of given numbers: * |a[0]| = max_j |a[j]| * prod_{i=0}^{k-1} |a[k] - a[i]| = max_j prod_{i=0}^{k-1} |a[j] - a[i]| When used as a preprocessing for np.poly it increases its numerical precision. """ n = len(a) c = np.argmax(np.abs(a)) a[[c, 0]] = a[[0, c]] for k in range(1, n): A = np.abs(a[:, np.newaxis][:, [0] * k] - a[np.newaxis, :k][[0] * n, :]) A = np.prod(A, -1) c = np.argmax(A) a[[k, c]] = a[[c, k]] return a def sfact(h, min_phase=False, eps=1e-5): """ Return a mid-phase (or min-phase) spectral factorization of the polynomial h of degree 2n; i.e., a polynomial g of degree n such that h(X) = X^n g(X) g_conj(1/X) The min_phase parameter is ignored if h is a complex signal. This code is inspired by Selesnick's sfactM.m and sfact.m. """ assert len(h) % 2 == 1, "Polynomial should have even degree." h = np.array(h) assert np.allclose( h, h[::-1].conj(), atol=0 ), "Coefficient sequence should be Hermitian." isreal = np.all(np.isreal(h)) # find roots of original polynomials roots = np.roots(h) # classify roots on unit circle roots_circ = roots[np.abs(np.abs(roots) - 1) < eps] assert ( len(roots_circ) % 2 == 0 ), "There should be an even number of roots of unit modulus." if min_phase and len(roots_circ) > 0: raise NotImplementedError # all roots on unit circle should appear an even number of times plus_one = np.abs(roots_circ - 1) < eps others = ~plus_one num_plus_one = sum(plus_one) assert num_plus_one % 2 == 0, "The root +1 should appear an even number of times." roots_circ_other = roots_circ[others] roots_circ_other = roots_circ_other[np.argsort(np.angle(roots_circ_other))] roots_circ_other = (roots_circ_other[::2] + roots_circ_other[1::2]) / 2 # collect half the +1's and half of all other roots roots_circ = np.r_[ roots_circ_other, [+1] * (num_plus_one // 2), ] # roots inside unit disk (for a polynomial with real coefficients, those roots should come in complex conjugate pairs unless they are real) roots_int = roots[np.abs(roots) <= 1 - eps] if isreal and not min_phase: pos_imags, reals = scipy.signal.filter_design._cplxreal(roots_int) A1 = np.r_[pos_imags[::2], pos_imags[::2].conj()] A2 = np.r_[pos_imags[1::2], pos_imags[1::2].conj()] imags = np.r_[1 / A1, A2] reals = np.r_[1 / reals[::2], reals[1::2]] roots_int = np.r_[imags, reals] # roots of the spectral factorization roots = np.r_[roots_circ, roots_int] roots = leja(roots) # build corresponding polynomial g = np.poly(roots) g = g * np.sqrt(h[-1] / (g[0] * g[-1])) if min(g) + max(g) < 0: g = -g # check that g is indeed a spectral factor of h assert np.allclose(np.convolve(g, g[::-1].conj()), h, atol=0), "No spectral factor" return g def selesnick_hwlet(K, L, min_phase=False): """ Return Selesnick's Hilbert transform wavelet pair (h, g). The parameter K determines the number of zeros at z=-1. The parameter L determines the support of the filter implementing the fractional delay. The length of both scaling filters is 2(K+L). This code is inspired by Selesnick's hwlet.m. """ d = allpass(1 / 2, L) # filter for z^(K+L) S(z) s1 = scipy.special.binom(2 * K, np.arange(2 * K + 1)) s2 = np.convolve(d, d[::-1]) s = np.convolve(s1, s2) # solve convolution system for z^(K+L-1) R(z) A = convmtx(s, 2 * (K + L) - 1) A = A[1::2] b = np.zeros(2 * (K + L) - 1) b[K + L - 1] = 1 r = np.linalg.solve(A, b) r = (r + r[::-1]) / 2 assert np.allclose(A @ r, b) # find spectral factor Q(z) and compute filter for z^K F(z) q = sfact(r, min_phase=min_phase) b = scipy.special.binom(K, np.arange(K + 1)) f = np.convolve(q, b) h = np.convolve(f, d) g = np.convolve(f, d[::-1]) # build orthogonal wavelet h = orthogonal_wavelet.from_scaling_filter(signal(h)) g = orthogonal_wavelet.from_scaling_filter(signal(g)) return h, g def evenbly_white_hwlet(): """ Return Evenbly-White's filter pair of length 4. """ h_s = signal( np.array([-0.129_409_52, 0.224_143_87, 0.836_516_3, 0.482_962_91]), start=-2 ) g_s = signal( np.array([0.482_962_91, 0.836_516_3, 0.224_143_87, -0.129_409_52]), start=0 ) h = orthogonal_wavelet.from_scaling_filter(h_s) g = orthogonal_wavelet.from_scaling_filter(g_s) return h, g
[ "numpy.abs", "numpy.prod", "numpy.convolve", "numpy.poly", "numpy.linalg.solve", "numpy.allclose", "numpy.arange", "numpy.sqrt", "numpy.argmax", "numpy.roots", "numpy.angle", "numpy.array", "numpy.zeros", "numpy.isreal", "numpy.cumprod" ]
[((399, 411), 'numpy.arange', 'np.arange', (['L'], {}), '(L)\n', (408, 411), True, 'import numpy as np\n'), ((491, 504), 'numpy.cumprod', 'np.cumprod', (['x'], {}), '(x)\n', (501, 504), True, 'import numpy as np\n'), ((1468, 1479), 'numpy.array', 'np.array', (['h'], {}), '(h)\n', (1476, 1479), True, 'import numpy as np\n'), ((1677, 1688), 'numpy.roots', 'np.roots', (['h'], {}), '(h)\n', (1685, 1688), True, 'import numpy as np\n'), ((3273, 3287), 'numpy.poly', 'np.poly', (['roots'], {}), '(roots)\n', (3280, 3287), True, 'import numpy as np\n'), ((4031, 4054), 'numpy.convolve', 'np.convolve', (['d', 'd[::-1]'], {}), '(d, d[::-1])\n', (4042, 4054), True, 'import numpy as np\n'), ((4063, 4082), 'numpy.convolve', 'np.convolve', (['s1', 's2'], {}), '(s1, s2)\n', (4074, 4082), True, 'import numpy as np\n'), ((4194, 4219), 'numpy.zeros', 'np.zeros', (['(2 * (K + L) - 1)'], {}), '(2 * (K + L) - 1)\n', (4202, 4219), True, 'import numpy as np\n'), ((4249, 4270), 'numpy.linalg.solve', 'np.linalg.solve', (['A', 'b'], {}), '(A, b)\n', (4264, 4270), True, 'import numpy as np\n'), ((4308, 4329), 'numpy.allclose', 'np.allclose', (['(A @ r)', 'b'], {}), '(A @ r, b)\n', (4319, 4329), True, 'import numpy as np\n'), ((4490, 4507), 'numpy.convolve', 'np.convolve', (['q', 'b'], {}), '(q, b)\n', (4501, 4507), True, 'import numpy as np\n'), ((4516, 4533), 'numpy.convolve', 'np.convolve', (['f', 'd'], {}), '(f, d)\n', (4527, 4533), True, 'import numpy as np\n'), ((4542, 4565), 'numpy.convolve', 'np.convolve', (['f', 'd[::-1]'], {}), '(f, d[::-1])\n', (4553, 4565), True, 'import numpy as np\n'), ((794, 803), 'numpy.abs', 'np.abs', (['a'], {}), '(a)\n', (800, 803), True, 'import numpy as np\n'), ((869, 937), 'numpy.abs', 'np.abs', (['(a[:, np.newaxis][:, [0] * k] - a[np.newaxis, :k][[0] * n, :])'], {}), '(a[:, np.newaxis][:, [0] * k] - a[np.newaxis, :k][[0] * n, :])\n', (875, 937), True, 'import numpy as np\n'), ((950, 964), 'numpy.prod', 'np.prod', (['A', '(-1)'], {}), '(A, -1)\n', (957, 964), True, 'import numpy as np\n'), ((977, 989), 'numpy.argmax', 'np.argmax', (['A'], {}), '(A)\n', (986, 989), True, 'import numpy as np\n'), ((1609, 1621), 'numpy.isreal', 'np.isreal', (['h'], {}), '(h)\n', (1618, 1621), True, 'import numpy as np\n'), ((2055, 2077), 'numpy.abs', 'np.abs', (['(roots_circ - 1)'], {}), '(roots_circ - 1)\n', (2061, 2077), True, 'import numpy as np\n'), ((3300, 3331), 'numpy.sqrt', 'np.sqrt', (['(h[-1] / (g[0] * g[-1]))'], {}), '(h[-1] / (g[0] * g[-1]))\n', (3307, 3331), True, 'import numpy as np\n'), ((4000, 4020), 'numpy.arange', 'np.arange', (['(2 * K + 1)'], {}), '(2 * K + 1)\n', (4009, 4020), True, 'import numpy as np\n'), ((4464, 4480), 'numpy.arange', 'np.arange', (['(K + 1)'], {}), '(K + 1)\n', (4473, 4480), True, 'import numpy as np\n'), ((4853, 4911), 'numpy.array', 'np.array', (['[-0.12940952, 0.22414387, 0.8365163, 0.48296291]'], {}), '([-0.12940952, 0.22414387, 0.8365163, 0.48296291])\n', (4861, 4911), True, 'import numpy as np\n'), ((4962, 5020), 'numpy.array', 'np.array', (['[0.48296291, 0.8365163, 0.22414387, -0.12940952]'], {}), '([0.48296291, 0.8365163, 0.22414387, -0.12940952])\n', (4970, 5020), True, 'import numpy as np\n'), ((2321, 2347), 'numpy.angle', 'np.angle', (['roots_circ_other'], {}), '(roots_circ_other)\n', (2329, 2347), True, 'import numpy as np\n'), ((2742, 2755), 'numpy.abs', 'np.abs', (['roots'], {}), '(roots)\n', (2748, 2755), True, 'import numpy as np\n'), ((1756, 1769), 'numpy.abs', 'np.abs', (['roots'], {}), '(roots)\n', (1762, 1769), True, 'import numpy as np\n')]
import numpy as np y=[-1,0,-1,0,-1,0,-1,1] c=np.array(['Negative One' if x==-1 else 'Zero' if x==0 else 'One' if x==1 else "" for x in y]) #no elif #else if d=c[c=="Zero"] print(d)
[ "numpy.array" ]
[((46, 151), 'numpy.array', 'np.array', (["[('Negative One' if x == -1 else 'Zero' if x == 0 else 'One' if x == 1 else\n '') for x in y]"], {}), "([('Negative One' if x == -1 else 'Zero' if x == 0 else 'One' if x ==\n 1 else '') for x in y])\n", (54, 151), True, 'import numpy as np\n')]
import pandas as pd import numpy as np from gym import spaces, Env from typing import List, Optional, Tuple, Dict from AdvisorClass import Advisor, SimpleAdvisor import timeit def scale(df,cols,scaling): df[cols]/= scaling return df MAX_STEPS = 1400 WINDOW_SIZE = 65 INITIAL_FORTUNE = 10000 BID_ASK_SPREAD_RANGE = (0.0065, 0.012) TRANSACTION_COST = 0.001 delta = 0.5 # fix the seed. np.random.seed(0) class MultiAssetTradingEnv(Env): """Custom Environment that follows gym interface""" metadata = {'render.modes': ['human']} _reward_types = ['profit','sharpe','discounted_profit','return','take_gain','log_return','step_profit','profit+step'] _scaling_functions = { 'tanh': np.tanh, 'sigmoid': lambda x: 1/(1+np.exp(-x)), 'softsign': lambda x: x/(1 + np.abs(x)), 'arctan': np.arctan, 'identity': lambda x: x, } def __init__(self, assets: List[pd.DataFrame], reward_type = 'profit', reward_scaling = 'softsign', discrete_actions: bool = False, scale_observations: bool = True, advisors: Optional[List[Advisor]] = None, window_size: int = WINDOW_SIZE, max_steps: int = MAX_STEPS, initial_fortune: float = INITIAL_FORTUNE, bid_ask_spread_range: Tuple[float, float] = BID_ASK_SPREAD_RANGE, transaction_cost: float = TRANSACTION_COST ): super(MultiAssetTradingEnv, self).__init__() """" Variables important for the environment: initial_fortune: starting initial_fortune for each episodes train_data: data_frame containing all the values bid_ask_spread: difference of price from buying-selling transaction_cost: cost from doing a trade window: allows a lookback to calculate indicators. """ assert reward_type in self._reward_types, 'Reward function unknown' self.reward_type = reward_type if reward_scaling in self._scaling_functions.keys(): self._scale_reward = self._scaling_functions[reward_scaling] else: self._scale_reward = lambda x: x self.scale_observations = scale_observations self.number_of_assets = len(assets) self.initial_fortune = initial_fortune self.old_net = initial_fortune self.window_size = window_size self.max_steps = max_steps self.data = assets self._active_data = list() self.bid_ask_spread_min = bid_ask_spread_range[0] self.bid_ask_spread_max = bid_ask_spread_range[1] self.transaction_cost = transaction_cost if advisors is None: advisors = [SimpleAdvisor()] self.advisors = advisors #Set action and observation space if discrete_actions: self.action_space = spaces.MultiDiscrete([3]*self.number_of_assets) else: self.action_space = spaces.Box(low=-1*np.ones(self.number_of_assets), high=np.ones(self.number_of_assets)) self.obs_size = sum([advisor.observation_space_size(num_assets = self.number_of_assets, window_size= self.window_size) for advisor in self.advisors]) + 4 + 2*self.number_of_assets self.observation_space = spaces.Box(low = -np.inf, high = np.inf, shape=(self.obs_size,), dtype=np.float64) self.reset_session() def _reward_function(self) -> float: """ Returns current reward of the environment """ if (self.reward_type == 'profit'): return self._scale_reward(float((self.net_worth - self.initial_fortune))) if (self.reward_type == 'return'): return (self.net_worth - self.initial_fortune)/(self.initial_fortune) if (self.reward_type == 'log_return'): return self._scale_reward(np.log(self.net_worth/self.initial_fortune)) if (self.reward_type == 'sharpe'): std = np.sqrt(np.array(self.std_portfolio).mean() + delta) return self._scale_reward((self.net_worth - self.initial_fortune)/(self.initial_fortune*std)) if (self.reward_type == 'discounted_profit'): return ((self._current_step - self.window_size)/MAX_STEPS)*self._scale_reward(float((self.net_worth - self.initial_fortune))) if (self.reward_type == 'take_gain'): return -1*self._scale_reward(np.max((self._current_step - self.window_size - MAX_STEPS)*(self.max_net_worth - self.net_worth)/self.initial_fortune,0))\ + self._scale_reward(float((self.net_worth - self.initial_fortune)/self.initial_fortune)) if (self.reward_type == 'step_profit'): return self._scale_reward((self.net_worth - self.old_net)/self.old_net) if (self.reward_type == 'profit+step'): return .5 * self._scale_reward((self.net_worth - self.initial_fortune)/self.initial_fortune) + 0.5 * self._scale_reward((self.net_worth -self.old_net)/self.old_net) def _make_trading_period(self) -> None: """ Sets the currently active trading episode of the environment """ start_episode = np.random.randint(1 + self.window_size, len(self.data[0]) - self._steps_left) self._active_data = list() for asset in self.data: #data = asset[start_episode - self.window_size:start_episode + self._steps_left].reset_index(drop=True) #data = data.reset_index(drop=True) dr = asset.loc[start_episode - self.window_size:start_episode + self._steps_left].reset_index(drop=True) dr = dr.reset_index(drop=True) self._active_data.append(dr) #print(self._active_data) def step(self, action): """ Define the evolution of the environment after the action:action has been taken by the agent. This is the action took at the begining of the session. Override from the gym.Env class' method. :param action: :return: obs,reward,done, {} """ self._current_step +=1 self._steps_left -=1 self.take_action(action) if self.net_worth <= 0: done = True obs = self.next_observation() reward = -1 elif np.any(self.portfolio < -10e-3): done = True obs = self.next_observation() reward = -1 elif self._steps_left == 1: done = True obs = self.reset() reward = self._reward_function() else: done = False obs = self.next_observation() reward = self._reward_function() return obs, reward, done, {} def reset_session(self) -> None: """ Reset the environment. """ self._current_step = self.window_size self._steps_left = self.max_steps self._make_trading_period() self.balance = self.initial_fortune self.last_action = np.zeros(self.number_of_assets) self.portfolio = np.zeros(self.number_of_assets) self.net_worth = self.initial_fortune self.max_net_worth = self.initial_fortune self.fees = 0 self.std_portfolio = [] self.old_net = self.initial_fortune def reset(self): """ Reset the environment, and return the next observation. :return: """ self.reset_session() return self.next_observation() def next_observation(self): """ Use the active dataset active_df to compile the state space fed to the agent. Scale the data to fit into the range of observation_space. Differentiation of data has to be implemented. :return: obs: observation given to the agent. Modify observation_space accordingly. """ # to think about max_initial_volume = max([asset_data['Volume'][0] for asset_data in self.data]) max_initial_open_price = max([asset_data['Open'][0] for asset_data in self.data]) window_data = list() for asset_data in self._active_data: window_asset_data = asset_data[self._current_step-self.window_size:self._current_step] if self.scale_observations: window_asset_data.Volume /= max_initial_volume #window_asset_data.apply(lambda x: x/max_initial_volume, index=['Volume'],axis =1) #window_asset_data[['Open', 'Close', 'High', 'Low']] = window_asset_data[['Open', 'Close', 'High', 'Low']]/max_initial_open_price window_asset_data.Open /= max_initial_open_price window_asset_data.Close /= max_initial_open_price window_asset_data.High /= max_initial_open_price window_asset_data.Low /= max_initial_open_price window_data.append(window_asset_data) observed_features = [] for advisor in self.advisors: advisor_features = advisor.observation(window_data) observed_features = np.concatenate((observed_features, advisor_features)) if self.scale_observations: observed_features = np.concatenate(( observed_features, self.portfolio, self.last_action, [ self.balance/self.initial_fortune, self._current_step/self.max_steps, self.net_worth/self.initial_fortune, (self.net_worth - self.initial_fortune)/self.initial_fortune] )) else: observed_features = np.concatenate(( observed_features, self.portfolio, self.last_action, [ self.balance, self._current_step, self.net_worth, self.net_worth - self.initial_fortune ] )) observed_features = observed_features.reshape((self.obs_size,)) return observed_features def bid_ask_spreads(self): """ Returns the bid ask spread, currently a list of random values sampled uniformly at random from the specified bid ask spread range """ return np.random.uniform(low = self.bid_ask_spread_min, high = self.bid_ask_spread_max, size = (self.number_of_assets)) def take_action(self,action): """ SEE CONSTRUCTOR FOR FULL DETAILS Important remark: when the agent takes action, it has not seen the closing value. The closing value determines the portfolio value after the action is took. Translate to the action made by the agent. It modifies the holding of btc, namely btc_holdings. Update the btc_holdings. Update the portfolio value. :param: action: action the agent takes. A value in [-1,1]. :return: """ self.old_net = self.net_worth price_open = [] for asset in self._active_data: price_open.append(asset.loc[self._current_step,'Open']) price_open = np.array(price_open) price_close = [] for asset in self._active_data: price_close.append(asset.loc[self._current_step,'Close']) price_close = np.array(price_close) bid_ask_spreads = self.bid_ask_spreads() idx_buy = [] #Sell before buying for j in range(self.number_of_assets): bid_ask_spread = bid_ask_spreads[j] #This corresponds to a sell action. if action[j] < -0.25: current_price_ask = price_open[j] - bid_ask_spread size = (np.abs(action[j]) - 0.25) / 0.75 asset_sold = max(self.portfolio[j]*size, self.balance/(self.transaction_cost-current_price_ask)) transaction_fees = asset_sold*self.transaction_cost self.fees += transaction_fees self.balance += (asset_sold * current_price_ask -transaction_fees) self.portfolio[j] -= asset_sold elif action[j] > 0.25: idx_buy.append(j) for idx in idx_buy: bid_ask_spread = bid_ask_spreads[idx] # This corresponds to a buy action. current_price_bid = price_open[idx] + bid_ask_spread size = (action[idx] - 0.25)/0.75 total_possible = np.max(self.balance/(current_price_bid +self.transaction_cost), 0) asset_bought = total_possible * size transaction_fees = asset_bought * self.transaction_cost cost = asset_bought * current_price_bid self.fees += transaction_fees self.balance -= (cost + transaction_fees) self.portfolio[idx] += asset_bought # Update book keeping. Calculate new net worth self.std_portfolio.append((self.net_worth - np.sum(self.portfolio * price_close))**2) self.net_worth = self.balance + np.sum(self.portfolio * price_close) if self.net_worth > self.max_net_worth: self.max_net_worth = self.net_worth self.last_action = action #return price_open def render(self, mode='human'): """ Method overriding render method in gym.Env Stands for information of the environment to the human in front. Display the performance of the agent :param mode: :return: """ profit = self.net_worth - self.initial_fortune reward = self._reward_function() print(f'Step: {self._current_step - self.window_size} over {self.max_steps -1}') print(f'Balance: {self.balance}') print(f'Portfolio: {self.portfolio}') print(f'Trading fees: {self.fees}') print(f'Net worth: {self.net_worth} (Max net worth: {self.max_net_worth})') print(f'Profit: {profit}') print(f'Reward: {reward}') return self._current_step - self.window_size, profit, self.max_net_worth
[ "numpy.abs", "numpy.ones", "gym.spaces.MultiDiscrete", "numpy.log", "numpy.any", "gym.spaces.Box", "numpy.max", "numpy.array", "numpy.zeros", "numpy.sum", "AdvisorClass.SimpleAdvisor", "numpy.random.seed", "numpy.concatenate", "numpy.random.uniform", "numpy.exp" ]
[((415, 432), 'numpy.random.seed', 'np.random.seed', (['(0)'], {}), '(0)\n', (429, 432), True, 'import numpy as np\n'), ((3325, 3403), 'gym.spaces.Box', 'spaces.Box', ([], {'low': '(-np.inf)', 'high': 'np.inf', 'shape': '(self.obs_size,)', 'dtype': 'np.float64'}), '(low=-np.inf, high=np.inf, shape=(self.obs_size,), dtype=np.float64)\n', (3335, 3403), False, 'from gym import spaces, Env\n'), ((7091, 7122), 'numpy.zeros', 'np.zeros', (['self.number_of_assets'], {}), '(self.number_of_assets)\n', (7099, 7122), True, 'import numpy as np\n'), ((7149, 7180), 'numpy.zeros', 'np.zeros', (['self.number_of_assets'], {}), '(self.number_of_assets)\n', (7157, 7180), True, 'import numpy as np\n'), ((10449, 10557), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': 'self.bid_ask_spread_min', 'high': 'self.bid_ask_spread_max', 'size': 'self.number_of_assets'}), '(low=self.bid_ask_spread_min, high=self.bid_ask_spread_max,\n size=self.number_of_assets)\n', (10466, 10557), True, 'import numpy as np\n'), ((11309, 11329), 'numpy.array', 'np.array', (['price_open'], {}), '(price_open)\n', (11317, 11329), True, 'import numpy as np\n'), ((11493, 11514), 'numpy.array', 'np.array', (['price_close'], {}), '(price_close)\n', (11501, 11514), True, 'import numpy as np\n'), ((2919, 2968), 'gym.spaces.MultiDiscrete', 'spaces.MultiDiscrete', (['([3] * self.number_of_assets)'], {}), '([3] * self.number_of_assets)\n', (2939, 2968), False, 'from gym import spaces, Env\n'), ((6354, 6384), 'numpy.any', 'np.any', (['(self.portfolio < -0.01)'], {}), '(self.portfolio < -0.01)\n', (6360, 6384), True, 'import numpy as np\n'), ((9180, 9233), 'numpy.concatenate', 'np.concatenate', (['(observed_features, advisor_features)'], {}), '((observed_features, advisor_features))\n', (9194, 9233), True, 'import numpy as np\n'), ((9306, 9569), 'numpy.concatenate', 'np.concatenate', (['(observed_features, self.portfolio, self.last_action, [self.balance / self.\n initial_fortune, self._current_step / self.max_steps, self.net_worth /\n self.initial_fortune, (self.net_worth - self.initial_fortune) / self.\n initial_fortune])'], {}), '((observed_features, self.portfolio, self.last_action, [self.\n balance / self.initial_fortune, self._current_step / self.max_steps, \n self.net_worth / self.initial_fortune, (self.net_worth - self.\n initial_fortune) / self.initial_fortune]))\n', (9320, 9569), True, 'import numpy as np\n'), ((9766, 9936), 'numpy.concatenate', 'np.concatenate', (['(observed_features, self.portfolio, self.last_action, [self.balance, self.\n _current_step, self.net_worth, self.net_worth - self.initial_fortune])'], {}), '((observed_features, self.portfolio, self.last_action, [self.\n balance, self._current_step, self.net_worth, self.net_worth - self.\n initial_fortune]))\n', (9780, 9936), True, 'import numpy as np\n'), ((12650, 12719), 'numpy.max', 'np.max', (['(self.balance / (current_price_bid + self.transaction_cost))', '(0)'], {}), '(self.balance / (current_price_bid + self.transaction_cost), 0)\n', (12656, 12719), True, 'import numpy as np\n'), ((13234, 13270), 'numpy.sum', 'np.sum', (['(self.portfolio * price_close)'], {}), '(self.portfolio * price_close)\n', (13240, 13270), True, 'import numpy as np\n'), ((2760, 2775), 'AdvisorClass.SimpleAdvisor', 'SimpleAdvisor', ([], {}), '()\n', (2773, 2775), False, 'from AdvisorClass import Advisor, SimpleAdvisor\n'), ((3909, 3954), 'numpy.log', 'np.log', (['(self.net_worth / self.initial_fortune)'], {}), '(self.net_worth / self.initial_fortune)\n', (3915, 3954), True, 'import numpy as np\n'), ((784, 794), 'numpy.exp', 'np.exp', (['(-x)'], {}), '(-x)\n', (790, 794), True, 'import numpy as np\n'), ((835, 844), 'numpy.abs', 'np.abs', (['x'], {}), '(x)\n', (841, 844), True, 'import numpy as np\n'), ((3070, 3100), 'numpy.ones', 'np.ones', (['self.number_of_assets'], {}), '(self.number_of_assets)\n', (3077, 3100), True, 'import numpy as np\n'), ((13149, 13185), 'numpy.sum', 'np.sum', (['(self.portfolio * price_close)'], {}), '(self.portfolio * price_close)\n', (13155, 13185), True, 'import numpy as np\n'), ((3033, 3063), 'numpy.ones', 'np.ones', (['self.number_of_assets'], {}), '(self.number_of_assets)\n', (3040, 3063), True, 'import numpy as np\n'), ((4460, 4590), 'numpy.max', 'np.max', (['((self._current_step - self.window_size - MAX_STEPS) * (self.max_net_worth -\n self.net_worth) / self.initial_fortune)', '(0)'], {}), '((self._current_step - self.window_size - MAX_STEPS) * (self.\n max_net_worth - self.net_worth) / self.initial_fortune, 0)\n', (4466, 4590), True, 'import numpy as np\n'), ((11902, 11919), 'numpy.abs', 'np.abs', (['action[j]'], {}), '(action[j])\n', (11908, 11919), True, 'import numpy as np\n'), ((4025, 4053), 'numpy.array', 'np.array', (['self.std_portfolio'], {}), '(self.std_portfolio)\n', (4033, 4053), True, 'import numpy as np\n')]
#from scipy.stats.stats import mode import tensorflow as tf import math import tensorflow.keras as keras #from tensorflow.python.keras import activations from tensorflow.python.keras import callbacks #import metrics as met import cv2 import os import numpy as np from sklearn.model_selection import train_test_split from tensorflow import config #from keras_preprocessing.image import ImageDataGenerator from sklearn.metrics import roc_auc_score , roc_curve #import pandas as pd from keras import backend as K from pathlib import * import pickle from tensorflow import device from utils import Dataloader from tensorflow.keras.utils import plot_model #import gc #gc.enable() #gc.set_debug(gc.DEBUG_LEAK) #tf.compat.v1.disable_eager_execution() gpus = config.experimental.list_physical_devices('GPU') config.experimental.set_memory_growth(gpus[0], True) def LoadTrainTestData(): bilder = list() bildmappar = list() for folder in os.listdir("data//UFC//training//frames"): path = os.path.join("data//UFC//training//frames",folder) bildmappar.append(folder) for img in os.listdir(path): bild = os.path.join(path,img) bilder.append(bild) etiketter = list() path = "data//UFC//training" träningsEttiketer = (x for x in Path(path).iterdir() if x.is_file()) for ettiket in träningsEttiketer: etiketter.append(np.load(ettiket)) etiketter = np.concatenate(etiketter,axis=0) #labels = np.load("data/frame_labels_avenue.npy") #labels = np.reshape(labels,labels.shape[1]) #X_train, X_test, Y_train, Y_test = train_test_split(bilder,etiketter,test_size=0.0001, random_state= 100) test_bilder = list() for folder in os.listdir("data//UFC//testing//frames"): path = os.path.join("data//UFC//testing//frames",folder) #bildmappar.append(folder) for img in os.listdir(path): bild = os.path.join(path,img) test_bilder.append(bild) test_etiketter = list() path = "data//UFC//testing" testnings_ettiketter = (x for x in Path(path).iterdir() if x.is_file()) for ettiket in testnings_ettiketter: test_etiketter.append(np.load(ettiket)) test_etiketter = np.concatenate(test_etiketter,axis=0) return bilder,etiketter,test_bilder,test_etiketter def LoadTrainAvenueData(): bilder = list() bildmappar = list() for folder in os.listdir("data//avenue//testing//frames"): path = os.path.join("data//avenue//testing//frames",folder) bildmappar.append(folder) for img in os.listdir(path): bild = os.path.join(path,img) bilder.append(bild) labels = np.load("data/frame_labels_avenue.npy") labels = np.reshape(labels,(labels.shape[1])) X_train, X_test, Y_train, Y_test = train_test_split(bilder,labels,test_size=0.2, random_state= 100) return X_train,Y_train,X_test,Y_test def CreateModel(): model = keras.Sequential() model.add(keras.layers.Conv3D(input_shape =(240, 320, 3, 16),activation="relu",filters=10,kernel_size=3,padding="same")) model.add(keras.layers.SpatialDropout3D(0.7)) #model.add(keras.layers.BatchNormalization()) #model.add(keras.layers.Conv3D(activation="relu",filters=64,kernel_size=3,padding="same")) #model.add(keras.layers.BatchNormalization()) #model.add(keras.layers.Conv3D(activation="relu",filters=64,kernel_size=3,padding="same")) model.add(keras.layers.MaxPooling3D(pool_size=(2,2,1))) model.add(keras.layers.Conv3D(activation="relu",filters=20,kernel_size=3,padding="same")) model.add(keras.layers.SpatialDropout3D(0.7)) #model.add(keras.layers.Conv3D(activation="relu",filters=128,kernel_size=3,padding="same")) #model.add(keras.layers.Conv3D(activation="relu",filters=128,kernel_size=3,padding="same")) #model.add(keras.layers.BatchNormalization()) model.add(keras.layers.MaxPooling3D(pool_size=(2,2,1))) model.add(keras.layers.Conv3D(activation="relu",filters=20,kernel_size=3,padding="same")) model.add(keras.layers.SpatialDropout3D(0.7)) model.add(keras.layers.MaxPooling3D(pool_size=(2,2,1))) model.add(keras.layers.Conv3D(activation="relu",filters=20,kernel_size=3,padding="same")) model.add(keras.layers.SpatialDropout3D(0.7)) model.add(keras.layers.MaxPooling3D(pool_size=(2,2,1))) #model.add(keras.layers.Conv3D(activation="relu",filters=18,kernel_size=3,padding="same")) #model.add(keras.layers.SpatialDropout3D(0.6)) #model.add(keras.layers.MaxPooling3D(pool_size=(2,2,1))) #model.add(keras.layers.Conv3D(activation="relu",filters=512,kernel_size=3,padding="same")) #model.add(keras.layers.Conv3D(activation="relu",filters=512,kernel_size=3,padding="same")) #model.add(keras.layers.Conv3D(activation="relu",filters=512,kernel_size=3,padding="same")) #model.add(keras.layers.BatchNormalization()) #model.add(keras.layers.MaxPooling3D(pool_size=(2,2,1))) #model.add(keras.layers.Conv3D(activation="relu",filters=512,kernel_size=3,padding="same")) #model.add(keras.layers.Conv3D(activation="relu",filters=512,kernel_size=3,padding="same")) #model.add(keras.layers.Conv3D(activation="relu",filters=512,kernel_size=3,padding="same")) #model.add(keras.layers.BatchNormalization()) #model.add(keras.layers.MaxPooling3D(pool_size=(2,2,1))) #model.add(keras.layers.Dense(5,activation="relu")) #model.add(keras.layers.GlobalAveragePooling3D()) model.add(keras.layers.Flatten()) #model.add(keras.layers.Dropout(0.5)) model.add(keras.layers.Dense(1000,activation="relu")) model.add(keras.layers.Dropout(0.6)) model.add(keras.layers.Dense(100,activation="relu")) model.add(keras.layers.Dropout(0.6)) model.add(keras.layers.Dense(10,activation="relu")) model.add(keras.layers.Dropout(0.2)) model.add(keras.layers.Dense(1,activation="sigmoid")) return model #metrics = [keras.metrics.categorical_crossentropy,keras.metrics.Accuracy,keras.metrics.Precision,met.f1_m] if __name__ == "__main__": batch_size = 16 #model = CreateModel() model = keras.models.load_model("modelUCFLocal5") #model = keras.models.load_model("modelUFC3D-ep001-loss0.482.h5-val_loss0.502.h5") bilder, etiketter, test_bilder, test_etiketter = LoadTrainTestData() #bilder, etiketter, test_bilder, test_etiketter = LoadTrainAvenueData() train_gen = Dataloader(bilder,etiketter,batch_size) test_gen = Dataloader(test_bilder,test_etiketter,batch_size) train_steps = math.ceil( len(bilder) / batch_size) validation_steps =math.ceil( len(test_bilder) / batch_size) #model.compile(optimizer="adam",metrics=["acc",met.f1_m,met.precision_m,met.recall_m],loss="binary_crossentropy") #model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.00001),metrics=["binary_accuracy","AUC","Precision","Recall","TruePositives","TrueNegatives","FalsePositives","FalseNegatives"],loss="binary_crossentropy") #model.run_eagerly = True model.summary() plot_model(model,show_shapes=True,show_layer_names=False) #quit() filepath = 'modelAvenue-ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.tf' #callbacks = [keras.callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min')]#keras.callbacks.EarlyStopping(monitor="val_loss", patience=3, mode="min") #history = model.fit(train_gen,verbose=1,epochs=20,steps_per_epoch=train_steps,callbacks=callbacks,validation_data=test_gen,validation_steps=validation_steps,workers=16,max_queue_size=15)#,validation_data=(X_test,Y_test)) model.fit(train_gen,verbose=1,epochs=5,steps_per_epoch=train_steps,workers=16,max_queue_size=15)#,validation_data=(X_test,Y_test)) model.save("modelUCFLocal5",save_format='tf') #with open("historyAv.pk","wb") as handle: # pickle.dump(history.history,handle) reconstructed_model = keras.models.load_model("modelUCFLocal5") np.testing.assert_allclose(model.predict(test_gen,steps=validation_steps), reconstructed_model.predict(test_gen,steps=validation_steps)) np.testing.assert_allclose(model.evaluate(test_gen,steps=validation_steps), reconstructed_model.evaluate(test_gen,steps=validation_steps)) model.evaluate(test_gen,steps=validation_steps,verbose=1) #y_score = model.predict(test_gen,steps=validation_steps) #auc = roc_auc_score(test_etiketter,y_score=y_score) #print('AUC: ', auc*100, '%')
[ "tensorflow.keras.layers.Conv3D", "os.listdir", "numpy.reshape", "tensorflow.keras.layers.SpatialDropout3D", "tensorflow.keras.layers.MaxPooling3D", "tensorflow.config.experimental.set_memory_growth", "sklearn.model_selection.train_test_split", "tensorflow.keras.Sequential", "tensorflow.keras.layers...
[((755, 803), 'tensorflow.config.experimental.list_physical_devices', 'config.experimental.list_physical_devices', (['"""GPU"""'], {}), "('GPU')\n", (796, 803), False, 'from tensorflow import config\n'), ((805, 857), 'tensorflow.config.experimental.set_memory_growth', 'config.experimental.set_memory_growth', (['gpus[0]', '(True)'], {}), '(gpus[0], True)\n', (842, 857), False, 'from tensorflow import config\n'), ((946, 987), 'os.listdir', 'os.listdir', (['"""data//UFC//training//frames"""'], {}), "('data//UFC//training//frames')\n", (956, 987), False, 'import os\n'), ((1446, 1479), 'numpy.concatenate', 'np.concatenate', (['etiketter'], {'axis': '(0)'}), '(etiketter, axis=0)\n', (1460, 1479), True, 'import numpy as np\n'), ((1738, 1778), 'os.listdir', 'os.listdir', (['"""data//UFC//testing//frames"""'], {}), "('data//UFC//testing//frames')\n", (1748, 1778), False, 'import os\n'), ((2263, 2301), 'numpy.concatenate', 'np.concatenate', (['test_etiketter'], {'axis': '(0)'}), '(test_etiketter, axis=0)\n', (2277, 2301), True, 'import numpy as np\n'), ((2447, 2490), 'os.listdir', 'os.listdir', (['"""data//avenue//testing//frames"""'], {}), "('data//avenue//testing//frames')\n", (2457, 2490), False, 'import os\n'), ((2719, 2758), 'numpy.load', 'np.load', (['"""data/frame_labels_avenue.npy"""'], {}), "('data/frame_labels_avenue.npy')\n", (2726, 2758), True, 'import numpy as np\n'), ((2772, 2807), 'numpy.reshape', 'np.reshape', (['labels', 'labels.shape[1]'], {}), '(labels, labels.shape[1])\n', (2782, 2807), True, 'import numpy as np\n'), ((2848, 2913), 'sklearn.model_selection.train_test_split', 'train_test_split', (['bilder', 'labels'], {'test_size': '(0.2)', 'random_state': '(100)'}), '(bilder, labels, test_size=0.2, random_state=100)\n', (2864, 2913), False, 'from sklearn.model_selection import train_test_split\n'), ((2988, 3006), 'tensorflow.keras.Sequential', 'keras.Sequential', ([], {}), '()\n', (3004, 3006), True, 'import tensorflow.keras as keras\n'), ((6163, 6204), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['"""modelUCFLocal5"""'], {}), "('modelUCFLocal5')\n", (6186, 6204), True, 'import tensorflow.keras as keras\n'), ((6457, 6498), 'utils.Dataloader', 'Dataloader', (['bilder', 'etiketter', 'batch_size'], {}), '(bilder, etiketter, batch_size)\n', (6467, 6498), False, 'from utils import Dataloader\n'), ((6513, 6564), 'utils.Dataloader', 'Dataloader', (['test_bilder', 'test_etiketter', 'batch_size'], {}), '(test_bilder, test_etiketter, batch_size)\n', (6523, 6564), False, 'from utils import Dataloader\n'), ((7079, 7138), 'tensorflow.keras.utils.plot_model', 'plot_model', (['model'], {'show_shapes': '(True)', 'show_layer_names': '(False)'}), '(model, show_shapes=True, show_layer_names=False)\n', (7089, 7138), False, 'from tensorflow.keras.utils import plot_model\n'), ((7963, 8004), 'tensorflow.keras.models.load_model', 'keras.models.load_model', (['"""modelUCFLocal5"""'], {}), "('modelUCFLocal5')\n", (7986, 8004), True, 'import tensorflow.keras as keras\n'), ((1004, 1055), 'os.path.join', 'os.path.join', (['"""data//UFC//training//frames"""', 'folder'], {}), "('data//UFC//training//frames', folder)\n", (1016, 1055), False, 'import os\n'), ((1108, 1124), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (1118, 1124), False, 'import os\n'), ((1795, 1845), 'os.path.join', 'os.path.join', (['"""data//UFC//testing//frames"""', 'folder'], {}), "('data//UFC//testing//frames', folder)\n", (1807, 1845), False, 'import os\n'), ((1899, 1915), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (1909, 1915), False, 'import os\n'), ((2507, 2560), 'os.path.join', 'os.path.join', (['"""data//avenue//testing//frames"""', 'folder'], {}), "('data//avenue//testing//frames', folder)\n", (2519, 2560), False, 'import os\n'), ((2613, 2629), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (2623, 2629), False, 'import os\n'), ((3022, 3138), 'tensorflow.keras.layers.Conv3D', 'keras.layers.Conv3D', ([], {'input_shape': '(240, 320, 3, 16)', 'activation': '"""relu"""', 'filters': '(10)', 'kernel_size': '(3)', 'padding': '"""same"""'}), "(input_shape=(240, 320, 3, 16), activation='relu',\n filters=10, kernel_size=3, padding='same')\n", (3041, 3138), True, 'import tensorflow.keras as keras\n'), ((3147, 3181), 'tensorflow.keras.layers.SpatialDropout3D', 'keras.layers.SpatialDropout3D', (['(0.7)'], {}), '(0.7)\n', (3176, 3181), True, 'import tensorflow.keras as keras\n'), ((3487, 3533), 'tensorflow.keras.layers.MaxPooling3D', 'keras.layers.MaxPooling3D', ([], {'pool_size': '(2, 2, 1)'}), '(pool_size=(2, 2, 1))\n', (3512, 3533), True, 'import tensorflow.keras as keras\n'), ((3548, 3634), 'tensorflow.keras.layers.Conv3D', 'keras.layers.Conv3D', ([], {'activation': '"""relu"""', 'filters': '(20)', 'kernel_size': '(3)', 'padding': '"""same"""'}), "(activation='relu', filters=20, kernel_size=3, padding=\n 'same')\n", (3567, 3634), True, 'import tensorflow.keras as keras\n'), ((3642, 3676), 'tensorflow.keras.layers.SpatialDropout3D', 'keras.layers.SpatialDropout3D', (['(0.7)'], {}), '(0.7)\n', (3671, 3676), True, 'import tensorflow.keras as keras\n'), ((3934, 3980), 'tensorflow.keras.layers.MaxPooling3D', 'keras.layers.MaxPooling3D', ([], {'pool_size': '(2, 2, 1)'}), '(pool_size=(2, 2, 1))\n', (3959, 3980), True, 'import tensorflow.keras as keras\n'), ((3995, 4081), 'tensorflow.keras.layers.Conv3D', 'keras.layers.Conv3D', ([], {'activation': '"""relu"""', 'filters': '(20)', 'kernel_size': '(3)', 'padding': '"""same"""'}), "(activation='relu', filters=20, kernel_size=3, padding=\n 'same')\n", (4014, 4081), True, 'import tensorflow.keras as keras\n'), ((4089, 4123), 'tensorflow.keras.layers.SpatialDropout3D', 'keras.layers.SpatialDropout3D', (['(0.7)'], {}), '(0.7)\n', (4118, 4123), True, 'import tensorflow.keras as keras\n'), ((4139, 4185), 'tensorflow.keras.layers.MaxPooling3D', 'keras.layers.MaxPooling3D', ([], {'pool_size': '(2, 2, 1)'}), '(pool_size=(2, 2, 1))\n', (4164, 4185), True, 'import tensorflow.keras as keras\n'), ((4200, 4286), 'tensorflow.keras.layers.Conv3D', 'keras.layers.Conv3D', ([], {'activation': '"""relu"""', 'filters': '(20)', 'kernel_size': '(3)', 'padding': '"""same"""'}), "(activation='relu', filters=20, kernel_size=3, padding=\n 'same')\n", (4219, 4286), True, 'import tensorflow.keras as keras\n'), ((4294, 4328), 'tensorflow.keras.layers.SpatialDropout3D', 'keras.layers.SpatialDropout3D', (['(0.7)'], {}), '(0.7)\n', (4323, 4328), True, 'import tensorflow.keras as keras\n'), ((4344, 4390), 'tensorflow.keras.layers.MaxPooling3D', 'keras.layers.MaxPooling3D', ([], {'pool_size': '(2, 2, 1)'}), '(pool_size=(2, 2, 1))\n', (4369, 4390), True, 'import tensorflow.keras as keras\n'), ((5523, 5545), 'tensorflow.keras.layers.Flatten', 'keras.layers.Flatten', ([], {}), '()\n', (5543, 5545), True, 'import tensorflow.keras as keras\n'), ((5603, 5646), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(1000)'], {'activation': '"""relu"""'}), "(1000, activation='relu')\n", (5621, 5646), True, 'import tensorflow.keras as keras\n'), ((5661, 5686), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (['(0.6)'], {}), '(0.6)\n', (5681, 5686), True, 'import tensorflow.keras as keras\n'), ((5702, 5744), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(100)'], {'activation': '"""relu"""'}), "(100, activation='relu')\n", (5720, 5744), True, 'import tensorflow.keras as keras\n'), ((5759, 5784), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (['(0.6)'], {}), '(0.6)\n', (5779, 5784), True, 'import tensorflow.keras as keras\n'), ((5800, 5841), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(10)'], {'activation': '"""relu"""'}), "(10, activation='relu')\n", (5818, 5841), True, 'import tensorflow.keras as keras\n'), ((5856, 5881), 'tensorflow.keras.layers.Dropout', 'keras.layers.Dropout', (['(0.2)'], {}), '(0.2)\n', (5876, 5881), True, 'import tensorflow.keras as keras\n'), ((5897, 5940), 'tensorflow.keras.layers.Dense', 'keras.layers.Dense', (['(1)'], {'activation': '"""sigmoid"""'}), "(1, activation='sigmoid')\n", (5915, 5940), True, 'import tensorflow.keras as keras\n'), ((1145, 1168), 'os.path.join', 'os.path.join', (['path', 'img'], {}), '(path, img)\n', (1157, 1168), False, 'import os\n'), ((1402, 1418), 'numpy.load', 'np.load', (['ettiket'], {}), '(ettiket)\n', (1409, 1418), True, 'import numpy as np\n'), ((1936, 1959), 'os.path.join', 'os.path.join', (['path', 'img'], {}), '(path, img)\n', (1948, 1959), False, 'import os\n'), ((2214, 2230), 'numpy.load', 'np.load', (['ettiket'], {}), '(ettiket)\n', (2221, 2230), True, 'import numpy as np\n'), ((2650, 2673), 'os.path.join', 'os.path.join', (['path', 'img'], {}), '(path, img)\n', (2662, 2673), False, 'import os\n')]
import tensorflow as tf import numpy as np import cnn c_cnn_model = cnn.cnn_model() # show the information about the model print(c_cnn_model.summary()) # inferencing print(c_cnn_model(np.random.random([10, 32, 32, 3]).astype(np.float32)))
[ "cnn.cnn_model", "numpy.random.random" ]
[((71, 86), 'cnn.cnn_model', 'cnn.cnn_model', ([], {}), '()\n', (84, 86), False, 'import cnn\n'), ((189, 222), 'numpy.random.random', 'np.random.random', (['[10, 32, 32, 3]'], {}), '([10, 32, 32, 3])\n', (205, 222), True, 'import numpy as np\n')]
import numpy as np import matplotlib.pyplot as plt import os import contorno from constantes import INTERVALOS, PASSOS, TAMANHO_BARRA, DELTA_T, DELTA_X import time # y = contorno.p_0 # y = contorno.p_1 # y = contorno.p_2 y = contorno.p_3 TAMANHO_BARRA = 2 x = np.linspace(0.0, TAMANHO_BARRA, INTERVALOS+1) y_temp = np.copy(y) for k in range(PASSOS+1): y = np.copy(y_temp) for i in range(1, INTERVALOS): y_temp[i] = y[i] + (DELTA_T/(DELTA_X**2)) * (y[i+1]-2*y[i]+y[i-1]) t = k*DELTA_T fig = plt.figure() ax = fig.add_subplot() fig.suptitle(f't={t:.3f}') ax.set_ylabel('T(x,t)') ax.set_xlabel('x') ax.set_ylim(-0.1, 1.1) plt.plot(x, y, '.', lw=2) plt.show()
[ "numpy.copy", "matplotlib.pyplot.plot", "numpy.linspace", "matplotlib.pyplot.figure", "matplotlib.pyplot.show" ]
[((262, 309), 'numpy.linspace', 'np.linspace', (['(0.0)', 'TAMANHO_BARRA', '(INTERVALOS + 1)'], {}), '(0.0, TAMANHO_BARRA, INTERVALOS + 1)\n', (273, 309), True, 'import numpy as np\n'), ((317, 327), 'numpy.copy', 'np.copy', (['y'], {}), '(y)\n', (324, 327), True, 'import numpy as np\n'), ((511, 523), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (521, 523), True, 'import matplotlib.pyplot as plt\n'), ((640, 665), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""."""'], {'lw': '(2)'}), "(x, y, '.', lw=2)\n", (648, 665), True, 'import matplotlib.pyplot as plt\n'), ((666, 676), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (674, 676), True, 'import matplotlib.pyplot as plt\n'), ((363, 378), 'numpy.copy', 'np.copy', (['y_temp'], {}), '(y_temp)\n', (370, 378), True, 'import numpy as np\n')]
"""Pitch-based representation output interface.""" from operator import attrgetter from typing import TYPE_CHECKING, Union import numpy as np from numpy import ndarray if TYPE_CHECKING: from ..music import Music def to_pitch_representation( music: "Music", use_hold_state: bool = False, dtype: Union[np.dtype, type, str] = int, ) -> ndarray: """Encode a Music object into pitch-based representation. The pitch-based represetantion represents music as a sequence of pitch, rest and (optional) hold tokens. Only monophonic melodies are compatible with this representation. The output shape is T x 1, where T is the number of time steps. The values indicate whether the current time step is a pitch (0-127), a rest (128) or, optionally, a hold (129). Parameters ---------- music : :class:`muspy.Music` Music object to encode. use_hold_state : bool, default: False Whether to use a special state for holds. dtype : np.dtype, type or str, default: int Data type of the return array. Returns ------- ndarray, shape=(?, 1) Encoded array in pitch-based representation. """ # Collect notes notes = [] for track in music.tracks: notes.extend(track.notes) # Raise an error if no notes are found if not notes: raise RuntimeError("No notes found.") # Sort the notes notes.sort(key=attrgetter("time", "pitch", "duration", "velocity")) # Initialize the array length = max((note.end for note in notes)) array = np.zeros((length, 1), dtype) # Fill the array with rests if use_hold_state: array.fill(128) # Encode note pitches for note in notes: if use_hold_state: array[note.time] = note.pitch array[note.time + 1 : note.time + note.duration] = 129 else: array[note.time : note.time + note.duration] = note.pitch return array
[ "operator.attrgetter", "numpy.zeros" ]
[((1574, 1602), 'numpy.zeros', 'np.zeros', (['(length, 1)', 'dtype'], {}), '((length, 1), dtype)\n', (1582, 1602), True, 'import numpy as np\n'), ((1434, 1485), 'operator.attrgetter', 'attrgetter', (['"""time"""', '"""pitch"""', '"""duration"""', '"""velocity"""'], {}), "('time', 'pitch', 'duration', 'velocity')\n", (1444, 1485), False, 'from operator import attrgetter\n')]
import anki_vector from anki_vector.events import Events import cv2 as cv import numpy as np import time import math # Constants Debug = False # milliseconds per main loop execution MainLoopDelay = 20 HeadTilt = anki_vector.robot.MIN_HEAD_ANGLE + anki_vector.util.degrees(5.0) LiftHeight = 0.0 class Camera: FovH = anki_vector.util.degrees(90.0) FovV = anki_vector.util.degrees(50.0) PixelsH = 640.0 PixelsV = 360.0 FocalLengthH = (PixelsH / 2.0) / math.tan(FovH.radians / 2.0) DegressPerPixelH = FovH.degrees / PixelsH DegreesPerPixelV = FovV.degrees / PixelsV class Ball: def __init__(self): # typical globals, but can be changed per instance if required # i.e. if more than one type and color of ball is used # these are based on the blue ball from a LEGO Mindstorms kit self.HsvMin = (105, 100, 10) self.HsvMax = (120, 200, 255) self.RadiusMax = 200.0 self.RadiusMin = 15.0 # was 25 self.RadiusScale = 38.0 self.RadiusTolerance = 0.2 self.AspectRatio = 1.0 self.AspectRatioTolerance = 0.5 self.AspectMin = (1 - self.AspectRatioTolerance) * self.AspectRatio self.AspectMax = (1 + self.AspectRatioTolerance) * self.AspectRatio self.TargetX = 310 self.TargetY = 70 self.found = False self.x = 0.0 self.y = 0.0 self.center = 0.0 self.radius = 0.0 self.deltaX = 0.0 self.deltaY = 0.0 self.imageId = 0 self.distance = anki_vector.util.distance_mm(0.0) self.angle = anki_vector.util.degrees(0.0) self.mask = True self.debug = True self.testing = False # this will change depending on the size of the ball used, so shouldn't # really be hard coded here for a generic class... # hack... fix later... or override def computeDistance(self, radius): # formula determined by measuring distance to ball versus # radius, entering into spreadsheet, calculating a regression formula distance = anki_vector.util.distance_mm(-174.1 * math.log(radius) + 852.5) return distance def computeAngle(self, x, camera): # measuring angle is based on camera FOV angle = anki_vector.util.radians(math.atan((x - (camera.PixelsH / 2.0)) / camera.FocalLengthH)) return angle # find the ball in an image def findBall(self, imageId: int, image: np.array, maskImage: np.array, camera: Camera): # only do this if we have a new image if (imageId != self.imageId): self.imageId = imageId # Much information and some code was obtained from here: # https://www.pyimagesearch.com/2015/09/14/ball-tracking-with-opencv/ # blur, convert to HSV, look for the ball HSV values, do some filtering maskedImage = cv.bitwise_and(image, maskImage) blurImage = cv.GaussianBlur(maskedImage, (11, 11), 0) hsvImage = cv.cvtColor(blurImage, cv.COLOR_BGR2HSV) self.trackerImage = cv.inRange(hsvImage, self.HsvMin, self.HsvMax) self.trackerImage = cv.erode(self.trackerImage, None, iterations = 2) self.trackerImage = cv.dilate(self.trackerImage, None, iterations = 2) # find contours im2, contours, hierarchy = cv.findContours(self.trackerImage.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) # We're given a a bunch of contours that might enclose the ball # To help decide if a contour is a ball: # - pick the largest contour # - find the radius of the enclosing circle (scale based on distance) # - compute the aspect ratio # If the radius and aspect ratio are within the tolerances of a ball, # it most likely is a ball. However, some features on the rink can # still come close to looking like a ball... more work could be done. if len(contours) > 0: # find the largest contour in the mask, then use # it to compute the minimum enclosing circle and # centroid c = max(contours, key=cv.contourArea) ((x, y), radius) = cv.minEnclosingCircle(c) M = cv.moments(c) center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"])) # compute the aspect ratio bX, bY, bW, bH = cv.boundingRect(c) aspectRatio = float(bW) / float(bH) deltaX = self.TargetX - int(x) # positive is to the left deltaY = self.TargetY - int(y) # positive is away # compute angle and distance based on radius # formula determined by measuring distance to ball versus # radius, entering into spreadsheet, calculating a regression formula # measuring angle is based on camera FOV # # this will change depending on the size of the ball used, so shouldn't # really be hard coded here for a generic class... # hack... fix later... distance = self.computeDistance(radius) angle = self.computeAngle(x, camera) if (self.debug): print(f'[findBall] ({x:.0f},{y:.0f}) ({deltaX:.0f},{deltaY:.0f}) R = {radius:.2f}') print(f'[findBall] width = {bW:.0f} height = {bH:.0f} aspect = {aspectRatio:.2f}') print(f'[findBall] angle = {angle.degrees:.2f} distance = {distance.distance_mm:.2f}') # perform the actual checks if ( (self.RadiusMin < radius < self.RadiusMax) and (self.AspectMin < aspectRatio < self.AspectMax) or self.testing ): if (self.debug): print('[findBall] Got it') self.found = True self.x = x self.y = y self.center = center self.radius = radius self.deltaX = deltaX self.deltaY = deltaY self.distance = distance self.angle = angle else: self.found = False # left of center is negative def goToObject(robot: anki_vector.Robot, distance: anki_vector.util.Distance, angle: anki_vector.util.Angle): global camera pDistance = 1.0 pAngle = 1.0 leftSpeed = pDistance * distance.distance_mm + pAngle * angle.degrees rightSpeed = pDistance * distance.distance_mm - pAngle * angle.degrees #print(f'[goToPixel] {leftSpeed:.1f}:{rightSpeed:.1f}') robot.motors.set_wheel_motors(leftSpeed, rightSpeed) def lookAround(robot: anki_vector.Robot, scanAngleIndex: int): ScanAngles = [0, -30, 30, -60, 60, -90, 90, -120, 120, -150, 150, 180] if (actionsDone()): robot.motors.set_wheel_motors(0, 0) scanAngleIndex += 1 if (scanAngleIndex == len(ScanAngles)): scanAngleIndex = 0 action(robot.behavior.turn_in_place(angle=anki_vector.util.degrees(ScanAngles[scanAngleIndex]), speed=anki_vector.util.degrees(60.0), is_absolute=True)) return scanAngleIndex def allDone(robot: anki_vector.Robot): print('[allDone] Cleaning up') robot.motors.set_wheel_motors(0, 0) cv.destroyAllWindows() robot.disconnect() exit() def actionsDone(): global actionList done = True for i in actionList: if not(i.done()): done = False return done def action(b): global actionList actionList.append(b) def main(): global actionList actionList = [] ball = Ball() camera = Camera() cvImageId = 0 scanAngleIndex = 0 # open the video window cv.namedWindow('Vector', cv.WINDOW_NORMAL) if ball.testing: cv.namedWindow('Tracker', cv.WINDOW_NORMAL) # read in the mask for Vector's lift (all the way down) vectorMaskImage = cv.imread('Vector_Mask.png') args = anki_vector.util.parse_command_args() # use AsyncRobot so that behaviors don't block robot = anki_vector.AsyncRobot(args.serial, enable_camera_feed=True, default_logging=Debug) robot.connect() time.sleep(1) done = False displayImage = False action(robot.behavior.set_head_angle(HeadTilt)) action(robot.behavior.set_lift_height(LiftHeight)) while not(actionsDone()): pass while not(done): # check to see if we have a new image if (robot.camera.latest_image_id != cvImageId): # if we do, convert it to an OpenCV image # and keep track of the id pilImage = robot.camera.latest_image cvImageId = robot.camera.latest_image_id cvImage = cv.cvtColor(np.array(pilImage), cv.COLOR_RGB2BGR) # display it displayImage = True # locate the ball (if we can see it) ball.findBall(imageId = cvImageId, image = cvImage, maskImage = vectorMaskImage, camera = camera) # ball overlay if ball.found: goToObject(robot, ball.distance, ball.angle) # draw the circle and centroid on the frame, # then update the list of tracked points cv.circle(cvImage, (int(ball.x), int(ball.y)), int(ball.radius), (0, 255, 255), 2) cv.circle(cvImage, ball.center, 5, (0, 0, 255), -1) else: #scanAngleIndex = lookAround(robot, scanAngleIndex) robot.motors.set_wheel_motors(0, 0) # display the image with any overlays cv.imshow('Vector', cvImage) if ball.testing: cv.imshow('Tracker', ball.trackerImage) # waitKey performs the display update # and checks to see if we hit the 'q' key c = cv.waitKey(MainLoopDelay) if (chr(c & 0xff) == 'q'): done = True allDone(robot) if __name__ == "__main__": main()
[ "time.sleep", "cv2.imshow", "math.log", "numpy.array", "cv2.destroyAllWindows", "math.atan", "anki_vector.util.distance_mm", "math.tan", "cv2.erode", "anki_vector.AsyncRobot", "cv2.waitKey", "anki_vector.util.parse_command_args", "cv2.minEnclosingCircle", "cv2.circle", "cv2.cvtColor", ...
[((251, 280), 'anki_vector.util.degrees', 'anki_vector.util.degrees', (['(5.0)'], {}), '(5.0)\n', (275, 280), False, 'import anki_vector\n'), ((321, 351), 'anki_vector.util.degrees', 'anki_vector.util.degrees', (['(90.0)'], {}), '(90.0)\n', (345, 351), False, 'import anki_vector\n'), ((360, 390), 'anki_vector.util.degrees', 'anki_vector.util.degrees', (['(50.0)'], {}), '(50.0)\n', (384, 390), False, 'import anki_vector\n'), ((6373, 6395), 'cv2.destroyAllWindows', 'cv.destroyAllWindows', ([], {}), '()\n', (6393, 6395), True, 'import cv2 as cv\n'), ((6754, 6796), 'cv2.namedWindow', 'cv.namedWindow', (['"""Vector"""', 'cv.WINDOW_NORMAL'], {}), "('Vector', cv.WINDOW_NORMAL)\n", (6768, 6796), True, 'import cv2 as cv\n'), ((6938, 6966), 'cv2.imread', 'cv.imread', (['"""Vector_Mask.png"""'], {}), "('Vector_Mask.png')\n", (6947, 6966), True, 'import cv2 as cv\n'), ((6976, 7013), 'anki_vector.util.parse_command_args', 'anki_vector.util.parse_command_args', ([], {}), '()\n', (7011, 7013), False, 'import anki_vector\n'), ((7071, 7158), 'anki_vector.AsyncRobot', 'anki_vector.AsyncRobot', (['args.serial'], {'enable_camera_feed': '(True)', 'default_logging': 'Debug'}), '(args.serial, enable_camera_feed=True,\n default_logging=Debug)\n', (7093, 7158), False, 'import anki_vector\n'), ((7173, 7186), 'time.sleep', 'time.sleep', (['(1)'], {}), '(1)\n', (7183, 7186), False, 'import time\n'), ((459, 487), 'math.tan', 'math.tan', (['(FovH.radians / 2.0)'], {}), '(FovH.radians / 2.0)\n', (467, 487), False, 'import math\n'), ((1383, 1416), 'anki_vector.util.distance_mm', 'anki_vector.util.distance_mm', (['(0.0)'], {}), '(0.0)\n', (1411, 1416), False, 'import anki_vector\n'), ((1432, 1461), 'anki_vector.util.degrees', 'anki_vector.util.degrees', (['(0.0)'], {}), '(0.0)\n', (1456, 1461), False, 'import anki_vector\n'), ((6817, 6860), 'cv2.namedWindow', 'cv.namedWindow', (['"""Tracker"""', 'cv.WINDOW_NORMAL'], {}), "('Tracker', cv.WINDOW_NORMAL)\n", (6831, 6860), True, 'import cv2 as cv\n'), ((8541, 8566), 'cv2.waitKey', 'cv.waitKey', (['MainLoopDelay'], {}), '(MainLoopDelay)\n', (8551, 8566), True, 'import cv2 as cv\n'), ((2065, 2124), 'math.atan', 'math.atan', (['((x - camera.PixelsH / 2.0) / camera.FocalLengthH)'], {}), '((x - camera.PixelsH / 2.0) / camera.FocalLengthH)\n', (2074, 2124), False, 'import math\n'), ((2589, 2621), 'cv2.bitwise_and', 'cv.bitwise_and', (['image', 'maskImage'], {}), '(image, maskImage)\n', (2603, 2621), True, 'import cv2 as cv\n'), ((2637, 2678), 'cv2.GaussianBlur', 'cv.GaussianBlur', (['maskedImage', '(11, 11)', '(0)'], {}), '(maskedImage, (11, 11), 0)\n', (2652, 2678), True, 'import cv2 as cv\n'), ((2693, 2733), 'cv2.cvtColor', 'cv.cvtColor', (['blurImage', 'cv.COLOR_BGR2HSV'], {}), '(blurImage, cv.COLOR_BGR2HSV)\n', (2704, 2733), True, 'import cv2 as cv\n'), ((2757, 2803), 'cv2.inRange', 'cv.inRange', (['hsvImage', 'self.HsvMin', 'self.HsvMax'], {}), '(hsvImage, self.HsvMin, self.HsvMax)\n', (2767, 2803), True, 'import cv2 as cv\n'), ((2827, 2874), 'cv2.erode', 'cv.erode', (['self.trackerImage', 'None'], {'iterations': '(2)'}), '(self.trackerImage, None, iterations=2)\n', (2835, 2874), True, 'import cv2 as cv\n'), ((2900, 2948), 'cv2.dilate', 'cv.dilate', (['self.trackerImage', 'None'], {'iterations': '(2)'}), '(self.trackerImage, None, iterations=2)\n', (2909, 2948), True, 'import cv2 as cv\n'), ((8357, 8385), 'cv2.imshow', 'cv.imshow', (['"""Vector"""', 'cvImage'], {}), "('Vector', cvImage)\n", (8366, 8385), True, 'import cv2 as cv\n'), ((3767, 3791), 'cv2.minEnclosingCircle', 'cv.minEnclosingCircle', (['c'], {}), '(c)\n', (3788, 3791), True, 'import cv2 as cv\n'), ((3800, 3813), 'cv2.moments', 'cv.moments', (['c'], {}), '(c)\n', (3810, 3813), True, 'import cv2 as cv\n'), ((3933, 3951), 'cv2.boundingRect', 'cv.boundingRect', (['c'], {}), '(c)\n', (3948, 3951), True, 'import cv2 as cv\n'), ((7657, 7675), 'numpy.array', 'np.array', (['pilImage'], {}), '(pilImage)\n', (7665, 7675), True, 'import numpy as np\n'), ((8153, 8204), 'cv2.circle', 'cv.circle', (['cvImage', 'ball.center', '(5)', '(0, 0, 255)', '(-1)'], {}), '(cvImage, ball.center, 5, (0, 0, 255), -1)\n', (8162, 8204), True, 'import cv2 as cv\n'), ((8410, 8449), 'cv2.imshow', 'cv.imshow', (['"""Tracker"""', 'ball.trackerImage'], {}), "('Tracker', ball.trackerImage)\n", (8419, 8449), True, 'import cv2 as cv\n'), ((1906, 1922), 'math.log', 'math.log', (['radius'], {}), '(radius)\n', (1914, 1922), False, 'import math\n'), ((6118, 6170), 'anki_vector.util.degrees', 'anki_vector.util.degrees', (['ScanAngles[scanAngleIndex]'], {}), '(ScanAngles[scanAngleIndex])\n', (6142, 6170), False, 'import anki_vector\n'), ((6182, 6212), 'anki_vector.util.degrees', 'anki_vector.util.degrees', (['(60.0)'], {}), '(60.0)\n', (6206, 6212), False, 'import anki_vector\n')]
#!/usr/bin/env python3 import numpy as np from math import nan def calc_parabolic_sar(df, af=0.2, steps=10): up = True sars = [nan] * len(df) sar = ep_lo = df.Low.iloc[0] ep = ep_hi = df.High.iloc[0] aaf = af aaf_step = aaf / steps af = 0 for i,(hi,lo) in enumerate(zip(df.High, df.Low)): # parabolic sar formula: sar = sar + af * (ep - sar) # handle new extreme points if hi > ep_hi: ep_hi = hi if up: ep = ep_hi af = min(aaf, af+aaf_step) elif lo < ep_lo: ep_lo = lo if not up: ep = ep_lo af = min(aaf, af+aaf_step) # handle switch if up: if lo < sar: up = not up sar = ep_hi ep = ep_lo = lo af = 0 else: if hi > sar: up = not up sar = ep_lo ep = ep_hi = hi af = 0 sars[i] = sar df['sar'] = sars return df['sar'] def calc_rsi(df, n=14): diff = df.Close.diff().values gains = diff losses = -diff gains[~(gains>0)] = 0.0 losses[~(losses>0)] = 1e-10 # we don't want divide by zero/NaN m = (n-1) / n ni = 1 / n g = gains[n] = gains[:n].mean() l = losses[n] = losses[:n].mean() gains[:n] = losses[:n] = nan for i,v in enumerate(gains[n:],n): g = gains[i] = ni*v + m*g for i,v in enumerate(losses[n:],n): l = losses[i] = ni*v + m*l rs = gains / losses rsi = 100 - (100/(1+rs)) return rsi def calc_stochastic_oscillator(df, n=14, m=3, smooth=3): lo = df.Low.rolling(n).min() hi = df.High.rolling(n).max() k = 100 * (df.Close-lo) / (hi-lo) d = k.rolling(m).mean() return k, d def calc_stochasticRsi_oscillator(df, n=14, m=3, smooth=3): lo = df.Low.rolling(n).min() hi = df.High.rolling(n).max() k = 100 * (df.Close-lo) / (hi-lo) d = k.rolling(m).mean() return k, d # calculating RSI (gives the same values as TradingView) # https://stackoverflow.com/questions/20526414/relative-strength-index-in-python-pandas def RSI(series, period=14): delta = series.diff().dropna() ups = delta * 0 downs = ups.copy() ups[delta > 0] = delta[delta > 0] downs[delta < 0] = -delta[delta < 0] ups[ups.index[period-1]] = np.mean( ups[:period] ) #first value is sum of avg gains ups = ups.drop(ups.index[:(period-1)]) downs[downs.index[period-1]] = np.mean( downs[:period] ) #first value is sum of avg losses downs = downs.drop(downs.index[:(period-1)]) rs = ups.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean() / \ downs.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean() return 100 - 100 / (1 + rs) # calculating Stoch RSI (gives the same values as TradingView) # https://www.tradingview.com/wiki/Stochastic_RSI_(STOCH_RSI) def StochRSI(series, period=14, smoothK=3, smoothD=3): # Calculate RSI delta = series.diff().dropna() ups = delta * 0 downs = ups.copy() ups[delta > 0] = delta[delta > 0] downs[delta < 0] = -delta[delta < 0] ups[ups.index[period-1]] = np.mean( ups[:period] ) #first value is sum of avg gains ups = ups.drop(ups.index[:(period-1)]) downs[downs.index[period-1]] = np.mean( downs[:period] ) #first value is sum of avg losses downs = downs.drop(downs.index[:(period-1)]) rs = ups.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean() / \ downs.ewm(com=period-1,min_periods=0,adjust=False,ignore_na=False).mean() rsi = 100 - 100 / (1 + rs) # Calculate StochRSI stochrsi = (rsi - rsi.rolling(period).min()) / (rsi.rolling(period).max() - rsi.rolling(period).min()) stochrsi_K = stochrsi.rolling(smoothK).mean() stochrsi_D = stochrsi_K.rolling(smoothD).mean() return stochrsi, stochrsi_K, stochrsi_D
[ "numpy.mean" ]
[((2422, 2443), 'numpy.mean', 'np.mean', (['ups[:period]'], {}), '(ups[:period])\n', (2429, 2443), True, 'import numpy as np\n'), ((2557, 2580), 'numpy.mean', 'np.mean', (['downs[:period]'], {}), '(downs[:period])\n', (2564, 2580), True, 'import numpy as np\n'), ((3259, 3280), 'numpy.mean', 'np.mean', (['ups[:period]'], {}), '(ups[:period])\n', (3266, 3280), True, 'import numpy as np\n'), ((3394, 3417), 'numpy.mean', 'np.mean', (['downs[:period]'], {}), '(downs[:period])\n', (3401, 3417), True, 'import numpy as np\n')]
import os import torch.utils.data as data import data.pre_proc as pre_proc import cv2 from scipy.io import loadmat import numpy as np import json import pydicom import torch from PIL import Image from torchvision import transforms import data.custom_transforms as tr def rearrange_pts(pts): boxes = [] for k in range(0, len(pts), 4): pts_4 = pts[k:k+4,:] x_inds = np.argsort(pts_4[:, 0]) pt_l = np.asarray(pts_4[x_inds[:2], :]) pt_r = np.asarray(pts_4[x_inds[2:], :]) y_inds_l = np.argsort(pt_l[:,1]) y_inds_r = np.argsort(pt_r[:,1]) tl = pt_l[y_inds_l[0], :] bl = pt_l[y_inds_l[1], :] tr = pt_r[y_inds_r[0], :] br = pt_r[y_inds_r[1], :] # boxes.append([tl, tr, bl, br]) boxes.append(tl) boxes.append(tr) boxes.append(bl) boxes.append(br) return np.asarray(boxes, np.float32) class BaseDataset_ap(data.Dataset): def __init__(self, data_dir, phase, input_h=None, input_w=None, down_ratio=4, ): super(BaseDataset_ap, self).__init__() self.data_dir = data_dir self.phase = phase self.input_h = input_h self.input_w = input_w self.down_ratio = down_ratio self.class_name = ['__background__', 'cell'] self.num_classes = 68 # self.img_dir = os.path.join(data_dir, 'data', self.phase) # self.img_ids = sorted(os.listdir(self.img_dir)) # self.img_dir = json.load(os.path.join(data_dir,'split_'+self.phase+'.json') # self.img_ids,self.img_dir = self.get_data(data_dir,phase) self.patient_ids, self.patient_dir = self.get_data(data_dir,phase) self.shunxu = self.get_shunxu() def get_data(self, data_dir,phase): patient_ids = [] patient_dir = [] patient_list = os.listdir(data_dir) for file_name in patient_list: patient_id = file_name.split('_')[0] ap_file = os.path.join(data_dir, file_name, patient_id+'_PRE_AP.dcm') bending_l = os.path.join(data_dir, file_name, patient_id+'_BL.dcm') bending_r = os.path.join(data_dir, file_name, patient_id+'_BR.dcm') lat_file = os.path.join(data_dir, file_name, patient_id+'_PRE_LAT.dcm') patient = {'ap':ap_file, 'bending_l':bending_l, 'bending_r':bending_r, 'lat':lat_file} patient_dir.append(patient) patient_ids.append(patient_id) return patient_ids, patient_dir def load_images(self, index): # image = np.load( image,(1,1,3)) # image = cv2.imread(os.path.join(self.img_dir, self.img_ids[index])) images = [] for x in ['ap', 'bending_l', 'bending_r', 'lat']: img_dir = self.patient_dir[index][x] # print(img_dir) image = pydicom.read_file(img_dir) image = image.pixel_array image = self.normalization(image) # print(image.shape) # image = np.expand_dims(image, 2) # image = np.tile(image,(1,1,3)) images.append(image) return images def normalization(self,data): _range = np.max(data) - np.min(data) return (data - np.min(data)) / _range def load_gt_pts(self, annopath): # points = np.load(annopath) # pts = [] # for i in range(68): # pts.append([points[2*i], points[2*i+1]]) # # pts = loadmat(annopath)['p2'] # num x 2 (x,y) # pts = np.array(pts) # pts = rearrange_pts(pts) with open(os.path.join(self.data_dir, annopath), 'r') as f: label = json.load(f) try: points = label['Image Data'][self.field]['points'] except: print(label['Patient Info']) print(annopath) points = list(eval(points)) offset = eval(label ['Image Data'][self.field]['pos']) points = [(point[0]+offset[0], point[1]+offset[1]) for point in points] index = eval(label['Image Data'][self.field]['measureData']['landmarkIndexes']) points = self.getlabels(points,index) pts = [] for i in range(68): pts.append([points[2*i], points[2*i+1]]) # pts = loadmat(annopath)['p2'] # num x 2 (x,y) pts = np.array(pts) pts = rearrange_pts(pts) return pts def load_annoFolder(self, img_id): return os.path.join(self.data_dir, 'labels', self.phase, img_id) # return os.path.join(self.data_dir, 'labels', self.phase, img_id+'.mat') def load_annotation(self, index): # img_id = self.img_ids[index] # annoFolder = self.load_annoFolder(img_id) # pts = self.load_gt_pts(annoFolder) annoFolder = self.img_dir[index]['json'] pts = self.load_gt_pts(annoFolder) return pts def __getitem__(self, index): patient_id = self.patient_ids[index] images = self.load_images(index) out_images = [] for image in images: # print(image.shape) out_image = pre_proc.processing_test(image=image, input_h=self.input_h, input_w=self.input_w) out_images.append(out_image) out_images = torch.stack(out_images) return {'images': out_images, 'patient_id': patient_id} def __len__(self): return len(self.patient_ids) def get_shunxu(self): jizhui = ['T', 'L'] weizhi = ['SupAnt','SupPost','InfAnt','InfPost'] shunxu = {} num = 0 for i in range(12): for s in weizhi: index = 'T' + str(i+1) + s shunxu[index] = num num = num + 1 for i in range(5): for s in weizhi: index = 'L' + str(i+1) + s shunxu[index] = num num = num + 1 shunxu['S1SupAnt'] = num num = num + 1 shunxu['S1SupPost'] = num num = num + 1 return shunxu def getlabels(self, points,index): ans = [] for (key, value) in self.shunxu.items(): i = index[key] ans.append(points[i][0]) ans.append(points[i][1]) return ans class BaseDataset_lat(data.Dataset): def __init__(self, data_dir, phase, input_h=None, input_w=None, down_ratio=4): super(BaseDataset_lat, self).__init__() self.data_dir = data_dir self.phase = phase self.input_h = input_h self.input_w = input_w self.down_ratio = down_ratio self.class_name = ['__background__', 'cell'] self.num_classes = 68 # self.img_dir = os.path.join(data_dir, 'data', self.phase) # self.img_ids = sorted(os.listdir(self.img_dir)) # self.img_dir = json.load(os.path.join(data_dir,'split_'+self.phase+'.json') # self.img_ids,self.img_dir = self.get_data(data_dir,phase) self.patient_ids, self.patient_dir = self.get_data(data_dir,phase) self.shunxu = self.get_shunxu() def get_data(self, data_dir,phase): # if phase=='train': # with open(os.path.join(data_dir,'split_train.json'),'r') as f: # split = json.load(f) # else: # with open(os.path.join(data_dir,'split_test.json'),'r') as f: # split = json.load(f) patient_ids = [] patient_dir = [] # for patient in split: # if patient['ap'] and patient['bending_l'] and patient['bending_r'] and patient['lat']: # patient_dir.append(patient) # patient_ids.append(patient['id']) patient_list = os.listdir(data_dir) for file_name in patient_list: patient_id = file_name.split('_')[0] lat_file = os.path.join(data_dir, file_name, patient_id+'_PRE_LAT.dcm') patient_dir.append(lat_file) patient_ids.append(patient_id) return patient_ids, patient_dir # return patient_ids, patient_dir def load_images(self, index): # image = np.load( image,(1,1,3)) # image = cv2.imread(os.path.join(self.img_dir, self.img_ids[index])) image = pydicom.read_file(self.patient_dir[index]) image = image.pixel_array # print(image.shape) image = self.normalization(image) # image = np.expand_dims(image, 2) # image = np.tile(image,(1,1,3)) return image def normalization(self,data): _range = np.max(data) - np.min(data) return (data - np.min(data)) / _range def load_gt_pts(self, annopath): # points = np.load(annopath) # pts = [] # for i in range(68): # pts.append([points[2*i], points[2*i+1]]) # # pts = loadmat(annopath)['p2'] # num x 2 (x,y) # pts = np.array(pts) # pts = rearrange_pts(pts) with open(os.path.join(self.data_dir, annopath), 'r') as f: label = json.load(f) try: points = label['Image Data'][self.field]['points'] except: print(label['Patient Info']) print(annopath) points = list(eval(points)) offset = eval(label ['Image Data'][self.field]['pos']) points = [(point[0]+offset[0], point[1]+offset[1]) for point in points] index = eval(label['Image Data'][self.field]['measureData']['landmarkIndexes']) points = self.getlabels(points,index) pts = [] for i in range(68): pts.append([points[2*i], points[2*i+1]]) # pts = loadmat(annopath)['p2'] # num x 2 (x,y) pts = np.array(pts) pts = rearrange_pts(pts) return pts def load_annoFolder(self, img_id): return os.path.join(self.data_dir, 'labels', self.phase, img_id) # return os.path.join(self.data_dir, 'labels', self.phase, img_id+'.mat') def load_annotation(self, index): # img_id = self.img_ids[index] # annoFolder = self.load_annoFolder(img_id) # pts = self.load_gt_pts(annoFolder) annoFolder = self.img_dir[index]['json'] pts = self.load_gt_pts(annoFolder) return pts def __getitem__(self, index): patient_id = self.patient_ids[index] image = self.load_images(index) # print(image) # print(image.shape) # out_images = [] out_image = pre_proc.processing_test(image=image, input_h=self.input_h, input_w=self.input_w) # out_images = torch.stack(out_images) return {'images': out_image, 'patient_id': patient_id} def __len__(self): return len(self.patient_ids) def get_shunxu(self): jizhui = ['T', 'L'] weizhi = ['SupAnt','SupPost','InfAnt','InfPost'] shunxu = {} num = 0 for i in range(12): for s in weizhi: index = 'T' + str(i+1) + s shunxu[index] = num num = num + 1 for i in range(5): for s in weizhi: index = 'L' + str(i+1) + s shunxu[index] = num num = num + 1 shunxu['S1SupAnt'] = num num = num + 1 shunxu['S1SupPost'] = num num = num + 1 return shunxu def getlabels(self, points,index): ans = [] for (key, value) in self.shunxu.items(): i = index[key] ans.append(points[i][0]) ans.append(points[i][1]) return ans class BaseDataset_csvl(data.Dataset): def __init__(self, data_dir, phase, input_h=None, input_w=None, down_ratio=4): super(BaseDataset_csvl, self).__init__() self.data_dir = data_dir self.phase = phase self.input_h = input_h self.input_w = input_w self.down_ratio = down_ratio self.class_name = ['__background__', 'cell'] self.num_classes = 68 # self.img_dir = os.path.join(data_dir, 'data', self.phase) # self.img_ids = sorted(os.listdir(self.img_dir)) # self.img_dir = json.load(os.path.join(data_dir,'split_'+self.phase+'.json') self.patient_ids, self.patient_dir = self.get_data(data_dir,phase) self.shunxu = self.get_shunxu() print('total samples:{}'.format(len(self.patient_dir))) def get_data(self, data_dir,phase): # if phase=='train': # with open(os.path.join(data_dir,'split_train.json'),'r') as f: # split = json.load(f) # else: # with open(os.path.join(data_dir,'split_test.json'),'r') as f: # split = json.load(f) patient_ids = [] patient_dir = [] # for patient in split: # if patient['ap'] and patient['bending_l'] and patient['bending_r'] and patient['lat']: # patient_dir.append(patient) # patient_ids.append(patient['id']) patient_list = os.listdir(data_dir) for file_name in patient_list: patient_id = file_name.split('_')[0] lat_file = os.path.join(data_dir, file_name, patient_id+'_PRE_AP.dcm') patient_dir.append(lat_file) patient_ids.append(patient_id) return patient_ids, patient_dir # def load_image(self, index): # # image = np.load(os.path.join(self.img_dir, self.img_ids[index])) # # image = np.expand_dims(image, 2) # # image = np.tile(image,(1,1,3)) # image = pydicom.read_file(os.path.join(self.data_dir, self.img_dir[index]['dcm'])) # image = image.pixel_array # #直接归一化 # image = self.normalization(image) # image = np.expand_dims(image, 2) # image = np.tile(image,(1,1,3)) # #图像灰度级不统一 # return image def load_image(self, index): # image = np.load( image,(1,1,3)) # image = cv2.imread(os.path.join(self.img_dir, self.img_ids[index])) image = pydicom.read_file(self.patient_dir[index]) image = image.pixel_array # print(image.shape) image = self.normalization(image) # image = np.expand_dims(image, 2) # image = np.tile(image,(1,1,3)) return image def normalization(self,data): _range = np.max(data) - np.min(data) return (data - np.min(data)) / _range def load_gt_pts(self, annopath): # points = np.load(annopath) # pts = [] # for i in range(68): # pts.append([points[2*i], points[2*i+1]]) # # pts = loadmat(annopath)['p2'] # num x 2 (x,y) # pts = np.array(pts) # pts = rearrange_pts(pts) with open(os.path.join(self.data_dir, annopath), 'r') as f: label = json.load(f) try: points = label['Image Data']['Coronal']['points'] except: print(label['Patient Info']) print(annopath) points = list(eval(points)) offset = eval(label ['Image Data']['Coronal']['pos']) points = [(point[0]+offset[0], point[1]+offset[1]) for point in points] index = eval(label['Image Data']['Coronal']['measureData']['landmarkIndexes']) points = self.getlabels(points,index) pts = [] for i in range(68): pts.append([points[2*i], points[2*i+1]]) # pts = loadmat(annopath)['p2'] # num x 2 (x,y) pts = np.array(pts) pts = rearrange_pts(pts) return pts def load_annoFolder(self, img_id): return os.path.join(self.data_dir, 'labels', self.phase, img_id) # return os.path.join(self.data_dir, 'labels', self.phase, img_id+'.mat') def load_annotation(self, index): # img_id = self.img_ids[index] # annoFolder = self.load_annoFolder(img_id) # pts = self.load_gt_pts(annoFolder) annoFolder = self.img_dir[index]['json'] pts = self.load_gt_pts(annoFolder) return pts def transform_val(self, sample): composed_transforms = transforms.Compose([ # tr.FixScaleCrop(crop_size=1000), # tr.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)), tr.ToTensor()]) return composed_transforms(sample) def __getitem__(self, index): patient_id = self.patient_ids[index] image = self.load_image(index) oimage = image * 255 # print(oimage.shape) sample = {'image': Image.fromarray(oimage.astype(np.uint8)), 'label': Image.fromarray(oimage.astype(np.uint8))} sample = self.transform_val(sample) #数据处理只要保证训练集和测试集统一 if self.phase == 'test': images = pre_proc.processing_test(image=image, input_h=self.input_h, input_w=self.input_w) return {'images': images, 'patient_id': patient_id, 'oimage': sample['image']} else: aug_label = False if self.phase == 'train': aug_label = True pts = self.load_annotation(index) # num_obj x h x w #预处理图片和标签 out_image, pts_2 = pre_proc.processing_train(image=image, pts=pts, image_h=self.input_h, #输入的大小 image_w=self.input_w, down_ratio=self.down_ratio, aug_label=aug_label, img_id=img_id) data_dict = pre_proc.generate_ground_truth(image=out_image, pts_2=pts_2, image_h=self.input_h//self.down_ratio, #结果的大小 image_w=self.input_w//self.down_ratio, img_id=img_id) return data_dict def __len__(self): return len(self.patient_ids) def get_shunxu(self): jizhui = ['T', 'L'] weizhi = ['SupAnt','SupPost','InfAnt','InfPost'] shunxu = {} num = 0 for i in range(12): for s in weizhi: index = 'T' + str(i+1) + s shunxu[index] = num num = num + 1 for i in range(5): for s in weizhi: index = 'L' + str(i+1) + s shunxu[index] = num num = num + 1 shunxu['S1SupAnt'] = num num = num + 1 shunxu['S1SupPost'] = num num = num + 1 return shunxu def getlabels(self, points,index): ans = [] for (key, value) in self.shunxu.items(): i = index[key] ans.append(points[i][0]) ans.append(points[i][1]) return ans
[ "data.pre_proc.generate_ground_truth", "os.listdir", "data.custom_transforms.ToTensor", "data.pre_proc.processing_test", "torch.stack", "numpy.asarray", "os.path.join", "numpy.max", "numpy.argsort", "numpy.array", "pydicom.read_file", "data.pre_proc.processing_train", "numpy.min", "json.lo...
[((879, 908), 'numpy.asarray', 'np.asarray', (['boxes', 'np.float32'], {}), '(boxes, np.float32)\n', (889, 908), True, 'import numpy as np\n'), ((389, 412), 'numpy.argsort', 'np.argsort', (['pts_4[:, 0]'], {}), '(pts_4[:, 0])\n', (399, 412), True, 'import numpy as np\n'), ((428, 460), 'numpy.asarray', 'np.asarray', (['pts_4[x_inds[:2], :]'], {}), '(pts_4[x_inds[:2], :])\n', (438, 460), True, 'import numpy as np\n'), ((476, 508), 'numpy.asarray', 'np.asarray', (['pts_4[x_inds[2:], :]'], {}), '(pts_4[x_inds[2:], :])\n', (486, 508), True, 'import numpy as np\n'), ((528, 550), 'numpy.argsort', 'np.argsort', (['pt_l[:, 1]'], {}), '(pt_l[:, 1])\n', (538, 550), True, 'import numpy as np\n'), ((569, 591), 'numpy.argsort', 'np.argsort', (['pt_r[:, 1]'], {}), '(pt_r[:, 1])\n', (579, 591), True, 'import numpy as np\n'), ((1839, 1859), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (1849, 1859), False, 'import os\n'), ((4298, 4311), 'numpy.array', 'np.array', (['pts'], {}), '(pts)\n', (4306, 4311), True, 'import numpy as np\n'), ((4420, 4477), 'os.path.join', 'os.path.join', (['self.data_dir', '"""labels"""', 'self.phase', 'img_id'], {}), "(self.data_dir, 'labels', self.phase, img_id)\n", (4432, 4477), False, 'import os\n'), ((5228, 5251), 'torch.stack', 'torch.stack', (['out_images'], {}), '(out_images)\n', (5239, 5251), False, 'import torch\n'), ((7717, 7737), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (7727, 7737), False, 'import os\n'), ((8287, 8329), 'pydicom.read_file', 'pydicom.read_file', (['self.patient_dir[index]'], {}), '(self.patient_dir[index])\n', (8304, 8329), False, 'import pydicom\n'), ((9720, 9733), 'numpy.array', 'np.array', (['pts'], {}), '(pts)\n', (9728, 9733), True, 'import numpy as np\n'), ((9842, 9899), 'os.path.join', 'os.path.join', (['self.data_dir', '"""labels"""', 'self.phase', 'img_id'], {}), "(self.data_dir, 'labels', self.phase, img_id)\n", (9854, 9899), False, 'import os\n'), ((10489, 10575), 'data.pre_proc.processing_test', 'pre_proc.processing_test', ([], {'image': 'image', 'input_h': 'self.input_h', 'input_w': 'self.input_w'}), '(image=image, input_h=self.input_h, input_w=self.\n input_w)\n', (10513, 10575), True, 'import data.pre_proc as pre_proc\n'), ((13071, 13091), 'os.listdir', 'os.listdir', (['data_dir'], {}), '(data_dir)\n', (13081, 13091), False, 'import os\n'), ((14084, 14126), 'pydicom.read_file', 'pydicom.read_file', (['self.patient_dir[index]'], {}), '(self.patient_dir[index])\n', (14101, 14126), False, 'import pydicom\n'), ((15515, 15528), 'numpy.array', 'np.array', (['pts'], {}), '(pts)\n', (15523, 15528), True, 'import numpy as np\n'), ((15637, 15694), 'os.path.join', 'os.path.join', (['self.data_dir', '"""labels"""', 'self.phase', 'img_id'], {}), "(self.data_dir, 'labels', self.phase, img_id)\n", (15649, 15694), False, 'import os\n'), ((1970, 2031), 'os.path.join', 'os.path.join', (['data_dir', 'file_name', "(patient_id + '_PRE_AP.dcm')"], {}), "(data_dir, file_name, patient_id + '_PRE_AP.dcm')\n", (1982, 2031), False, 'import os\n'), ((2054, 2111), 'os.path.join', 'os.path.join', (['data_dir', 'file_name', "(patient_id + '_BL.dcm')"], {}), "(data_dir, file_name, patient_id + '_BL.dcm')\n", (2066, 2111), False, 'import os\n'), ((2134, 2191), 'os.path.join', 'os.path.join', (['data_dir', 'file_name', "(patient_id + '_BR.dcm')"], {}), "(data_dir, file_name, patient_id + '_BR.dcm')\n", (2146, 2191), False, 'import os\n'), ((2213, 2275), 'os.path.join', 'os.path.join', (['data_dir', 'file_name', "(patient_id + '_PRE_LAT.dcm')"], {}), "(data_dir, file_name, patient_id + '_PRE_LAT.dcm')\n", (2225, 2275), False, 'import os\n'), ((2827, 2853), 'pydicom.read_file', 'pydicom.read_file', (['img_dir'], {}), '(img_dir)\n', (2844, 2853), False, 'import pydicom\n'), ((3174, 3186), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (3180, 3186), True, 'import numpy as np\n'), ((3189, 3201), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (3195, 3201), True, 'import numpy as np\n'), ((3640, 3652), 'json.load', 'json.load', (['f'], {}), '(f)\n', (3649, 3652), False, 'import json\n'), ((5084, 5170), 'data.pre_proc.processing_test', 'pre_proc.processing_test', ([], {'image': 'image', 'input_h': 'self.input_h', 'input_w': 'self.input_w'}), '(image=image, input_h=self.input_h, input_w=self.\n input_w)\n', (5108, 5170), True, 'import data.pre_proc as pre_proc\n'), ((7849, 7911), 'os.path.join', 'os.path.join', (['data_dir', 'file_name', "(patient_id + '_PRE_LAT.dcm')"], {}), "(data_dir, file_name, patient_id + '_PRE_LAT.dcm')\n", (7861, 7911), False, 'import os\n'), ((8596, 8608), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (8602, 8608), True, 'import numpy as np\n'), ((8611, 8623), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (8617, 8623), True, 'import numpy as np\n'), ((9062, 9074), 'json.load', 'json.load', (['f'], {}), '(f)\n', (9071, 9074), False, 'import json\n'), ((13203, 13264), 'os.path.join', 'os.path.join', (['data_dir', 'file_name', "(patient_id + '_PRE_AP.dcm')"], {}), "(data_dir, file_name, patient_id + '_PRE_AP.dcm')\n", (13215, 13264), False, 'import os\n'), ((14393, 14405), 'numpy.max', 'np.max', (['data'], {}), '(data)\n', (14399, 14405), True, 'import numpy as np\n'), ((14408, 14420), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (14414, 14420), True, 'import numpy as np\n'), ((14860, 14872), 'json.load', 'json.load', (['f'], {}), '(f)\n', (14869, 14872), False, 'import json\n'), ((16792, 16878), 'data.pre_proc.processing_test', 'pre_proc.processing_test', ([], {'image': 'image', 'input_h': 'self.input_h', 'input_w': 'self.input_w'}), '(image=image, input_h=self.input_h, input_w=self.\n input_w)\n', (16816, 16878), True, 'import data.pre_proc as pre_proc\n'), ((17199, 17362), 'data.pre_proc.processing_train', 'pre_proc.processing_train', ([], {'image': 'image', 'pts': 'pts', 'image_h': 'self.input_h', 'image_w': 'self.input_w', 'down_ratio': 'self.down_ratio', 'aug_label': 'aug_label', 'img_id': 'img_id'}), '(image=image, pts=pts, image_h=self.input_h,\n image_w=self.input_w, down_ratio=self.down_ratio, aug_label=aug_label,\n img_id=img_id)\n', (17224, 17362), True, 'import data.pre_proc as pre_proc\n'), ((17729, 17895), 'data.pre_proc.generate_ground_truth', 'pre_proc.generate_ground_truth', ([], {'image': 'out_image', 'pts_2': 'pts_2', 'image_h': '(self.input_h // self.down_ratio)', 'image_w': '(self.input_w // self.down_ratio)', 'img_id': 'img_id'}), '(image=out_image, pts_2=pts_2, image_h=self.\n input_h // self.down_ratio, image_w=self.input_w // self.down_ratio,\n img_id=img_id)\n', (17759, 17895), True, 'import data.pre_proc as pre_proc\n'), ((3225, 3237), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (3231, 3237), True, 'import numpy as np\n'), ((3570, 3607), 'os.path.join', 'os.path.join', (['self.data_dir', 'annopath'], {}), '(self.data_dir, annopath)\n', (3582, 3607), False, 'import os\n'), ((8647, 8659), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (8653, 8659), True, 'import numpy as np\n'), ((8992, 9029), 'os.path.join', 'os.path.join', (['self.data_dir', 'annopath'], {}), '(self.data_dir, annopath)\n', (9004, 9029), False, 'import os\n'), ((14444, 14456), 'numpy.min', 'np.min', (['data'], {}), '(data)\n', (14450, 14456), True, 'import numpy as np\n'), ((14790, 14827), 'os.path.join', 'os.path.join', (['self.data_dir', 'annopath'], {}), '(self.data_dir, annopath)\n', (14802, 14827), False, 'import os\n'), ((16297, 16310), 'data.custom_transforms.ToTensor', 'tr.ToTensor', ([], {}), '()\n', (16308, 16310), True, 'import data.custom_transforms as tr\n')]
import numpy as np import dezero from dezero import cuda, utils from dezero.core import Function, Variable, as_variable, as_array # ============================================================================= # Basic functions: sin / cos / tanh / exp / log # ============================================================================= class Sin(Function): def forward(self, x): xp = cuda.get_array_module(x) y = xp.sin(x) return y def backward(self, gy): x, = self.inputs gx = gy * cos(x) return gx def sin(x): return Sin()(x) class Cos(Function): def forward(self, x): xp = cuda.get_array_module(x) y = xp.cos(x) return y def backward(self, gy): x, = self.inputs gx = gy * -sin(x) return gx def cos(x): return Cos()(x) class Tanh(Function): def forward(self, x): xp = cuda.get_array_module(x) y = xp.tanh(x) return y def backward(self, gy): y = self.outputs[0]() gx = gy * (1 - y ** 2) return gx def tanh(x): return Tanh()(x) class Exp(Function): def forward(self, x): xp = cuda.get_array_module(x) y = xp.exp(x) return y def backward(self, gy): y = self.outputs[0]() gx = gy * y return gx def exp(x): return Exp()(x) class Log(Function): def forward(self, x): xp = cuda.get_array_module(x) y = xp.log(x) return y def backward(self, gy): x, = self.inputs gx = gy / x return gx def log(x): return Log()(x) # ============================================================================= # Tensor operations: reshape / transpose / get_item / expand_dims / flatten # ============================================================================= class Reshape(Function): def __init__(self, shape): self.shape = shape def forward(self, x): self.x_shape = x.shape y = x.reshape(self.shape) return y def backward(self, gy): return reshape(gy, self.x_shape) def reshape(x, shape): if x.shape == shape: return as_variable(x) return Reshape(shape)(x) class Transpose(Function): def __init__(self, axes=None): self.axes = axes def forward(self, x): y = x.transpose(self.axes) return y def backward(self, gy): if self.axes is None: return transpose(gy) axes_len = len(self.axes) inv_axes = tuple(np.argsort([ax % axes_len for ax in self.axes])) return transpose(gy, inv_axes) def transpose(x, axes=None): return Transpose(axes)(x) class GetItem(Function): def __init__(self, slices): self.slices = slices def forward(self, x): y = x[self.slices] return y def backward(self, gy): x, = self.inputs f = GetItemGrad(self.slices, x.shape) return f(gy) class GetItemGrad(Function): def __init__(self, slices, in_shape): self.slices = slices self.in_shape = in_shape def forward(self, gy): xp = cuda.get_array_module(gy) gx = xp.zeros(self.in_shape, dtype=gy.dtype) if xp is np: np.add.at(gx, self.slices, gy) else: xp.scatter_add(gx, self.slices, gy) return gx def backward(self, ggx): return get_item(ggx, self.slices) def get_item(x, slices): return GetItem(slices)(x) # ============================================================================= # sum / sum_to / broadcast_to / average / matmul / linear # ============================================================================= class Sum(Function): def __init__(self, axis, keepdims): self.axis = axis self.keepdims = keepdims def forward(self, x): self.x_shape = x.shape y = x.sum(axis=self.axis, keepdims=self.keepdims) return y def backward(self, gy): gy = utils.reshape_sum_backward( gy, self.x_shape, self.axis, self.keepdims) gx = broadcast_to(gy, self.x_shape) return gx def sum(x, axis=None, keepdims=False): return Sum(axis, keepdims)(x) class BroadcastTo(Function): def __init__(self, shape): self.shape = shape def forward(self, x): self.x_shape = x.shape xp = cuda.get_array_module(x) y = xp.broadcast_to(x, self.shape) return y def backward(self, gy): gx = sum_to(gy, self.x_shape) return gx def broadcast_to(x, shape): if x.shape == shape: return as_variable(x) return BroadcastTo(shape)(x) class SumTo(Function): def __init__(self, shape): self.shape = shape def forward(self, x): self.x_shape = x.shape y = utils.sum_to(x, self.shape) return y def backward(self, gy): gx = broadcast_to(gy, self.x_shape) return gx def sum_to(x, shape): if x.shape == shape: return as_variable(x) return SumTo(shape)(x) class MatMul(Function): def forward(self, x, W): y = x.dot(W) return y def backward(self, gy): x, W = self.inputs gx = matmul(gy, W.T) gW = matmul(x.T, gy) return gx, gW def matmul(x, W): return MatMul()(x, W) class Linear(Function): def forward(self, x, W, b): y = x.dot(W) if b is not None: y += b return y def backward(self, gy): x, W, b = self.inputs gb = None if b.data is None else sum_to(gy, b.shape) gx = matmul(gy, W.T) gW = matmul(x.T, gy) return gx, gW, gb def linear(x, W, b=None): return Linear()(x, W, b) def linear_simple(x, W, b=None): x, W = as_variable(x), as_variable(W) t = matmul(x, W) if b is None: return t y = t + b t.data = None return y # ============================================================================= # activation function: sigmoid / relu / softmax / log_softmax / leaky_relu # ============================================================================= def sigmoid_simple(x): x = as_variable(x) y = 1 / (1 + exp(-x)) return y class Sigmoid(Function): def forward(self, x): xp = cuda.get_array_module(x) y = xp.tanh(x * 0.5) * 0.5 + 0.5 return y def backward(self, gy): y = self.outputs[0]() gx = gy * y * (1 - y) return gx def sigmoid(x): return Sigmoid()(x) class ReLU(Function): def forward(self, x): xp = cuda.get_array_module(x) y = xp.maximum(x, 0.0) return y def backward(self, gy): x, = self.inputs mask = x.data > 0 gx = gy * mask return gx def relu(x): return ReLU()(x) def softmax_simple(x, axis=1): x = as_variable(x) y = exp(x) sum_y = sum(y, axis=axis, keepdims=True) return y / sum_y class Softmax(Function): def __init__(self, axis=1): self.axis = axis def forward(self, x): xp = cuda.get_array_module(x) y = x - x.max(axis=self.axis, keepdims=True) y = xp.exp(y) y /= y.sum(axis=self.axis, keepdims=True) return y def backward(self, gy): y = self.outputs[0]() gx = y * gy sumdx = gx.sum(axis=self.axis, keepdims=True) gx -= y * sumdx return gx def softmax(x, axis=1): return Softmax(axis)(x) # ============================================================================= # loss function: mean_squared_error / softmax_cross_entropy / sigmoid_cross_entropy / binary_cross_entropy # ============================================================================= class MeanSquaredError(Function): def forward(self, x0, x1): diff = x0 - x1 y = (diff ** 2).sum() / len(diff) return y def backward(self, gy): x0, x1 = self.inputs diff = x0 - x1 gy = broadcast_to(gy, diff.shape) gx0 = gy * diff * (2. / len(diff)) gx1 = -gx0 return gx0, gx1 def mean_squared_error(x0, x1): return MeanSquaredError()(x0, x1) class SoftmaxCrossEntropy(Function): def forward(self, x, t): N = x.shape[0] log_z = utils.logsumexp(x, axis=1) log_p = x - log_z # ravel flatten multi dim data to one dim data log_p = log_p[np.arange(N), t.ravel()] y = -log_p.sum() / np.float32(N) return y def backward(self, gy): x, t = self.inputs N, CLS_NUM = x.shape gy *= 1/N y = softmax(x) # convert to one-hot # eye => create Identity matrix xp = cuda.get_array_module(t.data) t_one_hot = xp.eye(CLS_NUM, dtype=t.dtype)[t.data] y = (y - t_one_hot) * gy return y def softmax_cross_entropy(x, t): return SoftmaxCrossEntropy()(x, t) def softmax_cross_entropy_simple(x, t): x, t = as_variable(x), as_variable(t) N = x.shape[0] p = softmax_simple(x) p = clip(p, 1e-15, 1.0) log_p = log(p) tlog_p = log_p[np.arange(N), t.data] print("p:{}\nlog_p:{}\ntlog_p:{}".format(p, log_p, tlog_p)) y = 1 - sum(tlog_p) / N return y # ============================================================================= # accuracy / dropout / batch_norm / embed_id # ============================================================================= def accuracy(y, t): y, t = as_variable(y), as_variable(t) pred = y.data.argmax(axis=1).reshape(t.shape) result = (pred == t.data) acc = result.mean() return as_variable(as_array(acc)) def dropout(x, dropout_ratio=0.5): x = as_variable(x) if dezero.Config.train: xp = cuda.get_array_module(x) mask = xp.random.rand(*x.shape) > dropout_ratio scale = xp.array(1.0 - dropout_ratio).astype(x.dtype) y = x*mask/scale return y else: return x # ============================================================================= # max / min / clip # ============================================================================= class Max(Function): def __init__(self, axis=None, keepdims=False): self.axis = axis self.keepdims = keepdims def forward(self, x): y = x.max(axis=self.axis, keepdims=self.keepdims) return y def backward(self, gy): x = self.inputs[0] y = self.outputs[0]() # weakref shape = utils.max_backward_shape(x, self.axis) gy = reshape(gy, shape) y = reshape(y, shape) cond = (x.data == y.data) gy = broadcast_to(gy, cond.shape) return gy * cond class Min(Max): def forward(self, x): y = x.min(axis=self.axis, keepdims=self.keepdims) return y def max(x, axis=None, keepdims=False): return Max(axis, keepdims)(x) def min(x, axis=None, keepdims=False): return Min(axis, keepdims)(x) class Clip(Function): def __init__(self, x_min, x_max): self.x_min = x_min self.x_max = x_max def forward(self, x): xp = cuda.get_array_module(x) y = xp.clip(x, self.x_min, self.x_max) return y def backward(self, gy): x = self.inputs mask = (x.data >= self.x_min) * (x.data <= self.x_max) gx = gy * mask return gx def clip(x, x_min, x_max): return Clip(x_min, x_max)(x) # ============================================================================= # conv2d / col2im / im2col / basic_math # ============================================================================= conv_import = True if conv_import: from dezero.functions_conv import conv2d from dezero.functions_conv import deconv2d from dezero.functions_conv import conv2d_simple from dezero.functions_conv import im2col from dezero.functions_conv import col2im from dezero.functions_conv import pooling_simple # from dezero.functions_conv import pooling # from dezero.functions_conv import average_pooling # from dezero.core import add # from dezero.core import sub # from dezero.core import rsub # from dezero.core import mul # from dezero.core import div # from dezero.core import neg # from dezero.core import pow
[ "dezero.cuda.get_array_module", "numpy.float32", "dezero.core.as_array", "dezero.utils.sum_to", "numpy.argsort", "dezero.utils.logsumexp", "dezero.utils.max_backward_shape", "dezero.core.as_variable", "dezero.utils.reshape_sum_backward", "numpy.add.at", "numpy.arange" ]
[((6225, 6239), 'dezero.core.as_variable', 'as_variable', (['x'], {}), '(x)\n', (6236, 6239), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((6911, 6925), 'dezero.core.as_variable', 'as_variable', (['x'], {}), '(x)\n', (6922, 6925), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((9745, 9759), 'dezero.core.as_variable', 'as_variable', (['x'], {}), '(x)\n', (9756, 9759), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((401, 425), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (422, 425), False, 'from dezero import cuda, utils\n'), ((658, 682), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (679, 682), False, 'from dezero import cuda, utils\n'), ((917, 941), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (938, 941), False, 'from dezero import cuda, utils\n'), ((1188, 1212), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (1209, 1212), False, 'from dezero import cuda, utils\n'), ((1445, 1469), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (1466, 1469), False, 'from dezero import cuda, utils\n'), ((2201, 2215), 'dezero.core.as_variable', 'as_variable', (['x'], {}), '(x)\n', (2212, 2215), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((3170, 3195), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['gy'], {}), '(gy)\n', (3191, 3195), False, 'from dezero import cuda, utils\n'), ((4038, 4108), 'dezero.utils.reshape_sum_backward', 'utils.reshape_sum_backward', (['gy', 'self.x_shape', 'self.axis', 'self.keepdims'], {}), '(gy, self.x_shape, self.axis, self.keepdims)\n', (4064, 4108), False, 'from dezero import cuda, utils\n'), ((4419, 4443), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (4440, 4443), False, 'from dezero import cuda, utils\n'), ((4659, 4673), 'dezero.core.as_variable', 'as_variable', (['x'], {}), '(x)\n', (4670, 4673), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((4860, 4887), 'dezero.utils.sum_to', 'utils.sum_to', (['x', 'self.shape'], {}), '(x, self.shape)\n', (4872, 4887), False, 'from dezero import cuda, utils\n'), ((5060, 5074), 'dezero.core.as_variable', 'as_variable', (['x'], {}), '(x)\n', (5071, 5074), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((5825, 5839), 'dezero.core.as_variable', 'as_variable', (['x'], {}), '(x)\n', (5836, 5839), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((5841, 5855), 'dezero.core.as_variable', 'as_variable', (['W'], {}), '(W)\n', (5852, 5855), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((6345, 6369), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (6366, 6369), False, 'from dezero import cuda, utils\n'), ((6640, 6664), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (6661, 6664), False, 'from dezero import cuda, utils\n'), ((7131, 7155), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (7152, 7155), False, 'from dezero import cuda, utils\n'), ((8331, 8357), 'dezero.utils.logsumexp', 'utils.logsumexp', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (8346, 8357), False, 'from dezero import cuda, utils\n'), ((8754, 8783), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['t.data'], {}), '(t.data)\n', (8775, 8783), False, 'from dezero import cuda, utils\n'), ((9020, 9034), 'dezero.core.as_variable', 'as_variable', (['x'], {}), '(x)\n', (9031, 9034), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((9036, 9050), 'dezero.core.as_variable', 'as_variable', (['t'], {}), '(t)\n', (9047, 9050), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((9527, 9541), 'dezero.core.as_variable', 'as_variable', (['y'], {}), '(y)\n', (9538, 9541), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((9543, 9557), 'dezero.core.as_variable', 'as_variable', (['t'], {}), '(t)\n', (9554, 9557), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((9685, 9698), 'dezero.core.as_array', 'as_array', (['acc'], {}), '(acc)\n', (9693, 9698), False, 'from dezero.core import Function, Variable, as_variable, as_array\n'), ((9802, 9826), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (9823, 9826), False, 'from dezero import cuda, utils\n'), ((10542, 10580), 'dezero.utils.max_backward_shape', 'utils.max_backward_shape', (['x', 'self.axis'], {}), '(x, self.axis)\n', (10566, 10580), False, 'from dezero import cuda, utils\n'), ((11169, 11193), 'dezero.cuda.get_array_module', 'cuda.get_array_module', (['x'], {}), '(x)\n', (11190, 11193), False, 'from dezero import cuda, utils\n'), ((2565, 2614), 'numpy.argsort', 'np.argsort', (['[(ax % axes_len) for ax in self.axes]'], {}), '([(ax % axes_len) for ax in self.axes])\n', (2575, 2614), True, 'import numpy as np\n'), ((3283, 3313), 'numpy.add.at', 'np.add.at', (['gx', 'self.slices', 'gy'], {}), '(gx, self.slices, gy)\n', (3292, 3313), True, 'import numpy as np\n'), ((8513, 8526), 'numpy.float32', 'np.float32', (['N'], {}), '(N)\n', (8523, 8526), True, 'import numpy as np\n'), ((9162, 9174), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (9171, 9174), True, 'import numpy as np\n'), ((8461, 8473), 'numpy.arange', 'np.arange', (['N'], {}), '(N)\n', (8470, 8473), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- from __future__ import division, print_function __all__ = ["TimeSeries"] import numpy as np from itertools import izip from .frame import Frame from ._kpsf import solve, N_INT_TIME class TimeSeries(object): def __init__(self, time, flux_images, ferr_images, quality, **kwargs): # Initialize the frame images. self.time = time self.frames = [] for i, (f, fe) in enumerate(izip(flux_images, ferr_images)): frame = [] if quality[i] == 0: frame = Frame(f, fe, **kwargs) if not np.any(frame.mask): frame = [] self.frames.append(frame) # Save the frame shape. self.shape = self.frames[0].shape if any(f.shape != self.shape for f in self.frames if len(f)): raise ValueError("Frame shape mismatch") # Update the frames to have a coherent time series. self.initialize() def initialize(self): # Traverse the graph and construct the (greedy) best path. ns = min(map(len, filter(len, self.frames))) metric = np.array([1.0, 1.0, 1e-8]) current = None for t, node in enumerate(self.frames): if not len(node): continue if current is None: current = node.coords[:ns] node.coords = current continue # Compute the set of distances between this node and the current # position. r = sum([(node.coords[k][:, None] - current[k][None, :]) ** 2 * metric[i] for i, k in enumerate(("x", "y", "flux"))]) r0 = np.array(r) # Loop over the permutations and greedily choose the best update. rows, cols = np.arange(r.shape[0]), np.arange(r.shape[1]) update = np.nan + np.zeros(ns) while any(np.isnan(update)): row, col = np.unravel_index(np.argmin(r), r.shape) update[cols[col]] = rows[row] r = np.delete(r, row, axis=0) r = np.delete(r, col, axis=1) rows = np.delete(rows, row) cols = np.delete(cols, col) update = np.array(update, dtype=int) # Compute the total cost. MAGIC cost = np.sum(r0[(update, range(ns))]) if cost > 10.0: node.coords = None continue # Update the current locations. current = np.array([node.coords[j] for j in update]) self.frames[t].coords = current # Approximate the frame motion as the motion of the brightest star. self.origin = np.nan + np.zeros((len(self.frames), N_INT_TIME, 2)) for t, node in enumerate(self.frames): if not len(node): continue self.origin[t, None, :] = node.coords["x"][0], node.coords["y"][0] # Find the list of times that were acceptable. self.good_times = np.all(np.isfinite(self.origin), axis=(1, 2)) # Center the motion and compute the mean offsets. self.origin[self.good_times] -= np.mean(self.origin[self.good_times], axis=0) self.origin[np.isnan(self.origin)] = 0.0 self.offsets = np.zeros((ns, 2)) for i in np.arange(len(self.frames))[self.good_times]: cen = self.origin[i, 0] node = self.frames[i] self.offsets[:, 0] += node.coords["x"] - cen[0] self.offsets[:, 1] += node.coords["y"] - cen[1] self.offsets /= np.sum(self.good_times) self.response = np.ones(self.shape, dtype=np.float64) def solve(self, psf, cauchy_strength=1.0, response_strength=100.0, fit_response=1, fit_psf=1): nt = np.sum(self.good_times) ns = len(self.offsets) norm = psf(0.0, 0.0) # Initialize the fluxes and backgrounds. response = np.array(self.response) fluxes = np.empty((nt, ns), dtype=np.float64) background = np.empty(nt, dtype=np.float64) for i, j in enumerate(np.arange(len(self.frames))[self.good_times]): frame = self.frames[j] fluxes[i] = frame.coords["flux"] / norm background[i] = np.median(frame.coords["bkg"]) fluxes[:, :] = np.median(fluxes, axis=0)[None, :] # Pull out pointers to the parameters. psfpars = psf.pars origin = np.ascontiguousarray(self.origin[self.good_times], dtype=np.float64) np.random.seed(123) origin += 1e-5 * np.random.randn(*(origin.shape)) offsets = self.offsets # Run the solver. solve(self, fluxes, origin, offsets, psfpars, background, response, cauchy_strength, response_strength, fit_response, fit_psf) # Update the PSF. psf.pars = psfpars norm = psf(0.0, 0.0) # Update the frames. self.response = response self.origin[self.good_times] = origin for i, j in enumerate(np.arange(len(self.frames))[self.good_times]): frame = self.frames[j] frame.coords["flux"] = fluxes[i] * norm frame.coords["bkg"] = background[i] return self.time[self.good_times], fluxes, background
[ "numpy.mean", "numpy.median", "numpy.ones", "numpy.delete", "numpy.any", "numpy.ascontiguousarray", "numpy.array", "numpy.zeros", "numpy.sum", "numpy.empty", "numpy.random.seed", "itertools.izip", "numpy.isfinite", "numpy.isnan", "numpy.argmin", "numpy.random.randn", "numpy.arange" ]
[((1134, 1161), 'numpy.array', 'np.array', (['[1.0, 1.0, 1e-08]'], {}), '([1.0, 1.0, 1e-08])\n', (1142, 1161), True, 'import numpy as np\n'), ((3179, 3224), 'numpy.mean', 'np.mean', (['self.origin[self.good_times]'], {'axis': '(0)'}), '(self.origin[self.good_times], axis=0)\n', (3186, 3224), True, 'import numpy as np\n'), ((3345, 3362), 'numpy.zeros', 'np.zeros', (['(ns, 2)'], {}), '((ns, 2))\n', (3353, 3362), True, 'import numpy as np\n'), ((3640, 3663), 'numpy.sum', 'np.sum', (['self.good_times'], {}), '(self.good_times)\n', (3646, 3663), True, 'import numpy as np\n'), ((3689, 3726), 'numpy.ones', 'np.ones', (['self.shape'], {'dtype': 'np.float64'}), '(self.shape, dtype=np.float64)\n', (3696, 3726), True, 'import numpy as np\n'), ((3854, 3877), 'numpy.sum', 'np.sum', (['self.good_times'], {}), '(self.good_times)\n', (3860, 3877), True, 'import numpy as np\n'), ((4007, 4030), 'numpy.array', 'np.array', (['self.response'], {}), '(self.response)\n', (4015, 4030), True, 'import numpy as np\n'), ((4048, 4084), 'numpy.empty', 'np.empty', (['(nt, ns)'], {'dtype': 'np.float64'}), '((nt, ns), dtype=np.float64)\n', (4056, 4084), True, 'import numpy as np\n'), ((4106, 4136), 'numpy.empty', 'np.empty', (['nt'], {'dtype': 'np.float64'}), '(nt, dtype=np.float64)\n', (4114, 4136), True, 'import numpy as np\n'), ((4510, 4578), 'numpy.ascontiguousarray', 'np.ascontiguousarray', (['self.origin[self.good_times]'], {'dtype': 'np.float64'}), '(self.origin[self.good_times], dtype=np.float64)\n', (4530, 4578), True, 'import numpy as np\n'), ((4625, 4644), 'numpy.random.seed', 'np.random.seed', (['(123)'], {}), '(123)\n', (4639, 4644), True, 'import numpy as np\n'), ((438, 468), 'itertools.izip', 'izip', (['flux_images', 'ferr_images'], {}), '(flux_images, ferr_images)\n', (442, 468), False, 'from itertools import izip\n'), ((1694, 1705), 'numpy.array', 'np.array', (['r'], {}), '(r)\n', (1702, 1705), True, 'import numpy as np\n'), ((2253, 2280), 'numpy.array', 'np.array', (['update'], {'dtype': 'int'}), '(update, dtype=int)\n', (2261, 2280), True, 'import numpy as np\n'), ((2532, 2574), 'numpy.array', 'np.array', (['[node.coords[j] for j in update]'], {}), '([node.coords[j] for j in update])\n', (2540, 2574), True, 'import numpy as np\n'), ((3041, 3065), 'numpy.isfinite', 'np.isfinite', (['self.origin'], {}), '(self.origin)\n', (3052, 3065), True, 'import numpy as np\n'), ((3293, 3314), 'numpy.isnan', 'np.isnan', (['self.origin'], {}), '(self.origin)\n', (3301, 3314), True, 'import numpy as np\n'), ((4329, 4359), 'numpy.median', 'np.median', (["frame.coords['bkg']"], {}), "(frame.coords['bkg'])\n", (4338, 4359), True, 'import numpy as np\n'), ((4383, 4408), 'numpy.median', 'np.median', (['fluxes'], {'axis': '(0)'}), '(fluxes, axis=0)\n', (4392, 4408), True, 'import numpy as np\n'), ((4670, 4700), 'numpy.random.randn', 'np.random.randn', (['*origin.shape'], {}), '(*origin.shape)\n', (4685, 4700), True, 'import numpy as np\n'), ((1810, 1831), 'numpy.arange', 'np.arange', (['r.shape[0]'], {}), '(r.shape[0])\n', (1819, 1831), True, 'import numpy as np\n'), ((1833, 1854), 'numpy.arange', 'np.arange', (['r.shape[1]'], {}), '(r.shape[1])\n', (1842, 1854), True, 'import numpy as np\n'), ((1885, 1897), 'numpy.zeros', 'np.zeros', (['ns'], {}), '(ns)\n', (1893, 1897), True, 'import numpy as np\n'), ((1920, 1936), 'numpy.isnan', 'np.isnan', (['update'], {}), '(update)\n', (1928, 1936), True, 'import numpy as np\n'), ((2072, 2097), 'numpy.delete', 'np.delete', (['r', 'row'], {'axis': '(0)'}), '(r, row, axis=0)\n', (2081, 2097), True, 'import numpy as np\n'), ((2118, 2143), 'numpy.delete', 'np.delete', (['r', 'col'], {'axis': '(1)'}), '(r, col, axis=1)\n', (2127, 2143), True, 'import numpy as np\n'), ((2167, 2187), 'numpy.delete', 'np.delete', (['rows', 'row'], {}), '(rows, row)\n', (2176, 2187), True, 'import numpy as np\n'), ((2211, 2231), 'numpy.delete', 'np.delete', (['cols', 'col'], {}), '(cols, col)\n', (2220, 2231), True, 'import numpy as np\n'), ((596, 614), 'numpy.any', 'np.any', (['frame.mask'], {}), '(frame.mask)\n', (602, 614), True, 'import numpy as np\n'), ((1983, 1995), 'numpy.argmin', 'np.argmin', (['r'], {}), '(r)\n', (1992, 1995), True, 'import numpy as np\n')]
# AUTOGENERATED! DO NOT EDIT! File to edit: viz.ipynb (unless otherwise specified). __all__ = ['TrianglePlot2D_MPL', 'sorted_eig', 'pca_proj', 'setup_plotly', 'TrianglePlot3D_Plotly', 'plotly_already_setup', 'setup_bokeh', 'TrianglePlot2D_Bokeh', 'CDH_SAMPLE_URLS', 'bokeh_already_setup', 'VizPreds', 'image_and_bars'] # Cell import matplotlib.pyplot as plt import numpy as np import torch import torch.nn.functional as F from numpy import linalg as LA from fastcore.basics import * from fastai.callback.core import Callback from fastai.callback.progress import ProgressCallback from .utils import * from .scrape import * import plotly.graph_objects as go from bokeh.plotting import figure, ColumnDataSource, output_file, show from bokeh.io import output_notebook from bokeh.models import Label, WheelZoomTool from IPython.display import display, HTML from .utils import calc_prob # Cell class TrianglePlot2D_MPL(): "Plot categority predictions for 3 categories - matplotlib style" """ pred: (n,3): probability values of n data points in each of 3 classes targ: (n): target value (0,1,2) for each data point""" def __init__(self, pred, targ=None, labels=['0','1','2'], show_labels=True, show_bounds=True, comment='', **kwargs): store_attr() self.fig = plt.figure(figsize=(5,4)) self.ax = self.fig.add_subplot(111) if show_labels: self.ax.text(-1,0, labels[0], ha='right', va='top', size=14) self.ax.text(1,0, labels[1], size=14, va='top') self.ax.text(0,1, labels[2], va='bottom', ha='center', size=14) if comment != '': self.ax.text(-1.1,1, comment, va='bottom', ha='left', size=14) if show_bounds: # draw lines for decision boundaries, and 'ideal' points self.ax.plot([0,0],[0.333,0], color='black') self.ax.plot([0,.5],[0.333,.5], color='black') self.ax.plot([0,-.5],[0.333,.5], color='black') self.ax.plot(-1,0, marker='o', color='black') self.ax.plot(1,0, marker='o', color='black') self.ax.plot(0,1, marker='o', color='black') eps = 0.02 self.ax.set_xlim(-1-eps,1+eps) self.ax.set_ylim(-eps,1+eps) self.ax.set_axis_off() def do_plot(self): colors = self.pred if (self.targ is None) else [ ['red','green','blue'][i] for i in self.targ] self.scat = self.ax.scatter(self.pred.T[1]-self.pred.T[0],self.pred.T[2], facecolors=colors, marker='o') plt.tight_layout() return plt def update(self, pred, targ): self.pred, self.targ = pred, targ return self.do_plot() # Cell def sorted_eig(A): # returns sorted eigenvalues (& their corresponding eignevectors) of A lambdas, vecs = LA.eig(A) # Next line just sorts values & vectors together in order of decreasing eigenvalues lambdas, vecs = zip(*sorted(zip(list(lambdas), list(vecs.T)),key=lambda x: x[0], reverse=True)) return lambdas, np.array(vecs).T # un-doing the list-casting from the previous line def pca_proj(data, dim=3): """Projects data using Principal Component Analysis""" cov = np.cov(data.T) # get covariance matrix lambdas, vecs = sorted_eig(np.array(cov)) # get the eigenvectors W = vecs[:,0:dim] # Grab the 2 most significant dimensions return np.array(data @ W, dtype=np.float32) # Last step of PCA: projection # Cell plotly_already_setup = False def setup_plotly(nbdev=True): """Plotly is already 'setup' on colab, but on regular Jupyter notebooks we need to do a couple things""" global plotly_already_setup if plotly_already_setup: return if nbdev and not on_colab(): # <NAME>' code for normal-Juptyer use with plotly & nbdev import plotly.io as pio pio.renderers.default = 'notebook_connected' js = '<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js" integrity="sha512-c3Nl8+7g4LMSTdrm621y7kf9v3SDPnhxLNhcjFJbKECVnmZHTdo+IRO05sNLTH/D3vA6u1X32ehoLC7WFVdheg==" crossorigin="anonymous"></script>' display(HTML(js)) plotly_already_setup = True class TrianglePlot3D_Plotly(): def __init__(self, pred, # prediction values, probabilities for each class targ=None, # target values, singly enocde (not one-hot), if none, RGB colors are used labels=['x','y','z'], # class labels show_bounds:bool=True, # show inter-class boundaries or not show_labels:bool=True, # point to class ideal poles with arrows & labels show_axes:bool=True, # show axes or not poles_included=False, # tells whether the "pole" points / triangle tips are already included in the beginning of preds margin_t=0, # top margin, plotly's default on Colab is 0, but in jupyter it's 100 nbdev=True, # whether this is for use with nbdev or not; doesn't save full plots in files cmap='jet', # lots of hate against jet but I love it. the purple->yellow colormaps are hard to read IMHO add_poles=True, # add data points for category ideals auto_pca=True, # if you send it more than 3 dimensions, it will PCA to 3. (note only 10 colors defined) **kwargs): "plot a 3d triangle plot using plot.ly." store_attr() setup_plotly() self.dim, self.odim = pred.shape[-1], pred.shape[-1] # save original dimension if self.add_poles and not self.poles_included: self.poles = np.eye(self.dim) self.pred = np.vstack((np.eye(self.dim),self.pred)) self.targ = None if self.targ is None else np.hstack((np.arange(self.dim),self.targ)) self.poles_included = True if auto_pca and self.dim>3: self.pred, self.dim = pca_proj(self.pred), 3 clist = ['red','green','blue','orange','purple','black','brown','cyan','pink','yellow'] self.colors = self.pred if self.targ is None else [ clist[i] for i in self.targ] self.hlabels = None if self.targ is None else [ labels[i] for i in self.targ] # labels for each point self.fig = go.Figure(data=[go.Scatter3d(x=self.pred[:,0], y=self.pred[:,1], z=self.pred[:,2], hovertext=self.hlabels, mode='markers', marker=dict(size=5, opacity=0.6, color=self.colors))]) def do_plot(self, pred=None, targ=None, **kwargs): self.pred = self.pred if pred is None else pred self.targ = self.targ if targ is None else targ assert self.pred is not None, 'Nothing to plot' poles = self.pred[0:self.odim,:] if self.poles_included else np.eye(self.dim) if self.show_labels: self.fig.update_layout(scene = dict( xaxis_title=f'{self.labels[0]} - ness', yaxis_title=f'{self.labels[1]} - ness', zaxis_title=f'{self.labels[2]} - ness', # add little arrows pointing to the "poles" or tips annotations = [ dict(text=self.labels[i], xanchor='center', x=poles[i,0], y=poles[i,1], z=poles[i,2]) for i in range(self.odim)]), width=700, margin=dict(r=20, b=10, l=10, t=10), showlegend=False ) if self.show_bounds and self.odim==3: self.fig.add_trace( go.Scatter3d(mode='lines', x=[0.333,0.5], y=[0.333,0.5], z=[0.333,0], line=dict(color='black', width=5) )) self.fig.add_trace( go.Scatter3d(mode='lines', x=[0.333,0], y=[0.333,0.5], z=[0.333,0.5], line=dict(color='black', width=5) )) self.fig.add_trace( go.Scatter3d(mode='lines', x=[0.333,0.5], y=[0.333,0], z=[0.333,0.5], line=dict(color='black', width=5) )) if (not self.show_axes) or (self.dim != self.odim): # turn off the axis names self.fig.update_layout(scene=dict( xaxis=dict(showticklabels=False, title=''), yaxis=dict(showticklabels=False, title=''), zaxis=dict(showticklabels=False, title=''))) self.fig.update_layout(margin_t=self.margin_t) return self.fig.show() # Cell # cat-dog-horse sample image urls (Warning: these may change & stop working; perhaps switch to Imgur) CDH_SAMPLE_URLS = ['https://upload.wikimedia.org/wikipedia/commons/thumb/4/4f/Felis_silvestris_catus_lying_on_rice_straw.jpg/220px-Felis_silvestris_catus_lying_on_rice_straw.jpg', 'https://upload.wikimedia.org/wikipedia/commons/e/e3/Perfect_Side_View_Of_Black_Labrador_North_East_England.JPG', 'https://upload.wikimedia.org/wikipedia/commons/thumb/e/ea/SilverMorgan.jpg/250px-SilverMorgan.jpg'] bokeh_already_setup = False def setup_bokeh(): """bokeh requires we add jquery manually """ global bokeh_already_setup if not bokeh_already_setup: js = '<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>' display(HTML(js)) bokeh_already_setup = True class TrianglePlot2D_Bokeh(): """This gives a 2d plot with image tooltips when the mouse hovers over a data point.""" # NOTE: in Markdown cells before trying to show the plot, you may need to # force your own JQery import in order for the graph to appear (i.e. if you # get "Uncaught ReferenceError: $ is not defined"). If so, add this: # <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> def __init__(self, pred=None, # (n,3): probability values of n data points in each of 3 classes targ=None, # (n): target value (0,1,2) for each data point labels:list=['0','1','2'], # the class labels show_bounds:bool=True, # show inter-class boundaries or not show_labels:bool=True, # point to class ideal poles with arrows & labels show_axes:bool=True, # show axes or not urls:list=None, # image urls to display upon mouseover (default: stock images) comment:str='', # just a comment to put in the top left corner thumb_height:int=100, # height of thumbnail images (aspect ratio is preserved) ) -> None: # __init__ isn't allowed to return anything (it's a Python thing) store_attr() output_notebook(hide_banner=True) # output_file("toolbar.html") self.colors = ['red','green','blue'] self.TOOLTIPS_HTML = f""" <div> <div> <img src="@imgs" height="{thumb_height}" alt="@imgs" style="float: left; margin: 0px 15px 15px 0px;" border="2" ></img> </div> <div> <span style="font-size: 17px; font-weight: bold;">@desc</span> <span style="font-size: 15px; color: #966;">[$index]</span> </div> <!---commenting-out coordinate values <div> <span style="font-size: 10px; color: #696;">($x, $y)</span> </div> --> </div> """ setup_bokeh() self.clear() return def clear(self): self.p = figure(plot_width=400, plot_height=350, tooltips=self.TOOLTIPS_HTML, title="Mouse over the dots") self.p.toolbar.active_scroll = self.p.select_one(WheelZoomTool) def do_plot(self, pred=None, targ=None, urls=None): self.pred = self.pred if pred is None else pred self.targ = self.targ if targ is None else targ self.urls = self.urls if urls is None else urls assert self.pred is not None, 'Nothing to plot' assert self.targ is not None, 'TODO: right now we require targ' xs, ys = self.pred.T[1] - self.pred.T[0], self.pred.T[2] if self.show_bounds: self.p.line([0, 0],[0.333,0], line_width=2, color='black') self.p.line([0,.5],[0.333,.5], line_width=2, color='black') self.p.line([0,-.5],[0.333,.5], line_width=2, color='black') n = self.pred.shape[0] full_labels = [self.labels[self.targ[i]] for i in range(n)] full_colors = [self.colors[self.targ[i]] for i in range(n)] full_urls = self.urls if self.urls is not None else [CDH_SAMPLE_URLS[self.targ[i]] for i in range(n)] source = ColumnDataSource( data=dict(x=xs, y=ys, desc=full_labels, imgs=full_urls, colors=full_colors ) ) self.p.circle('x', 'y', size=6, line_color='colors', fill_color='colors', source=source) if self.show_labels: self.p.add_layout( Label(x=-1, y=0, text=self.labels[0], text_align='right')) self.p.add_layout( Label(x=1, y=0, text=self.labels[1])) self.p.add_layout( Label(x=0, y=1, text=self.labels[2], text_align='center')) if self.comment != '': self.p.add_layout( Label(x=-1, y=0.95, text=self.comment, text_align='left')) return show(self.p) def update(self, pred, targ): self.pred, self.targ = pred, targ self.clear() return self.do_plot() # Cell class VizPreds(Callback): "Progress-like callback: call the bokeh triangle plot with each batch of training" order = ProgressCallback.order+1 def __init__(self, method='auto', # plotting method must have a .do_plot(preds,targs) gen_urls=True, # if we should generate thumbnail urls (if they don't exist) (2D_Bokeh only) thumb_height=80, # lets you vary the height of image thumbnails (2D_Bokeh only) force_new_urls=False, # if False, keeps whatever thumbnail urls are in learn.dls ): store_attr() self.we_made_the_thumbs = False # so that we don't force-gen new urls a 2nd time after un-freezing def before_fit(self): if self.method=='auto': self.method = TrianglePlot2D_Bokeh if len(self.learn.dls.vocab) <= 3 else TrianglePlot3D_Plotly dv = self.learn.dls.valid # just a shorthand if self.gen_urls and self.method==TrianglePlot2D_Bokeh and (('url_dict' not in dir(dv)) or self.force_new_urls) and not self.we_made_the_thumbs: self.we_made_the_thumbs = True self.learn.dls.valid.url_dict = dict(zip(dv.items, get_thumb_urls(dv.items, size=(self.thumb_height,self.thumb_height)))) def before_epoch(self): if not self.learn.training: self.learn.viz_preds, self.learn.viz_targs = None, None def after_batch(self, **kwargs): if not self.learn.training: with torch.no_grad(): preds, targs = F.softmax(self.learn.pred, dim=1), self.learn.y # pred is logits preds, targs = [x.detach().cpu().numpy().copy() for x in [preds,targs]] self.learn.viz_preds = preds if self.learn.viz_preds is None else np.vstack((self.learn.viz_preds, preds)) self.learn.viz_targs = targs if self.learn.viz_targs is None else np.hstack((self.learn.viz_targs, targs)) def after_epoch(self): if not self.learn.training: print(f"Epoch {self.learn.epoch}: Plotting {len(self.learn.viz_targs)} (= {len(self.learn.dls.valid.items)}?) points:") urls = None if self.method==TrianglePlot2D_Bokeh: dv = self.learn.dls.valid # just a shorthand urls = [dv.url_dict[f] for f in dv.items] if 'url_dict' in dir(dv) else dv.items self.method(self.learn.viz_preds, self.learn.viz_targs, urls=urls, labels=self.dls.vocab, comment=f'Epoch {self.learn.epoch}', thumb_height=self.thumb_height).do_plot() # Cell def image_and_bars(values, labels, image_url, title="Probabilities", height=225, width=500): """Plot an image along with a bar graph""" fig = go.Figure() fig.add_trace( go.Bar(x=labels, y=values, marker_color=["red","green","blue"]) ) fig.add_layout_image( dict( source=image_url, xref="paper", yref="paper", x=-0.2, y=0.5, sizex=1, sizey=1, xanchor="right", yanchor="middle" ) ) # update layout properties fig.update_layout( autosize=False, height=height, width=width, bargap=0.15, bargroupgap=0.1, barmode="stack", hovermode="x", margin=dict(r=20, l=width*0.55, t=30, b=20), yaxis=dict(range=[0,1]), title={ 'text': title, 'y':0.9, 'x':0.76, 'xanchor': 'center', 'yanchor': 'bottom'} ) return fig
[ "plotly.graph_objects.Bar", "numpy.eye", "numpy.linalg.eig", "bokeh.plotting.figure", "bokeh.plotting.show", "bokeh.models.Label", "numpy.hstack", "bokeh.io.output_notebook", "numpy.array", "matplotlib.pyplot.figure", "plotly.graph_objects.Figure", "numpy.vstack", "matplotlib.pyplot.tight_la...
[((2785, 2794), 'numpy.linalg.eig', 'LA.eig', (['A'], {}), '(A)\n', (2791, 2794), True, 'from numpy import linalg as LA\n'), ((3170, 3184), 'numpy.cov', 'np.cov', (['data.T'], {}), '(data.T)\n', (3176, 3184), True, 'import numpy as np\n'), ((3376, 3412), 'numpy.array', 'np.array', (['(data @ W)'], {'dtype': 'np.float32'}), '(data @ W, dtype=np.float32)\n', (3384, 3412), True, 'import numpy as np\n'), ((15944, 15955), 'plotly.graph_objects.Figure', 'go.Figure', ([], {}), '()\n', (15953, 15955), True, 'import plotly.graph_objects as go\n'), ((1315, 1341), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(5, 4)'}), '(figsize=(5, 4))\n', (1325, 1341), True, 'import matplotlib.pyplot as plt\n'), ((2521, 2539), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2537, 2539), True, 'import matplotlib.pyplot as plt\n'), ((3242, 3255), 'numpy.array', 'np.array', (['cov'], {}), '(cov)\n', (3250, 3255), True, 'import numpy as np\n'), ((10416, 10449), 'bokeh.io.output_notebook', 'output_notebook', ([], {'hide_banner': '(True)'}), '(hide_banner=True)\n', (10431, 10449), False, 'from bokeh.io import output_notebook\n'), ((11360, 11462), 'bokeh.plotting.figure', 'figure', ([], {'plot_width': '(400)', 'plot_height': '(350)', 'tooltips': 'self.TOOLTIPS_HTML', 'title': '"""Mouse over the dots"""'}), "(plot_width=400, plot_height=350, tooltips=self.TOOLTIPS_HTML, title=\n 'Mouse over the dots')\n", (11366, 11462), False, 'from bokeh.plotting import figure, ColumnDataSource, output_file, show\n'), ((13113, 13125), 'bokeh.plotting.show', 'show', (['self.p'], {}), '(self.p)\n', (13117, 13125), False, 'from bokeh.plotting import figure, ColumnDataSource, output_file, show\n'), ((15975, 16040), 'plotly.graph_objects.Bar', 'go.Bar', ([], {'x': 'labels', 'y': 'values', 'marker_color': "['red', 'green', 'blue']"}), "(x=labels, y=values, marker_color=['red', 'green', 'blue'])\n", (15981, 16040), True, 'import plotly.graph_objects as go\n'), ((3003, 3017), 'numpy.array', 'np.array', (['vecs'], {}), '(vecs)\n', (3011, 3017), True, 'import numpy as np\n'), ((4125, 4133), 'IPython.display.HTML', 'HTML', (['js'], {}), '(js)\n', (4129, 4133), False, 'from IPython.display import display, HTML\n'), ((5649, 5665), 'numpy.eye', 'np.eye', (['self.dim'], {}), '(self.dim)\n', (5655, 5665), True, 'import numpy as np\n'), ((6750, 6766), 'numpy.eye', 'np.eye', (['self.dim'], {}), '(self.dim)\n', (6756, 6766), True, 'import numpy as np\n'), ((8999, 9007), 'IPython.display.HTML', 'HTML', (['js'], {}), '(js)\n', (9003, 9007), False, 'from IPython.display import display, HTML\n'), ((12757, 12814), 'bokeh.models.Label', 'Label', ([], {'x': '(-1)', 'y': '(0)', 'text': 'self.labels[0]', 'text_align': '"""right"""'}), "(x=-1, y=0, text=self.labels[0], text_align='right')\n", (12762, 12814), False, 'from bokeh.models import Label, WheelZoomTool\n'), ((12847, 12883), 'bokeh.models.Label', 'Label', ([], {'x': '(1)', 'y': '(0)', 'text': 'self.labels[1]'}), '(x=1, y=0, text=self.labels[1])\n', (12852, 12883), False, 'from bokeh.models import Label, WheelZoomTool\n'), ((12916, 12973), 'bokeh.models.Label', 'Label', ([], {'x': '(0)', 'y': '(1)', 'text': 'self.labels[2]', 'text_align': '"""center"""'}), "(x=0, y=1, text=self.labels[2], text_align='center')\n", (12921, 12973), False, 'from bokeh.models import Label, WheelZoomTool\n'), ((13038, 13095), 'bokeh.models.Label', 'Label', ([], {'x': '(-1)', 'y': '(0.95)', 'text': 'self.comment', 'text_align': '"""left"""'}), "(x=-1, y=0.95, text=self.comment, text_align='left')\n", (13043, 13095), False, 'from bokeh.models import Label, WheelZoomTool\n'), ((14708, 14723), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (14721, 14723), False, 'import torch\n'), ((5701, 5717), 'numpy.eye', 'np.eye', (['self.dim'], {}), '(self.dim)\n', (5707, 5717), True, 'import numpy as np\n'), ((14756, 14789), 'torch.nn.functional.softmax', 'F.softmax', (['self.learn.pred'], {'dim': '(1)'}), '(self.learn.pred, dim=1)\n', (14765, 14789), True, 'import torch.nn.functional as F\n'), ((14991, 15031), 'numpy.vstack', 'np.vstack', (['(self.learn.viz_preds, preds)'], {}), '((self.learn.viz_preds, preds))\n', (15000, 15031), True, 'import numpy as np\n'), ((15114, 15154), 'numpy.hstack', 'np.hstack', (['(self.learn.viz_targs, targs)'], {}), '((self.learn.viz_targs, targs))\n', (15123, 15154), True, 'import numpy as np\n'), ((5796, 5815), 'numpy.arange', 'np.arange', (['self.dim'], {}), '(self.dim)\n', (5805, 5815), True, 'import numpy as np\n')]
import matplotlib.pyplot as plt import pickle import numpy as np from datetime import datetime from deap.tools.emo import sortNondominated # Functions for handling and analyzing # the population and logbook data def problemName(pop, logbook, stateName): n = pop[0].numberOfQubits NGEN = len(logbook.select("gen")) time = datetime.now() time_str = time.strftime("%d.%m.%y-%H:%M") # ID = time.strftime("%d%m%y%H%M%S")+str(len(pop))+str(NGEN)+str(n) #This needs improving f = open(path+time_str+"-"+str(len(pop))+"pop-"+str(NGEN)+"GEN-"+state_name+".pop", 'wb') # Save a population object and a logbook def save(pop, logbook, path, problemName): f = open(path+problemName+".pop", 'wb') pickle.dump(pop, f) f.close() f = open(path+problemName+".logbook", 'wb') pickle.dump(logbook, f) f.close() print('Saved!') # # Load a population object and corresponding logbook. # # Path contains the name of pop/logbook file # WITHOUT .pop/.logbook extension # def load(path): f = open(path+".pop", 'rb') pop = pickle.load(f) f.close() f = open(path+".logbook", 'rb') logbook = pickle.load(f) f.close() return pop, logbook def loadState(numberOfQubits, index): stateName = str(numberOfQubits)+"QB_state"+str(index) f = open('states/'+str(numberOfQubits)+'_qubits/' + stateName, 'rb') desired_state = pickle.load(f) f.close() return desired_state # Load allowed gateset, fitness and seed from a file def getSetup(path): return 0 # Plot the fitness and size def plotFitSize(logbook, fitness="min", size="avg"): """ Values for fitness and size: "min" plots the minimum "max" plots the maximum "avg" plots the average "std" plots the standard deviation """ gen = logbook.select("gen") fit_mins = logbook.chapters["fitness"].select(fitness) size_avgs = logbook.chapters["size"].select(size) fig, ax1 = plt.subplots() line1 = ax1.plot(gen, fit_mins, "b-", label=f"{fitness} Error") ax1.set_xlabel("Generation") ax1.set_ylabel("Error", color="b") for tl in ax1.get_yticklabels(): tl.set_color("b") plt.ylim(0,1) ax2 = ax1.twinx() line2 = ax2.plot(gen, size_avgs, "r-", label=f"{size} Size") ax2.set_ylabel("Size", color="r") for tl in ax2.get_yticklabels(): tl.set_color("r") lns = line1 + line2 labs = [l.get_label() for l in lns] ax1.legend(lns, labs, loc="center right") plt.show() def plotCircLengths(circs, circs2): sizes1 = np.array([circ.size() for circ in circs]) max_size = sizes1.max() sizes2 = np.array([circ.size() for circ in circs2]) if sizes2.max() > max_size: max_size = sizes2.max() plt.hist(sizes1, bins=max_size, range=(0,max_size), alpha=0.5) plt.hist(sizes2, bins=max_size, range=(0,max_size), alpha=0.5) plt.show() def plotLenFidScatter(directory, problemName, numberOfQubits, stateName, evaluateInd, POPSIZE): name = problemName+".pop" f = open('states/'+str(numberOfQubits)+'_qubits/' + stateName, 'rb') desired_state = pickle.load(f) f.close() data = [] c=[] for i in range(POPSIZE): c.append(i) f = open(directory+name, 'rb') pop = pickle.load(f) f.close() pop[i].trim() circ = pop[i] data.append([circ.toQiskitCircuit().size(), 1 - evaluateInd(circ)[0]]) # plt.scatter(circ.toQiskitCircuit().size(), 1-evaluateInd(circ, desired_state)[0]) data = np.array(data) x = data[:, 0] y = data[:, 1] plt.scatter(x, y, c=c) plt.ylabel("Fidelity") plt.xlabel("Length") #plt.xlim(0,400) plt.ylim(0,1) # plt.title("Evaluation by length (1000 gen)") plt.colorbar() plt.show() def paretoFront(pop): ranks = sortNondominated(pop, len(pop), first_front_only=True) front = ranks[0] data = [] for i in range(len(ranks[0]), len(pop)): pop[i].trim() circ = pop[i] data.append([circ.toQiskitCircuit().size(), 1 - circ.fitness.values[0]]) # plt.scatter(circ.toQiskitCircuit().size(), 1-evaluateInd(circ, desired_state)[0]) data = np.array(data) x = data[:, 0] y = data[:, 1] plt.scatter(x, y, color='b') data = [] data = np.array([[circ.toQiskitCircuit().size(), 1 - circ.fitness.values[0]] for circ in front]) # for i in range(0, len(front)): # pop[i].trim() # circ = pop[i] # data.append([circ.toQiskitCircuit().size(), 1 - circ.fitness.values[0]]) x = data[:, 0] y = data[:, 1] plt.scatter(x, y, color='r') plt.ylabel("Fidelity") plt.xlabel("Length") plt.ylim(0,1) plt.show()
[ "pickle.dump", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.colorbar", "pickle.load", "datetime.datetime.now", "numpy.array", "matplotlib.pyplot.scatter", "matplotlib.pyplot.ylim", "matplotlib.pyplot.subplots", "matplotlib.pyplot.show" ]
[((341, 355), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (353, 355), False, 'from datetime import datetime\n'), ((730, 749), 'pickle.dump', 'pickle.dump', (['pop', 'f'], {}), '(pop, f)\n', (741, 749), False, 'import pickle\n'), ((816, 839), 'pickle.dump', 'pickle.dump', (['logbook', 'f'], {}), '(logbook, f)\n', (827, 839), False, 'import pickle\n'), ((1079, 1093), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1090, 1093), False, 'import pickle\n'), ((1158, 1172), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1169, 1172), False, 'import pickle\n'), ((1405, 1419), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (1416, 1419), False, 'import pickle\n'), ((1971, 1985), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1983, 1985), True, 'import matplotlib.pyplot as plt\n'), ((2181, 2195), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (2189, 2195), True, 'import matplotlib.pyplot as plt\n'), ((2483, 2493), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2491, 2493), True, 'import matplotlib.pyplot as plt\n'), ((2738, 2801), 'matplotlib.pyplot.hist', 'plt.hist', (['sizes1'], {'bins': 'max_size', 'range': '(0, max_size)', 'alpha': '(0.5)'}), '(sizes1, bins=max_size, range=(0, max_size), alpha=0.5)\n', (2746, 2801), True, 'import matplotlib.pyplot as plt\n'), ((2805, 2868), 'matplotlib.pyplot.hist', 'plt.hist', (['sizes2'], {'bins': 'max_size', 'range': '(0, max_size)', 'alpha': '(0.5)'}), '(sizes2, bins=max_size, range=(0, max_size), alpha=0.5)\n', (2813, 2868), True, 'import matplotlib.pyplot as plt\n'), ((2872, 2882), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2880, 2882), True, 'import matplotlib.pyplot as plt\n'), ((3104, 3118), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3115, 3118), False, 'import pickle\n'), ((3522, 3536), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (3530, 3536), True, 'import numpy as np\n'), ((3579, 3601), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'c': 'c'}), '(x, y, c=c)\n', (3590, 3601), True, 'import matplotlib.pyplot as plt\n'), ((3606, 3628), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Fidelity"""'], {}), "('Fidelity')\n", (3616, 3628), True, 'import matplotlib.pyplot as plt\n'), ((3633, 3653), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Length"""'], {}), "('Length')\n", (3643, 3653), True, 'import matplotlib.pyplot as plt\n'), ((3675, 3689), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (3683, 3689), True, 'import matplotlib.pyplot as plt\n'), ((3743, 3757), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (3755, 3757), True, 'import matplotlib.pyplot as plt\n'), ((3762, 3772), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3770, 3772), True, 'import matplotlib.pyplot as plt\n'), ((4156, 4170), 'numpy.array', 'np.array', (['data'], {}), '(data)\n', (4164, 4170), True, 'import numpy as np\n'), ((4207, 4235), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'color': '"""b"""'}), "(x, y, color='b')\n", (4218, 4235), True, 'import matplotlib.pyplot as plt\n'), ((4540, 4568), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x', 'y'], {'color': '"""r"""'}), "(x, y, color='r')\n", (4551, 4568), True, 'import matplotlib.pyplot as plt\n'), ((4571, 4593), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Fidelity"""'], {}), "('Fidelity')\n", (4581, 4593), True, 'import matplotlib.pyplot as plt\n'), ((4596, 4616), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Length"""'], {}), "('Length')\n", (4606, 4616), True, 'import matplotlib.pyplot as plt\n'), ((4619, 4633), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1)'], {}), '(0, 1)\n', (4627, 4633), True, 'import matplotlib.pyplot as plt\n'), ((4635, 4645), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4643, 4645), True, 'import matplotlib.pyplot as plt\n'), ((3259, 3273), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (3270, 3273), False, 'import pickle\n')]
""" DEPRECATED: please use MultiModeSystem instead. Driven Single Mode Linear System """ from typing import Dict, Any import numpy as np import warnings from quantumnetworks.systems.base import SystemSolver class SingleModeSystem(SystemSolver): def __init__(self, params: Dict[str, Any], A_in=None) -> None: """ Arguments: A_in (function): takes in time t and returns np.ndarray """ warnings.warn( "Please use MultiModeSystem instead.", DeprecationWarning, stacklevel=2 ) super().__init__(params) self._A = None self._B = None self.A_in = A_in if A_in else lambda t: 0 def _param_validation(self): super()._param_validation() if "omega_a" not in self.params: self.params["omega_a"] = 2 * np.pi * 1 # 2pi * GHz if "kappa_a" not in self.params: self.params["kappa_a"] = 2 * np.pi * 0.001 # 2pi * GHz if "gamma_a" not in self.params: self.params["gamma_a"] = 2 * np.pi * 0.002 # 2pi * GHz if "kerr_a" not in self.params: self.params["kerr_a"] = 2 * np.pi * 0.001 # 2pi * GHz # Known System Parameters and Load # ================================= @property def A(self): if self._A is None: omega_a = self.params["omega_a"] kappa_a = self.params["kappa_a"] gamma_a = self.params["gamma_a"] A = np.array( [ [-kappa_a / 2 - gamma_a / 2, omega_a], [-omega_a, -kappa_a / 2 - gamma_a / 2], ] ) self._A = A return self._A @property def B(self): if self._B is None: kappa_a = self.params["kappa_a"] B = np.array([[-np.sqrt(kappa_a), 0], [0, -np.sqrt(kappa_a)]]) self._B = B return self._B # Nonlinear # ================================= def f_nl(self, x: np.ndarray): """ Nonlinear part of eq of motion """ K = self.params["kerr_a"] non_linearity = np.zeros_like(x) q = x[0] p = x[1] non_linearity[0] = 2 * K * (q ** 2 + p ** 2) * p non_linearity[1] = -2 * K * (q ** 2 + p ** 2) * q return non_linearity def Jf_nl(self, x: np.ndarray): """ Jacobian of nonlinear part of eq of motion """ K = self.params["kerr_a"] nonlinear_Jf = np.zeros((x.size, x.size)) q = x[0] p = x[1] nonlinear_Jf[0][0] = 4 * K * q * p nonlinear_Jf[0][1] = 2 * K * (q ** 2 + p ** 2) + 4 * K * p ** 2 nonlinear_Jf[1][0] = -2 * K * (q ** 2 + p ** 2) - 4 * K * q ** 2 nonlinear_Jf[1][1] = -4 * K * q * p return nonlinear_Jf # Eval # ================================= def eval_f(self, x: np.ndarray, u: np.ndarray) -> np.ndarray: f = self.A.dot(x) + self.f_nl(x) + u return f def eval_u(self, t: float): A_in = self.A_in(t) A_in_vec = np.array([np.real(A_in), np.imag(A_in)]) u = self.B.dot(A_in_vec) return u def eval_Jf(self, x: np.ndarray, u: np.ndarray) -> np.ndarray: return self.A + self.Jf_nl(x)
[ "numpy.sqrt", "numpy.array", "numpy.zeros", "numpy.real", "warnings.warn", "numpy.zeros_like", "numpy.imag" ]
[((434, 524), 'warnings.warn', 'warnings.warn', (['"""Please use MultiModeSystem instead."""', 'DeprecationWarning'], {'stacklevel': '(2)'}), "('Please use MultiModeSystem instead.', DeprecationWarning,\n stacklevel=2)\n", (447, 524), False, 'import warnings\n'), ((2129, 2145), 'numpy.zeros_like', 'np.zeros_like', (['x'], {}), '(x)\n', (2142, 2145), True, 'import numpy as np\n'), ((2494, 2520), 'numpy.zeros', 'np.zeros', (['(x.size, x.size)'], {}), '((x.size, x.size))\n', (2502, 2520), True, 'import numpy as np\n'), ((1463, 1557), 'numpy.array', 'np.array', (['[[-kappa_a / 2 - gamma_a / 2, omega_a], [-omega_a, -kappa_a / 2 - gamma_a / 2]]'], {}), '([[-kappa_a / 2 - gamma_a / 2, omega_a], [-omega_a, -kappa_a / 2 - \n gamma_a / 2]])\n', (1471, 1557), True, 'import numpy as np\n'), ((3087, 3100), 'numpy.real', 'np.real', (['A_in'], {}), '(A_in)\n', (3094, 3100), True, 'import numpy as np\n'), ((3102, 3115), 'numpy.imag', 'np.imag', (['A_in'], {}), '(A_in)\n', (3109, 3115), True, 'import numpy as np\n'), ((1822, 1838), 'numpy.sqrt', 'np.sqrt', (['kappa_a'], {}), '(kappa_a)\n', (1829, 1838), True, 'import numpy as np\n'), ((1849, 1865), 'numpy.sqrt', 'np.sqrt', (['kappa_a'], {}), '(kappa_a)\n', (1856, 1865), True, 'import numpy as np\n')]
# import SDF_module as sdf #legacy changed in (1/6/2021) import numpy as np import os import sys import matplotlib.pyplot as plt import csv import shutil #Alteration @ 1/6/2021 : Moved the SDF_module code here as i reckon it would be way #slower and more complicated to work with multiple modules and there was no point #to hold the module as it required no more work to be done. def grid_con(Nx,Ny): x = np.linspace(-0.1,1.1,Nx) y = np.linspace(-0.15,0.15,Ny) grid = np.zeros((1,2)) grid =np.meshgrid(x,y) return grid def sdf_map(geometry,grid): #needs refining # The grid is imported as a meshgrid # The geometry is imported as 2D array # The function exports a 2D surface grid try: GRID_SDF = np.empty(grid[0].shape) for ii in range(GRID_SDF.shape[0]): #rows for jj in range(GRID_SDF.shape[1]):#columns k = 1e+10 v = 1 for ll in range(len(geometry)): sdf = np.sqrt((grid[0][ii,jj]-geometry[ll,0])**2+(grid[1][ii,jj]-geometry[ll,1])**2) if sdf < k : k = sdf pos = ll if((grid[0][ii,jj]>=0) & (grid[0][ii,jj]<=1)): if((abs(grid[1][ii,jj]) <= abs(geometry[pos,1]))): #standard geometry v=-1 #multiplier for point in geometry # print((grid[0][ii,jj],grid[1][ii,jj])," point ", geometry[pos,:]) elif((ll > int(len(geometry)/2)) & (grid[1][ii,jj]>=geometry[pos,1]) & (grid[1][ii,jj]<=geometry[pos-int(len(geometry)/2),1])): # close to trailing edge there are some areas where the underside of the airfoil gains positive y-coordinates v=-1 #multiplier for point in geometry # print((grid[0][ii,jj],grid[1][ii,jj])," point ", geometry[pos,:]) GRID_SDF[ii,jj]=k*v # Magnitude assignment to each node return GRID_SDF except: print(len(geometry)) #--------------------------------------------------------------------------------------------------------------------------- def image_generator(geometry,file_name,Pxx,Pxy,directory="",export_csv=False,showplot=False,showcontours = False): """The method image_generator is used to create the image data needed as input for any kind of training and validation attempt. The method uses as inputs the geometry that we want to approximate with SDF and then export it in an image according to the Pxx pixels along the x axis and Pxy pixels along the y axis. The file_name has arguements about the directory where the image would be saved, its name and finally the image type. Preferably the image shall be stored as an png (ie. C:/CustomDir/image_name.png). Optional arguments are the export_csv in order to export image data to csv file, showplot in order to plot the sdf image and showcontours to plot a clear contour plot of the SDF image for troubleshooting.""" #----------------- GRAPHIC GRID CREATION ------------------------ grid = grid_con(Pxx,Pxy) colormap = sdf_map(geometry,grid) if(export_csv): #------ EXPORTING THE IMAGE DATA IN CSV ------------------------ file = open(directory+"image_data.csv",'w') file_writer = csv.writer(file,dialect = "excel",lineterminator = '\n')#=delimiter=',',quotechar='"',quoting=csv.QUOTE_MINIMAL) for ii in range(colormap.shape[0]): file_writer.writerow(colormap[ii,:]) file.close() #------------------------------------------------------------- if(showcontours): fig = plt.figure() plt.plot(geometry[:,0],geometry[:,1],'k*') c_plot=plt.contour(grid[0],grid[1],colormap, 30, cmap='jet') plt.clabel(c_plot, inline=True, fontsize=8) plt.colorbar(); plt.show() fig,ax = plt.subplots() plt.imshow(colormap,extent = [-0.1,1.1,-0.15,0.15], origin = 'lower', cmap = 'jet',aspect='auto') ax.axis("off") # plt.savefig("SDF_test.png",bbox_inches='tight',pad_inches =0) plt.imsave(directory+file_name,colormap,cmap='jet') if(showplot):plt.show() plt.close() def ImageDatabase(_directory,file): """ The generator's purpose is to generate the images needed to train and test the Neural Netwotrk. This program will create a Directory to store the images and give each one of them a unique name.""" #------ BASIC DATA INITIALIZATION -------- GEOM = np.zeros((1,2)) contents = np.empty((1,2)) isOneParsed = False isZeroParsed = False FirstElement= True #-------------------------------------------- i=1 for line in file: if (("variant" in line)|("- EOF -" in line)): #when changing variant it is expected to "soft reset" the #reading algorithm if not("- EOF -" in line): name = int(line.split(".")[1].split('\n')[0]) # hold the variant No. else: name = name+1 if not(FirstElement): #when the next variant start is found call the image_generator() GEOM = np.delete(GEOM,0,0) name = (name-1) image_generator(GEOM,(f"RAE_var.png"),32,32,directory=_directory,showplot=False,showcontours = False) # image_generator(GEOM,(f"RAE_var # {name}.png"),32,32,directory=_directory) print(f"Airfoil variant {name} \'s SDF image has been stored @ {_directory}.") elif(FirstElement): FirstElement=False continue GEOM = np.zeros((1,2)) contents = np.empty((1,2)) isOneParsed = False isZeroParsed = False elif (("#up" in line) | ("#down" in line)): continue else: text = line.split(' ') if(("1.0000" in text[1]) & ~isOneParsed): isOneParsed = True elif(("1.0000" in text[1]) & isOneParsed): continue if(("0.0000" in text[1]) & ~isZeroParsed): isZeroParsed = True elif(("0.0000" in text[1]) & isZeroParsed): continue contents[0,0]=float(text[0]) contents[0,1]=float(text[1].split('\n')[0]) # ie '6.605880231510667e-20\n' -> ['6.605880231510667e-20', ''] GEOM = np.append(GEOM,contents,axis=0) if("__main__"==__name__): # open the file if (len(sys.argv)>=2): filename = sys.argv[1] else: print("Enter the input .geom file:") filename = input() directory = filename.split("/") directory.pop() directory = [f"{directory[i]}/" for i in range(len(directory))] directory = "".join(directory) try: file = open(filename,"r") print("File %s exists." %filename) lines=file.readlines() file.close() except: print("File %s doesnot exist." %filename) ImageDatabase(directory,lines)
[ "matplotlib.pyplot.imshow", "numpy.sqrt", "numpy.delete", "matplotlib.pyplot.imsave", "csv.writer", "matplotlib.pyplot.plot", "matplotlib.pyplot.colorbar", "matplotlib.pyplot.close", "matplotlib.pyplot.contour", "numpy.linspace", "numpy.zeros", "numpy.empty", "matplotlib.pyplot.figure", "n...
[((413, 439), 'numpy.linspace', 'np.linspace', (['(-0.1)', '(1.1)', 'Nx'], {}), '(-0.1, 1.1, Nx)\n', (424, 439), True, 'import numpy as np\n'), ((450, 478), 'numpy.linspace', 'np.linspace', (['(-0.15)', '(0.15)', 'Ny'], {}), '(-0.15, 0.15, Ny)\n', (461, 478), True, 'import numpy as np\n'), ((492, 508), 'numpy.zeros', 'np.zeros', (['(1, 2)'], {}), '((1, 2))\n', (500, 508), True, 'import numpy as np\n'), ((522, 539), 'numpy.meshgrid', 'np.meshgrid', (['x', 'y'], {}), '(x, y)\n', (533, 539), True, 'import numpy as np\n'), ((4255, 4269), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (4267, 4269), True, 'import matplotlib.pyplot as plt\n'), ((4274, 4375), 'matplotlib.pyplot.imshow', 'plt.imshow', (['colormap'], {'extent': '[-0.1, 1.1, -0.15, 0.15]', 'origin': '"""lower"""', 'cmap': '"""jet"""', 'aspect': '"""auto"""'}), "(colormap, extent=[-0.1, 1.1, -0.15, 0.15], origin='lower', cmap=\n 'jet', aspect='auto')\n", (4284, 4375), True, 'import matplotlib.pyplot as plt\n'), ((4483, 4538), 'matplotlib.pyplot.imsave', 'plt.imsave', (['(directory + file_name)', 'colormap'], {'cmap': '"""jet"""'}), "(directory + file_name, colormap, cmap='jet')\n", (4493, 4538), True, 'import matplotlib.pyplot as plt\n'), ((4567, 4578), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (4576, 4578), True, 'import matplotlib.pyplot as plt\n'), ((4896, 4912), 'numpy.zeros', 'np.zeros', (['(1, 2)'], {}), '((1, 2))\n', (4904, 4912), True, 'import numpy as np\n'), ((4927, 4943), 'numpy.empty', 'np.empty', (['(1, 2)'], {}), '((1, 2))\n', (4935, 4943), True, 'import numpy as np\n'), ((781, 804), 'numpy.empty', 'np.empty', (['grid[0].shape'], {}), '(grid[0].shape)\n', (789, 804), True, 'import numpy as np\n'), ((3679, 3733), 'csv.writer', 'csv.writer', (['file'], {'dialect': '"""excel"""', 'lineterminator': '"""\n"""'}), "(file, dialect='excel', lineterminator='\\n')\n", (3689, 3733), False, 'import csv\n'), ((4013, 4025), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4023, 4025), True, 'import matplotlib.pyplot as plt\n'), ((4034, 4080), 'matplotlib.pyplot.plot', 'plt.plot', (['geometry[:, 0]', 'geometry[:, 1]', '"""k*"""'], {}), "(geometry[:, 0], geometry[:, 1], 'k*')\n", (4042, 4080), True, 'import matplotlib.pyplot as plt\n'), ((4092, 4147), 'matplotlib.pyplot.contour', 'plt.contour', (['grid[0]', 'grid[1]', 'colormap', '(30)'], {'cmap': '"""jet"""'}), "(grid[0], grid[1], colormap, 30, cmap='jet')\n", (4103, 4147), True, 'import matplotlib.pyplot as plt\n'), ((4154, 4197), 'matplotlib.pyplot.clabel', 'plt.clabel', (['c_plot'], {'inline': '(True)', 'fontsize': '(8)'}), '(c_plot, inline=True, fontsize=8)\n', (4164, 4197), True, 'import matplotlib.pyplot as plt\n'), ((4206, 4220), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (4218, 4220), True, 'import matplotlib.pyplot as plt\n'), ((4230, 4240), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4238, 4240), True, 'import matplotlib.pyplot as plt\n'), ((4552, 4562), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4560, 4562), True, 'import matplotlib.pyplot as plt\n'), ((6013, 6029), 'numpy.zeros', 'np.zeros', (['(1, 2)'], {}), '((1, 2))\n', (6021, 6029), True, 'import numpy as np\n'), ((6052, 6068), 'numpy.empty', 'np.empty', (['(1, 2)'], {}), '((1, 2))\n', (6060, 6068), True, 'import numpy as np\n'), ((5544, 5565), 'numpy.delete', 'np.delete', (['GEOM', '(0)', '(0)'], {}), '(GEOM, 0, 0)\n', (5553, 5565), True, 'import numpy as np\n'), ((6712, 6745), 'numpy.append', 'np.append', (['GEOM', 'contents'], {'axis': '(0)'}), '(GEOM, contents, axis=0)\n', (6721, 6745), True, 'import numpy as np\n'), ((1097, 1193), 'numpy.sqrt', 'np.sqrt', (['((grid[0][ii, jj] - geometry[ll, 0]) ** 2 + (grid[1][ii, jj] - geometry[ll,\n 1]) ** 2)'], {}), '((grid[0][ii, jj] - geometry[ll, 0]) ** 2 + (grid[1][ii, jj] -\n geometry[ll, 1]) ** 2)\n', (1104, 1193), True, 'import numpy as np\n')]
import numpy as np from scipy import optimize __author__ = '<NAME> & <NAME>' class NeuralNetwork(object): """A feedforward neural network that capable of regression or classification. Requires Numpy to run and takes in ndarray inputs. """ # CONSTANTS SUM_OF_SQUARES_TYPE = "Sum of Squares" CROSS_ENTROPY_TYPE = "Cross Entropy" #Variables inputLayerSize = None outputLayerSize = None hiddenLayerSizes = None weight = None def __init__(self, layer_sizes): """Constructor Params: tuple: Floats; First element is the input layer, last element is the output layer, and every other layer acts as an input layer """ # Define each layer self.inputLayerSize = layer_sizes[0] self.outputLayerSize = layer_sizes[len(layer_sizes) - 1] self.hiddenLayerSizes = layer_sizes[1:len(layer_sizes) - 1] # Set each weight depending on the number of each layer being paired self.weight = [] # If there are hidden layers if len(self.hiddenLayerSizes) != 0: # Add random weights from input layer to hidden layer 0 self.weight.append(np.random.randn(self.inputLayerSize, self.hiddenLayerSizes[0])) # For each hidden layer for i in range(len(self.hiddenLayerSizes) - 1): # Add random weights between each hidden layer self.weight.append(np.random.randn(self.hiddenLayerSizes[i], self.hiddenLayerSizes[i + 1])) # Add random weights between the last hidden layer and output layer self.weight.append( np.random.randn(self.hiddenLayerSizes[len(self.hiddenLayerSizes) - 1], self.outputLayerSize)) else: # Add random weights between the input layer and output layer self.weight.append(np.random.randn(self.inputLayerSize, self.outputLayerSize)) def forward(self, input_matrix): """Feeds the input forward through the neural network Returns: ndarray: Output of our inputted matrix that is [n, 10] (n being the # of inputs) """ # Values taken from each set of weights * input summed together self.inputSum = [] # The inputSums inserted into the threshold function (sigmoid) self.threshold = [] # Append each inputSum value matrix self.inputSum.append(np.dot(input_matrix, self.weight[0])) for i in range(len(self.weight) - 1): # Append each A value from the sigmoid(Z) self.threshold.append(self.sigmoid(self.inputSum[i])) self.inputSum.append(np.dot(self.threshold[i], self.weight[i + 1])) y_hat = self.sigmoid(self.inputSum[len(self.inputSum) - 1]) return y_hat @staticmethod def sigmoid(z): """Static Sigmoid Function Params: ndarray: floats Returns: ndarray: floats """ return 1 / (1 + np.exp(-(z.clip(-100, 100)))) def sigmoid_prime(self, z): """Derivative of the Sigmoid Function Params: ndarray: floats Returns: ndarray: floats """ return np.multiply(self.sigmoid(z), (1 - self.sigmoid(z))) @staticmethod def tanh(z): """Static Tanh Function Params: ndarray: floats Returns: ndarray: floats """ return np.tanh(z) @staticmethod def tanh_prime(z): """Static Tanh Derivative Function Params: ndarray: floats Returns: ndarray: floats """ return np.multiply(((2 * np.cosh(z))/(np.cosh(2 * z) + 1)), ((2 * np.cosh(z))/(np.cosh(2 * z) + 1))) def cost_function(self, x, y): """The cost function that compares the expected output with the actual output for training Params: ndarray: Input; Should match [n, InputLayerSize] where n is the number of inputs >= to 1. ndarray: Output; Should match [n, OutputLayerSize] where n is the number of outputs >= to 1. The n value for input and output should be the same. Returns: None: If invalid training data float: Cost of the training data """ y_hat = self.forward(x) if y.shape[0] == x.shape[0]: type = self.cost_function_type(x, y) if type == self.SUM_OF_SQUARES_TYPE: return self._sum_of_squares(y, y_hat) elif type == self.CROSS_ENTROPY_TYPE: return self._cross_entropy(y, y_hat) return None def cost_function_type(self, x, y): if y.shape[1] == 1: return self.SUM_OF_SQUARES_TYPE elif y.shape[1] > 1: return self.CROSS_ENTROPY_TYPE else: return None def _cross_entropy(self, y, y_hat): """A type of cost function used for classification greater than 2. Returns: float: Cost of current neural network. """ return -1 * np.sum(np.multiply(y, self.safe_log(y_hat)) + np.multiply(1 - y, self.safe_log(1 - y_hat))) / y.shape[0] @staticmethod def safe_log(x, min_val=0.0000000001): """A log function used to cap ndarray x when having low or nan elements Returns: ndarray: Natural log of x matrix """ return np.log(x.clip(min=min_val)) @staticmethod def _sum_of_squares(y, y_hat): """A cost function used for regression or binary classification Returns: float: Cost of current neural network. """ return np.sum(np.power(y - y_hat, 2)) / y.shape[0] def cost_function_prime(self, x, y): """The derivative of the cost function Uses the derived cost function to retrieve the gradient for each component Returns: list: ndarray; Returns a list of matricies where each matrix represent a specific component """ y_hat = self.forward(x); delta = [] derived = [] delta.append(np.multiply(-(y-y_hat), self.sigmoid_prime(self.inputSum[len(self.inputSum) - 1]))) derived.append(np.dot(self.threshold[len(self.threshold) - 1].T, delta[len(delta) - 1])) for i in range(2, len(self.inputSum)): delta.append(np.array(np.dot(delta[len(delta) - 1], self.weight[len(self.weight) - i + 1].T)) * np.array(self.sigmoid_prime(self.inputSum[len(self.inputSum) - i]))) derived.append(np.dot(self.threshold[len(self.threshold) - i].T, delta[len(delta) - 1])) delta.append(np.array(np.dot(delta[len(delta) - 1], self.weight[1].T)) * np.array(self.sigmoid_prime(self.inputSum[0]))) derived.append(np.dot(x.T, delta[len(delta) - 1])) return derived def compute_gradients(self, x, y): """Returns the gradients from each layer of computation Returns: ndarray: 1-D array of floats containing the gradient values """ # Obtains the derived costs over each derived weight set derived = self.cost_function_prime(x, y) # Unravels the derived cost for each set of weights and concatenates them all together params = derived[len(derived) - 1].ravel(); # Concatenates the gradients for i in range(len(derived) - 1): params = np.concatenate((params.ravel(), derived[len(derived) - 2 - i].ravel())) return params def get_params(self): """Returns the weights in a 1-D array Returns: ndarray: 1-D array of floats containing the weights. Size of array is [1, n] where n = InputLayerSize * HiddenLayerSize[0] + range(0,lastHiddenLayer - 1) for HiddenLayerSize[i-1] * HiddenLayerSize[i+1] + HiddenLayerSize[lastHiddenLayer] * OutputLayerSize """ params = None for i in range(len(self.weight)): if params is None: params = self.weight[i].ravel() elif len(params.shape) == 1: params = np.concatenate((params.ravel(), self.weight[i].ravel())) else: params = np.concatenate((params.ravel(), self.weight[i].ravel()), axis=1) if len(params.shape) == 2 and params.shape[0] == 1: return params.T return params def set_params(self, params): """Sets the weights of the Neural Network from a 1-D array Params: ndarray: 1-D array of floats that are the weights. Size of array is [1, n] where n = InputLayerSize * HiddenLayerSize[0] + range(0,lastHiddenLayer - 1) for HiddenLayerSize[i-1] * HiddenLayerSize[i+1] + HiddenLayerSize[lastHiddenLayer] * OutputLayerSize """ # Starting position of first set of weights hiddenStart = 0 # Ending position of first set of weights hiddenEnd = self.hiddenLayerSizes[0] * self.inputLayerSize # Sets the first set of weights self.weight[0] = np.reshape(params[hiddenStart:hiddenEnd], (self.inputLayerSize, self.hiddenLayerSizes[0])) # for each hidden layer for layer in range(0, len(self.hiddenLayerSizes) - 1): # new start position is the previous end position hiddenStart = hiddenEnd # set new end position hiddenEnd = hiddenStart + self.hiddenLayerSizes[layer] * self.hiddenLayerSizes[layer + 1] # Sets the set of weights to weight list self.weight[layer + 1] = np.reshape(params[hiddenStart:hiddenEnd], (self.hiddenLayerSizes[layer], self.hiddenLayerSizes[layer + 1])) # Setting the final set of weights to output hiddenStart = hiddenEnd hiddenEnd = hiddenStart + self.hiddenLayerSizes[len(self.hiddenLayerSizes) - 1] * self.outputLayerSize self.weight[len(self.weight) - 1] = np.reshape(params[hiddenStart:hiddenEnd], (self.hiddenLayerSizes[len(self.hiddenLayerSizes) - 1], self.outputLayerSize)) class Trainer(object): def __init__(self, N): """Constructor Params: NeuralNetwork: Sets neural network to be trained. """ self.neural_net = N def cost_function_wrapper(self, params, x, y): """Used to set the parameters of the Neural Network being trained Returns: float: Cost of the current Neural Network ndarray: 1-D array of gradients """ # Sets the parameters self.neural_net.set_params(params) # Gets the cost cost = self.neural_net.cost_function(x, y) # Obtain the derived cost for each derived weights grad = self.neural_net.compute_gradients(x, y) return cost, grad def train(self, x, y): """Trains the Neural Network to fit the training data Uses the training method to minimize the cost function and set the weights of the Neural Network. Params: ndarray: Input value for the Neural Network ndarray: Expected output value from the Neural Network """ # Parameters of weights from the Neural Network params = self.neural_net.get_params() # Options: maximum # of iterations and show information display after minimizing opt = {'maxiter': 200, 'disp': False} # jac: Jacobian (Defines that cost_function_wrapper returns gradients) # BFGS: Uses BFGS method of training and gradient descent # callback: Return values acts as parameter for set_params optimize.minimize(self.cost_function_wrapper, params, jac=True, method='BFGS', args=(x, y), options=opt, callback=self.neural_net.set_params)
[ "numpy.reshape", "numpy.power", "scipy.optimize.minimize", "numpy.tanh", "numpy.dot", "numpy.cosh", "numpy.random.randn" ]
[((3470, 3480), 'numpy.tanh', 'np.tanh', (['z'], {}), '(z)\n', (3477, 3480), True, 'import numpy as np\n'), ((9266, 9361), 'numpy.reshape', 'np.reshape', (['params[hiddenStart:hiddenEnd]', '(self.inputLayerSize, self.hiddenLayerSizes[0])'], {}), '(params[hiddenStart:hiddenEnd], (self.inputLayerSize, self.\n hiddenLayerSizes[0]))\n', (9276, 9361), True, 'import numpy as np\n'), ((11870, 12016), 'scipy.optimize.minimize', 'optimize.minimize', (['self.cost_function_wrapper', 'params'], {'jac': '(True)', 'method': '"""BFGS"""', 'args': '(x, y)', 'options': 'opt', 'callback': 'self.neural_net.set_params'}), "(self.cost_function_wrapper, params, jac=True, method=\n 'BFGS', args=(x, y), options=opt, callback=self.neural_net.set_params)\n", (11887, 12016), False, 'from scipy import optimize\n'), ((2431, 2467), 'numpy.dot', 'np.dot', (['input_matrix', 'self.weight[0]'], {}), '(input_matrix, self.weight[0])\n', (2437, 2467), True, 'import numpy as np\n'), ((9778, 9889), 'numpy.reshape', 'np.reshape', (['params[hiddenStart:hiddenEnd]', '(self.hiddenLayerSizes[layer], self.hiddenLayerSizes[layer + 1])'], {}), '(params[hiddenStart:hiddenEnd], (self.hiddenLayerSizes[layer],\n self.hiddenLayerSizes[layer + 1]))\n', (9788, 9889), True, 'import numpy as np\n'), ((1203, 1265), 'numpy.random.randn', 'np.random.randn', (['self.inputLayerSize', 'self.hiddenLayerSizes[0]'], {}), '(self.inputLayerSize, self.hiddenLayerSizes[0])\n', (1218, 1265), True, 'import numpy as np\n'), ((1875, 1933), 'numpy.random.randn', 'np.random.randn', (['self.inputLayerSize', 'self.outputLayerSize'], {}), '(self.inputLayerSize, self.outputLayerSize)\n', (1890, 1933), True, 'import numpy as np\n'), ((2668, 2713), 'numpy.dot', 'np.dot', (['self.threshold[i]', 'self.weight[i + 1]'], {}), '(self.threshold[i], self.weight[i + 1])\n', (2674, 2713), True, 'import numpy as np\n'), ((5699, 5721), 'numpy.power', 'np.power', (['(y - y_hat)', '(2)'], {}), '(y - y_hat, 2)\n', (5707, 5721), True, 'import numpy as np\n'), ((1461, 1532), 'numpy.random.randn', 'np.random.randn', (['self.hiddenLayerSizes[i]', 'self.hiddenLayerSizes[i + 1]'], {}), '(self.hiddenLayerSizes[i], self.hiddenLayerSizes[i + 1])\n', (1476, 1532), True, 'import numpy as np\n'), ((3702, 3712), 'numpy.cosh', 'np.cosh', (['z'], {}), '(z)\n', (3709, 3712), True, 'import numpy as np\n'), ((3715, 3729), 'numpy.cosh', 'np.cosh', (['(2 * z)'], {}), '(2 * z)\n', (3722, 3729), True, 'import numpy as np\n'), ((3743, 3753), 'numpy.cosh', 'np.cosh', (['z'], {}), '(z)\n', (3750, 3753), True, 'import numpy as np\n'), ((3756, 3770), 'numpy.cosh', 'np.cosh', (['(2 * z)'], {}), '(2 * z)\n', (3763, 3770), True, 'import numpy as np\n')]
# -*- coding: utf-8 -*- """ @author: hkaneko """ import math import sys import numpy as np import pandas as pd import sample_functions from sklearn import tree, metrics from sklearn.ensemble import RandomForestClassifier # RF モデルの構築に使用 from sklearn.model_selection import cross_val_predict method_name = 'dt' # 'dt' or 'rf' max_max_depth = 10 # 木の深さの上限、の最大値 min_samples_leaf = 3 # 葉ごとのサンプル数の最小値 rf_number_of_trees = 300 # RF における決定木の数 rf_x_variables_rates = np.arange(1, 11, dtype=float) / 10 # 1 つの決定木における説明変数の数の割合の候補 fold_number = 2 # N-fold CV の N number_of_test_samples = 50 # テストデータのサンプル数 if method_name != 'dt' and method_name != 'rf': sys.exit('\'{0}\' という異常診断手法はありません。method_name を見直してください。'.format(method_name)) x = pd.read_csv('tep_7.csv', index_col=0) # OCSVM モデルで検出された異常サンプルを positive として目的変数を設定 x = x.iloc[:177, :] y = np.full(x.shape[0], 'negative') y[167:] = 'positive' if method_name == 'dt': # クロスバリデーションによる木の深さの最適化 accuracy_cv = [] max_depthes = [] for max_depth in range(1, max_max_depth): model_in_cv = tree.DecisionTreeClassifier(max_depth=max_depth, min_samples_leaf=min_samples_leaf) estimated_y_in_cv = cross_val_predict(model_in_cv, x, y, cv=fold_number) accuracy_cv.append(metrics.accuracy_score(y, estimated_y_in_cv)) max_depthes.append(max_depth) optimal_max_depth = sample_functions.plot_and_selection_of_hyperparameter(max_depthes, accuracy_cv, 'maximum depth of tree', 'accuracy in CV') print('\nCV で最適化された木の深さ :', optimal_max_depth) # DT model = tree.DecisionTreeClassifier(max_depth=optimal_max_depth, min_samples_leaf=min_samples_leaf) # モデルの宣言 model.fit(x, y) # モデルの構築 # 決定木のモデルを確認するための dot ファイルの作成 with open('tree.dot', 'w') as f: if model.classes_.dtype == 'object': class_names = model.classes_ else: # クラス名が数値のときの対応 class_names = [] for class_name_number in range(0, model.classes_.shape[0]): class_names.append(str(model.classes_[class_name_number])) tree.export_graphviz(model, out_file=f, feature_names=x.columns, class_names=class_names) elif method_name == 'rf': # OOB (Out-Of-Bugs) による説明変数の数の割合の最適化 accuracy_oob = [] for index, x_variables_rate in enumerate(rf_x_variables_rates): print(index + 1, '/', len(rf_x_variables_rates)) model_in_validation = RandomForestClassifier(n_estimators=rf_number_of_trees, max_features=int( max(math.ceil(x.shape[1] * x_variables_rate), 1)), oob_score=True) model_in_validation.fit(x, y) accuracy_oob.append(model_in_validation.oob_score_) optimal_x_variables_rate = sample_functions.plot_and_selection_of_hyperparameter(rf_x_variables_rates, accuracy_oob, 'rate of x-variables', 'accuracy for OOB') print('\nOOB で最適化された説明変数の数の割合 :', optimal_x_variables_rate) # RF model = RandomForestClassifier(n_estimators=rf_number_of_trees, max_features=int(max(math.ceil(x.shape[1] * optimal_x_variables_rate), 1)), oob_score=True) # RF モデルの宣言 model.fit(x, y) # モデルの構築 # 説明変数の重要度 x_importances = pd.DataFrame(model.feature_importances_, index=x.columns, columns=['importance']) x_importances.to_csv('rf_x_importances.csv') # csv ファイルに保存。同じ名前のファイルがあるときは上書きされますので注意してください # トレーニングデータのクラスの推定 estimated_y_train = pd.DataFrame(model.predict(x), index=x.index, columns=[ 'estimated_class']) # トレーニングデータのクラスを推定し、Pandas の DataFrame 型に変換。行の名前・列の名前も設定 estimated_y_train.to_csv('estimated_y_train.csv') # csv ファイルに保存。同じ名前のファイルがあるときは上書きされますので注意してください # トレーニングデータの混同行列 class_types = list(set(y)) # クラスの種類。これで混同行列における縦と横のクラスの順番を定めます class_types.sort(reverse=True) # 並び替え confusion_matrix_train = pd.DataFrame( metrics.confusion_matrix(y, estimated_y_train, labels=class_types), index=class_types, columns=class_types) # 混同行列を作成し、Pandas の DataFrame 型に変換。行の名前・列の名前を定めたクラスの名前として設定 confusion_matrix_train.to_csv('confusion_matrix_train.csv') # csv ファイルに保存。同じ名前のファイルがあるときは上書きされますので注意してください print(confusion_matrix_train) # 混同行列の表示 print('Accuracy for training data :', metrics.accuracy_score(y, estimated_y_train), '\n') # 正解率の表示
[ "math.ceil", "pandas.read_csv", "sklearn.tree.DecisionTreeClassifier", "sample_functions.plot_and_selection_of_hyperparameter", "sklearn.tree.export_graphviz", "pandas.DataFrame", "numpy.full", "sklearn.model_selection.cross_val_predict", "sklearn.metrics.accuracy_score", "numpy.arange", "sklear...
[((776, 813), 'pandas.read_csv', 'pd.read_csv', (['"""tep_7.csv"""'], {'index_col': '(0)'}), "('tep_7.csv', index_col=0)\n", (787, 813), True, 'import pandas as pd\n'), ((886, 917), 'numpy.full', 'np.full', (['x.shape[0]', '"""negative"""'], {}), "(x.shape[0], 'negative')\n", (893, 917), True, 'import numpy as np\n'), ((487, 516), 'numpy.arange', 'np.arange', (['(1)', '(11)'], {'dtype': 'float'}), '(1, 11, dtype=float)\n', (496, 516), True, 'import numpy as np\n'), ((1414, 1540), 'sample_functions.plot_and_selection_of_hyperparameter', 'sample_functions.plot_and_selection_of_hyperparameter', (['max_depthes', 'accuracy_cv', '"""maximum depth of tree"""', '"""accuracy in CV"""'], {}), "(max_depthes,\n accuracy_cv, 'maximum depth of tree', 'accuracy in CV')\n", (1467, 1540), False, 'import sample_functions\n'), ((1691, 1787), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {'max_depth': 'optimal_max_depth', 'min_samples_leaf': 'min_samples_leaf'}), '(max_depth=optimal_max_depth, min_samples_leaf=\n min_samples_leaf)\n', (1718, 1787), False, 'from sklearn import tree, metrics\n'), ((4256, 4322), 'sklearn.metrics.confusion_matrix', 'metrics.confusion_matrix', (['y', 'estimated_y_train'], {'labels': 'class_types'}), '(y, estimated_y_train, labels=class_types)\n', (4280, 4322), False, 'from sklearn import tree, metrics\n'), ((4620, 4664), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y', 'estimated_y_train'], {}), '(y, estimated_y_train)\n', (4642, 4664), False, 'from sklearn import tree, metrics\n'), ((1110, 1198), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {'max_depth': 'max_depth', 'min_samples_leaf': 'min_samples_leaf'}), '(max_depth=max_depth, min_samples_leaf=\n min_samples_leaf)\n', (1137, 1198), False, 'from sklearn import tree, metrics\n'), ((1223, 1275), 'sklearn.model_selection.cross_val_predict', 'cross_val_predict', (['model_in_cv', 'x', 'y'], {'cv': 'fold_number'}), '(model_in_cv, x, y, cv=fold_number)\n', (1240, 1275), False, 'from sklearn.model_selection import cross_val_predict\n'), ((2217, 2310), 'sklearn.tree.export_graphviz', 'tree.export_graphviz', (['model'], {'out_file': 'f', 'feature_names': 'x.columns', 'class_names': 'class_names'}), '(model, out_file=f, feature_names=x.columns,\n class_names=class_names)\n', (2237, 2310), False, 'from sklearn import tree, metrics\n'), ((2843, 2979), 'sample_functions.plot_and_selection_of_hyperparameter', 'sample_functions.plot_and_selection_of_hyperparameter', (['rf_x_variables_rates', 'accuracy_oob', '"""rate of x-variables"""', '"""accuracy for OOB"""'], {}), "(rf_x_variables_rates,\n accuracy_oob, 'rate of x-variables', 'accuracy for OOB')\n", (2896, 2979), False, 'import sample_functions\n'), ((3625, 3711), 'pandas.DataFrame', 'pd.DataFrame', (['model.feature_importances_'], {'index': 'x.columns', 'columns': "['importance']"}), "(model.feature_importances_, index=x.columns, columns=[\n 'importance'])\n", (3637, 3711), True, 'import pandas as pd\n'), ((1304, 1348), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y', 'estimated_y_in_cv'], {}), '(y, estimated_y_in_cv)\n', (1326, 1348), False, 'from sklearn import tree, metrics\n'), ((3435, 3483), 'math.ceil', 'math.ceil', (['(x.shape[1] * optimal_x_variables_rate)'], {}), '(x.shape[1] * optimal_x_variables_rate)\n', (3444, 3483), False, 'import math\n'), ((2648, 2688), 'math.ceil', 'math.ceil', (['(x.shape[1] * x_variables_rate)'], {}), '(x.shape[1] * x_variables_rate)\n', (2657, 2688), False, 'import math\n')]
import numpy as np for i in range(4,11): print(i) validation_score = np.zeros((1,)) data_nn = np.zeros((1,)) data_em = np.zeros((1,)) for j in range(1,13): data = np.genfromtxt(str(i)+"/simple_validation_"+str(j)+".txt", usecols=(0,1)) data_nn = np.append(data_nn, data[:,0]) data_em = np.append(data_em, data[:,1]) data = np.abs(data[:,0]-data[:,1]) validation_score = np.append(validation_score,1-data) validation_score = validation_score[1:] val_mean = validation_score.mean() val_std = 1.96*np.std(validation_score)/len(validation_score)**0.5 print(str(data_nn.mean())+" "+str(data_em.mean())) print("{:.8g} {:.8g}".format(val_mean,val_std))
[ "numpy.append", "numpy.abs", "numpy.zeros", "numpy.std" ]
[((78, 92), 'numpy.zeros', 'np.zeros', (['(1,)'], {}), '((1,))\n', (86, 92), True, 'import numpy as np\n'), ((107, 121), 'numpy.zeros', 'np.zeros', (['(1,)'], {}), '((1,))\n', (115, 121), True, 'import numpy as np\n'), ((136, 150), 'numpy.zeros', 'np.zeros', (['(1,)'], {}), '((1,))\n', (144, 150), True, 'import numpy as np\n'), ((283, 313), 'numpy.append', 'np.append', (['data_nn', 'data[:, 0]'], {}), '(data_nn, data[:, 0])\n', (292, 313), True, 'import numpy as np\n'), ((331, 361), 'numpy.append', 'np.append', (['data_em', 'data[:, 1]'], {}), '(data_em, data[:, 1])\n', (340, 361), True, 'import numpy as np\n'), ((376, 407), 'numpy.abs', 'np.abs', (['(data[:, 0] - data[:, 1])'], {}), '(data[:, 0] - data[:, 1])\n', (382, 407), True, 'import numpy as np\n'), ((431, 468), 'numpy.append', 'np.append', (['validation_score', '(1 - data)'], {}), '(validation_score, 1 - data)\n', (440, 468), True, 'import numpy as np\n'), ((568, 592), 'numpy.std', 'np.std', (['validation_score'], {}), '(validation_score)\n', (574, 592), True, 'import numpy as np\n')]
""" Copyright 2018 Novartis Institutes for BioMedical Research Inc. 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. """ import numpy as np from scipy.spatial.distance import cdist from server import utils def random_sampling(data: np.ndarray, num_samples: int = 20): try: return data[np.random.choice(data.shape[0], size=num_samples, replace=False)] except ValueError: print( "WARNING: too few data points ({}) for sampling {} items".format( data.shape[0], num_samples ) ) return data def dist_sampling( data: np.ndarray, selected: np.ndarray, target: np.ndarray, num_samples: int = 20, dist_metric: str = "euclidean", ): indices = np.where(selected)[0] try: dist = cdist( data[selected], target.reshape((1, target.size)), dist_metric ).flatten() except ValueError: dist = cdist(data[selected], target.reshape((1, target.size))).flatten() dist_sorted_idx = np.argsort(dist) indices_sorted = indices[dist_sorted_idx] N = dist.size # Number of ranges such that at least 10 windows are to be chosen from n = np.floor(np.log2(N / 10)).astype(int) samples_per_round = np.floor(num_samples / n).astype(int) samples_last_round = num_samples - samples_per_round * (n - 1) samples_per_round = [samples_per_round] * (n - 1) + [samples_last_round] # Lets sample from ranges of halfing size. E.g.: the * mark the range # |*|**|****|********| samples = np.zeros(num_samples) start = np.round(N / 2).astype(int) end = N k = 0 for i in np.arange(n): # Randomly sample points from the range samples[k : k + samples_per_round[i]] = random_sampling( indices_sorted[start:end], num_samples=samples_per_round[i] ) end = start start = np.round(start / 2).astype(int) k += samples_per_round[i] return samples def get_seeds( data: np.ndarray, selected: np.ndarray, target: np.ndarray, num_seeds: int = 40, dist_metric: str = "euclidean", ): half = int(num_seeds // 2) other_half = num_seeds - half seeds = np.zeros(num_seeds).astype(int) # First half is sampled in increasing distance to the target seeds[:half] = dist_sampling( data, selected, target, dist_metric=dist_metric, num_samples=half ) # data_no_dist = np.delete(data, seeds[0:half], axis=0) selected[seeds[0:half]] = False # Half of the seeds are sampled randomly seeds[half:] = random_sampling(np.where(selected)[0], num_samples=other_half) # data_no_dist_rnd = np.detele(data, samples[0:half * 2], axis=0) # The other half are sampled spatially randomly # samples[third * 2:] = spatial_sampling( # data_no_dist_rnd, num_samples=third # ) return seeds def seeds_by_dim( data: np.ndarray, src: np.ndarray, metric: str = "euclidean", sdim: int = 4 ): N = data.shape[0] ndim = src.ndim samples = np.empty((sdim * ndim,)).astype(int) for dim in range(ndim): if np.max(data[:, dim]) == 0: print("Skipping meaningless dimension") continue # Remove already sampled points (nr = non-redundant) nr_data = np.delete(data, samples[: dim * sdim], 0) dim_data = nr_data[:, dim].reshape((nr_data.shape[0], 1)) dim_src = src[dim].reshape((1, 1)) reduced_data = np.delete(nr_data, dim, 1) reduced_src = np.delete(src, dim, 0).reshape((1, src.size - 1)) try: dim_dist = cdist(dim_data, dim_src, metric).flatten() reduced_dist = cdist(reduced_data, reduced_src, metric).flatten() except ValueError: dim_dist = cdist(dim_data, dim_src).flatten() reduced_dist = cdist(reduced_data, reduced_src).flatten() max_dim_dist = np.max(dim_dist) n = 25 dim_var = 0 while dim_var < 0.1 and n < N: dim_sample = dim_dist[np.argsort(reduced_dist)[:n]] dim_var = np.max(dim_sample) / max_dim_dist n *= 2 # Random sample dim_sample2 = np.argsort(dim_sample) np.random.randint(sdim, size=dim_sample2.size) print( dim_sample2.shape[0], nr_data.shape[0], max_dim_dist, dim * sdim, (dim + 1) * sdim, dim_sample2.size, ) samples[dim * sdim : (dim + 1) * sdim] = np.random.randint( sdim, size=dim_sample2.size ) def sample_by_dist_density( data: np.ndarray, selected: np.ndarray, dist_to_target: np.ndarray, knn_density: np.ndarray, levels: int = 5, level_sample_size: int = 5, initial_level_size: int = 10, dist_metric: str = "euclidean", ): """Sample by distance and density This sampling strategy does is based on the distance of the encoded windows to the encoded target window and the windows' knn-density. For `levels` number of increasing size it samples iteratively by density and maximum distance to already sampled windows. Essentially this search strategy samples in increases radii. You can think of it like this: | .... .. . . |.. . . |. . .[X] . |. ...| ... . . ...| 2 ↑ 1 ↑ 0 ↑ ↑ 0 ↑ 1 ↑ 3 Where `[X]` is the search target, `.` are windows, and `|` indicate the level boundaries, and `↑` indicates the sampled windows. The boundaries are defined by the number of windows for a certain level. In this examples, the `initial_level_size` is {4}, so the first level consists of the 4 nearest neighbors to the search target. The second level consists of the next 8 nearest neighbors, the third level consists of the next 16 nearest neighbors etc. Within these levels the algorithm iteratively samples the densest windows that are furthest away from the already sampled windows. E.g. In level zero the left sample is selected because it's close to other windows but the second sample is selected because it's far away from the first sample while the other available windows are too close to the already sampled window. Arguments: data {np.ndarray} -- The complete data selected {np.ndarray} -- A subset of the data to be sampled on dist_to_target {np.ndarray} -- Pre-computed distances between each data item (i.e., row in `data`) and the search target in the latent space knn_density {np.ndarray} -- Pre-computed knn-density of every data item (i.e., row in `data`) in the latent space Keyword Arguments: levels {int} -- The number of levels used for sampling. The final number of sampled windows will be `levels` times `levels_sample_size` (default: {5}) level_sample_size {int} -- The number of windows to be sampled per level. (default: {5}) initial_level_size {int} -- The number of windows considered to be the first level for which `level_sample_size` windows are sampled. In every subsequent sampling the size is doubled. (default: {10}) dist_metric {str} -- The distance metric used to determine the distance between already sampled windows and the remaining windows in the level. (default: {"euclidean"}) Returns: {np.ndarray} -- Sampled windows """ sdata = data[selected] selected_idx = np.where(selected)[0] dist_selected = dist_to_target[selected] knn_density_selected = knn_density[selected] rel_wins_idx_sorted_by_dist = np.argsort(dist_selected) all_samples = np.zeros(levels * level_sample_size).astype(np.int) from_size = 0 for l in range(levels): to_size = from_size + initial_level_size * (2 ** l) # Select all windows in an increasing distance from the search target rel_wins_idx = rel_wins_idx_sorted_by_dist[from_size:to_size] selection_mask = np.zeros(rel_wins_idx.size).astype(np.bool) # Get the sorted list of windows by density # Note that density is determined as the average distance of the 5 nearest # neighbors of the window. Hence, the lowest value indicates the highest # density. The absolute minimum is 0, when all 5 nearest neighbors are the same wins_idx_by_knn_density = np.argsort(knn_density_selected[rel_wins_idx]) samples = np.zeros(level_sample_size).astype(np.uint32) - 1 # Sample first window by density only samples[0] = wins_idx_by_knn_density[0] selection_mask[samples[0]] = True for s in range(1, level_sample_size): # Get all the windows in the current level that have not been sampeled yet remaining_wins_idx = rel_wins_idx[~selection_mask] remaining_wins = sdata[remaining_wins_idx] sampled_wins = sdata[samples[:s]] if s == 1: sampled_wins = sampled_wins.reshape((1, -1)) # Get the normalized summed distance of the remaining windows to the # already sampled windows dist = np.sum( utils.normalize(cdist(remaining_wins, sampled_wins, dist_metric)), axis=1, ) # Select the window that is farthest away from the already sampled windows # and is in the most dense areas samples[s] = np.where(~selection_mask)[0][ np.argsort( utils.normalize_simple(np.max(dist) - dist) + utils.normalize_simple(knn_density_selected[remaining_wins_idx]) )[0] ] selection_mask[samples[s]] = True all_samples[l * level_sample_size : (l + 1) * level_sample_size] = rel_wins_idx[ samples ] from_size = to_size return selected_idx[all_samples] def maximize_pairwise_distance( data: np.ndarray, selection: np.ndarray, ranking: np.ndarray, n: int, dist_metric: str = "euclidean", ): subsamples = np.zeros(n).astype(np.uint32) - 1 subselection_mask = np.zeros(selection.size).astype(np.bool) subsamples[0] = selection[0] subselection_mask[0] = True for i in range(1, n): # Get all the windows in the current level that have not been sampeled yet remaining_wins_idx = selection[~subselection_mask] remaining_wins = data[remaining_wins_idx] sampled_wins = data[subsamples[:i]] if i == 1: sampled_wins = sampled_wins.reshape((1, -1)) # Get the normalized summed distance of the remaining windows to the # already sampled windows dist = np.sum( utils.normalize(cdist(remaining_wins, sampled_wins, dist_metric)), axis=1 ) # Select the window that is farthest away from the already sampled windows # and is in the most dense areas rel_idx = np.where(~subselection_mask)[0][ np.argsort( utils.normalize_simple(np.max(dist) - dist) + utils.normalize_simple(ranking[~subselection_mask]) )[0] ] subselection_mask[rel_idx] = True subsamples[i] = selection[rel_idx] return subsamples def sample_by_uncertainty_dist_density( data: np.ndarray, selected: np.ndarray, dist_to_target: np.ndarray, knn_dist: np.ndarray, p_y: np.ndarray, n: int = 10, k: int = 5, knn_dist_weight: float = 0.5, dist_to_target_weight: float = 0.5, dist_metric: str = "euclidean", ): # Select regions indices = np.where(selected)[0] # Convert the class probabilities into probabilities of uncertainty # p = 0: abs(0 - 0.5) * 2 == 1 # p = 0.5: abs(0.5 - 0.5) * 2 == 0 # p = 1: abs(1 - 0.5) * 2 == 1 p_certain = np.abs(p_y[selected] - 0.5) * 2 # Normalize knn-density knn_dist_norm_selected = utils.normalize_simple(knn_dist[selected]) # Weight density: a value of 0.5 downweights the importants by scaling # the relative density closer to 1 knn_dist_norm_selected_weighted = knn_dist_norm_selected * knn_dist_weight + ( 1 - knn_dist_weight ) # Normalize distance to target dist_to_target_norm_selected = utils.normalize_simple(dist_to_target[selected]) dist_to_target_norm_selected_weighted = ( dist_to_target_norm_selected * dist_to_target_weight + (1 - dist_to_target_weight) ) # Combine uncertainty and density uncertain_knn_dist = ( p_certain * knn_dist_norm_selected_weighted * dist_to_target_norm_selected_weighted ) # Sort descending uncertain_knn_dist_sorted_idx = np.argsort(uncertain_knn_dist) # Subsample by maximizing the pairwise distance subsample = maximize_pairwise_distance( data, indices[uncertain_knn_dist_sorted_idx][: n * 5], np.sort(uncertain_knn_dist)[: n * 5], n, ) return subsample
[ "numpy.abs", "server.utils.normalize_simple", "numpy.where", "numpy.delete", "numpy.random.choice", "numpy.floor", "numpy.round", "numpy.sort", "numpy.max", "numpy.argsort", "scipy.spatial.distance.cdist", "numpy.zeros", "numpy.random.randint", "numpy.empty", "numpy.log2", "numpy.arang...
[((1485, 1501), 'numpy.argsort', 'np.argsort', (['dist'], {}), '(dist)\n', (1495, 1501), True, 'import numpy as np\n'), ((2011, 2032), 'numpy.zeros', 'np.zeros', (['num_samples'], {}), '(num_samples)\n', (2019, 2032), True, 'import numpy as np\n'), ((2108, 2120), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (2117, 2120), True, 'import numpy as np\n'), ((8163, 8188), 'numpy.argsort', 'np.argsort', (['dist_selected'], {}), '(dist_selected)\n', (8173, 8188), True, 'import numpy as np\n'), ((12508, 12550), 'server.utils.normalize_simple', 'utils.normalize_simple', (['knn_dist[selected]'], {}), '(knn_dist[selected])\n', (12530, 12550), False, 'from server import utils\n'), ((12853, 12901), 'server.utils.normalize_simple', 'utils.normalize_simple', (['dist_to_target[selected]'], {}), '(dist_to_target[selected])\n', (12875, 12901), False, 'from server import utils\n'), ((13292, 13322), 'numpy.argsort', 'np.argsort', (['uncertain_knn_dist'], {}), '(uncertain_knn_dist)\n', (13302, 13322), True, 'import numpy as np\n'), ((1211, 1229), 'numpy.where', 'np.where', (['selected'], {}), '(selected)\n', (1219, 1229), True, 'import numpy as np\n'), ((3761, 3801), 'numpy.delete', 'np.delete', (['data', 'samples[:dim * sdim]', '(0)'], {}), '(data, samples[:dim * sdim], 0)\n', (3770, 3801), True, 'import numpy as np\n'), ((3936, 3962), 'numpy.delete', 'np.delete', (['nr_data', 'dim', '(1)'], {}), '(nr_data, dim, 1)\n', (3945, 3962), True, 'import numpy as np\n'), ((4372, 4388), 'numpy.max', 'np.max', (['dim_dist'], {}), '(dim_dist)\n', (4378, 4388), True, 'import numpy as np\n'), ((4650, 4672), 'numpy.argsort', 'np.argsort', (['dim_sample'], {}), '(dim_sample)\n', (4660, 4672), True, 'import numpy as np\n'), ((4681, 4727), 'numpy.random.randint', 'np.random.randint', (['sdim'], {'size': 'dim_sample2.size'}), '(sdim, size=dim_sample2.size)\n', (4698, 4727), True, 'import numpy as np\n'), ((4978, 5024), 'numpy.random.randint', 'np.random.randint', (['sdim'], {'size': 'dim_sample2.size'}), '(sdim, size=dim_sample2.size)\n', (4995, 5024), True, 'import numpy as np\n'), ((8011, 8029), 'numpy.where', 'np.where', (['selected'], {}), '(selected)\n', (8019, 8029), True, 'import numpy as np\n'), ((8924, 8970), 'numpy.argsort', 'np.argsort', (['knn_density_selected[rel_wins_idx]'], {}), '(knn_density_selected[rel_wins_idx])\n', (8934, 8970), True, 'import numpy as np\n'), ((12190, 12208), 'numpy.where', 'np.where', (['selected'], {}), '(selected)\n', (12198, 12208), True, 'import numpy as np\n'), ((12418, 12445), 'numpy.abs', 'np.abs', (['(p_y[selected] - 0.5)'], {}), '(p_y[selected] - 0.5)\n', (12424, 12445), True, 'import numpy as np\n'), ((769, 833), 'numpy.random.choice', 'np.random.choice', (['data.shape[0]'], {'size': 'num_samples', 'replace': '(False)'}), '(data.shape[0], size=num_samples, replace=False)\n', (785, 833), True, 'import numpy as np\n'), ((1713, 1738), 'numpy.floor', 'np.floor', (['(num_samples / n)'], {}), '(num_samples / n)\n', (1721, 1738), True, 'import numpy as np\n'), ((2045, 2060), 'numpy.round', 'np.round', (['(N / 2)'], {}), '(N / 2)\n', (2053, 2060), True, 'import numpy as np\n'), ((2669, 2688), 'numpy.zeros', 'np.zeros', (['num_seeds'], {}), '(num_seeds)\n', (2677, 2688), True, 'import numpy as np\n'), ((3058, 3076), 'numpy.where', 'np.where', (['selected'], {}), '(selected)\n', (3066, 3076), True, 'import numpy as np\n'), ((3504, 3528), 'numpy.empty', 'np.empty', (['(sdim * ndim,)'], {}), '((sdim * ndim,))\n', (3512, 3528), True, 'import numpy as np\n'), ((3581, 3601), 'numpy.max', 'np.max', (['data[:, dim]'], {}), '(data[:, dim])\n', (3587, 3601), True, 'import numpy as np\n'), ((8208, 8244), 'numpy.zeros', 'np.zeros', (['(levels * level_sample_size)'], {}), '(levels * level_sample_size)\n', (8216, 8244), True, 'import numpy as np\n'), ((10697, 10721), 'numpy.zeros', 'np.zeros', (['selection.size'], {}), '(selection.size)\n', (10705, 10721), True, 'import numpy as np\n'), ((13499, 13526), 'numpy.sort', 'np.sort', (['uncertain_knn_dist'], {}), '(uncertain_knn_dist)\n', (13506, 13526), True, 'import numpy as np\n'), ((1660, 1675), 'numpy.log2', 'np.log2', (['(N / 10)'], {}), '(N / 10)\n', (1667, 1675), True, 'import numpy as np\n'), ((2353, 2372), 'numpy.round', 'np.round', (['(start / 2)'], {}), '(start / 2)\n', (2361, 2372), True, 'import numpy as np\n'), ((3985, 4007), 'numpy.delete', 'np.delete', (['src', 'dim', '(0)'], {}), '(src, dim, 0)\n', (3994, 4007), True, 'import numpy as np\n'), ((4550, 4568), 'numpy.max', 'np.max', (['dim_sample'], {}), '(dim_sample)\n', (4556, 4568), True, 'import numpy as np\n'), ((8541, 8568), 'numpy.zeros', 'np.zeros', (['rel_wins_idx.size'], {}), '(rel_wins_idx.size)\n', (8549, 8568), True, 'import numpy as np\n'), ((10639, 10650), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (10647, 10650), True, 'import numpy as np\n'), ((11307, 11355), 'scipy.spatial.distance.cdist', 'cdist', (['remaining_wins', 'sampled_wins', 'dist_metric'], {}), '(remaining_wins, sampled_wins, dist_metric)\n', (11312, 11355), False, 'from scipy.spatial.distance import cdist\n'), ((11518, 11546), 'numpy.where', 'np.where', (['(~subselection_mask)'], {}), '(~subselection_mask)\n', (11526, 11546), True, 'import numpy as np\n'), ((4072, 4104), 'scipy.spatial.distance.cdist', 'cdist', (['dim_data', 'dim_src', 'metric'], {}), '(dim_data, dim_src, metric)\n', (4077, 4104), False, 'from scipy.spatial.distance import cdist\n'), ((4142, 4182), 'scipy.spatial.distance.cdist', 'cdist', (['reduced_data', 'reduced_src', 'metric'], {}), '(reduced_data, reduced_src, metric)\n', (4147, 4182), False, 'from scipy.spatial.distance import cdist\n'), ((4498, 4522), 'numpy.argsort', 'np.argsort', (['reduced_dist'], {}), '(reduced_dist)\n', (4508, 4522), True, 'import numpy as np\n'), ((8990, 9017), 'numpy.zeros', 'np.zeros', (['level_sample_size'], {}), '(level_sample_size)\n', (8998, 9017), True, 'import numpy as np\n'), ((9739, 9787), 'scipy.spatial.distance.cdist', 'cdist', (['remaining_wins', 'sampled_wins', 'dist_metric'], {}), '(remaining_wins, sampled_wins, dist_metric)\n', (9744, 9787), False, 'from scipy.spatial.distance import cdist\n'), ((9986, 10011), 'numpy.where', 'np.where', (['(~selection_mask)'], {}), '(~selection_mask)\n', (9994, 10011), True, 'import numpy as np\n'), ((4243, 4267), 'scipy.spatial.distance.cdist', 'cdist', (['dim_data', 'dim_src'], {}), '(dim_data, dim_src)\n', (4248, 4267), False, 'from scipy.spatial.distance import cdist\n'), ((4305, 4337), 'scipy.spatial.distance.cdist', 'cdist', (['reduced_data', 'reduced_src'], {}), '(reduced_data, reduced_src)\n', (4310, 4337), False, 'from scipy.spatial.distance import cdist\n'), ((11653, 11704), 'server.utils.normalize_simple', 'utils.normalize_simple', (['ranking[~subselection_mask]'], {}), '(ranking[~subselection_mask])\n', (11675, 11704), False, 'from server import utils\n'), ((10130, 10194), 'server.utils.normalize_simple', 'utils.normalize_simple', (['knn_density_selected[remaining_wins_idx]'], {}), '(knn_density_selected[remaining_wins_idx])\n', (10152, 10194), False, 'from server import utils\n'), ((11614, 11626), 'numpy.max', 'np.max', (['dist'], {}), '(dist)\n', (11620, 11626), True, 'import numpy as np\n'), ((10087, 10099), 'numpy.max', 'np.max', (['dist'], {}), '(dist)\n', (10093, 10099), True, 'import numpy as np\n')]
import numpy as np import math ''' # FAST BSS Version 0.1.0: fastica: FastICA (most stable) meica: Multi-level extraction ICA (stable) cdica: Component dependent ICA (stable) aeica: Adaptive extraction ICA (*warning: unstable!) ufica: Ultra-fast ICA (cdica + aeica) (*warning: unstable!) # Basic definition: S: Source signals. shape = (source_number, time_slots_number) X: Mixed source signals. shape = (source_number, time_slots_number) A: Mixing matrix. shape = (source_number, source_number) B: Separation matrix. shape = (source_number, source_number) hat_S: Estimated source signals durch ICA algorithms. shape = (source_number, time_slots_number) # Notes: X = A @ S S = B @ X B = A ^ -1 ''' class FastbssBasic(): def whiten(self, X): ''' # whiten(self, X): # Usage: Whitening the mixed signals, i.e. matrix X. Let the mixed signals X are uncorrelated with each other. Meanwhile the variance of each mixed signal (i.e. each channel) x is 1, which is the premise of standard normal distribution. # Parameters: X: Mixed signals, matrix X. # Output: X, V X: Whitened mixed signals X. V: Whitening matrix. ''' X = X - X.mean(-1)[:, np.newaxis] A = np.dot(X, X.T) D, P = np.linalg.eig(A) D = np.diag(D) D_inv = np.linalg.inv(D) D_half = np.sqrt(D_inv) V = np.dot(D_half, P.T) m = X.shape[1] return np.sqrt(m)*np.dot(V, X), V def whiten_with_inv_V(self, X): ''' # whiten_with_inv_V(self, X): # Usage: Whitening the mixed signals, i.e. matrix X. Let the mixed signals X are uncorrelated with each other. Meanwhile the variance of each mixed signal (i.e. each channel) x is 1, which is the premise of standard normal distribution. # Parameters: X: Mixed signals, matrix X. # Output: X, V, V_inv X: Whitened mixed signals X. V: Whitening matrix. V_inv: The inverse of the whitening matrix V. ''' X = X - X.mean(-1)[:, np.newaxis] A = np.dot(X, X.T) D, P = np.linalg.eig(A) D = np.diag(D) D_inv = np.linalg.inv(D) D_half = np.sqrt(D_inv) V = np.dot(D_half, P.T) m = X.shape[1] V_inv = np.dot(P, np.sqrt(D)) return np.sqrt(m)*np.dot(V, X), V, V_inv def _tanh(self, x): gx = np.tanh(x) g_x = gx ** 2 g_x -= 1 g_x *= -1 return gx, g_x.sum(axis=-1) def _exp(self, x): exp = np.exp(-(x ** 2) / 2) gx = x * exp g_x = (1 - x ** 2) * exp return gx, g_x.sum(axis=-1) def _cube(self, x): return x ** 3, (3 * x ** 2).sum(axis=-1) def decorrelation(self, B): ''' # decorrelation(self, B): # Usage: Decorrelate the signals. Let each signal (i.e. channel) of B@X is uncorrelated with each other. # Parameters: B: The estimated separation matrix B. # Output: Decorrelated separation matrix B. ''' U, S = np.linalg.eigh(np.dot(B, B.T)) U = np.diag(U) U_inv = np.linalg.inv(U) U_half = np.sqrt(U_inv) rebuild_B = np.dot(np.dot(np.dot(S, U_half), S.T), B) return rebuild_B def generate_initial_matrix_B(self, V, A=None): ''' # decorrelation(self, B): # Usage: Generate the intial separation matrix for newton iteration. # Parameters: V: The whitening matrix, also used for getting the number of the original sources. A: The estimated mixing matrix. Then, the initial matrix B is (V @ A)^-1. When the value of A is None, this function will return a random matrix B, its size is according to the shape of matirx V. # Output: Initial separation matrix B. ''' n = np.shape(V)[0] if A is None: B = np.random.random_sample((n, n)) else: B = np.linalg.inv(np.dot(V, A)) try: return self.decorrelation(B) except: raise SystemError( 'Error - initial matrix generation : unkown, please try it again!') else: return self.generate_initial_matrix_B(V) def _iteration(self, B, X): ''' # _iteration(self, B, X): # Usage: Basic part of newton iteration for BSS. # Parameters: B: Separation matrix. X: Whitened mixed signals. # Output: Updated separation matrix B. ''' gbx, g_bx = self._tanh(np.dot(B, X)) B1 = self.decorrelation(np.dot(gbx, X.T) - g_bx[:, None] * B) lim = max(abs(abs(np.diag(np.dot(B1, B.T))) - 1)) # print(lim) return B1, lim def newton_iteration(self, B, X, max_iter, tol): ''' # newton_iteration(self, B, X, max_iter, tol): # Usage: Newton iteration part for BSS, the iteration jumps out when the convergence is smaller than the determined tolerance. # Parameters: B: Separation matrix. X: Whitened mixed signals. max_iter: Maximum number of iteration. tol: Tolerance of the convergence of the matrix B calculated from the last iteration and the matrix B calculated from current newton iteration. # Output: B,lim B: Separation matrix B. lim: Convergence of the iteration. ''' for _ in range(max_iter): B, lim = self._iteration(B, X) if lim < tol: break return B, lim # version3.0 class MultiLevelExtractionICA(FastbssBasic): def newton_iteration_auto_break(self, B, X, max_iter, tol, break_coef): ''' # newton_iteration_auto_break(self, B, X, max_iter, tol, break_coef): # Usage: Newton iteration part for BSS, the iteration jumps out automatically when the convergence decrease slower. # Parameters: B: Separation matrix. X: Whitened mixed signals. max_iter: Maximum number of iteration. tol: Tolerance of the convergence of the matrix B. break_coef: The paramter, which determine when the iteration should jump out. # Output: B,lim B: Separation matrix B. lim: Convergence of the iteration. break_by_tol: True if the Newton iteration triggers a fast break. ''' _sum = 0 _max = 0 break_by_tol = False for i in range(max_iter): B, lim = self._iteration(B, X) self.Stack.append(lim) if lim > _max: _max = lim self.Stack = [lim] _sum = 0 _sum += lim if self.Stack[-1] < tol: break_by_tol = True break if _sum < break_coef*0.5*(self.Stack[0]+self.Stack[-1])*len(self.Stack): break return (B, lim, break_by_tol) def multi_level_extraction_newton_iteration(self, X, B, max_iter, tol, break_coef, ext_multi_ica): ''' # multi_level_extraction_newton_iteration # (self, X, B, max_iter, tol, break_coef, ext_multi_ica): # Usage: Newton iteration with multi-level signal extraction, the extraction interval is (ext_multi_ica)^grad, grad=ext_multi_ica,...,3,2,1. # Parameters: B: Separation matrix. X: Whitened mixed signals. max_iter: Maximum number of iteration. tol: Tolerance of the convergence of the matrix B. break_coef: The paramter, which determine when the iteration should jump out. ext_multi_ica: The maximum signal extraction interval is m/((ext_multi_ica)^grad) >= n # Output: Separation matrix B. ''' n, m = X.shape _grad = int(math.log(m//n, ext_multi_ica)) _prop_series = ext_multi_ica**np.arange(_grad, -1, -1) for i in range(1, _grad+1): _X = X[:, ::_prop_series[i]] _X, V, V_inv = self.whiten_with_inv_V(_X) B = self.decorrelation(np.dot(B, V_inv)) self.Stack = [] B, _, break_by_tol = self.newton_iteration_auto_break( B, _X, max_iter, tol, break_coef) B = np.dot(B, V) if break_by_tol: break return B def meica(self, X, max_iter=100, tol=1e-04, break_coef=0.9, ext_multi_ica=8): ''' # mleica(self, X, max_iter=100, break_coef=0.9, ext_multi_ica=8): # Usage: Newton iteration with multi-level signal extraction, the extraction interval is 2^n, n=ext_multi_ica,...,3,2,1. # Parameters: X: Mixed signals, which is obtained from the observers. max_iter: Maximum number of iteration. break_coef: The paramter, which determine when the iteration should jump out. ext_multi_ica: The maximum signal extraction interval is 2^ext_multi_ica # Output: Estimated source signals matrix S. ''' self.Stack = [] B1 = self.generate_initial_matrix_B(X) B2 = self.multi_level_extraction_newton_iteration( X, B1, max_iter, tol, break_coef, ext_multi_ica) S2 = np.dot(B2, X) return S2 # Following methods use naming convention (of the paper) of X, uX (mu X), W, # uW (muW) instead of the B of previous methods. def meica_generate_uxs(self, X, ext_multi_ica=2) -> list(): """Generate a list of uX for distributed MEICA iterations. :param X: Mixed signals, which is obtained from the observers. :param ext_multi_ica: The maximum signal extraction interval is 2^ext_multi_ica :return: A list of uX. """ n, m = X.shape _grad = int(math.log(m//n, ext_multi_ica)) _prop_series = ext_multi_ica**np.arange(_grad, -1, -1) uXs = list() for i in range(1, _grad+1): _X = X[:, ::_prop_series[i]] uXs.append(_X) return uXs def meica_dist_get_uw(self, uX, uW, max_iter=100, tol=1e-04, break_coef=0.9) -> tuple: """Perform uW iteration for distributed MEICA. This method takes the current uX and uW of the previous distributed MEICA iteration as input and perform one iteration. :param uX: Extracted X with ext_multi_ica. :param uW: Calculated W from previous MEICA step. :param max_iter: Maximum number of iteration. :param break_coef: The paramter, which determine when the iteration should jump out. :return: uW_next: uW for the next iteration. break_by_tol: True if the Newton iteration triggers a fast break. """ self.Stack = [] _X = uX _X, V, V_inv = self.whiten_with_inv_V(_X) uW_next = self.decorrelation(np.dot(uW, V_inv)) self.Stack = [] uW_next, _, break_by_tol = self.newton_iteration_auto_break( uW_next, _X, max_iter, tol, break_coef) uW_next = np.dot(uW_next, V) return (uW_next, break_by_tol) def meica_dist_get_hat_s(self, uW, X): """Calculate the hat_S. :param uW: The uW of last iteration of meica_dist_get_uw method. :param X: Mixed signals, which is obtained from the observers. :return: Calculated hat_S. """ hat_S = np.dot(uW, X) return hat_S class ComponentDependentICA(FastbssBasic): def mixing_matrix_estimation(self, X, ext_initial_matrix): ''' # mixing_matrix_estimation(self, X, ext_initial_matrix): # Usage: According to the mixed signals observed from the observers, estimate a rough mixing matrix, which is used for calculating the intial separation matrix B_0. # Parameters: X: Mixed signals, which is obtained from the observers. ext_initial_matrix: The signal extraction interval for mixed signals extraction, default value is 0, which means use all the inputed signals. # Output: Estimated mixing matrix A. ''' m, n = X.shape sampling_interval = np.int(ext_initial_matrix) _signals = X[:, ::sampling_interval] if sampling_interval else X m, n = _signals.shape A = np.zeros([m, m]) indexs_max_abs = np.nanargmax(np.abs(_signals), axis=-2) indexs_max_abs_positive = np.where( _signals[indexs_max_abs, np.arange(n)] > 0, indexs_max_abs, np.nan) for y in range(m): selected_indexs = np.argwhere(indexs_max_abs_positive == y) if selected_indexs.shape[0] < 5: return None A[:, [y]] = np.sum(_signals[:, selected_indexs], axis=-2) A = np.dot(A, np.diag(1/np.max(A, axis=-1))) A = np.clip(A, 0.01, None) return A def cdica(self, X, max_iter=100, tol=1e-04, ext_initial_matrix=0): ''' # cdica(self, X, max_iter=100, tol=1e-04, ext_initial_matrix=0): # Usage: Component dependent ICA. It is a combination of initial mixing matrix estimation and original fastica. # Parameters: X: Mixed signals, which is obtained from the observers. max_iter: Maximum number of iteration. tol: Tolerance of the convergence of the matrix B calculated from the last iteration and the matrix B calculated from current newton iteration. ext_initial_matrix: The signal extraction interval for mixed signals extraction, default value is 0, which means use all the inputed signals. # Output: Estimated source signals matrix S. ''' X, V = self.whiten(X) A1 = self.mixing_matrix_estimation(X, ext_initial_matrix) B1 = self.generate_initial_matrix_B(V, A1) B2 = self.newton_iteration(B1, X, max_iter, tol)[0] S2 = np.dot(B2, X) return S2 class AdapiveExtractionICA(FastbssBasic): def adaptive_extraction_iteration(self, X, B, max_iter, tol, ext_adapt_ica): ''' # adaptive_extraction_iteration(self, X, B, max_iter, tol, _ext_adapt_ica): # Usage: Adaptive extraction newton iteration. It is a combination of several fastica algorithm with different partial signals, which is extracted by different intervals. the extraction interval can be detemined by the convergence of the iteration. # Parameters: X: Mixed signals, which is obtained from the observers. max_iter: Maximum number of iteration. tol: Tolerance of the convergence of the matrix B calculated from the last iteration and the matrix B calculated from current newton iteration. _ext_adapt_ica: The intial and the maximum extraction interval of the input signals. # Output: Estimated source separation matrix B. ''' _prop_series = np.arange(1, ext_adapt_ica) grads_num = _prop_series.shape[0] _tols = tol*(_prop_series**0.5) _tol = 1 for i in range(grads_num-1, 0, -1): if _tol > _tols[i]: _X = X[:, ::np.int(_prop_series[i])] _X, V, V_inv = self.whiten_with_inv_V(_X) B = self.decorrelation(np.dot(B, V_inv)) B, _tol = self.newton_iteration(B, _X, max_iter, _tols[i]) B = np.dot(B, V) _X = X _X, V, V_inv = self.whiten_with_inv_V(_X) B = self.decorrelation(np.dot(B, V_inv)) B, _tol = self.newton_iteration(B, _X, max_iter, _tols[i]) B = np.dot(B, V) return B def aeica(self, X, max_iter=100, tol=1e-04, ext_adapt_ica=50): ''' # aeica(self, X, max_iter=100, tol=1e-04, ext_adapt_ica=30): # Usage: Adaptive extraction ICA. It is a combination of several fastica algorithm with different partial signals, which is extracted by different intervals. the extraction interval can be detemined by the convergence of the iteration. A original fastica is added at the end, in order to get the best result. # Parameters: X: Mixed signals, which is obtained from the observers. max_iter: Maximum number of iteration. tol: Tolerance of the convergence of the matrix B calculated from the last iteration and the matrix B calculated from current newton iteration. _ext_adapt_ica: The intial and the maximum extraction interval of the input signals. # Output: Estimated source signals matrix S. ''' B1 = self.generate_initial_matrix_B(X) B2 = self.adaptive_extraction_iteration( X, B1, max_iter, tol, ext_adapt_ica) S2 = np.dot(B2, X) return S2 class UltraFastICA(ComponentDependentICA, AdapiveExtractionICA): def ufica(self, X, max_iter=100, tol=1e-04, ext_initial_matrix=0, ext_adapt_ica=100): ''' # ufica(self, X, max_iter=100, tol=1e-04, ext_initial_matrix=0, ext_adapt_ica=100): # Usage: Ultra-fast ICA. It is a combination of CdICA and AeICA. Firstly, CdICA, then, AeICA. # Parameters: X: Mixed signals, which is obtained from the observers. max_iter: Maximum number of iteration. tol: Tolerance of the convergence of the matrix B calculated from the last iteration and the matrix B calculated from current newton iteration. ext_initial_matrix: The signal extraction interval for mixed signals extraction, default value is 0, which means use all the inputed signals. _ext_adapt_ica: The intial and the maximum extraction interval of the input signals. # Output: Estimated source signals matrix S. ''' #X, V = self.whiten(X) A1 = self.mixing_matrix_estimation(X, ext_initial_matrix) B1 = np.linalg.inv(A1) B2 = self.adaptive_extraction_iteration( X, B1, max_iter, tol, ext_adapt_ica) S2 = np.dot(B2, X) return S2 class FastICA(FastbssBasic): def newton_iteration_auto_break2(self, B, X, max_iter, break_coef): ''' # newton_iteration_auto_break(self, B, X, max_iter, break_coef): # Usage: Newton iteration part for BSS, the iteration jumps out automatically when the convergence decrease slower. # Parameters: B: Separation matrix. X: Whitened mixed signals. max_iter: Maximum number of iteration. break_coef: The paramter, which determine when the iteration should jump out. # Output: B,lim B: Separation matrix B. lim: Convergence of the iteration. ''' _sum = 0 _max = 0 for _ in range(max_iter): B, lim = self._iteration(B, X) # print("3:",lim) self.Stack.append(lim) if lim > _max: _max = lim self.Stack = [lim] _sum = 0 _sum += lim if _sum < break_coef*0.5*(self.Stack[0]+self.Stack[-1])*len(self.Stack): break # print("3:",_) return B, lim def fastica(self, X, max_iter=100, tol=1e-04): ''' # fastica(self, X, max_iter=100, tol=1e-04): # Usage: Original FastICA. # Parameters: B: Separation matrix. X: Whitened mixed signals. max_iter: Maximum number of iteration. tol: Tolerance of the convergence of the matrix B calculated from the last iteration and the matrix B calculated from current newton iteration. # Output: Estimated source signals matrix S. ''' X, V = self.whiten(X) B1 = self.generate_initial_matrix_B(V) B2 = self.newton_iteration(B1, X, max_iter, tol)[0] S2 = np.dot(B2, X) return S2 def fastica_auto_break(self, X, max_iter=100, break_coef=0.98): _X = X _X, V = self.whiten(_X) B1 = self.generate_initial_matrix_B(V) self.Stack = [] B2 = self.newton_iteration_auto_break2( B1, _X, max_iter, break_coef)[0] B2 = np.dot(B2, V) S2 = np.dot(B2, X) return S2 class PyFastbss(MultiLevelExtractionICA, UltraFastICA, FastICA): def fastbss(self, method, X, max_iter=100, tol=1e-04, break_coef=0.9, ext_initial_matrix=0, ext_adapt_ica=100, ext_multi_ica=8): if method == 'fastica': return self.fastica(X, max_iter, tol) elif method == 'meica': return self.meica(X, max_iter, tol, break_coef, ext_multi_ica) elif method == 'cdica': return self.cdica(X, max_iter, tol, ext_initial_matrix) elif method == 'aeica': return self.aeica(X, max_iter, tol, ext_adapt_ica) elif method == 'ufica': return self.ufica(X, max_iter, tol, ext_initial_matrix, ext_adapt_ica) else: print('Method Identification Error!') return None # pyfastbss core pyfbss = PyFastbss()
[ "numpy.clip", "numpy.abs", "numpy.sqrt", "numpy.linalg.eig", "numpy.random.random_sample", "numpy.tanh", "numpy.diag", "numpy.exp", "math.log", "numpy.dot", "numpy.linalg.inv", "numpy.zeros", "numpy.argwhere", "numpy.sum", "numpy.max", "numpy.shape", "numpy.int", "numpy.arange" ]
[((1405, 1419), 'numpy.dot', 'np.dot', (['X', 'X.T'], {}), '(X, X.T)\n', (1411, 1419), True, 'import numpy as np\n'), ((1435, 1451), 'numpy.linalg.eig', 'np.linalg.eig', (['A'], {}), '(A)\n', (1448, 1451), True, 'import numpy as np\n'), ((1464, 1474), 'numpy.diag', 'np.diag', (['D'], {}), '(D)\n', (1471, 1474), True, 'import numpy as np\n'), ((1491, 1507), 'numpy.linalg.inv', 'np.linalg.inv', (['D'], {}), '(D)\n', (1504, 1507), True, 'import numpy as np\n'), ((1525, 1539), 'numpy.sqrt', 'np.sqrt', (['D_inv'], {}), '(D_inv)\n', (1532, 1539), True, 'import numpy as np\n'), ((1552, 1571), 'numpy.dot', 'np.dot', (['D_half', 'P.T'], {}), '(D_half, P.T)\n', (1558, 1571), True, 'import numpy as np\n'), ((2340, 2354), 'numpy.dot', 'np.dot', (['X', 'X.T'], {}), '(X, X.T)\n', (2346, 2354), True, 'import numpy as np\n'), ((2370, 2386), 'numpy.linalg.eig', 'np.linalg.eig', (['A'], {}), '(A)\n', (2383, 2386), True, 'import numpy as np\n'), ((2399, 2409), 'numpy.diag', 'np.diag', (['D'], {}), '(D)\n', (2406, 2409), True, 'import numpy as np\n'), ((2426, 2442), 'numpy.linalg.inv', 'np.linalg.inv', (['D'], {}), '(D)\n', (2439, 2442), True, 'import numpy as np\n'), ((2460, 2474), 'numpy.sqrt', 'np.sqrt', (['D_inv'], {}), '(D_inv)\n', (2467, 2474), True, 'import numpy as np\n'), ((2487, 2506), 'numpy.dot', 'np.dot', (['D_half', 'P.T'], {}), '(D_half, P.T)\n', (2493, 2506), True, 'import numpy as np\n'), ((2655, 2665), 'numpy.tanh', 'np.tanh', (['x'], {}), '(x)\n', (2662, 2665), True, 'import numpy as np\n'), ((2797, 2816), 'numpy.exp', 'np.exp', (['(-x ** 2 / 2)'], {}), '(-x ** 2 / 2)\n', (2803, 2816), True, 'import numpy as np\n'), ((3412, 3422), 'numpy.diag', 'np.diag', (['U'], {}), '(U)\n', (3419, 3422), True, 'import numpy as np\n'), ((3439, 3455), 'numpy.linalg.inv', 'np.linalg.inv', (['U'], {}), '(U)\n', (3452, 3455), True, 'import numpy as np\n'), ((3473, 3487), 'numpy.sqrt', 'np.sqrt', (['U_inv'], {}), '(U_inv)\n', (3480, 3487), True, 'import numpy as np\n'), ((9957, 9970), 'numpy.dot', 'np.dot', (['B2', 'X'], {}), '(B2, X)\n', (9963, 9970), True, 'import numpy as np\n'), ((11747, 11765), 'numpy.dot', 'np.dot', (['uW_next', 'V'], {}), '(uW_next, V)\n', (11753, 11765), True, 'import numpy as np\n'), ((12091, 12104), 'numpy.dot', 'np.dot', (['uW', 'X'], {}), '(uW, X)\n', (12097, 12104), True, 'import numpy as np\n'), ((12925, 12951), 'numpy.int', 'np.int', (['ext_initial_matrix'], {}), '(ext_initial_matrix)\n', (12931, 12951), True, 'import numpy as np\n'), ((13088, 13104), 'numpy.zeros', 'np.zeros', (['[m, m]'], {}), '([m, m])\n', (13096, 13104), True, 'import numpy as np\n'), ((13601, 13623), 'numpy.clip', 'np.clip', (['A', '(0.01)', 'None'], {}), '(A, 0.01, None)\n', (13608, 13623), True, 'import numpy as np\n'), ((14777, 14790), 'numpy.dot', 'np.dot', (['B2', 'X'], {}), '(B2, X)\n', (14783, 14790), True, 'import numpy as np\n'), ((15891, 15918), 'numpy.arange', 'np.arange', (['(1)', 'ext_adapt_ica'], {}), '(1, ext_adapt_ica)\n', (15900, 15918), True, 'import numpy as np\n'), ((16563, 16575), 'numpy.dot', 'np.dot', (['B', 'V'], {}), '(B, V)\n', (16569, 16575), True, 'import numpy as np\n'), ((17806, 17819), 'numpy.dot', 'np.dot', (['B2', 'X'], {}), '(B2, X)\n', (17812, 17819), True, 'import numpy as np\n'), ((19051, 19068), 'numpy.linalg.inv', 'np.linalg.inv', (['A1'], {}), '(A1)\n', (19064, 19068), True, 'import numpy as np\n'), ((19180, 19193), 'numpy.dot', 'np.dot', (['B2', 'X'], {}), '(B2, X)\n', (19186, 19193), True, 'import numpy as np\n'), ((21138, 21151), 'numpy.dot', 'np.dot', (['B2', 'X'], {}), '(B2, X)\n', (21144, 21151), True, 'import numpy as np\n'), ((21463, 21476), 'numpy.dot', 'np.dot', (['B2', 'V'], {}), '(B2, V)\n', (21469, 21476), True, 'import numpy as np\n'), ((21490, 21503), 'numpy.dot', 'np.dot', (['B2', 'X'], {}), '(B2, X)\n', (21496, 21503), True, 'import numpy as np\n'), ((2556, 2566), 'numpy.sqrt', 'np.sqrt', (['D'], {}), '(D)\n', (2563, 2566), True, 'import numpy as np\n'), ((3384, 3398), 'numpy.dot', 'np.dot', (['B', 'B.T'], {}), '(B, B.T)\n', (3390, 3398), True, 'import numpy as np\n'), ((4246, 4257), 'numpy.shape', 'np.shape', (['V'], {}), '(V)\n', (4254, 4257), True, 'import numpy as np\n'), ((4299, 4330), 'numpy.random.random_sample', 'np.random.random_sample', (['(n, n)'], {}), '((n, n))\n', (4322, 4330), True, 'import numpy as np\n'), ((4992, 5004), 'numpy.dot', 'np.dot', (['B', 'X'], {}), '(B, X)\n', (4998, 5004), True, 'import numpy as np\n'), ((8494, 8525), 'math.log', 'math.log', (['(m // n)', 'ext_multi_ica'], {}), '(m // n, ext_multi_ica)\n', (8502, 8525), False, 'import math\n'), ((8563, 8587), 'numpy.arange', 'np.arange', (['_grad', '(-1)', '(-1)'], {}), '(_grad, -1, -1)\n', (8572, 8587), True, 'import numpy as np\n'), ((8933, 8945), 'numpy.dot', 'np.dot', (['B', 'V'], {}), '(B, V)\n', (8939, 8945), True, 'import numpy as np\n'), ((10504, 10535), 'math.log', 'math.log', (['(m // n)', 'ext_multi_ica'], {}), '(m // n, ext_multi_ica)\n', (10512, 10535), False, 'import math\n'), ((10573, 10597), 'numpy.arange', 'np.arange', (['_grad', '(-1)', '(-1)'], {}), '(_grad, -1, -1)\n', (10582, 10597), True, 'import numpy as np\n'), ((11565, 11582), 'numpy.dot', 'np.dot', (['uW', 'V_inv'], {}), '(uW, V_inv)\n', (11571, 11582), True, 'import numpy as np\n'), ((13143, 13159), 'numpy.abs', 'np.abs', (['_signals'], {}), '(_signals)\n', (13149, 13159), True, 'import numpy as np\n'), ((13351, 13392), 'numpy.argwhere', 'np.argwhere', (['(indexs_max_abs_positive == y)'], {}), '(indexs_max_abs_positive == y)\n', (13362, 13392), True, 'import numpy as np\n'), ((13490, 13535), 'numpy.sum', 'np.sum', (['_signals[:, selected_indexs]'], {'axis': '(-2)'}), '(_signals[:, selected_indexs], axis=-2)\n', (13496, 13535), True, 'import numpy as np\n'), ((16466, 16482), 'numpy.dot', 'np.dot', (['B', 'V_inv'], {}), '(B, V_inv)\n', (16472, 16482), True, 'import numpy as np\n'), ((1610, 1620), 'numpy.sqrt', 'np.sqrt', (['m'], {}), '(m)\n', (1617, 1620), True, 'import numpy as np\n'), ((1621, 1633), 'numpy.dot', 'np.dot', (['V', 'X'], {}), '(V, X)\n', (1627, 1633), True, 'import numpy as np\n'), ((2583, 2593), 'numpy.sqrt', 'np.sqrt', (['m'], {}), '(m)\n', (2590, 2593), True, 'import numpy as np\n'), ((2594, 2606), 'numpy.dot', 'np.dot', (['V', 'X'], {}), '(V, X)\n', (2600, 2606), True, 'import numpy as np\n'), ((3522, 3539), 'numpy.dot', 'np.dot', (['S', 'U_half'], {}), '(S, U_half)\n', (3528, 3539), True, 'import numpy as np\n'), ((4375, 4387), 'numpy.dot', 'np.dot', (['V', 'A'], {}), '(V, A)\n', (4381, 4387), True, 'import numpy as np\n'), ((5038, 5054), 'numpy.dot', 'np.dot', (['gbx', 'X.T'], {}), '(gbx, X.T)\n', (5044, 5054), True, 'import numpy as np\n'), ((8754, 8770), 'numpy.dot', 'np.dot', (['B', 'V_inv'], {}), '(B, V_inv)\n', (8760, 8770), True, 'import numpy as np\n'), ((16357, 16369), 'numpy.dot', 'np.dot', (['B', 'V'], {}), '(B, V)\n', (16363, 16369), True, 'import numpy as np\n'), ((13568, 13586), 'numpy.max', 'np.max', (['A'], {'axis': '(-1)'}), '(A, axis=-1)\n', (13574, 13586), True, 'import numpy as np\n'), ((16244, 16260), 'numpy.dot', 'np.dot', (['B', 'V_inv'], {}), '(B, V_inv)\n', (16250, 16260), True, 'import numpy as np\n'), ((13251, 13263), 'numpy.arange', 'np.arange', (['n'], {}), '(n)\n', (13260, 13263), True, 'import numpy as np\n'), ((5110, 5125), 'numpy.dot', 'np.dot', (['B1', 'B.T'], {}), '(B1, B.T)\n', (5116, 5125), True, 'import numpy as np\n'), ((16122, 16145), 'numpy.int', 'np.int', (['_prop_series[i]'], {}), '(_prop_series[i])\n', (16128, 16145), True, 'import numpy as np\n')]
import numpy as np from finta import TA import pyqtgraph as pg """ Different indicators require different methods of plotting for example rsi can have lines at 70 and 30 """ class IndicatorFunctions: def __init__(self, create_func, plot_func, ohlc): self.create_func = create_func self.plot_func = plot_func self.ohlc = ohlc self.funcs = { "SMA": self.standard_function, "RSI": lambda indicator, **kwargs: self.RSI_lines(self.standard_function(indicator, **kwargs)) } def indicator_method(self, indicator, **kwargs): self.func = self.funcs[indicator](indicator) def standard_function(self, indicator, **kwargs): transformed_data = getattr(TA, indicator)(self.ohlc) transformed_data.dropna(inplace=True) time = transformed_data.index price = np.array(transformed_data) gw = self.create_func() self.plot_func(gw, time, price, indicator, pen=pg.mkPen(color=(108, 189, 128)), width=3.0) return gw def RSI_lines(self, gw): gw.addLine(x=None, y=70, pen=pg.mkPen('b', width=1)) gw.addLine(x=None, y=30, pen=pg.mkPen('b', width=1))
[ "numpy.array", "pyqtgraph.mkPen" ]
[((875, 901), 'numpy.array', 'np.array', (['transformed_data'], {}), '(transformed_data)\n', (883, 901), True, 'import numpy as np\n'), ((990, 1021), 'pyqtgraph.mkPen', 'pg.mkPen', ([], {'color': '(108, 189, 128)'}), '(color=(108, 189, 128))\n', (998, 1021), True, 'import pyqtgraph as pg\n'), ((1120, 1142), 'pyqtgraph.mkPen', 'pg.mkPen', (['"""b"""'], {'width': '(1)'}), "('b', width=1)\n", (1128, 1142), True, 'import pyqtgraph as pg\n'), ((1181, 1203), 'pyqtgraph.mkPen', 'pg.mkPen', (['"""b"""'], {'width': '(1)'}), "('b', width=1)\n", (1189, 1203), True, 'import pyqtgraph as pg\n')]
from multiprocessing import Pool import platform import numpy as np from mogp_emulator.GaussianProcess import ( GaussianProcessBase, GaussianProcess, PredictResult ) from mogp_emulator.Kernel import KernelBase from mogp_emulator.Priors import GPPriors class MultiOutputGP(object): """Implementation of a multiple-output Gaussian Process Emulator. Essentially a parallelized wrapper for the predict method. To fit in parallel, use the ``fit_GP_MAP`` routine Required arguments are ``inputs`` and ``targets``, both of which must be numpy arrays. ``inputs`` can be 1D or 2D (if 1D, assumes second axis has length 1). ``targets`` can be 1D or 2D (if 2D, assumes a single emulator and the first axis has length 1). Optional arguments specify how each individual emulator is constructed, including the mean function, kernel, priors, and how to handle the nugget. Each argument can take values allowed by the base ``GaussianProcess`` class, in which case all emulators are assumed to use the same value. Any of these arguments can alternatively be a list of values with length matching the number of emulators to set those values individually. """ def __init__(self, inputs, targets, mean=None, kernel="SquaredExponential", priors=None, nugget="adaptive", inputdict={}, use_patsy=True): """ Create a new multi-output GP Emulator """ self.GPClass = GaussianProcess if not inputdict == {}: warnings.warn("The inputdict interface for mean functions has been deprecated. " + "You must input your mean formulae using the x[0] format directly " + "in the formula.", DeprecationWarning) if not use_patsy: warnings.warn("patsy is now required to parse all formulae and form design " + "matrices in mogp-emulator. The use_patsy=False option will be ignored.") # check input types and shapes, reshape as appropriate for the case of a single emulator inputs = np.array(inputs) targets = np.array(targets) if len(inputs.shape) == 1: inputs = np.reshape(inputs, (-1, 1)) if len(targets.shape) == 1: targets = np.reshape(targets, (1, -1)) elif not (len(targets.shape) == 2): raise ValueError("targets must be either a 1D or 2D array") if not (len(inputs.shape) == 2): raise ValueError("inputs must be either a 1D or 2D array") if not (inputs.shape[0] == targets.shape[1]): raise ValueError("the first dimension of inputs must be the same length as the second dimension of targets (or first if targets is 1D))") self.n_emulators = targets.shape[0] self.n = inputs.shape[0] self.D = inputs.shape[1] if not isinstance(mean, list): mean = self.n_emulators*[mean] assert isinstance(mean, list), "mean must be None, a string, a valid patsy model description, or a list of None/string/mean functions" assert len(mean) == self.n_emulators if isinstance(kernel, str) or issubclass(type(kernel), KernelBase): kernel = self.n_emulators*[kernel] assert isinstance(kernel, list), "kernel must be a Kernel subclass or a list of Kernel subclasses" assert len(kernel) == self.n_emulators if isinstance(priors, (GPPriors, dict)) or priors is None: priorslist = self.n_emulators*[priors] else: priorslist = list(priors) assert isinstance(priorslist, list), ("priors must be a GPPriors object, None, or arguments to construct " + "a GPPriors object or a list of length n_emulators containing the above") assert len(priorslist) == self.n_emulators, "Bad length for list provided for priors to MultiOutputGP" if isinstance(nugget, (str, float)): nugget = self.n_emulators*[nugget] assert isinstance(nugget, list), "nugget must be a string, float, or a list of strings and floats" assert len(nugget) == self.n_emulators self.emulators = [ self.GPClass(inputs, single_target, m, k, p, n) for (single_target, m, k, p, n) in zip(targets, mean, kernel, priorslist, nugget)] def predict(self, testing, unc=True, deriv=False, include_nugget=True, allow_not_fit=False, processes=None): """Make a prediction for a set of input vectors Makes predictions for each of the emulators on a given set of input vectors. The input vectors must be passed as a ``(n_predict, D)`` or ``(D,)`` shaped array-like object, where ``n_predict`` is the number of different prediction points under consideration and ``D`` is the number of inputs to the emulator. If the prediction inputs array has shape ``(D,)``, then the method assumes ``n_predict == 1``. The prediction points are passed to each emulator and the predictions are collected into an ``(n_emulators, n_predict)`` shaped numpy array as the first return value from the method. Optionally, the emulator can also calculate the uncertainties in the predictions (as a variance) and the derivatives with respect to each input parameter. If the uncertainties are computed, they are returned as the second output from the method as an ``(n_emulators, n_predict)`` shaped numpy array. If the derivatives are computed, they are returned as the third output from the method as an ``(n_emulators, n_predict, D)`` shaped numpy array. Finally, if uncertainties are computed, the ``include_nugget`` flag determines if the uncertainties should include the nugget. By default, this is set to ``True``. Derivatives have been deprecated due to changes in how the mean function is computed, so setting ``deriv=True`` will have no effect and will raise a ``DeprecationWarning``. The ``allow_not_fit`` flag determines how the object handles any emulators that do not have fit hyperparameter values (because fitting presumably failed). By default, ``allow_not_fit=False`` and the method will raise an error if any emulators are not fit. Passing ``allow_not_fit=True`` will override this and ``NaN`` will be returned from any emulators that have not been fit. As with the fitting, this computation can be done independently for each emulator and thus can be done in parallel. :param testing: Array-like object holding the points where predictions will be made. Must have shape ``(n_predict, D)`` or ``(D,)`` (for a single prediction) :type testing: ndarray :param unc: (optional) Flag indicating if the uncertainties are to be computed. If ``False`` the method returns ``None`` in place of the uncertainty array. Default value is ``True``. :type unc: bool :param include_nugget: (optional) Flag indicating if the nugget should be included in the predictive variance. Only relevant if ``unc = True``. Default is ``True``. :type include_nugget: bool :param allow_not_fit: (optional) Flag that allows predictions to be made even if not all emulators have been fit. Default is ``False`` which will raise an error if any unfitted emulators are present. :type allow_not_fit: bool :param processes: (optional) Number of processes to use when making the predictions. Must be a positive integer or ``None`` to use the number of processors on the computer (default is ``None``) :type processes: int or None :returns: ``PredictResult`` object holding numpy arrays containing the predictions, uncertainties, and derivatives, respectively. Predictions and uncertainties have shape ``(n_emulators, n_predict)`` while the derivatives have shape ``(n_emulators, n_predict, D)``. If the ``do_unc`` or ``do_deriv`` flags are set to ``False``, then those arrays are replaced by ``None``. :rtype: PredictResult """ testing = np.array(testing) if self.D == 1 and testing.ndim == 1: testing = np.reshape(testing, (-1, 1)) elif testing.ndim == 1: testing = np.reshape(testing, (1, len(testing))) assert testing.ndim == 2, "testing must be a 2D array" n_testing, D = np.shape(testing) assert D == self.D, "second dimension of testing must be the same as the number of input parameters" if deriv: warnings.warn("Prediction derivatives have been deprecated and are no longer supported", DeprecationWarning) if not processes is None: processes = int(processes) assert processes > 0, "number of processes must be a positive integer" if allow_not_fit: predict_method = _gp_predict_default_NaN else: predict_method = self.GPClass.predict if platform.system() == "Windows": predict_vals = [predict_method(gp, testing, unc, deriv, include_nugget) for gp in self.emulators] else: with Pool(processes) as p: predict_vals = p.starmap(predict_method, [(gp, testing, unc, deriv, include_nugget) for gp in self.emulators]) # repackage predictions into numpy arrays predict_unpacked, unc_unpacked, deriv_unpacked = [np.array(t) for t in zip(*predict_vals)] if not unc: unc_unpacked = None deriv_unpacked = None return PredictResult(mean=predict_unpacked, unc=unc_unpacked, deriv=deriv_unpacked) def __call__(self, testing, processes=None): """Interface to predict means by calling the object A MultiOutputGP object is callable, which makes predictions of the mean only for a given set of inputs. Works similarly to the same method of the base GP class. """ return self.predict(testing, unc=False, deriv=False, processes=processes)[0] def get_indices_fit(self): """Returns the indices of the emulators that have been fit When a ``MultiOutputGP`` class is initialized, none of the emulators are fit. Fitting is done by passing the object to an external fitting routine, which modifies the object to fit the hyperparameters. Any emulators where the fitting fails are returned to the initialized state, and this method is used to determine the indices of the emulators that have succesfully been fit. Returns a list of non-negative integers indicating the indices of the emulators that have been fit. :returns: List of integer indicies indicating the emulators that have been fit. If no emulators have been fit, returns an empty list. :rtype: list of int """ return [idx for (failed_fit, idx) in zip([em.theta.get_data() is None for em in self.emulators], list(range(len(self.emulators)))) if not failed_fit] def get_indices_not_fit(self): """Returns the indices of the emulators that have not been fit When a ``MultiOutputGP`` class is initialized, none of the emulators are fit. Fitting is done by passing the object to an external fitting routine, which modifies the object to fit the hyperparameters. Any emulators where the fitting fails are returned to the initialized state, and this method is used to determine the indices of the emulators that have not been fit. Returns a list of non-negative integers indicating the indices of the emulators that have not been fit. :returns: List of integer indicies indicating the emulators that have not been fit. If all emulators have been fit, returns an empty list. :rtype: list of int """ return [idx for (failed_fit, idx) in zip([em.theta.get_data() is None for em in self.emulators], list(range(len(self.emulators)))) if failed_fit] def get_emulators_fit(self): """Returns the emulators that have been fit When a ``MultiOutputGP`` class is initialized, none of the emulators are fit. Fitting is done by passing the object to an external fitting routine, which modifies the object to fit the hyperparameters. Any emulators where the fitting fails are returned to the initialized state, and this method is used to obtain a list of emulators that have successfully been fit. Returns a list of ``GaussianProcess`` objects which have been fit (i.e. those which have a current valid set of hyperparameters). :returns: List of ``GaussianProcess`` objects indicating the emulators that have been fit. If no emulators have been fit, returns an empty list. :rtype: list of ``GaussianProcess`` objects """ return [gpem for (failed_fit, gpem) in zip([em.theta.get_data() is None for em in self.emulators], self.emulators) if not failed_fit] def get_emulators_not_fit(self): """Returns the indices of the emulators that have not been fit When a ``MultiOutputGP`` class is initialized, none of the emulators are fit. Fitting is done by passing the object to an external fitting routine, which modifies the object to fit the hyperparameters. Any emulators where the fitting fails are returned to the initialized state, and this method is used to obtain a list of emulators that have not been fit. Returns a list of ``GaussianProcess`` objects which have not been fit (i.e. those which do not have a current set of hyperparameters). :returns: List of ``GaussianProcess`` objects indicating the emulators that have not been fit. If all emulators have been fit, returns an empty list. :rtype: list of ``GaussianProcess`` objects """ return [gpem for (failed_fit, gpem) in zip([em.theta.get_data() is None for em in self.emulators], self.emulators) if failed_fit] def __str__(self): """Returns a string representation of the model :returns: A string representation of the model (indicates number of sub-components and array shapes) :rtype: str """ return ("Multi-Output Gaussian Process with:\n"+ str(self.n_emulators)+" emulators\n"+ str(self.n)+" training examples\n"+ str(self.D)+" input variables") def _gp_predict_default_NaN(gp, testing, unc, deriv, include_nugget): """Prediction method for GPs that defaults to NaN for unfit GPs Wrapper function for the ``GaussianProcess`` predict method that returns NaN if the GP is not fit. Allows ``MultiOutputGP`` objects that do not have all emulators fit to still return predictions with unfit emulator predictions replaced with NaN. The first argument to this function is the GP that will be used for prediction. All other arguments are the same as the arguments for the ``predict`` method of ``GaussianProcess``. :param gp: The ``GaussianProcess`` object (or related class) for which predictions will be made. :type gp: GaussianProcess :param testing: Array-like object holding the points where predictions will be made. Must have shape ``(n_predict, D)`` or ``(D,)`` (for a single prediction) :type testing: ndarray :param unc: (optional) Flag indicating if the uncertainties are to be computed. If ``False`` the method returns ``None`` in place of the uncertainty array. Default value is ``True``. :type unc: bool :param deriv: (optional) Flag indicating if the derivatives are to be computed. If ``False`` the method returns ``None`` in place of the derivative array. Default value is ``True``. :type deriv: bool :param include_nugget: (optional) Flag indicating if the nugget should be included in the predictive variance. Only relevant if ``unc = True``. Default is ``True``. :type include_nugget: bool :returns: Tuple of numpy arrays holding the predictions, uncertainties, and derivatives, respectively. Predictions and uncertainties have shape ``(n_predict,)`` while the derivatives have shape ``(n_predict, D)``. If the ``unc`` or ``deriv`` flags are set to ``False``, then those arrays are replaced by ``None``. :rtype: tuple """ assert isinstance(gp, GaussianProcessBase) try: return gp.predict(testing, unc, deriv, include_nugget) except ValueError: n_predict = testing.shape[0] if unc: unc_array = np.array([np.nan]*n_predict) else: unc_array = None if deriv: deriv_array = np.reshape(np.array([np.nan]*n_predict*gp.D), (n_predict, gp.D)) else: deriv_array = None return PredictResult(mean =np.array([np.nan]*n_predict), unc=unc_array, deriv=deriv_array)
[ "numpy.reshape", "numpy.array", "platform.system", "mogp_emulator.GaussianProcess.PredictResult", "multiprocessing.Pool", "numpy.shape" ]
[((2149, 2165), 'numpy.array', 'np.array', (['inputs'], {}), '(inputs)\n', (2157, 2165), True, 'import numpy as np\n'), ((2184, 2201), 'numpy.array', 'np.array', (['targets'], {}), '(targets)\n', (2192, 2201), True, 'import numpy as np\n'), ((8902, 8919), 'numpy.array', 'np.array', (['testing'], {}), '(testing)\n', (8910, 8919), True, 'import numpy as np\n'), ((9197, 9214), 'numpy.shape', 'np.shape', (['testing'], {}), '(testing)\n', (9205, 9214), True, 'import numpy as np\n'), ((10494, 10570), 'mogp_emulator.GaussianProcess.PredictResult', 'PredictResult', ([], {'mean': 'predict_unpacked', 'unc': 'unc_unpacked', 'deriv': 'deriv_unpacked'}), '(mean=predict_unpacked, unc=unc_unpacked, deriv=deriv_unpacked)\n', (10507, 10570), False, 'from mogp_emulator.GaussianProcess import GaussianProcessBase, GaussianProcess, PredictResult\n'), ((2258, 2285), 'numpy.reshape', 'np.reshape', (['inputs', '(-1, 1)'], {}), '(inputs, (-1, 1))\n', (2268, 2285), True, 'import numpy as np\n'), ((2344, 2372), 'numpy.reshape', 'np.reshape', (['targets', '(1, -1)'], {}), '(targets, (1, -1))\n', (2354, 2372), True, 'import numpy as np\n'), ((8988, 9016), 'numpy.reshape', 'np.reshape', (['testing', '(-1, 1)'], {}), '(testing, (-1, 1))\n', (8998, 9016), True, 'import numpy as np\n'), ((9811, 9828), 'platform.system', 'platform.system', ([], {}), '()\n', (9826, 9828), False, 'import platform\n'), ((10354, 10365), 'numpy.array', 'np.array', (['t'], {}), '(t)\n', (10362, 10365), True, 'import numpy as np\n'), ((10012, 10027), 'multiprocessing.Pool', 'Pool', (['processes'], {}), '(processes)\n', (10016, 10027), False, 'from multiprocessing import Pool\n'), ((18217, 18247), 'numpy.array', 'np.array', (['([np.nan] * n_predict)'], {}), '([np.nan] * n_predict)\n', (18225, 18247), True, 'import numpy as np\n'), ((18345, 18382), 'numpy.array', 'np.array', (['([np.nan] * n_predict * gp.D)'], {}), '([np.nan] * n_predict * gp.D)\n', (18353, 18382), True, 'import numpy as np\n'), ((18517, 18547), 'numpy.array', 'np.array', (['([np.nan] * n_predict)'], {}), '([np.nan] * n_predict)\n', (18525, 18547), True, 'import numpy as np\n')]
import argparse import os from typing import NoReturn import librosa import numpy as np import soundfile from bytesep.dataset_creation.pack_audios_to_hdf5s.instruments_solo import ( read_csv as read_instruments_solo_csv, ) from bytesep.dataset_creation.pack_audios_to_hdf5s.maestro import ( read_csv as read_maestro_csv, ) from bytesep.utils import load_random_segment def create_evaluation(args) -> NoReturn: r"""Random mix and write out audios for evaluation. Args: violin_dataset_dir: str, the directory of the violin dataset piano_dataset_dir: str, the directory of the piano dataset evaluation_audios_dir: str, the directory to write out randomly selected and mixed audio segments sample_rate: int channels: int, e.g., 1 | 2 evaluation_segments_num: int mono: bool Returns: NoReturn """ # arguments & parameters violin_dataset_dir = args.violin_dataset_dir piano_dataset_dir = args.piano_dataset_dir evaluation_audios_dir = args.evaluation_audios_dir sample_rate = args.sample_rate channels = args.channels evaluation_segments_num = args.evaluation_segments_num mono = True if channels == 1 else False split = 'test' segment_seconds = 10.0 random_state = np.random.RandomState(1234) violin_meta_csv = os.path.join(violin_dataset_dir, 'validation.csv') violin_names_dict = read_instruments_solo_csv(violin_meta_csv) violin_audio_names = violin_names_dict['{}'.format(split)] piano_meta_csv = os.path.join(piano_dataset_dir, 'maestro-v2.0.0.csv') piano_names_dict = read_maestro_csv(piano_meta_csv) piano_audio_names = piano_names_dict['{}'.format(split)] for source_type in ['violin', 'piano', 'mixture']: output_dir = os.path.join(evaluation_audios_dir, split, source_type) os.makedirs(output_dir, exist_ok=True) for n in range(evaluation_segments_num): print('{} / {}'.format(n, evaluation_segments_num)) # Randomly select and write out a clean violin segment. violin_audio_name = random_state.choice(violin_audio_names) violin_audio_path = os.path.join(violin_dataset_dir, "mp3s", violin_audio_name) violin_audio = load_random_segment( audio_path=violin_audio_path, random_state=random_state, segment_seconds=segment_seconds, mono=mono, sample_rate=sample_rate, ) # (channels_num, audio_samples) output_violin_path = os.path.join( evaluation_audios_dir, split, 'violin', '{:04d}.wav'.format(n) ) soundfile.write( file=output_violin_path, data=violin_audio.T, samplerate=sample_rate ) print("Write out to {}".format(output_violin_path)) # Randomly select and write out a clean piano segment. piano_audio_name = random_state.choice(piano_audio_names) piano_audio_path = os.path.join(piano_dataset_dir, piano_audio_name) piano_audio = load_random_segment( audio_path=piano_audio_path, random_state=random_state, segment_seconds=segment_seconds, mono=mono, sample_rate=sample_rate, ) # (channels_num, audio_samples) output_piano_path = os.path.join( evaluation_audios_dir, split, 'piano', '{:04d}.wav'.format(n) ) soundfile.write( file=output_piano_path, data=piano_audio.T, samplerate=sample_rate ) print("Write out to {}".format(output_piano_path)) # Mix violin and piano segments and write out a mixture segment. mixture_audio = violin_audio + piano_audio # (channels_num, audio_samples) output_mixture_path = os.path.join( evaluation_audios_dir, split, 'mixture', '{:04d}.wav'.format(n) ) soundfile.write( file=output_mixture_path, data=mixture_audio.T, samplerate=sample_rate ) print("Write out to {}".format(output_mixture_path)) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--violin_dataset_dir", type=str, required=True, help="The directory of the violin dataset.", ) parser.add_argument( "--piano_dataset_dir", type=str, required=True, help="The directory of the piano dataset.", ) parser.add_argument( "--evaluation_audios_dir", type=str, required=True, help="The directory to write out randomly selected and mixed audio segments.", ) parser.add_argument( "--sample_rate", type=int, required=True, help="Sample rate", ) parser.add_argument( "--channels", type=int, required=True, help="Audio channels, e.g, 1 or 2.", ) parser.add_argument( "--evaluation_segments_num", type=int, required=True, help="The number of segments to create for evaluation.", ) # Parse arguments. args = parser.parse_args() create_evaluation(args)
[ "argparse.ArgumentParser", "os.makedirs", "os.path.join", "bytesep.dataset_creation.pack_audios_to_hdf5s.instruments_solo.read_csv", "bytesep.utils.load_random_segment", "soundfile.write", "bytesep.dataset_creation.pack_audios_to_hdf5s.maestro.read_csv", "numpy.random.RandomState" ]
[((1301, 1328), 'numpy.random.RandomState', 'np.random.RandomState', (['(1234)'], {}), '(1234)\n', (1322, 1328), True, 'import numpy as np\n'), ((1352, 1402), 'os.path.join', 'os.path.join', (['violin_dataset_dir', '"""validation.csv"""'], {}), "(violin_dataset_dir, 'validation.csv')\n", (1364, 1402), False, 'import os\n'), ((1427, 1469), 'bytesep.dataset_creation.pack_audios_to_hdf5s.instruments_solo.read_csv', 'read_instruments_solo_csv', (['violin_meta_csv'], {}), '(violin_meta_csv)\n', (1452, 1469), True, 'from bytesep.dataset_creation.pack_audios_to_hdf5s.instruments_solo import read_csv as read_instruments_solo_csv\n'), ((1555, 1608), 'os.path.join', 'os.path.join', (['piano_dataset_dir', '"""maestro-v2.0.0.csv"""'], {}), "(piano_dataset_dir, 'maestro-v2.0.0.csv')\n", (1567, 1608), False, 'import os\n'), ((1632, 1664), 'bytesep.dataset_creation.pack_audios_to_hdf5s.maestro.read_csv', 'read_maestro_csv', (['piano_meta_csv'], {}), '(piano_meta_csv)\n', (1648, 1664), True, 'from bytesep.dataset_creation.pack_audios_to_hdf5s.maestro import read_csv as read_maestro_csv\n'), ((4123, 4148), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4146, 4148), False, 'import argparse\n'), ((1803, 1858), 'os.path.join', 'os.path.join', (['evaluation_audios_dir', 'split', 'source_type'], {}), '(evaluation_audios_dir, split, source_type)\n', (1815, 1858), False, 'import os\n'), ((1867, 1905), 'os.makedirs', 'os.makedirs', (['output_dir'], {'exist_ok': '(True)'}), '(output_dir, exist_ok=True)\n', (1878, 1905), False, 'import os\n'), ((2174, 2233), 'os.path.join', 'os.path.join', (['violin_dataset_dir', '"""mp3s"""', 'violin_audio_name'], {}), "(violin_dataset_dir, 'mp3s', violin_audio_name)\n", (2186, 2233), False, 'import os\n'), ((2258, 2407), 'bytesep.utils.load_random_segment', 'load_random_segment', ([], {'audio_path': 'violin_audio_path', 'random_state': 'random_state', 'segment_seconds': 'segment_seconds', 'mono': 'mono', 'sample_rate': 'sample_rate'}), '(audio_path=violin_audio_path, random_state=random_state,\n segment_seconds=segment_seconds, mono=mono, sample_rate=sample_rate)\n', (2277, 2407), False, 'from bytesep.utils import load_random_segment\n'), ((2652, 2742), 'soundfile.write', 'soundfile.write', ([], {'file': 'output_violin_path', 'data': 'violin_audio.T', 'samplerate': 'sample_rate'}), '(file=output_violin_path, data=violin_audio.T, samplerate=\n sample_rate)\n', (2667, 2742), False, 'import soundfile\n'), ((2977, 3026), 'os.path.join', 'os.path.join', (['piano_dataset_dir', 'piano_audio_name'], {}), '(piano_dataset_dir, piano_audio_name)\n', (2989, 3026), False, 'import os\n'), ((3050, 3198), 'bytesep.utils.load_random_segment', 'load_random_segment', ([], {'audio_path': 'piano_audio_path', 'random_state': 'random_state', 'segment_seconds': 'segment_seconds', 'mono': 'mono', 'sample_rate': 'sample_rate'}), '(audio_path=piano_audio_path, random_state=random_state,\n segment_seconds=segment_seconds, mono=mono, sample_rate=sample_rate)\n', (3069, 3198), False, 'from bytesep.utils import load_random_segment\n'), ((3441, 3529), 'soundfile.write', 'soundfile.write', ([], {'file': 'output_piano_path', 'data': 'piano_audio.T', 'samplerate': 'sample_rate'}), '(file=output_piano_path, data=piano_audio.T, samplerate=\n sample_rate)\n', (3456, 3529), False, 'import soundfile\n'), ((3910, 4002), 'soundfile.write', 'soundfile.write', ([], {'file': 'output_mixture_path', 'data': 'mixture_audio.T', 'samplerate': 'sample_rate'}), '(file=output_mixture_path, data=mixture_audio.T, samplerate=\n sample_rate)\n', (3925, 4002), False, 'import soundfile\n')]
import simpy import numpy as np def calculate_avg_original_time(num_robots, task_runtime_list, env): ''' Calculates the time required assuming all tasks are single-robot tasks. ''' num_tasks = len(task_runtime_list) total_time = 0 # First consider the case when there are at least as many robots as tasks. # Every task has a robot to work on it from the beginning, without needing to # wait in a queue while robots finish other tasks. if num_robots >= num_tasks: longest_task_runtime = np.max(task_runtime_list) longest_task = simpy.Container(env, init=longest_task_runtime, capacity=longest_task_runtime) while longest_task.level > 0: longest_task.get(1) total_time += 1 # Next consider the case when there are more tasks than robots if num_robots < num_tasks: # Create a dict of all the values as tasks (using simpy containers) and keys as unique task ids unassigned_task_dict = dict() # Sort the list so the longest tasks are assigned first (which mitigates possibility of a case in which # towards the end of the process, a single robot is hacking away at a large task while all others sit idle # for an extended period of time) task_runtime_list.sort(reverse=True) task_id = 0 for runtime in task_runtime_list: task = simpy.Container(env, init=runtime, capacity=runtime) unassigned_task_dict[task_id] = task task_id += 1 inprogress_task_dict = dict() # Now allocate the homogenous robots to the tasks. # Since they are homogenous, the assignment order does not matter for bot in range(num_robots): # While a task is in unassigned_task_dict, it's available for a robot to be assigned to it # Once a bot is assigned to it, it moves to the inprogress_task_dict # Once a a task's level is 0, then it is removed from the inprogress_task_dict # All .get(1) methods are called at the same time across the robots, and a tally is added to # total_time for each call (which simulates a minute passing) inprogress_task_dict[bot] = None while len(unassigned_task_dict) > 0 or any(inprogress_task_dict.values()): # Move tasks from the unassigned_task_dict to the inprogress_task_dict as space allows for bot in inprogress_task_dict.keys(): if inprogress_task_dict[bot] is None: if len(unassigned_task_dict) > 0: inprogress_task_dict[bot] = unassigned_task_dict.popitem() # Let the bots each do one minute of work on the tasks they have, and increment the total time accordingly for bot in inprogress_task_dict.keys(): if inprogress_task_dict[bot] is not None: inprogress_task = inprogress_task_dict[bot][1] inprogress_task.get(1) total_time += 1 # If a task is finished, remove it from the inprogress_task_dict so the robot that completed it can # begin work on another task. for bot in inprogress_task_dict.keys(): if inprogress_task_dict[bot] is not None: inprogress_task = inprogress_task_dict[bot][1] if inprogress_task.level <= 0: inprogress_task_dict[bot] = None avg_original_time = total_time # print(f"Average original time: {avg_original_time}") return avg_original_time def calculate_multi_robot_task_time(num_robots, task_runtime_list, env): ''' A naive method for assigning groups of robots to multi-robot tasks ''' # Sort the task list so that the most time-consuming task is first num_tasks = len(task_runtime_list) task_runtime_list.sort(reverse=True) task_list = [] # Build the tasks for runtime in task_runtime_list: task = simpy.Container(env, init=runtime, capacity=runtime) task_list.append(task) # Allocate the tasks, counting each round of get() calls (one get() call per robot) as one timestep passed # Keep track of all the timesteps used to get a measure of total time multi_robot_task_time = 0 leftover = 0 for task in task_list: # This simply keeps track of 'leftovers' in the case that there are more robots assigned to a task # than the task itself can accommodate, so the 'leftover' robots can be assigned to the next task in the queue. while leftover > 0 and task.level > 0: if leftover > task.level: decrement_to_leftover = task.level task.get(task.level) leftover -= decrement_to_leftover if leftover <= task.level: task.get(leftover) leftover = 0 # The robots swarm to complete the tasks, with some leftover if the number is too great while task.level > 0: multi_robot_task_time += 1 for robot in range(num_robots): task.get(1) if task.level <= 0: leftover += 1 # print(f'Multi-robot task time: {multi_robot_task_time}') return multi_robot_task_time def st_mr_ia(num_robots, task_runtime_list): env = simpy.Environment() # Find the cumulative time of all tasks (if a single robot was responsible for completing all tasks on its own) cumulative_task_time = np.sum(task_runtime_list) # print(f"Cumulative task time (for example, if only had 1 robot to work on them): {cumulative_task_time}") # Find the average original time (the time without allowing robots to collaborate on a given task) avg_original_time = calculate_avg_original_time(num_robots, task_runtime_list, env) # Find the time required when we allow for multi-robot tasks multi_robot_task_time = calculate_multi_robot_task_time(num_robots, task_runtime_list, env) return cumulative_task_time, avg_original_time, multi_robot_task_time def run(num_robots, num_task): cumulative_task_list = [] avg_orig_time_list = [] multi_robot_time_list = [] for _ in range(50): task_runtime_array = np.random.randint(low=1, high=30, size=(num_task,), dtype=int) task_runtime_list = task_runtime_array.tolist() cumulative_task_time, avg_orig_time, multi_robot_time = st_mr_ia(num_robots=num_robots, task_runtime_list=task_runtime_list) cumulative_task_list.append(cumulative_task_time) avg_orig_time_list.append(avg_orig_time) multi_robot_time_list.append(multi_robot_time) final_cumulative_task_time = np.mean(cumulative_task_list) final_avg_orig_time = np.mean(avg_orig_time_list) final_multi_robot_mean_time = np.mean(multi_robot_time_list) final_multi_robot_std = np.std(multi_robot_time_list) print(f'{num_robots} \t{num_task} \t{final_cumulative_task_time} \t{final_avg_orig_time} \t\t{final_multi_robot_mean_time} \t{final_multi_robot_std}', flush=True) def make_table(): np.random.seed(1) print('Robots', '\tTasks', '\tCumul.Time', '\tAvg.Orig.Time', '\tMu', '\t\tSigma', flush=True) run(11, 4) run(8, 3) run(6, 4) run(4, 12) run(8, 8) def main(): make_table() if __name__ == '__main__': main()
[ "numpy.mean", "simpy.Environment", "numpy.max", "numpy.sum", "numpy.random.randint", "numpy.random.seed", "numpy.std", "simpy.Container" ]
[((5358, 5377), 'simpy.Environment', 'simpy.Environment', ([], {}), '()\n', (5375, 5377), False, 'import simpy\n'), ((5522, 5547), 'numpy.sum', 'np.sum', (['task_runtime_list'], {}), '(task_runtime_list)\n', (5528, 5547), True, 'import numpy as np\n'), ((6787, 6816), 'numpy.mean', 'np.mean', (['cumulative_task_list'], {}), '(cumulative_task_list)\n', (6794, 6816), True, 'import numpy as np\n'), ((6843, 6870), 'numpy.mean', 'np.mean', (['avg_orig_time_list'], {}), '(avg_orig_time_list)\n', (6850, 6870), True, 'import numpy as np\n'), ((6905, 6935), 'numpy.mean', 'np.mean', (['multi_robot_time_list'], {}), '(multi_robot_time_list)\n', (6912, 6935), True, 'import numpy as np\n'), ((6964, 6993), 'numpy.std', 'np.std', (['multi_robot_time_list'], {}), '(multi_robot_time_list)\n', (6970, 6993), True, 'import numpy as np\n'), ((7199, 7216), 'numpy.random.seed', 'np.random.seed', (['(1)'], {}), '(1)\n', (7213, 7216), True, 'import numpy as np\n'), ((532, 557), 'numpy.max', 'np.max', (['task_runtime_list'], {}), '(task_runtime_list)\n', (538, 557), True, 'import numpy as np\n'), ((581, 659), 'simpy.Container', 'simpy.Container', (['env'], {'init': 'longest_task_runtime', 'capacity': 'longest_task_runtime'}), '(env, init=longest_task_runtime, capacity=longest_task_runtime)\n', (596, 659), False, 'import simpy\n'), ((3997, 4049), 'simpy.Container', 'simpy.Container', (['env'], {'init': 'runtime', 'capacity': 'runtime'}), '(env, init=runtime, capacity=runtime)\n', (4012, 4049), False, 'import simpy\n'), ((6266, 6328), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(1)', 'high': '(30)', 'size': '(num_task,)', 'dtype': 'int'}), '(low=1, high=30, size=(num_task,), dtype=int)\n', (6283, 6328), True, 'import numpy as np\n'), ((1395, 1447), 'simpy.Container', 'simpy.Container', (['env'], {'init': 'runtime', 'capacity': 'runtime'}), '(env, init=runtime, capacity=runtime)\n', (1410, 1447), False, 'import simpy\n')]
"""Evaluation metrics for Annif""" import collections import statistics import warnings import numpy as np from sklearn.metrics import precision_score, recall_score, f1_score from sklearn.metrics import label_ranking_average_precision_score def true_positives(y_true, y_pred): """calculate the number of true positives using bitwise operations, emulating the way sklearn evaluation metric functions work""" return (y_true & y_pred).sum() def false_positives(y_true, y_pred): """calculate the number of false positives using bitwise operations, emulating the way sklearn evaluation metric functions work""" return (~y_true & y_pred).sum() def false_negatives(y_true, y_pred): """calculate the number of false negatives using bitwise operations, emulating the way sklearn evaluation metric functions work""" return (y_true & ~y_pred).sum() def precision_at_k_score(y_true, y_pred, limit): """calculate the precision at K, i.e. the number of relevant items among the top K predicted ones""" scores = [] origlimit = limit for true, pred in zip(y_true, y_pred): order = pred.argsort()[::-1] orderlimit = min(limit, np.count_nonzero(pred)) order = order[:orderlimit] gain = true[order] if orderlimit > 0: scores.append(gain.sum() / orderlimit) else: scores.append(0.0) return statistics.mean(scores) def dcg_score(y_true, y_pred, limit=None): """return the discounted cumulative gain (DCG) score for the selected labels vs. relevant labels""" order = y_pred.argsort()[::-1] n_pred = np.count_nonzero(y_pred) if limit is not None: n_pred = min(limit, n_pred) order = order[:n_pred] gain = y_true[order] discount = np.log2(np.arange(order.size) + 2) return (gain / discount).sum() def ndcg_score(y_true, y_pred, limit=None): """return the normalized discounted cumulative gain (nDCG) score for the selected labels vs. relevant labels""" scores = [] for true, pred in zip(y_true, y_pred): idcg = dcg_score(true, true, limit) dcg = dcg_score(true, pred, limit) if idcg > 0: scores.append(dcg / idcg) else: scores.append(1.0) # perfect score for no relevant hits case return statistics.mean(scores) class EvaluationBatch: """A class for evaluating batches of results using all available metrics. The evaluate() method is called once per document in the batch. Final results can be queried using the results() method.""" def __init__(self, subject_index): self._subject_index = subject_index self._samples = [] def evaluate(self, hits, gold_subjects): self._samples.append((hits, gold_subjects)) def _evaluate_samples(self, y_true, y_pred, metrics='all'): y_pred_binary = y_pred > 0.0 results = collections.OrderedDict() with warnings.catch_warnings(): warnings.simplefilter('ignore') results['Precision (doc avg)'] = precision_score( y_true, y_pred_binary, average='samples') results['Recall (doc avg)'] = recall_score( y_true, y_pred_binary, average='samples') results['F1 score (doc avg)'] = f1_score( y_true, y_pred_binary, average='samples') if metrics == 'all': results['Precision (conc avg)'] = precision_score( y_true, y_pred_binary, average='macro') results['Recall (conc avg)'] = recall_score( y_true, y_pred_binary, average='macro') results['F1 score (conc avg)'] = f1_score( y_true, y_pred_binary, average='macro') results['Precision (microavg)'] = precision_score( y_true, y_pred_binary, average='micro') results['Recall (microavg)'] = recall_score( y_true, y_pred_binary, average='micro') results['F1 score (microavg)'] = f1_score( y_true, y_pred_binary, average='micro') results['NDCG'] = ndcg_score(y_true, y_pred) results['NDCG@5'] = ndcg_score(y_true, y_pred, limit=5) results['NDCG@10'] = ndcg_score(y_true, y_pred, limit=10) if metrics == 'all': results['Precision@1'] = precision_at_k_score( y_true, y_pred, limit=1) results['Precision@3'] = precision_at_k_score( y_true, y_pred, limit=3) results['Precision@5'] = precision_at_k_score( y_true, y_pred, limit=5) results['LRAP'] = label_ranking_average_precision_score( y_true, y_pred) results['True positives'] = true_positives( y_true, y_pred_binary) results['False positives'] = false_positives( y_true, y_pred_binary) results['False negatives'] = false_negatives( y_true, y_pred_binary) return results def results(self, metrics='all'): """evaluate a set of selected subjects against a gold standard using different metrics. The set of metrics can be either 'all' or 'simple'.""" y_true = np.array([gold_subjects.as_vector(self._subject_index) for hits, gold_subjects in self._samples]) y_pred = np.array([hits.vector for hits, gold_subjects in self._samples]) results = self._evaluate_samples( y_true, y_pred, metrics) results['Documents evaluated'] = y_true.shape[0] return results
[ "statistics.mean", "collections.OrderedDict", "sklearn.metrics.f1_score", "sklearn.metrics.label_ranking_average_precision_score", "warnings.catch_warnings", "sklearn.metrics.precision_score", "numpy.count_nonzero", "numpy.array", "sklearn.metrics.recall_score", "warnings.simplefilter", "numpy.a...
[((1411, 1434), 'statistics.mean', 'statistics.mean', (['scores'], {}), '(scores)\n', (1426, 1434), False, 'import statistics\n'), ((1636, 1660), 'numpy.count_nonzero', 'np.count_nonzero', (['y_pred'], {}), '(y_pred)\n', (1652, 1660), True, 'import numpy as np\n'), ((2331, 2354), 'statistics.mean', 'statistics.mean', (['scores'], {}), '(scores)\n', (2346, 2354), False, 'import statistics\n'), ((2919, 2944), 'collections.OrderedDict', 'collections.OrderedDict', ([], {}), '()\n', (2942, 2944), False, 'import collections\n'), ((5507, 5571), 'numpy.array', 'np.array', (['[hits.vector for hits, gold_subjects in self._samples]'], {}), '([hits.vector for hits, gold_subjects in self._samples])\n', (5515, 5571), True, 'import numpy as np\n'), ((1191, 1213), 'numpy.count_nonzero', 'np.count_nonzero', (['pred'], {}), '(pred)\n', (1207, 1213), True, 'import numpy as np\n'), ((1798, 1819), 'numpy.arange', 'np.arange', (['order.size'], {}), '(order.size)\n', (1807, 1819), True, 'import numpy as np\n'), ((2958, 2983), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (2981, 2983), False, 'import warnings\n'), ((2997, 3028), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (3018, 3028), False, 'import warnings\n'), ((3075, 3132), 'sklearn.metrics.precision_score', 'precision_score', (['y_true', 'y_pred_binary'], {'average': '"""samples"""'}), "(y_true, y_pred_binary, average='samples')\n", (3090, 3132), False, 'from sklearn.metrics import precision_score, recall_score, f1_score\n'), ((3192, 3246), 'sklearn.metrics.recall_score', 'recall_score', (['y_true', 'y_pred_binary'], {'average': '"""samples"""'}), "(y_true, y_pred_binary, average='samples')\n", (3204, 3246), False, 'from sklearn.metrics import precision_score, recall_score, f1_score\n'), ((3308, 3358), 'sklearn.metrics.f1_score', 'f1_score', (['y_true', 'y_pred_binary'], {'average': '"""samples"""'}), "(y_true, y_pred_binary, average='samples')\n", (3316, 3358), False, 'from sklearn.metrics import precision_score, recall_score, f1_score\n'), ((3459, 3514), 'sklearn.metrics.precision_score', 'precision_score', (['y_true', 'y_pred_binary'], {'average': '"""macro"""'}), "(y_true, y_pred_binary, average='macro')\n", (3474, 3514), False, 'from sklearn.metrics import precision_score, recall_score, f1_score\n'), ((3583, 3635), 'sklearn.metrics.recall_score', 'recall_score', (['y_true', 'y_pred_binary'], {'average': '"""macro"""'}), "(y_true, y_pred_binary, average='macro')\n", (3595, 3635), False, 'from sklearn.metrics import precision_score, recall_score, f1_score\n'), ((3706, 3754), 'sklearn.metrics.f1_score', 'f1_score', (['y_true', 'y_pred_binary'], {'average': '"""macro"""'}), "(y_true, y_pred_binary, average='macro')\n", (3714, 3754), False, 'from sklearn.metrics import precision_score, recall_score, f1_score\n'), ((3826, 3881), 'sklearn.metrics.precision_score', 'precision_score', (['y_true', 'y_pred_binary'], {'average': '"""micro"""'}), "(y_true, y_pred_binary, average='micro')\n", (3841, 3881), False, 'from sklearn.metrics import precision_score, recall_score, f1_score\n'), ((3950, 4002), 'sklearn.metrics.recall_score', 'recall_score', (['y_true', 'y_pred_binary'], {'average': '"""micro"""'}), "(y_true, y_pred_binary, average='micro')\n", (3962, 4002), False, 'from sklearn.metrics import precision_score, recall_score, f1_score\n'), ((4073, 4121), 'sklearn.metrics.f1_score', 'f1_score', (['y_true', 'y_pred_binary'], {'average': '"""micro"""'}), "(y_true, y_pred_binary, average='micro')\n", (4081, 4121), False, 'from sklearn.metrics import precision_score, recall_score, f1_score\n'), ((4729, 4782), 'sklearn.metrics.label_ranking_average_precision_score', 'label_ranking_average_precision_score', (['y_true', 'y_pred'], {}), '(y_true, y_pred)\n', (4766, 4782), False, 'from sklearn.metrics import label_ranking_average_precision_score\n')]
import numpy as np def rand_bbox(height, width, lamda): # Size of the cropping region cut_ratio = np.sqrt(1 - lamda) cut_height = np.int(height * cut_ratio) cut_width = np.int(width * cut_ratio) # Coordinates of the center center_width = np.random.randint(width) center_height = np.random.randint(height) # Coordinates of the bounding box width_start = np.clip(center_width - cut_width // 2, 0, width) width_end = np.clip(center_width + cut_width // 2, 0, width) height_start = np.clip(center_height - cut_height // 2, 0, height) height_end = np.clip(center_height + cut_height // 2, 0, height) return width_start, width_end, height_start, height_end def perform_cutmix(image_content_alpha, one_hot_encoding_tuple_alpha, image_content_beta, one_hot_encoding_tuple_beta, alpha=0.4): """ https://github.com/clovaai/CutMix-PyTorch https://www.kaggle.com/c/bengaliai-cv19/discussion/126504 """ # Get lamda from a Beta distribution lamda = np.random.beta(alpha, alpha) # Get coordinates of the bounding box height, width = image_content_alpha.shape[:2] width_start, width_end, height_start, height_end = rand_bbox( height, width, lamda) lamda = 1 - (height_end - height_start) * (width_end - width_start) / (height * width) # Copy the region from the second image image_content = image_content_alpha.copy() image_content[height_start:height_end, width_start:width_end] = image_content_beta[ height_start:height_end, width_start:width_end] # Modify the one hot encoding vector one_hot_encoding_tuple = [] for one_hot_encoding_alpha, one_hot_encoding_beta in zip( one_hot_encoding_tuple_alpha, one_hot_encoding_tuple_beta): one_hot_encoding = one_hot_encoding_alpha * lamda + one_hot_encoding_beta * ( 1 - lamda) one_hot_encoding_tuple.append(one_hot_encoding) one_hot_encoding_tuple = tuple(one_hot_encoding_tuple) return image_content, one_hot_encoding_tuple def perform_mixup(image_content_alpha, one_hot_encoding_tuple_alpha, image_content_beta, one_hot_encoding_tuple_beta, alpha=0.4): """ https://github.com/facebookresearch/mixup-cifar10 https://www.kaggle.com/c/bengaliai-cv19/discussion/126504 """ # Get lamda from a Beta distribution lamda = np.random.beta(alpha, alpha) # MixUp image_content = lamda * image_content_alpha + (1 - lamda) * image_content_beta # Modify the one hot encoding vector one_hot_encoding_tuple = [] for one_hot_encoding_alpha, one_hot_encoding_beta in zip( one_hot_encoding_tuple_alpha, one_hot_encoding_tuple_beta): one_hot_encoding = one_hot_encoding_alpha * lamda + one_hot_encoding_beta * ( 1 - lamda) one_hot_encoding_tuple.append(one_hot_encoding) one_hot_encoding_tuple = tuple(one_hot_encoding_tuple) return image_content, one_hot_encoding_tuple
[ "numpy.clip", "numpy.sqrt", "numpy.random.beta", "numpy.random.randint", "numpy.int" ]
[((108, 126), 'numpy.sqrt', 'np.sqrt', (['(1 - lamda)'], {}), '(1 - lamda)\n', (115, 126), True, 'import numpy as np\n'), ((144, 170), 'numpy.int', 'np.int', (['(height * cut_ratio)'], {}), '(height * cut_ratio)\n', (150, 170), True, 'import numpy as np\n'), ((187, 212), 'numpy.int', 'np.int', (['(width * cut_ratio)'], {}), '(width * cut_ratio)\n', (193, 212), True, 'import numpy as np\n'), ((265, 289), 'numpy.random.randint', 'np.random.randint', (['width'], {}), '(width)\n', (282, 289), True, 'import numpy as np\n'), ((310, 335), 'numpy.random.randint', 'np.random.randint', (['height'], {}), '(height)\n', (327, 335), True, 'import numpy as np\n'), ((393, 441), 'numpy.clip', 'np.clip', (['(center_width - cut_width // 2)', '(0)', 'width'], {}), '(center_width - cut_width // 2, 0, width)\n', (400, 441), True, 'import numpy as np\n'), ((458, 506), 'numpy.clip', 'np.clip', (['(center_width + cut_width // 2)', '(0)', 'width'], {}), '(center_width + cut_width // 2, 0, width)\n', (465, 506), True, 'import numpy as np\n'), ((526, 577), 'numpy.clip', 'np.clip', (['(center_height - cut_height // 2)', '(0)', 'height'], {}), '(center_height - cut_height // 2, 0, height)\n', (533, 577), True, 'import numpy as np\n'), ((595, 646), 'numpy.clip', 'np.clip', (['(center_height + cut_height // 2)', '(0)', 'height'], {}), '(center_height + cut_height // 2, 0, height)\n', (602, 646), True, 'import numpy as np\n'), ((1102, 1130), 'numpy.random.beta', 'np.random.beta', (['alpha', 'alpha'], {}), '(alpha, alpha)\n', (1116, 1130), True, 'import numpy as np\n'), ((2605, 2633), 'numpy.random.beta', 'np.random.beta', (['alpha', 'alpha'], {}), '(alpha, alpha)\n', (2619, 2633), True, 'import numpy as np\n')]
# MIT License # # Copyright (c) 2021 <NAME> # # 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. import os import random from typing import Tuple import librosa import torch import torchaudio import numpy as np from torch import Tensor from torch.utils.data import Dataset def parse_manifest_file(manifest_file_path: str) -> Tuple[list, list]: """ Parsing manifest file """ audio_paths = list() transcripts = list() with open(manifest_file_path) as f: for idx, line in enumerate(f.readlines()): audio_path, _, transcript = line.split('\t') transcript = transcript.replace('\n', '') audio_paths.append(audio_path) transcripts.append(transcript) return audio_paths, transcripts class AudioDataset(Dataset): """ Dataset for audio & transcript matching Note: Do not use this class directly, use one of the sub classes. Args: dataset_path (str): path of librispeech dataset audio_paths (list): list of audio path transcripts (list): list of transript apply_spec_augment (bool): flag indication whether to apply spec augment or not sos_id (int): identification of <sos> eos_id (int): identification of <eos> sample_rate (int): sampling rate of audio num_mels (int): the number of mfc coefficients to retain. frame_length (float): frame length for spectrogram (ms) frame_shift (float): length of hop between STFT (short time fourier transform) windows. freq_mask_para (int): hyper Parameter for freq masking to limit freq masking length time_mask_num (int): how many time-masked area to make freq_mask_num (int): how many freq-masked area to make """ def __init__( self, dataset_path: str, audio_paths: list, transcripts: list, apply_spec_augment: bool = False, sos_id: int = 1, eos_id: int = 2, sample_rate: int = 16000, num_mels: int = 80, frame_length: float = 25.0, frame_shift: float = 10.0, freq_mask_para: int = 27, time_mask_num: int = 4, freq_mask_num: int = 2, ) -> None: super(AudioDataset, self).__init__() self.dataset_path = dataset_path self.audio_paths = list(audio_paths) self.transcripts = list(transcripts) self.spec_augment_flags = [False] * len(self.audio_paths) self.dataset_size = len(self.audio_paths) self.sos_id = sos_id self.eos_id = eos_id self.sample_rate = sample_rate self.num_mels = num_mels self.frame_length = frame_length self.frame_shift = frame_shift self.freq_mask_para = freq_mask_para self.time_mask_num = time_mask_num self.freq_mask_num = freq_mask_num self.n_fft = int(round(sample_rate * 0.001 * frame_length)) self.hop_length = int(round(sample_rate * 0.001 * frame_shift)) if apply_spec_augment: for idx in range(self.dataset_size): self.spec_augment_flags.append(True) self.audio_paths.append(self.audio_paths[idx]) self.transcripts.append(self.transcripts[idx]) self.shuffle() def _spec_augment(self, feature: Tensor) -> Tensor: """ Provides Spec Augment. A simple data augmentation method for speech recognition. This concept proposed in https://arxiv.org/abs/1904.08779 """ time_axis_length = feature.size(0) freq_axis_length = feature.size(1) time_mask_para = time_axis_length / 20 # Refer to "Specaugment on large scale dataset" paper # time mask for _ in range(self.time_mask_num): t = int(np.random.uniform(low=0.0, high=time_mask_para)) t0 = random.randint(0, time_axis_length - t) feature[t0: t0 + t, :] = 0 # freq mask for _ in range(self.freq_mask_num): f = int(np.random.uniform(low=0.0, high=self.freq_mask_para)) f0 = random.randint(0, freq_axis_length - f) feature[:, f0: f0 + f] = 0 return feature def _get_feature(self, signal: np.ndarray) -> np.ndarray: """ Provides feature extraction Inputs: signal (np.ndarray): audio signal Returns: feature (np.ndarray): feature extract by sub-class """ raise NotImplementedError def _parse_audio(self, audio_path: str, apply_spec_augment: bool) -> Tensor: """ Parses audio. Args: audio_path (str): path of audio file apply_spec_augment (bool): flag indication whether to apply spec augment or not Returns: feature (np.ndarray): feature extract by sub-class """ signal, sr = librosa.load(audio_path, sr=self.sample_rate) feature = self._get_feature(signal) feature -= feature.mean() feature /= np.std(feature) feature = torch.FloatTensor(feature).transpose(0, 1) if apply_spec_augment: feature = self._spec_augment(feature) return feature def _parse_transcript(self, transcript: str) -> list: """ Parses transcript Args: transcript (str): transcript of audio file Returns transcript (list): transcript that added <sos> and <eos> tokens """ tokens = transcript.split(' ') transcript = list() transcript.append(int(self.sos_id)) for token in tokens: transcript.append(int(token)) transcript.append(int(self.eos_id)) return transcript def __getitem__(self, idx): """ Provides paif of audio & transcript """ audio_path = os.path.join(self.dataset_path, self.audio_paths[idx]) feature = self._parse_audio(audio_path, self.spec_augment_flags[idx]) transcript = self._parse_transcript(self.transcripts[idx]) return feature, transcript def shuffle(self): tmp = list(zip(self.audio_paths, self.transcripts, self.spec_augment_flags)) random.shuffle(tmp) self.audio_paths, self.transcripts, self.spec_augment_flags = zip(*tmp) def __len__(self): return len(self.audio_paths) def count(self): return len(self.audio_paths) class FBankDataset(AudioDataset): """ Dataset for filter bank & transcript matching """ def _get_feature(self, signal: np.ndarray) -> np.ndarray: return torchaudio.compliance.kaldi.fbank( Tensor(signal).unsqueeze(0), num_mel_bins=self.num_mels, frame_length=self.frame_length, frame_shift=self.frame_shift, ).transpose(0, 1).numpy() class SpectrogramDataset(AudioDataset): """ Dataset for spectrogram & transcript matching """ def _get_feature(self, signal: np.ndarray) -> np.ndarray: spectrogram = torch.stft( Tensor(signal), self.n_fft, hop_length=self.hop_length, win_length=self.n_fft, window=torch.hamming_window(self.n_fft), center=False, normalized=False, onesided=True ) spectrogram = (spectrogram[:, :, 0].pow(2) + spectrogram[:, :, 1].pow(2)).pow(0.5) spectrogram = np.log1p(spectrogram.numpy()) return spectrogram class MelSpectrogramDataset(AudioDataset): """ Dataset for mel-spectrogram & transcript matching """ def _get_feature(self, signal: np.ndarray) -> np.ndarray: melspectrogram = librosa.feature.melspectrogram( y=signal, sr=self.sample_rate, n_mels=self.num_mels, n_fft=self.n_fft, hop_length=self.hop_length, ) melspectrogram = librosa.power_to_db(melspectrogram, ref=np.max) return melspectrogram class MFCCDataset(AudioDataset): """ Dataset for MFCC & transcript matching """ def _get_feature(self, signal: np.ndarray) -> np.ndarray: return librosa.feature.mfcc( y=signal, sr=self.sample_rate, n_mfcc=self.num_mels, n_fft=self.n_fft, hop_length=self.hop_length, )
[ "librosa.feature.melspectrogram", "random.shuffle", "os.path.join", "librosa.feature.mfcc", "torch.Tensor", "torch.FloatTensor", "librosa.power_to_db", "numpy.random.uniform", "torch.hamming_window", "numpy.std", "random.randint", "librosa.load" ]
[((5936, 5981), 'librosa.load', 'librosa.load', (['audio_path'], {'sr': 'self.sample_rate'}), '(audio_path, sr=self.sample_rate)\n', (5948, 5981), False, 'import librosa\n'), ((6080, 6095), 'numpy.std', 'np.std', (['feature'], {}), '(feature)\n', (6086, 6095), True, 'import numpy as np\n'), ((6896, 6950), 'os.path.join', 'os.path.join', (['self.dataset_path', 'self.audio_paths[idx]'], {}), '(self.dataset_path, self.audio_paths[idx])\n', (6908, 6950), False, 'import os\n'), ((7248, 7267), 'random.shuffle', 'random.shuffle', (['tmp'], {}), '(tmp)\n', (7262, 7267), False, 'import random\n'), ((8647, 8781), 'librosa.feature.melspectrogram', 'librosa.feature.melspectrogram', ([], {'y': 'signal', 'sr': 'self.sample_rate', 'n_mels': 'self.num_mels', 'n_fft': 'self.n_fft', 'hop_length': 'self.hop_length'}), '(y=signal, sr=self.sample_rate, n_mels=self.\n num_mels, n_fft=self.n_fft, hop_length=self.hop_length)\n', (8677, 8781), False, 'import librosa\n'), ((8873, 8920), 'librosa.power_to_db', 'librosa.power_to_db', (['melspectrogram'], {'ref': 'np.max'}), '(melspectrogram, ref=np.max)\n', (8892, 8920), False, 'import librosa\n'), ((9114, 9237), 'librosa.feature.mfcc', 'librosa.feature.mfcc', ([], {'y': 'signal', 'sr': 'self.sample_rate', 'n_mfcc': 'self.num_mels', 'n_fft': 'self.n_fft', 'hop_length': 'self.hop_length'}), '(y=signal, sr=self.sample_rate, n_mfcc=self.num_mels,\n n_fft=self.n_fft, hop_length=self.hop_length)\n', (9134, 9237), False, 'import librosa\n'), ((4911, 4950), 'random.randint', 'random.randint', (['(0)', '(time_axis_length - t)'], {}), '(0, time_axis_length - t)\n', (4925, 4950), False, 'import random\n'), ((5146, 5185), 'random.randint', 'random.randint', (['(0)', '(freq_axis_length - f)'], {}), '(0, freq_axis_length - f)\n', (5160, 5185), False, 'import random\n'), ((8083, 8097), 'torch.Tensor', 'Tensor', (['signal'], {}), '(signal)\n', (8089, 8097), False, 'from torch import Tensor\n'), ((4845, 4892), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.0)', 'high': 'time_mask_para'}), '(low=0.0, high=time_mask_para)\n', (4862, 4892), True, 'import numpy as np\n'), ((5075, 5127), 'numpy.random.uniform', 'np.random.uniform', ([], {'low': '(0.0)', 'high': 'self.freq_mask_para'}), '(low=0.0, high=self.freq_mask_para)\n', (5092, 5127), True, 'import numpy as np\n'), ((6115, 6141), 'torch.FloatTensor', 'torch.FloatTensor', (['feature'], {}), '(feature)\n', (6132, 6141), False, 'import torch\n'), ((8181, 8213), 'torch.hamming_window', 'torch.hamming_window', (['self.n_fft'], {}), '(self.n_fft)\n', (8201, 8213), False, 'import torch\n'), ((7686, 7700), 'torch.Tensor', 'Tensor', (['signal'], {}), '(signal)\n', (7692, 7700), False, 'from torch import Tensor\n')]
import os import argparse import numpy as np import tensorflow as tf from PIL import Image from six.moves import cPickle as pickle def gaussian_filter_(kernel_shape, ax): x = np.zeros(kernel_shape, dtype = float) mid = np.floor(kernel_shape[0] / 2.) for kernel_idx in range(0, kernel_shape[2]): for i in range(0, kernel_shape[0]): for j in range(0, kernel_shape[1]): x[i, j, kernel_idx, 0] = gauss(i - mid, j - mid) return tf.convert_to_tensor(x / np.sum(x), dtype=tf.float32) def gaussian_filter(kernel_shape, ax): # The Gaussian filter of the desired size initialized to zero filter_ = np.zeros(kernel_shape, dtype = float) mid = np.floor(kernel_shape[0] / 2.) # Middle of kernel of Gaussian filter for kernel_idx in range(0, kernel_shape[2]): for i in range(0, kernel_shape[0]): # go on width of Gaussian weighting window for j in range(0, kernel_shape[1]): # go on height of Gaussian weighting window filter_[i, j, kernel_idx, 0] = gauss(i - mid, j - mid) filter_ = filter_ / np.sum(filter_) return tf.convert_to_tensor(filter_, dtype=tf.float32), filter_ def gauss(x, y, sigma=3.0): Z = 2 * np.pi * sigma ** 2 return 1. / Z * np.exp(-(x ** 2 + y ** 2) / (2. * sigma ** 2)) def LecunLCN(X, image_shape, threshold=1e-4, radius=7, use_divisor=True): """ Local Contrast Normalization :param X: tf_train_dataset :param image_shape: [batch_size, image_size, image_size, num_channels] """ # Get Gaussian filter filter_shape = (radius, radius, image_shape[3], 1) # For process visualisation # plt.rcParams['figure.figsize'] = (45.0, 100.0) # f, ax = plt.subplots(nrows= radius * radius + 1, ncols=1) # [i.axis('off') for i in ax] ax = None filters, filters_asarray = gaussian_filter(filter_shape, ax) X = tf.convert_to_tensor(X, dtype=tf.float32) # Compute the Guassian weighted average by means of convolution convout = tf.nn.conv2d(X, filters, [1,1,1,1], 'SAME') # Subtractive step mid = int(np.floor(filter_shape[1] / 2.)) # Make filter dimension broadcastable and subtract centered_X = tf.subtract(X, convout) # Boolean marks whether or not to perform divisive step if use_divisor: # Note that the local variances can be computed by using the centered_X # tensor. If we convolve this with the mean filter, that should give us # the variance at each point. We simply take the square root to get our # denominator # Compute variances sum_sqr_XX = tf.nn.conv2d(tf.square(centered_X), filters, [1,1,1,1], 'SAME') # Take square root to get local standard deviation denom = tf.sqrt(sum_sqr_XX) per_img_mean = tf.reduce_mean(denom) divisor = tf.maximum(per_img_mean, denom) # Divisise step new_X = tf.truediv(centered_X, tf.maximum(divisor, threshold)) else: new_X = centered_X return new_X def init_model(graph, test_dataset, image_index): image_size = 32 num_labels = 11 # 0-9, + blank num_channels = 1 # grayscale patch_size = 5 depth1 = 16 depth2 = 32 depth3 = 64 num_hidden1 = 64 # Input data. tf_test_dataset = tf.placeholder(tf.float32, shape=(1, 32, 32, 1)) # Variables. layer1_weights = tf.get_variable("W1", shape=[patch_size, patch_size, num_channels, depth1], initializer=tf.contrib.layers.xavier_initializer_conv2d()) layer1_biases = tf.Variable(tf.constant(1.0, shape=[depth1]), name='B1') layer2_weights = tf.get_variable("W2", shape=[patch_size, patch_size, depth1, depth2], initializer=tf.contrib.layers.xavier_initializer_conv2d()) layer2_biases = tf.Variable(tf.constant(1.0, shape=[depth2]), name='B2') layer3_weights = tf.get_variable("W3", shape=[patch_size, patch_size, depth2, num_hidden1], initializer=tf.contrib.layers.xavier_initializer_conv2d()) layer3_biases = tf.Variable(tf.constant(1.0, shape=[num_hidden1]), name='B3') s1_w = tf.get_variable("WS1", shape=[num_hidden1, num_labels], initializer=tf.contrib.layers.xavier_initializer()) s1_b = tf.Variable(tf.constant(1.0, shape=[num_labels]), name='BS1') s2_w = tf.get_variable("WS2", shape=[num_hidden1, num_labels], initializer=tf.contrib.layers.xavier_initializer()) s2_b = tf.Variable(tf.constant(1.0, shape=[num_labels]), name='BS2') s3_w = tf.get_variable("WS3", shape=[num_hidden1, num_labels], initializer=tf.contrib.layers.xavier_initializer()) s3_b = tf.Variable(tf.constant(1.0, shape=[num_labels]), name='BS3') s4_w = tf.get_variable("WS4", shape=[num_hidden1, num_labels], initializer=tf.contrib.layers.xavier_initializer()) s4_b = tf.Variable(tf.constant(1.0, shape=[num_labels]), name='BS4') s5_w = tf.get_variable("WS5", shape=[num_hidden1, num_labels], initializer=tf.contrib.layers.xavier_initializer()) s5_b = tf.Variable(tf.constant(1.0, shape=[num_labels]), name='BS5') # Model. def model(data, keep_prob, shape): LCN = LecunLCN(data, shape) conv = tf.nn.conv2d(LCN, layer1_weights, [1,1,1,1], 'VALID', name='C1') hidden = tf.nn.relu(conv + layer1_biases) lrn = tf.nn.local_response_normalization(hidden) sub = tf.nn.max_pool(lrn, [1,2,2,1], [1,2,2,1], 'SAME', name='S2') conv = tf.nn.conv2d(sub, layer2_weights, [1,1,1,1], padding='VALID', name='C3') hidden = tf.nn.relu(conv + layer2_biases) lrn = tf.nn.local_response_normalization(hidden) sub = tf.nn.max_pool(lrn, [1,2,2,1], [1,2,2,1], 'SAME', name='S4') conv = tf.nn.conv2d(sub, layer3_weights, [1,1,1,1], padding='VALID', name='C5') hidden = tf.nn.relu(conv + layer3_biases) hidden = tf.nn.dropout(hidden, keep_prob) shape = hidden.get_shape().as_list() reshape = tf.reshape(hidden, [shape[0], shape[1] * shape[2] * shape[3]]) logits1 = tf.matmul(reshape, s1_w) + s1_b logits2 = tf.matmul(reshape, s2_w) + s2_b logits3 = tf.matmul(reshape, s3_w) + s3_b logits4 = tf.matmul(reshape, s4_w) + s4_b logits5 = tf.matmul(reshape, s5_w) + s5_b return [logits1, logits2, logits3, logits4, logits5] # Training computation. [logits1, logits2, logits3, logits4, logits5] = model(tf_test_dataset, 1, [10, 32, 32, 1]) predict = tf.stack([tf.nn.softmax(logits1), tf.nn.softmax(logits2), tf.nn.softmax(logits3), tf.nn.softmax(logits4), tf.nn.softmax(logits5)]) test_prediction = tf.transpose(tf.argmax(predict, 2)) input_image_array = np.expand_dims(test_dataset[image_index, :, :, :], axis=0) return graph, test_prediction, input_image_array, tf_test_dataset def predict(graph, test_prediction, input_image_array, tf_test_dataset): with tf.Session(graph=graph) as session: saver = tf.train.Saver() saver.restore(session, "./model/CNN_multi2.ckpt") print("Model restored.") print('Initialized') prediction_ = session.run(test_prediction, feed_dict={tf_test_dataset: input_image_array,}) number_house = "".join([str(digit) for digit in prediction_[0, :] if digit != 10]) return number_house def main(filename): pickle_file = './model/SVHN_multi.pickle' with open(pickle_file, 'rb') as f: save = pickle.load(f) test_dataset = save['test_dataset'] test_labels = save['test_labels'] del save # hint to help gc free up memory # print('Test set', test_dataset.shape, test_labels.shape) fullname = os.path.join('./data/test', filename) im = Image.open(fullname) house_num = '' image_index, _ = filename.split(".") image_index = int(image_index) graph = tf.Graph() with graph.as_default(): graph, test_prediction, input_image_array, tf_test_dataset = init_model(graph, test_dataset, image_index) number_house = predict(graph, test_prediction, input_image_array, tf_test_dataset) print("\nNUMBER HOUSE: {}".format(number_house)) if __name__ == '__main__': arg_parser = argparse.ArgumentParser() arg_parser.add_argument("-f", action='store', type=str, dest='FileName', help="Specify file name.") args = arg_parser.parse_args() if args.FileName: file_name = args.FileName main(file_name) else: print("Specify file name")
[ "tensorflow.nn.dropout", "tensorflow.nn.softmax", "tensorflow.reduce_mean", "tensorflow.Graph", "argparse.ArgumentParser", "six.moves.cPickle.load", "tensorflow.placeholder", "tensorflow.Session", "numpy.exp", "tensorflow.matmul", "tensorflow.contrib.layers.xavier_initializer_conv2d", "tensorf...
[((181, 216), 'numpy.zeros', 'np.zeros', (['kernel_shape'], {'dtype': 'float'}), '(kernel_shape, dtype=float)\n', (189, 216), True, 'import numpy as np\n'), ((229, 260), 'numpy.floor', 'np.floor', (['(kernel_shape[0] / 2.0)'], {}), '(kernel_shape[0] / 2.0)\n', (237, 260), True, 'import numpy as np\n'), ((654, 689), 'numpy.zeros', 'np.zeros', (['kernel_shape'], {'dtype': 'float'}), '(kernel_shape, dtype=float)\n', (662, 689), True, 'import numpy as np\n'), ((702, 733), 'numpy.floor', 'np.floor', (['(kernel_shape[0] / 2.0)'], {}), '(kernel_shape[0] / 2.0)\n', (710, 733), True, 'import numpy as np\n'), ((1900, 1941), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['X'], {'dtype': 'tf.float32'}), '(X, dtype=tf.float32)\n', (1920, 1941), True, 'import tensorflow as tf\n'), ((2024, 2070), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['X', 'filters', '[1, 1, 1, 1]', '"""SAME"""'], {}), "(X, filters, [1, 1, 1, 1], 'SAME')\n", (2036, 2070), True, 'import tensorflow as tf\n'), ((2211, 2234), 'tensorflow.subtract', 'tf.subtract', (['X', 'convout'], {}), '(X, convout)\n', (2222, 2234), True, 'import tensorflow as tf\n'), ((3306, 3354), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '(1, 32, 32, 1)'}), '(tf.float32, shape=(1, 32, 32, 1))\n', (3320, 3354), True, 'import tensorflow as tf\n'), ((7068, 7126), 'numpy.expand_dims', 'np.expand_dims', (['test_dataset[image_index, :, :, :]'], {'axis': '(0)'}), '(test_dataset[image_index, :, :, :], axis=0)\n', (7082, 7126), True, 'import numpy as np\n'), ((8049, 8086), 'os.path.join', 'os.path.join', (['"""./data/test"""', 'filename'], {}), "('./data/test', filename)\n", (8061, 8086), False, 'import os\n'), ((8096, 8116), 'PIL.Image.open', 'Image.open', (['fullname'], {}), '(fullname)\n', (8106, 8116), False, 'from PIL import Image\n'), ((8225, 8235), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (8233, 8235), True, 'import tensorflow as tf\n'), ((8569, 8594), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (8592, 8594), False, 'import argparse\n'), ((1099, 1114), 'numpy.sum', 'np.sum', (['filter_'], {}), '(filter_)\n', (1105, 1114), True, 'import numpy as np\n'), ((1126, 1173), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['filter_'], {'dtype': 'tf.float32'}), '(filter_, dtype=tf.float32)\n', (1146, 1173), True, 'import tensorflow as tf\n'), ((1265, 1312), 'numpy.exp', 'np.exp', (['(-(x ** 2 + y ** 2) / (2.0 * sigma ** 2))'], {}), '(-(x ** 2 + y ** 2) / (2.0 * sigma ** 2))\n', (1271, 1312), True, 'import numpy as np\n'), ((2106, 2137), 'numpy.floor', 'np.floor', (['(filter_shape[1] / 2.0)'], {}), '(filter_shape[1] / 2.0)\n', (2114, 2137), True, 'import numpy as np\n'), ((2768, 2787), 'tensorflow.sqrt', 'tf.sqrt', (['sum_sqr_XX'], {}), '(sum_sqr_XX)\n', (2775, 2787), True, 'import tensorflow as tf\n'), ((2812, 2833), 'tensorflow.reduce_mean', 'tf.reduce_mean', (['denom'], {}), '(denom)\n', (2826, 2833), True, 'import tensorflow as tf\n'), ((2852, 2883), 'tensorflow.maximum', 'tf.maximum', (['per_img_mean', 'denom'], {}), '(per_img_mean, denom)\n', (2862, 2883), True, 'import tensorflow as tf\n'), ((3641, 3673), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[depth1]'}), '(1.0, shape=[depth1])\n', (3652, 3673), True, 'import tensorflow as tf\n'), ((3946, 3978), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[depth2]'}), '(1.0, shape=[depth2])\n', (3957, 3978), True, 'import tensorflow as tf\n'), ((4256, 4293), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[num_hidden1]'}), '(1.0, shape=[num_hidden1])\n', (4267, 4293), True, 'import tensorflow as tf\n'), ((4478, 4514), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[num_labels]'}), '(1.0, shape=[num_labels])\n', (4489, 4514), True, 'import tensorflow as tf\n'), ((4699, 4735), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[num_labels]'}), '(1.0, shape=[num_labels])\n', (4710, 4735), True, 'import tensorflow as tf\n'), ((4920, 4956), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[num_labels]'}), '(1.0, shape=[num_labels])\n', (4931, 4956), True, 'import tensorflow as tf\n'), ((5141, 5177), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[num_labels]'}), '(1.0, shape=[num_labels])\n', (5152, 5177), True, 'import tensorflow as tf\n'), ((5361, 5397), 'tensorflow.constant', 'tf.constant', (['(1.0)'], {'shape': '[num_labels]'}), '(1.0, shape=[num_labels])\n', (5372, 5397), True, 'import tensorflow as tf\n'), ((5517, 5584), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['LCN', 'layer1_weights', '[1, 1, 1, 1]', '"""VALID"""'], {'name': '"""C1"""'}), "(LCN, layer1_weights, [1, 1, 1, 1], 'VALID', name='C1')\n", (5529, 5584), True, 'import tensorflow as tf\n'), ((5599, 5631), 'tensorflow.nn.relu', 'tf.nn.relu', (['(conv + layer1_biases)'], {}), '(conv + layer1_biases)\n', (5609, 5631), True, 'import tensorflow as tf\n'), ((5646, 5688), 'tensorflow.nn.local_response_normalization', 'tf.nn.local_response_normalization', (['hidden'], {}), '(hidden)\n', (5680, 5688), True, 'import tensorflow as tf\n'), ((5703, 5769), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['lrn', '[1, 2, 2, 1]', '[1, 2, 2, 1]', '"""SAME"""'], {'name': '"""S2"""'}), "(lrn, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME', name='S2')\n", (5717, 5769), True, 'import tensorflow as tf\n'), ((5779, 5854), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['sub', 'layer2_weights', '[1, 1, 1, 1]'], {'padding': '"""VALID"""', 'name': '"""C3"""'}), "(sub, layer2_weights, [1, 1, 1, 1], padding='VALID', name='C3')\n", (5791, 5854), True, 'import tensorflow as tf\n'), ((5869, 5901), 'tensorflow.nn.relu', 'tf.nn.relu', (['(conv + layer2_biases)'], {}), '(conv + layer2_biases)\n', (5879, 5901), True, 'import tensorflow as tf\n'), ((5916, 5958), 'tensorflow.nn.local_response_normalization', 'tf.nn.local_response_normalization', (['hidden'], {}), '(hidden)\n', (5950, 5958), True, 'import tensorflow as tf\n'), ((5973, 6039), 'tensorflow.nn.max_pool', 'tf.nn.max_pool', (['lrn', '[1, 2, 2, 1]', '[1, 2, 2, 1]', '"""SAME"""'], {'name': '"""S4"""'}), "(lrn, [1, 2, 2, 1], [1, 2, 2, 1], 'SAME', name='S4')\n", (5987, 6039), True, 'import tensorflow as tf\n'), ((6049, 6124), 'tensorflow.nn.conv2d', 'tf.nn.conv2d', (['sub', 'layer3_weights', '[1, 1, 1, 1]'], {'padding': '"""VALID"""', 'name': '"""C5"""'}), "(sub, layer3_weights, [1, 1, 1, 1], padding='VALID', name='C5')\n", (6061, 6124), True, 'import tensorflow as tf\n'), ((6139, 6171), 'tensorflow.nn.relu', 'tf.nn.relu', (['(conv + layer3_biases)'], {}), '(conv + layer3_biases)\n', (6149, 6171), True, 'import tensorflow as tf\n'), ((6189, 6221), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['hidden', 'keep_prob'], {}), '(hidden, keep_prob)\n', (6202, 6221), True, 'import tensorflow as tf\n'), ((6285, 6347), 'tensorflow.reshape', 'tf.reshape', (['hidden', '[shape[0], shape[1] * shape[2] * shape[3]]'], {}), '(hidden, [shape[0], shape[1] * shape[2] * shape[3]])\n', (6295, 6347), True, 'import tensorflow as tf\n'), ((7021, 7042), 'tensorflow.argmax', 'tf.argmax', (['predict', '(2)'], {}), '(predict, 2)\n', (7030, 7042), True, 'import tensorflow as tf\n'), ((7283, 7306), 'tensorflow.Session', 'tf.Session', ([], {'graph': 'graph'}), '(graph=graph)\n', (7293, 7306), True, 'import tensorflow as tf\n'), ((7335, 7351), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (7349, 7351), True, 'import tensorflow as tf\n'), ((7814, 7828), 'six.moves.cPickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7825, 7828), True, 'from six.moves import cPickle as pickle\n'), ((504, 513), 'numpy.sum', 'np.sum', (['x'], {}), '(x)\n', (510, 513), True, 'import numpy as np\n'), ((2641, 2662), 'tensorflow.square', 'tf.square', (['centered_X'], {}), '(centered_X)\n', (2650, 2662), True, 'import tensorflow as tf\n'), ((2947, 2977), 'tensorflow.maximum', 'tf.maximum', (['divisor', 'threshold'], {}), '(divisor, threshold)\n', (2957, 2977), True, 'import tensorflow as tf\n'), ((3562, 3607), 'tensorflow.contrib.layers.xavier_initializer_conv2d', 'tf.contrib.layers.xavier_initializer_conv2d', ([], {}), '()\n', (3605, 3607), True, 'import tensorflow as tf\n'), ((3867, 3912), 'tensorflow.contrib.layers.xavier_initializer_conv2d', 'tf.contrib.layers.xavier_initializer_conv2d', ([], {}), '()\n', (3910, 3912), True, 'import tensorflow as tf\n'), ((4177, 4222), 'tensorflow.contrib.layers.xavier_initializer_conv2d', 'tf.contrib.layers.xavier_initializer_conv2d', ([], {}), '()\n', (4220, 4222), True, 'import tensorflow as tf\n'), ((4415, 4453), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (4451, 4453), True, 'import tensorflow as tf\n'), ((4636, 4674), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (4672, 4674), True, 'import tensorflow as tf\n'), ((4857, 4895), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (4893, 4895), True, 'import tensorflow as tf\n'), ((5078, 5116), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (5114, 5116), True, 'import tensorflow as tf\n'), ((5298, 5336), 'tensorflow.contrib.layers.xavier_initializer', 'tf.contrib.layers.xavier_initializer', ([], {}), '()\n', (5334, 5336), True, 'import tensorflow as tf\n'), ((6367, 6391), 'tensorflow.matmul', 'tf.matmul', (['reshape', 's1_w'], {}), '(reshape, s1_w)\n', (6376, 6391), True, 'import tensorflow as tf\n'), ((6417, 6441), 'tensorflow.matmul', 'tf.matmul', (['reshape', 's2_w'], {}), '(reshape, s2_w)\n', (6426, 6441), True, 'import tensorflow as tf\n'), ((6467, 6491), 'tensorflow.matmul', 'tf.matmul', (['reshape', 's3_w'], {}), '(reshape, s3_w)\n', (6476, 6491), True, 'import tensorflow as tf\n'), ((6517, 6541), 'tensorflow.matmul', 'tf.matmul', (['reshape', 's4_w'], {}), '(reshape, s4_w)\n', (6526, 6541), True, 'import tensorflow as tf\n'), ((6567, 6591), 'tensorflow.matmul', 'tf.matmul', (['reshape', 's5_w'], {}), '(reshape, s5_w)\n', (6576, 6591), True, 'import tensorflow as tf\n'), ((6814, 6836), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits1'], {}), '(logits1)\n', (6827, 6836), True, 'import tensorflow as tf\n'), ((6838, 6860), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits2'], {}), '(logits2)\n', (6851, 6860), True, 'import tensorflow as tf\n'), ((6886, 6908), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits3'], {}), '(logits3)\n', (6899, 6908), True, 'import tensorflow as tf\n'), ((6910, 6932), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits4'], {}), '(logits4)\n', (6923, 6932), True, 'import tensorflow as tf\n'), ((6958, 6980), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits5'], {}), '(logits5)\n', (6971, 6980), True, 'import tensorflow as tf\n')]
""" Quintic Polynomials Planner author: <NAME> (@Atsushi_twi) Ref: - [Local Path planning And Motion Control For Agv In Positioning](http://ieeexplore.ieee.org/document/637936/) The MIT License (MIT) Copyright (c) 2016 - 2021 <NAME> 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. """ import math from collections import namedtuple import matplotlib.pyplot as plt import numpy as np from roboticstoolbox.mobile.PlannerBase import PlannerBase # parameter show_animation = True class QuinticPolynomial: def __init__(self, xs, vxs, axs, xe, vxe, axe, time): # calc coefficient of quintic polynomial # See jupyter notebook document for derivation of this equation. self.a0 = xs self.a1 = vxs self.a2 = axs / 2.0 A = np.array([[time ** 3, time ** 4, time ** 5], [3 * time ** 2, 4 * time ** 3, 5 * time ** 4], [6 * time, 12 * time ** 2, 20 * time ** 3]]) b = np.array([xe - self.a0 - self.a1 * time - self.a2 * time ** 2, vxe - self.a1 - 2 * self.a2 * time, axe - 2 * self.a2]) x = np.linalg.solve(A, b) self.a3 = x[0] self.a4 = x[1] self.a5 = x[2] def calc_point(self, t): xt = self.a0 + self.a1 * t + self.a2 * t ** 2 + \ self.a3 * t ** 3 + self.a4 * t ** 4 + self.a5 * t ** 5 return xt def calc_first_derivative(self, t): xt = self.a1 + 2 * self.a2 * t + \ 3 * self.a3 * t ** 2 + 4 * self.a4 * t ** 3 + 5 * self.a5 * t ** 4 return xt def calc_second_derivative(self, t): xt = 2 * self.a2 + 6 * self.a3 * t + 12 * self.a4 * t ** 2 + 20 * self.a5 * t ** 3 return xt def calc_third_derivative(self, t): xt = 6 * self.a3 + 24 * self.a4 * t + 60 * self.a5 * t ** 2 return xt def quintic_polynomials_planner(sx, sy, syaw, sv, sa, gx, gy, gyaw, gv, ga, max_accel, max_jerk, dt, MIN_T, MAX_T): """ quintic polynomial planner input s_x: start x position [m] s_y: start y position [m] s_yaw: start yaw angle [rad] sa: start accel [m/ss] gx: goal x position [m] gy: goal y position [m] gyaw: goal yaw angle [rad] ga: goal accel [m/ss] max_accel: maximum accel [m/ss] max_jerk: maximum jerk [m/sss] dt: time tick [s] return time: time result rx: x position result list ry: y position result list ryaw: yaw angle result list rv: velocity result list ra: accel result list """ vxs = sv * math.cos(syaw) vys = sv * math.sin(syaw) vxg = gv * math.cos(gyaw) vyg = gv * math.sin(gyaw) axs = sa * math.cos(syaw) ays = sa * math.sin(syaw) axg = ga * math.cos(gyaw) ayg = ga * math.sin(gyaw) time, rx, ry, ryaw, rv, ra, rj = [], [], [], [], [], [], [] for T in np.arange(MIN_T, MAX_T, MIN_T): xqp = QuinticPolynomial(sx, vxs, axs, gx, vxg, axg, T) yqp = QuinticPolynomial(sy, vys, ays, gy, vyg, ayg, T) time, rx, ry, ryaw, rv, ra, rj = [], [], [], [], [], [], [] for t in np.arange(0.0, T + dt, dt): time.append(t) rx.append(xqp.calc_point(t)) ry.append(yqp.calc_point(t)) vx = xqp.calc_first_derivative(t) vy = yqp.calc_first_derivative(t) v = np.hypot(vx, vy) yaw = math.atan2(vy, vx) rv.append(v) ryaw.append(yaw) ax = xqp.calc_second_derivative(t) ay = yqp.calc_second_derivative(t) a = np.hypot(ax, ay) if len(rv) >= 2 and rv[-1] - rv[-2] < 0.0: a *= -1 ra.append(a) jx = xqp.calc_third_derivative(t) jy = yqp.calc_third_derivative(t) j = np.hypot(jx, jy) if len(ra) >= 2 and ra[-1] - ra[-2] < 0.0: j *= -1 rj.append(j) if max([abs(i) for i in ra]) <= max_accel and max([abs(i) for i in rj]) <= max_jerk: print("find path!!") break return time, np.c_[rx, ry, ryaw], rv, ra, rj class QuinticPolyPlanner(PlannerBase): r""" Quintic polynomial path planner :param dt: time step, defaults to 0.1 :type dt: float, optional :param start_vel: initial velocity, defaults to 0 :type start_vel: float, optional :param start_acc: initial acceleration, defaults to 0 :type start_acc: float, optional :param goal_vel: goal velocity, defaults to 0 :type goal_vel: float, optional :param goal_acc: goal acceleration, defaults to 0 :type goal_acc: float, optional :param max_acc: [description], defaults to 1 :type max_acc: int, optional :param max_jerk: maximum jerk, defaults to 0.5 :type min_t: float, optional :param min_t: minimum path time, defaults to 5 :type max_t: float, optional :param max_t: maximum path time, defaults to 100 :type max_jerk: float, optional :return: Quintic polynomial path planner :rtype: QuinticPolyPlanner instance ================== ======================== Feature Capability ================== ======================== Plan Configuration space Obstacle avoidance No Curvature Continuous Motion Forwards only ================== ======================== Creates a planner that finds the path between two configurations in the plane using forward motion only. The path is a continuous quintic polynomial for x and y .. math:: x(t) &= a_0 + a_1 t + a_2 t^2 + a_3 t^3 + a_4 t^4 + a_5 t^5 \\ y(t) &= b_0 + b_1 t + b_2 t^2 + b_3 t^3 + b_4 t^4 + b_5 t^5 :reference: "Local Path Planning And Motion Control For AGV In Positioning", Takahashi, T. Hongo, <NAME> and <NAME>; Proceedings. IEEE/RSJ International Workshop on Intelligent Robots and Systems (IROS '89) doi: 10.1109/IROS.1989.637936 .. note:: The path time is searched in the interval [``min_t``, `max_t`] in steps of ``min_t``. :seealso: :class:`Planner` """ def __init__(self, dt=0.1, start_vel=0, start_acc=0, goal_vel=0, goal_acc=0, max_acc=1, max_jerk=0.5, min_t=5, max_t=100): super().__init__(ndims=3) self.dt = dt self.start_vel = start_vel self.start_acc = start_acc self.goal_vel = goal_vel self.goal_acc = goal_acc self.max_acc = max_acc self.max_jerk = max_jerk self.min_t = min_t self.max_t = max_t def query(self, start, goal): r""" Find a quintic polynomial path :param start: start configuration :math:`(x, y, \theta)` :type start: array_like(3), optional :param goal: goal configuration :math:`(x, y, \theta)` :type goal: array_like(3), optional :return: path and status :rtype: ndarray(N,3), namedtuple The returned status value has elements: ========== =================================================== Element Description ========== =================================================== ``t`` time to execute the path ``vel`` velocity profile along the path ``accel`` acceleration profile along the path ``jerk`` jerk profile along the path ========== =================================================== :seealso: :meth:`Planner.query` """ self._start = start self._goal = goal time, path, v, a, j = quintic_polynomials_planner( start[0], start[1], start[2], self.start_vel, self.start_acc, goal[0], goal[1], goal[2], self.start_vel, self.start_acc, self.max_acc, self.max_jerk, dt=self.dt, MIN_T=self.min_t, MAX_T=self.max_t) status = namedtuple('QuinticPolyStatus', ['t', 'vel', 'acc', 'jerk'])( time, v, a, j) return path, status if __name__ == '__main__': from math import pi start = (10, 10, np.deg2rad(10.0)) goal = (30, -10, np.deg2rad(20.0)) quintic = QuinticPolyPlanner(start_vel=1) path, status = quintic.query(start, goal) print(status) quintic.plot(path) plt.figure() plt.subplot(311) plt.plot(status.t, status.vel, "-r") plt.ylabel("velocity (m/s)") plt.grid(True) plt.subplot(312) plt.plot(status.t, status.acc, "-r") plt.ylabel("accel (m/s2)") plt.grid(True) plt.subplot(313) plt.plot(status.t, status.jerk, "-r") plt.xlabel("Time (s)") plt.ylabel("jerk (m/s3)") plt.grid(True) plt.show(block=True)
[ "matplotlib.pyplot.grid", "numpy.linalg.solve", "collections.namedtuple", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "math.cos", "numpy.array", "matplotlib.pyplot.figure", "numpy.deg2rad", "math.atan2", "numpy.hypot", "math.sin", "matplotlib.pyplot.su...
[((3466, 3496), 'numpy.arange', 'np.arange', (['MIN_T', 'MAX_T', 'MIN_T'], {}), '(MIN_T, MAX_T, MIN_T)\n', (3475, 3496), True, 'import numpy as np\n'), ((8902, 8914), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (8912, 8914), True, 'import matplotlib.pyplot as plt\n'), ((8919, 8935), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(311)'], {}), '(311)\n', (8930, 8935), True, 'import matplotlib.pyplot as plt\n'), ((8940, 8976), 'matplotlib.pyplot.plot', 'plt.plot', (['status.t', 'status.vel', '"""-r"""'], {}), "(status.t, status.vel, '-r')\n", (8948, 8976), True, 'import matplotlib.pyplot as plt\n'), ((8981, 9009), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""velocity (m/s)"""'], {}), "('velocity (m/s)')\n", (8991, 9009), True, 'import matplotlib.pyplot as plt\n'), ((9014, 9028), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (9022, 9028), True, 'import matplotlib.pyplot as plt\n'), ((9034, 9050), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(312)'], {}), '(312)\n', (9045, 9050), True, 'import matplotlib.pyplot as plt\n'), ((9055, 9091), 'matplotlib.pyplot.plot', 'plt.plot', (['status.t', 'status.acc', '"""-r"""'], {}), "(status.t, status.acc, '-r')\n", (9063, 9091), True, 'import matplotlib.pyplot as plt\n'), ((9096, 9122), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""accel (m/s2)"""'], {}), "('accel (m/s2)')\n", (9106, 9122), True, 'import matplotlib.pyplot as plt\n'), ((9127, 9141), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (9135, 9141), True, 'import matplotlib.pyplot as plt\n'), ((9147, 9163), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(313)'], {}), '(313)\n', (9158, 9163), True, 'import matplotlib.pyplot as plt\n'), ((9168, 9205), 'matplotlib.pyplot.plot', 'plt.plot', (['status.t', 'status.jerk', '"""-r"""'], {}), "(status.t, status.jerk, '-r')\n", (9176, 9205), True, 'import matplotlib.pyplot as plt\n'), ((9210, 9232), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Time (s)"""'], {}), "('Time (s)')\n", (9220, 9232), True, 'import matplotlib.pyplot as plt\n'), ((9237, 9262), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""jerk (m/s3)"""'], {}), "('jerk (m/s3)')\n", (9247, 9262), True, 'import matplotlib.pyplot as plt\n'), ((9267, 9281), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (9275, 9281), True, 'import matplotlib.pyplot as plt\n'), ((9287, 9307), 'matplotlib.pyplot.show', 'plt.show', ([], {'block': '(True)'}), '(block=True)\n', (9295, 9307), True, 'import matplotlib.pyplot as plt\n'), ((1293, 1433), 'numpy.array', 'np.array', (['[[time ** 3, time ** 4, time ** 5], [3 * time ** 2, 4 * time ** 3, 5 * time **\n 4], [6 * time, 12 * time ** 2, 20 * time ** 3]]'], {}), '([[time ** 3, time ** 4, time ** 5], [3 * time ** 2, 4 * time ** 3,\n 5 * time ** 4], [6 * time, 12 * time ** 2, 20 * time ** 3]])\n', (1301, 1433), True, 'import numpy as np\n'), ((1486, 1609), 'numpy.array', 'np.array', (['[xe - self.a0 - self.a1 * time - self.a2 * time ** 2, vxe - self.a1 - 2 *\n self.a2 * time, axe - 2 * self.a2]'], {}), '([xe - self.a0 - self.a1 * time - self.a2 * time ** 2, vxe - self.\n a1 - 2 * self.a2 * time, axe - 2 * self.a2])\n', (1494, 1609), True, 'import numpy as np\n'), ((1661, 1682), 'numpy.linalg.solve', 'np.linalg.solve', (['A', 'b'], {}), '(A, b)\n', (1676, 1682), True, 'import numpy as np\n'), ((3161, 3175), 'math.cos', 'math.cos', (['syaw'], {}), '(syaw)\n', (3169, 3175), False, 'import math\n'), ((3191, 3205), 'math.sin', 'math.sin', (['syaw'], {}), '(syaw)\n', (3199, 3205), False, 'import math\n'), ((3221, 3235), 'math.cos', 'math.cos', (['gyaw'], {}), '(gyaw)\n', (3229, 3235), False, 'import math\n'), ((3251, 3265), 'math.sin', 'math.sin', (['gyaw'], {}), '(gyaw)\n', (3259, 3265), False, 'import math\n'), ((3282, 3296), 'math.cos', 'math.cos', (['syaw'], {}), '(syaw)\n', (3290, 3296), False, 'import math\n'), ((3312, 3326), 'math.sin', 'math.sin', (['syaw'], {}), '(syaw)\n', (3320, 3326), False, 'import math\n'), ((3342, 3356), 'math.cos', 'math.cos', (['gyaw'], {}), '(gyaw)\n', (3350, 3356), False, 'import math\n'), ((3372, 3386), 'math.sin', 'math.sin', (['gyaw'], {}), '(gyaw)\n', (3380, 3386), False, 'import math\n'), ((3711, 3737), 'numpy.arange', 'np.arange', (['(0.0)', '(T + dt)', 'dt'], {}), '(0.0, T + dt, dt)\n', (3720, 3737), True, 'import numpy as np\n'), ((8705, 8721), 'numpy.deg2rad', 'np.deg2rad', (['(10.0)'], {}), '(10.0)\n', (8715, 8721), True, 'import numpy as np\n'), ((8744, 8760), 'numpy.deg2rad', 'np.deg2rad', (['(20.0)'], {}), '(20.0)\n', (8754, 8760), True, 'import numpy as np\n'), ((3957, 3973), 'numpy.hypot', 'np.hypot', (['vx', 'vy'], {}), '(vx, vy)\n', (3965, 3973), True, 'import numpy as np\n'), ((3992, 4010), 'math.atan2', 'math.atan2', (['vy', 'vx'], {}), '(vy, vx)\n', (4002, 4010), False, 'import math\n'), ((4176, 4192), 'numpy.hypot', 'np.hypot', (['ax', 'ay'], {}), '(ax, ay)\n', (4184, 4192), True, 'import numpy as np\n'), ((4406, 4422), 'numpy.hypot', 'np.hypot', (['jx', 'jy'], {}), '(jx, jy)\n', (4414, 4422), True, 'import numpy as np\n'), ((8501, 8561), 'collections.namedtuple', 'namedtuple', (['"""QuinticPolyStatus"""', "['t', 'vel', 'acc', 'jerk']"], {}), "('QuinticPolyStatus', ['t', 'vel', 'acc', 'jerk'])\n", (8511, 8561), False, 'from collections import namedtuple\n')]
from matplotlib import get_backend import pendsim, pytest import numpy as np @pytest.fixture def pend(): return pendsim.sim.Pendulum(3.0, 1.0, 2.0) @pytest.fixture def BangBang(): return pendsim.controller.BangBang(0, 10) @pytest.fixture def PID(): return pendsim.controller.PID(1, 1, 1) @pytest.fixture def LQR(pend): Q = np.diag([1, 1, 1, 1]) R = np.atleast_2d([1]) return pendsim.controller.LQR(pend, 0.01, 10, Q, R) @pytest.fixture def NoController(): return pendsim.controller.NoController() @pytest.fixture def policy_args(): return (np.array([0.1, 0.0, 2.11, 0.02]), 0.02) def test_policy_BangBang(BangBang, policy_args): policy_output = BangBang.policy(*policy_args) assert type(policy_output) == tuple assert type(policy_output[0]) == float or type(policy_output[0]) == np.float64 assert type(policy_output[1]) == dict def test_policy_PID(PID, policy_args): policy_output = PID.policy(*policy_args) assert type(policy_output) == tuple assert type(policy_output[0]) == float or type(policy_output[0]) == np.float64 assert type(policy_output[1]) == dict def test_policy_LQR(LQR, policy_args): policy_output = LQR.policy(*policy_args) assert type(policy_output) == tuple assert type(policy_output[0]) == float or type(policy_output[0]) == np.float64 assert type(policy_output[1]) == dict def test_policy_NoController(NoController, policy_args): policy_output = NoController.policy(*policy_args) assert type(policy_output) == tuple assert type(policy_output[0]) == float or type(policy_output[0]) == np.float64 assert type(policy_output[1]) == dict
[ "numpy.atleast_2d", "pendsim.controller.LQR", "pendsim.controller.PID", "numpy.diag", "pendsim.sim.Pendulum", "numpy.array", "pendsim.controller.NoController", "pendsim.controller.BangBang" ]
[((118, 153), 'pendsim.sim.Pendulum', 'pendsim.sim.Pendulum', (['(3.0)', '(1.0)', '(2.0)'], {}), '(3.0, 1.0, 2.0)\n', (138, 153), False, 'import pendsim, pytest\n'), ((199, 233), 'pendsim.controller.BangBang', 'pendsim.controller.BangBang', (['(0)', '(10)'], {}), '(0, 10)\n', (226, 233), False, 'import pendsim, pytest\n'), ((274, 305), 'pendsim.controller.PID', 'pendsim.controller.PID', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (296, 305), False, 'import pendsim, pytest\n'), ((347, 368), 'numpy.diag', 'np.diag', (['[1, 1, 1, 1]'], {}), '([1, 1, 1, 1])\n', (354, 368), True, 'import numpy as np\n'), ((377, 395), 'numpy.atleast_2d', 'np.atleast_2d', (['[1]'], {}), '([1])\n', (390, 395), True, 'import numpy as np\n'), ((407, 451), 'pendsim.controller.LQR', 'pendsim.controller.LQR', (['pend', '(0.01)', '(10)', 'Q', 'R'], {}), '(pend, 0.01, 10, Q, R)\n', (429, 451), False, 'import pendsim, pytest\n'), ((501, 534), 'pendsim.controller.NoController', 'pendsim.controller.NoController', ([], {}), '()\n', (532, 534), False, 'import pendsim, pytest\n'), ((584, 616), 'numpy.array', 'np.array', (['[0.1, 0.0, 2.11, 0.02]'], {}), '([0.1, 0.0, 2.11, 0.02])\n', (592, 616), True, 'import numpy as np\n')]
"""Look up labels for a segmentation This uses the structure for the Allen Brain Atlas to find the labels associated with a reference segmentation for a list of points """ import numpy as np from .utils.warp import Warper def get_segment_ids(segmentation, fixed_pts, moving_pts, lookup_pts, warp_args={}, decimation=None): """Find the segment ID for every point in lookup_pts :param segmentation: a reference segmentation in the fixed space :param fixed_pts: keypoints in the fixed space :param moving_pts: corresponding keypoints in the moving space :param lookup_pts: look up the segment IDs for these points :param warp_args: keyword arguments for the warper (see nuggt.warp.Warper) :param decimation: downsample the fixed segmentation by this amount when creating the cubic splines from the thin-plate ones. Defaults to breaking the destination space into at least 5 blocks in each direction. :returns: a vector of segment ID per lookup point """ if decimation is None: decimation = max(1, np.min(segmentation.shape) // 5) inputs = [ np.arange(0, segmentation.shape[_] + decimation - 1, decimation) for _ in range(3)] warper = Warper(moving_pts, fixed_pts, *warp_args).approximate(*inputs) return get_segment_ids_using_warper(segmentation, warper, lookup_pts) def get_segment_ids_using_warper(segmentation, warper, lookup_pts): """Get segment IDs per lookup point, giving a transform function :param segmentation: the segmentation in the reference space :param warper: a function object that can be called with a list of lookup points to return their location in the reference space :param lookup_pts: look up the segment IDs for these points :returns: a vector of segment ID per lookup point """ reference_pts = np.round(warper(lookup_pts), 0).astype(np.int32) result = np.zeros(len(reference_pts), segmentation.dtype) mask = \ (~ np.any(np.isnan(reference_pts), 1)) &\ np.all(reference_pts >= 0, 1) &\ (reference_pts[:, 0] < segmentation.shape[0]) &\ (reference_pts[:, 1] < segmentation.shape[1]) &\ (reference_pts[:, 2] < segmentation.shape[2]) result[mask] = segmentation[reference_pts[mask, 0], reference_pts[mask, 1], reference_pts[mask, 2]] return result
[ "numpy.all", "numpy.isnan", "numpy.arange", "numpy.min" ]
[((1131, 1195), 'numpy.arange', 'np.arange', (['(0)', '(segmentation.shape[_] + decimation - 1)', 'decimation'], {}), '(0, segmentation.shape[_] + decimation - 1, decimation)\n', (1140, 1195), True, 'import numpy as np\n'), ((1075, 1101), 'numpy.min', 'np.min', (['segmentation.shape'], {}), '(segmentation.shape)\n', (1081, 1101), True, 'import numpy as np\n'), ((2080, 2109), 'numpy.all', 'np.all', (['(reference_pts >= 0)', '(1)'], {}), '(reference_pts >= 0, 1)\n', (2086, 2109), True, 'import numpy as np\n'), ((2040, 2063), 'numpy.isnan', 'np.isnan', (['reference_pts'], {}), '(reference_pts)\n', (2048, 2063), True, 'import numpy as np\n')]
import torch.utils.data as data import os import os.path from scipy.ndimage import imread import numpy as np from skimage import color import random #from matlab_imresize.imresize import * # import matlab_imresize from skimage import img_as_float from skimage.measure import compare_ssim,compare_psnr def BayesSR_loader(root, im_path, video_name, task, task_param, # DownResizer=None,UpResizer=None, input_frame_size = ( 128,128,3)): # if task == 'denoise': # root_input = os.path.join(root,'input',im_path) # else: root_input = os.path.join(root,video_name, 'bicubic') root_target =os.path.join(root,video_name, 'original') # path_y_ = os.path.join(root,'target_ours',im_path) # frame_prefix = im_path path = [] im = [] target = [] cur_idex = int(im_path[-6:-4]) for i in range(0,7): temp = os.path.join(root_input, im_path[:-6]+ str((cur_idex-3+i)).zfill(2)+im_path[-4:]) path.append(temp) # if video_name == 'foliage': # print("") for i in range(0,7): if os.path.exists(path[i]): im.append(imread(path[i])) else: im.append(imread(path[3])) target = imread(os.path.join(root_target,im_path )) if task == 'sr': # for i in range(0,7): # step 1: turn to low resolution #temp = img_as_float(im[i]) # ratio = task_param[0] #temp = imresize(temp,1/ratio) #temp = convertDouble2Byte(temp) # temp = im[i] # step 2: preprocess for network # temp = img_as_float(temp) # temp = imresize(temp,ratio) # temp = UpResizer.imresize(temp) # temp = convertDouble2Byte(temp) # im[i] = temp print(compare_psnr(im[3],target)) elif task=='denoise': # for i in range(0,7): # temp = im[i] #sigma = task_param[0] #gaussian_noise = np.clip(np.random.normal(0.0, sigma * 255.0, input_frame_size), 0, 255).astype("uint8") #temp = np.clip(temp.astype("uint32") + gaussian_noise.astype("uint32"), 0, 255).astype("uint8") #b = np.clip((np.random.rand(input_frame_size[0],input_frame_size[1], input_frame_size[2]) * 255.0), 0, 255).astype("uint8") #p = task_param[1] #tm = np.random.rand(input_frame_size[0], input_frame_size[1] ) <= p #tm = np.stack((tm, tm, tm), axis=2) #temp[tm] = b[tm] #im[i] = temp print(compare_psnr(im[3],target)) pass elif task== 'deblock': for i in range(0,7): temp = img_as_float(im[i]) raise("not implemented for deblock") for i in range(0,7): im[i] = np.transpose(im[i],(2,0,1)) target= np.transpose(target,(2,0,1)) return [im[i].astype("float32")/255.0 for i in range(0,7)], target.astype("float32")/255.0 class ListDataset(data.Dataset): def __init__(self, root, path_list,videos_list, task = 'sr', task_param = [4.0], loader=BayesSR_loader): #transform=None, target_transform=None, co_transform=None, self.root = root self.videos_list = videos_list self.path_list = path_list # self.transform = transform # self.target_transform = target_transform # self.co_transform = co_transform self.loader = loader self.task = task self.task_param = task_param print("task is " + task," with parameter " ) print(task_param) # if task == 'sr': # self.DownResizer = matlab_imresize.Imresize((256,448,3),1/task_param[0]) # self.UpResizer = matlab_imresize.Imresize((256/task_param[0],448/task_param[0],3),task_param[0]) # self.DownResizer # self.task_param += self.UpResizer def __getitem__(self, index): path = self.path_list[index] video = self.videos_list[index] # print(path) Xs,y, = self.loader(self.root, path,video, self.task, self.task_param) return Xs,y,path,video def __len__(self): return len(self.path_list)
[ "os.path.exists", "os.path.join", "skimage.img_as_float", "scipy.ndimage.imread", "skimage.measure.compare_psnr", "numpy.transpose" ]
[((594, 635), 'os.path.join', 'os.path.join', (['root', 'video_name', '"""bicubic"""'], {}), "(root, video_name, 'bicubic')\n", (606, 635), False, 'import os\n'), ((652, 694), 'os.path.join', 'os.path.join', (['root', 'video_name', '"""original"""'], {}), "(root, video_name, 'original')\n", (664, 694), False, 'import os\n'), ((2873, 2904), 'numpy.transpose', 'np.transpose', (['target', '(2, 0, 1)'], {}), '(target, (2, 0, 1))\n', (2885, 2904), True, 'import numpy as np\n'), ((1132, 1155), 'os.path.exists', 'os.path.exists', (['path[i]'], {}), '(path[i])\n', (1146, 1155), False, 'import os\n'), ((1274, 1308), 'os.path.join', 'os.path.join', (['root_target', 'im_path'], {}), '(root_target, im_path)\n', (1286, 1308), False, 'import os\n'), ((2833, 2863), 'numpy.transpose', 'np.transpose', (['im[i]', '(2, 0, 1)'], {}), '(im[i], (2, 0, 1))\n', (2845, 2863), True, 'import numpy as np\n'), ((1859, 1886), 'skimage.measure.compare_psnr', 'compare_psnr', (['im[3]', 'target'], {}), '(im[3], target)\n', (1871, 1886), False, 'from skimage.measure import compare_ssim, compare_psnr\n'), ((1179, 1194), 'scipy.ndimage.imread', 'imread', (['path[i]'], {}), '(path[i])\n', (1185, 1194), False, 'from scipy.ndimage import imread\n'), ((1232, 1247), 'scipy.ndimage.imread', 'imread', (['path[3]'], {}), '(path[3])\n', (1238, 1247), False, 'from scipy.ndimage import imread\n'), ((2602, 2629), 'skimage.measure.compare_psnr', 'compare_psnr', (['im[3]', 'target'], {}), '(im[3], target)\n', (2614, 2629), False, 'from skimage.measure import compare_ssim, compare_psnr\n'), ((2718, 2737), 'skimage.img_as_float', 'img_as_float', (['im[i]'], {}), '(im[i])\n', (2730, 2737), False, 'from skimage import img_as_float\n')]
# -*- coding: utf-8 -*- """ Spyder Editor 15201002 <NAME> """ #initializing PCA from sklearn import decomposition pca=decomposition.PCA() import pandas as pd import numpy as np import seaborn as sn import matplotlib.pyplot as plt from sklearn.preprocessing import StandardScaler data=pd.read_csv('Thesis_responses_Scaled.csv') #configure the parameters #number of componenets = 2 labels=data['Flag'] data=data.drop(['Timestamp','Flag','ID','Rehab'],axis=1) #scaler=StandardScaler() #scaler.fit(data) ## compute the mean and standard which will be used in the next command #X_scaled=scaler.transform(data) ## fit and transform can be applied together and I leave that for simple exercise pca.n_components=2 pca_data=pca.fit_transform(data) #pca_reduced will contain 2-d projects of sample data print("shape of pca_reduced.shape = ",pca_data.shape) ex_variance=np.var(pca_data,axis=0) ex_variance_ratio=ex_variance/np.sum(ex_variance) print("Ex variance ratio of components ",ex_variance_ratio) # attaching the label for each 2-d data point pca_data = np.vstack((pca_data.T, labels)).T # creating a new data fram which help us in ploting the result data pca_df = pd.DataFrame(data=pca_data, columns=("1st_principal", "2nd_principal", "label")) sn.FacetGrid(pca_df, hue="label", size=6).map(plt.scatter, '1st_principal', '2nd_principal').add_legend() plt.show() # PCA for dimensionality redcution (non-visualization) pca.n_components = 59 pca_data = pca.fit_transform(data) percentage_var_explained = pca.explained_variance_ / np.sum(pca.explained_variance_); cum_var_explained = np.cumsum(percentage_var_explained) # Plot the PCA spectrum plt.rcParams.update({'font.size': 16}) plt.figure(1, figsize=(6, 4)) plt.clf() plt.plot(cum_var_explained, linewidth=2) plt.axis('tight') plt.grid() plt.xlabel('n_components') plt.ylabel('Cumulative_explained_variance') plt.show() # If we take 30-dimensions, approx. 90% of variance is expalined.
[ "matplotlib.pyplot.grid", "pandas.read_csv", "matplotlib.pyplot.ylabel", "sklearn.decomposition.PCA", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.clf", "matplotlib.pyplot.plot", "matplotlib.pyplot.axis", "matplotlib.pyplot.rcParams.update", "matplotlib.pyplot.figure", "numpy.sum", "numpy.vs...
[((120, 139), 'sklearn.decomposition.PCA', 'decomposition.PCA', ([], {}), '()\n', (137, 139), False, 'from sklearn import decomposition\n'), ((286, 328), 'pandas.read_csv', 'pd.read_csv', (['"""Thesis_responses_Scaled.csv"""'], {}), "('Thesis_responses_Scaled.csv')\n", (297, 328), True, 'import pandas as pd\n'), ((867, 891), 'numpy.var', 'np.var', (['pca_data'], {'axis': '(0)'}), '(pca_data, axis=0)\n', (873, 891), True, 'import numpy as np\n'), ((1172, 1257), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'pca_data', 'columns': "('1st_principal', '2nd_principal', 'label')"}), "(data=pca_data, columns=('1st_principal', '2nd_principal', 'label')\n )\n", (1184, 1257), True, 'import pandas as pd\n'), ((1359, 1369), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1367, 1369), True, 'import matplotlib.pyplot as plt\n'), ((1592, 1627), 'numpy.cumsum', 'np.cumsum', (['percentage_var_explained'], {}), '(percentage_var_explained)\n', (1601, 1627), True, 'import numpy as np\n'), ((1653, 1691), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 16}"], {}), "({'font.size': 16})\n", (1672, 1691), True, 'import matplotlib.pyplot as plt\n'), ((1692, 1721), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(6, 4)'}), '(1, figsize=(6, 4))\n', (1702, 1721), True, 'import matplotlib.pyplot as plt\n'), ((1723, 1732), 'matplotlib.pyplot.clf', 'plt.clf', ([], {}), '()\n', (1730, 1732), True, 'import matplotlib.pyplot as plt\n'), ((1733, 1773), 'matplotlib.pyplot.plot', 'plt.plot', (['cum_var_explained'], {'linewidth': '(2)'}), '(cum_var_explained, linewidth=2)\n', (1741, 1773), True, 'import matplotlib.pyplot as plt\n'), ((1774, 1791), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (1782, 1791), True, 'import matplotlib.pyplot as plt\n'), ((1792, 1802), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (1800, 1802), True, 'import matplotlib.pyplot as plt\n'), ((1803, 1829), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""n_components"""'], {}), "('n_components')\n", (1813, 1829), True, 'import matplotlib.pyplot as plt\n'), ((1830, 1873), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cumulative_explained_variance"""'], {}), "('Cumulative_explained_variance')\n", (1840, 1873), True, 'import matplotlib.pyplot as plt\n'), ((1874, 1884), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1882, 1884), True, 'import matplotlib.pyplot as plt\n'), ((921, 940), 'numpy.sum', 'np.sum', (['ex_variance'], {}), '(ex_variance)\n', (927, 940), True, 'import numpy as np\n'), ((1060, 1091), 'numpy.vstack', 'np.vstack', (['(pca_data.T, labels)'], {}), '((pca_data.T, labels))\n', (1069, 1091), True, 'import numpy as np\n'), ((1538, 1569), 'numpy.sum', 'np.sum', (['pca.explained_variance_'], {}), '(pca.explained_variance_)\n', (1544, 1569), True, 'import numpy as np\n'), ((1253, 1294), 'seaborn.FacetGrid', 'sn.FacetGrid', (['pca_df'], {'hue': '"""label"""', 'size': '(6)'}), "(pca_df, hue='label', size=6)\n", (1265, 1294), True, 'import seaborn as sn\n')]
from keras.models import load_model import numpy as np from keras.preprocessing.image import img_to_array, load_img jpg_name = './hiragana73/U304A/1971_1352040_0240' model=load_model('./sample_hiragana_cnn_model.h5') img_path = (jpg_name + '.png') img = img_to_array(load_img(img_path, target_size=(28,28), grayscale=True)) img_nad = img_to_array(img)/255 img_nad = img_nad[None, ...] pred = model.predict(img_nad, batch_size=1, verbose=0) score = np.max(pred) print('label:', np.argmax(pred)) print('score:',score)
[ "keras.preprocessing.image.img_to_array", "keras.models.load_model", "numpy.argmax", "numpy.max", "keras.preprocessing.image.load_img" ]
[((174, 218), 'keras.models.load_model', 'load_model', (['"""./sample_hiragana_cnn_model.h5"""'], {}), "('./sample_hiragana_cnn_model.h5')\n", (184, 218), False, 'from keras.models import load_model\n'), ((452, 464), 'numpy.max', 'np.max', (['pred'], {}), '(pred)\n', (458, 464), True, 'import numpy as np\n'), ((270, 326), 'keras.preprocessing.image.load_img', 'load_img', (['img_path'], {'target_size': '(28, 28)', 'grayscale': '(True)'}), '(img_path, target_size=(28, 28), grayscale=True)\n', (278, 326), False, 'from keras.preprocessing.image import img_to_array, load_img\n'), ((337, 354), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['img'], {}), '(img)\n', (349, 354), False, 'from keras.preprocessing.image import img_to_array, load_img\n'), ((481, 496), 'numpy.argmax', 'np.argmax', (['pred'], {}), '(pred)\n', (490, 496), True, 'import numpy as np\n')]
import os import numpy as np import tensorflow as tf from tensorflow.python.client import timeline from attacks import jsma img_size = 28 img_chan = 1 n_classes = 10 print('\nConstruction graph') def model(x, logits=False, training=False): with tf.variable_scope('conv0'): z = tf.layers.conv2d(x, filters=32, kernel_size=[3, 3], padding='same', activation=tf.nn.relu) z = tf.layers.max_pooling2d(z, pool_size=[2, 2], strides=2) with tf.variable_scope('conv1'): z = tf.layers.conv2d(z, filters=64, kernel_size=[3, 3], padding='same', activation=tf.nn.relu) z = tf.layers.max_pooling2d(z, pool_size=[2, 2], strides=2) with tf.variable_scope('flatten'): shape = z.get_shape().as_list() z = tf.reshape(z, [-1, np.prod(shape[1:])]) with tf.variable_scope('mlp'): z = tf.layers.dense(z, units=128, activation=tf.nn.relu) z = tf.layers.dropout(z, rate=0.25, training=training) logits_ = tf.layers.dense(z, units=10, name='logits') y = tf.nn.softmax(logits_, name='ybar') if logits: return y, logits_ return y class Dummy: pass env = Dummy() with tf.variable_scope('model'): env.x = tf.placeholder(tf.float32, (None, img_size, img_size, img_chan), name='x') env.y = tf.placeholder(tf.float32, (None, n_classes), name='y') env.training = tf.placeholder_with_default(False, (), name='mode') env.ybar, logits = model(env.x, logits=True, training=env.training) with tf.variable_scope('model', reuse=True): env.target = tf.placeholder(tf.int32, (), name='target') env.adv_epochs = tf.placeholder_with_default(20, shape=(), name='epochs') env.adv_eps = tf.placeholder_with_default(0.2, shape=(), name='eps') env.x_jsma = jsma(model, env.x, env.target, eps=env.adv_eps, k=1, epochs=env.adv_epochs) print('\nInitializing graph') sess = tf.InteractiveSession() sess.run(tf.global_variables_initializer()) sess.run(tf.local_variables_initializer()) options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() X_data = np.random.random((1000, 28, 28, 1)) batch_size = 128 n_sample = X_data.shape[0] n_batch = int((n_sample + batch_size - 1) / batch_size) X_adv = np.empty_like(X_data) for batch in range(n_batch): print(' batch {0}/{1}'.format(batch + 1, n_batch), end='\r') start = batch * batch_size end = min(n_sample, start + batch_size) feed_dict = { env.x: X_data[start:end], env.target: np.random.choice(n_classes), env.adv_epochs: 1000, env.adv_eps: 0.1} adv = sess.run(env.x_jsma, feed_dict=feed_dict, options=options, run_metadata=run_metadata) X_adv[start:end] = adv print() fetched_timeline = timeline.Timeline(run_metadata.step_stats) chrome_trace = fetched_timeline.generate_chrome_trace_format() with open('timeline_{}.json'.format(batch), 'w') as f: f.write(chrome_trace)
[ "attacks.jsma", "tensorflow.local_variables_initializer", "numpy.prod", "tensorflow.nn.softmax", "tensorflow.RunMetadata", "numpy.random.random", "tensorflow.RunOptions", "tensorflow.placeholder", "tensorflow.layers.conv2d", "tensorflow.layers.dropout", "tensorflow.python.client.timeline.Timelin...
[((1990, 2013), 'tensorflow.InteractiveSession', 'tf.InteractiveSession', ([], {}), '()\n', (2011, 2013), True, 'import tensorflow as tf\n'), ((2112, 2163), 'tensorflow.RunOptions', 'tf.RunOptions', ([], {'trace_level': 'tf.RunOptions.FULL_TRACE'}), '(trace_level=tf.RunOptions.FULL_TRACE)\n', (2125, 2163), True, 'import tensorflow as tf\n'), ((2179, 2195), 'tensorflow.RunMetadata', 'tf.RunMetadata', ([], {}), '()\n', (2193, 2195), True, 'import tensorflow as tf\n'), ((2206, 2241), 'numpy.random.random', 'np.random.random', (['(1000, 28, 28, 1)'], {}), '((1000, 28, 28, 1))\n', (2222, 2241), True, 'import numpy as np\n'), ((2350, 2371), 'numpy.empty_like', 'np.empty_like', (['X_data'], {}), '(X_data)\n', (2363, 2371), True, 'import numpy as np\n'), ((1034, 1077), 'tensorflow.layers.dense', 'tf.layers.dense', (['z'], {'units': '(10)', 'name': '"""logits"""'}), "(z, units=10, name='logits')\n", (1049, 1077), True, 'import tensorflow as tf\n'), ((1086, 1121), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['logits_'], {'name': '"""ybar"""'}), "(logits_, name='ybar')\n", (1099, 1121), True, 'import tensorflow as tf\n'), ((1224, 1250), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""model"""'], {}), "('model')\n", (1241, 1250), True, 'import tensorflow as tf\n'), ((1264, 1338), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '(None, img_size, img_size, img_chan)'], {'name': '"""x"""'}), "(tf.float32, (None, img_size, img_size, img_chan), name='x')\n", (1278, 1338), True, 'import tensorflow as tf\n'), ((1378, 1433), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32', '(None, n_classes)'], {'name': '"""y"""'}), "(tf.float32, (None, n_classes), name='y')\n", (1392, 1433), True, 'import tensorflow as tf\n'), ((1453, 1504), 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', (['(False)', '()'], {'name': '"""mode"""'}), "(False, (), name='mode')\n", (1480, 1504), True, 'import tensorflow as tf\n'), ((1584, 1622), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""model"""'], {'reuse': '(True)'}), "('model', reuse=True)\n", (1601, 1622), True, 'import tensorflow as tf\n'), ((1641, 1684), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32', '()'], {'name': '"""target"""'}), "(tf.int32, (), name='target')\n", (1655, 1684), True, 'import tensorflow as tf\n'), ((1706, 1762), 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', (['(20)'], {'shape': '()', 'name': '"""epochs"""'}), "(20, shape=(), name='epochs')\n", (1733, 1762), True, 'import tensorflow as tf\n'), ((1781, 1835), 'tensorflow.placeholder_with_default', 'tf.placeholder_with_default', (['(0.2)'], {'shape': '()', 'name': '"""eps"""'}), "(0.2, shape=(), name='eps')\n", (1808, 1835), True, 'import tensorflow as tf\n'), ((1853, 1928), 'attacks.jsma', 'jsma', (['model', 'env.x', 'env.target'], {'eps': 'env.adv_eps', 'k': '(1)', 'epochs': 'env.adv_epochs'}), '(model, env.x, env.target, eps=env.adv_eps, k=1, epochs=env.adv_epochs)\n', (1857, 1928), False, 'from attacks import jsma\n'), ((2023, 2056), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (2054, 2056), True, 'import tensorflow as tf\n'), ((2067, 2099), 'tensorflow.local_variables_initializer', 'tf.local_variables_initializer', ([], {}), '()\n', (2097, 2099), True, 'import tensorflow as tf\n'), ((2877, 2919), 'tensorflow.python.client.timeline.Timeline', 'timeline.Timeline', (['run_metadata.step_stats'], {}), '(run_metadata.step_stats)\n', (2894, 2919), False, 'from tensorflow.python.client import timeline\n'), ((257, 283), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv0"""'], {}), "('conv0')\n", (274, 283), True, 'import tensorflow as tf\n'), ((297, 391), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['x'], {'filters': '(32)', 'kernel_size': '[3, 3]', 'padding': '"""same"""', 'activation': 'tf.nn.relu'}), "(x, filters=32, kernel_size=[3, 3], padding='same',\n activation=tf.nn.relu)\n", (313, 391), True, 'import tensorflow as tf\n'), ((429, 484), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', (['z'], {'pool_size': '[2, 2]', 'strides': '(2)'}), '(z, pool_size=[2, 2], strides=2)\n', (452, 484), True, 'import tensorflow as tf\n'), ((495, 521), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""conv1"""'], {}), "('conv1')\n", (512, 521), True, 'import tensorflow as tf\n'), ((535, 629), 'tensorflow.layers.conv2d', 'tf.layers.conv2d', (['z'], {'filters': '(64)', 'kernel_size': '[3, 3]', 'padding': '"""same"""', 'activation': 'tf.nn.relu'}), "(z, filters=64, kernel_size=[3, 3], padding='same',\n activation=tf.nn.relu)\n", (551, 629), True, 'import tensorflow as tf\n'), ((667, 722), 'tensorflow.layers.max_pooling2d', 'tf.layers.max_pooling2d', (['z'], {'pool_size': '[2, 2]', 'strides': '(2)'}), '(z, pool_size=[2, 2], strides=2)\n', (690, 722), True, 'import tensorflow as tf\n'), ((733, 761), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""flatten"""'], {}), "('flatten')\n", (750, 761), True, 'import tensorflow as tf\n'), ((865, 889), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""mlp"""'], {}), "('mlp')\n", (882, 889), True, 'import tensorflow as tf\n'), ((903, 955), 'tensorflow.layers.dense', 'tf.layers.dense', (['z'], {'units': '(128)', 'activation': 'tf.nn.relu'}), '(z, units=128, activation=tf.nn.relu)\n', (918, 955), True, 'import tensorflow as tf\n'), ((968, 1018), 'tensorflow.layers.dropout', 'tf.layers.dropout', (['z'], {'rate': '(0.25)', 'training': 'training'}), '(z, rate=0.25, training=training)\n', (985, 1018), True, 'import tensorflow as tf\n'), ((2614, 2641), 'numpy.random.choice', 'np.random.choice', (['n_classes'], {}), '(n_classes)\n', (2630, 2641), True, 'import numpy as np\n'), ((834, 852), 'numpy.prod', 'np.prod', (['shape[1:]'], {}), '(shape[1:])\n', (841, 852), True, 'import numpy as np\n')]
import numpy as np import pandas as pd from pathlib import Path from tqdm import tqdm from scipy.spatial.distance import cdist from sklearn.metrics import roc_curve, roc_auc_score masif_preds = Path("masif_preds/") timings = Path("timings/") raw_data = Path("surface_data/raw/protein_surfaces/01-benchmark_surfaces_npy") experiment_names = [ "TangentConv_site_1layer_5A_epoch49", "TangentConv_site_1layer_9A_epoch49", "TangentConv_site_1layer_15A_epoch49", "TangentConv_site_3layer_15A_epoch17", "TangentConv_site_3layer_5A_epoch49", "TangentConv_site_3layer_9A_epoch46", "PointNet_site_3layer_9A_epoch37", "PointNet_site_3layer_5A_epoch46", "DGCNN_site_1layer_k100_epoch32", "PointNet_site_1layer_5A_epoch30", "PointNet_site_1layer_9A_epoch30", "DGCNN_site_1layer_k40_epoch46", "DGCNN_site_3layer_k40_epoch33", ] experiment_names = [ 'Rebuttal_TangentConv_site_1L_8dim_9A_gc_subsamp20_dist05_epoch42', 'Rebuttal_TangentConv_site_1L_8dim_9A_gc_subsamp20_dist20_epoch49', 'Rebuttal_TangentConv_site_1L_8dim_9A_gc_subsamp20_dist105_epoch44', 'Rebuttal_TangentConv_site_1L_8dim_9A_gc_subsamp20_var01_epoch43', 'Rebuttal_TangentConv_site_1L_8dim_9A_gc_subsamp20_var02_epoch49', 'Rebuttal_TangentConv_site_1L_8dim_9A_gc_subsamp20_var005_epoch37' ] for experiment_name in experiment_names: print(experiment_name) datafolder = Path(f"preds/{experiment_name}") pdb_list = [p.stem[:-5] for p in datafolder.glob("*pred.vtk")] n_meshpoints = [] n_predpoints = [] meshpoints_mindists = [] predpoints_mindists = [] for pdb_id in tqdm(pdb_list): predpoints = np.load(datafolder / (pdb_id + "_predcoords.npy")) meshpoints = np.load(datafolder / (pdb_id + "_meshpoints.npy")) n_meshpoints.append(meshpoints.shape[0]) n_predpoints.append(predpoints.shape[0]) pdists = cdist(meshpoints, predpoints) meshpoints_mindists.append(pdists.min(1)) predpoints_mindists.append(pdists.min(0)) all_meshpoints_mindists = np.concatenate(meshpoints_mindists) all_predpoints_mindists = np.concatenate(predpoints_mindists) meshpoint_percentile = np.percentile(all_meshpoints_mindists, 99) predpoint_percentile = np.percentile(all_predpoints_mindists, 99) meshpoints_masks = [] predpoints_masks = [] for pdb_id in tqdm(pdb_list): predpoints = np.load(datafolder / (pdb_id + "_predcoords.npy")) meshpoints = np.load(datafolder / (pdb_id + "_meshpoints.npy")) pdists = cdist(meshpoints, predpoints) meshpoints_masks.append(pdists.min(1) < meshpoint_percentile) predpoints_masks.append(pdists.min(0) < predpoint_percentile) predpoints_preds = [] predpoints_labels = [] npoints = [] for i, pdb_id in enumerate(tqdm(pdb_list)): predpoints_features = np.load(datafolder / (pdb_id + "_predfeatures.npy")) predpoints_features = predpoints_features[predpoints_masks[i]] predpoints_preds.append(predpoints_features[:, -2]) predpoints_labels.append(predpoints_features[:, -1]) npoints.append(predpoints_features.shape[0]) predpoints_labels = np.concatenate(predpoints_labels) predpoints_preds = np.concatenate(predpoints_preds) rocauc = roc_auc_score(predpoints_labels.reshape(-1), predpoints_preds.reshape(-1)) print("ROC-AUC", rocauc) np.save(timings / f"{experiment_name}_predpoints_preds", predpoints_preds) np.save(timings / f"{experiment_name}_predpoints_labels", predpoints_labels) np.save(timings / f"{experiment_name}_npoints", npoints)
[ "pathlib.Path", "scipy.spatial.distance.cdist", "tqdm.tqdm", "numpy.concatenate", "numpy.percentile", "numpy.load", "numpy.save" ]
[((196, 216), 'pathlib.Path', 'Path', (['"""masif_preds/"""'], {}), "('masif_preds/')\n", (200, 216), False, 'from pathlib import Path\n'), ((227, 243), 'pathlib.Path', 'Path', (['"""timings/"""'], {}), "('timings/')\n", (231, 243), False, 'from pathlib import Path\n'), ((255, 322), 'pathlib.Path', 'Path', (['"""surface_data/raw/protein_surfaces/01-benchmark_surfaces_npy"""'], {}), "('surface_data/raw/protein_surfaces/01-benchmark_surfaces_npy')\n", (259, 322), False, 'from pathlib import Path\n'), ((1409, 1441), 'pathlib.Path', 'Path', (['f"""preds/{experiment_name}"""'], {}), "(f'preds/{experiment_name}')\n", (1413, 1441), False, 'from pathlib import Path\n'), ((1630, 1644), 'tqdm.tqdm', 'tqdm', (['pdb_list'], {}), '(pdb_list)\n', (1634, 1644), False, 'from tqdm import tqdm\n'), ((2067, 2102), 'numpy.concatenate', 'np.concatenate', (['meshpoints_mindists'], {}), '(meshpoints_mindists)\n', (2081, 2102), True, 'import numpy as np\n'), ((2133, 2168), 'numpy.concatenate', 'np.concatenate', (['predpoints_mindists'], {}), '(predpoints_mindists)\n', (2147, 2168), True, 'import numpy as np\n'), ((2197, 2239), 'numpy.percentile', 'np.percentile', (['all_meshpoints_mindists', '(99)'], {}), '(all_meshpoints_mindists, 99)\n', (2210, 2239), True, 'import numpy as np\n'), ((2267, 2309), 'numpy.percentile', 'np.percentile', (['all_predpoints_mindists', '(99)'], {}), '(all_predpoints_mindists, 99)\n', (2280, 2309), True, 'import numpy as np\n'), ((2381, 2395), 'tqdm.tqdm', 'tqdm', (['pdb_list'], {}), '(pdb_list)\n', (2385, 2395), False, 'from tqdm import tqdm\n'), ((3202, 3235), 'numpy.concatenate', 'np.concatenate', (['predpoints_labels'], {}), '(predpoints_labels)\n', (3216, 3235), True, 'import numpy as np\n'), ((3259, 3291), 'numpy.concatenate', 'np.concatenate', (['predpoints_preds'], {}), '(predpoints_preds)\n', (3273, 3291), True, 'import numpy as np\n'), ((3414, 3488), 'numpy.save', 'np.save', (["(timings / f'{experiment_name}_predpoints_preds')", 'predpoints_preds'], {}), "(timings / f'{experiment_name}_predpoints_preds', predpoints_preds)\n", (3421, 3488), True, 'import numpy as np\n'), ((3493, 3569), 'numpy.save', 'np.save', (["(timings / f'{experiment_name}_predpoints_labels')", 'predpoints_labels'], {}), "(timings / f'{experiment_name}_predpoints_labels', predpoints_labels)\n", (3500, 3569), True, 'import numpy as np\n'), ((3574, 3630), 'numpy.save', 'np.save', (["(timings / f'{experiment_name}_npoints')", 'npoints'], {}), "(timings / f'{experiment_name}_npoints', npoints)\n", (3581, 3630), True, 'import numpy as np\n'), ((1667, 1717), 'numpy.load', 'np.load', (["(datafolder / (pdb_id + '_predcoords.npy'))"], {}), "(datafolder / (pdb_id + '_predcoords.npy'))\n", (1674, 1717), True, 'import numpy as np\n'), ((1739, 1789), 'numpy.load', 'np.load', (["(datafolder / (pdb_id + '_meshpoints.npy'))"], {}), "(datafolder / (pdb_id + '_meshpoints.npy'))\n", (1746, 1789), True, 'import numpy as np\n'), ((1906, 1935), 'scipy.spatial.distance.cdist', 'cdist', (['meshpoints', 'predpoints'], {}), '(meshpoints, predpoints)\n', (1911, 1935), False, 'from scipy.spatial.distance import cdist\n'), ((2418, 2468), 'numpy.load', 'np.load', (["(datafolder / (pdb_id + '_predcoords.npy'))"], {}), "(datafolder / (pdb_id + '_predcoords.npy'))\n", (2425, 2468), True, 'import numpy as np\n'), ((2490, 2540), 'numpy.load', 'np.load', (["(datafolder / (pdb_id + '_meshpoints.npy'))"], {}), "(datafolder / (pdb_id + '_meshpoints.npy'))\n", (2497, 2540), True, 'import numpy as np\n'), ((2559, 2588), 'scipy.spatial.distance.cdist', 'cdist', (['meshpoints', 'predpoints'], {}), '(meshpoints, predpoints)\n', (2564, 2588), False, 'from scipy.spatial.distance import cdist\n'), ((2831, 2845), 'tqdm.tqdm', 'tqdm', (['pdb_list'], {}), '(pdb_list)\n', (2835, 2845), False, 'from tqdm import tqdm\n'), ((2878, 2930), 'numpy.load', 'np.load', (["(datafolder / (pdb_id + '_predfeatures.npy'))"], {}), "(datafolder / (pdb_id + '_predfeatures.npy'))\n", (2885, 2930), True, 'import numpy as np\n')]
import pandas as pd import os import torch import argparse import numpy as np import json import matplotlib.pyplot as plt import torch.nn.functional as F from utils import smooth from utils import detect_with_thresholding from utils import get_dataset, normalize, interpolate from utils import mask_to_detections, load_config_file from utils import output_detections_ucf_crime from utils import ucf_crime_old_cls_names, ucf_crime_old_cls_indices from utils import prepare_gt, segment_iou, load_config_file from collections import OrderedDict import pdb def softmax(x, dim): x = F.softmax(torch.from_numpy(x), dim=dim) return x.numpy() def prepare_detections(detpth): f = open(detpth) det_list = [] for i in f.readlines(): i = i.replace('\n', '') i = i.split(' ') det_list.append(i) df = pd.DataFrame(det_list) df.columns = ['videoname', 'start', 'end', 'cls', 'conf'] f.close() return df def interpolated_prec_rec(prec, rec): """ Interpolated AP - VOCdevkit from VOC 2011. """ mprec = np.hstack([[0], prec, [0]]) mrec = np.hstack([[0], rec, [1]]) for i in range(len(mprec) - 1)[::-1]: mprec[i] = max(mprec[i], mprec[i + 1]) idx = np.where(mrec[1::] != mrec[0:-1])[0] + 1 ap = np.sum((mrec[idx] - mrec[idx - 1]) * mprec[idx]) return ap def compute_average_precision_detection(ground_truth, prediction, tiou_thresholds): """ Compute average precision (detection task) between ground truth and predictions data frames. If multiple predictions occurs for the same predicted segment, only the one with highest IoU score is matched as true positive. This code is greatly inspired by Pascal VOC devkit. Parameters ---------- ground_truth : Data frame containing the ground truth instances. Required fields: ['videoname', 'start', 'end'] prediction : Data frame containing the prediction instances. Required fields: ['videoname', 'start', 'end', 'conf'] tiou_thresholds : 1darray, optional Temporal intersection over union threshold. Outputs ------- ap : float Average precision score. """ prediction = prediction.reset_index(drop=True) npos = float(len(ground_truth)) lock_gt = np.ones((len(tiou_thresholds), len(ground_truth))) * -1 # Sort predictions by decreasing (confidence) score order. sort_idx = prediction['conf'].values.argsort()[::-1] prediction = prediction.loc[sort_idx].reset_index(drop=True) # Initialize true positive and false positive vectors. tp = np.zeros((len(tiou_thresholds), len(prediction))) fp = np.zeros((len(tiou_thresholds), len(prediction))) # Adaptation to query faster ground_truth_gbvn = ground_truth.groupby('videoname') # Assigning true positive to truly grount truth instances. for idx, this_pred in prediction.iterrows(): try: # Check if there is at least one ground truth in the video associated with predicted video. ground_truth_videoid = ground_truth_gbvn.get_group(this_pred['videoname']) except Exception as e: fp[:, idx] = 1 continue this_gt = ground_truth_videoid.reset_index() tiou_arr = segment_iou(this_pred[['start', 'end']].values, this_gt[['start', 'end']].values) # We would like to retrieve the predictions with highest tiou score. tiou_sorted_idx = tiou_arr.argsort()[::-1] for tidx, tiou_thr in enumerate(tiou_thresholds): for jdx in tiou_sorted_idx: if tiou_arr[jdx] < tiou_thr: fp[tidx, idx] = 1 break if lock_gt[tidx, this_gt.loc[jdx]['index']] >= 0: continue # Assign as true positive after the filters above. tp[tidx, idx] = 1 lock_gt[tidx, this_gt.loc[jdx]['index']] = idx break if fp[tidx, idx] == 0 and tp[tidx, idx] == 0: fp[tidx, idx] = 1 ap = np.zeros(len(tiou_thresholds)) rec, prec = None, None for tidx in range(len(tiou_thresholds)): # Computing prec-rec (per-class basis at every individual tiou_thresholds) this_tp = np.cumsum(tp[tidx,:]).astype(np.float) this_fp = np.cumsum(fp[tidx,:]).astype(np.float) rec = this_tp / npos prec = this_tp / (this_tp + this_fp) ap[tidx] = interpolated_prec_rec(prec, rec) return ap def eval_ap(iou, clss, gt, prediction): ap = compute_average_precision_detection(gt, prediction, iou) return ap[0] def detect( dataset_dicts, cas_dir, subset, out_file_name, global_score_thrh, metric_type, thrh_type, thrh_value, interpolate_type, proc_type, proc_value, sample_offset, weight_inner, weight_outter, weight_global, att_filtering_value=None, ): assert (metric_type in ['score', 'multiply', 'att-filtering']) assert (thrh_type in ['mean', 'max']) assert (interpolate_type in ['quadratic', 'linear', 'nearest']) assert (proc_type in ['dilation', 'median']) out_detections = [] dataset_dict = dataset_dicts[subset] for video_name in dataset_dict.keys(): cas_file = video_name + '.npz' cas_data = np.load(os.path.join(cas_dir, cas_file)) avg_score = cas_data['avg_score'] att_weight = cas_data['weight'] branch_scores = cas_data['branch_scores'] global_score = cas_data['global_score'] fps = dataset_dict[video_name]['frame_rate'] frame_cnt = dataset_dict[video_name]['frame_cnt'] duration = frame_cnt/fps global_score = softmax(global_score, dim=0) ################ Thresholding ################ for class_id in range(all_params['action_class_num']): if global_score[class_id] <= global_score_thrh: continue if metric_type == 'score': metric = softmax(avg_score, dim=1)[:, class_id:class_id + 1] #metric = smooth(metric) metric = normalize(metric) elif metric_type == 'multiply': _score = softmax(avg_score, dim=1)[:, class_id:class_id + 1] metric = att_weight * _score #metric = smooth(metric) metric = normalize(metric) elif metric_type == 'att-filtering': assert (att_filtering_value is not None) metric = softmax(avg_score, dim=1)[:, class_id:class_id + 1] #metric = smooth(metric) metric = normalize(metric) metric[att_weight < att_filtering_value] = 0 metric = normalize(metric) ######################################### metric = interpolate(metric[:, 0], all_params['feature_type'], frame_cnt, all_params['base_sample_rate']*all_params['sample_rate'], snippet_size=all_params['base_snippet_size'], kind=interpolate_type) metric = np.expand_dims(metric, axis=1) mask = detect_with_thresholding(metric, thrh_type, thrh_value, proc_type, proc_value) temp_out = mask_to_detections(mask, metric, weight_inner, weight_outter) ######################################### for entry in temp_out: entry[2] = class_id entry[3] += global_score[class_id] * weight_global entry[0] = (entry[0] + sample_offset) / fps entry[1] = (entry[1] + sample_offset) / fps entry[0] = max(0, entry[0]) entry[1] = max(0, entry[1]) entry[0] = min(duration, entry[0]) entry[1] = min(duration, entry[1]) ######################################### for entry_id in range(len(temp_out)): temp_out[entry_id] = [video_name] + temp_out[entry_id] out_detections += temp_out output_detections_ucf_crime(out_detections, out_file_name) return out_detections if __name__ == '__main__': parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--config-file', type=str) parser.add_argument('--test-subset-name', type=str) args = parser.parse_args() print(args.config_file) print(args.test_subset_name) all_params = load_config_file(args.config_file) locals().update(all_params) odict = OrderedDict() test_dataset_dict = get_dataset( dataset_name=all_params['dataset_name'], subset=args.test_subset_name, file_paths=all_params['file_paths'], sample_rate=all_params['sample_rate'], base_sample_rate=all_params['base_sample_rate'], action_class_num=all_params['action_class_num'], modality='both', feature_type=all_params['feature_type'], feature_oversample=False, temporal_aug=False, ) dataset_dicts = {'test': test_dataset_dict} # Obtain ground truth gt_file_pth = all_params['file_paths'][args.test_subset_name]['anno_dir'] ground_truth = os.listdir(gt_file_pth)[0] gtpth = os.path.join(gt_file_pth, ground_truth) gtdf = prepare_gt(gtpth) summary_file = './outputs/summary-{}.json'.format(all_params['experiment_naming']) for run_idx in range(all_params['train_run_num']): for cp_idx, check_point in enumerate(all_params['check_points']): for mod_idx, modality in enumerate( ['both', 'rgb', 'flow', 'late-fusion']): cas_dir = os.path.join( 'cas-features', '{}-run-{}-{}-{}'.format(all_params['experiment_naming'], run_idx, check_point, modality)) pred_dir = os.path.join('outputs', 'predictions') if not os.path.exists(pred_dir): os.makedirs(pred_dir) test_pred_file = os.path.join( pred_dir, '{}-run-{}-{}-{}-test'.format(all_params['experiment_naming'], run_idx, check_point, modality)) # test_outs = [vid_name, start, end, predict_class, confidence_score] test_outs = detect(dataset_dicts, cas_dir, 'test', test_pred_file, **all_params['detect_params']) iou_range = [.1, .2, .3, .4, .5] odict[modality] = {} for IoU_idx, IoU in enumerate(iou_range): if len(test_outs) != 0: # Obtain detection predictions detdf = prepare_detections(test_pred_file) # Rearranging the ground-truth and predictions based on class gt_by_cls, det_by_cls = [], [] for clss in range(1, all_params['action_class_num']+1): gt_by_cls.append(gtdf[gtdf['cls'] == clss].reset_index(drop=True).drop('cls', 1)) det_by_cls.append(detdf[detdf['videoname'].str.contains(ucf_crime_old_cls_names[clss])].drop(columns=['cls'])) ap_values = [] mAP = 0 for clss in range(all_params['action_class_num']): #ap per-class basis ap = eval_ap([IoU], clss, gt_by_cls[clss], det_by_cls[clss]) ap_values.append(ap) # calculate mean AP across all classes (for every IoU value) for i in ap_values: mAP += i mAP = mAP/len(ap_values) else: print('Empty Detections') odict[modality][IoU] = '{:.4f}'.format(mAP) for k, v in odict.items(): print(k, v) json = json.dumps(odict) f = open(summary_file, 'w') f.write(json) f.close()
[ "utils.prepare_gt", "numpy.hstack", "utils.detect_with_thresholding", "torch.from_numpy", "utils.output_detections_ucf_crime", "utils.interpolate", "os.path.exists", "utils.load_config_file", "os.listdir", "argparse.ArgumentParser", "numpy.where", "json.dumps", "pandas.DataFrame", "collect...
[((846, 868), 'pandas.DataFrame', 'pd.DataFrame', (['det_list'], {}), '(det_list)\n', (858, 868), True, 'import pandas as pd\n'), ((1074, 1101), 'numpy.hstack', 'np.hstack', (['[[0], prec, [0]]'], {}), '([[0], prec, [0]])\n', (1083, 1101), True, 'import numpy as np\n'), ((1113, 1139), 'numpy.hstack', 'np.hstack', (['[[0], rec, [1]]'], {}), '([[0], rec, [1]])\n', (1122, 1139), True, 'import numpy as np\n'), ((1289, 1337), 'numpy.sum', 'np.sum', (['((mrec[idx] - mrec[idx - 1]) * mprec[idx])'], {}), '((mrec[idx] - mrec[idx - 1]) * mprec[idx])\n', (1295, 1337), True, 'import numpy as np\n'), ((8389, 8447), 'utils.output_detections_ucf_crime', 'output_detections_ucf_crime', (['out_detections', 'out_file_name'], {}), '(out_detections, out_file_name)\n', (8416, 8447), False, 'from utils import output_detections_ucf_crime\n'), ((8530, 8609), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'formatter_class': 'argparse.ArgumentDefaultsHelpFormatter'}), '(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n', (8553, 8609), False, 'import argparse\n'), ((8838, 8872), 'utils.load_config_file', 'load_config_file', (['args.config_file'], {}), '(args.config_file)\n', (8854, 8872), False, 'from utils import prepare_gt, segment_iou, load_config_file\n'), ((8922, 8935), 'collections.OrderedDict', 'OrderedDict', ([], {}), '()\n', (8933, 8935), False, 'from collections import OrderedDict\n'), ((8961, 9344), 'utils.get_dataset', 'get_dataset', ([], {'dataset_name': "all_params['dataset_name']", 'subset': 'args.test_subset_name', 'file_paths': "all_params['file_paths']", 'sample_rate': "all_params['sample_rate']", 'base_sample_rate': "all_params['base_sample_rate']", 'action_class_num': "all_params['action_class_num']", 'modality': '"""both"""', 'feature_type': "all_params['feature_type']", 'feature_oversample': '(False)', 'temporal_aug': '(False)'}), "(dataset_name=all_params['dataset_name'], subset=args.\n test_subset_name, file_paths=all_params['file_paths'], sample_rate=\n all_params['sample_rate'], base_sample_rate=all_params[\n 'base_sample_rate'], action_class_num=all_params['action_class_num'],\n modality='both', feature_type=all_params['feature_type'],\n feature_oversample=False, temporal_aug=False)\n", (8972, 9344), False, 'from utils import get_dataset, normalize, interpolate\n'), ((9621, 9660), 'os.path.join', 'os.path.join', (['gt_file_pth', 'ground_truth'], {}), '(gt_file_pth, ground_truth)\n', (9633, 9660), False, 'import os\n'), ((9672, 9689), 'utils.prepare_gt', 'prepare_gt', (['gtpth'], {}), '(gtpth)\n', (9682, 9689), False, 'from utils import prepare_gt, segment_iou, load_config_file\n'), ((12609, 12626), 'json.dumps', 'json.dumps', (['odict'], {}), '(odict)\n', (12619, 12626), False, 'import json\n'), ((596, 615), 'torch.from_numpy', 'torch.from_numpy', (['x'], {}), '(x)\n', (612, 615), False, 'import torch\n'), ((3290, 3376), 'utils.segment_iou', 'segment_iou', (["this_pred[['start', 'end']].values", "this_gt[['start', 'end']].values"], {}), "(this_pred[['start', 'end']].values, this_gt[['start', 'end']].\n values)\n", (3301, 3376), False, 'from utils import prepare_gt, segment_iou, load_config_file\n'), ((9582, 9605), 'os.listdir', 'os.listdir', (['gt_file_pth'], {}), '(gt_file_pth)\n', (9592, 9605), False, 'import os\n'), ((1239, 1271), 'numpy.where', 'np.where', (['(mrec[1:] != mrec[0:-1])'], {}), '(mrec[1:] != mrec[0:-1])\n', (1247, 1271), True, 'import numpy as np\n'), ((5441, 5472), 'os.path.join', 'os.path.join', (['cas_dir', 'cas_file'], {}), '(cas_dir, cas_file)\n', (5453, 5472), False, 'import os\n'), ((6962, 7165), 'utils.interpolate', 'interpolate', (['metric[:, 0]', "all_params['feature_type']", 'frame_cnt', "(all_params['base_sample_rate'] * all_params['sample_rate'])"], {'snippet_size': "all_params['base_snippet_size']", 'kind': 'interpolate_type'}), "(metric[:, 0], all_params['feature_type'], frame_cnt, all_params\n ['base_sample_rate'] * all_params['sample_rate'], snippet_size=\n all_params['base_snippet_size'], kind=interpolate_type)\n", (6973, 7165), False, 'from utils import get_dataset, normalize, interpolate\n'), ((7356, 7386), 'numpy.expand_dims', 'np.expand_dims', (['metric'], {'axis': '(1)'}), '(metric, axis=1)\n', (7370, 7386), True, 'import numpy as np\n'), ((7407, 7485), 'utils.detect_with_thresholding', 'detect_with_thresholding', (['metric', 'thrh_type', 'thrh_value', 'proc_type', 'proc_value'], {}), '(metric, thrh_type, thrh_value, proc_type, proc_value)\n', (7431, 7485), False, 'from utils import detect_with_thresholding\n'), ((7554, 7615), 'utils.mask_to_detections', 'mask_to_detections', (['mask', 'metric', 'weight_inner', 'weight_outter'], {}), '(mask, metric, weight_inner, weight_outter)\n', (7572, 7615), False, 'from utils import mask_to_detections, load_config_file\n'), ((4297, 4319), 'numpy.cumsum', 'np.cumsum', (['tp[tidx, :]'], {}), '(tp[tidx, :])\n', (4306, 4319), True, 'import numpy as np\n'), ((4354, 4376), 'numpy.cumsum', 'np.cumsum', (['fp[tidx, :]'], {}), '(fp[tidx, :])\n', (4363, 4376), True, 'import numpy as np\n'), ((6242, 6259), 'utils.normalize', 'normalize', (['metric'], {}), '(metric)\n', (6251, 6259), False, 'from utils import get_dataset, normalize, interpolate\n'), ((10277, 10315), 'os.path.join', 'os.path.join', (['"""outputs"""', '"""predictions"""'], {}), "('outputs', 'predictions')\n", (10289, 10315), False, 'import os\n'), ((6494, 6511), 'utils.normalize', 'normalize', (['metric'], {}), '(metric)\n', (6503, 6511), False, 'from utils import get_dataset, normalize, interpolate\n'), ((10340, 10364), 'os.path.exists', 'os.path.exists', (['pred_dir'], {}), '(pred_dir)\n', (10354, 10364), False, 'import os\n'), ((10386, 10407), 'os.makedirs', 'os.makedirs', (['pred_dir'], {}), '(pred_dir)\n', (10397, 10407), False, 'import os\n'), ((6763, 6780), 'utils.normalize', 'normalize', (['metric'], {}), '(metric)\n', (6772, 6780), False, 'from utils import get_dataset, normalize, interpolate\n'), ((6867, 6884), 'utils.normalize', 'normalize', (['metric'], {}), '(metric)\n', (6876, 6884), False, 'from utils import get_dataset, normalize, interpolate\n')]
import itertools import os, random import statistics import matplotlib import matplotlib.pyplot as plt from analyze_entropy import comp_entropy from analyze_prob_attn import compute_idf, get_ban_positions # from data_collection import CUR_DIR, PROB_META_DIR, spec_name, MODEL_NAME, DATA_NAME from util import convert_enc_attn, parse_arg from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator) font_size = 14 matplotlib.font_manager._rebuild() GLOBAL_FIGURE_WIDTH = 8 dpi = 800 # plt.rcParams["font.weight"] = "light" plt.rcParams.update({'font.size': 14}) plt.rcParams['font.family'] = 'DejaVu Sans' dir_datadrive = '/mnt/data0/jcxu/data/prob_gpt' # Density: x: entropy, two plots: is bigram or not FIG_SIZE_x = GLOBAL_FIGURE_WIDTH def get_ys(t, logits, BOS_token=0): # for one time step, get the tokens last_inp, cur_inp, cur_pred, and next_pred cur_pred = logits[t] try: next_pred = logits[t + 1] except IndexError: next_pred = None if t - 2 >= 0: last_inp = logits[t - 2] elif t - 2 == -1: last_inp = BOS_token else: last_inp = None if t - 1 >= 0: cur_inp = logits[t - 1] elif t - 1 == -1: cur_inp = BOS_token else: cur_inp = None return last_inp, cur_inp, cur_pred, next_pred from collections import Counter def truncate_attention_cell(attn_distb, input_doc, idf_ban_pos, tgt_prob_mass=0.9) -> Counter: # for each attention distribution, remove the idf ban tokens (positions), get the accumulated prob up to prob_mass. # return sorts = np.argsort(attn_distb, axis=-1, kind=None, order=None)[::-1] cum_prob_mass = 0 cnt = Counter() for topk in sorts: prob_mass = attn_distb[topk] cum_prob_mass += prob_mass if topk not in idf_ban_pos: cnt[input_doc[topk]] = prob_mass if cum_prob_mass > tgt_prob_mass or prob_mass < 0.01: break return cnt def _y_entropy_step(attn_lle, input_doc, idf_ban_pos): num_layer, num_head, src_len = attn_lle.shape all_attns = Counter() for l in range(num_layer): for h in range(num_head): cell_attn = truncate_attention_cell(attn_lle[l][h], input_doc, idf_ban_pos=idf_ban_pos) all_attns = all_attns + cell_attn return all_attns def retrieve_tok_val(cnter, token): try: v = cnter[token] except: v = 0 return v import matplotlib import matplotlib.pyplot as plt def plot_hist(val_ent_pairs, title): weights = [p[0] for p in val_ent_pairs] xs = [p[1] for p in val_ent_pairs] plt.hist(xs, bins=20, weights=weights, density=True) plt.xlabel('Pred Ent') plt.ylabel('Cum Attn') plt.title(title) plt.grid(True) plt.show() import seaborn as sns def get_statistics(matrix): result = [0 for _ in range(len(matrix))] for idx, row in enumerate(matrix): try: m = statistics.mean(row) except: m = 0 print("NO DATA!") result[idx] = m return result def proceed_data(segs, val_ent_pairs, step_size=0.5): cat_bins = [[[] for _ in range(segs)] for _ in range(5)] for p in val_ent_pairs: last_inp, cur_inp, cur_pred, next_pred, pred_ent, atte_ent = p # attn_val, ent, attn_e = p[0], p[1], p[2] cat = int(pred_ent // step_size) try: cat_bins[0][cat].append(last_inp) cat_bins[1][cat].append(cur_inp) cat_bins[2][cat].append(cur_pred) cat_bins[3][cat].append(next_pred) cat_bins[4][cat].append(atte_ent) except: pass last_inp_mean = get_statistics(cat_bins[0]) cur_inp_mean = get_statistics(cat_bins[1]) cur_pred_mean = get_statistics(cat_bins[2]) next_pred_mean = get_statistics(cat_bins[3]) atte_ent_mean = get_statistics(cat_bins[4]) return last_inp_mean, cur_inp_mean, cur_pred_mean, next_pred_mean, atte_ent_mean def read_stack_data(last_inp_mean, cur_inp_mean, cur_pred_mean, next_pred_mean, seps=10): bar0 = last_inp_mean bar1 = cur_inp_mean bar2 = cur_pred_mean bar3 = next_pred_mean from operator import add bar01 = np.add(bar0, bar1).tolist() bar012 = np.add(bar01, bar2).tolist() # x = list(range(10)) return bar0, bar1, bar2, bar3, bar01, bar012 def plot_single_line(this_fig, spec_config, input_data, step_size=0.5, ent_max=5, show_x_ticks=False, show_y_ticks=True, data_name="", model_name="", ymin=2, ymax=5): segs = np.arange(0, ent_max, step_size).tolist() # colorblind = sns.color_palette("coolwarm", 10)[::-1] last_inp_mean, cur_inp_mean, cur_pred_mean, next_pred_mean, atte_ent_mean = input_data axes = this_fig.add_subplot(spec_config) sns.lineplot(x=list(np.arange(0, 5, step_size)), y=atte_ent_mean, markers=True, dashes=False) # axes = sns.boxplot(x=x, y=y, palette=colorblind, showfliers=False) axes.xaxis.set_major_locator(MultipleLocator(1)) axes.xaxis.set_major_formatter(FormatStrFormatter('%d')) # For the minor ticks, use no labels; default NullFormatter. axes.xaxis.set_minor_locator(MultipleLocator(0.5)) # axes.get_ylim() # axes.set_ylim(ymin, ymax) if show_x_ticks: # x_vals = [m * step_size for m in xticks] # axes.set_xticklabels(x_vals, rotation='vertical')center pass else: plt.setp(axes.get_xticklabels(), visible=False) # if not show_y_ticks: # plt.setp(axes.get_yticklabels(), visible=False) if data_name != "": axes.set_ylabel(data_name) else: axes.set_ylabel("") if model_name != "": axes.set_title(model_name) return axes def plot_single_box(this_fig, spec_config, input_data, step_size=0.5, ent_max=5, show_x_ticks=False, show_y_ticks=True, ylim=0.8, data_name="", model_name="", show_legend=False): segs = np.arange(0, ent_max, step_size).tolist() # colorblind = sns.color_palette("coolwarm", 10)[::-1] last_inp_mean, cur_inp_mean, cur_pred_mean, next_pred_mean, atte_ent_mean = input_data bar0, bar1, bar2, bar3, bar01, bar012 = read_stack_data(last_inp_mean, cur_inp_mean, cur_pred_mean, next_pred_mean) colorblind = sns.color_palette("coolwarm", 4) # colorblind = sns.color_palette("Set2") # colorblind = sns.color_palette() catnames = ['$y_{t-2}$', '$y_{t-1}$', '$y_{t}$', '$y_{t+1}$'] linewidth = 1.5 axes = this_fig.add_subplot(spec_config) x = list(np.arange(0, 5, 0.5)) axes.bar(x, bar0, color=colorblind[0], # edgecolor=colorblind[0],linewidth=linewidth, label=catnames[0], width=step_size, # hatch='/' ) axes.bar(x, bar1, bottom=bar0, # edgecolor='white', linewidth=1, label=catnames[1], width=step_size, # hatch='-', facecolor=colorblind[1], # histtype='step', facecolor='g', # alpha=0.75 # ,hatch='-' ) axes.bar(x, bar2, bottom=bar01, # edgecolor=colorblind[3], linewidth=0, label=catnames[2], width=step_size, facecolor=colorblind[3], # histtype='step', # hatch='|' # ,hatch='|' ) axes.bar(x, bar3, bottom=bar012, color=colorblind[2], label=catnames[3], width=step_size, # edgecolor=colorblind[2], linewidth=linewidth, # hatch='\\' ) # axes = sns.boxplot(x=x, y=y, palette=colorblind, showfliers=False) axes.xaxis.set_major_locator(MultipleLocator(1)) axes.xaxis.set_major_formatter(FormatStrFormatter('%d')) if show_legend: axes.legend(ncol=2, frameon=False) # For the minor ticks, use no labels; default NullFormatter. axes.xaxis.set_minor_locator(MultipleLocator(0.5)) axes.set_ylim(0, ylim) if show_x_ticks: # x_vals = [m * step_size for m in xticks] # axes.set_xticklabels(x_vals, rotation='vertical')center pass else: plt.setp(axes.get_xticklabels(), visible=False) if not show_y_ticks: plt.setp(axes.get_yticklabels(), visible=False) if data_name != "": axes.set_ylabel(data_name) else: axes.set_ylabel("") if model_name != "": axes.set_title(model_name) return axes def plot_box(val_ent_pairs, title=None, step_size=.25): # max_pred_ent = max([p[1] for p in val_ent_pairs]) # segs = np.linspace(0, max_pred_ent + 0.1, num=20).tolist() segs = np.arange(0, 8, step_size).tolist() colorblind = sns.color_palette("coolwarm", 10)[::-1] bins = [[] for _ in range(len(segs))] x, y = [], [] for p in val_ent_pairs: v, ent = p[0], p[1] cat = int(ent // step_size) try: bins[cat].append(v) x.append(cat) y.append(v) except: pass fig1, ax1 = plt.subplots() ax1.set_title(title) ax1 = sns.violinplot(x=x, y=y, cut=0, palette=colorblind, inner='quartile') # ax1.set_xticks( np.arange(0, 8, step_size).tolist()) # ax1.set_xticklabels(np.arange(0, 8, step_size).tolist()) return ax1 def plot_single_scatter(val_ent_pairs, title): y_attn_frac = [m[0] for m in val_ent_pairs] x_pred_ent = [m[1] for m in val_ent_pairs] ax = sns.jointplot(x=x_pred_ent, y=y_attn_frac, kind="hex", color="#4CB391") # ax = sns.scatterplot(x=x_pred_ent,y=y_attn_frac) # # sns.histplot(x=x_pred_ent, y=y_attn_frac, bins=50, pthresh=.1, cmap="mako") # sns.kdeplot(x=x_pred_ent, y=y_attn_frac, levels=5,linewidths=1) # ax.set_title(title) plt.show() return ax def analyze_attention_y_entropy(max_time_step, attn_tlle, pred_distribution, input_doc, ban_positions, logits, nuc, top_p): # T = attn_tlle.shape[0] # data_pairs = [[], [], [], []] data = [] for t in range(max_time_step): try: t_pred_ent = comp_entropy(pred_distribution[t], nuc, top_p) last_inp, cur_inp, cur_pred, next_pred = get_ys(t, logits) all_attns_counter = _y_entropy_step(attn_tlle[t], input_doc, ban_positions) total_attn_val = sum(all_attns_counter.values()) all_attention = list(all_attns_counter.values()) np_attn = np.asarray(all_attention) / total_attn_val attn_ent = comp_entropy(np_attn) last_inp_val = retrieve_tok_val(all_attns_counter, last_inp) cur_inp_val = retrieve_tok_val(all_attns_counter, cur_inp) cur_pred_val = retrieve_tok_val(all_attns_counter, cur_pred) next_pred_val = retrieve_tok_val(all_attns_counter, next_pred) # data_pairs[0].append((last_inp_val / total_attn_val, t_pred_ent)) # data_pairs[1].append((cur_inp_val / total_attn_val, t_pred_ent)) # data_pairs[2].append((cur_pred_val / total_attn_val, t_pred_ent)) data.append((last_inp_val / total_attn_val, cur_inp_val / total_attn_val, cur_pred_val / total_attn_val, next_pred_val / total_attn_val, t_pred_ent, attn_ent)) except: pass # data_pairs[3].append((next_pred_val / total_attn_val, t_pred_ent)) return data import pickle import numpy as np from scipy.stats import entropy import matplotlib.gridspec as gridspec import multiprocessing def detect_useless_ids(indices): last = -100 good_indices = [] for x in indices: if x - 5 > last: last = x good_indices.append(x) else: break return good_indices def process_data_single(args, f, eos_token_ids): print("running") BOS_TOKEN = 0 with open(os.path.join(args.cur_dir, f), 'rb') as fd: data = pickle.load(fd) attentions, pred_distb, logits, input_doc = data['attentions'], data['pred_distributions'], data['logits'], \ data['input_doc'] timesteps = len(attentions) attentions_tlle = convert_enc_attn(attentions, merge_layer_head=False) # T,L,L,E attention_tle = convert_enc_attn(attentions, merge_layer_head=True) # T,L,E document_len = input_doc.shape[0] input_doc = input_doc.astype(np.int).tolist() logits = logits.tolist() indices = [i for i, x in enumerate(logits) if x in eos_token_ids] good_indices = detect_useless_ids(indices) if good_indices: max_t = good_indices[-1] else: max_t = attentions_tlle.shape[0] # dec_inp_logits = [BOS_TOKEN] + logits[:-1] pred_distb = np.exp(pred_distb) # time step, vocab size # pred_ent = entropy(pred_distb, axis=-1) idf_flag = compute_idf(attention_tle[:max_t]) # E ban_positions = get_ban_positions(idf_flag) # ban_positions = [] data_pairs = analyze_attention_y_entropy(max_t, attentions_tlle, pred_distb, input_doc, ban_positions, logits, args.nucleus, args.nuc_prob) return data_pairs from itertools import product def plot_stack_vocab(cnndm_peg, xsum_peg, cnndm_bart, xsum_bart): fig = plt.figure(figsize=(FIG_SIZE_x, FIG_SIZE_x - 4)) spec2 = gridspec.GridSpec(ncols=2, nrows=2, figure=fig) plot_single_box(this_fig=fig, spec_config=spec2[0, 0], input_data=cnndm_peg, show_x_ticks=False, show_y_ticks=True, data_name="CNN/DM", model_name="PEGASUS", ylim=0.7) plot_single_box(this_fig=fig, spec_config=spec2[0, 1], input_data=cnndm_bart, show_x_ticks=False, show_y_ticks=False, model_name="BART", ylim=0.7) plot_single_box(this_fig=fig, spec_config=spec2[1, 0], input_data=xsum_peg, show_x_ticks=True, show_y_ticks=True, data_name='XSum', ylim=0.4) plot_single_box(this_fig=fig, spec_config=spec2[1, 1], input_data=xsum_bart, show_x_ticks=True, show_y_ticks=False, ylim=0.4, show_legend=True) fig.text(0.5, 0.01, 'Prediction Entropy', ha='center', fontsize=font_size) fig.text(0.0, 0.5, 'Vocab Projected Attention', va='center', rotation='vertical', fontsize=font_size) fig.tight_layout() plt.savefig(f"x_pred_ent_y_attn_frac.pdf", dpi=dpi, bbox_inches='tight') plt.show() plt.close() def run_one_fig(spec, args, num_samples=300): print(f"--{spec}--") CUR_DIR = os.path.join(args.prob_meta_dir, spec) args.cur_dir = CUR_DIR files = os.listdir(CUR_DIR) random.shuffle(files) files = files[:num_samples] BOS_TOKEN = 0 print(args.spec_name) if 'pegasus' in args.model_name: from transformers import PegasusTokenizer bpe_tokenizer = PegasusTokenizer.from_pretrained(args.model_name) EOS_TOK_IDs = [106, bpe_tokenizer.eos_token_id, 2] # <n> elif 'gpt' in args.model_name: from transformers import GPT2Tokenizer bpe_tokenizer = GPT2Tokenizer.from_pretrained('gpt2') EOS_TOK_IDs = [bpe_tokenizer.eos_token_id] elif 'bart' in args.model_name: from transformers import BartTokenizer bpe_tokenizer = BartTokenizer.from_pretrained(args.model_name) EOS_TOK_IDs = [bpe_tokenizer.eos_token_id] else: raise NotImplementedError # process_data_single(args, files[0], eos_token_ids=EOS_TOK_IDs) len_samples = len(files) cpu_cnt = multiprocessing.cpu_count() with multiprocessing.Pool(processes=cpu_cnt) as pool: results = pool.starmap(process_data_single, zip([args] * len_samples, files, [EOS_TOK_IDs] * len_samples)) output = list(itertools.chain.from_iterable(results)) print(f"Samples: {len(output)}") output = proceed_data(10, output) return output def plot_ant_entropy(cnndm_peg, xsum_peg, cnndm_bart, xsum_bart): fig = plt.figure(figsize=(FIG_SIZE_x, FIG_SIZE_x - 5)) step_size = 0.5 d = {'PEG$_{C}$': cnndm_peg[-1], 'PEG-X': xsum_peg[-1], 'BART-C': cnndm_bart[-1], 'BART-X': xsum_bart[-1], } # df = pd.DataFrame(data=d) ax = fig.add_subplot(1, 1, 1) # line1 = sns.lineplot(x=list(np.arange(0, 5, step_size)), y=cnndm_peg[-1], label='PEG$_{C}$', markers='x') plt.plot(list(np.arange(0, 5, step_size)), cnndm_peg[-1], label='PEG$_{C}$', marker='+', # color='k' ) plt.plot(list(np.arange(0, 5, step_size)), xsum_peg[-1], label='PEG$_{X}$', marker='x', # color='k' ) plt.plot(list(np.arange(0, 5, step_size)), cnndm_bart[-1], label='BART$_{C}$', ls='--', marker='+', # color='k' ) plt.plot(list(np.arange(0, 5, step_size)), xsum_bart[-1], label='BART$_{X}$', ls='--', marker='x', # color='k' ) plt.legend(loc='best', ncol=2, frameon=False) # spec2 = gridspec.GridSpec(ncols=2, nrows=2, figure=fig) # plot_single_line(this_fig=fig, spec_config=spec2[0, 0], input_data=cnndm_peg, show_x_ticks=False, # show_y_ticks=True, data_name="CNN/DM", model_name="PEGASUS", ymin=2, ymax=4 # ) # plot_single_line(this_fig=fig, spec_config=spec2[0, 1], input_data=cnndm_bart, show_x_ticks=False, # show_y_ticks=False, model_name="BART", ymin=2, ymax=4) # plot_single_line(this_fig=fig, spec_config=spec2[1, 0], input_data=xsum_peg, show_x_ticks=True, show_y_ticks=True, # data_name='XSUM', ymin=2.5, ymax=4) # plot_single_line(this_fig=fig, spec_config=spec2[1, 1], input_data=xsum_bart, show_x_ticks=True, # show_y_ticks=False, ymin=2.5, ymax=4) ax.set_ylabel('Attention Entropy') ax.set_xlabel('Prediction Entropy') ax.xaxis.set_major_locator(MultipleLocator(0.5)) # ax.xaxis.set_major_formatter(FormatStrFormatter('%d')) # For the minor ticks, use no labels; default NullFormatter. # plt.xaxis.set_minor_locator(MultipleLocator(0.5)) fig.tight_layout() plt.savefig(f"atten_entropy.pdf", dpi=dpi, bbox_inches='tight') # fig.text(0.5, 0.01, 'Prediction Entropy', ha='center') # fig.text(0.0, 0.5, '', va='center', rotation='vertical') plt.show() plt.close() import pandas as pd if __name__ == '__main__': args = parse_arg() print("Looking at attention") if 'pegasus' in args.model_name: from transformers import PegasusTokenizer bpe_tokenizer = PegasusTokenizer.from_pretrained(args.model_name) EOS_TOK_IDs = [106, bpe_tokenizer.eos_token_id] # <n> BOS_TOK_ID = 0 else: raise NotImplementedError cnndm_peg = "d_cnn_dailymail-m_googlepegasuscnn_dailymail-full1" xsum_peg = "d_xsum-m_googlepegasusxsum-full1" cnndm_bart = "d_cnn_dailymail-m_facebookbartlargecnn-full1" xsum_bart = 'd_xsum-m_facebookbartlargexsum-full1' xsum_bart_out = run_one_fig(xsum_bart, args) cnndm_peg_out = run_one_fig(cnndm_peg, args) xsum_peg_out = run_one_fig(xsum_peg, args) cnndm_bart_out = run_one_fig(cnndm_bart, args) # df = pd.DataFrame(data=xsum_bart_out) # plot_stack_vocab(cnndm_peg_out, xsum_peg_out, cnndm_bart_out, xsum_bart_out) plot_stack_vocab(cnndm_peg_out, xsum_peg_out, cnndm_bart_out, xsum_bart_out) plot_ant_entropy(cnndm_peg_out, xsum_peg_out, cnndm_bart_out, xsum_bart_out) # plot_box(all_data_pairs[0], 'last_inp') # plot_box(all_data_pairs[1], 'cur_inp') # plot_box(all_data_pairs[2], 'cur_pred') # plot_box(all_data_pairs[3], 'next_pred')
[ "matplotlib.pyplot.grid", "matplotlib.pyplot.hist", "matplotlib.pyplot.ylabel", "multiprocessing.cpu_count", "numpy.argsort", "util.parse_arg", "seaborn.violinplot", "numpy.arange", "analyze_entropy.comp_entropy", "os.listdir", "seaborn.color_palette", "matplotlib.pyplot.xlabel", "numpy.asar...
[((472, 506), 'matplotlib.font_manager._rebuild', 'matplotlib.font_manager._rebuild', ([], {}), '()\n', (504, 506), False, 'import matplotlib\n'), ((581, 619), 'matplotlib.pyplot.rcParams.update', 'plt.rcParams.update', (["{'font.size': 14}"], {}), "({'font.size': 14})\n", (600, 619), True, 'import matplotlib.pyplot as plt\n'), ((1728, 1737), 'collections.Counter', 'Counter', ([], {}), '()\n', (1735, 1737), False, 'from collections import Counter\n'), ((2133, 2142), 'collections.Counter', 'Counter', ([], {}), '()\n', (2140, 2142), False, 'from collections import Counter\n'), ((2666, 2718), 'matplotlib.pyplot.hist', 'plt.hist', (['xs'], {'bins': '(20)', 'weights': 'weights', 'density': '(True)'}), '(xs, bins=20, weights=weights, density=True)\n', (2674, 2718), True, 'import matplotlib.pyplot as plt\n'), ((2724, 2746), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Pred Ent"""'], {}), "('Pred Ent')\n", (2734, 2746), True, 'import matplotlib.pyplot as plt\n'), ((2751, 2773), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Cum Attn"""'], {}), "('Cum Attn')\n", (2761, 2773), True, 'import matplotlib.pyplot as plt\n'), ((2779, 2795), 'matplotlib.pyplot.title', 'plt.title', (['title'], {}), '(title)\n', (2788, 2795), True, 'import matplotlib.pyplot as plt\n'), ((2800, 2814), 'matplotlib.pyplot.grid', 'plt.grid', (['(True)'], {}), '(True)\n', (2808, 2814), True, 'import matplotlib.pyplot as plt\n'), ((2819, 2829), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2827, 2829), True, 'import matplotlib.pyplot as plt\n'), ((6330, 6362), 'seaborn.color_palette', 'sns.color_palette', (['"""coolwarm"""', '(4)'], {}), "('coolwarm', 4)\n", (6347, 6362), True, 'import seaborn as sns\n'), ((9057, 9071), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (9069, 9071), True, 'import matplotlib.pyplot as plt\n'), ((9107, 9176), 'seaborn.violinplot', 'sns.violinplot', ([], {'x': 'x', 'y': 'y', 'cut': '(0)', 'palette': 'colorblind', 'inner': '"""quartile"""'}), "(x=x, y=y, cut=0, palette=colorblind, inner='quartile')\n", (9121, 9176), True, 'import seaborn as sns\n'), ((9469, 9540), 'seaborn.jointplot', 'sns.jointplot', ([], {'x': 'x_pred_ent', 'y': 'y_attn_frac', 'kind': '"""hex"""', 'color': '"""#4CB391"""'}), "(x=x_pred_ent, y=y_attn_frac, kind='hex', color='#4CB391')\n", (9482, 9540), True, 'import seaborn as sns\n'), ((9786, 9796), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9794, 9796), True, 'import matplotlib.pyplot as plt\n'), ((12217, 12269), 'util.convert_enc_attn', 'convert_enc_attn', (['attentions'], {'merge_layer_head': '(False)'}), '(attentions, merge_layer_head=False)\n', (12233, 12269), False, 'from util import convert_enc_attn, parse_arg\n'), ((12301, 12352), 'util.convert_enc_attn', 'convert_enc_attn', (['attentions'], {'merge_layer_head': '(True)'}), '(attentions, merge_layer_head=True)\n', (12317, 12352), False, 'from util import convert_enc_attn, parse_arg\n'), ((12772, 12790), 'numpy.exp', 'np.exp', (['pred_distb'], {}), '(pred_distb)\n', (12778, 12790), True, 'import numpy as np\n'), ((12877, 12911), 'analyze_prob_attn.compute_idf', 'compute_idf', (['attention_tle[:max_t]'], {}), '(attention_tle[:max_t])\n', (12888, 12911), False, 'from analyze_prob_attn import compute_idf, get_ban_positions\n'), ((12937, 12964), 'analyze_prob_attn.get_ban_positions', 'get_ban_positions', (['idf_flag'], {}), '(idf_flag)\n', (12954, 12964), False, 'from analyze_prob_attn import compute_idf, get_ban_positions\n'), ((13311, 13359), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(FIG_SIZE_x, FIG_SIZE_x - 4)'}), '(figsize=(FIG_SIZE_x, FIG_SIZE_x - 4))\n', (13321, 13359), True, 'import matplotlib.pyplot as plt\n'), ((13372, 13419), 'matplotlib.gridspec.GridSpec', 'gridspec.GridSpec', ([], {'ncols': '(2)', 'nrows': '(2)', 'figure': 'fig'}), '(ncols=2, nrows=2, figure=fig)\n', (13389, 13419), True, 'import matplotlib.gridspec as gridspec\n'), ((14330, 14402), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""x_pred_ent_y_attn_frac.pdf"""'], {'dpi': 'dpi', 'bbox_inches': '"""tight"""'}), "(f'x_pred_ent_y_attn_frac.pdf', dpi=dpi, bbox_inches='tight')\n", (14341, 14402), True, 'import matplotlib.pyplot as plt\n'), ((14407, 14417), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (14415, 14417), True, 'import matplotlib.pyplot as plt\n'), ((14422, 14433), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (14431, 14433), True, 'import matplotlib.pyplot as plt\n'), ((14521, 14559), 'os.path.join', 'os.path.join', (['args.prob_meta_dir', 'spec'], {}), '(args.prob_meta_dir, spec)\n', (14533, 14559), False, 'import os, random\n'), ((14599, 14618), 'os.listdir', 'os.listdir', (['CUR_DIR'], {}), '(CUR_DIR)\n', (14609, 14618), False, 'import os, random\n'), ((14623, 14644), 'random.shuffle', 'random.shuffle', (['files'], {}), '(files)\n', (14637, 14644), False, 'import os, random\n'), ((15508, 15535), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (15533, 15535), False, 'import multiprocessing\n'), ((15938, 15986), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(FIG_SIZE_x, FIG_SIZE_x - 5)'}), '(figsize=(FIG_SIZE_x, FIG_SIZE_x - 5))\n', (15948, 15986), True, 'import matplotlib.pyplot as plt\n'), ((16891, 16936), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""best"""', 'ncol': '(2)', 'frameon': '(False)'}), "(loc='best', ncol=2, frameon=False)\n", (16901, 16936), True, 'import matplotlib.pyplot as plt\n'), ((18098, 18161), 'matplotlib.pyplot.savefig', 'plt.savefig', (['f"""atten_entropy.pdf"""'], {'dpi': 'dpi', 'bbox_inches': '"""tight"""'}), "(f'atten_entropy.pdf', dpi=dpi, bbox_inches='tight')\n", (18109, 18161), True, 'import matplotlib.pyplot as plt\n'), ((18292, 18302), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (18300, 18302), True, 'import matplotlib.pyplot as plt\n'), ((18307, 18318), 'matplotlib.pyplot.close', 'plt.close', ([], {}), '()\n', (18316, 18318), True, 'import matplotlib.pyplot as plt\n'), ((18380, 18391), 'util.parse_arg', 'parse_arg', ([], {}), '()\n', (18389, 18391), False, 'from util import convert_enc_attn, parse_arg\n'), ((1635, 1689), 'numpy.argsort', 'np.argsort', (['attn_distb'], {'axis': '(-1)', 'kind': 'None', 'order': 'None'}), '(attn_distb, axis=-1, kind=None, order=None)\n', (1645, 1689), True, 'import numpy as np\n'), ((5056, 5074), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(1)'], {}), '(1)\n', (5071, 5074), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\n'), ((5111, 5135), 'matplotlib.ticker.FormatStrFormatter', 'FormatStrFormatter', (['"""%d"""'], {}), "('%d')\n", (5129, 5135), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\n'), ((5236, 5256), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(0.5)'], {}), '(0.5)\n', (5251, 5256), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\n'), ((6610, 6630), 'numpy.arange', 'np.arange', (['(0)', '(5)', '(0.5)'], {}), '(0, 5, 0.5)\n', (6619, 6630), True, 'import numpy as np\n'), ((7711, 7729), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(1)'], {}), '(1)\n', (7726, 7729), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\n'), ((7766, 7790), 'matplotlib.ticker.FormatStrFormatter', 'FormatStrFormatter', (['"""%d"""'], {}), "('%d')\n", (7784, 7790), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\n'), ((7954, 7974), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(0.5)'], {}), '(0.5)\n', (7969, 7974), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\n'), ((8720, 8753), 'seaborn.color_palette', 'sns.color_palette', (['"""coolwarm"""', '(10)'], {}), "('coolwarm', 10)\n", (8737, 8753), True, 'import seaborn as sns\n'), ((11965, 11980), 'pickle.load', 'pickle.load', (['fd'], {}), '(fd)\n', (11976, 11980), False, 'import pickle\n'), ((14834, 14883), 'transformers.PegasusTokenizer.from_pretrained', 'PegasusTokenizer.from_pretrained', (['args.model_name'], {}), '(args.model_name)\n', (14866, 14883), False, 'from transformers import PegasusTokenizer\n'), ((15545, 15584), 'multiprocessing.Pool', 'multiprocessing.Pool', ([], {'processes': 'cpu_cnt'}), '(processes=cpu_cnt)\n', (15565, 15584), False, 'import multiprocessing\n'), ((15727, 15765), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['results'], {}), '(results)\n', (15756, 15765), False, 'import itertools\n'), ((17866, 17886), 'matplotlib.ticker.MultipleLocator', 'MultipleLocator', (['(0.5)'], {}), '(0.5)\n', (17881, 17886), False, 'from matplotlib.ticker import MultipleLocator, FormatStrFormatter, AutoMinorLocator\n'), ((18538, 18587), 'transformers.PegasusTokenizer.from_pretrained', 'PegasusTokenizer.from_pretrained', (['args.model_name'], {}), '(args.model_name)\n', (18570, 18587), False, 'from transformers import PegasusTokenizer\n'), ((2997, 3017), 'statistics.mean', 'statistics.mean', (['row'], {}), '(row)\n', (3012, 3017), False, 'import statistics\n'), ((4266, 4284), 'numpy.add', 'np.add', (['bar0', 'bar1'], {}), '(bar0, bar1)\n', (4272, 4284), True, 'import numpy as np\n'), ((4307, 4326), 'numpy.add', 'np.add', (['bar01', 'bar2'], {}), '(bar01, bar2)\n', (4313, 4326), True, 'import numpy as np\n'), ((4612, 4644), 'numpy.arange', 'np.arange', (['(0)', 'ent_max', 'step_size'], {}), '(0, ent_max, step_size)\n', (4621, 4644), True, 'import numpy as np\n'), ((6001, 6033), 'numpy.arange', 'np.arange', (['(0)', 'ent_max', 'step_size'], {}), '(0, ent_max, step_size)\n', (6010, 6033), True, 'import numpy as np\n'), ((8667, 8693), 'numpy.arange', 'np.arange', (['(0)', '(8)', 'step_size'], {}), '(0, 8, step_size)\n', (8676, 8693), True, 'import numpy as np\n'), ((10121, 10167), 'analyze_entropy.comp_entropy', 'comp_entropy', (['pred_distribution[t]', 'nuc', 'top_p'], {}), '(pred_distribution[t], nuc, top_p)\n', (10133, 10167), False, 'from analyze_entropy import comp_entropy\n'), ((10538, 10559), 'analyze_entropy.comp_entropy', 'comp_entropy', (['np_attn'], {}), '(np_attn)\n', (10550, 10559), False, 'from analyze_entropy import comp_entropy\n'), ((11906, 11935), 'os.path.join', 'os.path.join', (['args.cur_dir', 'f'], {}), '(args.cur_dir, f)\n', (11918, 11935), False, 'import os, random\n'), ((15057, 15094), 'transformers.GPT2Tokenizer.from_pretrained', 'GPT2Tokenizer.from_pretrained', (['"""gpt2"""'], {}), "('gpt2')\n", (15086, 15094), False, 'from transformers import GPT2Tokenizer\n'), ((16352, 16378), 'numpy.arange', 'np.arange', (['(0)', '(5)', 'step_size'], {}), '(0, 5, step_size)\n', (16361, 16378), True, 'import numpy as np\n'), ((16485, 16511), 'numpy.arange', 'np.arange', (['(0)', '(5)', 'step_size'], {}), '(0, 5, step_size)\n', (16494, 16511), True, 'import numpy as np\n'), ((16617, 16643), 'numpy.arange', 'np.arange', (['(0)', '(5)', 'step_size'], {}), '(0, 5, step_size)\n', (16626, 16643), True, 'import numpy as np\n'), ((16761, 16787), 'numpy.arange', 'np.arange', (['(0)', '(5)', 'step_size'], {}), '(0, 5, step_size)\n', (16770, 16787), True, 'import numpy as np\n'), ((4874, 4900), 'numpy.arange', 'np.arange', (['(0)', '(5)', 'step_size'], {}), '(0, 5, step_size)\n', (4883, 4900), True, 'import numpy as np\n'), ((10472, 10497), 'numpy.asarray', 'np.asarray', (['all_attention'], {}), '(all_attention)\n', (10482, 10497), True, 'import numpy as np\n'), ((15254, 15300), 'transformers.BartTokenizer.from_pretrained', 'BartTokenizer.from_pretrained', (['args.model_name'], {}), '(args.model_name)\n', (15283, 15300), False, 'from transformers import BartTokenizer\n')]
import io import numpy as np import sys import math import tensorflow as tf import tensorflow_addons as tfa import tensorflow_datasets as tfds def _normalize_img(img, label): img = tf.cast(img, tf.float32) / 255. return (img, label) def get_data(data_type = 'mnist', data_kind='img'): train_dataset, test_dataset = tfds.load(name=data_type, split=['train', 'test'], as_supervised=True) # Build your input pipelines train_dataset = train_dataset.shuffle(1024).batch(32) test_dataset = test_dataset.batch(32) if data_kind == 'img': train_dataset = train_dataset.map(_normalize_img) test_dataset = test_dataset.map(_normalize_img) return train_dataset, test_dataset def get_model(shape=(28,28,1)): return tf.keras.Sequential([ tf.keras.layers.Conv2D(filters=64, kernel_size=2, padding='same', activation='relu', input_shape=shape), tf.keras.layers.MaxPooling2D(pool_size=2), tf.keras.layers.Dropout(0.3), tf.keras.layers.Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'), tf.keras.layers.MaxPooling2D(pool_size=2), tf.keras.layers.Dropout(0.3), tf.keras.layers.Flatten(), tf.keras.layers.Dense(256, activation=None), # No activation on final dense layer tf.keras.layers.Lambda(lambda x: tf.math.l2_normalize(x, axis=1)) # L2 normalize embeddings, ]) def get_model_LSTM(): max_features = 20000 # Only consider the top 20k words return tf.keras.Sequential( [ tf.keras.Input(shape=(None,), dtype="int32"), tf.keras.layers.Embedding(max_features, 128), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)), tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)), tf.keras.layers.Dense(256, activation=None) ]) def get_model_FF(): max_features = 20000 # Only consider the top 20k words return tf.keras.Sequential([ # tf.keras.Input(shape=(None,), dtype="int32"), # tf.keras.layers.Embedding(max_features, 128), # tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64, return_sequences=True)), # tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(64)), tf.keras.layers.Dense(256, input_dim=2, activation=None), tf.keras.layers.Dense(256, input_dim=2, activation=None) ]) def get_data_text(): max_features = 20000 # Only consider the top 20k words maxlen = 200 # Only consider the first 200 words of each movie review (x_train, y_train), (x_val, y_val) = tf.keras.datasets.imdb.load_data( num_words=max_features ) print(len(x_train), "Training sequences") print(len(x_val), "Validation sequences") x_train = tf.keras.preprocessing.sequence.pad_sequences(x_train, maxlen=maxlen) x_val = tf.keras.preprocessing.sequence.pad_sequences(x_val, maxlen=maxlen) return (x_train, y_train), (x_val, y_val) def decide(val): if pow(val, 2) < 0.25 or pow(val, 2) > 0.75: return 1 else: return 0 def decide_two(val1, val2): if (pow(val1, 2) + pow(val2, 2)) < 0.25 or (pow(val1, 2) + pow(val2, 2)) > 0.75: return 1 else: return 0 def decide_two_sign(val1, val2): if math.sin(pow(val1, 2) + pow(val2, 2)) < -0.5 or math.sin(pow(val1, 2) + pow(val2, 2)) > 0.5: return 1 else: return 0 ''' format: (x_train, y_train), (x_val, y_val) x_train.shape: (10,): double y_train.shape: (10,): bool ''' def get_data_numerical(): maxlen = 20000 x_train = np.random.rand(maxlen, 1) for item in x_train: item[0] = round(item[0], 3) y_train = np.zeros(x_train.shape) for id_r, item_r in enumerate(x_train): y_train[id_r][0] = decide(item_r[0]) x_val = np.random.rand(maxlen, 1) for item in x_val: item[0] = round(item[0], 3) y_val = np.zeros(x_val.shape) for id_r, item_r in enumerate(x_val): y_val[id_r][0] = decide(item_r[0]) return (x_train, y_train), (x_val, y_val) def get_data_numerical_two(): maxlen = 20000 x_train = np.random.rand(maxlen, 2) for item in x_train: item[0] = round(item[0], 3) item[1] = round(item[1], 3) y_train = np.zeros((maxlen, 1)) for id_r, item_r in enumerate(x_train): y_train[id_r][0] = decide_two_sign(item_r[0], item_r[1]) x_val = np.random.rand(maxlen, 2) for item in x_val: item[0] = round(item[0], 3) item[1] = round(item[1], 3) y_val = np.zeros((maxlen, 1)) for id_r, item_r in enumerate(x_val): y_val[id_r][0] = decide_two_sign(item_r[0], item_r[1]) return (x_train, y_train), (x_val, y_val) def main(): _type = sys.argv[1] if _type == 'mnist': model = get_model() train_dataset, test_dataset = get_data() elif _type == 'imdb': model = get_model_LSTM() (x_train, y_train), (x_val, y_val) = get_data_text() test_dataset = (x_val, y_val) elif _type == 'func': model = get_model_FF() (x_train, y_train), (x_val, y_val) = get_data_numerical_two() test_dataset = (x_val, y_val) # Compile the model model.compile( optimizer=tf.keras.optimizers.Adam(0.001), loss=tfa.losses.TripletSemiHardLoss()) # model.compile( # optimizer=tf.keras.optimizers.Adam(0.001), # loss=tf.keras.losses.BinaryCrossentropy()) if _type == 'mnist': history = model.fit(train_dataset, epochs=1) results = model.predict(test_dataset) elif _type == 'imdb': history = model.fit(x_train, y_train, batch_size=32, epochs=1) results = model.predict(test_dataset) elif _type == 'func': history = model.fit(x_train, y_train, batch_size=32, epochs=2) results = model.predict(x_val) # Save test embeddings for visualization in projector np.savetxt("vecs.tsv", results, delimiter='\t') # out_m = io.open('meta.tsv', 'w', encoding='utf-8') # for img, labels in tfds.as_numpy(test_dataset): # [out_m.write(str(x) + "\n") for x in labels] # out_m.close() try: from google.colab import files files.download('vecs.tsv') files.download('meta.tsv') except: pass def print_dataset(ds): for example in ds.take(1): image, label = example[0], example[1] if __name__ == "__main__": main()
[ "numpy.random.rand", "tensorflow.keras.preprocessing.sequence.pad_sequences", "tensorflow.keras.layers.Dense", "tensorflow.keras.datasets.imdb.load_data", "tensorflow_addons.losses.TripletSemiHardLoss", "tensorflow.cast", "google.colab.files.download", "tensorflow.keras.layers.Conv2D", "tensorflow.m...
[((331, 401), 'tensorflow_datasets.load', 'tfds.load', ([], {'name': 'data_type', 'split': "['train', 'test']", 'as_supervised': '(True)'}), "(name=data_type, split=['train', 'test'], as_supervised=True)\n", (340, 401), True, 'import tensorflow_datasets as tfds\n'), ((2560, 2616), 'tensorflow.keras.datasets.imdb.load_data', 'tf.keras.datasets.imdb.load_data', ([], {'num_words': 'max_features'}), '(num_words=max_features)\n', (2592, 2616), True, 'import tensorflow as tf\n'), ((2737, 2806), 'tensorflow.keras.preprocessing.sequence.pad_sequences', 'tf.keras.preprocessing.sequence.pad_sequences', (['x_train'], {'maxlen': 'maxlen'}), '(x_train, maxlen=maxlen)\n', (2782, 2806), True, 'import tensorflow as tf\n'), ((2819, 2886), 'tensorflow.keras.preprocessing.sequence.pad_sequences', 'tf.keras.preprocessing.sequence.pad_sequences', (['x_val'], {'maxlen': 'maxlen'}), '(x_val, maxlen=maxlen)\n', (2864, 2886), True, 'import tensorflow as tf\n'), ((3564, 3589), 'numpy.random.rand', 'np.random.rand', (['maxlen', '(1)'], {}), '(maxlen, 1)\n', (3578, 3589), True, 'import numpy as np\n'), ((3665, 3688), 'numpy.zeros', 'np.zeros', (['x_train.shape'], {}), '(x_train.shape)\n', (3673, 3688), True, 'import numpy as np\n'), ((3795, 3820), 'numpy.random.rand', 'np.random.rand', (['maxlen', '(1)'], {}), '(maxlen, 1)\n', (3809, 3820), True, 'import numpy as np\n'), ((3892, 3913), 'numpy.zeros', 'np.zeros', (['x_val.shape'], {}), '(x_val.shape)\n', (3900, 3913), True, 'import numpy as np\n'), ((4130, 4155), 'numpy.random.rand', 'np.random.rand', (['maxlen', '(2)'], {}), '(maxlen, 2)\n', (4144, 4155), True, 'import numpy as np\n'), ((4276, 4297), 'numpy.zeros', 'np.zeros', (['(maxlen, 1)'], {}), '((maxlen, 1))\n', (4284, 4297), True, 'import numpy as np\n'), ((4424, 4449), 'numpy.random.rand', 'np.random.rand', (['maxlen', '(2)'], {}), '(maxlen, 2)\n', (4438, 4449), True, 'import numpy as np\n'), ((4557, 4578), 'numpy.zeros', 'np.zeros', (['(maxlen, 1)'], {}), '((maxlen, 1))\n', (4565, 4578), True, 'import numpy as np\n'), ((5971, 6018), 'numpy.savetxt', 'np.savetxt', (['"""vecs.tsv"""', 'results'], {'delimiter': '"""\t"""'}), "('vecs.tsv', results, delimiter='\\t')\n", (5981, 6018), True, 'import numpy as np\n'), ((188, 212), 'tensorflow.cast', 'tf.cast', (['img', 'tf.float32'], {}), '(img, tf.float32)\n', (195, 212), True, 'import tensorflow as tf\n'), ((6260, 6286), 'google.colab.files.download', 'files.download', (['"""vecs.tsv"""'], {}), "('vecs.tsv')\n", (6274, 6286), False, 'from google.colab import files\n'), ((6295, 6321), 'google.colab.files.download', 'files.download', (['"""meta.tsv"""'], {}), "('meta.tsv')\n", (6309, 6321), False, 'from google.colab import files\n'), ((789, 896), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(64)', 'kernel_size': '(2)', 'padding': '"""same"""', 'activation': '"""relu"""', 'input_shape': 'shape'}), "(filters=64, kernel_size=2, padding='same',\n activation='relu', input_shape=shape)\n", (811, 896), True, 'import tensorflow as tf\n'), ((902, 943), 'tensorflow.keras.layers.MaxPooling2D', 'tf.keras.layers.MaxPooling2D', ([], {'pool_size': '(2)'}), '(pool_size=2)\n', (930, 943), True, 'import tensorflow as tf\n'), ((953, 981), 'tensorflow.keras.layers.Dropout', 'tf.keras.layers.Dropout', (['(0.3)'], {}), '(0.3)\n', (976, 981), True, 'import tensorflow as tf\n'), ((991, 1079), 'tensorflow.keras.layers.Conv2D', 'tf.keras.layers.Conv2D', ([], {'filters': '(32)', 'kernel_size': '(2)', 'padding': '"""same"""', 'activation': '"""relu"""'}), "(filters=32, kernel_size=2, padding='same',\n activation='relu')\n", (1013, 1079), True, 'import tensorflow as tf\n'), ((1085, 1126), 'tensorflow.keras.layers.MaxPooling2D', 'tf.keras.layers.MaxPooling2D', ([], {'pool_size': '(2)'}), '(pool_size=2)\n', (1113, 1126), True, 'import tensorflow as tf\n'), ((1136, 1164), 'tensorflow.keras.layers.Dropout', 'tf.keras.layers.Dropout', (['(0.3)'], {}), '(0.3)\n', (1159, 1164), True, 'import tensorflow as tf\n'), ((1174, 1199), 'tensorflow.keras.layers.Flatten', 'tf.keras.layers.Flatten', ([], {}), '()\n', (1197, 1199), True, 'import tensorflow as tf\n'), ((1209, 1252), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(256)'], {'activation': 'None'}), '(256, activation=None)\n', (1230, 1252), True, 'import tensorflow as tf\n'), ((1528, 1572), 'tensorflow.keras.Input', 'tf.keras.Input', ([], {'shape': '(None,)', 'dtype': '"""int32"""'}), "(shape=(None,), dtype='int32')\n", (1542, 1572), True, 'import tensorflow as tf\n'), ((1582, 1626), 'tensorflow.keras.layers.Embedding', 'tf.keras.layers.Embedding', (['max_features', '(128)'], {}), '(max_features, 128)\n', (1607, 1626), True, 'import tensorflow as tf\n'), ((1789, 1832), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(256)'], {'activation': 'None'}), '(256, activation=None)\n', (1810, 1832), True, 'import tensorflow as tf\n'), ((2227, 2283), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(256)'], {'input_dim': '(2)', 'activation': 'None'}), '(256, input_dim=2, activation=None)\n', (2248, 2283), True, 'import tensorflow as tf\n'), ((2293, 2349), 'tensorflow.keras.layers.Dense', 'tf.keras.layers.Dense', (['(256)'], {'input_dim': '(2)', 'activation': 'None'}), '(256, input_dim=2, activation=None)\n', (2314, 2349), True, 'import tensorflow as tf\n'), ((5297, 5328), 'tensorflow.keras.optimizers.Adam', 'tf.keras.optimizers.Adam', (['(0.001)'], {}), '(0.001)\n', (5321, 5328), True, 'import tensorflow as tf\n'), ((5343, 5375), 'tensorflow_addons.losses.TripletSemiHardLoss', 'tfa.losses.TripletSemiHardLoss', ([], {}), '()\n', (5373, 5375), True, 'import tensorflow_addons as tfa\n'), ((1666, 1713), 'tensorflow.keras.layers.LSTM', 'tf.keras.layers.LSTM', (['(64)'], {'return_sequences': '(True)'}), '(64, return_sequences=True)\n', (1686, 1713), True, 'import tensorflow as tf\n'), ((1754, 1778), 'tensorflow.keras.layers.LSTM', 'tf.keras.layers.LSTM', (['(64)'], {}), '(64)\n', (1774, 1778), True, 'import tensorflow as tf\n'), ((1332, 1363), 'tensorflow.math.l2_normalize', 'tf.math.l2_normalize', (['x'], {'axis': '(1)'}), '(x, axis=1)\n', (1352, 1363), True, 'import tensorflow as tf\n')]
import numpy as np import torch def parameter_number(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) def normal2unit(vertices: "(vertice_num, 3)"): """ Return: (vertice_num, 3) => normalized into unit sphere """ center = vertices.mean(dim= 0) vertices -= center distance = vertices.norm(dim= 1) vertices /= distance.max() return vertices def rotate(points, degree: float, axis: int): """Rotate along upward direction""" rotate_matrix = torch.eye(3) theta = (degree/360)*2*np.pi cos = np.cos(theta) sin = np.sin(theta) axises = [0, 1, 2] assert axis in axises axises.remove(axis) rotate_matrix[axises[0], axises[0]] = cos rotate_matrix[axises[0], axises[1]] = -sin rotate_matrix[axises[1], axises[0]] = sin rotate_matrix[axises[1], axises[1]] = cos points = points @ rotate_matrix return points class Transform(): def __init__(self, normal: bool, shift: float = None, scale: float = None, rotate: float = None, axis: int = 0, random:bool= False): self.normal = normal self.shift = shift self.scale = scale self.rotate = rotate self.axis = axis self.random = random def __call__(self, points: "(point_num, 3)"): if self.normal: points = normal2unit(points) if self.shift: shift = self.shift if self.random: shift = (torch.rand(3)*2 - 1) * self.shift points += shift if self.scale: scale = self.scale points *= scale if self.rotate: degree = self.rotate if self.random: degree = (torch.rand(1).item()*2 - 1) * self.rotate points = rotate(points, degree, self.axis) return points def test(): points = torch.randn(1024, 3) transform = Transform(normal= True, scale= 10.0, axis= 1, random= True) points = transform(points) print(points.size()) if __name__ == '__main__': test()
[ "torch.eye", "numpy.cos", "numpy.sin", "torch.randn", "torch.rand" ]
[((512, 524), 'torch.eye', 'torch.eye', (['(3)'], {}), '(3)\n', (521, 524), False, 'import torch\n'), ((568, 581), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (574, 581), True, 'import numpy as np\n'), ((592, 605), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (598, 605), True, 'import numpy as np\n'), ((1995, 2015), 'torch.randn', 'torch.randn', (['(1024)', '(3)'], {}), '(1024, 3)\n', (2006, 2015), False, 'import torch\n'), ((1575, 1588), 'torch.rand', 'torch.rand', (['(3)'], {}), '(3)\n', (1585, 1588), False, 'import torch\n'), ((1849, 1862), 'torch.rand', 'torch.rand', (['(1)'], {}), '(1)\n', (1859, 1862), False, 'import torch\n')]
# -*- coding: utf-8 -*- """ Created on Thu Jun 28 15:15:32 2018 @author: Administrator """ import numpy as np import matplotlib.pyplot as plt import os import sys #import shutil global count1, count2 count1 = count2 =0 def file_segmentation(lBound, rBound): dataSet = [] for i in range(lBound, rBound): if os.path.exists('Shot_%d.txt' % i): with open('Shot_%d.txt' % i, 'r') as f: lines = f.readlines() ls = len(lines) for j in range(ls): lineArr = [] line = lines[j].strip().split(' ') l = len(line) for k in range(l): la = line[k].strip() if la == '': pass else: lineArr.append(np.float32(la)) dataSet.append(lineArr) else: pass length = len(dataSet) return dataSet, length def normalization(dataMat): minVals = dataMat.min(0) maxVals = dataMat.max(0) ranges = maxVals - minVals normDataSet = np.zeros(np.shape(dataMat)) m = dataMat.shape normDataSet = dataMat - np.tile(minVals, m) normDataSet = normDataSet/np.tile(ranges, m) return normDataSet # def check_filename_available(filename): # def check_meta(file_name): # n=[0] # file_name_new=file_name # if os.path.isfile(file_name): # file_name_new=file_name[:file_name.rfind('.')]+'_'+str(n[0])+file_name[file_name.rfind('.'):] # n[0] += 1 # if os.path.isfile(file_name_new): # file_name_new=check_meta(file_name) # return file_name_new # return_name=check_meta(filename) # return return_name def cutout_pictures(firstArrival_point, finalDataMat, stride): global count1,count2 axis_x = np.array(np.linspace(0, 3500, 876)) for i in range(876-stride): plt.figure(figsize=(2.99,2.99)) plt.rcParams['savefig.dpi'] = 100 plt.axis('off') plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0) plt.margins(0,0) x = axis_x[i:i+stride+1] y = finalDataMat[i:i+stride+1] plt.plot(x, y, color = 'k', linewidth = 1.5) if firstArrival_point in x: # plt.savefig(check_filename_available('trainSet1\\1.jpg')) filename1 = ('trainSet\\1_%d.jpg' %count1) plt.savefig(filename1) count1 += 1 else: filename2 = ('trainSet\\0_%d.jpg' %count2) #plt.savefig(check_filename_available('trainSet1\\0.jpg')) plt.savefig(filename2) count2 += 1 # plt.show() plt.close("all") sys.stdout.flush() #plt.clf() # for i in range(13378,13538): # for j in range(20000): # os.chdir('d:\\1wyh\\2zhenyuan_huizong') # text = ('{:}_shuchu_{:}.txt'.format(i,j)) # if not os.path.exists(text): # break # else: # file = ('%d' %i) # shutil.move(text, file) if __name__ == '__main__': dataSet, dataSet_len = file_segmentation(13369, 13370) for i in range(int(dataSet_len/2), dataSet_len): dataSet_segmentation = dataSet[i][12:] firstArrival_point = dataSet[i][11] if firstArrival_point == 0: pass else: dataMat = np.array(dataSet_segmentation) normDataSet = normalization(dataMat) cutout_pictures(firstArrival_point, normDataSet, 6) # dataSet_segmentation = dataSet[0][12:] # dataMat = np.array(dataSet_segmentation) # normDataSet = normalization(dataMat) # # print(dataSet_segmentation) # # print(dataMat) # # print(normDataSet) # plt.figure(figsize=(29.9,2.99)) # plt.axis('off') # plt.subplots_adjust(top = 1, bottom = 0, # right = 1, left = 0, # hspace = 0, wspace = 0) # plt.margins(0,0) # axis_x = np.array(np.linspace(0, 3500, 876)) # # x = axis_x[i:i+stride+1] # # y = finalDataMat[i:i+stride+1] # plt.plot(axis_x, normDataSet, color = 'k', linewidth = 1.5) # plt.show()
[ "sys.stdout.flush", "os.path.exists", "numpy.tile", "matplotlib.pyplot.savefig", "matplotlib.pyplot.margins", "matplotlib.pyplot.plot", "matplotlib.pyplot.close", "numpy.array", "matplotlib.pyplot.figure", "numpy.linspace", "matplotlib.pyplot.axis", "numpy.shape", "numpy.float32", "matplot...
[((332, 365), 'os.path.exists', 'os.path.exists', (["('Shot_%d.txt' % i)"], {}), "('Shot_%d.txt' % i)\n", (346, 365), False, 'import os\n'), ((944, 961), 'numpy.shape', 'np.shape', (['dataMat'], {}), '(dataMat)\n', (952, 961), True, 'import numpy as np\n'), ((1009, 1028), 'numpy.tile', 'np.tile', (['minVals', 'm'], {}), '(minVals, m)\n', (1016, 1028), True, 'import numpy as np\n'), ((1057, 1075), 'numpy.tile', 'np.tile', (['ranges', 'm'], {}), '(ranges, m)\n', (1064, 1075), True, 'import numpy as np\n'), ((1640, 1665), 'numpy.linspace', 'np.linspace', (['(0)', '(3500)', '(876)'], {}), '(0, 3500, 876)\n', (1651, 1665), True, 'import numpy as np\n'), ((1701, 1733), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(2.99, 2.99)'}), '(figsize=(2.99, 2.99))\n', (1711, 1733), True, 'import matplotlib.pyplot as plt\n'), ((1773, 1788), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1781, 1788), True, 'import matplotlib.pyplot as plt\n'), ((1793, 1866), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'top': '(1)', 'bottom': '(0)', 'right': '(1)', 'left': '(0)', 'hspace': '(0)', 'wspace': '(0)'}), '(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)\n', (1812, 1866), True, 'import matplotlib.pyplot as plt\n'), ((1899, 1916), 'matplotlib.pyplot.margins', 'plt.margins', (['(0)', '(0)'], {}), '(0, 0)\n', (1910, 1916), True, 'import matplotlib.pyplot as plt\n'), ((1981, 2021), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'color': '"""k"""', 'linewidth': '(1.5)'}), "(x, y, color='k', linewidth=1.5)\n", (1989, 2021), True, 'import matplotlib.pyplot as plt\n'), ((2393, 2409), 'matplotlib.pyplot.close', 'plt.close', (['"""all"""'], {}), "('all')\n", (2402, 2409), True, 'import matplotlib.pyplot as plt\n'), ((2413, 2431), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (2429, 2431), False, 'import sys\n'), ((2172, 2194), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename1'], {}), '(filename1)\n', (2183, 2194), True, 'import matplotlib.pyplot as plt\n'), ((2334, 2356), 'matplotlib.pyplot.savefig', 'plt.savefig', (['filename2'], {}), '(filename2)\n', (2345, 2356), True, 'import matplotlib.pyplot as plt\n'), ((3011, 3041), 'numpy.array', 'np.array', (['dataSet_segmentation'], {}), '(dataSet_segmentation)\n', (3019, 3041), True, 'import numpy as np\n'), ((692, 706), 'numpy.float32', 'np.float32', (['la'], {}), '(la)\n', (702, 706), True, 'import numpy as np\n')]
# Copyright 2020 The TensorFlow Quantum 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. # ============================================================================== """Compute gradients by combining function values linearly.""" import numbers import numpy as np import tensorflow as tf from tensorflow_quantum.python.differentiators import differentiator class LinearCombination(differentiator.Differentiator): """Differentiate a circuit with respect to its inputs by linearly combining values obtained by evaluating the op using parameter values perturbed about their forward-pass values. >>> my_op = tfq.get_expectation_op() >>> weights = [5, 6, 7] >>> perturbations = [0, 0.5, 0.25] >>> linear_differentiator = tfq.differentiators.LinearCombination( ... weights, perturbations ... ) >>> # Get an expectation op, with this differentiator attached. >>> op = linear_differentiator.generate_differentiable_op( ... analytic_op=my_op ... ) >>> qubit = cirq.GridQubit(0, 0) >>> circuit = tfq.convert_to_tensor([ ... cirq.Circuit(cirq.X(qubit) ** sympy.Symbol('alpha')) ... ]) >>> psums = tfq.convert_to_tensor([[cirq.Z(qubit)]]) >>> symbol_values = np.array([[0.123]], dtype=np.float32) >>> # Calculate tfq gradient. >>> symbol_values_t = tf.convert_to_tensor(symbol_values) >>> symbol_names = tf.convert_to_tensor(['alpha']) >>> with tf.GradientTape() as g: ... g.watch(symbol_values_t) ... expectations = op(circuit, symbol_names, symbol_values_t, psums ... ) >>> # Gradient would be: 5 * f(x+0) + 6 * f(x+0.5) + 7 * f(x+0.25) >>> grads = g.gradient(expectations, symbol_values_t) >>> # Note: this gradient visn't correct in value, but showcases >>> # the principle of how gradients can be defined in a very flexible >>> # fashion. >>> grads tf.Tensor([[5.089467]], shape=(1, 1), dtype=float32) """ def __init__(self, weights, perturbations): """Instantiate this differentiator. Create a LinearComobinationDifferentiator. Pass in weights and perturbations as described below. Args: weights: Python `list` of real numbers representing linear combination coeffecients for each perturbed function evaluation. perturbations: Python `list` of real numbers representing perturbation values. """ if not isinstance(weights, (np.ndarray, list, tuple)): raise TypeError("weights must be a numpy array, list or tuple." "Got {}".format(type(weights))) if not all([isinstance(weight, numbers.Real) for weight in weights]): raise TypeError("Each weight in weights must be a real number.") if not isinstance(perturbations, (np.ndarray, list, tuple)): raise TypeError("perturbations must be a numpy array," " list or tuple. Got {}".format(type(weights))) if not all([ isinstance(perturbation, numbers.Real) for perturbation in perturbations ]): raise TypeError("Each perturbation in perturbations must be a" " real number.") if not len(weights) == len(perturbations): raise ValueError("weights and perturbations must have the same " "length.") if len(perturbations) < 2: raise ValueError("Must specify at least two perturbations. " "Providing only one perturbation is the same as " "evaluating the circuit at a single location, " "which is insufficient for differentiation.") self.weights = tf.constant(weights, dtype=tf.float32) self.n_perturbations = tf.constant(len(perturbations)) self.perturbations = tf.constant(perturbations, dtype=tf.float32) # Uniqueness in particular ensures there at most one zero perturbation. if not len(list(set(perturbations))) == len(perturbations): raise ValueError("All values in perturbations must be unique.") mask = tf.not_equal(self.perturbations, tf.zeros_like(self.perturbations)) self.non_zero_weights = tf.boolean_mask(self.weights, mask) self.zero_weights = tf.boolean_mask(self.weights, tf.math.logical_not(mask)) self.non_zero_perturbations = tf.boolean_mask(self.perturbations, mask) self.n_non_zero_perturbations = tf.gather( tf.shape(self.non_zero_perturbations), 0) @tf.function def get_gradient_circuits(self, programs, symbol_names, symbol_values): """See base class description.""" n_programs = tf.gather(tf.shape(programs), 0) n_symbols = tf.gather(tf.shape(symbol_names), 0) # A new copy of each program is run for each symbol and each # non-zero perturbation, plus one more if there is a zero perturbation. # `m` represents the last index of the batch mapper. base_m_tile = n_symbols * self.n_non_zero_perturbations m_tile = tf.cond(self.n_non_zero_perturbations < self.n_perturbations, lambda: base_m_tile + 1, lambda: base_m_tile) batch_programs = tf.tile(tf.expand_dims(programs, 1), [1, m_tile]) # LinearCombination does not add new symbols to the gradient circuits. new_symbol_names = tf.identity(symbol_names) # Build the symbol value perturbations for a single input program. perts_zeros_pad = tf.zeros([self.n_non_zero_perturbations], dtype=tf.float32) stacked_perts = tf.stack([perts_zeros_pad, self.non_zero_perturbations]) # Identity matrix lets us tile the perturbations and simultaneously # put zeros in all the symbol locations not being perturbed. gathered_perts = tf.gather(stacked_perts, tf.eye(n_symbols, dtype=tf.int32)) transposed_perts = tf.transpose(gathered_perts, [0, 2, 1]) reshaped_perts = tf.reshape(transposed_perts, [base_m_tile, n_symbols]) symbol_zeros_pad = tf.zeros([1, n_symbols]) single_program_perts = tf.cond( self.n_non_zero_perturbations < self.n_perturbations, lambda: tf.concat([symbol_zeros_pad, reshaped_perts], 0), lambda: reshaped_perts) # Make a copy of the perturbations tensor for each input program. all_perts = tf.tile(tf.expand_dims(single_program_perts, 0), [n_programs, 1, 1]) # Apply perturbations to the forward pass symbol values. bare_symbol_values = tf.tile(tf.expand_dims(symbol_values, 1), [1, m_tile, 1]) batch_symbol_values = bare_symbol_values + all_perts # The weights for all the programs. tiled_weights = tf.tile(tf.expand_dims(self.non_zero_weights, 0), [n_symbols, 1]) tiled_zero_weights = tf.tile(tf.expand_dims(self.zero_weights, 0), [n_symbols, 1]) single_program_weights = tf.concat([tiled_zero_weights, tiled_weights], 1) # Mapping is also the same for each program. batch_weights = tf.tile(tf.expand_dims(single_program_weights, 0), [n_programs, 1, 1]) # The mapper selects the zero weight if it exists. single_program_mapper_base = tf.reshape( tf.range(n_symbols * self.n_non_zero_perturbations), [n_symbols, self.n_non_zero_perturbations]) single_program_mapper = tf.cond( self.n_non_zero_perturbations < self.n_perturbations, lambda: tf.concat([ tf.zeros([n_symbols, 1], dtype=tf.int32), single_program_mapper_base + 1 ], 1), lambda: single_program_mapper_base) batch_mapper = tf.tile(tf.expand_dims(single_program_mapper, 0), [n_programs, 1, 1]) return (batch_programs, new_symbol_names, batch_symbol_values, batch_weights, batch_mapper) class ForwardDifference(LinearCombination): """Differentiate a circuit using forward differencing. Forward differencing computes a derivative at a point x using only points larger than x (in this way, it is 'one sided'). A closed form for the coefficients of this derivative for an arbitrary positive error order is used here, which is described in the following article: https://www.sciencedirect.com/science/article/pii/S0377042799000886. >>> my_op = tfq.get_expectation_op() >>> linear_differentiator = tfq.differentiators.ForwardDifference(2, 0.01) >>> # Get an expectation op, with this differentiator attached. >>> op = linear_differentiator.generate_differentiable_op( ... analytic_op=my_op ... ) >>> qubit = cirq.GridQubit(0, 0) >>> circuit = tfq.convert_to_tensor([ ... cirq.Circuit(cirq.X(qubit) ** sympy.Symbol('alpha')) ... ]) >>> psums = tfq.convert_to_tensor([[cirq.Z(qubit)]]) >>> symbol_values_array = np.array([[0.123]], dtype=np.float32) >>> # Calculate tfq gradient. >>> symbol_values_tensor = tf.convert_to_tensor(symbol_values_array) >>> with tf.GradientTape() as g: ... g.watch(symbol_values_tensor) ... expectations = op(circuit, ['alpha'], symbol_values_tensor, psums) >>> # Gradient would be: -50 * f(x + 0.02) + 200 * f(x + 0.01) - 150 * f(x) >>> grads = g.gradient(expectations, symbol_values_tensor) >>> grads tf.Tensor([[-1.184372]], shape=(1, 1), dtype=float32) """ def __init__(self, error_order=1, grid_spacing=0.001): """Instantiate a ForwardDifference. Create a ForwardDifference differentiator, passing along an error order and grid spacing to be used to contstruct differentiator coeffecients. Args: error_order: A positive `int` specifying the error order of this differentiator. This corresponds to the smallest power of `grid_spacing` remaining in the series that was truncated to generate this finite differencing expression. grid_spacing: A positive `float` specifying how large of a grid to use in calculating this finite difference. """ if not (isinstance(error_order, numbers.Integral) and error_order > 0): raise ValueError("error_order must be a positive integer.") if not (isinstance(grid_spacing, numbers.Real) and grid_spacing > 0): raise ValueError("grid_spacing must be a positive real number.") self.error_order = error_order self.grid_spacing = grid_spacing grid_points_to_eval = np.arange(0, error_order + 1) weights = [] for point in grid_points_to_eval: if point == 0: weight = -1 * np.sum( [1 / j for j in np.arange(1, error_order + 1)]) else: weight = ((-1) ** (point+1) * np.math.factorial(error_order))/\ (point * np.math.factorial(error_order-point) * np.math.factorial(point)) weights.append(weight / grid_spacing) super().__init__(weights, grid_points_to_eval * grid_spacing) class CentralDifference(LinearCombination): """Differentiates a circuit using Central Differencing. Central differencing computes a derivative at point x using an equal number of points before and after x. A closed form for the coefficients of this derivative for an arbitrary positive error order is used here, which is described in the following article: https://www.sciencedirect.com/science/article/pii/S0377042799000886. >>> my_op = tfq.get_expectation_op() >>> linear_differentiator = tfq.differentiators.CentralDifference(2, 0.01) >>> # Get an expectation op, with this differentiator attached. >>> op = linear_differentiator.generate_differentiable_op( ... analytic_op=my_op ... ) >>> qubit = cirq.GridQubit(0, 0) >>> circuit = tfq.convert_to_tensor([ ... cirq.Circuit(cirq.X(qubit) ** sympy.Symbol('alpha')) ... ]) >>> psums = tfq.convert_to_tensor([[cirq.Z(qubit)]]) >>> symbol_values_array = np.array([[0.123]], dtype=np.float32) >>> # Calculate tfq gradient. >>> symbol_values_tensor = tf.convert_to_tensor(symbol_values_array) >>> with tf.GradientTape() as g: ... g.watch(symbol_values_tensor) ... expectations = op(circuit, ['alpha'], symbol_values_tensor, psums) >>> # Gradient would be: -50 * f(x + 0.02) + 200 * f(x + 0.01) - 150 * f(x) >>> grads = g.gradient(expectations, symbol_values_tensor) >>> grads tf.Tensor([[-1.1837807]], shape=(1, 1), dtype=float32) """ def __init__(self, error_order=2, grid_spacing=0.001): """Instantiate a CentralDifference. Create a CentralDifference differentaitor, passing along an error order and grid spacing to be used to contstruct differentiator coeffecients. Args: error_order: A positive, even `int` specifying the error order of this differentiator. This corresponds to the smallest power of `grid_spacing` remaining in the series that was truncated to generate this finite differencing expression. grid_spacing: A positive `float` specifying how large of a grid to use in calculating this finite difference. """ if not (isinstance(error_order, numbers.Integral) and error_order > 0 and error_order % 2 == 0): raise ValueError("error_order must be a positive, even integer.") if not (isinstance(grid_spacing, numbers.Real) and grid_spacing > 0): raise ValueError("grid_spacing must be a positive real number.") grid_points_to_eval = np.concatenate([ np.arange(-1 * error_order / 2, 0), np.arange(1, error_order / 2 + 1) ]) weights = [] n = error_order / 2 for k in grid_points_to_eval: numerator = (-1)**(k + 1) * np.math.factorial(n)**2 denom = k * np.math.factorial(n - k) * np.math.factorial(n + k) weights.append(numerator / (denom * grid_spacing)) super().__init__(weights, grid_points_to_eval * grid_spacing)
[ "tensorflow.expand_dims", "tensorflow.eye", "tensorflow.math.logical_not", "tensorflow.shape", "tensorflow.boolean_mask", "tensorflow.transpose", "numpy.arange", "tensorflow.cond", "tensorflow.stack", "tensorflow.concat", "tensorflow.range", "tensorflow.constant", "tensorflow.reshape", "te...
[((4354, 4392), 'tensorflow.constant', 'tf.constant', (['weights'], {'dtype': 'tf.float32'}), '(weights, dtype=tf.float32)\n', (4365, 4392), True, 'import tensorflow as tf\n'), ((4485, 4529), 'tensorflow.constant', 'tf.constant', (['perturbations'], {'dtype': 'tf.float32'}), '(perturbations, dtype=tf.float32)\n', (4496, 4529), True, 'import tensorflow as tf\n'), ((4898, 4933), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['self.weights', 'mask'], {}), '(self.weights, mask)\n', (4913, 4933), True, 'import tensorflow as tf\n'), ((5101, 5142), 'tensorflow.boolean_mask', 'tf.boolean_mask', (['self.perturbations', 'mask'], {}), '(self.perturbations, mask)\n', (5116, 5142), True, 'import tensorflow as tf\n'), ((5787, 5901), 'tensorflow.cond', 'tf.cond', (['(self.n_non_zero_perturbations < self.n_perturbations)', '(lambda : base_m_tile + 1)', '(lambda : base_m_tile)'], {}), '(self.n_non_zero_perturbations < self.n_perturbations, lambda : \n base_m_tile + 1, lambda : base_m_tile)\n', (5794, 5901), True, 'import tensorflow as tf\n'), ((6102, 6127), 'tensorflow.identity', 'tf.identity', (['symbol_names'], {}), '(symbol_names)\n', (6113, 6127), True, 'import tensorflow as tf\n'), ((6230, 6289), 'tensorflow.zeros', 'tf.zeros', (['[self.n_non_zero_perturbations]'], {'dtype': 'tf.float32'}), '([self.n_non_zero_perturbations], dtype=tf.float32)\n', (6238, 6289), True, 'import tensorflow as tf\n'), ((6349, 6405), 'tensorflow.stack', 'tf.stack', (['[perts_zeros_pad, self.non_zero_perturbations]'], {}), '([perts_zeros_pad, self.non_zero_perturbations])\n', (6357, 6405), True, 'import tensorflow as tf\n'), ((6698, 6737), 'tensorflow.transpose', 'tf.transpose', (['gathered_perts', '[0, 2, 1]'], {}), '(gathered_perts, [0, 2, 1])\n', (6710, 6737), True, 'import tensorflow as tf\n'), ((6763, 6817), 'tensorflow.reshape', 'tf.reshape', (['transposed_perts', '[base_m_tile, n_symbols]'], {}), '(transposed_perts, [base_m_tile, n_symbols])\n', (6773, 6817), True, 'import tensorflow as tf\n'), ((6845, 6869), 'tensorflow.zeros', 'tf.zeros', (['[1, n_symbols]'], {}), '([1, n_symbols])\n', (6853, 6869), True, 'import tensorflow as tf\n'), ((7851, 7900), 'tensorflow.concat', 'tf.concat', (['[tiled_zero_weights, tiled_weights]', '(1)'], {}), '([tiled_zero_weights, tiled_weights], 1)\n', (7860, 7900), True, 'import tensorflow as tf\n'), ((11561, 11590), 'numpy.arange', 'np.arange', (['(0)', '(error_order + 1)'], {}), '(0, error_order + 1)\n', (11570, 11590), True, 'import numpy as np\n'), ((4831, 4864), 'tensorflow.zeros_like', 'tf.zeros_like', (['self.perturbations'], {}), '(self.perturbations)\n', (4844, 4864), True, 'import tensorflow as tf\n'), ((5036, 5061), 'tensorflow.math.logical_not', 'tf.math.logical_not', (['mask'], {}), '(mask)\n', (5055, 5061), True, 'import tensorflow as tf\n'), ((5206, 5243), 'tensorflow.shape', 'tf.shape', (['self.non_zero_perturbations'], {}), '(self.non_zero_perturbations)\n', (5214, 5243), True, 'import tensorflow as tf\n'), ((5415, 5433), 'tensorflow.shape', 'tf.shape', (['programs'], {}), '(programs)\n', (5423, 5433), True, 'import tensorflow as tf\n'), ((5468, 5490), 'tensorflow.shape', 'tf.shape', (['symbol_names'], {}), '(symbol_names)\n', (5476, 5490), True, 'import tensorflow as tf\n'), ((5953, 5980), 'tensorflow.expand_dims', 'tf.expand_dims', (['programs', '(1)'], {}), '(programs, 1)\n', (5967, 5980), True, 'import tensorflow as tf\n'), ((6636, 6669), 'tensorflow.eye', 'tf.eye', (['n_symbols'], {'dtype': 'tf.int32'}), '(n_symbols, dtype=tf.int32)\n', (6642, 6669), True, 'import tensorflow as tf\n'), ((7184, 7223), 'tensorflow.expand_dims', 'tf.expand_dims', (['single_program_perts', '(0)'], {}), '(single_program_perts, 0)\n', (7198, 7223), True, 'import tensorflow as tf\n'), ((7375, 7407), 'tensorflow.expand_dims', 'tf.expand_dims', (['symbol_values', '(1)'], {}), '(symbol_values, 1)\n', (7389, 7407), True, 'import tensorflow as tf\n'), ((7600, 7640), 'tensorflow.expand_dims', 'tf.expand_dims', (['self.non_zero_weights', '(0)'], {}), '(self.non_zero_weights, 0)\n', (7614, 7640), True, 'import tensorflow as tf\n'), ((7727, 7763), 'tensorflow.expand_dims', 'tf.expand_dims', (['self.zero_weights', '(0)'], {}), '(self.zero_weights, 0)\n', (7741, 7763), True, 'import tensorflow as tf\n'), ((8029, 8070), 'tensorflow.expand_dims', 'tf.expand_dims', (['single_program_weights', '(0)'], {}), '(single_program_weights, 0)\n', (8043, 8070), True, 'import tensorflow as tf\n'), ((8245, 8296), 'tensorflow.range', 'tf.range', (['(n_symbols * self.n_non_zero_perturbations)'], {}), '(n_symbols * self.n_non_zero_perturbations)\n', (8253, 8296), True, 'import tensorflow as tf\n'), ((8684, 8724), 'tensorflow.expand_dims', 'tf.expand_dims', (['single_program_mapper', '(0)'], {}), '(single_program_mapper, 0)\n', (8698, 8724), True, 'import tensorflow as tf\n'), ((6996, 7044), 'tensorflow.concat', 'tf.concat', (['[symbol_zeros_pad, reshaped_perts]', '(0)'], {}), '([symbol_zeros_pad, reshaped_perts], 0)\n', (7005, 7044), True, 'import tensorflow as tf\n'), ((14785, 14819), 'numpy.arange', 'np.arange', (['(-1 * error_order / 2)', '(0)'], {}), '(-1 * error_order / 2, 0)\n', (14794, 14819), True, 'import numpy as np\n'), ((14833, 14866), 'numpy.arange', 'np.arange', (['(1)', '(error_order / 2 + 1)'], {}), '(1, error_order / 2 + 1)\n', (14842, 14866), True, 'import numpy as np\n'), ((15080, 15104), 'numpy.math.factorial', 'np.math.factorial', (['(n + k)'], {}), '(n + k)\n', (15097, 15104), True, 'import numpy as np\n'), ((15005, 15025), 'numpy.math.factorial', 'np.math.factorial', (['n'], {}), '(n)\n', (15022, 15025), True, 'import numpy as np\n'), ((15053, 15077), 'numpy.math.factorial', 'np.math.factorial', (['(n - k)'], {}), '(n - k)\n', (15070, 15077), True, 'import numpy as np\n'), ((8509, 8549), 'tensorflow.zeros', 'tf.zeros', (['[n_symbols, 1]'], {'dtype': 'tf.int32'}), '([n_symbols, 1], dtype=tf.int32)\n', (8517, 8549), True, 'import tensorflow as tf\n'), ((11851, 11881), 'numpy.math.factorial', 'np.math.factorial', (['error_order'], {}), '(error_order)\n', (11868, 11881), True, 'import numpy as np\n'), ((11984, 12008), 'numpy.math.factorial', 'np.math.factorial', (['point'], {}), '(point)\n', (12001, 12008), True, 'import numpy as np\n'), ((11919, 11957), 'numpy.math.factorial', 'np.math.factorial', (['(error_order - point)'], {}), '(error_order - point)\n', (11936, 11957), True, 'import numpy as np\n'), ((11755, 11784), 'numpy.arange', 'np.arange', (['(1)', '(error_order + 1)'], {}), '(1, error_order + 1)\n', (11764, 11784), True, 'import numpy as np\n')]
import numpy as np from extensive_form.games.extensive_game import State, Game class DeepSeaState(State): def __init__(self, index, depth, payoffs, successors): self._index = index self._depth = depth self._payoffs = payoffs self._successors = successors if np.random.random() <= 0.5: self._action_map = (0, 1) else: self._action_map = (1, 0) def _key(self): return self._index def depth(self): return self._depth def active_players(self): return [0] def num_actions(self, player_id): return 2 def payoffs(self, actions): return self._payoffs[self._action_map[actions[0]]] def successors(self, actions): if self._successors is None: return [] else: return [self._successors[self._action_map[actions[0]]]] def transitions(self, actions): return [1.] def descendants(self): if self._successors is None: return [] else: return self._successors class DeepSea(Game): def __init__(self, config={}): # Get configuration size = config.get("size", 10) penalty = config.get("penalty", 0.01) # Build last layer of game - this is where we get the big payoff if we reach the goal last_layer = [] index = 0 for _ in range(size - 1): last_layer.append(DeepSeaState(index, size, payoffs=[[0., 1.], [0., 1.]], successors=None)) index += 1 last_layer.append(DeepSeaState(index, size, payoffs=[[1., 0.], [1., 0.]], successors=None)) index += 1 # Build intermediate layers - in reverse depth order payoffs = [[penalty, 0.], [0., penalty]] for depth in range(size - 1, 0, -1): layer = [] for idx in range(size): left= last_layer[max(idx - 1, 0)] right = last_layer[min(idx + 1, size - 1)] layer.append(DeepSeaState(index, depth, payoffs=payoffs, successors=[left, right])) index += 1 last_layer = layer # Define initial states self._initial_states = [last_layer[0]] # Compute maximum payoff and depth self._max_payoff = 1. + (size - 1) * penalty self._max_depth = size def num_players(self): return 2 def max_depth(self): return self._max_depth def max_payoff(self): return self._max_payoff def initial_states(self): return self._initial_states def initial_distribution(self): return [1.]
[ "numpy.random.random" ]
[((307, 325), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (323, 325), True, 'import numpy as np\n')]
#Program to perform linear convolution import numpy as np import scipy as sy from matplotlib import pyplot as plt #impulse response h = [1,2,3,3,2,1]; #input response x = [1,2,3,4,5]; N1 = len(x) N2 = len(h) N = N1+N2-1 y = np.zeros(N) #x = [[x],[np.zeros(N-N1)]] #h = [h,np.zeros(N-N2)] #Linear convolution using built-in function in NumPy y1 = np.convolve(x,h) m = N-N1 n = N-N2 #Padding zeros to x and h to make their length to N x =np.pad(x,(0,m),'constant') h =np.pad(h,(0,n),'constant') #Linear convolution using convolution sum formula for n in range (N): for k in range (N): if n >= k: y[n] = y[n]+x[n-k]*h[k] print('Linear convolution using convolution sum formula output response y =\n',y) print('Linear convolution using NumPy built-in function output response y=\n',y1) #RESULT #Linear convolution using convolution sum formula output response y = #[ 1. 4. 10. 19. 30. 36. 35. 26. 14. 5.] #Linear convolution using NumPy built-in function output response y= #[ 1 4 10 19 30 36 35 26 14 5]
[ "numpy.zeros", "numpy.convolve", "numpy.pad" ]
[((235, 246), 'numpy.zeros', 'np.zeros', (['N'], {}), '(N)\n', (243, 246), True, 'import numpy as np\n'), ((361, 378), 'numpy.convolve', 'np.convolve', (['x', 'h'], {}), '(x, h)\n', (372, 378), True, 'import numpy as np\n'), ((455, 484), 'numpy.pad', 'np.pad', (['x', '(0, m)', '"""constant"""'], {}), "(x, (0, m), 'constant')\n", (461, 484), True, 'import numpy as np\n'), ((486, 515), 'numpy.pad', 'np.pad', (['h', '(0, n)', '"""constant"""'], {}), "(h, (0, n), 'constant')\n", (492, 515), True, 'import numpy as np\n')]
import numpy as _numpy from scipy.stats import binom as _binom # data: (nsamp, len) input matrix with event series # ktrmat: (nsamp, nsamp) input matrix with pairwise numbers of trigger coincidences # delta: time tolerance # returns (pvals, nemat, pimat), with # pvals: (nsamp, nsamp) output matrix with p-values for the pairwise numbers of trigger coincidences # nemat: (nsamp, nsamp) output matrix with maximum numbers of trigger coincidences for every pair # pimat: (nsamp, nsamp) output matrix with trigger coincidence probabilities \pi for every pair def ktr_bernoulli(data, ktrmat, delta): nemat = _numpy.repeat(_numpy.diag(ktrmat).reshape(-1,1), ktrmat.shape[0], axis=1) pimat = _numpy.repeat(1-_numpy.power(1-data.sum(axis=1)/data.shape[1], delta+1).reshape(1,-1), data.shape[0], axis=0) pvals = ((1-_binom.cdf(ktrmat.reshape(-1), nemat.reshape(-1), pimat.reshape(-1))).reshape(ktrmat.shape) + _binom.pmf(ktrmat.reshape(-1), nemat.reshape(-1), pimat.reshape(-1)).reshape(ktrmat.shape)) return pvals, nemat, pimat # data: (nsamp, len) input matrix with event series # ktrmat: (nsamp, nsamp) input matrix with pairwise numbers of precursor coincidences # delta: time tolerance # returns (pvals, nemat, pimat), with # pvals: (nsamp, nsamp) output matrix with p-values for the pairwise numbers of precursor coincidences # nemat: (nsamp, nsamp) output matrix with maximum numbers of precursor coincidences for every pair # pimat: (nsamp, nsamp) output matrix with precursor coincidence probabilities \pi for every pair def kpr_bernoulli(data, kprmat, delta): nemat = _numpy.repeat(_numpy.diag(kprmat).reshape(1,-1), kprmat.shape[0], axis=0) pimat = _numpy.repeat(1-_numpy.power(1-data.sum(axis=1)/data.shape[1], delta+1).reshape(-1,1), data.shape[0], axis=1) pvals = ((1-_binom.cdf(kprmat.reshape(-1), nemat.reshape(-1), pimat.reshape(-1))).reshape(kprmat.shape) + _binom.pmf(kprmat.reshape(-1), nemat.reshape(-1), pimat.reshape(-1)).reshape(kprmat.shape)) return pvals, nemat, pimat
[ "numpy.diag" ]
[((632, 651), 'numpy.diag', '_numpy.diag', (['ktrmat'], {}), '(ktrmat)\n', (643, 651), True, 'import numpy as _numpy\n'), ((1641, 1660), 'numpy.diag', '_numpy.diag', (['kprmat'], {}), '(kprmat)\n', (1652, 1660), True, 'import numpy as _numpy\n')]
"""A training script of Soft Actor-Critic on RoboschoolAtlasForwardWalk-v1.""" import argparse import functools import logging import sys import gym import gym.wrappers import numpy as np import torch from torch import distributions, nn import pfrl from pfrl import experiments, replay_buffers, utils from pfrl.nn.lmbda import Lambda def make_env(args, seed, test): if args.env.startswith("Roboschool"): # Check gym version because roboschool does not work with gym>=0.15.6 from distutils.version import StrictVersion gym_version = StrictVersion(gym.__version__) if gym_version >= StrictVersion("0.15.6"): raise RuntimeError("roboschool does not work with gym>=0.15.6") import roboschool # NOQA env = gym.make(args.env) # Unwrap TimiLimit wrapper assert isinstance(env, gym.wrappers.TimeLimit) env = env.env # Use different random seeds for train and test envs env_seed = 2 ** 32 - 1 - seed if test else seed env.seed(int(env_seed)) # Cast observations to float32 because our model uses float32 env = pfrl.wrappers.CastObservationToFloat32(env) # Normalize action space to [-1, 1]^n env = pfrl.wrappers.NormalizeActionSpace(env) if args.monitor: env = pfrl.wrappers.Monitor( env, args.outdir, force=True, video_callable=lambda _: True ) if args.render: env = pfrl.wrappers.Render(env, mode="human") return env def main(): parser = argparse.ArgumentParser() parser.add_argument( "--outdir", type=str, default="results", help=( "Directory path to save output files." " If it does not exist, it will be created." ), ) parser.add_argument( "--env", type=str, default="RoboschoolAtlasForwardWalk-v1", help="OpenAI Gym env to perform algorithm on.", ) parser.add_argument( "--num-envs", type=int, default=4, help="Number of envs run in parallel." ) parser.add_argument("--seed", type=int, default=0, help="Random seed [0, 2 ** 32)") parser.add_argument( "--gpu", type=int, default=0, help="GPU to use, set to -1 if no GPU." ) parser.add_argument( "--load", type=str, default="", help="Directory to load agent from." ) parser.add_argument( "--steps", type=int, default=10 ** 7, help="Total number of timesteps to train the agent.", ) parser.add_argument( "--eval-n-runs", type=int, default=20, help="Number of episodes run for each evaluation.", ) parser.add_argument( "--eval-interval", type=int, default=100000, help="Interval in timesteps between evaluations.", ) parser.add_argument( "--replay-start-size", type=int, default=10000, help="Minimum replay buffer size before " + "performing gradient updates.", ) parser.add_argument( "--update-interval", type=int, default=1, help="Interval in timesteps between model updates.", ) parser.add_argument("--batch-size", type=int, default=256, help="Minibatch size") parser.add_argument( "--render", action="store_true", help="Render env states in a GUI window." ) parser.add_argument( "--demo", action="store_true", help="Just run evaluation, not training." ) parser.add_argument( "--monitor", action="store_true", help="Wrap env with Monitor to write videos." ) parser.add_argument( "--log-interval", type=int, default=1000, help="Interval in timesteps between outputting log messages during training", ) parser.add_argument( "--log-level", type=int, default=logging.INFO, help="Level of the root logger." ) parser.add_argument( "--n-hidden-channels", type=int, default=1024, help="Number of hidden channels of NN models.", ) parser.add_argument("--discount", type=float, default=0.98, help="Discount factor.") parser.add_argument("--n-step-return", type=int, default=3, help="N-step return.") parser.add_argument("--lr", type=float, default=3e-4, help="Learning rate.") parser.add_argument("--adam-eps", type=float, default=1e-1, help="Adam eps.") args = parser.parse_args() logging.basicConfig(level=args.log_level) args.outdir = experiments.prepare_output_dir(args, args.outdir, argv=sys.argv) print("Output files are saved in {}".format(args.outdir)) # Set a random seed used in PFRL utils.set_random_seed(args.seed) # Set different random seeds for different subprocesses. # If seed=0 and processes=4, subprocess seeds are [0, 1, 2, 3]. # If seed=1 and processes=4, subprocess seeds are [4, 5, 6, 7]. process_seeds = np.arange(args.num_envs) + args.seed * args.num_envs assert process_seeds.max() < 2 ** 32 def make_batch_env(test): return pfrl.envs.MultiprocessVectorEnv( [ functools.partial(make_env, args, process_seeds[idx], test) for idx, env in enumerate(range(args.num_envs)) ] ) sample_env = make_env(args, process_seeds[0], test=False) timestep_limit = sample_env.spec.max_episode_steps obs_space = sample_env.observation_space action_space = sample_env.action_space print("Observation space:", obs_space) print("Action space:", action_space) del sample_env action_size = action_space.low.size def squashed_diagonal_gaussian_head(x): assert x.shape[-1] == action_size * 2 mean, log_scale = torch.chunk(x, 2, dim=1) log_scale = torch.clamp(log_scale, -20.0, 2.0) var = torch.exp(log_scale * 2) base_distribution = distributions.Independent( distributions.Normal(loc=mean, scale=torch.sqrt(var)), 1 ) # cache_size=1 is required for numerical stability return distributions.transformed_distribution.TransformedDistribution( base_distribution, [distributions.transforms.TanhTransform(cache_size=1)] ) policy = nn.Sequential( nn.Linear(obs_space.low.size, args.n_hidden_channels), nn.ReLU(), nn.Linear(args.n_hidden_channels, args.n_hidden_channels), nn.ReLU(), nn.Linear(args.n_hidden_channels, action_size * 2), Lambda(squashed_diagonal_gaussian_head), ) torch.nn.init.xavier_uniform_(policy[0].weight) torch.nn.init.xavier_uniform_(policy[2].weight) torch.nn.init.xavier_uniform_(policy[4].weight) policy_optimizer = torch.optim.Adam( policy.parameters(), lr=args.lr, eps=args.adam_eps ) def make_q_func_with_optimizer(): q_func = nn.Sequential( pfrl.nn.ConcatObsAndAction(), nn.Linear(obs_space.low.size + action_size, args.n_hidden_channels), nn.ReLU(), nn.Linear(args.n_hidden_channels, args.n_hidden_channels), nn.ReLU(), nn.Linear(args.n_hidden_channels, 1), ) torch.nn.init.xavier_uniform_(q_func[1].weight) torch.nn.init.xavier_uniform_(q_func[3].weight) torch.nn.init.xavier_uniform_(q_func[5].weight) q_func_optimizer = torch.optim.Adam( q_func.parameters(), lr=args.lr, eps=args.adam_eps ) return q_func, q_func_optimizer q_func1, q_func1_optimizer = make_q_func_with_optimizer() q_func2, q_func2_optimizer = make_q_func_with_optimizer() rbuf = replay_buffers.ReplayBuffer(10 ** 6, num_steps=args.n_step_return) def burnin_action_func(): """Select random actions until model is updated one or more times.""" return np.random.uniform(action_space.low, action_space.high).astype(np.float32) # Hyperparameters in http://arxiv.org/abs/1802.09477 agent = pfrl.agents.SoftActorCritic( policy, q_func1, q_func2, policy_optimizer, q_func1_optimizer, q_func2_optimizer, rbuf, gamma=args.discount, update_interval=args.update_interval, replay_start_size=args.replay_start_size, gpu=args.gpu, minibatch_size=args.batch_size, burnin_action_func=burnin_action_func, entropy_target=-action_size, temperature_optimizer_lr=args.lr, ) if len(args.load) > 0: agent.load(args.load) if args.demo: eval_env = make_env(args, seed=0, test=True) eval_stats = experiments.eval_performance( env=eval_env, agent=agent, n_steps=None, n_episodes=args.eval_n_runs, max_episode_len=timestep_limit, ) print( "n_runs: {} mean: {} median: {} stdev {}".format( args.eval_n_runs, eval_stats["mean"], eval_stats["median"], eval_stats["stdev"], ) ) else: experiments.train_agent_batch_with_evaluation( agent=agent, env=make_batch_env(test=False), eval_env=make_batch_env(test=True), outdir=args.outdir, steps=args.steps, eval_n_steps=None, eval_n_episodes=args.eval_n_runs, eval_interval=args.eval_interval, log_interval=args.log_interval, max_episode_len=timestep_limit, ) if __name__ == "__main__": main()
[ "torch.nn.ReLU", "pfrl.experiments.eval_performance", "pfrl.experiments.prepare_output_dir", "torch.sqrt", "torch.exp", "gym.make", "numpy.arange", "argparse.ArgumentParser", "torch.nn.init.xavier_uniform_", "pfrl.utils.set_random_seed", "pfrl.wrappers.NormalizeActionSpace", "pfrl.wrappers.Mon...
[((767, 785), 'gym.make', 'gym.make', (['args.env'], {}), '(args.env)\n', (775, 785), False, 'import gym\n'), ((1099, 1142), 'pfrl.wrappers.CastObservationToFloat32', 'pfrl.wrappers.CastObservationToFloat32', (['env'], {}), '(env)\n', (1137, 1142), False, 'import pfrl\n'), ((1195, 1234), 'pfrl.wrappers.NormalizeActionSpace', 'pfrl.wrappers.NormalizeActionSpace', (['env'], {}), '(env)\n', (1229, 1234), False, 'import pfrl\n'), ((1492, 1517), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (1515, 1517), False, 'import argparse\n'), ((4416, 4457), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'args.log_level'}), '(level=args.log_level)\n', (4435, 4457), False, 'import logging\n'), ((4477, 4541), 'pfrl.experiments.prepare_output_dir', 'experiments.prepare_output_dir', (['args', 'args.outdir'], {'argv': 'sys.argv'}), '(args, args.outdir, argv=sys.argv)\n', (4507, 4541), False, 'from pfrl import experiments, replay_buffers, utils\n'), ((4646, 4678), 'pfrl.utils.set_random_seed', 'utils.set_random_seed', (['args.seed'], {}), '(args.seed)\n', (4667, 4678), False, 'from pfrl import experiments, replay_buffers, utils\n'), ((6518, 6565), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['policy[0].weight'], {}), '(policy[0].weight)\n', (6547, 6565), False, 'import torch\n'), ((6570, 6617), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['policy[2].weight'], {}), '(policy[2].weight)\n', (6599, 6617), False, 'import torch\n'), ((6622, 6669), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['policy[4].weight'], {}), '(policy[4].weight)\n', (6651, 6669), False, 'import torch\n'), ((7610, 7676), 'pfrl.replay_buffers.ReplayBuffer', 'replay_buffers.ReplayBuffer', (['(10 ** 6)'], {'num_steps': 'args.n_step_return'}), '(10 ** 6, num_steps=args.n_step_return)\n', (7637, 7676), False, 'from pfrl import experiments, replay_buffers, utils\n'), ((7945, 8330), 'pfrl.agents.SoftActorCritic', 'pfrl.agents.SoftActorCritic', (['policy', 'q_func1', 'q_func2', 'policy_optimizer', 'q_func1_optimizer', 'q_func2_optimizer', 'rbuf'], {'gamma': 'args.discount', 'update_interval': 'args.update_interval', 'replay_start_size': 'args.replay_start_size', 'gpu': 'args.gpu', 'minibatch_size': 'args.batch_size', 'burnin_action_func': 'burnin_action_func', 'entropy_target': '(-action_size)', 'temperature_optimizer_lr': 'args.lr'}), '(policy, q_func1, q_func2, policy_optimizer,\n q_func1_optimizer, q_func2_optimizer, rbuf, gamma=args.discount,\n update_interval=args.update_interval, replay_start_size=args.\n replay_start_size, gpu=args.gpu, minibatch_size=args.batch_size,\n burnin_action_func=burnin_action_func, entropy_target=-action_size,\n temperature_optimizer_lr=args.lr)\n', (7972, 8330), False, 'import pfrl\n'), ((565, 595), 'distutils.version.StrictVersion', 'StrictVersion', (['gym.__version__'], {}), '(gym.__version__)\n', (578, 595), False, 'from distutils.version import StrictVersion\n'), ((1270, 1356), 'pfrl.wrappers.Monitor', 'pfrl.wrappers.Monitor', (['env', 'args.outdir'], {'force': '(True)', 'video_callable': '(lambda _: True)'}), '(env, args.outdir, force=True, video_callable=lambda _:\n True)\n', (1291, 1356), False, 'import pfrl\n'), ((1409, 1448), 'pfrl.wrappers.Render', 'pfrl.wrappers.Render', (['env'], {'mode': '"""human"""'}), "(env, mode='human')\n", (1429, 1448), False, 'import pfrl\n'), ((4897, 4921), 'numpy.arange', 'np.arange', (['args.num_envs'], {}), '(args.num_envs)\n', (4906, 4921), True, 'import numpy as np\n'), ((5715, 5739), 'torch.chunk', 'torch.chunk', (['x', '(2)'], {'dim': '(1)'}), '(x, 2, dim=1)\n', (5726, 5739), False, 'import torch\n'), ((5760, 5794), 'torch.clamp', 'torch.clamp', (['log_scale', '(-20.0)', '(2.0)'], {}), '(log_scale, -20.0, 2.0)\n', (5771, 5794), False, 'import torch\n'), ((5809, 5833), 'torch.exp', 'torch.exp', (['(log_scale * 2)'], {}), '(log_scale * 2)\n', (5818, 5833), False, 'import torch\n'), ((6239, 6292), 'torch.nn.Linear', 'nn.Linear', (['obs_space.low.size', 'args.n_hidden_channels'], {}), '(obs_space.low.size, args.n_hidden_channels)\n', (6248, 6292), False, 'from torch import distributions, nn\n'), ((6302, 6311), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (6309, 6311), False, 'from torch import distributions, nn\n'), ((6321, 6378), 'torch.nn.Linear', 'nn.Linear', (['args.n_hidden_channels', 'args.n_hidden_channels'], {}), '(args.n_hidden_channels, args.n_hidden_channels)\n', (6330, 6378), False, 'from torch import distributions, nn\n'), ((6388, 6397), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (6395, 6397), False, 'from torch import distributions, nn\n'), ((6407, 6457), 'torch.nn.Linear', 'nn.Linear', (['args.n_hidden_channels', '(action_size * 2)'], {}), '(args.n_hidden_channels, action_size * 2)\n', (6416, 6457), False, 'from torch import distributions, nn\n'), ((6467, 6506), 'pfrl.nn.lmbda.Lambda', 'Lambda', (['squashed_diagonal_gaussian_head'], {}), '(squashed_diagonal_gaussian_head)\n', (6473, 6506), False, 'from pfrl.nn.lmbda import Lambda\n'), ((7155, 7202), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['q_func[1].weight'], {}), '(q_func[1].weight)\n', (7184, 7202), False, 'import torch\n'), ((7211, 7258), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['q_func[3].weight'], {}), '(q_func[3].weight)\n', (7240, 7258), False, 'import torch\n'), ((7267, 7314), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['q_func[5].weight'], {}), '(q_func[5].weight)\n', (7296, 7314), False, 'import torch\n'), ((8588, 8722), 'pfrl.experiments.eval_performance', 'experiments.eval_performance', ([], {'env': 'eval_env', 'agent': 'agent', 'n_steps': 'None', 'n_episodes': 'args.eval_n_runs', 'max_episode_len': 'timestep_limit'}), '(env=eval_env, agent=agent, n_steps=None,\n n_episodes=args.eval_n_runs, max_episode_len=timestep_limit)\n', (8616, 8722), False, 'from pfrl import experiments, replay_buffers, utils\n'), ((622, 645), 'distutils.version.StrictVersion', 'StrictVersion', (['"""0.15.6"""'], {}), "('0.15.6')\n", (635, 645), False, 'from distutils.version import StrictVersion\n'), ((6859, 6887), 'pfrl.nn.ConcatObsAndAction', 'pfrl.nn.ConcatObsAndAction', ([], {}), '()\n', (6885, 6887), False, 'import pfrl\n'), ((6901, 6968), 'torch.nn.Linear', 'nn.Linear', (['(obs_space.low.size + action_size)', 'args.n_hidden_channels'], {}), '(obs_space.low.size + action_size, args.n_hidden_channels)\n', (6910, 6968), False, 'from torch import distributions, nn\n'), ((6982, 6991), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (6989, 6991), False, 'from torch import distributions, nn\n'), ((7005, 7062), 'torch.nn.Linear', 'nn.Linear', (['args.n_hidden_channels', 'args.n_hidden_channels'], {}), '(args.n_hidden_channels, args.n_hidden_channels)\n', (7014, 7062), False, 'from torch import distributions, nn\n'), ((7076, 7085), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (7083, 7085), False, 'from torch import distributions, nn\n'), ((7099, 7135), 'torch.nn.Linear', 'nn.Linear', (['args.n_hidden_channels', '(1)'], {}), '(args.n_hidden_channels, 1)\n', (7108, 7135), False, 'from torch import distributions, nn\n'), ((5100, 5159), 'functools.partial', 'functools.partial', (['make_env', 'args', 'process_seeds[idx]', 'test'], {}), '(make_env, args, process_seeds[idx], test)\n', (5117, 5159), False, 'import functools\n'), ((6138, 6190), 'torch.distributions.transforms.TanhTransform', 'distributions.transforms.TanhTransform', ([], {'cache_size': '(1)'}), '(cache_size=1)\n', (6176, 6190), False, 'from torch import distributions, nn\n'), ((7801, 7855), 'numpy.random.uniform', 'np.random.uniform', (['action_space.low', 'action_space.high'], {}), '(action_space.low, action_space.high)\n', (7818, 7855), True, 'import numpy as np\n'), ((5938, 5953), 'torch.sqrt', 'torch.sqrt', (['var'], {}), '(var)\n', (5948, 5953), False, 'import torch\n')]
""" Functions that are no longer used in my notebooks due to finding more effective functions. """ import numpy as np import numpy.polynomial.polynomial as poly import matplotlib.pyplot as plt import os from scipy import optimize as opt from scipy.stats import linregress import math import pandas as pd import netCDF4 as nc import datetime as dt from salishsea_tools import evaltools as et, viz_tools import gsw import matplotlib.gridspec as gridspec import matplotlib as mpl import matplotlib.dates as mdates import cmocean as cmo import scipy.interpolate as sinterp import pickle import warnings import cmocean import json import f90nml from collections import OrderedDict from matplotlib.colors import LogNorm colors=('blue','green','firebrick','darkorange','darkviolet','fuchsia', 'royalblue','darkgoldenrod','mediumspringgreen','deepskyblue') def ts_gsmooth_line(ax,df,obsvar,modvar,start_date,end_date,L=50,region='',station='',sepvar='',sepvals=([]),lname='',sepunits='', ocols=('blue','darkviolet','teal','green','deepskyblue'), mcols=('fuchsia','firebrick','orange','darkgoldenrod','maroon'),labels=''): """ Plots the daily average value of df[obsvar] and df[modvar] against df[YD]. """ if len(lname)==0: lname=sepvar ps=list() df=df.dropna(axis=0,subset=['dtUTC',obsvar,modvar]) if len(region) > 0: df=df[df['Basin'] == region] if len(station) > 0: df=df[df['Station'] == station] if len(sepvals)==0: obs0=et._deframe(df.loc[(df['dtUTC'] >= start_date)&(df['dtUTC']<= end_date),[obsvar]]) mod0=et._deframe(df.loc[(df['dtUTC'] >= start_date)&(df['dtUTC']<= end_date),[modvar]]) time0=et._deframe(df.loc[(df['dtUTC'] >= start_date)&(df['dtUTC']<= end_date),['YD']]) ox0,ox2=gsmooth(time0,obs0,L) ps0,=ax.plot(ox0,ox2,'-',color=ocols[0], label=f'Observed {lname}',alpha=0.7, linestyle='dashed') ps.append(ps0) mx0,mx2=gsmooth(time0,mod0,L) ps0,=ax.plot(mx0,mx2,'-',color=mcols[0], label=f'Modeled {lname}',alpha=0.7, linestyle='dashed') ps.append(ps0) else: obs0=et._deframe(df.loc[(df[obsvar]==df[obsvar])&(df[modvar]==df[modvar])&(df[sepvar]==df[sepvar])&(df['dtUTC'] >= start_date)&(df['dtUTC']<= end_date),[obsvar]]) mod0=et._deframe(df.loc[(df[obsvar]==df[obsvar])&(df[modvar]==df[modvar])&(df[sepvar]==df[sepvar])&(df['dtUTC'] >= start_date)&(df['dtUTC']<= end_date),[modvar]]) time0=et._deframe(df.loc[(df[obsvar]==df[obsvar])&(df[modvar]==df[modvar])&(df[sepvar]==df[sepvar])&(df['dtUTC'] >= start_date)&(df['dtUTC']<= end_date),['YD']]) sep0=et._deframe(df.loc[(df[obsvar]==df[obsvar])&(df[modvar]==df[modvar])&(df[sepvar]==df[sepvar])&(df['dtUTC'] >= start_date)&(df['dtUTC']<= end_date),[sepvar]]) sepvals=np.sort(sepvals) # less than min case: ii=0 iii=sep0<sepvals[ii] if np.sum(iii)>0: #ll=u'{} < {} {}'.format(lname,sepvals[ii],sepunits).strip() if len(labels)>0: ll=labels[0] else: ll=u'{} $<$ {} {}'.format(lname,sepvals[ii],sepunits).strip() ox0,ox2=gsmooth(time0[iii],obs0[iii],L) ps0,=ax.plot(ox0,ox2,'-',color=ocols[ii], label=f'Observed {ll}',alpha=0.7, linestyle='dashed') ps.append(ps0) mx0,mx2=gsmooth(time0[iii],mod0[iii],L) ps0,=ax.plot(mx0,mx2,'-',color=mcols[ii], label=f'Modeled {ll}',alpha=0.7, linestyle='dashed') ps.append(ps0) # between min and max: for ii in range(1,len(sepvals)): iii=np.logical_and(sep0<sepvals[ii],sep0>=sepvals[ii-1]) if np.sum(iii)>0: #ll=u'{} {} \u2264 {} < {} {}'.format(sepvals[ii-1],sepunits,lname,sepvals[ii],sepunits).strip() if len(labels)>0: ll=labels[ii] else: ll=u'{} {} $\leq$ {} $<$ {} {}'.format(sepvals[ii-1],sepunits,lname,sepvals[ii],sepunits).strip() ox0,ox2=gsmooth(time0[iii],obs0[iii],L) ps0,=ax.plot(ox0,ox2,'-',color=ocols[ii], label=f'Observed {ll}',alpha=0.7, linestyle='dashed') ps.append(ps0) mx0,mx2=gsmooth(time0[iii],mod0[iii],L) ps0,=ax.plot(mx0,mx2,'-',color=mcols[ii], label=f'Modeled {ll}',alpha=0.7, linestyle='dashed') ps.append(ps0) # greater than max: iii=sep0>=sepvals[ii] if np.sum(iii)>0: #ll=u'{} \u2265 {} {}'.format(lname,sepvals[ii],sepunits).strip() if len(labels)>0: ll=labels[ii+1] else: ll=u'{} $\geq$ {} {}'.format(lname,sepvals[ii],sepunits).strip() ox0,ox2=gsmooth(time0[iii],obs0[iii],L) ps0,=ax.plot(ox0,ox2,'-',color=ocols[ii+1], label=f'Observed {ll}',alpha=0.7, linestyle='dashed') ps.append(ps0) mx0,mx2=gsmooth(time0[iii],mod0[iii],L) ps0,=ax.plot(mx0,mx2,'-',color=mcols[ii+1], label=f'Modeled {ll}',alpha=0.7, linestyle='dashed') ps.append(ps0) yearsFmt = mdates.DateFormatter('%d %b %y') ax.xaxis.set_major_formatter(yearsFmt) return ps def gsmooth(YD,val,L,res=1): # DD is input date in decimal days (ususally since 1900,1,1) # val is values to be smoothed # L is length scale of gaussian kernel- larger widens the window # res can be changed to give a different resolution of output allt=np.arange(0,366+res,res) fil=np.empty(np.size(allt)) #ohhh this is cool. It automatically creates an empty array of the size you need. s=L/2.355 for ind,t in enumerate(allt): diff=[min(abs(x-t),abs(x-t+365), abs(x-t-365)) for x in YD] weight=[np.exp(-.5*x**2/s**2) if x <= 3*L else 0.0 for x in diff] fil[ind]=np.sum(weight*val)/np.sum(weight) return allt,fil
[ "numpy.logical_and", "numpy.sort", "matplotlib.dates.DateFormatter", "numpy.size", "numpy.exp", "numpy.sum", "salishsea_tools.evaltools._deframe", "numpy.arange" ]
[((5162, 5194), 'matplotlib.dates.DateFormatter', 'mdates.DateFormatter', (['"""%d %b %y"""'], {}), "('%d %b %y')\n", (5182, 5194), True, 'import matplotlib.dates as mdates\n'), ((5510, 5538), 'numpy.arange', 'np.arange', (['(0)', '(366 + res)', 'res'], {}), '(0, 366 + res, res)\n', (5519, 5538), True, 'import numpy as np\n'), ((1518, 1608), 'salishsea_tools.evaltools._deframe', 'et._deframe', (["df.loc[(df['dtUTC'] >= start_date) & (df['dtUTC'] <= end_date), [obsvar]]"], {}), "(df.loc[(df['dtUTC'] >= start_date) & (df['dtUTC'] <= end_date),\n [obsvar]])\n", (1529, 1608), True, 'from salishsea_tools import evaltools as et, viz_tools\n'), ((1614, 1704), 'salishsea_tools.evaltools._deframe', 'et._deframe', (["df.loc[(df['dtUTC'] >= start_date) & (df['dtUTC'] <= end_date), [modvar]]"], {}), "(df.loc[(df['dtUTC'] >= start_date) & (df['dtUTC'] <= end_date),\n [modvar]])\n", (1625, 1704), True, 'from salishsea_tools import evaltools as et, viz_tools\n'), ((1711, 1799), 'salishsea_tools.evaltools._deframe', 'et._deframe', (["df.loc[(df['dtUTC'] >= start_date) & (df['dtUTC'] <= end_date), ['YD']]"], {}), "(df.loc[(df['dtUTC'] >= start_date) & (df['dtUTC'] <= end_date),\n ['YD']])\n", (1722, 1799), True, 'from salishsea_tools import evaltools as et, viz_tools\n'), ((2148, 2329), 'salishsea_tools.evaltools._deframe', 'et._deframe', (["df.loc[(df[obsvar] == df[obsvar]) & (df[modvar] == df[modvar]) & (df[sepvar\n ] == df[sepvar]) & (df['dtUTC'] >= start_date) & (df['dtUTC'] <=\n end_date), [obsvar]]"], {}), "(df.loc[(df[obsvar] == df[obsvar]) & (df[modvar] == df[modvar]) &\n (df[sepvar] == df[sepvar]) & (df['dtUTC'] >= start_date) & (df['dtUTC'] <=\n end_date), [obsvar]])\n", (2159, 2329), True, 'from salishsea_tools import evaltools as et, viz_tools\n'), ((2319, 2500), 'salishsea_tools.evaltools._deframe', 'et._deframe', (["df.loc[(df[obsvar] == df[obsvar]) & (df[modvar] == df[modvar]) & (df[sepvar\n ] == df[sepvar]) & (df['dtUTC'] >= start_date) & (df['dtUTC'] <=\n end_date), [modvar]]"], {}), "(df.loc[(df[obsvar] == df[obsvar]) & (df[modvar] == df[modvar]) &\n (df[sepvar] == df[sepvar]) & (df['dtUTC'] >= start_date) & (df['dtUTC'] <=\n end_date), [modvar]])\n", (2330, 2500), True, 'from salishsea_tools import evaltools as et, viz_tools\n'), ((2491, 2670), 'salishsea_tools.evaltools._deframe', 'et._deframe', (["df.loc[(df[obsvar] == df[obsvar]) & (df[modvar] == df[modvar]) & (df[sepvar\n ] == df[sepvar]) & (df['dtUTC'] >= start_date) & (df['dtUTC'] <=\n end_date), ['YD']]"], {}), "(df.loc[(df[obsvar] == df[obsvar]) & (df[modvar] == df[modvar]) &\n (df[sepvar] == df[sepvar]) & (df['dtUTC'] >= start_date) & (df['dtUTC'] <=\n end_date), ['YD']])\n", (2502, 2670), True, 'from salishsea_tools import evaltools as et, viz_tools\n'), ((2660, 2841), 'salishsea_tools.evaltools._deframe', 'et._deframe', (["df.loc[(df[obsvar] == df[obsvar]) & (df[modvar] == df[modvar]) & (df[sepvar\n ] == df[sepvar]) & (df['dtUTC'] >= start_date) & (df['dtUTC'] <=\n end_date), [sepvar]]"], {}), "(df.loc[(df[obsvar] == df[obsvar]) & (df[modvar] == df[modvar]) &\n (df[sepvar] == df[sepvar]) & (df['dtUTC'] >= start_date) & (df['dtUTC'] <=\n end_date), [sepvar]])\n", (2671, 2841), True, 'from salishsea_tools import evaltools as et, viz_tools\n'), ((2834, 2850), 'numpy.sort', 'np.sort', (['sepvals'], {}), '(sepvals)\n', (2841, 2850), True, 'import numpy as np\n'), ((5552, 5565), 'numpy.size', 'np.size', (['allt'], {}), '(allt)\n', (5559, 5565), True, 'import numpy as np\n'), ((2942, 2953), 'numpy.sum', 'np.sum', (['iii'], {}), '(iii)\n', (2948, 2953), True, 'import numpy as np\n'), ((3646, 3705), 'numpy.logical_and', 'np.logical_and', (['(sep0 < sepvals[ii])', '(sep0 >= sepvals[ii - 1])'], {}), '(sep0 < sepvals[ii], sep0 >= sepvals[ii - 1])\n', (3660, 3705), True, 'import numpy as np\n'), ((4516, 4527), 'numpy.sum', 'np.sum', (['iii'], {}), '(iii)\n', (4522, 4527), True, 'import numpy as np\n'), ((5856, 5876), 'numpy.sum', 'np.sum', (['(weight * val)'], {}), '(weight * val)\n', (5862, 5876), True, 'import numpy as np\n'), ((5875, 5889), 'numpy.sum', 'np.sum', (['weight'], {}), '(weight)\n', (5881, 5889), True, 'import numpy as np\n'), ((3714, 3725), 'numpy.sum', 'np.sum', (['iii'], {}), '(iii)\n', (3720, 3725), True, 'import numpy as np\n'), ((5781, 5811), 'numpy.exp', 'np.exp', (['(-0.5 * x ** 2 / s ** 2)'], {}), '(-0.5 * x ** 2 / s ** 2)\n', (5787, 5811), True, 'import numpy as np\n')]
# code is based on https://github.com/katerakelly/pytorch-maml and is modified from https://github.com/floodsung/LearningToCompare_FSL.git import random import os from PIL import Image import matplotlib.pyplot as plt import numpy as np def mini_imagenet_folders(): train_folder = 'datas/miniImagenet/train' test_folder = 'datas/miniImagenet/test' metatrain_folders = [os.path.join(train_folder, label) \ for label in os.listdir(train_folder) \ if os.path.isdir(os.path.join(train_folder, label)) \ ] metatest_folders = [os.path.join(test_folder, label) \ for label in os.listdir(test_folder) \ if os.path.isdir(os.path.join(test_folder, label)) \ ] random.seed(1) random.shuffle(metatrain_folders) random.shuffle(metatest_folders) return metatrain_folders,metatest_folders class MiniImagenetTask(object): def __init__(self, character_folders, num_classes, train_num,test_num): self.character_folders = character_folders self.num_classes = num_classes self.train_num = train_num self.test_num = test_num class_folders = random.sample(self.character_folders,self.num_classes) labels = np.array(range(len(class_folders))) labels = dict(zip(class_folders, labels)) samples = dict() self.train_roots = [] self.test_roots = [] for c in class_folders: temp = [os.path.join(c, x) for x in os.listdir(c)] samples[c] = random.sample(temp, len(temp)) random.shuffle(samples[c]) self.train_roots += samples[c][:train_num] self.test_roots += samples[c][train_num:train_num+test_num] self.train_labels = [labels[self.get_class(x)] for x in self.train_roots] self.test_labels = [labels[self.get_class(x)] for x in self.test_roots] def get_class(self, sample): return os.path.join(*sample.split('/')[:-1]) class dataset(): def __init__(self, task, num_per_class, split='train', shuffle=True): self.num_per_class = num_per_class self.task = task self.split = split self.shuffle = shuffle self.image_roots = self.task.train_roots if self.split == 'train' else self.task.test_roots self.labels = self.task.train_labels if self.split == 'train' else self.task.test_labels def getitem(self, idx): image_root = self.image_roots[idx] image = Image.open(image_root) image = image.convert('RGB') label = np.zeros((self.task.num_classes,1)) label[self.labels[idx],0] = 1 return ((np.array(image)/255)-0.92206)/0.08426, label def generator(self): while(True): if self.split == 'train': num_inst = self.task.train_num else: num_inst = self.task.test_num if self.shuffle: batch = [[i+j*num_inst for i in np.random.permutation(num_inst)[:self.num_per_class]] for j in range(self.task.num_classes)] else: batch = [[i+j*num_inst for i in range(num_inst)[:self.num_per_class]] for j in range(self.task.num_classes)] batch = [item for sublist in batch for item in sublist] if self.shuffle: random.shuffle(batch) for idx in batch: yield self.getitem(idx)
[ "random.sample", "PIL.Image.open", "os.listdir", "random.shuffle", "os.path.join", "random.seed", "numpy.array", "numpy.zeros", "numpy.random.permutation" ]
[((770, 784), 'random.seed', 'random.seed', (['(1)'], {}), '(1)\n', (781, 784), False, 'import random\n'), ((789, 822), 'random.shuffle', 'random.shuffle', (['metatrain_folders'], {}), '(metatrain_folders)\n', (803, 822), False, 'import random\n'), ((827, 859), 'random.shuffle', 'random.shuffle', (['metatest_folders'], {}), '(metatest_folders)\n', (841, 859), False, 'import random\n'), ((384, 417), 'os.path.join', 'os.path.join', (['train_folder', 'label'], {}), '(train_folder, label)\n', (396, 417), False, 'import os\n'), ((588, 620), 'os.path.join', 'os.path.join', (['test_folder', 'label'], {}), '(test_folder, label)\n', (600, 620), False, 'import os\n'), ((1202, 1257), 'random.sample', 'random.sample', (['self.character_folders', 'self.num_classes'], {}), '(self.character_folders, self.num_classes)\n', (1215, 1257), False, 'import random\n'), ((2533, 2555), 'PIL.Image.open', 'Image.open', (['image_root'], {}), '(image_root)\n', (2543, 2555), False, 'from PIL import Image\n'), ((2609, 2645), 'numpy.zeros', 'np.zeros', (['(self.task.num_classes, 1)'], {}), '((self.task.num_classes, 1))\n', (2617, 2645), True, 'import numpy as np\n'), ((449, 473), 'os.listdir', 'os.listdir', (['train_folder'], {}), '(train_folder)\n', (459, 473), False, 'import os\n'), ((652, 675), 'os.listdir', 'os.listdir', (['test_folder'], {}), '(test_folder)\n', (662, 675), False, 'import os\n'), ((1609, 1635), 'random.shuffle', 'random.shuffle', (['samples[c]'], {}), '(samples[c])\n', (1623, 1635), False, 'import random\n'), ((509, 542), 'os.path.join', 'os.path.join', (['train_folder', 'label'], {}), '(train_folder, label)\n', (521, 542), False, 'import os\n'), ((711, 743), 'os.path.join', 'os.path.join', (['test_folder', 'label'], {}), '(test_folder, label)\n', (723, 743), False, 'import os\n'), ((1498, 1516), 'os.path.join', 'os.path.join', (['c', 'x'], {}), '(c, x)\n', (1510, 1516), False, 'import os\n'), ((3369, 3390), 'random.shuffle', 'random.shuffle', (['batch'], {}), '(batch)\n', (3383, 3390), False, 'import random\n'), ((1526, 1539), 'os.listdir', 'os.listdir', (['c'], {}), '(c)\n', (1536, 1539), False, 'import os\n'), ((2700, 2715), 'numpy.array', 'np.array', (['image'], {}), '(image)\n', (2708, 2715), True, 'import numpy as np\n'), ((3019, 3050), 'numpy.random.permutation', 'np.random.permutation', (['num_inst'], {}), '(num_inst)\n', (3040, 3050), True, 'import numpy as np\n')]
#Copyright (c) Microsoft Corporation. All rights reserved. #Licensed under the MIT License. from tensorflow.keras import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten, LeakyReLU, Reshape, Conv2DTranspose, Conv2D from tensorflow.keras.optimizers import Adam from tensorflow.keras import initializers import numpy as np def CIFAR_Generator(randomDim = 100, optim = Adam(lr=0.0002, beta_1=0.5)): """Creates a generateof for LFW dataset Args: randomDim (int, optional): input shape. Defaults to 100. optim ([Adam], optional): optimizer. Defaults to Adam(lr=0.0002, beta_1=0.5). """ generator = Sequential() generator.add(Dense(2*2*512, input_shape=(randomDim,), kernel_initializer=initializers.RandomNormal(stddev=0.02), name = 'layer'+str(np.random.randint(0,1e9)))) generator.add(Reshape((2, 2, 512), name = 'layer'+str(np.random.randint(0,1e9)))) generator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) generator.add(Conv2DTranspose(256, kernel_size=5, strides=2, padding='same', name = 'layer'+str(np.random.randint(0,1e9)))) generator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) generator.add(Conv2DTranspose(128, kernel_size=5, strides=2, padding='same', name = 'layer'+str(np.random.randint(0,1e9)))) generator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) generator.add(Conv2DTranspose(64, kernel_size=5, strides=2, padding='same', name = 'layer'+str(np.random.randint(0,1e9)))) generator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) generator.add(Conv2DTranspose(3, kernel_size=5, strides=2, padding='same', activation='tanh', name = 'layer'+str(np.random.randint(0,1e9)))) generator.compile(loss='binary_crossentropy', optimizer=optim) return generator def CIFAR_Discriminator(optim = Adam(lr=0.0002, beta_1=0.5)): """Discriminator for LFW dataset Args: optim ([Adam], optional): optimizer. Defaults to Adam(lr=0.0002, beta_1=0.5). """ discriminator = Sequential() discriminator.add(Conv2D(64, kernel_size=5, strides=2, padding='same', input_shape=((32, 32, 3)), kernel_initializer=initializers.RandomNormal(stddev=0.02), name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(Conv2D(128, kernel_size=5, strides=2, padding='same', name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(Conv2D(128, kernel_size=5, strides=2, padding='same', name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(Conv2D(256, kernel_size=5, strides=2, padding='same', name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(Flatten(name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(Dense(1, activation='sigmoid', name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.compile(loss='binary_crossentropy', optimizer=optim) return discriminator def CIFAR_DiscriminatorPrivate(OutSize = 2, optim = Adam(lr=0.0002, beta_1=0.5)): """The discriminator designed to guess which Generator generated the data Args: OutSize (int, optional): [description]. Defaults to 2. optim ([type], optional): optimizer. Defaults to Adam(lr=0.0002, beta_1=0.5). """ discriminator = Sequential() discriminator.add(Conv2D(64, kernel_size=5, strides=2, padding='same', input_shape=((32, 32, 3)), kernel_initializer=initializers.RandomNormal(stddev=0.02), name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(Conv2D(128, kernel_size=5, strides=2, padding='same', name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(Conv2D(128, kernel_size=5, strides=2, padding='same', name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(LeakyReLU(0.2,name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(Conv2D(256, kernel_size=5, strides=2, padding='same', name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(LeakyReLU(0.2, name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(Flatten(name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.add(Dense(OutSize, activation='softmax', name = 'layer'+str(np.random.randint(0,1e9)))) discriminator.compile(loss='sparse_categorical_crossentropy', optimizer=optim) return discriminator
[ "tensorflow.keras.optimizers.Adam", "numpy.random.randint", "tensorflow.keras.Sequential", "tensorflow.keras.initializers.RandomNormal" ]
[((392, 419), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)', 'beta_1': '(0.5)'}), '(lr=0.0002, beta_1=0.5)\n', (396, 419), False, 'from tensorflow.keras.optimizers import Adam\n'), ((653, 665), 'tensorflow.keras.Sequential', 'Sequential', ([], {}), '()\n', (663, 665), False, 'from tensorflow.keras import Sequential\n'), ((2091, 2118), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)', 'beta_1': '(0.5)'}), '(lr=0.0002, beta_1=0.5)\n', (2095, 2118), False, 'from tensorflow.keras.optimizers import Adam\n'), ((2288, 2300), 'tensorflow.keras.Sequential', 'Sequential', ([], {}), '()\n', (2298, 2300), False, 'from tensorflow.keras import Sequential\n'), ((3831, 3858), 'tensorflow.keras.optimizers.Adam', 'Adam', ([], {'lr': '(0.0002)', 'beta_1': '(0.5)'}), '(lr=0.0002, beta_1=0.5)\n', (3835, 3858), False, 'from tensorflow.keras.optimizers import Adam\n'), ((4132, 4144), 'tensorflow.keras.Sequential', 'Sequential', ([], {}), '()\n', (4142, 4144), False, 'from tensorflow.keras import Sequential\n'), ((744, 782), 'tensorflow.keras.initializers.RandomNormal', 'initializers.RandomNormal', ([], {'stddev': '(0.02)'}), '(stddev=0.02)\n', (769, 782), False, 'from tensorflow.keras import initializers\n'), ((2451, 2489), 'tensorflow.keras.initializers.RandomNormal', 'initializers.RandomNormal', ([], {'stddev': '(0.02)'}), '(stddev=0.02)\n', (2476, 2489), False, 'from tensorflow.keras import initializers\n'), ((4295, 4333), 'tensorflow.keras.initializers.RandomNormal', 'initializers.RandomNormal', ([], {'stddev': '(0.02)'}), '(stddev=0.02)\n', (4320, 4333), False, 'from tensorflow.keras import initializers\n'), ((820, 854), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (837, 854), True, 'import numpy as np\n'), ((923, 957), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (940, 957), True, 'import numpy as np\n'), ((1020, 1054), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (1037, 1054), True, 'import numpy as np\n'), ((1165, 1199), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (1182, 1199), True, 'import numpy as np\n'), ((1262, 1296), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (1279, 1296), True, 'import numpy as np\n'), ((1407, 1441), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (1424, 1441), True, 'import numpy as np\n'), ((1504, 1538), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (1521, 1538), True, 'import numpy as np\n'), ((1648, 1682), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (1665, 1682), True, 'import numpy as np\n'), ((1745, 1779), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (1762, 1779), True, 'import numpy as np\n'), ((1937, 1971), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (1954, 1971), True, 'import numpy as np\n'), ((2539, 2573), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (2556, 2573), True, 'import numpy as np\n'), ((2652, 2686), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (2669, 2686), True, 'import numpy as np\n'), ((2804, 2838), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (2821, 2838), True, 'import numpy as np\n'), ((2917, 2951), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (2934, 2951), True, 'import numpy as np\n'), ((3069, 3103), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (3086, 3103), True, 'import numpy as np\n'), ((3182, 3216), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (3199, 3216), True, 'import numpy as np\n'), ((3334, 3368), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (3351, 3368), True, 'import numpy as np\n'), ((3447, 3481), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (3464, 3481), True, 'import numpy as np\n'), ((3524, 3558), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (3541, 3558), True, 'import numpy as np\n'), ((3653, 3687), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (3670, 3687), True, 'import numpy as np\n'), ((4383, 4417), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (4400, 4417), True, 'import numpy as np\n'), ((4496, 4530), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (4513, 4530), True, 'import numpy as np\n'), ((4648, 4682), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (4665, 4682), True, 'import numpy as np\n'), ((4761, 4795), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (4778, 4795), True, 'import numpy as np\n'), ((4913, 4947), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (4930, 4947), True, 'import numpy as np\n'), ((4996, 5030), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (5013, 5030), True, 'import numpy as np\n'), ((5148, 5182), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (5165, 5182), True, 'import numpy as np\n'), ((5261, 5295), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (5278, 5295), True, 'import numpy as np\n'), ((5338, 5372), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (5355, 5372), True, 'import numpy as np\n'), ((5473, 5507), 'numpy.random.randint', 'np.random.randint', (['(0)', '(1000000000.0)'], {}), '(0, 1000000000.0)\n', (5490, 5507), True, 'import numpy as np\n')]
import sys import random import matplotlib import matplotlib.animation as animation import matplotlib.pyplot as plt import mpl_toolkits.mplot3d.axes3d as p3 from mpl_toolkits.mplot3d import proj3d import numpy as np matplotlib.use("Qt5Agg") from PyQt5 import QtCore from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget,QTabWidget from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas import time import math import Func import parameters matplotlib.matplotlib_fname() class MyMplCanvas(FigureCanvas): """这是一个窗口部件,即QWidget(当然也是FigureCanvasAgg)""" def __init__(self, parent=None, width=5, height=4, dpi=100): self.fig = plt.Figure(figsize=(width, height), dpi=dpi) #self.axes = fig.add_subplot(111) # 每次plot()调用的时候,我们希望原来的坐标轴被清除(所以False) #self.axes.hold(False) self.compute_initial_figure() # FigureCanvas.__init__(self, self.fig) self.setParent(parent) FigureCanvas.setSizePolicy(self, QSizePolicy.Expanding, QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) def compute_initial_figure(self): pass class MyStaticMplCanvas(MyMplCanvas): """静态画布:一条正弦线""" def first_figure(self): x=gs.outKPIall['alpha'] ax1 = self.fig.add_subplot(2,2,1) ax1.plot(x,gs.outKPIall['beta'],'k--',label='Beta') ax1.plot(x,gs.outKPIall['beta2'],'r--',label='Gamma') ax1.set_title('wiping angle v.s motor angle') ax2 = self.fig.add_subplot(2,2,2) ax2.plot(x,gs.outKPIall['beta_s'],'k--',label='B-S') ax2.plot(x,gs.outKPIall['beta_s2'],'r:',label='G-S') ax2.set_title('wiping angle velocity v.s motor angle') ax3 = self.fig.add_subplot(2,2,3) ax3.plot(x,gs.outKPIall['beta_ss'],'k--',label='B-SS') ax3.plot(x,gs.outKPIall['beta_ss2'],'r:',label='G-SS') ax3.set_title('wiping angel accelaration v.s motor angle') ax1.legend() ax2.legend() ax3.legend() self.fig.savefig('.\\output\\pics\\'+gs.ProjectName+'_Angle'+gs.styleTime+'.jpg') #plt.figure(2) def second_figure(self): x=gs.outKPIall['alpha'] axs1 = self.fig.add_subplot(2,2,1) axs1.plot(x,gs.outKPIall['NYS_T'],'k--',label='NYS_T') axs1.plot(x,gs.outKPIall['NYS_T2'],'r:',label='NYS_T2') axs1.set_title('NYS_T v.s motro angle') axs2 = self.fig.add_subplot(2,2,2) axs2.plot(x,gs.outKPIall['NYK_T'],'k--',label='NYK_T') axs2.plot(x,gs.outKPIall['NYK_T2'],'r:',label='NYK_T2') axs2.set_title('NYK_T v.s motro angle') axs3 = self.fig.add_subplot(2,2,3) axs3.plot(x,gs.outKPIall['NYS_A'],'k--',label='NYS_A') axs3.plot(x,gs.outKPIall['NYS_A2'],'r:',label='NYS_A2') axs3.set_title('NYS_A v.s motro angle') axs4 = self.fig.add_subplot(2,2,4) axs4.plot(x,gs.outKPIall['NYK_A'],'k--',label='NYK_A') axs4.plot(x,gs.outKPIall['NYK_A2'],'r:',label='NYK_A2') axs4.set_title('NYK_A v.s motro angle') axs1.legend() axs2.legend() axs3.legend() axs4.legend() self.fig.savefig('.\\output\\pics\\'+gs.ProjectName+'_NY'+gs.styleTime+'.jpg') # temporialy test @staticmethod def generateData(): # generate data to animate number = gs.num Atemp=np.array([gs.A]*number).T Btemp=np.array([gs.B]*number).T Etemp=np.array([gs.E]*number).T Ftemp=np.array([gs.F]*number).T A2temp=np.array([gs.A2]*number).T B2temp=np.array([gs.B2]*number).T E2temp=np.array([gs.E2]*number).T F2temp=np.array([gs.F2]*number).T Ctemp= np.array((gs.outCordinateall['Cx'],gs.outCordinateall['Cy'],gs.outCordinateall['Cz'])) Dtemp= np.array((gs.outCordinateall['Dx'],gs.outCordinateall['Dy'],gs.outCordinateall['Dz'])) C2temp= np.array((gs.outCordinateall['Cx2'],gs.outCordinateall['Cy2'],gs.outCordinateall['Cz2'])) D2temp= np.array((gs.outCordinateall['Dx2'],gs.outCordinateall['Dy2'],gs.outCordinateall['Dz2'])) dataAB=np.r_[Atemp,Btemp] dataAB2=np.r_[A2temp,B2temp] dataEF=np.r_[Etemp,Ftemp] dataEF2=np.r_[E2temp,F2temp] dataCD =np.r_[Ctemp,Dtemp] dataCD2=np.r_[C2temp,D2temp] dataBC=np.r_[Btemp,Ctemp] dataDE=np.r_[Dtemp,Etemp] dataBC2=np.r_[B2temp,C2temp] dataDE2=np.r_[D2temp,E2temp] dataCD2=np.r_[C2temp,D2temp] data=np.ones((10,6,number)) data[0]=dataAB data[1]=dataBC data[2]=dataCD data[3]=dataDE data[4]=dataEF data[5]=dataAB2 data[6]=dataBC2 data[7]=dataCD2 data[8]=dataDE2 data[9]=dataEF2 return data @staticmethod def getMinMax(data): # get min/max az,el for 3d plot cordinateMin = np.max(data[0],axis=1) cordinateMax = np.max(data[0],axis=1) for item in data: cordinateMaxNew = np.max(item,axis=1) cordinateMinNew = np.min(item,axis=1) for i in range(6): if cordinateMaxNew[i] > cordinateMax[i]: cordinateMax[i] = cordinateMaxNew[i] if cordinateMinNew[i] < cordinateMin[i]: cordinateMin[i] = cordinateMinNew[i] xmin = min (cordinateMin[0],cordinateMin[3]) ymin = min (cordinateMin[1],cordinateMin[4]) zmin = min (cordinateMin[2],cordinateMin[5]) xmax = max (cordinateMax[0],cordinateMax[3]) ymax = max (cordinateMax[1],cordinateMax[4]) zmax = max (cordinateMax[2],cordinateMax[5]) xxrange = xmax-xmin yrange = ymax-ymin zrange = zmax-zmin ab=gs.B-gs.A abScale = [ab[0]/xxrange,ab[1]/yrange,ab[2]/zrange] #scale axis equal az=-90-Func.degree(math.atan(abScale[0]/abScale[1])) el=-np.sign(ab[1])*Func.degree(math.atan(abScale[2]/math.sqrt(abScale[0]**2+abScale[1]**2))) return [[xmin,xmax,ymin,ymax,zmin,zmax],[az,el]] #TBD # initial point @staticmethod def orthogonal_proj(zfront, zback): a = (zfront+zback)/(zfront-zback) b = -2*(zfront*zback)/(zfront-zback) return np.array([[1,0,0,0], [0,1,0,0], [0,0,a,b], [0,0, -0.0001,zback]]) def animationSteady(self): proj3d.persp_transformation = self.orthogonal_proj data= self.generateData() [[xmin,xmax,ymin,ymax,zmin,zmax],[az,el]]= self.getMinMax(data) ax2 = p3.Axes3D(self.fig) ax2.set_xlabel('x') ax2.set_ylabel('y') ax2.set_zlabel('z') Label=['AB','BC','CD','DE','EF','AB2','BC2','CD2','DE2','EF2'] colors ='bgcmkbgcmk' linestyles=['-','-','-','-','-','--','--','--','--','--'] ax2.set_xlim3d(xmin,xmax) ax2.set_ylim3d(ymin,ymax) ax2.set_zlim3d(zmin,zmax) ax2.set_title('initial position') #ax2.axis('scaled') ax2.view_init(azim=az, elev=el) lines = [ax2.plot([data[i][0,0],data[i][3,0]],[data[i][1,0],data[i][4,0]],[data[i][2,0],data[i][5,0]],label=Label[i],color=colors[i],linestyle=linestyles[i])[0] for i in range(10)] self.fig.legend() # Attaching 3D axis to the figure def animation(self): def onClick(event): gs.pause ^= True def update_lines ( num, dataLines, lines, ax): if not gs.pause: for line, data in zip(lines, dataLines): # NOTE: there is no .set_data() for 3 dim data. Cx = data[0, num] Cy = data[1, num] Cz = data[2, num] Dx = data[3, num] Dy = data[4, num] Dz = data[5, num] temp = [[Cx, Dx], [Cy, Dy]] line.set_data(temp) line.set_3d_properties([Cz, Dz]) return lines number = 12 proj3d.persp_transformation = self.orthogonal_proj data= self.generateData() [[xmin,xmax,ymin,ymax,zmin,zmax],[az,el]]= self.getMinMax(data) ax = p3.Axes3D(self.fig) gs.pause =False # ============================================================================= ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') ax.set_title('kinematics') #ax.set_xbound(0.9*xmin,1.1*xmax) #ax.set_ybound(0.9*ymin,1.1*ymax) #ax.set_zbound(0.9*zmin,1.1*zmax) # ============================================================================= #ax.axis('equal') ax.view_init(azim=az,elev=el) # ============================================================================= txt=['A','B','C','D','E','F','A2','B2','C2','D2','E2','F2'] # Creating the Animation object Label=['AB','BC','CD','DE','EF','AB2','BC2','CD2','DE2','EF2'] colors ='bgcmkbgcmk' linestyles=['-','-','-','-','-','--','--','--','--','--'] lines = [ax.plot([data[i][0,0],data[i][3,0]],[data[i][1,0],data[i][4,0]],[data[i][2,0],data[i][5,0]],label=Label[i],color=colors[i],linestyle=linestyles[i])[0] for i in range(10)] #start of each line self.fig.canvas.mpl_connect('button_press_event', onClick) gs.line_ani=animation.FuncAnimation(self.fig, update_lines, number, fargs=(data, lines,ax),interval=int(3600/number), blit=True) #============================================================================== # plt.rcParams['animation.ffmpeg_path']='G:\\wai\\ffmpeg\\bin\\ffmpeg.exe' #============================================================================== self.fig.legend() #plt.show() #return gs.line_ani class ApplicationWindow(QTabWidget): def __init__(self): QMainWindow.__init__(self) self.showMaximized() self.setAttribute(QtCore.Qt.WA_DeleteOnClose) self.setWindowTitle("plot&anmiation") self.widget1 = QWidget(self) self.widget2 = QWidget(self) self.widget3 = QWidget(self) self.widget4 = QWidget(self) self.addTab(self.widget1,u"Wiping angle curve") self.addTab(self.widget2,u"NY angle curve") self.addTab(self.widget3,u"initial position ") self.addTab(self.widget4,u"animation ") sc1 = MyStaticMplCanvas(self.widget1, width=8, height=6, dpi=100) sc2 = MyStaticMplCanvas(self.widget2, width=8, height=6, dpi=100) sc3 = MyStaticMplCanvas(self.widget3, width=8, height=6, dpi=100) sc4 = MyStaticMplCanvas(self.widget4, width=8, height=6, dpi=100) sc1.first_figure() sc2.second_figure() sc3.animationSteady() sc4.animation() l1 = QVBoxLayout(self.widget1) l2 = QVBoxLayout(self.widget2) l3 = QVBoxLayout(self.widget3) l4 = QVBoxLayout(self.widget4) l1.addWidget(sc1) l2.addWidget(sc2) l3.addWidget(sc3) l4.addWidget(sc4) self.widget1.setFocus() #self.settCentralWidget(self.widget1) # 状态条显示2秒 #self.statusBar().showMessage(str(time.time())+' k5la') def fileQuit(self): self.close() def closeEvent(self, ce): self.fileQuit() def about(self): QMessageBox.about(self, "About", """embedding_in_qt5.py example Copyright 2015 BoxControL This program is a simple example of a Qt5 application embedding matplotlib canvases. It is base on example from matplolib documentation, and initially was developed from <NAME> and <NAME>. http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html It may be used and modified with no restriction; raw copies as well as modified versions may be distributed without limitation. """ ) if __name__ == '__main__': app = QApplication(sys.argv) outputs= parameters.Outputs() gs = parameters.GS() outjson='output.json' Func.LoadJson(outjson,outputs,gs) aw = ApplicationWindow() aw.show() #sys.exit(qApp.exec_()) app.exec_()
[ "matplotlib.pyplot.Figure", "math.sqrt", "numpy.array", "matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.updateGeometry", "PyQt5.QtWidgets.QMessageBox.about", "PyQt5.QtWidgets.QApplication", "PyQt5.QtWidgets.QVBoxLayout", "math.atan", "matplotlib.matplotlib_fname", "numpy.max", "numpy.min",...
[((217, 241), 'matplotlib.use', 'matplotlib.use', (['"""Qt5Agg"""'], {}), "('Qt5Agg')\n", (231, 241), False, 'import matplotlib\n'), ((524, 553), 'matplotlib.matplotlib_fname', 'matplotlib.matplotlib_fname', ([], {}), '()\n', (551, 553), False, 'import matplotlib\n'), ((13006, 13028), 'PyQt5.QtWidgets.QApplication', 'QApplication', (['sys.argv'], {}), '(sys.argv)\n', (13018, 13028), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((13042, 13062), 'parameters.Outputs', 'parameters.Outputs', ([], {}), '()\n', (13060, 13062), False, 'import parameters\n'), ((13072, 13087), 'parameters.GS', 'parameters.GS', ([], {}), '()\n', (13085, 13087), False, 'import parameters\n'), ((13118, 13153), 'Func.LoadJson', 'Func.LoadJson', (['outjson', 'outputs', 'gs'], {}), '(outjson, outputs, gs)\n', (13131, 13153), False, 'import Func\n'), ((720, 764), 'matplotlib.pyplot.Figure', 'plt.Figure', ([], {'figsize': '(width, height)', 'dpi': 'dpi'}), '(figsize=(width, height), dpi=dpi)\n', (730, 764), True, 'import matplotlib.pyplot as plt\n'), ((943, 980), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.__init__', 'FigureCanvas.__init__', (['self', 'self.fig'], {}), '(self, self.fig)\n', (964, 980), True, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n'), ((1021, 1099), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.setSizePolicy', 'FigureCanvas.setSizePolicy', (['self', 'QSizePolicy.Expanding', 'QSizePolicy.Expanding'], {}), '(self, QSizePolicy.Expanding, QSizePolicy.Expanding)\n', (1047, 1099), True, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n'), ((1178, 1211), 'matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg.updateGeometry', 'FigureCanvas.updateGeometry', (['self'], {}), '(self)\n', (1205, 1211), True, 'from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\n'), ((4054, 4147), 'numpy.array', 'np.array', (["(gs.outCordinateall['Cx'], gs.outCordinateall['Cy'], gs.outCordinateall['Cz'])"], {}), "((gs.outCordinateall['Cx'], gs.outCordinateall['Cy'], gs.\n outCordinateall['Cz']))\n", (4062, 4147), True, 'import numpy as np\n'), ((4160, 4253), 'numpy.array', 'np.array', (["(gs.outCordinateall['Dx'], gs.outCordinateall['Dy'], gs.outCordinateall['Dz'])"], {}), "((gs.outCordinateall['Dx'], gs.outCordinateall['Dy'], gs.\n outCordinateall['Dz']))\n", (4168, 4253), True, 'import numpy as np\n'), ((4267, 4363), 'numpy.array', 'np.array', (["(gs.outCordinateall['Cx2'], gs.outCordinateall['Cy2'], gs.outCordinateall[\n 'Cz2'])"], {}), "((gs.outCordinateall['Cx2'], gs.outCordinateall['Cy2'], gs.\n outCordinateall['Cz2']))\n", (4275, 4363), True, 'import numpy as np\n'), ((4377, 4473), 'numpy.array', 'np.array', (["(gs.outCordinateall['Dx2'], gs.outCordinateall['Dy2'], gs.outCordinateall[\n 'Dz2'])"], {}), "((gs.outCordinateall['Dx2'], gs.outCordinateall['Dy2'], gs.\n outCordinateall['Dz2']))\n", (4385, 4473), True, 'import numpy as np\n'), ((4921, 4945), 'numpy.ones', 'np.ones', (['(10, 6, number)'], {}), '((10, 6, number))\n', (4928, 4945), True, 'import numpy as np\n'), ((5362, 5385), 'numpy.max', 'np.max', (['data[0]'], {'axis': '(1)'}), '(data[0], axis=1)\n', (5368, 5385), True, 'import numpy as np\n'), ((5412, 5435), 'numpy.max', 'np.max', (['data[0]'], {'axis': '(1)'}), '(data[0], axis=1)\n', (5418, 5435), True, 'import numpy as np\n'), ((6864, 6940), 'numpy.array', 'np.array', (['[[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, a, b], [0, 0, -0.0001, zback]]'], {}), '([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, a, b], [0, 0, -0.0001, zback]])\n', (6872, 6940), True, 'import numpy as np\n'), ((7253, 7272), 'mpl_toolkits.mplot3d.axes3d.Axes3D', 'p3.Axes3D', (['self.fig'], {}), '(self.fig)\n', (7262, 7272), True, 'import mpl_toolkits.mplot3d.axes3d as p3\n'), ((9049, 9068), 'mpl_toolkits.mplot3d.axes3d.Axes3D', 'p3.Axes3D', (['self.fig'], {}), '(self.fig)\n', (9058, 9068), True, 'import mpl_toolkits.mplot3d.axes3d as p3\n'), ((10875, 10901), 'PyQt5.QtWidgets.QMainWindow.__init__', 'QMainWindow.__init__', (['self'], {}), '(self)\n', (10895, 10901), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((11055, 11068), 'PyQt5.QtWidgets.QWidget', 'QWidget', (['self'], {}), '(self)\n', (11062, 11068), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((11092, 11105), 'PyQt5.QtWidgets.QWidget', 'QWidget', (['self'], {}), '(self)\n', (11099, 11105), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((11129, 11142), 'PyQt5.QtWidgets.QWidget', 'QWidget', (['self'], {}), '(self)\n', (11136, 11142), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((11166, 11179), 'PyQt5.QtWidgets.QWidget', 'QWidget', (['self'], {}), '(self)\n', (11173, 11179), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((11853, 11878), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', (['self.widget1'], {}), '(self.widget1)\n', (11864, 11878), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((11892, 11917), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', (['self.widget2'], {}), '(self.widget2)\n', (11903, 11917), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((11931, 11956), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', (['self.widget3'], {}), '(self.widget3)\n', (11942, 11956), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((11970, 11995), 'PyQt5.QtWidgets.QVBoxLayout', 'QVBoxLayout', (['self.widget4'], {}), '(self.widget4)\n', (11981, 11995), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((12403, 12959), 'PyQt5.QtWidgets.QMessageBox.about', 'QMessageBox.about', (['self', '"""About"""', '"""embedding_in_qt5.py example\n Copyright 2015 BoxControL\n\n This program is a simple example of a Qt5 application embedding matplotlib\n canvases. It is base on example from matplolib documentation, and initially was\n developed from <NAME> and <NAME>.\n\n http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html\n\n It may be used and modified with no restriction; raw copies as well as\n modified versions may be distributed without limitation.\n """'], {}), '(self, \'About\',\n """embedding_in_qt5.py example\n Copyright 2015 BoxControL\n\n This program is a simple example of a Qt5 application embedding matplotlib\n canvases. It is base on example from matplolib documentation, and initially was\n developed from <NAME> and <NAME>.\n\n http://matplotlib.org/examples/user_interfaces/embedding_in_qt4.html\n\n It may be used and modified with no restriction; raw copies as well as\n modified versions may be distributed without limitation.\n """\n )\n', (12420, 12959), False, 'from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QTabWidget\n'), ((3693, 3718), 'numpy.array', 'np.array', (['([gs.A] * number)'], {}), '([gs.A] * number)\n', (3701, 3718), True, 'import numpy as np\n'), ((3737, 3762), 'numpy.array', 'np.array', (['([gs.B] * number)'], {}), '([gs.B] * number)\n', (3745, 3762), True, 'import numpy as np\n'), ((3781, 3806), 'numpy.array', 'np.array', (['([gs.E] * number)'], {}), '([gs.E] * number)\n', (3789, 3806), True, 'import numpy as np\n'), ((3825, 3850), 'numpy.array', 'np.array', (['([gs.F] * number)'], {}), '([gs.F] * number)\n', (3833, 3850), True, 'import numpy as np\n'), ((3870, 3896), 'numpy.array', 'np.array', (['([gs.A2] * number)'], {}), '([gs.A2] * number)\n', (3878, 3896), True, 'import numpy as np\n'), ((3916, 3942), 'numpy.array', 'np.array', (['([gs.B2] * number)'], {}), '([gs.B2] * number)\n', (3924, 3942), True, 'import numpy as np\n'), ((3962, 3988), 'numpy.array', 'np.array', (['([gs.E2] * number)'], {}), '([gs.E2] * number)\n', (3970, 3988), True, 'import numpy as np\n'), ((4008, 4034), 'numpy.array', 'np.array', (['([gs.F2] * number)'], {}), '([gs.F2] * number)\n', (4016, 4034), True, 'import numpy as np\n'), ((5499, 5519), 'numpy.max', 'np.max', (['item'], {'axis': '(1)'}), '(item, axis=1)\n', (5505, 5519), True, 'import numpy as np\n'), ((5553, 5573), 'numpy.min', 'np.min', (['item'], {'axis': '(1)'}), '(item, axis=1)\n', (5559, 5573), True, 'import numpy as np\n'), ((6453, 6487), 'math.atan', 'math.atan', (['(abScale[0] / abScale[1])'], {}), '(abScale[0] / abScale[1])\n', (6462, 6487), False, 'import math\n'), ((6503, 6517), 'numpy.sign', 'np.sign', (['ab[1]'], {}), '(ab[1])\n', (6510, 6517), True, 'import numpy as np\n'), ((6551, 6595), 'math.sqrt', 'math.sqrt', (['(abScale[0] ** 2 + abScale[1] ** 2)'], {}), '(abScale[0] ** 2 + abScale[1] ** 2)\n', (6560, 6595), False, 'import math\n')]
from IPython import embed import numpy as np from astropy import stats def sigma_clip(cube, **kwargs): """ Args: cube: **kwargs: Returns: """ out = np.ma.empty_like(cube) for row_index in range(cube.shape[1]): out[:, row_index, :] = stats.sigma_clip(cube[:, row_index, :], axis=0, masked=True, **kwargs) return out def sigma_clipped_stats(cube, **kwargs): """ Args: cube: **kwargs: Returns: """ number_rows = cube.shape[1] frame_shape = cube.shape[1:] mean = np.empty(frame_shape) median = np.empty(frame_shape) std = np.empty(frame_shape) for row_index in range(number_rows[:2]): row_stats = stats.sigma_clipped_stats(cube[:, row_index, :], axis=0, **kwargs) mean[:, row_index, :], median[:, row_index, :], std[:, row_index, :] = row_stats return mean, median, std
[ "astropy.stats.sigma_clipped_stats", "numpy.empty", "numpy.ma.empty_like", "astropy.stats.sigma_clip" ]
[((190, 212), 'numpy.ma.empty_like', 'np.ma.empty_like', (['cube'], {}), '(cube)\n', (206, 212), True, 'import numpy as np\n'), ((568, 589), 'numpy.empty', 'np.empty', (['frame_shape'], {}), '(frame_shape)\n', (576, 589), True, 'import numpy as np\n'), ((603, 624), 'numpy.empty', 'np.empty', (['frame_shape'], {}), '(frame_shape)\n', (611, 624), True, 'import numpy as np\n'), ((635, 656), 'numpy.empty', 'np.empty', (['frame_shape'], {}), '(frame_shape)\n', (643, 656), True, 'import numpy as np\n'), ((288, 358), 'astropy.stats.sigma_clip', 'stats.sigma_clip', (['cube[:, row_index, :]'], {'axis': '(0)', 'masked': '(True)'}), '(cube[:, row_index, :], axis=0, masked=True, **kwargs)\n', (304, 358), False, 'from astropy import stats\n'), ((723, 789), 'astropy.stats.sigma_clipped_stats', 'stats.sigma_clipped_stats', (['cube[:, row_index, :]'], {'axis': '(0)'}), '(cube[:, row_index, :], axis=0, **kwargs)\n', (748, 789), False, 'from astropy import stats\n')]
from __future__ import division from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, DirectSolver, BoundsEnforceLS from openmdao.api import ScipyOptimizeDriver, ExplicitComponent, ImplicitComponent import numpy as np import scipy.sparse as sp import sys, os sys.path.insert(0,os.getcwd()) from openconcept.components.ducts import ImplicitCompressibleDuct from openconcept.utilities.math.integrals import Integrator from openconcept.utilities.math.derivatives import FirstDerivative from openconcept.utilities.math import AddSubtractComp, ElementMultiplyDivideComp, VectorConcatenateComp, VectorSplitComp from openconcept.analysis.atmospherics.compute_atmos_props import ComputeAtmosphericProperties """Analysis routines for simulating thermal management of aircraft components""" class ThermalComponentWithMass(ExplicitComponent): """ Computes thermal residual of a component with heating, cooling, and thermal mass Inputs ------ q_in : float Heat generated by the component (vector, W) q_out : float Heat to waste stream (vector, W) mass : float Thermal mass (scalar, kg) Outputs ------- dTdt : float First derivative of temperature (vector, K/s) Options ------- specific_heat : float Specific heat capacity of the object in J / kg / K (default 921 = aluminum) num_nodes : float The number of analysis points to run """ def initialize(self): self.options.declare('num_nodes', default=1) self.options.declare('specific_heat', default=921, desc='Specific heat in J/kg/K - default 921 for aluminum') def setup(self): nn_tot = self.options['num_nodes'] arange = np.arange(0, nn_tot) self.add_input('q_in', units='W', shape=(nn_tot,)) self.add_input('q_out', units='W', shape=(nn_tot,)) self.add_input('mass', units='kg') self.add_output('dTdt', units='K/s', shape=(nn_tot,)) self.declare_partials(['dTdt'], ['q_in'], rows=arange, cols=arange) self.declare_partials(['dTdt'], ['q_out'], rows=arange, cols=arange) self.declare_partials(['dTdt'], ['mass'], rows=arange, cols=np.zeros((nn_tot,))) def compute(self, inputs, outputs): spec_heat = self.options['specific_heat'] outputs['dTdt'] = (inputs['q_in'] - inputs['q_out']) / inputs['mass'] / spec_heat def compute_partials(self, inputs, J): nn_tot = self.options['num_nodes'] spec_heat = self.options['specific_heat'] J['dTdt','mass'] = - (inputs['q_in'] - inputs['q_out']) / inputs['mass']**2 / spec_heat J['dTdt','q_in'] = 1 / inputs['mass'] / spec_heat J['dTdt','q_out'] = - 1 / inputs['mass'] / spec_heat class CoolantReservoirRate(ExplicitComponent): """ Computes dT/dt of a coolant reservoir based on inflow and current temps and flow rate Inputs ------ T_in : float Coolant stream in (vector, K) T_out : float Temperature of the reservoir (vector, K) mass : float Total quantity of coolant (scalar, kg) mdot_coolant : float Mass flow rate of the coolant (vector, kg/s) Outputs ------- dTdt : float First derivative of temperature (vector, K/s) Options ------- num_nodes : float The number of analysis points to run """ def initialize(self): self.options.declare('num_nodes', default=1) def setup(self): nn_tot = self.options['num_nodes'] arange = np.arange(0, nn_tot) self.add_input('T_in', units='K', shape=(nn_tot,)) self.add_input('T_out', units='K', shape=(nn_tot,)) self.add_input('mdot_coolant', units='kg/s', shape=(nn_tot,)) self.add_input('mass', units='kg') self.add_output('dTdt', units='K/s', shape=(nn_tot,)) self.declare_partials(['dTdt'], ['T_in','T_out','mdot_coolant'], rows=arange, cols=arange) self.declare_partials(['dTdt'], ['mass'], rows=arange, cols=np.zeros((nn_tot,))) def compute(self, inputs, outputs): outputs['dTdt'] = inputs['mdot_coolant'] / inputs['mass'] * (inputs['T_in'] - inputs['T_out']) def compute_partials(self, inputs, J): J['dTdt','mass'] = - inputs['mdot_coolant'] / inputs['mass']**2 * (inputs['T_in'] - inputs['T_out']) J['dTdt','mdot_coolant'] = 1 / inputs['mass'] * (inputs['T_in'] - inputs['T_out']) J['dTdt','T_in'] = inputs['mdot_coolant'] / inputs['mass'] J['dTdt','T_out'] = - inputs['mdot_coolant'] / inputs['mass'] class ThermalComponentMassless(ImplicitComponent): """ Computes thermal residual of a component with heating, cooling, and thermal mass Inputs ------ q_in : float Heat generated by the component (vector, W) q_out : float Heat to waste stream (vector, W) Outputs ------- T_object : float Object temperature (vector, K/s) Options ------- num_nodes : float The number of analysis points to run """ def initialize(self): self.options.declare('num_nodes',default=1) def setup(self): nn_tot = self.options['num_nodes'] arange = np.arange(0, nn_tot) self.add_input('q_in', units='W', shape=(nn_tot,)) self.add_input('q_out', units='W', shape=(nn_tot,)) self.add_output('T_object', units='K', shape=(nn_tot,)) self.declare_partials(['T_object'], ['q_in'], rows=arange, cols=arange, val=np.ones((nn_tot,))) self.declare_partials(['T_object'], ['q_out'], rows=arange, cols=arange, val=-np.ones((nn_tot,))) def apply_nonlinear(self, inputs, outputs, residuals): residuals['T_object'] = inputs['q_in'] - inputs['q_out'] class ConstantSurfaceTemperatureColdPlate_NTU(ExplicitComponent): """ Computes heat rejection to fluid stream of a microchannel cold plate with uniform temperature Inputs ------ T_in : float Coolant inlet temperature (vector, K) T_surface : float Temperature of the cold plate (vector, K) mdot_coolant : float Mass flow rate of the coolant (vector, kg/s) channel_length : float Length of each microchannel (scalar, m) channel_width : float Width of each microchannel (scalar, m) channel_height : float Height of each microchannel (scalar, m) n_parallel : float Number of fluid channels (scalar, dimensionless) Outputs ------- q : float Heat transfer rate from the plate to the fluid (vector, W) T_out : float Outlet fluid temperature (vector, K) Options ------- num_nodes : float The number of analysis points to run fluid_rho : float Coolant density in kg/m**3 (default 0.997, water) fluid_k : float Thermal conductivity of the fluid (W/m/K) (default 0.405, glycol/water) nusselt : float Hydraulic diameter Nusselt number of the coolant in the channels (default 7.54 for constant temperature infinite parallel plate) specific_heat : float Specific heat of the coolant (J/kg/K) (default 3801, glycol/water) """ def initialize(self): self.options.declare('num_nodes', default=1, desc='Number of analysis points') self.options.declare('fluid_rho', default=997.0, desc='Fluid density in kg/m3') self.options.declare('fluid_k', default=0.405, desc='Thermal conductivity of the fluid in W / mK') self.options.declare('nusselt', default=7.54, desc='Hydraulic diameter Nusselt number') self.options.declare('specific_heat', default=3801, desc='Specific heat in J/kg/K') def setup(self): nn_tot = self.options['num_nodes'] arange = np.arange(0, nn_tot) self.add_input('T_in', units='K', shape=(nn_tot,)) self.add_input('T_surface', units='K', shape=(nn_tot,)) self.add_input('channel_width', units='m') self.add_input('channel_height', units='m') self.add_input('channel_length', units='m') self.add_input('n_parallel') self.add_input('mdot_coolant', units='kg/s', shape=(nn_tot,)) self.add_output('q', units='W', shape=(nn_tot,)) self.add_output('T_out', units='K', shape=(nn_tot,)) self.declare_partials(['q','T_out'], ['T_in','T_surface','mdot_coolant'], method='cs') self.declare_partials(['q','T_out'], ['channel_width','channel_height','channel_length','n_parallel'], method='cs') def compute(self, inputs, outputs): Ts = inputs['T_surface'] Ti = inputs['T_in'] Cmin = inputs['mdot_coolant'] * self.options['specific_heat'] #cross_section_area = inputs['channel_width'] * inputs['channel_height'] * inputs['n_parallel'] #flow_rate = inputs['mdot_coolant'] / self.options['rho'] / cross_section_area # m/s surface_area = 2 * (inputs['channel_width']*inputs['channel_length'] + inputs['channel_height'] * inputs['channel_length']) * inputs['n_parallel'] d_h = 2 * inputs['channel_width'] * inputs['channel_height'] / (inputs['channel_width'] + inputs['channel_height']) h = self.options['nusselt'] * self.options['fluid_k'] / d_h ntu = surface_area * h / Cmin effectiveness = 1 - np.exp(-ntu) outputs['q'] = effectiveness * Cmin * (Ts - Ti) outputs['T_out'] = inputs['T_in'] + outputs['q'] / inputs['mdot_coolant'] / self.options['specific_heat'] class LiquidCooledComp(Group): """A component (heat producing) with thermal mass cooled by a cold plate. Inputs ------ q_in : float Heat produced by the operating component (vector, W) mdot_coolant : float Coolant mass flow rate (vector, kg/s) T_in : float Instantaneous coolant inflow temperature (vector, K) mass : float Object mass (only required in thermal mass mode) (scalar, kg) T_initial : float Initial temperature of the cold plate (only required in thermal mass mode) / object (scalar, K) duration : float Duration of mission segment, only required in unsteady mode channel_width : float Width of coolant channels (scalar, m) channel_height : float Height of coolant channels (scalar, m) channel_length : float Length of coolant channels (scalar, m) n_parallel : float Number of identical coolant channels (scalar, dimensionless) Outputs ------- T_out : float Instantaneous coolant outlet temperature (vector, K) T: float Object temperature (vector, K) Options ------- specific_heat_object : float Specific heat capacity of the object in J / kg / K (default 921 = aluminum) specific_heat_coolant : float Specific heat capacity of the coolant in J / kg / K (default 3801, glycol/water) num_nodes : int Number of analysis points to run quasi_steady : bool Whether or not to treat the component as having thermal mass """ def initialize(self): self.options.declare('specific_heat_object', default=921.0, desc='Specific heat in J/kg/K') self.options.declare('specific_heat_coolant', default=3801, desc='Specific heat in J/kg/K') self.options.declare('quasi_steady', default=False, desc='Treat the component as quasi-steady or with thermal mass') self.options.declare('num_nodes', default=1, desc='Number of quasi-steady points to runs') def setup(self): nn = self.options['num_nodes'] quasi_steady = self.options['quasi_steady'] if not quasi_steady: self.add_subsystem('base', ThermalComponentWithMass(specific_heat=self.options['specific_heat_object'], num_nodes=nn), promotes_inputs=['q_in', 'mass']) self.add_subsystem('integratetemp', Integrator(num_intervals=int((nn-1)/2), quantity_units='K', diff_units='s', method='simpson', time_setup='duration'), promotes_inputs=['duration',('q_initial','T_initial')], promotes_outputs=[('q','T'),('q_final','T_final')]) self.connect('base.dTdt','integratetemp.dqdt') else: self.add_subsystem('base', ThermalComponentMassless(num_nodes=nn), promotes_inputs=['q_in'], promotes_outputs=['T']) self.add_subsystem('hex', ConstantSurfaceTemperatureColdPlate_NTU(num_nodes=nn, specific_heat=self.options['specific_heat_coolant']), promotes_inputs=['T_in', ('T_surface','T'),'n_parallel','channel*','mdot_coolant'], promotes_outputs=['T_out']) self.connect('hex.q','base.q_out') class CoolantReservoir(Group): """A reservoir of coolant capable of buffering temperature Inputs ------ mdot_coolant : float Coolant mass flow rate (vector, kg/s) T_in : float Coolant inflow temperature (vector, K) mass : float Object mass (only required in thermal mass mode) (scalar, kg) T_initial : float Initial temperature of the coolant reservoir(only required in thermal mass mode) / object (scalar, K) duration : float Time step of each mission segment (one for each segment) (scalar, s) If a single segment is provided (by default) this variable will be called just 'dt' only required in thermal mass mode Outputs ------- T_out : float Coolant outlet temperature (vector, K) Options ------- num_nodes : int Number of analysis points to run """ def initialize(self): self.options.declare('num_nodes',default=5) def setup(self): nn = self.options['num_nodes'] self.add_subsystem('rate', CoolantReservoirRate(num_nodes=nn), promotes_inputs=['T_in', 'T_out', 'mass', 'mdot_coolant']) self.add_subsystem('integratetemp', Integrator(num_intervals=int((nn-1)/2), quantity_units='K', diff_units='s', method='simpson', time_setup='duration'), promotes_inputs=['duration',('q_initial','T_initial')], promotes_outputs=[('q','T_out'),('q_final','T_final')]) self.connect('rate.dTdt','integratetemp.dqdt') class LiquidCoolantTestGroup(Group): """A component (heat producing) with thermal mass cooled by a cold plate. """ def initialize(self): self.options.declare('num_nodes',default=11) self.options.declare('quasi_steady', default=False, desc='Treat the component as quasi-steady or with thermal mass') def setup(self): quasi_steady = self.options['quasi_steady'] nn = self.options['num_nodes'] iv = self.add_subsystem('iv',IndepVarComp(), promotes_outputs=['*']) #iv.add_output('q_in', val=10*np.concatenate([np.ones((nn,)),0.5*np.ones((nn,)),0.2*np.ones((nn,))]), units='kW') throttle_profile = np.ones((nn,)) iv.add_output('q_in',val=10*throttle_profile, units='kW') #iv.add_output('T_in', val=40*np.ones((nn_tot,)), units='degC') iv.add_output('mdot_coolant', val=0.1*np.ones((nn,)), units='kg/s') iv.add_output('rho_coolant', val=997*np.ones((nn,)),units='kg/m**3') iv.add_output('motor_mass', val=50., units='kg') iv.add_output('coolant_mass', val=10., units='kg') iv.add_output('T_motor_initial', val=15, units='degC') iv.add_output('T_res_initial', val=15.1, units='degC') iv.add_output('duration', val=800, units='s') iv.add_output('channel_width', val=1, units='mm') iv.add_output('channel_height', val=20, units='mm') iv.add_output('channel_length', val=0.2, units='m') iv.add_output('n_parallel', val=20) Ueas = np.ones((nn))*150 h = np.concatenate([np.linspace(0,25000,nn)]) iv.add_output('fltcond|Ueas', val=Ueas, units='kn' ) iv.add_output('fltcond|h', val=h, units='ft') self.add_subsystem('atmos', ComputeAtmosphericProperties(num_nodes=nn), promotes_inputs=["fltcond|h", "fltcond|Ueas"]) if not quasi_steady: lc_promotes = ['q_in',('mass','motor_mass'),'duration','channel_*','n_parallel'] else: lc_promotes = ['q_in','channel_*','n_parallel'] self.add_subsystem('component', LiquidCooledComp(num_nodes=nn, quasi_steady=quasi_steady), promotes_inputs=lc_promotes) self.add_subsystem('duct', ImplicitCompressibleDuct(num_nodes=nn)) self.connect('atmos.fltcond|p','duct.p_inf') self.connect('atmos.fltcond|T','duct.T_inf') self.connect('atmos.fltcond|Utrue','duct.Utrue') self.connect('component.T_out','duct.T_in_hot') self.connect('rho_coolant','duct.rho_hot') if quasi_steady: self.connect('duct.T_out_hot','component.T_in') self.connect('mdot_coolant',['component.mdot_coolant','duct.mdot_hot']) else: self.add_subsystem('reservoir', CoolantReservoir(num_nodes=nn), promotes_inputs=['duration',('mass','coolant_mass')]) self.connect('duct.T_out_hot','reservoir.T_in') self.connect('reservoir.T_out','component.T_in') self.connect('mdot_coolant',['component.mdot_coolant','duct.mdot_hot','reservoir.mdot_coolant']) self.connect('T_motor_initial','component.T_initial') self.connect('T_res_initial','reservoir.T_initial') if __name__ == '__main__': # run this script from the root openconcept directory like so: # python .\openconcept\components\ducts.py quasi_steady = False nn = 11 prob = Problem(LiquidCoolantTestGroup(quasi_steady=quasi_steady, num_nodes=nn)) prob.model.options['assembled_jac_type'] = 'csc' prob.model.nonlinear_solver=NewtonSolver(iprint=2) prob.model.linear_solver = DirectSolver(assemble_jac=True) prob.model.nonlinear_solver.options['solve_subsystems'] = True prob.model.nonlinear_solver.options['maxiter'] = 20 prob.model.nonlinear_solver.options['atol'] = 1e-8 prob.model.nonlinear_solver.options['rtol'] = 1e-8 prob.model.nonlinear_solver.linesearch = BoundsEnforceLS(bound_enforcement='scalar',print_bound_enforce=True) prob.setup(check=True,force_alloc_complex=True) prob.run_model() #print(prob['duct.inlet.M']) print(np.max(prob['component.T']-273.15)) print(np.max(-prob['duct.force.F_net'])) prob.check_partials(method='cs', compact_print=True) #prob.model.list_outputs(units=True, print_arrays=True) if quasi_steady: np.save('quasi_steady',prob['component.T']) # prob.run_driver() # prob.model.list_inputs(units=True) t = np.linspace(0,800,nn)/60 import matplotlib.pyplot as plt plt.figure() plt.plot(t, prob['component.T'] - 273.15) plt.xlabel('time (min)') plt.ylabel('motor temp (C)') plt.figure() plt.plot(prob['fltcond|h'], prob['component.T'] - 273.15) plt.xlabel('altitude (ft)') plt.ylabel('motor temp (C)') plt.figure() plt.plot(t, prob['duct.inlet.M']) plt.xlabel('Mach number') plt.ylabel('steady state motor temp (C)') plt.figure() plt.plot(prob['duct.inlet.M'], prob['duct.force.F_net']) plt.xlabel('M_inf') plt.ylabel('drag N') plt.figure() plt.plot(prob['duct.inlet.M'], prob['duct.mdot']/prob['atmos.fltcond|rho']/prob.get_val('atmos.fltcond|Utrue',units='m/s')/prob.get_val('duct.area_nozzle',units='m**2')) plt.xlabel('M_inf') plt.ylabel('mdot / rho / U / A_nozzle') plt.figure() plt.plot(prob['duct.inlet.M'],prob['duct.nozzle.M']) plt.xlabel('M_inf') # plt.ylabel('M_nozzle') plt.show()
[ "openconcept.components.ducts.ImplicitCompressibleDuct", "matplotlib.pyplot.ylabel", "openmdao.api.IndepVarComp", "numpy.save", "numpy.arange", "matplotlib.pyplot.xlabel", "matplotlib.pyplot.plot", "numpy.max", "numpy.exp", "numpy.linspace", "numpy.ones", "matplotlib.pyplot.show", "openconce...
[((293, 304), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (302, 304), False, 'import sys, os\n'), ((18883, 18905), 'openmdao.api.NewtonSolver', 'NewtonSolver', ([], {'iprint': '(2)'}), '(iprint=2)\n', (18895, 18905), False, 'from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, DirectSolver, BoundsEnforceLS\n'), ((18937, 18968), 'openmdao.api.DirectSolver', 'DirectSolver', ([], {'assemble_jac': '(True)'}), '(assemble_jac=True)\n', (18949, 18968), False, 'from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, DirectSolver, BoundsEnforceLS\n'), ((19247, 19316), 'openmdao.api.BoundsEnforceLS', 'BoundsEnforceLS', ([], {'bound_enforcement': '"""scalar"""', 'print_bound_enforce': '(True)'}), "(bound_enforcement='scalar', print_bound_enforce=True)\n", (19262, 19316), False, 'from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, DirectSolver, BoundsEnforceLS\n'), ((19847, 19859), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (19857, 19859), True, 'import matplotlib.pyplot as plt\n'), ((19864, 19905), 'matplotlib.pyplot.plot', 'plt.plot', (['t', "(prob['component.T'] - 273.15)"], {}), "(t, prob['component.T'] - 273.15)\n", (19872, 19905), True, 'import matplotlib.pyplot as plt\n'), ((19910, 19934), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""time (min)"""'], {}), "('time (min)')\n", (19920, 19934), True, 'import matplotlib.pyplot as plt\n'), ((19939, 19967), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""motor temp (C)"""'], {}), "('motor temp (C)')\n", (19949, 19967), True, 'import matplotlib.pyplot as plt\n'), ((19972, 19984), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (19982, 19984), True, 'import matplotlib.pyplot as plt\n'), ((19989, 20046), 'matplotlib.pyplot.plot', 'plt.plot', (["prob['fltcond|h']", "(prob['component.T'] - 273.15)"], {}), "(prob['fltcond|h'], prob['component.T'] - 273.15)\n", (19997, 20046), True, 'import matplotlib.pyplot as plt\n'), ((20051, 20078), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""altitude (ft)"""'], {}), "('altitude (ft)')\n", (20061, 20078), True, 'import matplotlib.pyplot as plt\n'), ((20083, 20111), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""motor temp (C)"""'], {}), "('motor temp (C)')\n", (20093, 20111), True, 'import matplotlib.pyplot as plt\n'), ((20116, 20128), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (20126, 20128), True, 'import matplotlib.pyplot as plt\n'), ((20133, 20166), 'matplotlib.pyplot.plot', 'plt.plot', (['t', "prob['duct.inlet.M']"], {}), "(t, prob['duct.inlet.M'])\n", (20141, 20166), True, 'import matplotlib.pyplot as plt\n'), ((20171, 20196), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Mach number"""'], {}), "('Mach number')\n", (20181, 20196), True, 'import matplotlib.pyplot as plt\n'), ((20201, 20242), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""steady state motor temp (C)"""'], {}), "('steady state motor temp (C)')\n", (20211, 20242), True, 'import matplotlib.pyplot as plt\n'), ((20247, 20259), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (20257, 20259), True, 'import matplotlib.pyplot as plt\n'), ((20264, 20320), 'matplotlib.pyplot.plot', 'plt.plot', (["prob['duct.inlet.M']", "prob['duct.force.F_net']"], {}), "(prob['duct.inlet.M'], prob['duct.force.F_net'])\n", (20272, 20320), True, 'import matplotlib.pyplot as plt\n'), ((20325, 20344), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""M_inf"""'], {}), "('M_inf')\n", (20335, 20344), True, 'import matplotlib.pyplot as plt\n'), ((20349, 20369), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""drag N"""'], {}), "('drag N')\n", (20359, 20369), True, 'import matplotlib.pyplot as plt\n'), ((20374, 20386), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (20384, 20386), True, 'import matplotlib.pyplot as plt\n'), ((20565, 20584), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""M_inf"""'], {}), "('M_inf')\n", (20575, 20584), True, 'import matplotlib.pyplot as plt\n'), ((20589, 20628), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""mdot / rho / U / A_nozzle"""'], {}), "('mdot / rho / U / A_nozzle')\n", (20599, 20628), True, 'import matplotlib.pyplot as plt\n'), ((20633, 20645), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (20643, 20645), True, 'import matplotlib.pyplot as plt\n'), ((20650, 20703), 'matplotlib.pyplot.plot', 'plt.plot', (["prob['duct.inlet.M']", "prob['duct.nozzle.M']"], {}), "(prob['duct.inlet.M'], prob['duct.nozzle.M'])\n", (20658, 20703), True, 'import matplotlib.pyplot as plt\n'), ((20707, 20726), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""M_inf"""'], {}), "('M_inf')\n", (20717, 20726), True, 'import matplotlib.pyplot as plt\n'), ((20760, 20770), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (20768, 20770), True, 'import matplotlib.pyplot as plt\n'), ((1732, 1752), 'numpy.arange', 'np.arange', (['(0)', 'nn_tot'], {}), '(0, nn_tot)\n', (1741, 1752), True, 'import numpy as np\n'), ((3545, 3565), 'numpy.arange', 'np.arange', (['(0)', 'nn_tot'], {}), '(0, nn_tot)\n', (3554, 3565), True, 'import numpy as np\n'), ((5218, 5238), 'numpy.arange', 'np.arange', (['(0)', 'nn_tot'], {}), '(0, nn_tot)\n', (5227, 5238), True, 'import numpy as np\n'), ((7768, 7788), 'numpy.arange', 'np.arange', (['(0)', 'nn_tot'], {}), '(0, nn_tot)\n', (7777, 7788), True, 'import numpy as np\n'), ((15712, 15726), 'numpy.ones', 'np.ones', (['(nn,)'], {}), '((nn,))\n', (15719, 15726), True, 'import numpy as np\n'), ((19434, 19470), 'numpy.max', 'np.max', (["(prob['component.T'] - 273.15)"], {}), "(prob['component.T'] - 273.15)\n", (19440, 19470), True, 'import numpy as np\n'), ((19480, 19513), 'numpy.max', 'np.max', (["(-prob['duct.force.F_net'])"], {}), "(-prob['duct.force.F_net'])\n", (19486, 19513), True, 'import numpy as np\n'), ((19663, 19707), 'numpy.save', 'np.save', (['"""quasi_steady"""', "prob['component.T']"], {}), "('quasi_steady', prob['component.T'])\n", (19670, 19707), True, 'import numpy as np\n'), ((19781, 19804), 'numpy.linspace', 'np.linspace', (['(0)', '(800)', 'nn'], {}), '(0, 800, nn)\n', (19792, 19804), True, 'import numpy as np\n'), ((9327, 9339), 'numpy.exp', 'np.exp', (['(-ntu)'], {}), '(-ntu)\n', (9333, 9339), True, 'import numpy as np\n'), ((15523, 15537), 'openmdao.api.IndepVarComp', 'IndepVarComp', ([], {}), '()\n', (15535, 15537), False, 'from openmdao.api import Problem, Group, IndepVarComp, NewtonSolver, DirectSolver, BoundsEnforceLS\n'), ((16551, 16562), 'numpy.ones', 'np.ones', (['nn'], {}), '(nn)\n', (16558, 16562), True, 'import numpy as np\n'), ((16803, 16845), 'openconcept.analysis.atmospherics.compute_atmos_props.ComputeAtmosphericProperties', 'ComputeAtmosphericProperties', ([], {'num_nodes': 'nn'}), '(num_nodes=nn)\n', (16831, 16845), False, 'from openconcept.analysis.atmospherics.compute_atmos_props import ComputeAtmosphericProperties\n'), ((17468, 17506), 'openconcept.components.ducts.ImplicitCompressibleDuct', 'ImplicitCompressibleDuct', ([], {'num_nodes': 'nn'}), '(num_nodes=nn)\n', (17492, 17506), False, 'from openconcept.components.ducts import ImplicitCompressibleDuct\n'), ((2200, 2219), 'numpy.zeros', 'np.zeros', (['(nn_tot,)'], {}), '((nn_tot,))\n', (2208, 2219), True, 'import numpy as np\n'), ((4029, 4048), 'numpy.zeros', 'np.zeros', (['(nn_tot,)'], {}), '((nn_tot,))\n', (4037, 4048), True, 'import numpy as np\n'), ((5508, 5526), 'numpy.ones', 'np.ones', (['(nn_tot,)'], {}), '((nn_tot,))\n', (5515, 5526), True, 'import numpy as np\n'), ((16597, 16622), 'numpy.linspace', 'np.linspace', (['(0)', '(25000)', 'nn'], {}), '(0, 25000, nn)\n', (16608, 16622), True, 'import numpy as np\n'), ((5614, 5632), 'numpy.ones', 'np.ones', (['(nn_tot,)'], {}), '((nn_tot,))\n', (5621, 5632), True, 'import numpy as np\n'), ((15911, 15925), 'numpy.ones', 'np.ones', (['(nn,)'], {}), '((nn,))\n', (15918, 15925), True, 'import numpy as np\n'), ((15986, 16000), 'numpy.ones', 'np.ones', (['(nn,)'], {}), '((nn,))\n', (15993, 16000), True, 'import numpy as np\n')]
""" ## Pandas DataFrane UltraQuick Tutorial ### DataFrames * central data structure in pandas API, a 2D mutable-size heterogenous tabular data with labeled axes. A dict like container for Series objects. * similar to an in-memory spreadsheet """ ## import NumPy and Pandas module import numpy as np import pandas as pd """ ## creating a dataframe * following code cell creates a simple DataFrame with 10 cells: 5 rows, 2 columns ('temperature' and `'activity') 'pd.DataFrame' class to instantiate DataFrame, takes 2 args where 1st provides data & 2nd identifies names of 2 columns """ my_dataset = [[0,3], [5,4], [10,5], [15,6], [20,7]] my_columns = ['temperature', 'activity'] my_df = pd.DataFrame( data=np.array(my_dataset), columns=my_columns, ) print(my_df) ## adding new column to existing DataFrame, following creates 3rd column named 'adjusted' my_df['adjusted'] = my_df['activity'] + 2 print(my_df) ## Pandas provide multiple ways to isolate specific rows, columns, slices or cells in DataFrame print("Rows #0, #1, #2:") print(my_df.head(3), '\n') print("Row #2:") print(my_df.iloc[[2]], '\n') print("Rows #1, #2, #3:") print(my_df[1:4], '\n') print("Column 'temperature:'") print(my_df['temperature']) """ Task.1 Create a DataFrame * create 3x4 DataFrame with columns 'monday', 'tuesday', 'wednesday', 'thursday' > populate each of 12 cells with random int between 0 & 50 * output entire DataFrame, value in cell of row#1 of 'monday' column * create 5th column named 'friday' populated by row sums of 'tuesday' & 'wednesday' """ my_columns = ['monday', 'tuesday', 'wednesday', 'thursday'] random_ints_0_to_50 = np.random.randint(low=0, high=51, size=(3, 4)) my_df = pd.DataFrame(data=random_ints_0_to_50, columns=my_columns) print(my_df) print("\nSecond row of the 'monday' column: %d\n" % my_df['monday'][1]) my_df['friday'] = my_df['tuesday'] + my_df['wednesday'] print(my_df) """ Task.2 Copying a DataFrame Pandas allow 2 ways to duplicate DataFrame: * 'Referencing', assigning to new dataframe with changes reflected back * 'Copying', with 'pd.DataFrame.copy' creating independent copy """ # reference ref_my_df = my_df print("Starting value of my_df: %d | ref_my_df: %d" % (my_df['monday'][1], ref_my_df['monday'][1])) my_df.at[1, 'monday'] = my_df['monday'][1] + 1 print("Updated value of my_df: %d | ref_my_df: %d" % (my_df['monday'][1], ref_my_df['monday'][1])) # copying copy_my_df = my_df.copy() print("Starting value of my_df: %d | copy_my_df: %d" % (my_df['monday'][1], copy_my_df['monday'][1])) my_df.at[1, 'monday'] = my_df['monday'][1] + 1 print("Updated value of my_df: %d | copy_my_df: %d" % (my_df['monday'][1], copy_my_df['monday'][1]))
[ "pandas.DataFrame", "numpy.array", "numpy.random.randint" ]
[((1650, 1696), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(51)', 'size': '(3, 4)'}), '(low=0, high=51, size=(3, 4))\n', (1667, 1696), True, 'import numpy as np\n'), ((1706, 1764), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': 'random_ints_0_to_50', 'columns': 'my_columns'}), '(data=random_ints_0_to_50, columns=my_columns)\n', (1718, 1764), True, 'import pandas as pd\n'), ((716, 736), 'numpy.array', 'np.array', (['my_dataset'], {}), '(my_dataset)\n', (724, 736), True, 'import numpy as np\n')]
import numpy as np from calciumflexanalysis import calcium_flex as cal from collections import defaultdict import pandas as pd import matplotlib.pyplot as plt from datetime import date import copy class CaFlexGroup: """Class used for the analysis of multiple Calcium Flex well plates. :param caflexplates: List of caflexplates to combine, generated from CaFlexPlate class :type caflexplates: list of calciumflexanalysis.calcium_flex.CaFlexPlates """ def __init__(self, caflexplates = []): self.caflexplates = caflexplates self.grouplist = ['Protein', 'Type', 'Compound', 'Concentration', 'Concentration Units'] self.titles = {} self.plate_maps = {} self.data = {'ratio':{}} inject_list = [] # iterate through each plate and update attributes using predefined caflexanalysis methods for key, val in enumerate(self.caflexplates): # titles (nice ref for the user) self.titles["plate_{}".format(key+1)] = val.title # update processed data w/ ratios self.data['ratio']["plate_{}".format(key+1)] = val.processed_data['ratio'] # dictionary of plate maps for each plate self.plate_maps["plate_{}".format(key+1)] = val.plate_map # append list with injection times for each plate inject_list.append(val.inject) # mean inject across all plates (this might be changed) self.inject = np.array(inject_list).mean() def visualise_plates(self, share_y, export = False, title = "", colormap = 'Dark2_r', colorby = 'Type', labelby = 'Type', dpi = 200): """Returns color-coded and labelled plots of the data collected for each well of each well plate. :param share_y: 'True' sets y axis the same for all plots :type share_y: bool :param export: If 'True' a .png file of the figure is saved, default = False :type export: bool :param title: Sets the title of the figure, optional :type title: str :param colormap: Sets the colormap for the color-coding, default = 'Dark2_r' :type colormap: str :param colorby: Chooses the parameter to color code by, for example 'Type', 'Contents', 'Concentration', 'Compound', 'Protein', 'Concentration Units', default = 'Type' :type colorby: str :param labelby: Chooses the parameter to label code by, for example 'Type', 'Contents', 'Concentration', 'Compound', 'Protein', 'Concentration Units', default = 'Type' :type labelby: str :param dpi: Size of the figure, default = 200 :type dpi: int :return: Figure of plotted data for each well of the well plate described in plate_map_file :rtype: figure """ plates = self.caflexplates for key, val in enumerate(plates): if title == "": Title = "Plate {}\n{}".format(key+1, val.title) else: Title = "Plate {}\n{}".format(key+1, title) val.visualise_assay(share_y, export, title, colormap, colorby, labelby, dpi) def see_plates(self, title = "", export = False, colormap = 'Paired', colorby = 'Type', labelby = 'Type', dpi = 100): """Returns a visual representation of each plate map. The label and colour for each well can be customised to be a variable, for example 'Compound', 'Protein', 'Concentration', 'Concentration Units', 'Contents' or 'Type'. The size of the plate map used to generate the figure can be either 6, 12, 24, 48, 96 or 384. :param size: Size of platemap, 6, 12, 24, 48, 96 or 384, default = 96 :type size: int :param export: If 'True' a .png file of the figure is saved, default = False :type export: bool :param title: Sets the title of the figure, optional :type title: str :param colormap: Sets the colormap for the color-coding, default = 'Paired' :type colormap: str :param colorby: Chooses the parameter to color code by, for example 'Type', 'Contents', 'Concentration', 'Compound', 'Protein', 'Concentration Units', default = 'Type' :type colorby: str :param labelby: Chooses the parameter to label code by, for example 'Type', 'Contents', 'Concentration', 'Compound', 'Protein', 'Concentration Units', default = 'Type' :type labelby: str :param dpi: Size of the figure, default = 150 :type dpi: int :return: Visual representation of the plate map. :rtype: figure """ plates = self.caflexplates for key, val in enumerate(plates): if title == "": Title = "Plate {}\n{}".format(key+1, val.title) else: Title = "Plate {}\n{}".format(key+1, title) try: val.see_plate(Title, export, colormap, colorby, labelby, dpi) except: print("Check plate {}".format(key+1)) def baseline_correct(self): """Baseline corrects 'ratio' data for each well using the pre-injection time points.""" self.data['baseline_corrected'] = {} for key, val in enumerate(self.caflexplates): try: val.baseline_correct() print("Plate {}".format(key+1)) self.data['baseline_corrected']["plate_{}".format(key+1)] = val.processed_data['baseline_corrected'] except: print("Baseline correction for plate {} failed".format(key+1)) def get_window(self, data_type): """Finds the lowest overall mean gradient for across the ten time point window post injection for the plates :param data_type: Data series to calculate plateau, either 'ratio' or 'baseline_corrected' :type data_type: str :return: Tuple containing start and end index of plateau window :rtype: (int, int) """ plates = self.caflexplates gradients = {} for key, val in enumerate(plates): g = val.get_gradients(data_type) # keys for each plate are numbered by key this time - easier for unpacking gradients[key] = g # collect gradients for each window in each plate into single dictionary using default dict windows = defaultdict(list) for key, val in gradients.items(): for k, v in val.items(): # unpack dictionary of dictionaries windows[k].append(v) # where multiple plates have the same window, the resulting dict value will be a list of those gradients # take means of each window mean_windows = {} for key, val in windows.items(): mean_windows[key] = np.array(val).mean() # get minimum gradient index window across all plates and update self.window self.window = (min(mean_windows, key = mean_windows.get)) # update windows for each plate for key, val in enumerate(plates): val.window = self.window return self.window def def_window(self, time, data_type): """Manually sets each plateau window. :param time: Time point at start of window :type time: int :param data_type: Data to set window on, either 'ratio' or 'baseline_corrected' :type data_type: str :return: Tuple containing start and end index of plateau window :rtype: (int, int) """ plates = self.caflexplates temp = [] for key, val in enumerate(plates): val.def_window(time, data_type) temp.append(val.window) if all(x == temp[0] for x in temp) == True: self.window = temp[0] print("all windows equal, self.window updated") return self.window else: raise ValueError("Time points are not equal") def group_data(self, data_type): """Groups data from each plate of desired type (either ratio or baseline_corrected) into single dataframe. :param data_type: Data to be groupe, either 'ratio' or 'baseline_corrected' :type data_type: str :return: Dictionary of dataframes :rtype: {str:pandas.DataFrame, str:pandas.DataFrame} """ plates = self.caflexplates group_list = self.caflexplates data_list = [] # collect all data in list, then concatenate dfs, take means for each condition time_list = [] # same for time (sem not required) # get data for each plate in plates_list for key, val in enumerate(plates): plate_map = val.plate_map # extract data, combine with the plate's plate map, append data_list mapped = plate_map.fillna('none').join(val.processed_data[data_type]['data']) data_list.append(mapped) # repeat for time: for key, val in enumerate(plates): plate_map = val.plate_map # extract data, combine with the plate's plate map, append data_list mapped = plate_map.fillna('none').join(val.processed_data[data_type]['time']) time_list.append(mapped) # concat data and time - all data for every well now in one df for data and time all_data = pd.concat(data_list, ignore_index = True) all_time = pd.concat(time_list, ignore_index = True) self.data[data_type]['grouped'] = {'data':all_data, 'time': all_time} print("self.data updated. See self.data[{}]['grouped']".format(data_type)) def plot_conditions(self, data_type, plate_number = True, activator = " ", show_window = False, dpi = 120, title = "", error = False, control = ['control'], cmap = "winter_r", window_color = 'hotpink', proteins = [], compounds = [], marker = 'o', unique_markers = False, marker_list = ["o", "^", "s", "D", "p", "*", "v"], show_control = True): """Plots each mean condition versus time, for either each plate or over all plates, for each compound and protein. If no title is desired, set title to " ". :param plate_number: If True, plate number is added to each plot title, default = True :type plate_number: bool :param data_type: Data to be plotted, either 'ratio' or 'baseline_corrected' :type data_type: str :param show_window: If 'True', shows the window from which the plateau for each condition is calculated, default = False :type show_window: bool :param dpi: Size of figure, default = 120 :type dpi: int :param title: Title of plot ADD LIST OF TITLES? :type title: str :param error: If True, plots error bars for each mean condition, default = False :type error: bool :param control: If True, plots control data, default = True :type control: bool :param cmap: Colormap to use as the source of plot colors :type cmap: str :param window_color: Color of the plateau window, default = 'hotpink' :type window_color: str :param marker: Marker type, default = '-o' :type marker: str :param unique_markers: If True, plots each condition as a black line with a unique marker, default = False :type unique_markers: bool :param marker_list: List of marker symbols to use when unique_markers = True, default = ["o", "^", "s", "D", "p", "*", "v"] :type marker_list: [str] :return: Figure displaying each mean condition versus time :rtype: fig """ grouplist = self.grouplist for key, val in enumerate(self.caflexplates): try: # sort titles if plate_number == True: # show if title == "": Title = "Plate {}\n{}".format(key+1, val.title) else: Title = "Plate {}\n{}".format(key+1, title) else: if title == "": Title = val.title val.plot_conditions(data_type, activator, show_window, dpi, Title, error, control, cmap, window_color, proteins, compounds, marker, unique_markers, marker_list, show_control) except: print("Plate {} plot failed".format(key+1)) def amplitude(self, data_type): """Calculates response amplitude for each condition, for each plate. Don't worry about specifying whether you want to collate data yet - it'll do both. :param data_type: Data to use to calculate amplitudes, either 'ratio' or 'baseline_corrected' :type data_type: str """ for key, val in enumerate(self.caflexplates): try: val.amplitude(data_type) print("self.processed_data['plateau']['data'] updated for plate {}.".format(key+1)) except: print("Plate {} amplitude calculation failed.".format(key+1)) # collate data processed data from all plates and update self.data self.group_data(data_type) amp = self.data[data_type]['grouped']['data'].iloc[:, self.window[0]:self.window[1]].to_numpy() # easiest means to do this is to just calculate the means again - keeps everything in the same order. amp_mean = np.mean(amp, axis = 1) plateaus = pd.DataFrame(amp_mean, columns = ['Amplitude'], index = self.data[data_type]['grouped']['data'].index) # get plate map info cols = self.data[data_type]['grouped']['data'].columns cols_fltr = [i for i in cols if type(i) == str] # extract plate infor excluding data grouped_map = self.data[data_type]['grouped']['data'][cols_fltr] self.data['plateau'] = {} # merge plate map details with amps self.data['plateau']['data'] = grouped_map.join(plateaus) return self.data['plateau']['data'] print("self.data['plateau']['data'] updated") def mean_amplitude(self, use_normalised = False, combine = True): """Returns mean amplitudes and error for each condition, for either each plate or across all plates. The user must run the normalise method before attempting to get the mean amplitudes of the normalised amplitudes. :param use_normalised: If True, uses normalised amplitudes, default = False :type use_normalised: bool :return: Mean amplitudes and error for each condition :rtype: Pandas DataFrame :param combine: Generate mean amplitudes for each plate or across all plates, default = False :type combine: bool """ # check data_type == 'ratio' or 'baseline_corrected' self.data['mean_amplitudes'] = {} if combine == False: for key, val in enumerate(self.caflexplates): mean_amps = val.mean_amplitude(use_normalised) # get mean amps for each plate self.data['mean_amplitudes'][key] = mean_amps # update self.data print("self.data['mean_ampltitudes'][{}] updated".format(key)) if combine == True: if use_normalised == False: group = self.data['plateau']['data'] else: group = self.data['plateau']['data_normed'] # UPDATE NORMALISE FOR COMBINE # get valid data group = group[group.Valid == True] # drop cols which cause errors w/ groupby operations group.drop(['Valid'], axis = 1, inplace = True) # get mean amps for each condition across all plates mean_response = group.groupby(self.grouplist).mean().reset_index() # get errors if use_normalised == False: mean_response['Amplitude Error'] = group.groupby(self.grouplist).sem().reset_index().loc[:, 'Amplitude'] else: mean_response['amps_normed_error'] = group.groupby(self.grouplist).sem().reset_index().loc[:, 'amps_normed'] # drop empty rows mean_response.drop(mean_response[mean_response['Type'] == 'empty'].index) # update self.data self.data['mean_amplitudes'] = mean_response return self.data['mean_amplitudes'] def normalise(self, combine = True): """Normalises amplitudes to mean control amplitude. If combine = True, normalises to the mean control amplitude across all the plates. Updates either each caflexplate object or the caflexgroup object. :param combine: If true, normalises the response amplitudes to the mean control across all the plates :type combine: bool """ if combine == False: for key, val in enumerate(self.caflexplates): val.normalise() print("Plate {} normalised".format(key+1)) if combine == True: # get mean control amplitude mean_amps = self.mean_amplitude(use_normalised = False, combine = True) amps = self.data['plateau']['data']['Amplitude'] control_amp = mean_amps[mean_amps['Type'] == 'control']['Amplitude'].mean() # get plate map infor for every well across every plate platemap = self.data['plateau']['data'].loc[:, 'Well ID': 'Valid'] # normalise to mean control normed = ((amps*100) / control_amp).to_frame().rename(columns = {'Amplitude':'amps_normed'}) # update self.data self.data['plateau']['data_normed'] = platemap.join(normed) print("Collated data normalised to mean control. See self.data['plateau']['data_normed']") return self.data['plateau']['data_normed'] def collate_curve_data(self, plot_func, use_normalised, n, proteins, compounds, **kwargs): """Updates self.plot_data with the data from all the plates.""" mean_amps = self.mean_amplitude(combine = True, use_normalised = use_normalised) # use static method in calcium_flex to get curve_data curve_data = cal.CaFlexPlate._gen_curve_data(mean_amps, plot_func, use_normalised, n, proteins, compounds, **kwargs) self.plot_data = curve_data return self.plot_data def plot_curve(self, plot_func, combine_plates = False, combine = True, plate_number = True, activator = " ", use_normalised = False, type_to_plot = 'compound', title = ' ', dpi = 120, n = 5, proteins = [], compounds = [], error_bar = True, cmap = "Dark2", show_top_bot = False, conc_units = 'M', **kwargs): """Plots fitted curve, for either each plate or a combined plot using logistic regression with errors and IC50/EC50 values. :param plot_func: Plot function to use, either ic50 or ec50 :type plot_func: str :param combine_plates: Combines all plots across all plates onto the same graph, default = False :type combine_plates = bool :param combine: Combines different proteins and compounds on same plate to the same plot, default = False :type combine: bool :param activator: Activator injected into assay, default = "" :type activator: str :param use_normalised: If True, uses normalised amplitudes, default = False :type use_normalised: bool :param type_to_plot: Type of condition to plot, default = 'compound' :type type_to_plot: str :param title: Choose between automatic title or insert string to use, default = 'auto' :type title: str :param dpi: Size of figure :type dpi: int :param n: Number of concentrations required for plot :type n: int :param proteins: Proteins to plot, defaults to all :type proteins: list :param compounds: Compounds to plot, defaults to all :type compounds: list :param show_top_bot: 'True' shows the top and bottom curve fitting values in the legend :type show_top_bot: bool :param conc_units: Units displayed on x axis of graph :type conc_units: str :param **kwargs: Additional curve fitting arguments :return: Figure with fitted dose-response curve :rtype: fig """ # plot each plate separately (combine can be on or off) if combine_plates == False: for key, val in enumerate(self.caflexplates): val.plot_curve(plot_func, use_normalised, n, proteins, compounds, error_bar, cmap, combine, activator, title, dpi, show_top_bot, **kwargs) # update with type_to_plot # combine data from all plates (combine can still separate proteins/compounds) if combine_plates == True: curve_data = self.collate_curve_data(plot_func, use_normalised, n, proteins, compounds, **kwargs) # add curve data as object attribute self.curve_data = curve_data for k in self.curve_data.keys(): self.curve_data[k]['plot_func'] = plot_func # use static method in calcium_flex to plot cal.CaFlexPlate._plot_curve(curve_data, plot_func, use_normalised, n, proteins, compounds, error_bar, cmap, combine, activator, title, dpi, show_top_bot, conc_units) def export_data(self, combine_plates = False, title = ""): """Exports raw and processed data to an excel file. The excel file will be named after the 'self.title' parameter unless otherwise specified. Combining the data will calulate and generate the curve fit values that correspond to those used when combine_plates = True in plot_conditions. It is recommended that the user set the title if combine = True. :param combine_plates: Combines data from each plate to the same document, default = False :type combine_plates: bool :param title: Title of the excel file, default = self.title + '_data_export.xlsx' :type title: str :return: Excel document :rtype: .xlsx """ if combine_plates == False: for key, val in enumerate(self.caflexplates): # if title[-5:] != '.xlsx': # title = title + '.xlsx' if title == "": val.export_data() else: val.export_data("{}_{}".format(key, title)) print("Plate {} data exported as {}".format(key+1, title)) if combine_plates == True: # set title if title == "": title = date.today().strftime("%d-%m-%Y") + "_combined_data_" + '.xlsx' # get curve data curve_dict = {} if hasattr(self, 'curve_data'): for key, val in self.curve_data.items(): # get curve data for each protein/compound combo curve = copy.deepcopy(val) # get deep copy - prevents original dict from being edited curve['popt_keys'] = ['top', 'bottom', curve['plot_func'], 'hill'] # add popt index for i in ['compound', 'protein', 'c50units', 'plot_func']: # delete irrelevent keys curve.pop(i) curve_df = pd.DataFrame.from_dict(curve, orient = 'index') curve_dict[key] = curve_df # unpack data dictionary and upload to excel: with pd.ExcelWriter(title) as writer: for k1, v1 in self.data.items(): if isinstance(v1, pd.DataFrame): v1.to_excel(writer, sheet_name = k1) for k2, v2 in v1.items(): if isinstance(v2, pd.DataFrame): v2.to_excel(writer, sheet_name = k1 + "_" + k2) for k3, v3 in v2.items(): if isinstance(v3, pd.DataFrame): v3.to_excel(writer, sheet_name = k1 + "_" + k2 + "_" + k3) # export curve data for each protein/compund combination for key, val in curve_dict.items(): key = key.translate({ord(i): None for i in "[]:*?/" }) # get rid of invalid characters val.to_excel(writer, sheet_name = key + '_curve_data') print("Combined plate data exported as {}".format(title))
[ "numpy.mean", "calciumflexanalysis.calcium_flex.CaFlexPlate._plot_curve", "calciumflexanalysis.calcium_flex.CaFlexPlate._gen_curve_data", "datetime.date.today", "pandas.DataFrame.from_dict", "numpy.array", "collections.defaultdict", "copy.deepcopy", "pandas.DataFrame", "pandas.ExcelWriter", "pan...
[((6488, 6505), 'collections.defaultdict', 'defaultdict', (['list'], {}), '(list)\n', (6499, 6505), False, 'from collections import defaultdict\n'), ((9499, 9538), 'pandas.concat', 'pd.concat', (['data_list'], {'ignore_index': '(True)'}), '(data_list, ignore_index=True)\n', (9508, 9538), True, 'import pandas as pd\n'), ((9560, 9599), 'pandas.concat', 'pd.concat', (['time_list'], {'ignore_index': '(True)'}), '(time_list, ignore_index=True)\n', (9569, 9599), True, 'import pandas as pd\n'), ((13607, 13627), 'numpy.mean', 'np.mean', (['amp'], {'axis': '(1)'}), '(amp, axis=1)\n', (13614, 13627), True, 'import numpy as np\n'), ((13649, 13752), 'pandas.DataFrame', 'pd.DataFrame', (['amp_mean'], {'columns': "['Amplitude']", 'index': "self.data[data_type]['grouped']['data'].index"}), "(amp_mean, columns=['Amplitude'], index=self.data[data_type][\n 'grouped']['data'].index)\n", (13661, 13752), True, 'import pandas as pd\n'), ((18466, 18573), 'calciumflexanalysis.calcium_flex.CaFlexPlate._gen_curve_data', 'cal.CaFlexPlate._gen_curve_data', (['mean_amps', 'plot_func', 'use_normalised', 'n', 'proteins', 'compounds'], {}), '(mean_amps, plot_func, use_normalised, n,\n proteins, compounds, **kwargs)\n', (18497, 18573), True, 'from calciumflexanalysis import calcium_flex as cal\n'), ((21519, 21692), 'calciumflexanalysis.calcium_flex.CaFlexPlate._plot_curve', 'cal.CaFlexPlate._plot_curve', (['curve_data', 'plot_func', 'use_normalised', 'n', 'proteins', 'compounds', 'error_bar', 'cmap', 'combine', 'activator', 'title', 'dpi', 'show_top_bot', 'conc_units'], {}), '(curve_data, plot_func, use_normalised, n,\n proteins, compounds, error_bar, cmap, combine, activator, title, dpi,\n show_top_bot, conc_units)\n', (21546, 21692), True, 'from calciumflexanalysis import calcium_flex as cal\n'), ((1516, 1537), 'numpy.array', 'np.array', (['inject_list'], {}), '(inject_list)\n', (1524, 1537), True, 'import numpy as np\n'), ((23857, 23878), 'pandas.ExcelWriter', 'pd.ExcelWriter', (['title'], {}), '(title)\n', (23871, 23878), True, 'import pandas as pd\n'), ((6908, 6921), 'numpy.array', 'np.array', (['val'], {}), '(val)\n', (6916, 6921), True, 'import numpy as np\n'), ((23298, 23316), 'copy.deepcopy', 'copy.deepcopy', (['val'], {}), '(val)\n', (23311, 23316), False, 'import copy\n'), ((23652, 23697), 'pandas.DataFrame.from_dict', 'pd.DataFrame.from_dict', (['curve'], {'orient': '"""index"""'}), "(curve, orient='index')\n", (23674, 23697), True, 'import pandas as pd\n'), ((22980, 22992), 'datetime.date.today', 'date.today', ([], {}), '()\n', (22990, 22992), False, 'from datetime import date\n')]