text
stringlengths
0
27.1M
meta
dict
import matplotlib.pyplot as plt import numpy as np x = np.linspace(-2, 2) plt.subplots(2, 2, sharex = True) plt.subplot(2, 2, 1) plt.ylabel("y") plt.xlabel("x") plt.yticks([1, 0, -1]) plt.plot(x, np.sin(4*x), color="red", label="sin(4x)") plt.legend(loc = "center right") plt.subplot(2, 2, 2) plt.xlabel("x") plt.yticks([0.5, 0, -0.5]) plt.plot(x, np.cos(x)*np.sin(x), color="green", label="cos(x)sin(x)") plt.legend(loc = "center") plt.subplot(2, 2, 3) plt.ylabel("y") plt.xlabel("x") plt.xticks([-2, 0, 2]) plt.yticks([0, 10]) plt.plot(x, x**4, color="blue", label="x^4") plt.legend(loc = "upper center") plt.subplot(2, 2, 4) plt.xlabel("x") plt.yticks([1, 0, -1]) plt.plot(x, np.cos(x)+np.sin(x), color="black", label="cos(x)+sin(x)") plt.legend(loc = "lower right") plt.show()
{ "alphanum_fraction": 0.6226175349, "author": null, "avg_line_length": 22.4857142857, "converted": null, "ext": "py", "file": null, "hexsha": "59d0db270bf493e7e74da26d483d6eaf0f9a95cb", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "VoxelPi/compm", "max_forks_repo_path": "ue/ue_06/problem_2.py", "max_issues_count": 4, "max_issues_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_issues_repo_issues_event_max_datetime": "2022-03-29T21:33:49.000Z", "max_issues_repo_issues_event_min_datetime": "2022-03-09T22:54:25.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "VoxelPi/compm", "max_issues_repo_path": "ue/ue_06/problem_2.py", "max_line_length": 70, "max_stars_count": null, "max_stars_repo_head_hexsha": "745019d4e0d156910f19ed9168949f150356a349", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "VoxelPi/compm", "max_stars_repo_path": "ue/ue_06/problem_2.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 289, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 787 }
from flask import Flask, request, jsonify app = Flask(__name__) import pickle with open('../models/digitizer.pickle', 'rb') as fd: methods = pickle.load(fd) scale = methods['scale'] model = methods['model'] import numpy as np from json import loads @app.route('/', methods=['POST']) def index(): data = loads(request.json) result = { 'prediction': int( model.predict( np.array([data]).astype(float) / scale )[0] ) } return jsonify(result) # файл запустили напрямую if __name__ == '__main__': app.run(host='localhost', port=5555, debug=True)
{ "alphanum_fraction": 0.6095238095, "author": null, "avg_line_length": 21.724137931, "converted": null, "ext": "py", "file": null, "hexsha": "b168a09393a292e788037eaeefccba24b7b3be41", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bec3e3fb49cc934c2e310b341a52820b8d3a4bab", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "timeseries-ru/course", "max_forks_repo_path": "code/digitizer_service.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "bec3e3fb49cc934c2e310b341a52820b8d3a4bab", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "timeseries-ru/course", "max_issues_repo_path": "code/digitizer_service.py", "max_line_length": 54, "max_stars_count": 7, "max_stars_repo_head_hexsha": "bec3e3fb49cc934c2e310b341a52820b8d3a4bab", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "timeseries-ru/course", "max_stars_repo_path": "code/digitizer_service.py", "max_stars_repo_stars_event_max_datetime": "2022-02-08T04:18:46.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-12T07:22:04.000Z", "num_tokens": 154, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 630 }
import requests import json import sys import time import argparse import numpy as np parser = argparse.ArgumentParser() parser.add_argument('--datatransformer_provider', help='URL of the Data Transformer Provider') #parser.add_argument('--resource_type', help='Type of resource') parser.add_argument('--num_test', help='Number of tests') args = parser.parse_args() num_test =int(args.num_test) payload = {"tenantId": "valenciaportcontrol", "description": "this is a special instance for valencia port", "name":"truckprocessor" } headers = { 'Content-Type': "application/json", 'Cache-Control': "no-cache", } for i in range(num_test): payload['name']="truckprocessor"+str(i) response = requests.request("POST", args.datatransformer_provider, data=json.dumps(payload), headers=headers) print(response.text)
{ "alphanum_fraction": 0.7144508671, "author": null, "avg_line_length": 32.037037037, "converted": null, "ext": "py", "file": null, "hexsha": "ca7efde0a9b83a9d5a150d9d0d132501b67d6a00", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-09-23T07:07:01.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-17T17:04:04.000Z", "max_forks_repo_head_hexsha": "37a3550627682981aa7d2a4cf317f19a3b1a699c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rdsea/IoTCloudSamples", "max_forks_repo_path": "InterOpProviders/nodered-datatransformer-provider/tests/instance_limit_test.py", "max_issues_count": 7, "max_issues_repo_head_hexsha": "37a3550627682981aa7d2a4cf317f19a3b1a699c", "max_issues_repo_issues_event_max_datetime": "2022-02-06T18:03:32.000Z", "max_issues_repo_issues_event_min_datetime": "2017-10-30T22:53:51.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rdsea/IoTCloudSamples", "max_issues_repo_path": "InterOpProviders/nodered-datatransformer-provider/tests/instance_limit_test.py", "max_line_length": 113, "max_stars_count": 5, "max_stars_repo_head_hexsha": "37a3550627682981aa7d2a4cf317f19a3b1a699c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rdsea/IoTCloudSamples", "max_stars_repo_path": "InterOpProviders/nodered-datatransformer-provider/tests/instance_limit_test.py", "max_stars_repo_stars_event_max_datetime": "2021-12-20T14:22:52.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-04T08:43:58.000Z", "num_tokens": 191, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 865 }
[STATEMENT] lemma preal_add_less_cancel_left [simp]: "(t + (r::preal) < t + s) \<longleftrightarrow> (r < s)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (t + r < t + s) = (r < s) [PROOF STEP] by (blast intro: preal_add_less2_mono2 preal_add_left_less_cancel)
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "Dedekind_Real_Dedekind_Real", "hexsha": null, "include": null, "lang": null, "length": 1, "llama_tokens": 118, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": null }
\chapter{Overview} \noindent \CmdStan is the command-line interface for Stan. The next two chapters describe tools that are built as part of \CmdStan installation: \code{stanc} and \code{stansummary}. The process of building a \CmdStan executable from a Stan program is as follows: % \begin{enumerate} \item A Stan program is written to file with a \code{.stan} extension. \item \code{stanc} is used to translate the Stan program into a \Cpp file. This \Cpp file is not a full program that can be compiled to executable directly, but a translation from the Stan language into a \Cpp concept. Each interface will generate identical \Cpp for the same Stan program. \item A \CmdStan executable is generated from the \CmdStan source and the generated \Cpp. Each Stan program will have its own \CmdStan executable. The options to the \CmdStan executable are described in \refchapter{stan-cmd}. \end{enumerate} \section{GNU Make utility} \CmdStan uses GNU Make utility to build CmdStan binaries and Stan programs The CmdStan `makefile` defines named targets to build the former and general rules to build the latter. A call to {\tt make} has the following general syntax: % \begin{quote} \begin{Verbatim}[fontshape=sl] make <flags> <variable=value> <name> \end{Verbatim} \end{quote} % When invoked without any arguments at all, {\tt make} prints a help message % \begin{quote} \begin{Verbatim}[fontshape=sl, fontsize=\footnotesize] -------------------------------------------------------------------------------- CmdStan v2.22.0 help Build CmdStan utilities: > make build This target will: 1. Install the Stan compiler bin/stanc from stanc3 binaries and build bin/stanc2. 2. Build the print utility bin/print (deprecated; will be removed in v3.0) 3. Build the stansummary utility bin/stansummary 4. Build the diagnose utility bin/diagnose 5. Build all libraries and object files compile and link an executable Stan program Note: to build using multiple cores, use the -j option to make, e.g., for 4 cores: > make build -j4 Build a Stan program: Given a Stan program at foo/bar.stan, build an executable by typing: > make foo/bar This target will: 1. Install the Stan compiler (bin/stanc), as needed. 2. Use the Stan compiler to generate C++ code, foo/bar.hpp. 3. Compile the C++ code using cc . to generate foo/bar Additional make options: STANCFLAGS: defaults to "". These are extra options passed to bin/stanc when generating C++ code. If you want to allow undefined functions in the Stan program, either add this to make/local or the command line: STANCFLAGS = --allow_undefined USER_HEADER: when STANCFLAGS has --allow_undefined, this is the name of the header file that is included. This defaults to "user_header.hpp" in the directory of the Stan program. STANC2: When set, use bin/stanc2 to generate C++ code. Example - bernoulli model: examples/bernoulli/bernoulli.stan 1. Build the model: > make examples/bernoulli/bernoulli 2. Run the model: > examples/bernoulli/bernoulli sample data file=examples/bernoulli/bernoulli.data.R 3. Look at the samples: > bin/stansummary output.csv Clean CmdStan: Remove the built CmdStan tools: > make clean-all -------------------------------------------------------------------------------- \end{Verbatim} \end{quote} % \section{Building the \CmdStan Tools}\label{build.section} The easy way to build \CmdStan is through the use of make. From a command line window, type: % \begin{quote} \begin{Verbatim}[fontshape=sl,fontsize=\small] > cd <cmdstan-home> > make build \end{Verbatim} \end{quote} % This will build utilities \code{stansummary} and \code{diagnose} and instantiate the \code{stanc} binary. If your computer has multiple cores and sufficient ram, the build process can be parallelized by providing the \code{-j} option. For example, to build on 4 cores, type: % \begin{quote} \begin{Verbatim}[fontshape=sl,fontsize=\small] > cd <cmdstan-home> > make -j4 build \end{Verbatim} \end{quote} % \textbf{Warning:} \ The \code{make} program may take 10+ minutes and consume 2+ GB of memory to build \CmdStan.
{ "alphanum_fraction": 0.702247191, "author": null, "avg_line_length": 33.6377952756, "converted": null, "ext": "tex", "file": null, "hexsha": "abeb184d1428b4b3cd8c52a34578a244e7f297ec", "include": null, "lang": "TeX", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "10c5a562519591af7a496edbda23f8702cd8657a", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "rybern/cmdstan", "max_forks_repo_path": "src/docs/cmdstan-guide/tools.tex", "max_issues_count": null, "max_issues_repo_head_hexsha": "10c5a562519591af7a496edbda23f8702cd8657a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "rybern/cmdstan", "max_issues_repo_path": "src/docs/cmdstan-guide/tools.tex", "max_line_length": 105, "max_stars_count": 1, "max_stars_repo_head_hexsha": "10c5a562519591af7a496edbda23f8702cd8657a", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "rybern/cmdstan", "max_stars_repo_path": "src/docs/cmdstan-guide/tools.tex", "max_stars_repo_stars_event_max_datetime": "2020-05-04T17:15:40.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-04T17:15:40.000Z", "num_tokens": 1114, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 4272 }
# Copyright 2019 AIST # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from copy import copy from typing import Optional, Tuple import combo import numpy as np def write(new_data: combo.variable, test: combo.variable, t: np.ndarray) -> None: new_data.add(X=test.X, t=t, Z=test.Z) def init_config(config: Optional[combo.misc.set_config] = None) -> combo.misc.set_config: if config is not None: return config else: return combo.misc.set_config() def init_predictor(num_rand_basis: int, config: combo.misc.set_config) -> combo.base_predictor: is_rand_expans = False if num_rand_basis == 0 else True if is_rand_expans: return combo.blm.predictor(config) else: return combo.gp.predictor(config) def learn(predictor: combo.base_predictor, training: combo.variable, num_rand_basis: int) -> None: training = copy(training) predictor.fit(training, num_rand_basis) training.Z = predictor.get_basis(training.X) predictor.prepare(training) def update(predictor: combo.base_predictor, new_data: combo.variable) -> None: predictor.update(None, new_data) def get_basis(predictor: combo.base_predictor, X: np.ndarray) -> np.ndarray: return predictor.get_basis(X) def init_test(predictor: combo.base_predictor, test_X: np.ndarray) -> combo.variable: return combo.variable(X=test_X, Z=predictor.get_basis(test_X)) def get_score(predictor: combo.base_predictor, test: combo.variable, score: str) -> np.ndarray: if score == 'EI': return combo.search.score.EI(predictor, None, test) elif score == 'PI': return combo.search.score.PI(predictor, None, test) elif score == 'TS': return combo.search.score.TS(predictor, None, test, predictor.config.search.alpha) else: raise NotImplementedError('mode must be EI, PI or TS.') class Centering: def __init__(self, X: np.ndarray, config: combo.misc.set_config) -> None: self.mean = np.mean(X, axis=0) std = np.std(X, axis=0) self.std = np.where(std >= config.learning.epsilon, std, 1) def __call__(self, X: np.ndarray) -> np.ndarray: return (X - self.mean) / self.std class Predictor: def __init__(self, policy: 'Policy', num_rand_basis: int, config: combo.misc.set_config) -> None: self.policy = policy self.new_data = combo.variable() self.predictor = init_predictor(num_rand_basis=num_rand_basis, config=config) training = self.policy.training self.centering = Centering(training.X, config=config) learn(self.predictor, combo.variable(X=self.centering(training.X), t=training.t), num_rand_basis=num_rand_basis) def write(self, X: np.ndarray, test: combo.variable, t: np.ndarray, is_disp: bool = True) -> None: self.new_data.add(X=test.X, t=t, Z=test.Z) self.policy.write(X, t, is_disp) def init_test(self, X: np.ndarray) -> combo.variable: return init_test(self.predictor, self.centering(X)) def get_score(self, test: combo.variable, score: str) -> np.ndarray: update(self.predictor, self.new_data) self.new_data = combo.variable() return get_score(self.predictor, test, score) class Policy: def __init__(self, config: Optional[combo.misc.set_config] = None) -> None: super().__init__() self.training = combo.variable() self.history = combo.search.discrete.history() self.config = init_config(config) def write(self, X: np.ndarray, t: np.ndarray, is_disp: bool = True) -> None: st = self.history.total_num_search self.history.write(t, np.arange(st, st + t.shape[0])) self.training.add(X=X, t=t) if is_disp: combo.search.utility.show_search_results(self.history, t.shape[0]) def learn(self, num_rand_basis: int) -> Predictor: return Predictor(self, num_rand_basis=num_rand_basis, config=self.config) class Test: def __init__(self, X: np.ndarray) -> None: self.X = X def random_search(self, policy: Policy) -> np.ndarray: ... def bayes_search(self, predictor: Predictor) -> Tuple[np.ndarray, combo.variable]: ...
{ "alphanum_fraction": 0.6703433923, "author": null, "avg_line_length": 35.5925925926, "converted": null, "ext": "py", "file": null, "hexsha": "2a7073b09c6734f5328d39372244934865d4e3b8", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "174fb68ef10c75307865a6af546d39c899a266cf", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "atsu-kan/quml", "max_forks_repo_path": "src/common/combo/__init__.py", "max_issues_count": 1, "max_issues_repo_head_hexsha": "174fb68ef10c75307865a6af546d39c899a266cf", "max_issues_repo_issues_event_max_datetime": "2020-04-14T12:50:26.000Z", "max_issues_repo_issues_event_min_datetime": "2020-04-14T12:50:26.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "atsu-kan/quml", "max_issues_repo_path": "src/common/combo/__init__.py", "max_line_length": 121, "max_stars_count": null, "max_stars_repo_head_hexsha": "174fb68ef10c75307865a6af546d39c899a266cf", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "atsu-kan/quml", "max_stars_repo_path": "src/common/combo/__init__.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1116, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 4805 }
```python import sympy as sp ``` ```python s = sp.Symbol('s') ``` ```python V = sp.Symbol('V') ``` ```python top = (2*V*s)*(1/s+2*s/(4*s**2+1)) - 0 ``` ```python bottom = (1/s+(6*s+3)/(3*s+1))*(1/s+2*s/(4*s**2+1)) - (1/s)**2 ``` ```python sp.simplify(top/bottom) ``` 2*V*s*(18*s**3 + 6*s**2 + 3*s + 1)/(36*s**3 + 24*s**2 + 8*s + 3) ```python ```
{ "alphanum_fraction": 0.4562647754, "author": null, "avg_line_length": 17.2653061224, "converted": true, "ext": "ipynb", "file": null, "hexsha": "e178a047d949025d989cb87cbd398e8eacfef633", "include": null, "lang": "Jupyter Notebook", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "dccad2ad7a875f2ecccb0db2bb6e2afa392916d1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "fossabot/PyNumDiff", "max_forks_repo_path": "notebooks/paper_figures/misc/Untitled2.ipynb", "max_issues_count": null, "max_issues_repo_head_hexsha": "dccad2ad7a875f2ecccb0db2bb6e2afa392916d1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "fossabot/PyNumDiff", "max_issues_repo_path": "notebooks/paper_figures/misc/Untitled2.ipynb", "max_line_length": 73, "max_stars_count": null, "max_stars_repo_head_hexsha": "dccad2ad7a875f2ecccb0db2bb6e2afa392916d1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "fossabot/PyNumDiff", "max_stars_repo_path": "notebooks/paper_figures/misc/Untitled2.ipynb", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 166, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 1692 }
import os, argparse, torch, time import torch.optim as optim import torchvision.models as models import torch.nn.functional as F import torch.nn as nn import torch.utils.data as torchdata import numpy as np import torch.backends.cudnn as cudnn from torch.utils.data import DataLoader import torchvision.transforms as transforms from PIL import Image import itertools ####################################################### utils ################################################## def default_loader(path): return Image.open(path).convert('RGB') class MyDataset(torchdata.Dataset): def __init__(self, path, txt, transform=None, loader=default_loader): self.transform = transform self.path = path self.loader = loader fh = open(txt, 'r') imgs = [] for line in fh: if line == '': break line = line.strip('\n') line = line.rstrip() words = line.split(' ') imgs.append(words) self.imgs = imgs def __getitem__(self, index): words = self.imgs[index] img = self.loader(self.path + words[0]) # as 'imgPath' in line 69 img = self.transform(img) label = int(words[1]) return img, label def __len__(self): return len(self.imgs) def myDataloader(opt): batchSize = opt.batchSize normalize = transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)) # normalize = transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)) transform_train = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), normalize ]) transform_test = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), normalize ]) if opt.dataset == 'CUB': train_dir = opt.imgPath + 'CUB_Train.txt' test_dir = opt.imgPath + 'CUB_Test.txt' DB_dir = opt.imgPath + 'CUB_DB.txt' imgPath = opt.imgPath + 'CUB_200_2011/images/' test_set = MyDataset(imgPath, txt=test_dir, transform=transform_test) test_loader = torchdata.DataLoader(test_set, batch_size=batchSize,shuffle=False, num_workers=2, pin_memory=True) train_set = MyDataset(imgPath, txt=train_dir, transform=transform_train) train_loader = torchdata.DataLoader(train_set, batch_size=batchSize, shuffle=True, num_workers=2, pin_memory=True) DB_set = MyDataset(imgPath, txt=DB_dir, transform=transform_test) DB_loader = torchdata.DataLoader(DB_set, batch_size=batchSize, shuffle=False, num_workers=2, pin_memory=True) return DB_loader, train_loader, test_loader def combinations(iterable, r): pool = list(iterable) n = len(pool) for indices in itertools.permutations(range(n), r): if sorted(indices) == list(indices): yield list(pool[i] for i in indices) def get_triplets(labels): labels = labels.cpu().data.numpy() triplets = [] for label in set(labels): label_mask = (labels == label) label_indices = np.where(label_mask)[0] if len(label_indices) < 2: continue negative_indices = np.where(np.logical_not(label_mask))[0] anchor_positives = list(combinations(label_indices, 2)) # All anchor-positive pairs # Add all negatives for all positive pairs temp_triplets = [[anchor_positive[0], anchor_positive[1], neg_ind] for anchor_positive in anchor_positives for neg_ind in negative_indices] triplets += temp_triplets return torch.LongTensor(np.array(triplets)) def compute_result(dataloader, net, opt): bs, clses = [], [] net.eval() with torch.no_grad(): for img, cls in dataloader: clses.append(cls) img = F.interpolate(img, size=(224, 224), mode='bilinear', align_corners=False) bs.append(net(img.cuda())) return torch.sign(torch.cat(bs)), torch.cat(clses) def compute_mAP(trn_binary, tst_binary, trn_label, tst_label): for x in trn_binary, tst_binary, trn_label, tst_label: x.long() AP = [] Ns = torch.arange(1, trn_binary.size(0) + 1) Ns = Ns.type(torch.FloatTensor) for i in range(tst_binary.size(0)): query_label, query_binary = tst_label[i], tst_binary[i] _, query_result = torch.sum((query_binary != trn_binary).long(), dim=1).sort() correct = (query_label == trn_label[query_result]).float() P = torch.cumsum(correct.type(torch.FloatTensor), dim=0) / Ns AP.append(torch.sum(P * correct) / torch.sum(correct)) mAP = torch.mean(torch.Tensor(AP)) return mAP def choose_gpu(i_gpu): """choose current CUDA device""" torch.cuda.device(i_gpu).__enter__() cudnn.benchmark = True def feed_random_seed(seed=np.random.randint(1, 10000)): """feed random seed""" np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed(seed) def saveHashCodes(trn_binary, tst_binary, trn_label, tst_label, mAP, opt): saved = dict() saved['db_hcodes'] = trn_binary saved['test_hcodes'] = tst_binary saved['db_labels'] = trn_label saved['test_labels'] = tst_label torch.save(saved, opt.savePath + f'TripletH_{opt.dataset}_{opt.bits}bits_[{mAP*100:.2f}]mAP.pkl') ####################################################### main ################################################## def triplet_hashing_loss_regu(embeddings, triplets, margin): pos_dist = (embeddings[triplets[:, 0]] - embeddings[triplets[:, 1]]).pow(2).sum(1) # .pow(.5) neg_dist = (embeddings[triplets[:, 0]] - embeddings[triplets[:, 2]]).pow(2).sum(1) # .pow(.5) losses = F.relu(pos_dist - neg_dist + margin) # hinge loss return losses.mean() def train(dataloader, net, optimizer, opt): sum_lossT = 0 sum_lossQ = 0 net.train() for i, (img, cls) in enumerate(dataloader): net.zero_grad() embeddings = net(img.cuda()) embeddings = torch.tanh(embeddings) triplets = get_triplets(cls) if triplets.shape[0] != 0: lossT = triplet_hashing_loss_regu(embeddings, triplets, opt.margin) lossQ = torch.abs(torch.pow(embeddings.abs() - torch.ones(embeddings.size()).cuda(), 3)).mean() loss = lossT + opt.lambdaQ * lossQ # triplet loss + lambdaQ * quantization loss loss.backward() optimizer.step() sum_lossT += float(lossT) sum_lossQ += float(lossQ) else: del embeddings return sum_lossT/len(dataloader), sum_lossQ/len(dataloader) def main(): parser = argparse.ArgumentParser(description='Triplet Loss') parser.add_argument('--checkpoint', type=int, default=20, help='check mAP') parser.add_argument('--obpoint', type=int, default=10, help='show loss') parser.add_argument('--batchSize', type=int, default=100) parser.add_argument('--ngpu', type=int, default=0, help='gpu id') parser.add_argument('--bits', type=int, default=64, help='hash bit length') parser.add_argument('--niter', type=int, default=2101, help='epoch') parser.add_argument('--dataset', type=str, default='CUB') parser.add_argument('--margin', type=float, default=0, help='0.5 bits by default') parser.add_argument('--lambdaQ', type=float, default=0.05, help='weight para for quantization loss') parser.add_argument('--savePath', type=str, default='/.../SavedHashCodes/') parser.add_argument('--imgPath', type=str, default='/.../Data/CUB/') opt = parser.parse_args() opt.margin = 0.5 * opt.bits print(opt) choose_gpu(opt.ngpu) feed_random_seed() DB_loader, train_loader, test_loader = myDataloader(opt) net = models.resnet50(pretrained=True) net.fc = nn.Linear(2048, opt.bits) net.cuda() optimizer = torch.optim.Adam(net.parameters(), lr=5e-5, betas=(0.9, 0.999), eps=1e-08, weight_decay=10**-5) # optimizer = torch.optim.RMSprop(net.parameters(), lr=1e-4, weight_decay=1e-5) print('Start training Triplet Loss Hashing. Training Loss is shown as [epoch]: Triplet Loss + Quantization Loss.') max_map = 0 for epoch in range(0, opt.niter): lossT, lossQ = train(train_loader, net, optimizer, opt) if epoch%opt.obpoint==0: print(f'[{epoch:4d}]: {lossT:.4f} + {lossQ:.4f}', end=' ') if epoch%opt.checkpoint==0 and epoch!=0: trn_binary, trn_label = compute_result(DB_loader, net, opt) tst_binary, tst_label = compute_result(test_loader, net, opt) mAP = compute_mAP(trn_binary, tst_binary, trn_label, tst_label) # if mAP>max_map and epoch>500: # saveHashCodes(trn_binary, tst_binary, trn_label, tst_label, mAP, opt) # torch.save(net.state_dict(), opt.savePath + f'TripletH_{opt.dataset}_{opt.bits}bits_[{mAP*100:.2f}]mAP_{epoch}epoch.pkl') max_map = max(mAP, max_map) # print(f'[{epoch:4d}] T:{lossT:.4f} Q:{lossQ:.4f}', end=' ') print(f' Triplet Hashing on {opt.dataset}, [{epoch}] epoch, mAP: {mAP*100:.2f} max_mAP: {max_map*100:.2f}') return max_map, opt if __name__ == '__main__': max_map, opt = main() print(opt) print('[Final] retrieval mAP: ', max_map)
{ "alphanum_fraction": 0.6941560714, "author": null, "avg_line_length": 36.0210084034, "converted": null, "ext": "py", "file": null, "hexsha": "dc29f7fb0027c3ec18683b51076d0d9471fed8b5", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "684d452a5b95c92421ad97f2e9444ecaeb42637c", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rayLemond/Triplet-Loss-for-Hashing", "max_forks_repo_path": "TripletHashing.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "684d452a5b95c92421ad97f2e9444ecaeb42637c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rayLemond/Triplet-Loss-for-Hashing", "max_issues_repo_path": "TripletHashing.py", "max_line_length": 127, "max_stars_count": 2, "max_stars_repo_head_hexsha": "684d452a5b95c92421ad97f2e9444ecaeb42637c", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rayLemond/TripletHashing", "max_stars_repo_path": "TripletHashing.py", "max_stars_repo_stars_event_max_datetime": "2021-11-22T12:49:39.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-13T15:05:02.000Z", "num_tokens": 2386, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 8573 }
# -*- coding: UTF-8 -*- import numpy as np import math from faceemo.utils import FACIAL_LANDMARKS_68_IDXS def _distance_x(l1, l2): return (l2[0] - l1[0]) def _distance_y(l1, l2): return (l2[1] - l1[1]) def _distance_allpairs_xy(landmarks): allpairsX = [] allpairsY = [] for i in range(len(landmarks)): this = landmarks[i] allpairsX.extend([_distance_x(this, that) for that in landmarks[i+1:]]) allpairsY.extend([_distance_y(this, that) for that in landmarks[i+1:]]) return allpairsX, allpairsY def _distance_neighbors_xy(landmarks): X = landmarks[:,0] Y = landmarks[:,1] Xneighbors = zip(X[1:], X[:-1]) Yneighbors = zip(Y[1:], Y[:-1]) f = lambda x: x[0] - x[1] Xdistance = list(map(f, Xneighbors)) Ydistance = list(map(f, Yneighbors)) return Xdistance, Ydistance def _angle(landmark): x, y = landmark return (math.atan2(y, x)*360)/(2*math.pi) def _angle_two_pts(p1, p2): dx, dy = p2 - p1 return (math.atan2(dy, dx)*360)/(2*math.pi) def inner_mouth_angles(landmarks): startupper, endupper = FACIAL_LANDMARKS_68_IDXS.get("inner_mouth_right_upper") im_landmarks_upper = landmarks[startupper: endupper] pairs_upper = list(zip(im_landmarks_upper[:-1], im_landmarks_upper[1:])) upper = [_angle_two_pts(p1, p2) for (p1, p2) in pairs_upper] im_landmarks_lower = [landmarks[60], landmarks[67], landmarks[66]] pairs_lower = list(zip(im_landmarks_lower[:-1], im_landmarks_lower[1:])) lower = [_angle_two_pts(p1, p2) for (p1, p2) in pairs_lower] return np.asarray(upper + lower) def features_by_neighbors_and_inner_mouth_angles(landmarks): ''' A combinations of features, from both `features_by_neighbors` and `inner_mouth_angles` ''' neighbors = features_by_neighbors(landmarks) angles1 = inner_mouth_angles(landmarks) return np.concatenate([neighbors, angles1]) def features_by_neighbors(landmarks): ''' Substract two neighbor landmarks. Returns: features = [ (x1 - x0), (x2 - x1), ..., (x67 - x66), (y1 - y0), (y2 - y1), ..., (y67 - y66) ] ''' Xfeatures, Yfeatures = _distance_neighbors_xy(landmarks) return np.asarray(Xfeatures + Yfeatures) def features_by_neighbors_extended(landmarks, mouth=True): ''' Get all features from the `features_by_neighbors` function plus, all pairs of landmarks in the mouth. ''' if mouth: mouth_start, mounth_end = FACIAL_LANDMARKS_68_IDXS.get("mouth") mouth_landmarks = landmarks[mouth_start: mounth_end] mX, mY = _distance_allpairs_xy(mouth_landmarks) other_landmarks = landmarks[:mouth_start] Xdistance, Ydistance = _distance_neighbors_xy(other_landmarks) return np.asarray(Xdistance + mX + Ydistance + mY) else: return features_by_neighbors(landmarks) def features_from_center(landmarks): ''' Get center (mean) point (Xmean, Ymean) of all landmarks, substract the center point from all other landmarks. Return: features = [ (x0 - xmean), (x1 - xmean), ..., (x67 - xmean), (y0 - ymean), (y1 - ymean), ..., (y67 - ymean) ] ''' X = landmarks[:,0] Y = landmarks[:,1] Xmean = np.mean(X) Ymean = np.mean(Y) return np.concatenate([X - Xmean, Y - Ymean]) def features_from_center_with_angle(landmarks): ''' Get center (mean) point (Xmean, Ymean) of all landmarks, calculate distance to the center point and angle Returns: features = [ norm(landmark0 - center), angle0, norm(landmark1 - center), andle1, ..., norm(landmark67 - center), angle67 ] ''' center = np.mean(landmarks, axis=0) distances = [np.linalg.norm(l - center) for l in landmarks] angles = [_angle(l) for l in landmarks] return np.asarray(list(zip(list(distances), list(angles))))
{ "alphanum_fraction": 0.6546153846, "author": null, "avg_line_length": 29.7709923664, "converted": null, "ext": "py", "file": null, "hexsha": "57b51241899f9fa4407db1b8dae5edfac3f2218f", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "3b25417f510c46d727eaf9b0301ce660b9437778", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "typedt/facial-emotion-recognition", "max_forks_repo_path": "src/faceemo/feature.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "3b25417f510c46d727eaf9b0301ce660b9437778", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "typedt/facial-emotion-recognition", "max_issues_repo_path": "src/faceemo/feature.py", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "3b25417f510c46d727eaf9b0301ce660b9437778", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "typedt/facial-emotion-recognition", "max_stars_repo_path": "src/faceemo/feature.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1106, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 3900 }
#include <iostream> #include <functional> #include <armadillo> #include <string> // include code from b.cc (except main function) #define NO_MAIN #include "b.cc" #undef NO_MAIN using namespace std; using namespace arma; const std::string CHECK_MARK = "✓"; const std::string BALLOT_X = "✗"; struct test { std::function<bool()> func; std::string name; }; const double TOLERANCE = 1e-13; /** * Test maxoff() on a symmetric matrix **/ bool test_maxoff_sym() { // create known symmetric matrix mat M(5, 5, arma::fill::zeros); M(0,0) = 3; M(1,1) = 9; M(2,2) = 17; M(3,3) = 0; M(4,4) = -9; M(2,0) = M(0,2) = 9; M(2,1) = M(1,2) = -5; M(3,0) = M(0,3) = -11; M(3,1) = M(1,3) = 10; M(3,2) = M(2,3) = -7; M(4,0) = M(0,4) = 5; // expected values size_t exp_k = 3, exp_l = 0; // maximal element position double exp_a = 121; // square of maximal element // find maximal element size_t k, l; double a = maxoff(M, k, l); // compare (up to order of k and l, since M is symmetric) return (abs(a - exp_a) < TOLERANCE && ((k == exp_k && l == exp_l) || (k == exp_l && l == exp_k))); } /** * Check that jacobi_step() conserves orthonormality of S. **/ bool test_ortho() { // if a matrix preserves scalar product (or orthonormality) then it must be an orthogonal matrix, // so S * S^T = I // set of random, pre-calculated tau, k and l values (where k != l) const double tau_values[] = { 0.5 }; const double kl_values[][2] = { { 1, 2 } }; const size_t count = 1; // initial P matrix (identity) and constant identity matrix I mat P(5, 5, arma::fill::eye); const mat I(5, 5, arma::fill::eye); // for each step, P' = P * S where S is calculated from a random tau value (see above list) for(size_t i = 0; i < count; i++) { apply_rot_col(kl_values[i][0], kl_values[i][1], tau_values[i], P); // check that P * P^T = I, within tolerance if(arma::abs(P * P.t() - I).max() >= TOLERANCE) return false; } // for each step, P' = S^T * P where S is calculated from a random tau value (see above list) for(size_t i = 0; i < count; i++) { apply_rot_row(kl_values[i][0], kl_values[i][1], tau_values[i], P); // check that P * P^T = I, within tolerance if(arma::abs(P * P.t() - I).max() >= TOLERANCE) return false; } return true; } int main() { // define tests const struct test tests[] = { { test_maxoff_sym, "Maximal diagonal test on symmetric matrix" }, { test_ortho, "Orthonormality test" }, }; const size_t test_count = 2; // run tests std::cout << "Running tests:" << std::endl; for(size_t i = 0; i < test_count; i++) { auto test = tests[i]; std::cout << " " << test.name << std::endl; if(test.func()) { std::cout << " " << CHECK_MARK << " test passed" << std::endl; } else { std::cout << " " << BALLOT_X << " test failed" << std::endl; } } }
{ "alphanum_fraction": 0.5841346154, "author": null, "avg_line_length": 26.2342342342, "converted": null, "ext": "cc", "file": null, "hexsha": "90a75352b9dae0c80fa059c4aae596420f8eb9b8", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "frxstrem/fys3150", "max_forks_repo_path": "project2/code-fredrik/b.test.cc", "max_issues_count": null, "max_issues_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "frxstrem/fys3150", "max_issues_repo_path": "project2/code-fredrik/b.test.cc", "max_line_length": 100, "max_stars_count": null, "max_stars_repo_head_hexsha": "35c0310f48fca07444ec5924267bf646d121b147", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "frxstrem/fys3150", "max_stars_repo_path": "project2/code-fredrik/b.test.cc", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 987, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2912 }
from sklearn.utils.class_weight import compute_class_weight from sklearn import metrics as skmetrics import matplotlib.pyplot as plt import pandas as pd import numpy as np import inspect def calc_metrics(metrics: list, y_true: np.array, y_pred: np.array or None = None, y_score: np.array or None = None) -> dict: """ Given a list of Scikit-Learn supported metrics (https://scikit-learn.org/stable/modules/model_evaluation.html) or callable functions with signature 'y_true', 'y_pred' and 'y_score', return a dictionary of results after checking that the required inputs are provided. Parameters ---------- metrics: list List of string values; names of required metrics y_true: numpy.ndarray True labels or binary label indicators. The binary and multiclass cases expect labels with shape (n_samples,) while the multilabel case expects binary label indicators with shape (n_samples, n_classes). y_pred: numpy.ndarray Estimated targets as returned by a classifier y_score: numpy.ndarray Target scores. In the binary and multilabel cases, these can be either probability estimates or non-thresholded decision values (as returned by decision_function on some classifiers). In the multiclass case, these must be probability estimates which sum to 1. The binary case expects a shape (n_samples,), and the scores must be the scores of the class with the greater label. The multiclass and multilabel cases expect a shape (n_samples, n_classes). In the multiclass case, the order of the class scores must correspond to the order of labels, if provided, or else to the numerical or lexicographical order of the labels in y_true. Returns ------- dict Dictionary of performance metrics Raises ------ AssertionError F1 score requested yet y_pred is missing AttributeError Requested metric requires probability scores and y_score is None ValueError Invalid metric provided; possibly missing signatures: 'y_true', 'y_score' or 'y_pred' """ results = dict() i = 1 for m in metrics: if callable(m): results[f"custom_metric_{i}"] = m(y_true=y_true, y_pred=y_pred, y_score=y_score) i += 1 continue if "f1" in m: avg = m.split("_") if len(avg) == 2: avg = m.split("_")[1] else: avg = None f = getattr(skmetrics, "f1_score") assert y_pred is not None, "For F1 score predictions must be provided;`y_pred` is None" results[m] = f(y_true=y_true, y_pred=y_pred, average=avg) elif m == "roc_auc_score": f = getattr(skmetrics, m) results[m] = f(y_true=y_true, y_score=y_score, multi_class="ovo", average="macro") else: f = getattr(skmetrics, m) if "y_score" in inspect.signature(f).parameters.keys(): if y_score is None: raise AttributeError(f"Metric requested ({m}) requires probabilities of positive class but " f"y_score not provided; y_score is None.") results[m] = f(y_true=y_true, y_score=y_score) elif "y_pred" in inspect.signature(f).parameters.keys(): results[m] = f(y_true=y_true, y_pred=y_pred) else: raise ValueError("Unexpected metric. Signature should contain either 'y_score' or 'y_pred'") return results def confusion_matrix_plots(classifier, x: pd.DataFrame, y: np.ndarray, class_labels: list, cmap: str or None = None, figsize: tuple = (8, 20), **kwargs): """ Generate a figure of two heatmaps showing a confusion matrix, one normalised by support one showing raw values, displaying a classifiers performance. Returns Matplotlib.Figure object. Parameters ---------- classifier: object Scikit-Learn classifier x: Pandas.DataFrame Feature space y: numpy.ndarray Labels class_labels: list Class labels (as they should be displayed on the axis) cmap: str Colour scheme, defaults to Matplotlib Blues figsize: tuple (default=(10,5)) Size of the figure kwargs: Additional keyword arguments passed to sklearn.metrics.plot_confusion_matrix Returns ------- Matplotlib.Figure """ cmap = cmap or plt.get_cmap("Blues") fig, axes = plt.subplots(2, 1, figsize=figsize) titles = ["Confusion matrix, without normalisation", "Confusion matrix; normalised"] for i, (title, norm) in enumerate(zip(titles, [None, 'true'])): skmetrics.plot_confusion_matrix(classifier, x, y, display_labels=class_labels, cmap=cmap, normalize=norm, ax=axes[i], **kwargs) axes[i].set_title(title) axes[i].set_xticklabels(axes[i].get_xticklabels(), rotation=90) axes[i].grid(False) fig.tight_layout() return fig def assert_population_labels(ref, expected_labels: list): """ Given some reference FileGroup and the expected population labels, check the validity of the labels and return list of valid populations only. Parameters ---------- ref: FileGroup expected_labels: list Returns ------- List Raises ------- AssertionError Ref missing expected populations """ assert len(ref.populations) >= 2, "Reference sample does not contain any gated populations" for x in expected_labels: assert x in ref.tree.keys(), f"Ref FileGroup missing expected population {x}" def check_downstream_populations(ref, root_population: str, population_labels: list) -> None: """ Check that in the ordered list of population labels, all populations are downstream of the given 'root' population. Parameters ---------- ref: FileGroup root_population: str population_labels: list Returns ------- None Raises ------ AssertionError One or more populations not downstream of root """ downstream = ref.list_downstream_populations(root_population) assert all([x in downstream for x in population_labels]), \ "The first population in population_labels should be the 'root' population, with all further populations " \ "being downstream from this 'root'. The given population_labels has one or more populations that is not " \ "downstream from the given root." def multilabel(ref, root_population: str, population_labels: list, features: list) -> (pd.DataFrame, pd.DataFrame): """ Load the root population DataFrame from the reference FileGroup (assumed to be the first population in 'population_labels'). Then iterate over the remaining population creating a dummy matrix of population affiliations for each row of the root population. Parameters ---------- ref: FileGroup root_population: str population_labels: list features: list Returns ------- (Pandas.DataFrame, Pandas.DataFrame) Root population flourescent intensity values, population affiliations (dummy matrix) """ root = ref.load_population_df(population=root_population, transform=None) for pop in population_labels: root[pop] = 0 root.loc[ref.get_population(pop).index, pop] = 1 return root[features], root[population_labels] def singlelabel(ref, root_population: str, population_labels: list, features: list) -> (pd.DataFrame, np.ndarray): """ Load the root population DataFrame from the reference FileGroup (assumed to be the first population in 'population_labels'). Then iterate over the remaining population creating a Array of population affiliations; each cell (row) is associated to their terminal leaf node in the FileGroup population tree. Parameters ---------- root_population ref: FileGroup population_labels: list features: list Returns ------- (Pandas.DataFrame, numpy.ndarray) Root population flourescent intensity values, labels """ root = ref.load_population_df(population=root_population, transform=None) root["label"] = 0 for i, pop in enumerate(population_labels): pop_idx = ref.get_population(population_name=pop).index root.loc[pop_idx, "label"] = i + 1 y = root["label"].values root.drop("label", axis=1, inplace=True) return root[features], y def auto_weights(y: np.ndarray): """ Estimate optimal weights from a list of class labels. Parameters ---------- y: numpy.ndarray Returns ------- dict Dictionary of class weights {label: weight} """ classes = np.unique(y) weights = compute_class_weight('balanced', classes=classes, y=y) return {i: w for i, w in enumerate(weights)}
{ "alphanum_fraction": 0.6057358645, "author": null, "avg_line_length": 35.6290909091, "converted": null, "ext": "py", "file": null, "hexsha": "0c922e8504fe8d8ef4d6d0b35023c93a9574edbe", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 8, "max_forks_repo_forks_event_max_datetime": "2022-03-02T19:02:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-28T15:16:24.000Z", "max_forks_repo_head_hexsha": "8537d707fa25645b55b4ec1e25fff9f19847fb1b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JANHMS/CytoPy", "max_forks_repo_path": "cytopy/flow/cell_classifier/utils.py", "max_issues_count": 27, "max_issues_repo_head_hexsha": "8537d707fa25645b55b4ec1e25fff9f19847fb1b", "max_issues_repo_issues_event_max_datetime": "2022-03-01T20:43:34.000Z", "max_issues_repo_issues_event_min_datetime": "2020-04-07T14:59:24.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "JANHMS/CytoPy", "max_issues_repo_path": "cytopy/flow/cell_classifier/utils.py", "max_line_length": 116, "max_stars_count": 41, "max_stars_repo_head_hexsha": "8537d707fa25645b55b4ec1e25fff9f19847fb1b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "JANHMS/CytoPy", "max_stars_repo_path": "cytopy/flow/cell_classifier/utils.py", "max_stars_repo_stars_event_max_datetime": "2022-03-11T17:17:18.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-08T11:01:28.000Z", "num_tokens": 2023, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 9798 }
\chapter{Conclusion} Conclusion
{ "alphanum_fraction": 0.84375, "author": null, "avg_line_length": 10.6666666667, "converted": null, "ext": "tex", "file": null, "hexsha": "a56125ce987f1cb9a5d1edd249e1036b42bd337b", "include": null, "lang": "TeX", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5d755c96cf6cbece2c382789015e9db9ceb02da7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hfan36/dissertation", "max_forks_repo_path": "Chapters/chap-conclusion.tex", "max_issues_count": null, "max_issues_repo_head_hexsha": "5d755c96cf6cbece2c382789015e9db9ceb02da7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "hfan36/dissertation", "max_issues_repo_path": "Chapters/chap-conclusion.tex", "max_line_length": 20, "max_stars_count": null, "max_stars_repo_head_hexsha": "5d755c96cf6cbece2c382789015e9db9ceb02da7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hfan36/dissertation", "max_stars_repo_path": "Chapters/chap-conclusion.tex", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 32 }
MODULE grid ! Based on grid of femswe, with additional variables of other files IMPLICIT NONE ! COUNTING ! Number of grids in multigrid hierarchy INTEGER :: ngrids ! nface Number of faces on each grid ! nedge Number of edges on each grid ! nvert Number of vertices on each edge INTEGER, ALLOCATABLE :: nface(:), nedge(:), nvert(:) INTEGER :: nfacex, nedgex, nvertx ! neoff Number of edges and vertices of each face on each grid ! neofv Number of edges of each vertex on each grid INTEGER, ALLOCATABLE :: neoff(:,:), neofv(:,:) INTEGER :: nefmx, nevmx ! CONNECTIVITY ! fnxtf Faces next to each face on each grid ! eoff Edges of each face on each grid ! voff Vertices of each face on each grid ! fnxte Faces either side of each edge on each grid ! vofe Vertices at the ends of each edge on each grid ! fofv Faces around each vertex on each grid ! eofv Edges incident on each vertex on each grid INTEGER, ALLOCATABLE :: fnxtf(:,:,:), eoff(:,:,:), voff(:,:,:), & fnxte(:,:,:), vofe(:,:,:), & fofv(:,:,:), eofv(:,:,:) ! Conventions ! ! 1. fnxtf and eoff are ordered anticlockwise and such that ! the i'th edge lies between the face in question and its i'th ! neighbour. ! ! 2. voff are ordered anticlockwise such that the k'th vertex ! is the common vertex of the k'th and (k+1)'th edge. ! ! 3. eofv are ordered anticlockwise. ! ! 4. fofv are ordered anticlockwise such that the k'th face lies ! between the k'th and (k+1)'th edge. ! ! 5. The positive normal direction n points from ! fnxte(:,1,:) -> fnxte(:,2,:) ! and the positive tangential direction t points from ! vofe(:,1,:) -> vofe(:,2,:) ! such that t = k x n (where k is vertical). ! eoffin(f,j,:) Indicates whether the normal at the j'th edge is ! inward or outward relative to face f. ! eofvin(v,j,:) Indicates whether the tangent at the j'th edge is ! inward or outward relative to vertex v. INTEGER, ALLOCATABLE :: eoffin(:,:,:), eofvin(:,:,:) ! COORDINATES AND GEOMETRICAL INFORMATION ! flong Longitude of faces on each grid ! flat Latitude of faces on each grid ! vlong Longitude of vertices on each grid ! vlat Latitude of vertices on each grid ! farea Area of faces on each grid ! varea Area of dual faces on each grid ! ldist Primal edge length, i.e. distance between neighbouring face centres ! ddist Dual edge length, i.e. distance between neighbouring vertices ! fareamin Minimum face area on each grid REAL*8, ALLOCATABLE :: flong(:,:), flat(:,:), & vlong(:,:), vlat(:,:), & farea(:,:), varea(:,:), & ldist(:,:), ddist(:,:), & fareamin(:) ! Conventions ! ! Latitude and longitude in radians. ! Area and lengths are for the unit sphere. ! HODGE STAR, MASS MATRIX, AND RELATED OPERATORS ! nlsten Number of faces in stencil for L mass matrix ! lsten Stencil for L mass matrix ! lmass Coefficients for L mass matrix ! nmsten Number of faces in stencil for M mass matrix ! msten Stencil for M mass matrix ! mmass Coefficients for M mass matrix ! njsten Number of vertices in stencil for J operator ! jsten Stencil for J operator ! jstar Coefficients for J operator ! nhsten Number of edges in stencil for H operator ! hsten Stencil for H operator ! hstar Coefficients for H operator ! nrsten Number of vertices in stencil for R operator (= neoff) ! rsten Stencil for R operator (= voff) ! rcoeff Coefficients for R operator ! nrxsten Number of faces in stencil for R transpose operator (= neofv) ! rxsten Stencil for R transpose operator (= fofv) ! rxcoeff Coefficients for R transpose operator ! nwsten Number of edges in stencil for W operator ! wsten Stencil for W operator ! wcoeff Coefficients for W operator ! ntsten Number of edges in stencel for T operator ! tsten Stencil for T operator ! tcoeff Coefficients for T operator ! jlump Coefficients of lumped J matrix ! mlump Coefficients of lumped M matrix ! hlump Coefficients of lumped H matrix ! nxminvten Number of edges in stencil for approximate inverse of M ! xminvsten Stencil for approximate inverse of M ! xminv Coefficients for approximate inverse of M INTEGER, ALLOCATABLE :: nlsten(:,:), nmsten(:,:), njsten(:,:), & nhsten(:,:), nrsten(:,:), nrxsten(:,:), & nwsten(:,:), ntsten(:,:), nxminvsten(:,:) INTEGER, ALLOCATABLE :: lsten(:,:,:), msten(:,:,:), jsten(:,:,:), & hsten(:,:,:), rsten(:,:,:), rxsten(:,:,:), & wsten(:,:,:), tsten(:,:,:), xminvsten(:,:,:) REAL*8, ALLOCATABLE :: lmass(:,:,:), mmass(:,:,:), jstar(:,:,:), & hstar(:,:,:), rcoeff(:,:,:), rxcoeff(:,:,:), & wcoeff(:,:,:), tcoeff(:,:,:,:), jlump(:,:), & mlump(:,:), hlump(:,:), xminv(:,:,:) INTEGER :: nlsmx, nmsmx, njsmx, nhsmx, nrsmx, nrxsmx, nwsmx, ntsmx, nxmisx ! RESTRICTION AND PROLONGATION OPERATORS FOR MULTIGRID ! nres Number of faces in stencil for restriction operator ! ressten Stencil for restriction operator ! reswgt Weights for restriction operator INTEGER, ALLOCATABLE :: nres(:,:), ressten(:,:,:) REAL*8, ALLOCATABLE :: reswgt(:,:,:) INTEGER :: nresmx INTEGER, ALLOCATABLE :: ninj(:,:), injsten(:,:,:) REAL*8, ALLOCATABLE :: injwgt(:,:,:) INTEGER :: ninjmx ! 0: no SFC optimization applied ! 1: SFC optimization applied and SFC Index information appended INTEGER :: SFCIndexAvailable INTEGER, ALLOCATABLE :: fNewFaceId(:,:), fNewFaceIdInverse(:,:), & fNewVertId(:,:), fNewVertIdInverse(:,:), & fNewEdgeId(:,:), fNewEdgeIdInverse(:,:) ! Additional variables from grid_hex INTEGER, ALLOCATABLE :: feofe(:,:,:) REAL*8, ALLOCATABLE :: gdist(:,:), coeff(:,:,:) ! Additional variables from grid_cube ! n x n cells on each panel ! Smallest and largest n INTEGER :: n0 INTEGER :: nl INTEGER :: nx2 ! Number of smoothing iterations. Must be at least 1 for ! consistency of H operator. INTEGER :: nsmooth = 1 ! Additional variables from grid_buildop ! Grid type (just used to determine file names) ! igtype 1 for hex, 2 for cube INTEGER :: igtype REAL*8, ALLOCATABLE :: elong(:,:), elat(:,:) ! INFORMATION DEFINING COMPOUND ELEMENTS ! ncvp Number of internal dofs to define a compound ! P0 element in space Vp. ! cvp Dofs to define a compound element in space Vp. ! ncsp Number of internal dofs to define a compound ! RT0 element in space Sp. ! csp Dofs to define a compound element in space Sp. ! ncep Number of internal dofs to define a compound ! P1 element in space Ep. ! cep Dofs to define a compound element in space Ep. ! ncvd Number of internal dofs to define a compound ! P0 element in space Vd. ! cvd Dofs to define a compound element in space Vp. ! ncsd Number of internal dofs to define a compound ! N0 element in space Sd. ! csd Dofs to define a compound element in space Sd. INTEGER, ALLOCATABLE :: ncvp(:), ncsp(:), ncep(:), & ncvd(:), ncsd(:) REAL*8, ALLOCATABLE :: cvp(:,:), csp(:,:), cep(:,:), & cvd(:,:), csd(:,:) INTEGER :: ncvpmx, ncspmx, ncepmx, ncvdmx, ncsdmx ! Variables for lat-lon grid table - P. Peixoto INTEGER*4, ALLOCATABLE :: lltable_primal(:,:), lltable_dual(:,:) INTEGER :: lltable_nlat, lltable_nlon END MODULE grid
{ "alphanum_fraction": 0.6151699645, "author": null, "avg_line_length": 37.5428571429, "converted": null, "ext": "f90", "file": null, "hexsha": "4055bc0d626daa75f3249c34e1cfb8a4678e0916", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 14, "max_forks_repo_forks_event_max_datetime": "2021-09-01T10:38:57.000Z", "max_forks_repo_forks_event_min_datetime": "2016-03-18T19:24:56.000Z", "max_forks_repo_head_hexsha": "8dd39e3564b6bc01df8dfe417493d9c7b22c40a8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "luanfs/iModel", "max_forks_repo_path": "mfem_swm/grid.f90", "max_issues_count": 2, "max_issues_repo_head_hexsha": "8dd39e3564b6bc01df8dfe417493d9c7b22c40a8", "max_issues_repo_issues_event_max_datetime": "2021-03-18T18:07:53.000Z", "max_issues_repo_issues_event_min_datetime": "2018-08-29T11:49:32.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "luanfs/iModel", "max_issues_repo_path": "mfem_swm/grid.f90", "max_line_length": 82, "max_stars_count": 10, "max_stars_repo_head_hexsha": "8dd39e3564b6bc01df8dfe417493d9c7b22c40a8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "luanfs/iModel", "max_stars_repo_path": "mfem_swm/grid.f90", "max_stars_repo_stars_event_max_datetime": "2021-06-10T01:56:33.000Z", "max_stars_repo_stars_event_min_datetime": "2015-10-09T17:44:51.000Z", "num_tokens": 2120, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 7884 }
#include <stdio.h> #include <gsl/gsl_linalg.h> double A[] = { -1.0, 0.0, 2.0, 1.0, 0.0, -1.0, 3.0, 2.0, 1.0, 2.0, 3.0, 0.0, -3.0, 1.0, 4.0, 2.0 }; double y[] = { 0.0, 1.0, 2.0, 1.0 }; int main() { gsl_matrix_view m = gsl_matrix_view_array(A, 4, 4); gsl_vector_view b = gsl_vector_view_array(y, 4); gsl_vector* x = gsl_vector_alloc(4); int s; gsl_permutation* p = gsl_permutation_alloc(4); gsl_linalg_LU_decomp(&m.matrix, p, &s); gsl_linalg_LU_solve(&m.matrix, p, &b.vector, x); printf("x = \n"); gsl_vector_fprintf(stdout, x, "%5.1f"); gsl_permutation_free(p); gsl_vector_free(x); return 0; }
{ "alphanum_fraction": 0.6148969889, "author": null, "avg_line_length": 20.3548387097, "converted": null, "ext": "c", "file": null, "hexsha": "f466e06136b6eb53c937e32ddafe8500c5ad2c5e", "include": null, "lang": "C", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_forks_repo_licenses": [ "FSFAP" ], "max_forks_repo_name": "julnamoo/practice-linux", "max_forks_repo_path": "src_book0/ex10/list1032/list1032B.c", "max_issues_count": null, "max_issues_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "FSFAP" ], "max_issues_repo_name": "julnamoo/practice-linux", "max_issues_repo_path": "src_book0/ex10/list1032/list1032B.c", "max_line_length": 53, "max_stars_count": 1, "max_stars_repo_head_hexsha": "ed0cbb5f62d54af5ca4691d18db09069097c064a", "max_stars_repo_licenses": [ "FSFAP" ], "max_stars_repo_name": "julnamoo/practice-linux", "max_stars_repo_path": "src_book0/ex10/list1032/list1032B.c", "max_stars_repo_stars_event_max_datetime": "2018-09-14T05:43:58.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-14T05:43:58.000Z", "num_tokens": 275, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 631 }
c subroutine newtil(tilseq,ntill,iplane,oldind) c c on the first day of simulation and at the end of a tilage day c the next tilage date is found integer tilseq, ntill,iplane,oldind include 'pmxpln.inc' include 'pmxtil.inc' include 'pmxtls.inc' c include 'cupdate.inc' c c oldind - old tilage index c newind - new tilage index c integer newind,indtil c oldind = indxy(iplane) newind = 0 do 10 indtil = 1, ntill if (oldind.eq.0) then if (newind.eq.0) then if (mdate(indtil,tilseq).gt.sdate) newind = indtil else if (mdate(indtil,tilseq).lt.mdate(newind,tilseq).and. 1 mdate(indtil,tilseq).gt.sdate) then newind = indtil end if else if (newind.eq.0) then if (mdate(indtil,tilseq).gt.mdate(oldind,tilseq)) newind = 1 indtil else if (mdate(indtil,tilseq).lt.mdate(newind,tilseq).and. 1 mdate(indtil,tilseq).gt.mdate(oldind,tilseq)) then newind = indtil end if end if 10 continue if (newind.eq.0) then indxy(iplane) = oldind else indxy(iplane) = newind end if c return end
{ "alphanum_fraction": 0.5802861685, "author": null, "avg_line_length": 27.347826087, "converted": null, "ext": "for", "file": null, "hexsha": "adee22707ed507c013fba91758c4359f3680392d", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-12-09T15:49:00.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-02T22:59:38.000Z", "max_forks_repo_head_hexsha": "7189a26fbcec3d8c3cc7d7015107b8fb6c5f6a45", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "akrherz/idep", "max_forks_repo_path": "src/wepp2012-src/newtil.for", "max_issues_count": 54, "max_issues_repo_head_hexsha": "fe73982f4c70039e1a31b9e8e2d9aac31502f803", "max_issues_repo_issues_event_max_datetime": "2022-03-28T19:14:25.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-12T18:02:31.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jarad/dep", "max_issues_repo_path": "src/wepp2012-src/newtil.for", "max_line_length": 70, "max_stars_count": 1, "max_stars_repo_head_hexsha": "fe73982f4c70039e1a31b9e8e2d9aac31502f803", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jarad/dep", "max_stars_repo_path": "src/wepp2012-src/newtil.for", "max_stars_repo_stars_event_max_datetime": "2019-11-26T17:49:19.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-26T17:49:19.000Z", "num_tokens": 412, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 1258 }
using Weave nkwds = (out_path = "notebooks/", jupyter_path = "$(homedir())/.julia/conda/3/bin/jupyter", nbconvert_options = "--allow-errors") skwds = (out_path = "sheets/", jupyter_path = "$(homedir())/.julia/conda/3/bin/jupyter", nbconvert_options = "--allow-errors") ## # notes ## notebook("src/Julia.jmd"; nkwds...) notebook("src/Asymptotics.jmd"; nkwds...) notebook("src/SpectralTheorem.jmd"; nkwds...) notebook("src/Numbers.jmd"; nkwds...) notebook("src/Differentiation.jmd"; nkwds...) notebook("src/StructuredMatrices.jmd"; nkwds...) notebook("src/Decompositions.jmd"; nkwds...) notebook("src/SingularValues.jmd"; nkwds...) notebook("src/DifferentialEquations.jmd"; nkwds...) notebook("src/Fourier.jmd"; nkwds...) notebook("src/OrthogonalPolynomials.jmd"; nkwds...) notebook("src/Quadrature.jmd"; nkwds...) notebook("src/Applications.jmd"; nkwds...) ## # problem sheets ## notebook("src/week1.jmd"; skwds...) notebook("src/week2.jmd"; skwds...) notebook("src/week4.jmd"; skwds...) notebook("src/week5.jmd"; skwds...) notebook("src/advanced1.jmd"; skwds...) notebook("src/advanced2.jmd"; skwds...) notebook("src/advanced3.jmd"; skwds...) ## # solutions ### notebook("src/week1s.jmd"; skwds...) notebook("src/week2s.jmd"; skwds...) notebook("src/week3s.jmd"; skwds...) notebook("src/week4s.jmd"; skwds...) notebook("src/week5s.jmd"; skwds...) notebook("src/week6s.jmd"; skwds...) notebook("src/week7s.jmd"; skwds...) notebook("src/week8s.jmd"; skwds...) ## # exams ## notebook("src/practice.jmd"; skwds...) notebook("src/practices.jmd"; skwds...) ## # extras ## notebook("src/juliasheet.jmd"; skwds...)
{ "alphanum_fraction": 0.6806153846, "author": null, "avg_line_length": 24.2537313433, "converted": null, "ext": "jl", "file": null, "hexsha": "6da19c39588851ba4ad0776e12274934694a4f28", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "94d6814d5fe24a26b05951e002e8fc2dcb543e47", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "NiallOswald/MATH50003NumericalAnalysis", "max_forks_repo_path": "src/MATH50003NumericalAnalysis.jl", "max_issues_count": null, "max_issues_repo_head_hexsha": "94d6814d5fe24a26b05951e002e8fc2dcb543e47", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "NiallOswald/MATH50003NumericalAnalysis", "max_issues_repo_path": "src/MATH50003NumericalAnalysis.jl", "max_line_length": 129, "max_stars_count": 1, "max_stars_repo_head_hexsha": "94d6814d5fe24a26b05951e002e8fc2dcb543e47", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "NiallOswald/MATH50003NumericalAnalysis", "max_stars_repo_path": "src/MATH50003NumericalAnalysis.jl", "max_stars_repo_stars_event_max_datetime": "2022-02-03T15:13:47.000Z", "max_stars_repo_stars_event_min_datetime": "2022-02-03T15:13:47.000Z", "num_tokens": 560, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 1625 }
r""" Bijection classes for type `A_{2n}^{(2)\dagger}` Part of the (internal) classes which runs the bijection between rigged configurations and KR tableaux of type `A_{2n}^{(2)\dagger}`. AUTHORS: - Travis Scrimshaw (2012-12-21): Initial version TESTS:: sage: KRT = crystals.TensorProductOfKirillovReshetikhinTableaux(CartanType(['A', 4, 2]).dual(), [[2, 1]]) sage: from sage.combinat.rigged_configurations.bij_type_A2_dual import KRTToRCBijectionTypeA2Dual sage: bijection = KRTToRCBijectionTypeA2Dual(KRT(pathlist=[[2,1]])) sage: TestSuite(bijection).run() sage: RC = RiggedConfigurations(CartanType(['A', 4, 2]).dual(), [[2, 1]]) sage: from sage.combinat.rigged_configurations.bij_type_A2_dual import RCToKRTBijectionTypeA2Dual sage: bijection = RCToKRTBijectionTypeA2Dual(RC(partition_list=[[],[]])) sage: TestSuite(bijection).run() """ #***************************************************************************** # Copyright (C) 2012 Travis Scrimshaw <tscrim@ucdavis.edu> # # Distributed under the terms of the GNU General Public License (GPL) # # This code is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # The full text of the GPL is available at: # # http://www.gnu.org/licenses/ #***************************************************************************** from sage.combinat.rigged_configurations.bij_type_C import KRTToRCBijectionTypeC from sage.combinat.rigged_configurations.bij_type_C import RCToKRTBijectionTypeC from sage.combinat.rigged_configurations.bij_type_A import KRTToRCBijectionTypeA from sage.rings.all import QQ class KRTToRCBijectionTypeA2Dual(KRTToRCBijectionTypeC): r""" Specific implementation of the bijection from KR tableaux to rigged configurations for type `A_{2n}^{(2)\dagger}`. This inherits from type `C_n^{(1)}` because we use the same methods in some places. """ def next_state(self, val): r""" Build the next state for type `A_{2n}^{(2)\dagger}`. TESTS:: sage: KRT = crystals.TensorProductOfKirillovReshetikhinTableaux(CartanType(['A', 4, 2]).dual(), [[2,1]]) sage: from sage.combinat.rigged_configurations.bij_type_A2_dual import KRTToRCBijectionTypeA2Dual sage: bijection = KRTToRCBijectionTypeA2Dual(KRT(pathlist=[[-1,2]])) sage: bijection.cur_path.insert(0, []) sage: bijection.cur_dims.insert(0, [0, 1]) sage: bijection.cur_path[0].insert(0, [2]) sage: bijection.next_state(2) """ n = self.n tableau_height = len(self.cur_path[0]) - 1 if val > 0: # If it is a regular value, we follow the A_n rules KRTToRCBijectionTypeA.next_state(self, val) return pos_val = -val if pos_val == 0: if len(self.ret_rig_con[pos_val - 1]) > 0: max_width = self.ret_rig_con[n-1][0] else: max_width = 1 max_width = self.ret_rig_con[n-1].insert_cell(max_width) width_n = max_width + 1 # Follow regular A_n rules for a in reversed(range(tableau_height, n-1)): max_width = self.ret_rig_con[a].insert_cell(max_width) self._update_vacancy_nums(a + 1) self._update_partition_values(a + 1) self._update_vacancy_nums(tableau_height) self._update_partition_values(tableau_height) if tableau_height > 0: self._update_vacancy_nums(tableau_height-1) self._update_partition_values(tableau_height-1) # Make the new string at n quasi-singular p = self.ret_rig_con[n-1] for i in range(len(p)): if p._list[i] == width_n: p.rigging[i] = p.rigging[i] - QQ(1)/QQ(2) break return case_S = [None] * n pos_val = -val # Always add a cell to the first singular value in the first # tableau we are updating. if len(self.ret_rig_con[pos_val - 1]) > 0: max_width = self.ret_rig_con[pos_val - 1][0] else: max_width = 1 # Add cells similar to type A_n but we move to the right until we # reach the value of n-1 for a in range(pos_val - 1, n-1): max_width = self.ret_rig_con[a].insert_cell(max_width) case_S[a] = max_width # Special case for n # If we find a quasi-singular string first, then we are in case (Q, S) # otherwise we will find a singular string and insert 2 cells partition = self.ret_rig_con[n-1] num_rows = len(partition) case_QS = False for i in range(num_rows + 1): if i == num_rows: max_width = 0 if case_QS: partition._list.append(1) partition.vacancy_numbers.append(None) # Go through our partition until we find a length of greater than 1 j = len(partition._list) - 1 while j >= 0 and partition._list[j] == 1: j -= 1 partition.rigging.insert(j + 1, None) width_n = 1 else: # Go through our partition until we find a length of greater than 2 j = len(partition._list) - 1 while j >= 0 and partition._list[j] <= 2: j -= 1 partition._list.insert(j+1, 2) partition.vacancy_numbers.insert(j+1, None) partition.rigging.insert(j+1, None) break elif partition._list[i] <= max_width: if partition.vacancy_numbers[i] == partition.rigging[i]: max_width = partition._list[i] if case_QS: partition._list[i] += 1 width_n = partition._list[i] partition.rigging[i] = None else: j = i - 1 while j >= 0 and partition._list[j] <= max_width + 2: partition.rigging[j+1] = partition.rigging[j] # Shuffle it along j -= 1 partition._list.pop(i) partition._list.insert(j+1, max_width + 2) partition.rigging[j+1] = None break elif partition.vacancy_numbers[i] - QQ(1)/QQ(2) == partition.rigging[i] and not case_QS: case_QS = True partition._list[i] += 1 partition.rigging[i] = None # No need to set max_width here since we will find a singular string # Now go back following the regular C_n (ish) rules for a in reversed(range(tableau_height, n-1)): if case_S[a] == max_width: self._insert_cell_case_S(self.ret_rig_con[a]) else: max_width = self.ret_rig_con[a].insert_cell(max_width) self._update_vacancy_nums(a + 1) self._update_partition_values(a + 1) # Update the final rigged partitions if tableau_height < n: self._update_vacancy_nums(tableau_height) self._update_partition_values(tableau_height) if pos_val <= tableau_height: for a in range(pos_val-1, tableau_height): self._update_vacancy_nums(a) self._update_partition_values(a) if pos_val > 1: self._update_vacancy_nums(pos_val - 2) self._update_partition_values(pos_val - 2) elif tableau_height > 0: self._update_vacancy_nums(tableau_height - 1) self._update_partition_values(tableau_height - 1) if case_QS: # Make the new string quasi-singular num_rows = len(partition) for i in range(num_rows): if partition._list[i] == width_n: partition.rigging[i] = partition.rigging[i] - QQ(1)/QQ(2) break class RCToKRTBijectionTypeA2Dual(RCToKRTBijectionTypeC): r""" Specific implementation of the bijection from rigged configurations to tensor products of KR tableaux for type `A_{2n}^{(2)\dagger}`. """ def next_state(self, height): r""" Build the next state for type `A_{2n}^{(2)\dagger}`. TESTS:: sage: RC = RiggedConfigurations(CartanType(['A', 4, 2]).dual(), [[2,1]]) sage: from sage.combinat.rigged_configurations.bij_type_A2_dual import RCToKRTBijectionTypeA2Dual sage: bijection = RCToKRTBijectionTypeA2Dual(RC(partition_list=[[2],[2,2]])) sage: bijection.next_state(2) -1 """ height -= 1 # indexing n = self.n ell = [None] * (2*n) case_S = [False] * n case_Q = False b = None # Calculate the rank and ell values last_size = 0 for a in range(height, n-1): ell[a] = self._find_singular_string(self.cur_partitions[a], last_size) if ell[a] is None: b = a + 1 break else: last_size = self.cur_partitions[a][ell[a]] if b is None: partition = self.cur_partitions[n-1] # Special case for n for i in reversed(range(len(partition))): if partition[i] >= last_size: if partition.vacancy_numbers[i] == partition.rigging[i]: last_size = partition[i] case_S[n-1] = True ell[2*n-1] = i break elif partition.vacancy_numbers[i] - QQ(1)/QQ(2) == partition.rigging[i] and not case_Q: case_Q = True # This will never be singular last_size = partition[i] + 1 ell[n-1] = i if ell[2*n-1] is None: if not case_Q: b = n else: b = 0 if b is None: # Now go back for a in reversed(range(n-1)): if a >= height and self.cur_partitions[a][ell[a]] == last_size: ell[n+a] = ell[a] case_S[a] = True else: ell[n+a] = self._find_singular_string(self.cur_partitions[a], last_size) if ell[n + a] is None: b = -(a + 2) break else: last_size = self.cur_partitions[a][ell[n + a]] if b is None: b = -1 # Determine the new rigged configuration by removing boxes from the # selected string and then making the new string singular if n > 1: if case_S[0]: row_num = None row_num_bar = self.cur_partitions[0].remove_cell(ell[n], 2) else: row_num = self.cur_partitions[0].remove_cell(ell[0]) row_num_bar = self.cur_partitions[0].remove_cell(ell[n]) for a in range(1, n-1): if case_S[a]: row_num_next = None row_num_bar_next = self.cur_partitions[a].remove_cell(ell[n+a], 2) else: row_num_next = self.cur_partitions[a].remove_cell(ell[a]) row_num_bar_next = self.cur_partitions[a].remove_cell(ell[n+a]) self._update_vacancy_numbers(a - 1) if row_num is not None: self.cur_partitions[a-1].rigging[row_num] = self.cur_partitions[a-1].vacancy_numbers[row_num] if row_num_bar is not None: self.cur_partitions[a-1].rigging[row_num_bar] = self.cur_partitions[a-1].vacancy_numbers[row_num_bar] row_num = row_num_next row_num_bar = row_num_bar_next if case_Q: row_num_next = self.cur_partitions[n-1].remove_cell(ell[n-1]) if case_S[n-1]: row_num_bar_next = self.cur_partitions[n-1].remove_cell(ell[2*n-1]) else: row_num_bar_next = None elif case_S[n-1]: row_num_next = None row_num_bar_next = self.cur_partitions[n-1].remove_cell(ell[2*n-1], 2) else: row_num_next = None row_num_bar_next = None if n > 1: self._update_vacancy_numbers(n - 2) if row_num is not None: self.cur_partitions[n-2].rigging[row_num] = self.cur_partitions[n-2].vacancy_numbers[row_num] if row_num_bar is not None: self.cur_partitions[n-2].rigging[row_num_bar] = self.cur_partitions[n-2].vacancy_numbers[row_num_bar] self._update_vacancy_numbers(n - 1) if row_num_next is not None: self.cur_partitions[n-1].rigging[row_num_next] = self.cur_partitions[n-1].vacancy_numbers[row_num_next] if row_num_bar_next is not None: if case_Q: # This will always be the largest value self.cur_partitions[n-1].rigging[row_num_bar_next] = self.cur_partitions[n-1].vacancy_numbers[row_num_bar_next] - QQ(1)/QQ(2) else: self.cur_partitions[n-1].rigging[row_num_bar_next] = self.cur_partitions[n-1].vacancy_numbers[row_num_bar_next] return(b)
{ "alphanum_fraction": 0.5534527593, "author": null, "avg_line_length": 41.2023809524, "converted": null, "ext": "py", "file": null, "hexsha": "50533fbc842998027fb3fc161410432c0674050d", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-07-23T10:40:14.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-23T10:40:14.000Z", "max_forks_repo_head_hexsha": "468f23815ade42a2192b0a9cd378de8fdc594dcd", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "dimpase/sage", "max_forks_repo_path": "src/sage/combinat/rigged_configurations/bij_type_A2_dual.py", "max_issues_count": 1, "max_issues_repo_head_hexsha": "467fbc70a08b552b3de33d9065204ee9cbfb02c7", "max_issues_repo_issues_event_max_datetime": "2020-04-18T16:30:43.000Z", "max_issues_repo_issues_event_min_datetime": "2020-04-18T16:30:43.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "Ivo-Maffei/sage", "max_issues_repo_path": "src/sage/combinat/rigged_configurations/bij_type_A2_dual.py", "max_line_length": 141, "max_stars_count": 4, "max_stars_repo_head_hexsha": "765c5cb3e24dd134708eca97e4c52e0221cd94ba", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "fchapoton/sage", "max_stars_repo_path": "src/sage/combinat/rigged_configurations/bij_type_A2_dual.py", "max_stars_repo_stars_event_max_datetime": "2020-07-29T06:33:51.000Z", "max_stars_repo_stars_event_min_datetime": "2020-07-17T04:49:44.000Z", "num_tokens": 3423, "path": null, "reason": "from sage", "repo": null, "save_path": null, "sha": null, "size": 13844 }
#pragma once #include <memory> #include <boost/serialization/access.hpp> #include <boost/serialization/base_object.hpp> #include "Layer.hpp" #include "../optimizer/NeuralNetworkOptimizer.hpp" #include "NoNeuronLayer.hpp" namespace snn::internal { class MaxPooling2D final : public NoNeuronLayer { private: friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, unsigned version); protected: int sizeOfFilterMatrix; std::vector<int> shapeOfInput; std::vector<int> shapeOfOutput; public: MaxPooling2D() = default; // use restricted to Boost library only MaxPooling2D(LayerModel& model); MaxPooling2D(const MaxPooling2D&) = default; ~MaxPooling2D() = default; [[nodiscard]] std::unique_ptr<BaseLayer> clone(std::shared_ptr<NeuralNetworkOptimizer> optimizer) const; [[nodiscard]] std::vector<float> output(const std::vector<float>& inputs, bool temporalReset) override; [[nodiscard]] std::vector<float> outputForTraining(const std::vector<float>& inputs, bool temporalReset) override; [[nodiscard]] std::vector<float> backOutput(std::vector<float>& inputErrors) override; void train(std::vector<float>& inputErrors) override; [[nodiscard]] int getNumberOfInputs() const override; [[nodiscard]] std::vector<int> getShapeOfInput() const override; [[nodiscard]] std::vector<int> getShapeOfOutput() const override; [[nodiscard]] int isValid() const override; bool operator==(const BaseLayer& layer) const override; bool operator!=(const BaseLayer& layer) const override; }; template <class Archive> void MaxPooling2D::serialize(Archive& ar, [[maybe_unused]] const unsigned version) { boost::serialization::void_cast_register<MaxPooling2D, NoNeuronLayer>(); ar & boost::serialization::base_object<NoNeuronLayer>(*this); ar & this->sizeOfFilterMatrix; ar & this->shapeOfInput; } }
{ "alphanum_fraction": 0.6857697912, "author": null, "avg_line_length": 38.8490566038, "converted": null, "ext": "hpp", "file": null, "hexsha": "02e4ac668351b5ba1a0f93a41df97387a9eed1fb", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-02-16T22:13:22.000Z", "max_forks_repo_forks_event_min_datetime": "2020-08-07T10:53:52.000Z", "max_forks_repo_head_hexsha": "e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "MatthieuHernandez/StraightforwardNeuralNetwork", "max_forks_repo_path": "src/neural_network/layer/MaxPooling2D.hpp", "max_issues_count": 7, "max_issues_repo_head_hexsha": "e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7", "max_issues_repo_issues_event_max_datetime": "2021-05-08T17:11:12.000Z", "max_issues_repo_issues_event_min_datetime": "2020-08-07T11:08:45.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "MatthieuHernandez/StraightforwardNeuralNetwork", "max_issues_repo_path": "src/neural_network/layer/MaxPooling2D.hpp", "max_line_length": 122, "max_stars_count": 14, "max_stars_repo_head_hexsha": "e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "MatthieuHernandez/StraightforwardNeuralNetwork", "max_stars_repo_path": "src/neural_network/layer/MaxPooling2D.hpp", "max_stars_repo_stars_event_max_datetime": "2022-03-22T12:51:02.000Z", "max_stars_repo_stars_event_min_datetime": "2019-08-29T07:20:19.000Z", "num_tokens": 465, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2059 }
[STATEMENT] lemma rGamma_complex_of_real: "rGamma (complex_of_real x) = complex_of_real (rGamma x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. rGamma (complex_of_real x) = complex_of_real (rGamma x) [PROOF STEP] unfolding rGamma_real_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. rGamma (complex_of_real x) = complex_of_real (Re (rGamma (complex_of_real x))) [PROOF STEP] using rGamma_complex_real [PROOF STATE] proof (prove) using this: ?z \<in> \<real> \<Longrightarrow> rGamma ?z \<in> \<real> goal (1 subgoal): 1. rGamma (complex_of_real x) = complex_of_real (Re (rGamma (complex_of_real x))) [PROOF STEP] by simp
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": null, "hexsha": null, "include": null, "lang": null, "length": 3, "llama_tokens": 260, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": null }
""" """ import numpy as np from jax import random as jran from ..utils.galmatch import calculate_indx_correspondence def inherit_host_centric_posvel( ran_key, is_sat_source, is_sat_target, logmh_host_source, logmh_host_target, pos_host_source, pos_host_target, vel_host_source, vel_host_target, pos_source, vel_source, dlogmh=0.25, ): pos_sats, vel_sats = _inherit_host_centric_posvel_matching_mhost( ran_key, logmh_host_source[is_sat_source], logmh_host_target[is_sat_target], pos_host_source[is_sat_source], pos_host_target[is_sat_target], vel_host_source[is_sat_source], vel_host_target[is_sat_target], pos_source[is_sat_source], vel_source[is_sat_source], dlogmh, ) pos_target = np.copy(pos_host_target) vel_target = np.copy(vel_host_target) pos_target[is_sat_target] = pos_sats vel_target[is_sat_target] = vel_sats return pos_target, vel_target def _inherit_host_centric_posvel_matching_mhost( ran_key, logmh_host_source, logmh_host_target, pos_host_source, pos_host_target, vel_host_source, vel_host_target, pos_source, vel_source, dlogmh, ): delta_pos_source = pos_source - pos_host_source delta_vel_source = vel_source - vel_host_source source_key, target_key = jran.split(ran_key, 2) uran_source = np.array( (jran.uniform(source_key, shape=logmh_host_source.shape) - 0.5) * 0.05 ) uran_target = np.array( (jran.uniform(target_key, shape=logmh_host_target.shape) - 0.5) * dlogmh ) dd_match, indx_match = calculate_indx_correspondence( (logmh_host_source + uran_source,), (logmh_host_target + uran_target,) ) delta_pos_target = delta_pos_source[indx_match] delta_vel_target = delta_vel_source[indx_match] pos_target = pos_host_target + delta_pos_target vel_target = vel_host_target + delta_vel_target return pos_target, vel_target def add_central_velbias(is_cen_target, vel_source, vel_host_source, vel_host_target): delta_vel_source = vel_source - vel_host_source vel_target = np.copy(vel_host_target) vel_target[is_cen_target] = ( vel_target[is_cen_target] + delta_vel_source[is_cen_target] ) return vel_target
{ "alphanum_fraction": 0.7229122056, "author": null, "avg_line_length": 27.7976190476, "converted": null, "ext": "py", "file": null, "hexsha": "085c536234e2941b55f708754dd38bf24be8ee46", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-03-11T19:45:30.000Z", "max_forks_repo_forks_event_min_datetime": "2018-03-27T17:21:06.000Z", "max_forks_repo_head_hexsha": "d36d083c9eb688640670dbe066bf299777a78ba7", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "aphearin/c3dev", "max_forks_repo_path": "c3dev/galmocks/galhalo_models/galsampler_phase_space.py", "max_issues_count": 2, "max_issues_repo_head_hexsha": "d36d083c9eb688640670dbe066bf299777a78ba7", "max_issues_repo_issues_event_max_datetime": "2022-02-07T20:58:40.000Z", "max_issues_repo_issues_event_min_datetime": "2022-01-24T15:45:08.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "aphearin/c3dev", "max_issues_repo_path": "c3dev/galmocks/galhalo_models/galsampler_phase_space.py", "max_line_length": 85, "max_stars_count": 2, "max_stars_repo_head_hexsha": "d36d083c9eb688640670dbe066bf299777a78ba7", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "aphearin/c3dev", "max_stars_repo_path": "c3dev/galmocks/galhalo_models/galsampler_phase_space.py", "max_stars_repo_stars_event_max_datetime": "2022-02-08T18:41:00.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-23T00:47:06.000Z", "num_tokens": 609, "path": null, "reason": "import numpy,from jax", "repo": null, "save_path": null, "sha": null, "size": 2335 }
_make_left_env(ψ::CuMPS, k::Int) = CUDA.ones(eltype(ψ), 1, 1, k) _make_left_env_new(ψ::CuMPS, k::Int) = CUDA.ones(eltype(ψ), 1, k) _make_LL(ψ::CuMPS, b::Int, k::Int, d::Int) = CUDA.zeros(eltype(ψ), b, b, k, d) _make_LL_new(ψ::CuMPS, b::Int, k::Int, d::Int) = CUDA.zeros(eltype(ψ), b, k, d) function CuMPS(ig::MetaGraph, control::MPSControl) Dcut = control.max_bond tol = control.var_ϵ max_sweeps = control.max_sweeps schedule = control.β @info "Set control parameters for MPS" Dcut tol max_sweeps rank = get_prop(ig, :rank) @info "Preparing Hadamard state as MPS" ρ = CuMPS(HadamardMPS(Float32, rank)) is_right = true @info "Sweeping through β and σ" schedule for dβ ∈ schedule ρ = _apply_layer_of_gates(ig, ρ, control, dβ) end ρ end function CuMPS(ig::MetaGraph, control::MPSControl, type::Symbol) L = nv(ig) Dcut = control.max_bond tol = control.var_ϵ max_sweeps = control.max_sweeps dβ = control.dβ β = control.β @info "Set control parameters for MPS" Dcut tol max_sweeps rank = get_prop(ig, :rank) @info "Preparing Hadamard state as MPS" ρ = CuMPS(HadamardMPS(Float32, rank)) is_right = true @info "Sweeping through β and σ" dβ if type == :log k = ceil(log2(β/dβ)) dβmax = β/(2^k) ρ = _apply_layer_of_gates(ig, ρ, control, dβmax) for j ∈ 1:k ρ = multiply_purifications(ρ, ρ, L) if bond_dimension(ρ) > Dcut @info "Compresing MPS" bond_dimension(ρ), Dcut ρ = compress(ρ, Dcut, tol, max_sweeps) is_right = true end end ρ elseif type == :lin k = β/dβ dβmax = β/k ρ = _apply_layer_of_gates(ig, ρ, control, dβmax) ρ0 = copy(ρ) for j ∈ 1:k ρ = multiply_purifications(ρ, ρ0, L) if bond_dimension(ρ) > Dcut @info "Compresing MPS" bond_dimension(ρ), Dcut ρ = compress(ρ, Dcut, tol, max_sweeps) is_right = true end end end ρ end
{ "alphanum_fraction": 0.581680831, "author": null, "avg_line_length": 29.8309859155, "converted": null, "ext": "jl", "file": null, "hexsha": "3a43c7694b12e9834fd218ba56f4abde77bf16e2", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-12-28T16:48:38.000Z", "max_forks_repo_forks_event_min_datetime": "2020-10-25T10:27:58.000Z", "max_forks_repo_head_hexsha": "7b4629f4243af3f60f617d6f214d4a532d82c38d", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "euro-hpc-pl/SpinGlassPEPS.jl", "max_forks_repo_path": "src/cuda/spectrum.jl", "max_issues_count": 39, "max_issues_repo_head_hexsha": "7b4629f4243af3f60f617d6f214d4a532d82c38d", "max_issues_repo_issues_event_max_datetime": "2021-03-22T10:50:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-10-15T10:20:04.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "iitis/SpinGlassPEPS.jl", "max_issues_repo_path": "src/cuda/spectrum.jl", "max_line_length": 79, "max_stars_count": 9, "max_stars_repo_head_hexsha": "7b4629f4243af3f60f617d6f214d4a532d82c38d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "euro-hpc-pl/SpinGlassPEPS.jl", "max_stars_repo_path": "src/cuda/spectrum.jl", "max_stars_repo_stars_event_max_datetime": "2021-02-16T11:34:24.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-28T10:28:46.000Z", "num_tokens": 740, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2118 }
%\input{/Users/joshyv/Research/misc/latex_paper.tex} \documentclass{article} \usepackage{amsmath} \usepackage{graphicx} \usepackage{amsfonts} \usepackage{amssymb} \usepackage{amsthm} %\usepackage{cite} \usepackage{algorithm} \usepackage{algorithmic} % \usepackage{times} \usepackage{fancyhdr} \usepackage{graphicx} \usepackage{verbatim} \usepackage{color} \usepackage[T1]{fontenc} \usepackage[scaled]{helvet} \renewcommand*\familydefault{\sfdefault} %% Only if the base font of the document is to be sans serif \pagestyle{fancy} \oddsidemargin=0.0in %%this makes the odd side margin go to the default of 1inch \evensidemargin=0.0in \textwidth=6.5in \headwidth=6.5in \textheight=9in %%sets the textwidth to 6.5, which leaves 1 for the remaining right margin with 8 1/2X11inch paper \headheight=12pt \topmargin=-0.25in %\headheight=0in %\headsep=0in %\pagestyle{headings} \usepackage{hyperref} % \usepackage{ulem} % \usepackage{color} % \newcommand{\loo}{$L^{(1)}_{h; \mD_n}$} \newcommand{\conv}{\rightarrow} % \newcommand{\Real}{\mathbb{R}} % \providecommand{\tr}[1]{\textcolor{red}{#1}} \newcommand{\mB}{\mathcal{B}} \newcommand{\mD}{\mathcal{D}} \newcommand{\mM}{\mathcal{M}} \newcommand{\PP}{F} % probability \newcommand{\EE}{\mathbb{E}} % expected value \newcommand{\II}{\mathbb{I}} % expected value \newcommand{\Real}{\mathbb{R}} % expected value \newcommand{\del}{\delta} \newcommand{\sig}{\sigma} \newcommand{\lam}{\lambda} \newcommand{\gam}{\gamma} \newcommand{\eps}{\varepsilon} \providecommand{\mc}[1]{\mathcal{#1}} \providecommand{\mb}[1]{\boldsymbol{#1}} \providecommand{\mbb}[1]{\mathbb{#1}} \providecommand{\mv}[1]{\vec{#1}} \providecommand{\mh}[1]{\widehat{#1}} \providecommand{\mt}[1]{\widetilde{#1}} \providecommand{\mhc}[1]{\hat{\mathcal{#1}}} \providecommand{\mhb}[1]{\hat{\boldsymbol{#1}}} \providecommand{\mvb}[1]{\vec{\boldsymbol{#1}}} \providecommand{\mtb}[1]{\widetilde{\boldsymbol{#1}}} \newcommand{\argmax}{\operatornamewithlimits{argmax}} \newcommand{\argmin}{\operatornamewithlimits{argmin}} % \newcommand{\mN}{\mathcal{N}} \newcommand{\hL}{\widehat{L}} \newcommand{\MeB}{\mM \overset{\varepsilon}{{\sim}}_{\PP} \mB} \newcommand{\MsB}{\mM \overset{S}{\sim}_{\PP} \mB} \newcommand{\MnoteB}{\mM \overset{\varepsilon}{{\not\sim}}_{\PP} \mB} \providecommand{\tr}[1]{\textcolor{black}{#1}} \providecommand{\norm}[1]{\left \lVert#1 \right \rVert} \newcommand{\T}{^{\ensuremath{\mathsf{T}}}} % transpose \newtheorem{defi}{Definition} \newtheorem{thm}{Theorem} \newtheorem{thex}{\emph{Gedankenexperiment}} \lhead{Vogelstein JT, et al.} \rhead{Statistical Supervenience Supplement} \begin{document} \begin{center} {\huge Supplementary Materials for: \\ Are mental properties supervenient on brain properties?} \end{center} \vspace{5px} \begin{center} {\large Joshua T. Vogelstein$^{1*}$, R. Jacob Vogelstein$^2$, Carey E. Priebe$^1$\\ $^1$Department of Applied Mathematics \& Statistics, \\ Johns Hopkins University, Baltimore, MD, 21218,\\ $^2$National Security Technology Department, \\ Johns Hopkins University Applied Physics Laboratory, Laurel, MD 20723} \end{center} \vspace{5px} % \section{Relations between sets} % (fold) % \label{sec:relations} In this appendix we compare supervenience to several other relations on sets (see Figure \ref{fig:rel}). % aim to provide more intuition regarding supervenience by discussing the limitations and extent of its implications. %For instance, it may be the case that minds supervene on brains, but one cannot form an \emph{injective} relation from brains to minds. First, a supervenient relation does not imply an injective relation. An injective relation is any relation that preserves distinctness. Thus if minds are injective on brains, then $b\neq b' \implies m \neq m'$ (note that the directionality of the implication has been switched relative to supervenience). However, it might be the case that a brain could change without the mind changing. Consider the case that a single subatomic particle shifts its position by a Plank length, changing brain state from $b$ to $b'$. It is possible (likely?) that the mental state supervening on brain state $b$ remains $m$, even after $b$ changes to $b'$. In such a scenario, the mind might still supervene on the brain, but the relation from brains to minds is not injective. This argument also shows that supervenience is not necessarily a \emph{symmetric} relation. Minds supervening on brains does not imply that brains supervene on minds. Second, supervenience does not imply causality. For instance, consider an analogy where $M$ and $B$ correspond to two coins being flipped, each possibly landing on heads or tails. Further assume that every time one lands on heads so does the other, and every time one lands on tails, so do the other. This implies that $M$ supervenes on $B$, but assumes nothing about whether $M$ causes $B$, or $B$ causes $M$, or some exogenous force causes both. Third, supervenience does not imply identity. The above example with the two coins demonstrates this, as the two coins are not the same thing, even if one has perfect information about the other. What supervenience does imply, however, is the following. Imagine finding two unequal minds. If $\MsB$, then the brains on which those two minds supervene must be different. In other words, there cannot be two unequal minds, either of which could supervene on a single brain. Figure \ref{fig:rel} shows several possible relations between the sets of minds and brains. Note that statistical supervenience is distinct from statistical correlation. \emph{Statistical correlation} between brain states and mental states is defined as $\rho_{MB}=\EE[(B-\mu_B)(M-\mu_M)]/(\sig_B \sig_M)$, where $\mu_X$ and $\sig_X$ are the mean and variance of $X$, and $\EE[X]$ is the expected value of $X$. If $\rho_{MB}=1$, then both $\MsB$ and $\mB \overset{S}{{\sim}}_{F} \mM$. Thus, perfect correlation implies supervenience, but supervenience does not imply correlation. In fact, supervenience may be thought of as a generalization of correlation which incorporates directionality, can be applied to arbitrary valued random variables (such as mental or brain properties), and can depend on any moment of a distribution (not just the first two). \begin{figure}[h!tbp] \centering \includegraphics[width=1\linewidth]{supervenience_relations.pdf} \caption{Possible relations between minds and brains. (A) Minds supervene on brains, and it so happens that there is a bijective relation from brains to minds. (B) Minds supervene on brains, and it so happens that there is a surjective (a.k.a., onto) relation from brains to minds, but not a bijective one. (C) Minds are \emph{not} supervenient on brains, because two different minds supervene on the same brain.} \label{fig:rel} \end{figure} % section relations_between_sets (end) % \section{Simulation} % (fold) % \label{sec:sim} % \bibliography{/Users/jovo/Research/latex/library} % \bibliographystyle{nature} \end{document}
{ "alphanum_fraction": 0.7415397631, "author": null, "avg_line_length": 47.28, "converted": null, "ext": "tex", "file": null, "hexsha": "14f5691d735454d3ac5ea6554a9cdecb23a6f767", "include": null, "lang": "TeX", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "f98ad5ebbaf54c4591b1ad9fd8d3f70fc13c5bc2", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "jovo/supervenience", "max_forks_repo_path": "nature_sci_rep/submission2/supp.tex", "max_issues_count": 1, "max_issues_repo_head_hexsha": "f98ad5ebbaf54c4591b1ad9fd8d3f70fc13c5bc2", "max_issues_repo_issues_event_max_datetime": "2015-02-20T01:54:10.000Z", "max_issues_repo_issues_event_min_datetime": "2015-02-20T01:54:10.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "jovo/supervenience", "max_issues_repo_path": "nature_sci_rep/submission2/supp.tex", "max_line_length": 935, "max_stars_count": null, "max_stars_repo_head_hexsha": "f98ad5ebbaf54c4591b1ad9fd8d3f70fc13c5bc2", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "jovo/supervenience", "max_stars_repo_path": "nature_sci_rep/submission2/supp.tex", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2077, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 7092 }
import numpy as np from examples.example_utils import make_chainer_a3c from dacbench.benchmarks import CMAESBenchmark # Helper method to flatten observation space def flatten(li): return [value for sublist in li for value in sublist] # Make CMA-ES environment # We use the configuration from the "Learning to Optimize Step-size Adaption in CMA-ES" Paper by Shala et al. bench = CMAESBenchmark() env = bench.get_benchmark() # Make chainer agent space_array = [ env.observation_space[k].low for k in list(env.observation_space.spaces.keys()) ] obs_size = np.array(flatten(space_array)).size action_size = env.action_space.low.size agent = make_chainer_a3c(obs_size, action_size) # Training num_episodes = 3 for i in range(num_episodes): # Reset environment to begin episode state = env.reset() # Flattening state state = np.array(flatten([state[k] for k in state.keys()])) # Casting is necessary for chainer state = state.astype(np.float32) # Initialize episode done = False r = 0 reward = 0 while not done: # Select action action = agent.act_and_train(state, reward) # Execute action next_state, reward, done, _ = env.step(action) r += reward state = np.array(flatten([next_state[k] for k in next_state.keys()])) state = state.astype(np.float32) # Train agent after episode has ended agent.stop_episode_and_train(state, reward, done=done) # Log episode print( f"Episode {i}/{num_episodes}...........................................Reward: {r}" )
{ "alphanum_fraction": 0.6779874214, "author": null, "avg_line_length": 29.4444444444, "converted": null, "ext": "py", "file": null, "hexsha": "fd25d8a2b6c80e8b63a69c0ae1782359595ac5fc", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "bf4e0398110a50ac33c7bc57a13ecca3590e8247", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "rishan92/DACBench", "max_forks_repo_path": "examples/benchmarks/chainerrl_cma.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "bf4e0398110a50ac33c7bc57a13ecca3590e8247", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "rishan92/DACBench", "max_issues_repo_path": "examples/benchmarks/chainerrl_cma.py", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "bf4e0398110a50ac33c7bc57a13ecca3590e8247", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "rishan92/DACBench", "max_stars_repo_path": "examples/benchmarks/chainerrl_cma.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 391, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1590 }
#!/usr/bin/env python from __future__ import print_function import gzip import os import pickle import time import gym import numpy as np from util import DATA_DIR, DATA_FILE def key_press(key, mod): global human_agent_action, human_wants_restart, human_wants_exit, human_sets_pause, acceleration if key == 0xff0d: # enter human_wants_restart = True if key == 0xff1b: # escape human_wants_exit = True if key == 0x020: # space human_sets_pause = not human_sets_pause if key == 0xff52: # up acceleration = True human_agent_action[1] = 1.0 human_agent_action[2] = 0 if key == 0xff54: # down human_agent_action[2] = 1 # stronger brakes if key == 0xff51: # left human_agent_action[0] = -1.0 # no acceleration while turning human_agent_action[1] = 0.0 if key == 0xff53: # right human_agent_action[0] = +1.0 # no acceleration when turning human_agent_action[1] = 0.0 def key_release(key, mod): global human_agent_action, acceleration if key == 0xff52: # up acceleration = False human_agent_action[1] = 0.0 if key == 0xff54: # down human_agent_action[2] = 0.0 if key == 0xff51: # left human_agent_action[0] = 0 # restore acceleration human_agent_action[1] = acceleration if key == 0xff53: # right human_agent_action[0] = 0 # restore acceleration human_agent_action[1] = acceleration def rollout(env): global human_wants_restart, human_agent_action, human_wants_exit, human_sets_pause ACTIONS = env.action_space.shape[0] human_agent_action = np.zeros(ACTIONS, dtype=np.float32) human_wants_exit = False human_sets_pause = False human_wants_restart = False # if the file exists, append if os.path.exists(os.path.join(DATA_DIR, DATA_FILE)): with gzip.open(os.path.join(DATA_DIR, DATA_FILE), 'rb') as f: observations = pickle.load(f) else: observations = list() state = env.reset() total_reward = 0 total_timesteps = 0 episode = 1 while 1: env.render() a = np.copy(human_agent_action) old_state = state if human_agent_action[2] != 0: human_agent_action[2] = 0.1 state, r, terminal, info = env.step(human_agent_action) observations.append((old_state, a, state, r, terminal)) total_reward += r if human_wants_exit: env.close() return if human_wants_restart: human_wants_restart = False state = env.reset() continue if terminal: if episode % 5 == 0: # store generated data data_file_path = os.path.join(DATA_DIR, DATA_FILE) print("Saving observations to " + data_file_path) if not os.path.exists(DATA_DIR): os.mkdir(DATA_DIR) with gzip.open(data_file_path, 'wb') as f: pickle.dump(observations, f) print("timesteps %i reward %0.2f" % (total_timesteps, total_reward)) episode += 1 state = env.reset() while human_sets_pause: env.render() time.sleep(0.1) if __name__ == '__main__': env = gym.make('CarRacing-v0') env.render() env.unwrapped.viewer.window.on_key_press = key_press env.unwrapped.viewer.window.on_key_release = key_release print("ACTIONS={}".format(env.action_space.shape[0])) print("Press keys 1 2 3 ... to take actions 1 2 3 ...") print("No keys pressed is taking action 0") rollout(env)
{ "alphanum_fraction": 0.60898636, "author": null, "avg_line_length": 25.0939597315, "converted": null, "ext": "py", "file": null, "hexsha": "0bfd598b347c29e68bd2a99c34ce1b4b67b563ef", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 65, "max_forks_repo_forks_event_max_datetime": "2022-02-20T02:00:42.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-29T13:06:13.000Z", "max_forks_repo_head_hexsha": "95f59244e8e27713c28f8aaed407e326de5fddfc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Bitdribble/pdl-se", "max_forks_repo_path": "ch10/imitation_learning/keyboard_agent.py", "max_issues_count": 2, "max_issues_repo_head_hexsha": "95f59244e8e27713c28f8aaed407e326de5fddfc", "max_issues_repo_issues_event_max_datetime": "2019-02-09T21:27:15.000Z", "max_issues_repo_issues_event_min_datetime": "2019-02-09T08:19:10.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Bitdribble/pdl-se", "max_issues_repo_path": "ch10/imitation_learning/keyboard_agent.py", "max_line_length": 100, "max_stars_count": 107, "max_stars_repo_head_hexsha": "95f59244e8e27713c28f8aaed407e326de5fddfc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Bitdribble/pdl-se", "max_stars_repo_path": "ch10/imitation_learning/keyboard_agent.py", "max_stars_repo_stars_event_max_datetime": "2021-08-31T03:23:39.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-09T13:49:33.000Z", "num_tokens": 972, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 3739 }
""" Bifurcation point classes. Each class locates and processes bifurcation points. * _BranchPointFold is a version based on BranchPoint location algorithms * BranchPoint: Branch process is broken (can't find alternate branch -- see MATCONT notes) Drew LaMar, March 2006 """ from __future__ import absolute_import, print_function from .misc import * from PyDSTool.common import args from .TestFunc import DiscreteMap, FixedPointMap from numpy import Inf, NaN, isfinite, r_, c_, sign, mod, \ subtract, divide, transpose, eye, real, imag, \ conjugate, average from scipy import optimize, linalg from numpy import dot as matrixmultiply from numpy import array, float, complex, int, float64, complex64, int32, \ zeros, divide, subtract, reshape, argsort, nonzero ##### _classes = ['BifPoint', 'BPoint', 'BranchPoint', 'FoldPoint', 'HopfPoint', 'BTPoint', 'ZHPoint', 'CPPoint', 'BranchPointFold', '_BranchPointFold', 'DHPoint', 'GHPoint', 'LPCPoint', 'PDPoint', 'NSPoint', 'SPoint'] __all__ = _classes ##### class BifPoint(object): def __init__(self, testfuncs, flagfuncs, label='Bifurcation', stop=False): self.testfuncs = [] self.flagfuncs = [] self.found = [] self.label = label self.stop = stop self.data = args() if not isinstance(testfuncs, list): testfuncs = [testfuncs] if not isinstance(flagfuncs, list): flagfuncs = [flagfuncs] self.testfuncs.extend(testfuncs) self.flagfuncs.extend(flagfuncs) self.tflen = len(self.testfuncs) def locate(self, P1, P2, C): pointlist = [] for i, testfunc in enumerate(self.testfuncs): if self.flagfuncs[i] == iszero: for ind in range(testfunc.m): X, V = testfunc.findzero(P1, P2, ind) pointlist.append((X,V)) X = average([point[0] for point in pointlist], axis=0) V = average([point[1] for point in pointlist], axis=0) C.Corrector(X,V) return X, V def process(self, X, V, C): data = args() data.X = todict(C, X) data.V = todict(C, V) self.found.append(data) def info(self, C, ind=None, strlist=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] if C.verbosity >= 1: print(self.label + ' Point found ') if C.verbosity >= 2: print('========================== ') for n, i in enumerate(ind): print(n, ': ') Xd = self.found[i].X for k, j in Xd.items(): print(k, ' = ', j) print('') if hasattr(self.found[i], 'eigs'): print('Eigenvalues = \n') for x in self.found[i].eigs: print(' (%f,%f)' % (x.real, x.imag)) print('\n') if strlist is not None: for string in strlist: print(string) print('') class SPoint(BifPoint): """Special point that represents user-selected free parameter values.""" def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'S', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) self.info(C, -1) return True class BPoint(BifPoint): """Special point that represents boundary of computational domain.""" def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'B', stop=stop) def locate(self, P1, P2, C): # Find location that triggered testfunc and initialize testfunc to that index val1 = (P1[0]-self.testfuncs[0].lower)*(self.testfuncs[0].upper-P1[0]) val2 = (P2[0]-self.testfuncs[0].lower)*(self.testfuncs[0].upper-P2[0]) ind = nonzero(val1*val2 < 0) self.testfuncs[0].ind = ind self.testfuncs[0].func = self.testfuncs[0].one X, V = BifPoint.locate(self, P1, P2, C) # Set testfunc back to monitoring all self.testfuncs[0].ind = None self.testfuncs[0].func = self.testfuncs[0].all return X, V def process(self, X, V, C): BifPoint.process(self, X, V, C) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind) class BranchPoint(BifPoint): """May only work for EquilibriumCurve ... (needs fixing)""" def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'BP', stop=stop) def __locate_newton(self, X, C): """x[0:self.dim] = (x,alpha) x[self.dim] = beta x[self.dim+1:2*self.dim] = p """ J_coords = C.CorrFunc.jac(X[0:C.dim], C.coords) J_params = C.CorrFunc.jac(X[0:C.dim], C.params) return r_[C.CorrFunc(X[0:C.dim]) + X[C.dim]*X[C.dim+1:], \ matrixmultiply(transpose(J_coords),X[C.dim+1:]), \ matrixmultiply(transpose(X[C.dim+1:]),J_params), \ matrixmultiply(transpose(X[C.dim+1:]),X[C.dim+1:]) - 1] def locate(self, P1, P2, C): # Initiliaze p vector to eigenvector with smallest eigenvalue X, V = P1 X2, V2 = P2 J_coords = C.CorrFunc.jac(X, C.coords) W, VL = linalg.eig(J_coords, left=1, right=0) ind = argsort([abs(eig) for eig in W])[0] p = real(VL[:,ind]) initpoint = zeros(2*C.dim, float) initpoint[0:C.dim] = X initpoint[C.dim+1:] = p X = optimize.fsolve(self.__locate_newton, initpoint, C) self.data.psi = X[C.dim+1:] X = X[0:C.dim] V = 0.5*(V+V2) return X, V def process(self, X, V, C): BifPoint.process(self, X, V, C) # Finds the new branch J_coords = C.CorrFunc.jac(X, C.coords) J_params = C.CorrFunc.jac(X, C.params) singular = True perpvec = r_[1,zeros(C.dim-1)] d = 1 while singular and d <= C.dim: try: v0 = linalg.solve(r_[c_[J_coords, J_params], [perpvec]], \ r_[zeros(C.dim-1),1]) except: perpvec = r_[0., perpvec[0:(C.dim-1)]] d += 1 else: singular = False if singular: raise PyDSTool_ExistError("Problem in _compute: Failed to compute tangent vector.") v0 /= linalg.norm(v0) V = sign([x for x in v0 if abs(x) > 1e-8][0])*v0 A = r_[c_[J_coords, J_params], [V]] W, VR = linalg.eig(A) W0 = [ind for ind, eig in enumerate(W) if abs(eig) < 5e-5] V1 = real(VR[:,W0[0]]) H = C.CorrFunc.hess(X, C.coords+C.params, C.coords+C.params) c11 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])]) c12 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])]) c22 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])]) beta = 1 alpha = -1*c22/(2*c12) V1 = alpha*V + beta*V1 V1 /= linalg.norm(V1) self.found[-1].eigs = W self.found[-1].branch = todict(C, V1) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] for n, i in enumerate(ind): strlist.append('branch angle = ' + repr(matrixmultiply(tocoords(C, self.found[i].V), \ tocoords(C, self.found[i].branch)))) X = tocoords(C, self.found[-1].X) V = tocoords(C, self.found[-1].V) C._preTestFunc(X, V) strlist.append('Test function #1: ' + repr(self.testfuncs[0](X,V)[0])) BifPoint.info(self, C, ind, strlist) class FoldPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'LP', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) # Compute normal form coefficient # NOTE: These are for free when using bordering technique!) # NOTE: Does not agree with MATCONT output! (if |p| = |q| = 1, then it does) J_coords = C.CorrFunc.jac(X, C.coords) W, VL, VR = linalg.eig(J_coords, left=1, right=1) minW = min(abs(W)) ind = [(abs(eig) < minW+1e-8) and (abs(eig) > minW-1e-8) for eig in W].index(True) p, q = real(VL[:,ind]), real(VR[:,ind]) p /= matrixmultiply(p,q) B = C.CorrFunc.hess(X, C.coords, C.coords) self.found[-1].a = abs(0.5*matrixmultiply(p,[bilinearform(B[i,:,:], q, q) for i in range(B.shape[0])])) self.found[-1].eigs = W numzero = len([eig for eig in W if abs(eig) < 1e-4]) if numzero > 1: if C.verbosity >= 2: print('Fold-Fold!\n') del self.found[-1] return False elif numzero == 0: if C.verbosity >= 2: print('False positive!\n') del self.found[-1] return False if C.verbosity >= 2: print('\nChecking...') print(' |q| = %f' % linalg.norm(q)) print(' <p,q> = %f' % matrixmultiply(p,q)) print(' |Aq| = %f' % linalg.norm(matrixmultiply(J_coords,q))) print(' |transpose(A)p| = %f\n' % linalg.norm(matrixmultiply(transpose(J_coords),p))) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] for n, i in enumerate(ind): strlist.append('a = ' + repr(self.found[i].a)) BifPoint.info(self, C, ind, strlist) class HopfPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'H', stop=stop) def process(self, X, V, C): """Tolerance for eigenvalues a possible problem when checking for neutral saddles.""" BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.jac(X, C.coords) eigs, LV, RV = linalg.eig(J_coords,left=1,right=1) # Check for neutral saddles found = False for i in range(len(eigs)): if abs(imag(eigs[i])) < 1e-5: for j in range(i+1,len(eigs)): if C.verbosity >= 2: if abs(eigs[i]) < 1e-5 and abs(eigs[j]) < 1e-5: print('Fold-Fold point found in Hopf!\n') elif abs(imag(eigs[j])) < 1e-5 and abs(real(eigs[i]) + real(eigs[j])) < 1e-5: print('Neutral saddle found!\n') elif abs(real(eigs[i])) < 1e-5: for j in range(i+1, len(eigs)): if abs(real(eigs[j])) < 1e-5 and abs(real(eigs[i]) - real(eigs[j])) < 1e-5: found = True w = abs(imag(eigs[i])) if imag(eigs[i]) > 0: p = conjugate(LV[:,j])/linalg.norm(LV[:,j]) q = RV[:,i]/linalg.norm(RV[:,i]) else: p = conjugate(LV[:,i])/linalg.norm(LV[:,i]) q = RV[:,j]/linalg.norm(RV[:,j]) if not found: del self.found[-1] return False direc = conjugate(1/matrixmultiply(conjugate(p),q)) p = direc*p # Alternate way to compute 1st lyapunov coefficient (from Kuznetsov [4]) #print (1./(w*w))*real(1j*matrixmultiply(conjugate(p),b1)*matrixmultiply(conjugate(p),b3) + \ # w*matrixmultiply(conjugate(p),trilinearform(D,q,q,conjugate(q)))) self.found[-1].w = w self.found[-1].l1 = firstlyapunov(X, C.CorrFunc, w, J_coords=J_coords, p=p, q=q, check=(C.verbosity==2)) self.found[-1].eigs = eigs self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] for n, i in enumerate(ind): strlist.append('w = ' + repr(self.found[i].w)) strlist.append('l1 = ' + repr(self.found[i].l1)) BifPoint.info(self, C, ind, strlist) # Codimension-2 bifurcations class BTPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'BT', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.sysfunc.jac(X, C.coords) W, VL, VR = linalg.eig(J_coords, left=1, right=1) self.found[-1].eigs = W if C.verbosity >= 2: if C.CorrFunc.testfunc.data.B.shape[1] == 2: b = matrixmultiply(transpose(J_coords), C.CorrFunc.testfunc.data.w[:,0]) c = matrixmultiply(J_coords, C.CorrFunc.testfunc.data.v[:,0]) else: b = C.CorrFunc.testfunc.data.w[:,0] c = C.CorrFunc.testfunc.data.v[:,0] print('\nChecking...') print(' <b,c> = %f' % matrixmultiply(transpose(b), c)) print('\n') self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind) class ZHPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'ZH', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.sysfunc.jac(X, C.coords) W, VL, VR = linalg.eig(J_coords, left=1, right=1) self.found[-1].eigs = W self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind) class CPPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'CP', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.sysfunc.jac(X, C.coords) B = C.CorrFunc.sysfunc.hess(X, C.coords, C.coords) W, VL, VR = linalg.eig(J_coords, left=1, right=1) q = C.CorrFunc.testfunc.data.C/linalg.norm(C.CorrFunc.testfunc.data.C) p = C.CorrFunc.testfunc.data.B/matrixmultiply(transpose(C.CorrFunc.testfunc.data.B),q) self.found[-1].eigs = W a = 0.5*matrixmultiply(transpose(p), reshape([bilinearform(B[i,:,:], q, q) \ for i in range(B.shape[0])],(B.shape[0],1)))[0][0] if C.verbosity >= 2: print('\nChecking...') print(' |a| = %f' % a) print('\n') self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind) class BranchPointFold(BifPoint): """Check Equilibrium.m in MATCONT""" def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'BP', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) pind = self.testfuncs[0].pind # Finds the new branch J_coords = C.CorrFunc.jac(X, C.coords) J_params = C.CorrFunc.jac(X, C.params) A = r_[c_[J_coords, J_params[:,pind]]] #A = r_[c_[J_coords, J_params], [V]] W, VR = linalg.eig(A) W0 = [ind for ind, eig in enumerate(W) if abs(eig) < 5e-5] tmp = real(VR[:,W0[0]]) V1 = r_[tmp[:-1], 0, 0] V1[len(tmp)-1+pind] = tmp[-1] """NEED TO FIX THIS!""" H = C.CorrFunc.hess(X, C.coords+C.params, C.coords+C.params) # c11 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])]) # c12 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])]) # c22 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])]) # beta = 1 # alpha = -1*c22/(2*c12) # V1 = alpha*V + beta*V1 # V1 /= linalg.norm(V1) self.found[-1].eigs = W self.found[-1].branch = None self.found[-1].par = C.freepars[self.testfuncs[0].pind] # self.found[-1].branch = todict(C, V1) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] #for n, i in enumerate(ind): # strlist.append('branch angle = ' + repr(matrixmultiply(tocoords(C, self.found[i].V), \ # tocoords(C, self.found[i].branch)))) X = tocoords(C, self.found[-1].X) V = tocoords(C, self.found[-1].V) C._preTestFunc(X, V) strlist.append('Test function #1: ' + repr(self.testfuncs[0](X,V)[0])) BifPoint.info(self, C, ind, strlist) class _BranchPointFold(BifPoint): """Check Equilibrium.m in MATCONT""" def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'BP', stop=stop) def __locate_newton(self, X, C): """Note: This is redundant!! B is a column of A!!! Works for now, though...""" pind = self.testfuncs[0].pind J_coords = C.CorrFunc.jac(X[0:C.dim], C.coords) J_params = C.CorrFunc.jac(X[0:C.dim], C.params) A = c_[J_coords, J_params[:,pind]] B = J_params[:,pind] return r_[C.CorrFunc(X[0:C.dim]) + X[C.dim]*X[C.dim+1:], \ matrixmultiply(transpose(A),X[C.dim+1:]), \ matrixmultiply(transpose(X[C.dim+1:]),B), \ matrixmultiply(transpose(X[C.dim+1:]),X[C.dim+1:]) - 1] def locate(self, P1, P2, C): # Initiliaze p vector to eigenvector with smallest eigenvalue X, V = P1 pind = self.testfuncs[0].pind J_coords = C.CorrFunc.jac(X, C.coords) J_params = C.CorrFunc.jac(X, C.params) A = r_[c_[J_coords, J_params[:,pind]]] W, VL = linalg.eig(A, left=1, right=0) ind = argsort([abs(eig) for eig in W])[0] p = real(VL[:,ind]) initpoint = zeros(2*C.dim, float) initpoint[0:C.dim] = X initpoint[C.dim+1:] = p X = optimize.fsolve(self.__locate_newton, initpoint, C) self.data.psi = X[C.dim+1:] X = X[0:C.dim] return X, V def process(self, X, V, C): BifPoint.process(self, X, V, C) pind = self.testfuncs[0].pind # Finds the new branch J_coords = C.CorrFunc.jac(X, C.coords) J_params = C.CorrFunc.jac(X, C.params) A = r_[c_[J_coords, J_params[:,pind]]] #A = r_[c_[J_coords, J_params], [V]] W, VR = linalg.eig(A) W0 = [ind for ind, eig in enumerate(W) if abs(eig) < 5e-5] tmp = real(VR[:,W0[0]]) V1 = r_[tmp[:-1], 0, 0] V1[len(tmp)-1+pind] = tmp[-1] """NEED TO FIX THIS!""" H = C.CorrFunc.hess(X, C.coords+C.params, C.coords+C.params) c11 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])]) c12 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])]) c22 = matrixmultiply(self.data.psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])]) beta = 1 alpha = -1*c22/(2*c12) V1 = alpha*V + beta*V1 V1 /= linalg.norm(V1) self.found[-1].eigs = W self.found[-1].branch = None self.found[-1].par = C.freepars[self.testfuncs[0].pind] self.found[-1].branch = todict(C, V1) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] #for n, i in enumerate(ind): # strlist.append('branch angle = ' + repr(matrixmultiply(tocoords(C, self.found[i].V), \ # tocoords(C, self.found[i].branch)))) X = tocoords(C, self.found[-1].X) V = tocoords(C, self.found[-1].V) C._preTestFunc(X, V) strlist.append('Test function #1: ' + repr(self.testfuncs[0](X,V)[0])) BifPoint.info(self, C, ind, strlist) class DHPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'DH', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.sysfunc.jac(X, C.coords) eigs, LV, RV = linalg.eig(J_coords,left=1,right=1) self.found[-1].eigs = eigs self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind) class GHPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'GH', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.CorrFunc.sysfunc.jac(X, C.coords) eigs, LV, RV = linalg.eig(J_coords,left=1,right=1) # Check for neutral saddles found = False for i in range(len(eigs)): if abs(imag(eigs[i])) < 1e-5: for j in range(i+1,len(eigs)): if C.verbosity >= 2: if abs(eigs[i]) < 1e-5 and abs(eigs[j]) < 1e-5: print('Fold-Fold point found in Hopf!\n') elif abs(imag(eigs[j])) < 1e-5 and abs(real(eigs[i]) + real(eigs[j])) < 1e-5: print('Neutral saddle found!\n') elif abs(real(eigs[i])) < 1e-5: for j in range(i+1, len(eigs)): if abs(real(eigs[j])) < 1e-5 and abs(real(eigs[i]) - real(eigs[j])) < 1e-5: found = True w = abs(imag(eigs[i])) if imag(eigs[i]) > 0: p = conjugate(LV[:,j]/linalg.norm(LV[:,j])) q = RV[:,i]/linalg.norm(RV[:,i]) else: p = conjugate(LV[:,i]/linalg.norm(LV[:,i])) q = RV[:,j]/linalg.norm(RV[:,j]) if not found: del self.found[-1] return False direc = conjugate(1/matrixmultiply(conjugate(p),q)) p = direc*p # Alternate way to compute 1st lyapunov coefficient (from Kuznetsov [4]) #print (1./(w*w))*real(1j*matrixmultiply(conjugate(p),b1)*matrixmultiply(conjugate(p),b3) + \ # w*matrixmultiply(conjugate(p),trilinearform(D,q,q,conjugate(q)))) self.found[-1].w = w self.found[-1].l1 = firstlyapunov(X, C.CorrFunc.sysfunc, w, J_coords=J_coords, p=p, q=q, check=(C.verbosity==2)) self.found[-1].eigs = eigs self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] for n, i in enumerate(ind): strlist.append('w = ' + repr(self.found[i].w)) strlist.append('l1 = ' + repr(self.found[i].l1)) BifPoint.info(self, C, ind, strlist) # Discrete maps class LPCPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'LPC', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.sysfunc.jac(X, C.coords) W, VL, VR = linalg.eig(J_coords, left=1, right=1) self.found[-1].eigs = W self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] X = tocoords(C, self.found[-1].X) V = tocoords(C, self.found[-1].V) C._preTestFunc(X, V) strlist.append('Test function #1: ' + repr(self.testfuncs[0](X,V)[0])) strlist.append('Test function #2: ' + repr(self.testfuncs[1](X,V)[0])) BifPoint.info(self, C, ind, strlist) class PDPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'PD', stop=stop) def process(self, X, V, C): """Do I need to compute the branch, or will it always be in the direction of freepar = constant?""" BifPoint.process(self, X, V, C) F = DiscreteMap(C.sysfunc, period=2*C.sysfunc.period) FP = FixedPointMap(F) J_coords = FP.jac(X, C.coords) J_params = FP.jac(X, C.params) # Locate branch of double period map W, VL = linalg.eig(J_coords, left=1, right=0) ind = argsort([abs(eig) for eig in W])[0] psi = real(VL[:,ind]) A = r_[c_[J_coords, J_params], [V]] W, VR = linalg.eig(A) W0 = argsort([abs(eig) for eig in W])[0] V1 = real(VR[:,W0]) H = FP.hess(X, C.coords+C.params, C.coords+C.params) c11 = matrixmultiply(psi,[bilinearform(H[i,:,:], V, V) for i in range(H.shape[0])]) c12 = matrixmultiply(psi,[bilinearform(H[i,:,:], V, V1) for i in range(H.shape[0])]) c22 = matrixmultiply(psi,[bilinearform(H[i,:,:], V1, V1) for i in range(H.shape[0])]) beta = 1 alpha = -1*c22/(2*c12) V1 = alpha*V + beta*V1 V1 /= linalg.norm(V1) J_coords = C.sysfunc.jac(X, C.coords) W = linalg.eig(J_coords, right=0) self.found[-1].eigs = W self.found[-1].branch_period = 2*C.sysfunc.period self.found[-1].branch = todict(C, V1) self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] strlist = [] for n, i in enumerate(ind): strlist.append('Period doubling branch angle = ' + repr(matrixmultiply(tocoords(C, self.found[i].V), \ tocoords(C, self.found[i].branch)))) BifPoint.info(self, C, ind, strlist) class NSPoint(BifPoint): def __init__(self, testfuncs, flagfuncs, stop=False): BifPoint.__init__(self, testfuncs, flagfuncs, 'NS', stop=stop) def process(self, X, V, C): BifPoint.process(self, X, V, C) J_coords = C.sysfunc.jac(X, C.coords) eigs, VL, VR = linalg.eig(J_coords, left=1, right=1) # Check for nonreal multipliers found = False for i in range(len(eigs)): for j in range(i+1,len(eigs)): if abs(imag(eigs[i])) > 1e-10 and \ abs(imag(eigs[j])) > 1e-10 and \ abs(eigs[i]*eigs[j] - 1) < 1e-5: found = True if not found: del self.found[-1] return False self.found[-1].eigs = eigs self.info(C, -1) return True def info(self, C, ind=None): if ind is None: ind = list(range(len(self.found))) elif isinstance(ind, int): ind = [ind] BifPoint.info(self, C, ind)
{ "alphanum_fraction": 0.5341793452, "author": null, "avg_line_length": 32.6384439359, "converted": null, "ext": "py", "file": null, "hexsha": "5338514dfbd12161e51e2cea2de687a8253338f8", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-02-25T14:43:36.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-25T14:43:36.000Z", "max_forks_repo_head_hexsha": "3d298e908ff55340cd3612078508be0c791f63a8", "max_forks_repo_licenses": [ "Python-2.0", "OLDAP-2.7" ], "max_forks_repo_name": "mdlama/pydstool", "max_forks_repo_path": "PyDSTool/PyCont/BifPoint.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "3d298e908ff55340cd3612078508be0c791f63a8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Python-2.0", "OLDAP-2.7" ], "max_issues_repo_name": "mdlama/pydstool", "max_issues_repo_path": "PyDSTool/PyCont/BifPoint.py", "max_line_length": 120, "max_stars_count": 2, "max_stars_repo_head_hexsha": "3d298e908ff55340cd3612078508be0c791f63a8", "max_stars_repo_licenses": [ "Python-2.0", "OLDAP-2.7" ], "max_stars_repo_name": "mdlama/pydstool", "max_stars_repo_path": "PyDSTool/PyCont/BifPoint.py", "max_stars_repo_stars_event_max_datetime": "2021-02-25T16:08:43.000Z", "max_stars_repo_stars_event_min_datetime": "2021-02-04T15:01:31.000Z", "num_tokens": 8264, "path": null, "reason": "from numpy,from scipy", "repo": null, "save_path": null, "sha": null, "size": 28526 }
import networkx as nx from cStringIO import StringIO from Bio import Phylo import matplotlib.pyplot as plt import random import logging from tqdm import tqdm logger = logging.getLogger() logger.setLevel(logging.INFO) import numpy as np import trees from trees.ddt import DirichletDiffusionTree, Inverse, GaussianLikelihoodModel from trees.mcmc import MetropolisHastingsSampler from trees.util import plot_tree_2d from sklearn.decomposition import PCA import seaborn as sns sns.set_style('white') import cPickle as pickle dataset = trees.data.load('zoo') X, y = dataset.X, dataset.y X += np.random.normal(scale=0.01, size=X.shape) pca = PCA(2) pca.fit(X) # X = pca.transform(X) N, D = X.shape with open('../../scripts/zoo.tree', 'rb') as fp: master_tree = pickle.load(fp) master_constraints = list(master_tree.generate_constraints()) random.seed(0) random.shuffle(master_constraints) train_constraints, test_constraints = master_constraints[:200], master_constraints[200:] test_constraints = test_constraints[:10000] df = Inverse(c=0.9) lm = GaussianLikelihoodModel(sigma=np.eye(D) / 4.0, sigma0=np.eye(D) / 2.0, mu0=X.mean(axis=0)).compile() model = DirichletDiffusionTree(df=df, likelihood_model=lm, constraints=[]) sampler = MetropolisHastingsSampler(model, X) sampler.initialize_assignments() constraint_add = 500 constraint_index = 0 n_iters = 100000 score_every = 1000 likelihoods = [] scores = [] for i in tqdm(xrange(n_iters + constraint_add)): if i != 0 and i % constraint_add == 0: sampler.add_constraint(train_constraints[constraint_index]) constraint_index += 1 sampler.sample() likelihoods.append(sampler.tree.marg_log_likelihood()) if i % score_every == 0: scores.append(float(sampler.tree.score_constraints(test_constraints)) / len(test_constraints)) scores.append(float(sampler.tree.score_constraints(test_constraints)) / len(test_constraints)) fontsize = 18 plt.figure() plt.xlim([0, n_iters + constraint_add]) plt.ylim([0, 1]) plt.xlabel("Iterations", fontsize=fontsize) plt.ylabel("Constraint Score", fontsize=fontsize) plt.plot(np.arange(0, n_iters + constraint_add + score_every, score_every), scores) plt.plot(scores) plt.legend(loc='best', fontsize=12) plt.savefig('online-scores.png', bbox_inches='tight') plt.figure() plt.xlim([0, n_iters + constraint_add]) plt.xlabel("Iterations", fontsize=fontsize) plt.ylabel("Data Log Likelihood", fontsize=fontsize) plt.plot(likelihoods) plt.legend(loc='best', fontsize=12) plt.savefig('online-likelihoods.png', bbox_inches='tight') final_tree = sampler.tree.copy() plt.figure() plot_tree_2d(final_tree, X, pca) for node in final_tree.dfs(): if node.is_leaf(): node.point = y[node.point] newick = final_tree.to_newick() tree = Phylo.read(StringIO(newick), 'newick') plt.figure() Phylo.draw_graphviz(tree, prog='neato') plt.savefig('tree.png', bbox_inches='tight') graph = Phylo.to_networkx(tree) with open('tree.nwk', 'w') as fp: print >>fp, newick, nx.write_dot(graph, 'tree.dot') plt.show()
{ "alphanum_fraction": 0.7382572076, "author": null, "avg_line_length": 27.8108108108, "converted": null, "ext": "py", "file": null, "hexsha": "df44038be7817e33a04df0a3950bbb630a81b95e", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-11-08T19:09:03.000Z", "max_forks_repo_forks_event_min_datetime": "2016-10-13T06:31:25.000Z", "max_forks_repo_head_hexsha": "502565c5bf02503c7bece09cddd93f9368da02c3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "islamazhar/trees", "max_forks_repo_path": "experiments/benchmark/create_online_graph.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "502565c5bf02503c7bece09cddd93f9368da02c3", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "islamazhar/trees", "max_issues_repo_path": "experiments/benchmark/create_online_graph.py", "max_line_length": 105, "max_stars_count": 3, "max_stars_repo_head_hexsha": "502565c5bf02503c7bece09cddd93f9368da02c3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "islamazhar/trees", "max_stars_repo_path": "experiments/benchmark/create_online_graph.py", "max_stars_repo_stars_event_max_datetime": "2019-01-22T19:11:58.000Z", "max_stars_repo_stars_event_min_datetime": "2017-01-18T21:20:26.000Z", "num_tokens": 767, "path": null, "reason": "import numpy,import networkx", "repo": null, "save_path": null, "sha": null, "size": 3087 }
[STATEMENT] lemma singular_simplex_empty: "topspace X = {} \<Longrightarrow> \<not> singular_simplex p X f" [PROOF STATE] proof (prove) goal (1 subgoal): 1. topspace X = {} \<Longrightarrow> \<not> singular_simplex p X f [PROOF STEP] by (simp add: singular_simplex_def continuous_map nonempty_standard_simplex)
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": null, "hexsha": null, "include": null, "lang": null, "length": 1, "llama_tokens": 109, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": null }
''' This file contains my implementation of the method to determine Stain Vector using SVD as outlined in the following paper:- Macenko, Marc, et al. "A method for normalizing histology slides for quantitative analysis." Biomedical Imaging: From Nano to Macro, 2009. ISBI'09. IEEE International Symposium on. IEEE, 2009. ''' import numpy as np import math import scipy.sparse.linalg from sklearn.preprocessing import normalize def rgb2od(img): img[np.where(img == 0)] = np.min(img[np.where(img > 0)]) return -np.log(img) def od2rgb(img): return np.exp(-img) def rodrigues_rot_matrix(v, k, theta): ''' This function implements rotation of vectors in v, along the directions specified in k, by an angle theta v,k are arrays like [[1,2,3]] theta is an array like [[1,2,3,....]] ''' v = v.astype('float32') k = k.astype('float32') theta = theta.astype('float32') k = k / math.sqrt(k[0, 0] * k[0, 0] + k[0, 1] * k[0, 1] + k[0, 2] * k[0, 2]) # normalize the normal vector crosskv = np.zeros(v[0, :].shape) # initialize cross of k and v with the correct dimension crosskv[0] = k[0, 1] * v[0, 2] - k[0, 2] * v[0, 1] crosskv[1] = k[0, 2] * v[0, 0] - k[0, 0] * v[0, 2] crosskv[2] = k[0, 0] * v[0, 1] - k[0, 1] * v[0, 0] theta_t = np.transpose(theta) return np.transpose(np.cos(theta_t) * np.transpose(v[0, :]) + \ np.sin(theta_t) * np.transpose(crosskv) + \ np.dot((1 - np.cos(theta_t)), k * np.dot(k, v[0, :]))) def GetOrthogonalBasis(image_rgb): w, h, d = image_rgb.shape img_od = np.transpose(np.reshape(rgb2od(image_rgb), [w * h, 3])) # remove pixels below threshold img_od_norm = np.sqrt(np.sum(img_od ** 2, 0)) good = img_od_norm > 0.15 img_od_good = img_od[:, good] phi_ortho = scipy.linalg.svd(img_od_good, full_matrices=False)[0] # reverse any axis having more than one negative value mask = phi_ortho < 0 cols = np.where(np.sum(mask, 0) > 1, 1, 0) phi_ortho = np.transpose([-phi_ortho[:, j] if cols[j] else phi_ortho[:, j] for j in range(len(cols))]) a_ortho = np.dot(scipy.linalg.pinv(phi_ortho), img_od) return phi_ortho, a_ortho def GetWedgeMacenko(image_rgb, squeeze_percentile): phi_ortho, a_ortho = GetOrthogonalBasis(image_rgb) image_od = np.dot(phi_ortho, a_ortho) phi_wedge = phi_ortho phi_plane = phi_ortho[:, [0, 1]] a_plane = a_ortho[[0, 1], :] # normalize a_plane a_plane_normalized = normalize(a_plane, axis=0, norm='l2') # find robust extreme angles min_a = np.percentile(np.arctan(a_plane_normalized[1, :] / a_plane_normalized[0, :]), squeeze_percentile) max_a = np.percentile(np.arctan(a_plane_normalized[1, :] / a_plane_normalized[0, :]), 100 - squeeze_percentile) phi_1 = rodrigues_rot_matrix(np.array([phi_plane[:, 0]]), \ np.array([np.cross(phi_plane[:, 0], phi_plane[:, 1])]), np.array([min_a])) phi_2 = rodrigues_rot_matrix(np.array([phi_plane[:, 0]]), \ np.array([np.cross(phi_plane[:, 0], phi_plane[:, 1])]), np.array([max_a])) phi_wedge[:, [0, 1]] = np.transpose([phi_1, phi_2]) a_wedge = np.dot(scipy.linalg.pinv(phi_ortho), image_od) return phi_wedge, a_wedge
{ "alphanum_fraction": 0.6259771497, "author": null, "avg_line_length": 35.3829787234, "converted": null, "ext": "py", "file": null, "hexsha": "609dbba606f3d54d89870d3f130a3ee6d6dfa052", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "05a4a22ee432e51e7da5a849ff0b9584ad3228fa", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "gsaha36/B-CellClassification", "max_forks_repo_path": "src/macenko.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "05a4a22ee432e51e7da5a849ff0b9584ad3228fa", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "gsaha36/B-CellClassification", "max_issues_repo_path": "src/macenko.py", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "05a4a22ee432e51e7da5a849ff0b9584ad3228fa", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "gsaha36/B-CellClassification", "max_stars_repo_path": "src/macenko.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1044, "path": null, "reason": "import numpy,import scipy", "repo": null, "save_path": null, "sha": null, "size": 3326 }
library(ggplot2) library(dplyr) library(shiny) library(lubridate) library(stringr) library(gridExtra) library(RCurl) library(scales) shinyServer(function(input, output) { ########LOAD SONAR####### load("data/sonar.rda") ########GET REALTIME##### load("data/rt_dat.rda") ########TEST FISH######## load("data/testFish.rda") #input <- list(year = c(2002,2012), # start_date = "06-30", # end_date = "08-05") foo <- sonar year(foo$date) <- 2015 average_sonar <- foo %>% group_by(date) %>% summarize(mean = mean(n)) sonar_reactive <- reactive({ year(sonar$date) <- 2014 factor(sonar$year) start_year <- input$year[1] end_year <- input$year[2] start_date <- ymd(paste("2014", input$start_date, sep = "-")) end_date <- ymd(paste("2014", input$end_date, sep = "-")) sonar %>% filter(year >= start_year, year <= end_year, date >= start_date, date <= end_date) %>% mutate(year = factor(year)) #sonar_reactive <- sonar }) realtime_reactive <- reactive({ return(rt_dat2) #realtime_reactive <- rt_dat }) ######################## #######PLOTING######### prior_barchart <- reactive({ p <- ggplot(data = sonar_reactive(), aes(x = date, y = n, group = year, fill = year)) + geom_bar(stat = "identity") + ylab("Cumulative Daily Count Across Years") + xlab("Date") + scale_y_continuous(labels =comma) return(p) }) ######Publishing######### output$realtime <- renderPlot({ x <- getURL("http://www.adfg.alaska.gov/sf/FishCounts/index.cfm?ADFG=export.excel&countLocationID=40&year=2015&speciesID=420") this_season <- read.csv(text = x, sep = "\t") this_season$count_date <- ymd(paste(this_season$year, this_season$count_date)) blank <- this_season[1,] blank$fish_count <- 0 blank$count_date <- blank$count_date - days(1) this_season <- rbind(this_season, blank) ggplot(data = average_sonar, aes(x = date, y = mean)) + geom_line() + geom_bar(data = this_season, aes(x = count_date, y = fish_count), fill = "red", stat = "identity") + ylab("Fish Count") + xlab("Date") + ggtitle("Kenai River Sockeye") + geom_vline(xintercept = as.numeric(ymd("2015-07-10")), linetype = "dashed", colour="#000099") + geom_vline(xintercept = as.numeric(ymd("2015-07-31")), linetype = "dashed", colour="#000099") + scale_y_continuous(labels =comma) }) ###TABSET: PRIOR DATA#### output$linechart <- renderPlot({ print(prior_linechart()) }) output$barchart <- renderPlot({ p <- prior_barchart() print(p) }) }) ##TABSET: ABOUT
{ "alphanum_fraction": 0.5965824666, "author": null, "avg_line_length": 28.6382978723, "converted": null, "ext": "r", "file": null, "hexsha": "f69961f7341909363aef610861dbd7627321ab09", "include": null, "lang": "R", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-03-25T21:05:40.000Z", "max_forks_repo_forks_event_min_datetime": "2020-03-25T21:05:40.000Z", "max_forks_repo_head_hexsha": "5139e294b3864089c2e4a667b40bed66dc17d8c6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "codeforanchorage/shiny-server", "max_forks_repo_path": "kenaisockeye/server.r", "max_issues_count": 1, "max_issues_repo_head_hexsha": "5139e294b3864089c2e4a667b40bed66dc17d8c6", "max_issues_repo_issues_event_max_datetime": "2015-10-20T20:44:49.000Z", "max_issues_repo_issues_event_min_datetime": "2015-10-20T20:41:10.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "codeforanchorage/shiny-server", "max_issues_repo_path": "kenaisockeye/server.r", "max_line_length": 128, "max_stars_count": null, "max_stars_repo_head_hexsha": "5139e294b3864089c2e4a667b40bed66dc17d8c6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "codeforanchorage/shiny-server", "max_stars_repo_path": "kenaisockeye/server.r", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 799, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2692 }
using Test using Plots function test_backwardpass_sqrt!(res::SolverIterResults,solver::Solver,bp::BackwardPass) # Get problem sizes res = results2 n,m,N = get_sizes(solver) m̄,mm = get_num_controls(solver) n̄,nn = get_num_states(solver) # Objective costfun = solver.obj.cost dt = solver.dt X = res.X; U = res.U; K = res.K; d = res.d; Su = res.S; s = res.s for k = 1:N-1 res.S[k] = zeros(nn+mm,nn) end Su = res.S # # for now just re-instantiate # bp = BackwardPass(nn,mm,N) # Qx = bp.Qx; Qu = bp.Qu; Qxx = bp.Qxx; Quu = bp.Quu; Qux = bp.Qux # Quu_reg = bp.Quu_reg; Qux_reg = bp.Qux_reg # Boundary Conditions lxx,lx = taylor_expansion(costfun, X[N][1:n]) # Initialize expected change in cost-to-go Δv = zeros(2) # Terminal constraints if res isa ConstrainedIterResults C = res.C; Iμ = res.Iμ; λ = res.λ Cx = res.Cx; Cu = res.Cu Iμ_sqrt = sqrt.(Iμ[N]) Su[N][1:nn,1:nn] = chol_plus(cholesky(lxx).U,Iμ_sqrt*Cx[N]) s[N] = lx + Cx[N]'*(Iμ[N]*C[N] + λ[N]) @test isapprox(lxx + Cx[N]'*Iμ[N]*Cx[N],Su[N]'*Su[N]) else Su[N] = cholesky(lxx).U s[N] = lx end # Backward pass k = N-1 while k >= 1 x = X[k][1:n] u = U[k][1:m] h = sqrt(dt) expansion = taylor_expansion(costfun,x,u) lxx,luu,lux,lx,_lu = expansion # Compute gradients of the dynamics fdx, fdu = res.fdx[k], res.fdu[k] # Gradients and Hessians of Taylor Series Expansion of Q Qx = dt*lx + fdx'*s[k+1] Qu = dt*_lu + fdu'*s[k+1] Wxx = chol_plus(cholesky(dt*lxx).U, Su[k+1]*fdx) Wuu = chol_plus(cholesky(dt*luu).U, Su[k+1]*fdu) Qux = dt*lux + (fdu'*Su[k+1]')*(Su[k+1]*fdx) @test isapprox(dt*lxx + fdx'*Su[k+1]'*Su[k+1]*fdx, Wxx'*Wxx) @test isapprox(dt*luu + fdu'*Su[k+1]'*Su[k+1]*fdu, Wuu'*Wuu) # Constraints if res isa ConstrainedIterResults Iμ_sqrt = sqrt.(Iμ[k]) Qx += Cx[k]'*(Iμ[k]*C[k] + λ[k]) Qu += Cu[k]'*(Iμ[k]*C[k] + λ[k]) Wxx = chol_plus(Wxx,Iμ_sqrt*Cx[k]) Wuu = chol_plus(Wuu,Iμ_sqrt*Cu[k]) Qux += Cu[k]'*Iμ[k]*Cx[k] @test isapprox(dt*lxx + fdx'*Su[k+1]'*Su[k+1]*fdx + Cx[k]'*Iμ[k]*Cx[k], Wxx'*Wxx) @test isapprox(dt*luu + fdu'*Su[k+1]'*Su[k+1]*fdu + Cu[k]'*Iμ[k]*Cu[k], Wuu'*Wuu) end # if solver.opts.bp_reg_type == :state Wuu_reg = chol_plus(Wuu,sqrt(res.ρ[1])*I*fdu) Qux_reg = Qux + res.ρ[1]*fdu'*fdx elseif solver.opts.bp_reg_type == :control Wuu_reg = chol_plus(Wuu,sqrt(res.ρ[1])*Matrix(I,m,m)) Qux_reg = Qux end #TODO find better PD check for Wuu_reg # # Regularization # if !isposdef(Hermitian(Array(Wuu_reg))) # need to wrap Array since isposdef doesn't work for static arrays # # increase regularization # regularization_update!(res,solver,:increase) # # # reset backward pass # k = N-1 # Δv[1] = 0. # Δv[2] = 0. # continue # end # Compute gains K[k] = -Wuu_reg\(Wuu_reg'\Qux_reg) d[k] = -Wuu_reg\(Wuu_reg'\Qu) # Calculate cost-to-go s[k] = Qx + (K[k]'*Wuu')*(Wuu*d[k]) + K[k]'*Qu + Qux'*d[k] tmp1 = (Wxx')\Qux' tmp2 = cholesky(Wuu'*Wuu - tmp1'*tmp1).U Su[k][1:nn,1:nn] = Wxx + tmp1*K[k] Su[k][nn+1:nn+mm,1:nn] = tmp2*K[k] # calculated change is cost-to-go over entire trajectory Δv[1] += d[k]'*Qu Δv[2] += 0.5*d[k]'*Wuu'*Wuu*d[k] k = k - 1; end # decrease regularization after backward pass regularization_update!(res,solver,:decrease) return Δv end function chol_plus(A,B) n1,m = size(A) n2 = size(B,1) P = zeros(n1+n2,m) P[1:n1,:] = A P[n1+1:end,:] = B return qr(P).R end # model_dubins, obj_uncon_dubins = TrajectoryOptimization.Dynamics.dubinscar # # # dubins car # u_min_dubins = [-1; -1] # u_max_dubins = [1; 1] # x_min_dubins = [0; -100; -100] # x_max_dubins = [1.0; 100; 100] # obj_con_dubins = ConstrainedObjective(obj_uncon_dubins, u_min=u_min_dubins, u_max=u_max_dubins, x_min=x_min_dubins, x_max=x_max_dubins) # # # -Constrained objective # # model = model_dubins # obj = obj_con_dubins # u_max = u_max_dubins # u_min = u_min_dubins # Solver options # Set up quadrotor model, objective, solver intergrator = :rk4 dt = 0.005 N = 201 tf = 10.0 r_quad = 3.0 model, = TrajectoryOptimization.Dynamics.quadrotor n = model.n m = model.m # -initial state x0 = zeros(n) x0[1:3] = [0.; 0.; 0.] q0 = [1.;0.;0.;0.] x0[4:7] = q0 # -final state xf = copy(x0) xf[1:3] = [0.;40.;0.] # xyz position xf[4:7] = q0 # -control limits u_min = 0.0 u_max = 5.0 Q = (1e-1)*Matrix(I,n,n) Q[4,4] = 1.0 Q[5,5] = 1.0 Q[6,6] = 1.0 Q[7,7] = 1.0 R = (1.0)*Matrix(I,m,m) Qf = (1000.0)*Matrix(I,n,n) # obstacles constraint r_sphere = 3.0 spheres = ((0.,10.,0.,r_sphere),(0.,20.,0.,r_sphere),(0.,30.,0.,r_sphere)) n_spheres = 3 function cI(c,x,u) for i = 1:n_spheres c[i] = sphere_constraint(x,spheres[i][1],spheres[i][2],spheres[i][3],spheres[i][4]+r_quad) end c end # unit quaternion constraint function cE(c,x,u) c = sqrt(x[4]^2 + x[5]^2 + x[6]^2 + x[7]^2) - 1.0 end obj_uncon = LQRObjective(Q, R, Qf, tf, x0, xf) obj = TrajectoryOptimization.ConstrainedObjective(obj_uncon,u_min=u_min,u_max=u_max,cI=cI,cE=cE) # Solver solver = Solver(model,obj,integration=intergrator,N=N) solver.opts.bp_reg_initial = 1.0 U0 = ones(solver.model.m,solver.N) results1 = init_results(solver,Array{Float64}(undef,0,0),U0) results2 = init_results(solver,Array{Float64}(undef,0,0),U0) rollout!(results1,solver) rollout!(results2,solver) update_jacobians!(results1, solver) update_jacobians!(results2, solver) n,m,N = get_sizes(solver) m̄,mm = get_num_controls(solver) n̄,nn = get_num_states(solver) bp = BackwardPass(nn,mm,solver.N) v1 = _backwardpass!(results1,solver,bp) v2 = test_backwardpass_sqrt!(results2,solver,bp) @test isapprox(v1[1:2], v2[1:2]) @test isapprox(to_array(results1.K),to_array(results2.K)) @test isapprox(to_array(results1.d),to_array(results2.d)) S_sqrt = [zeros(nn,nn) for k = 1:N] cond_normal = zeros(N) cond_sqrt = zeros(N) for k = 1:N S_sqrt[k] = results2.S[k]'*results2.S[k] cond_normal[k] = cond(results1.S[k]) cond_sqrt[k] = cond(results2.S[k]) end @test isapprox(to_array(results1.S),to_array(S_sqrt)) plot(cond_normal,label="bp") plot(cond_sqrt,title="Condition number",label="sqrt bp")
{ "alphanum_fraction": 0.5873655914, "author": null, "avg_line_length": 27.1093117409, "converted": null, "ext": "jl", "file": null, "hexsha": "92b140643f84458f583997667a26b17e4a9ec7ef", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c036b790555553b3477c7bebeaea118e17e43142", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "GathererA/TrajectoryOptimization.jl", "max_forks_repo_path": "development/backwardpass_sqrt_dev.jl", "max_issues_count": null, "max_issues_repo_head_hexsha": "c036b790555553b3477c7bebeaea118e17e43142", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "GathererA/TrajectoryOptimization.jl", "max_issues_repo_path": "development/backwardpass_sqrt_dev.jl", "max_line_length": 137, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c036b790555553b3477c7bebeaea118e17e43142", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "GathererA/TrajectoryOptimization.jl", "max_stars_repo_path": "development/backwardpass_sqrt_dev.jl", "max_stars_repo_stars_event_max_datetime": "2020-05-01T16:16:08.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-01T16:16:08.000Z", "num_tokens": 2468, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 6696 }
# Cython compile instructions from setuptools import setup from setuptools import Extension, find_packages import numpy import os import glob from sys import platform import sys import sysconfig # py_modules = ['alphaimpute2'] # py_modules += [os.path.join('src','General', 'InputOutput')] # py_modules += [os.path.join('src','General', 'Pedigree')] # src_modules = [] # src_modules += glob.glob(os.path.join('src','tinyhouse', '*.py')) # src_modules += glob.glob(os.path.join('src','Imputation', '*.py')) # src_modules = [os.path.splitext(file)[0] for file in src_modules] # py_modules += src_modules setup( name="AlphaImpute2", version="0.0.3", author="Andrew Whalen", author_email="awhalen@roslin.ed.ac.uk", description="An imputation software for massive livestock populations.", long_description="An imputation software for massive livestock populations.", long_description_content_type="text/markdown", url="", license="MIT license", packages=['alphaimpute2', 'alphaimpute2.tinyhouse','alphaimpute2.Imputation'], package_dir={'': 'src'}, classifiers=[ "Programming Language :: Python :: 3", ], entry_points = { 'console_scripts': [ 'AlphaImpute2=alphaimpute2.alphaimpute2:main' ], }, install_requires=[ 'numpy>=1.19', 'numba>=0.49.0' ] )
{ "alphanum_fraction": 0.6735143067, "author": null, "avg_line_length": 27.26, "converted": null, "ext": "py", "file": null, "hexsha": "80579bbeb51a444af72162d9b2ccae3e34e4224c", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2711b5bc42359fa059c5d2381d9a6241b9881577", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sgavril/AlphaImpute2", "max_forks_repo_path": "setup.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "2711b5bc42359fa059c5d2381d9a6241b9881577", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sgavril/AlphaImpute2", "max_issues_repo_path": "setup.py", "max_line_length": 82, "max_stars_count": null, "max_stars_repo_head_hexsha": "2711b5bc42359fa059c5d2381d9a6241b9881577", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sgavril/AlphaImpute2", "max_stars_repo_path": "setup.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 345, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1363 }
/* Copyright (c) 2014, Project OSRM contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "../../data_structures/dynamic_graph.hpp" #include "../../util/make_unique.hpp" #include "../../typedefs.h" #include <boost/test/unit_test.hpp> #include <boost/test/test_case_template.hpp> #include <boost/mpl/list.hpp> #include <random> #include <unordered_map> BOOST_AUTO_TEST_SUITE(dynamic_graph) struct TestData { EdgeID id; }; typedef DynamicGraph<TestData> TestDynamicGraph; typedef TestDynamicGraph::InputEdge TestInputEdge; BOOST_AUTO_TEST_CASE(find_test) { /* * (0) -1-> (1) * ^ ^ * 2 5 * | | * (3) -3-> (4) * <-4- */ std::vector<TestInputEdge> input_edges = { TestInputEdge{0, 1, TestData{1}}, TestInputEdge{3, 0, TestData{2}}, TestInputEdge{3, 4, TestData{3}}, TestInputEdge{4, 3, TestData{4}}, TestInputEdge{3, 0, TestData{5}} }; TestDynamicGraph simple_graph(5, input_edges); auto eit = simple_graph.FindEdge(0, 1); BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 1); eit = simple_graph.FindEdge(1, 0); BOOST_CHECK_EQUAL(eit, SPECIAL_EDGEID); eit = simple_graph.FindEdgeInEitherDirection(1, 0); BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 1); bool reverse = false; eit = simple_graph.FindEdgeIndicateIfReverse(1, 0, reverse); BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 1); BOOST_CHECK(reverse); eit = simple_graph.FindEdge(3, 1); BOOST_CHECK_EQUAL(eit, SPECIAL_EDGEID); eit = simple_graph.FindEdge(0, 4); BOOST_CHECK_EQUAL(eit, SPECIAL_EDGEID); eit = simple_graph.FindEdge(3, 4); BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 3); eit = simple_graph.FindEdgeInEitherDirection(3, 4); BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 3); eit = simple_graph.FindEdge(3, 0); BOOST_CHECK_EQUAL(simple_graph.GetEdgeData(eit).id, 2); } BOOST_AUTO_TEST_SUITE_END()
{ "alphanum_fraction": 0.7353673724, "author": null, "avg_line_length": 33.1134020619, "converted": null, "ext": "cpp", "file": null, "hexsha": "27dc7dc68f29ce08a85516358a029799d3b4faeb", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1493, "max_forks_repo_forks_event_max_datetime": "2022-03-21T09:16:49.000Z", "max_forks_repo_forks_event_min_datetime": "2015-09-30T10:43:06.000Z", "max_forks_repo_head_hexsha": "d22fe2b6e0beee697f096e931df97a64f9db9dc1", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "mbrukman/omim", "max_forks_repo_path": "3party/osrm/osrm-backend/unit_tests/data_structures/dynamic_graph.cpp", "max_issues_count": 7549, "max_issues_repo_head_hexsha": "d22fe2b6e0beee697f096e931df97a64f9db9dc1", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:04:22.000Z", "max_issues_repo_issues_event_min_datetime": "2015-09-30T10:52:53.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "mbrukman/omim", "max_issues_repo_path": "3party/osrm/osrm-backend/unit_tests/data_structures/dynamic_graph.cpp", "max_line_length": 80, "max_stars_count": 4879, "max_stars_repo_head_hexsha": "390236365749e0525b9229684132c2888d11369d", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "kudlav/organicmaps", "max_stars_repo_path": "3party/osrm/osrm-backend/unit_tests/data_structures/dynamic_graph.cpp", "max_stars_repo_stars_event_max_datetime": "2022-03-31T18:43:03.000Z", "max_stars_repo_stars_event_min_datetime": "2015-09-30T10:56:36.000Z", "num_tokens": 804, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 3212 }
#!/bin/python import numpy as np def binary_step(x): return np.where(x < 0, 0, 1) def binary_step_(x): return np.where(x != 0, 0, np.inf) def linear(x, a=1): return a * x def linear_(x, a=1): return a def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_(x): return sigmoid(x) * (1-sigmoid(x)) def tanh(x): return (2 / (1 + np.exp(-2*x))) -1 def tanh_(x): return 1 - np.power(tanh(x), 2) def relu(x): """Rectified Linear Unit (ReLU) (Hahnloser et al., 2000; Jarrett et al., 2009; Nair & Hinton, 2010)""" return np.where(x < 0, 0, x) def relu_(x): return np.where(x < 0, 0, 1) def leaky_relu(x, a=0.01): """Leaky ReLU (LReLU) (Maas et al., 2013)""" return np.where(x < 0, a * x, x) def leaky_relu_(x, a=0.01): return np.where(x < 0, a, 1) def elu(x, a=1): """Exponential Linear Unit (ELU) (Clevert et al., 2015)""" return np.where(x < 0, a * (np.exp(x)-1), x) def elu_(x, a=1): return np.where(x < 0, a * (np.exp(x)), 1) def swish(x, beta=1): """SWISH: A SELF-GATED ACTIVATION FUNCTION https://arxiv.org/pdf/1710.05941v1.pdf""" return 2 * x * sigmoid(beta * x) def swish_(x, beta=1): return swish(x, beta) + sigmoid(x)*(1 - swish(x, beta)) def eswish(x, beta=1): """Eswish https://arxiv.org/abs/1801.07145 > Eswish is just a generalization of the Swish activation function (x*sigmoid(x)), which is multiplied by a parameter beta """ return beta * x * sigmoid(x) def eswish_(x, beta=1): return eswish(x, beta) + sigmoid(x) * (beta - eswish(x, beta))
{ "alphanum_fraction": 0.5881612091, "author": null, "avg_line_length": 23.3529411765, "converted": null, "ext": "py", "file": null, "hexsha": "0821fe8e944f666d6fb944b172f6ec793382c375", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-11-03T08:57:23.000Z", "max_forks_repo_forks_event_min_datetime": "2020-11-03T08:57:23.000Z", "max_forks_repo_head_hexsha": "e1a2bec1b8e36b039807ec02c53ee3970bb4e255", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Zabamund/misc", "max_forks_repo_path": "scripts/demos/activation_funcs.py", "max_issues_count": 4, "max_issues_repo_head_hexsha": "e1a2bec1b8e36b039807ec02c53ee3970bb4e255", "max_issues_repo_issues_event_max_datetime": "2019-04-13T02:18:12.000Z", "max_issues_repo_issues_event_min_datetime": "2019-04-01T20:22:41.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Zabamund/misc", "max_issues_repo_path": "scripts/demos/activation_funcs.py", "max_line_length": 106, "max_stars_count": 8, "max_stars_repo_head_hexsha": "e1a2bec1b8e36b039807ec02c53ee3970bb4e255", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Zabamund/misc", "max_stars_repo_path": "scripts/demos/activation_funcs.py", "max_stars_repo_stars_event_max_datetime": "2021-05-21T06:34:31.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-18T18:38:18.000Z", "num_tokens": 573, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1588 }
"""sfh dataset.""" import os import glob from astropy.table import Table, vstack import tensorflow as tf import tensorflow_datasets as tfds import numpy as np # TODO(sfh): Markdown description that will appear on the catalog page. _DESCRIPTION = """ # SFH Dataset Dataset for generative models. Data is extracted from csv files of TNG100 snapshots For each galaxy, the following sequence are stored into the dataset: - time - SFR_halfRad - SFR_Rad - SFR_Max - Mstar_Half - Mstar - Mask, 0 is value has been inserted, 1 otherwise """ # TODO(sfh): BibTeX citation _CITATION = """ """ N_TIMESTEPS = 100 class Sfh(tfds.core.GeneratorBasedBuilder): """DatasetBuilder for sfh dataset.""" VERSION = tfds.core.Version("1.0.0") RELEASE_NOTES = { "1.0.0": "Initial release.", } MANUAL_DOWNLOAD_INSTRUCTIONS = "TBD" def _info(self) -> tfds.core.DatasetInfo: """Returns the dataset metadata.""" # TODO(sfh): Specifies the tfds.core.DatasetInfo object return tfds.core.DatasetInfo( builder=self, description=_DESCRIPTION, features=tfds.features.FeaturesDict( { "time": tfds.features.Tensor( shape=(N_TIMESTEPS,), dtype=tf.dtypes.float32), "SFR_halfRad": tfds.features.Tensor( shape=(N_TIMESTEPS,), dtype=tf.dtypes.float32), "SFR_Rad": tfds.features.Tensor( shape=(N_TIMESTEPS,), dtype=tf.dtypes.float32), "SFR_Max": tfds.features.Tensor( shape=(N_TIMESTEPS,), dtype=tf.dtypes.float32), "Mstar_Half": tfds.features.Tensor( shape=(N_TIMESTEPS,), dtype=tf.dtypes.float32), "Mstar": tfds.features.Tensor( shape=(N_TIMESTEPS,), dtype=tf.dtypes.float32), "Mask": tfds.features.Tensor( shape=(N_TIMESTEPS,), dtype=tf.dtypes.int32), } ), # If there's a common (input, target) tuple from the # features, specify them here. They'll be used if # `as_supervised=True` in `builder.as_dataset`. supervised_keys=(None), # Set to `None` to disable homepage="https://dataset-homepage/", citation=_CITATION, ) def _split_generators(self, dl_manager: tfds.download.DownloadManager): """Returns SplitGenerators.""" # TODO(sfh): Downloads the data and defines the splits data_path = os.path.join(dl_manager.manual_dir, "cats_SFH") #download_and_extract("https://todo-data-url") # TODO(sfh): Returns the Dict[split names, Iterator[Key, Example]] return [ tfds.core.SplitGenerator( name=tfds.Split.TRAIN, # Send paths to fits files and the TNG100_SDSS_MajorMergers.csv to _generate_examples method gen_kwargs={"data_path": data_path}, ), ] def _generate_examples(self, data_path): """Yields examples.""" # To complete the partial SFH (the ones not starting at the beginning # of the Universe) we need to have all the SnapNums with the associated # time. We take those from a know SFH. empty_sfh = Table.read(os.path.join(data_path, "TNG100_mainprojenitors_102694.csv")) empty_sfh['SFR_halfRad'] = 0. empty_sfh['SFR_Rad'] = 0. empty_sfh['SFR_Max'] = 0. empty_sfh['Mstar_Half'] = 0. empty_sfh['Mstar'] = 0 for filename in glob.glob(data_path+"/*.csv"): object_id = filename.split("_")[-1] sfh = Table.read(filename) mask = np.zeros((N_TIMESTEPS,), dtype=np.int32) mask[99-sfh['SnapNUm']] = 1. tmp_sfh = empty_sfh.copy() for k in empty_sfh.colnames: tmp_sfh[k][99-sfh['SnapNUm']] = sfh[k] yield object_id, { "time": np.array(tmp_sfh['time']).astype('float32'), "SFR_halfRad": np.array(tmp_sfh['SFR_halfRad']).astype('float32'), "SFR_Rad": np.array(tmp_sfh['SFR_Rad']).astype('float32'), "SFR_Max": np.array(tmp_sfh['SFR_Max']).astype('float32'), "Mstar_Half": np.array(tmp_sfh['Mstar_Half']).astype('float32'), "Mstar": np.array(tmp_sfh['Mstar']).astype('float32'), "Mask": mask }
{ "alphanum_fraction": 0.5751691032, "author": null, "avg_line_length": 38.1916666667, "converted": null, "ext": "py", "file": null, "hexsha": "f432a07009769640a85d374a09b9c7a7034cd21f", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2022-01-03T09:58:54.000Z", "max_forks_repo_forks_event_min_datetime": "2021-12-06T10:56:48.000Z", "max_forks_repo_head_hexsha": "25a7b7956e4fd92f7a7858e85408424123fb4276", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mhuertascompany/sfh-inference", "max_forks_repo_path": "sfh/datasets/sfh/sfh.py", "max_issues_count": 17, "max_issues_repo_head_hexsha": "25a7b7956e4fd92f7a7858e85408424123fb4276", "max_issues_repo_issues_event_max_datetime": "2022-03-25T17:17:48.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-04T16:15:51.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "mhuertascompany/sfh-inference", "max_issues_repo_path": "sfh/datasets/sfh/sfh.py", "max_line_length": 114, "max_stars_count": 4, "max_stars_repo_head_hexsha": "25a7b7956e4fd92f7a7858e85408424123fb4276", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mhuertascompany/sfh-inference", "max_stars_repo_path": "sfh/datasets/sfh/sfh.py", "max_stars_repo_stars_event_max_datetime": "2022-02-18T10:04:26.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-06T16:10:26.000Z", "num_tokens": 1096, "path": null, "reason": "import numpy,from astropy", "repo": null, "save_path": null, "sha": null, "size": 4583 }
import train_synth.config as config from src.utils.data_manipulation import generate_target_others, denormalize_mean_variance from train_synth.dataloader import DataLoaderEval from src.utils.parallel import DataParallelModel from src.utils.utils import generate_word_bbox, get_weighted_character_target, calculate_fscore, _init_fn import pytesseract import cv2 import json from torch.utils.data import DataLoader import torch from tqdm import tqdm import os import numpy as np import matplotlib.pyplot as plt os.environ['CUDA_VISIBLE_DEVICES'] = str(config.num_cuda) # Specify which GPU you want to use def synthesize( dataloader, model, base_path_affinity, base_path_character, base_path_bbox, base_path_char, base_path_aff, base_path_json): """ Given a path to a set of images, and path to a pre-trained model, generate the character heatmap and affinity heatmap :param dataloader: A Pytorch dataloader for loading and resizing the images of the folder :param model: A pre-trained model :param base_path_affinity: Path where to store the predicted affinity heatmap :param base_path_character: Path where to store the predicted character heatmap :param base_path_bbox: Path where to store the word_bbox overlapped on images :param base_path_aff: Path where to store the predicted affinity bbox :param base_path_char: Path where to store the predicted character bbox :param base_path_json: Path where to store the predicted bbox in json format :return: None """ with torch.no_grad(): model.eval() iterator = tqdm(dataloader) for no, (image, image_name, original_dim) in enumerate(iterator): if config.use_cuda: image = image.cuda() output = model(image) if type(output) == list: # If using custom DataParallelModel this is necessary to convert the list to tensor output = torch.cat(output, dim=0) output = output.data.cpu().numpy() output[output < 0] = 0 output[output > 1] = 1 original_dim = original_dim.cpu().numpy() for i in range(output.shape[0]): # --------- Resizing it back to the original image size and saving it ----------- # image_i = denormalize_mean_variance(image[i].data.cpu().numpy().transpose(1, 2, 0)) max_dim = original_dim[i].max() resizing_factor = 768/max_dim before_pad_dim = [int(original_dim[i][0]*resizing_factor), int(original_dim[i][1]*resizing_factor)] output[i, :, :, :] = np.uint8(output[i, :, :, :]*255) height_pad = (768 - before_pad_dim[0])//2 width_pad = (768 - before_pad_dim[1])//2 image_i = cv2.resize( image_i[height_pad:height_pad + before_pad_dim[0], width_pad:width_pad + before_pad_dim[1]], (original_dim[i][1], original_dim[i][0]) ) character_bbox = cv2.resize( output[i, 0, height_pad:height_pad + before_pad_dim[0], width_pad:width_pad + before_pad_dim[1]], (original_dim[i][1], original_dim[i][0]) )/255 affinity_bbox = cv2.resize( output[i, 1, height_pad:height_pad + before_pad_dim[0], width_pad:width_pad + before_pad_dim[1]], (original_dim[i][1], original_dim[i][0]) )/255 predicted_bbox = generate_word_bbox( character_bbox, affinity_bbox, character_threshold=config.threshold_character, affinity_threshold=config.threshold_affinity, word_threshold=config.threshold_word, character_threshold_upper=config.threshold_character_upper, affinity_threshold_upper=config.threshold_affinity_upper, scaling_character=config.scale_character, scaling_affinity=config.scale_affinity ) word_bbox = predicted_bbox['word_bbox'] char_bbox = np.concatenate(predicted_bbox['characters'], axis=0) aff_bbox = np.concatenate(predicted_bbox['affinity'], axis=0) word_image = image_i.copy() char_image = image_i.copy() aff_image = image_i.copy() cv2.drawContours(word_image, word_bbox, -1, (0, 255, 0), 2) cv2.drawContours(char_image, char_bbox, -1, (0, 255, 0), 2) cv2.drawContours(aff_image, aff_bbox, -1, (0, 255, 0), 2) # plt.imsave( # base_path_char + '/' + '.'.join(image_name[i].split('.')[:-1]) + '.png', # char_image) # plt.imsave( # base_path_aff + '/' + '.'.join(image_name[i].split('.')[:-1]) + '.png', # aff_image) plt.imsave( base_path_bbox + '/' + '.'.join(image_name[i].split('.')[:-1]) + '.png', word_image) # plt.imsave( # base_path_character + '/' + '.'.join(image_name[i].split('.')[:-1]) + '.png', # np.float32(character_bbox > config.threshold_character), # cmap='gray') # plt.imsave( # base_path_affinity+'/'+'.'.join(image_name[i].split('.')[:-1])+'.png', # np.float32(affinity_bbox > config.threshold_affinity), # cmap='gray') predicted_bbox['word_bbox'] = predicted_bbox['word_bbox'].tolist() predicted_bbox['characters'] = [_.tolist() for _ in predicted_bbox['characters']] predicted_bbox['affinity'] = [_.tolist() for _ in predicted_bbox['affinity']] with open(base_path_json + '/' + '.'.join(image_name[i].split('.')[:-1])+'.json', 'w') as f: json.dump(predicted_bbox, f) boxes_printed = 0 BOX = [] for boxes in predicted_bbox['word_bbox']: for box in boxes: BOX.append(box[0]) BOX1= [] BOX2 = [] count = 1 for boxes in BOX: BOX1.append(boxes) if count%4 ==0: BOX2.append(BOX1) BOX1 = [] count += 1 for box in BOX2: x = [p[0] for p in box] y = [p[1] for p in box] min_x = min(x) max_x = max(x) min_y = min(y) max_y = max(y) img = image_i.copy() crop_img = img[min_y:max_y, min_x:max_x] text = pytesseract.image_to_string(crop_img).rstrip() boxes_printed += 1 f = open("./text_folder" + '/' + '.'.join(image_name[i].split('.')[:-1]) + '.txt', "a") f.write(text) f.write('\n') f.close() f = open("./text_folder" + '/' + '.'.join(image_name[i].split('.')[:-1]) + '.txt', "a") f.write("Total number of boxes : " + str(len(BOX2))) f.write('\n') f.write("Total number of boxes printed: " + str(boxes_printed)) f.close() def generate_next_targets(original_dim, output, image, base_target_path, image_name, annots, dataloader, no): visualize = config.visualize_generated and no % config.visualize_freq == 0 and no != 0 max_dim = original_dim.max() resizing_factor = 768 / max_dim before_pad_dim = [int(original_dim[0] * resizing_factor), int(original_dim[1] * resizing_factor)] output = np.uint8(output * 255) height_pad = (768 - before_pad_dim[0]) // 2 width_pad = (768 - before_pad_dim[1]) // 2 character_bbox = cv2.resize( output[0, height_pad:height_pad + before_pad_dim[0], width_pad:width_pad + before_pad_dim[1]], (original_dim[1]//2, original_dim[0]//2)) / 255 affinity_bbox = cv2.resize( output[1, height_pad:height_pad + before_pad_dim[0], width_pad:width_pad + before_pad_dim[1]], (original_dim[1]//2, original_dim[0]//2)) / 255 # Generating word-bbox given character and affinity heatmap generated_targets = generate_word_bbox( character_bbox, affinity_bbox, character_threshold=config.threshold_character, affinity_threshold=config.threshold_affinity, word_threshold=config.threshold_word, character_threshold_upper=config.threshold_character_upper, affinity_threshold_upper=config.threshold_affinity_upper, scaling_character=config.scale_character, scaling_affinity=config.scale_affinity ) generated_targets['word_bbox'] = generated_targets['word_bbox'] * 2 generated_targets['characters'] = [i * 2 for i in generated_targets['characters']] generated_targets['affinity'] = [i * 2 for i in generated_targets['affinity']] if visualize: character_bbox = cv2.resize((character_bbox*255).astype(np.uint8), (original_dim[1], original_dim[0])) / 255 affinity_bbox = cv2.resize((affinity_bbox*255).astype(np.uint8), (original_dim[1], original_dim[0])) / 255 image_i = denormalize_mean_variance(image.data.cpu().numpy().transpose(1, 2, 0)) image_i = cv2.resize( image_i[height_pad:height_pad + before_pad_dim[0], width_pad:width_pad + before_pad_dim[1]], (original_dim[1], original_dim[0]) ) # Saving affinity heat map plt.imsave( base_target_path + '_predicted/affinity/' + '.'.join(image_name.split('.')[:-1]) + '.png', np.float32(affinity_bbox > config.threshold_affinity_upper), cmap='gray') # Saving character heat map plt.imsave( base_target_path + '_predicted/character/' + '.'.join(image_name.split('.')[:-1]) + '.png', np.float32(character_bbox > config.threshold_character_upper), cmap='gray') cv2.drawContours( image_i, generated_targets['word_bbox'], -1, (0, 255, 0), 2) # Saving word bbox drawn on the original image plt.imsave( base_target_path + '_predicted/word_bbox/' + '.'.join(image_name.split('.')[:-1]) + '.png', image_i) predicted_word_bbox = generated_targets['word_bbox'].copy() # --------------- PostProcessing for creating the targets for the next iteration ---------------- # generated_targets = get_weighted_character_target( generated_targets, {'bbox': annots['bbox'], 'text': annots['text']}, dataloader.dataset.unknown, config.threshold_fscore, config.weight_threshold ) target_word_bbox = generated_targets['word_bbox'].copy() f_score = calculate_fscore( predicted_word_bbox[:, :, 0, :], target_word_bbox[:, :, 0, :], text_target=annots['text'], unknown=dataloader.dataset.gt['unknown'] )['f_score'] if visualize: image_i = denormalize_mean_variance(image.data.cpu().numpy().transpose(1, 2, 0)) image_i = cv2.resize( image_i[height_pad:height_pad + before_pad_dim[0], width_pad:width_pad + before_pad_dim[1]], (original_dim[1], original_dim[0]) ) # Generated word_bbox after postprocessing cv2.drawContours( image_i, generated_targets['word_bbox'], -1, (0, 255, 0), 2) # Saving word bbox after postprocessing plt.imsave( base_target_path + '_next_target/word_bbox/' + '.'.join(image_name.split('.')[:-1]) + '.png', image_i) # Generate affinity heatmap after postprocessing affinity_target, affinity_weight_map = generate_target_others( (image_i.shape[0], image_i.shape[1]), generated_targets['affinity'].copy(), np.array(generated_targets['weights'])[:, 1]) # Generate character heatmap after postprocessing character_target, characters_weight_map = generate_target_others( (image_i.shape[0], image_i.shape[1]), generated_targets['characters'].copy(), np.array(generated_targets['weights'])[:, 0]) # Saving the affinity heatmap plt.imsave( base_target_path + '_next_target/affinity/' + '.'.join(image_name.split('.')[:-1]) + '.png', affinity_target, cmap='gray') # Saving the character heatmap plt.imsave( base_target_path + '_next_target/character/' + '.'.join(image_name.split('.')[:-1]) + '.png', character_target, cmap='gray') # Saving the affinity weight map plt.imsave( base_target_path + '_next_target/affinity_weight/' + '.'.join(image_name.split('.')[:-1]) + '.png', affinity_weight_map, cmap='gray') # Saving the character weight map plt.imsave( base_target_path + '_next_target/character_weight/' + '.'.join(image_name.split('.')[:-1]) + '.png', characters_weight_map, cmap='gray') # Saving the target for next iteration in json format generated_targets['word_bbox'] = generated_targets['word_bbox'].tolist() generated_targets['characters'] = [word_i.tolist() for word_i in generated_targets['characters']] generated_targets['affinity'] = [word_i.tolist() for word_i in generated_targets['affinity']] with open(base_target_path + '/' + image_name + '.json', 'w') as f: json.dump(generated_targets, f) return f_score def synthesize_with_score(dataloader, model, base_target_path): """ Given a path to a set of images(icdar 2013 dataset), and path to a pre-trained model, generate the character heatmap and affinity heatmap and a json of all the annotations :param dataloader: dataloader for icdar 2013 dataset :param model: pre-trained model :param base_target_path: path where to store the predictions :return: """ with torch.no_grad(): model.eval() iterator = tqdm(dataloader) mean_f_score = [] for no, (image, image_name, original_dim, item) in enumerate(iterator): annots = [] for i in item: annot = dataloader.dataset.gt['annots'][dataloader.dataset.imnames[i]] annots.append(annot) if config.use_cuda: image = image.cuda() output = model(image) if type(output) == list: output = torch.cat(output, dim=0) output = output.data.cpu().numpy() output[output < 0] = 0 output[output > 1] = 1 original_dim = original_dim.cpu().numpy() f_score = [] for i in range(output.shape[0]): f_score.append( generate_next_targets( original_dim[i], output[i], image[i], base_target_path, image_name[i], annots[i], dataloader, no ) ) mean_f_score.append(np.mean(f_score)) iterator.set_description('F-score: ' + str(np.mean(mean_f_score))) def main( folder_path, base_path_character=None, base_path_affinity=None, base_path_bbox=None, base_path_char=None, base_path_aff=None, base_path_json=None, model_path=None, model=None, ): """ Entry function for synthesising character and affinity heatmap on images given in a folder using a pre-trained model :param folder_path: Path of folder where the images are :param base_path_character: Path where to store the character heatmap :param base_path_affinity: Path where to store the affinity heatmap :param base_path_char: Path where to store the image with character contours :param base_path_aff: Path where to store the image with affinity contours :param base_path_bbox: Path where to store the generated word_bbox overlapped on the image :param base_path_json: Path where to store the generated bbox in json format :param model_path: Path where the pre-trained model is stored :param model: If model is provided directly use it instead of loading it :return: """ if base_path_character is None: base_path_character = '/'.join(folder_path.split('/')[:-1])+'/character_heatmap' if base_path_affinity is None: base_path_affinity = '/'.join(folder_path.split('/')[:-1]) + '/affinity_heatmap' if base_path_bbox is None: base_path_bbox = '/'.join(folder_path.split('/')[:-1]) + '/word_bbox' if base_path_aff is None: base_path_aff = '/'.join(folder_path.split('/')[:-1])+'/affinity_bbox' if base_path_char is None: base_path_char = '/'.join(folder_path.split('/')[:-1]) + '/character_bbox' if base_path_json is None: base_path_json = '/'.join(folder_path.split('/')[:-1])+'/json_annotations' os.makedirs(base_path_affinity, exist_ok=True) os.makedirs(base_path_character, exist_ok=True) os.makedirs(base_path_aff, exist_ok=True) os.makedirs(base_path_char, exist_ok=True) os.makedirs(base_path_bbox, exist_ok=True) os.makedirs(base_path_json, exist_ok=True) # Dataloader to pre-process images given in the folder infer_dataloader = DataLoaderEval(folder_path) infer_dataloader = DataLoader( infer_dataloader, batch_size=config.batch_size['test'], shuffle=True, num_workers=config.num_workers['test'], worker_init_fn=_init_fn) if model is None: # If model has not been provided, loading it from the path provided if config.model_architecture == 'UNET_ResNet': from src.UNET_ResNet import UNetWithResnet50Encoder model = UNetWithResnet50Encoder() else: from src.craft_model import CRAFT model = CRAFT() model = DataParallelModel(model) if config.use_cuda: model = model.cuda() saved_model = torch.load(model_path) else: saved_model = torch.load(model_path, map_location='cpu') if 'state_dict' in saved_model.keys(): model.load_state_dict(saved_model['state_dict']) else: model.load_state_dict(saved_model) synthesize( infer_dataloader, model, base_path_affinity, base_path_character, base_path_bbox, base_path_char, base_path_aff, base_path_json) def generator_(base_target_path, model_path=None, model=None): from train_weak_supervision.dataloader import DataLoaderEvalOther """ Generator function to generate weighted heat-maps for weak-supervision training :param base_target_path: Path where to store the generated annotations :param model_path: If model is not provided then load from model_path :param model: Pytorch Model can be directly provided ofr inference :return: None """ os.makedirs(base_target_path, exist_ok=True) # Storing Predicted os.makedirs(base_target_path + '_predicted/affinity', exist_ok=True) os.makedirs(base_target_path + '_predicted/character', exist_ok=True) os.makedirs(base_target_path + '_predicted/word_bbox', exist_ok=True) # Storing Targets for next iteration os.makedirs(base_target_path + '_next_target/affinity', exist_ok=True) os.makedirs(base_target_path + '_next_target/character', exist_ok=True) os.makedirs(base_target_path + '_next_target/affinity_weight', exist_ok=True) os.makedirs(base_target_path + '_next_target/character_weight', exist_ok=True) os.makedirs(base_target_path + '_next_target/word_bbox', exist_ok=True) # Dataloader to pre-process images given in the dataset and provide annotations to generate weight infer_dataloader = DataLoaderEvalOther('train') infer_dataloader = DataLoader( infer_dataloader, batch_size=config.batch_size['test'], shuffle=False, num_workers=config.num_workers['test'], worker_init_fn=_init_fn) if model is None: # If model has not been provided, loading it from the path provided if config.model_architecture == 'UNET_ResNet': from src.UNET_ResNet import UNetWithResnet50Encoder model = UNetWithResnet50Encoder() else: from src.craft_model import CRAFT model = CRAFT() model = DataParallelModel(model) if config.use_cuda: model = model.cuda() saved_model = torch.load(model_path) model.load_state_dict(saved_model['state_dict']) synthesize_with_score(infer_dataloader, model, base_target_path)
{ "alphanum_fraction": 0.7137092316, "author": null, "avg_line_length": 33.8130841121, "converted": null, "ext": "py", "file": null, "hexsha": "773563ccb7f3e24ad3cd0e770a63503f5bc473fa", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1d5d990ebdca44582cd5271f13c46a27b79e0249", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ds-brx/CRAFT-Remade", "max_forks_repo_path": "train_synth/synthesize.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "1d5d990ebdca44582cd5271f13c46a27b79e0249", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ds-brx/CRAFT-Remade", "max_issues_repo_path": "train_synth/synthesize.py", "max_line_length": 118, "max_stars_count": null, "max_stars_repo_head_hexsha": "1d5d990ebdca44582cd5271f13c46a27b79e0249", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ds-brx/CRAFT-Remade", "max_stars_repo_path": "train_synth/synthesize.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4749, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 18090 }
Address(Decatur Court) is a residential Culdesacs culdesac in South Davis. Intersecting Streets Concord Avenue
{ "alphanum_fraction": 0.7966101695, "author": null, "avg_line_length": 16.8571428571, "converted": null, "ext": "f", "file": null, "hexsha": "5e11fb49272aaa99eafe3a2be10715ac60515c0d", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "voflo/Search", "max_forks_repo_path": "lab/davisWiki/Decatur_Court.f", "max_issues_count": null, "max_issues_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "voflo/Search", "max_issues_repo_path": "lab/davisWiki/Decatur_Court.f", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "voflo/Search", "max_stars_repo_path": "lab/davisWiki/Decatur_Court.f", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 28, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 118 }
# Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import functools import numpy as np from absl.testing import parameterized from tensorflow.python import ipu from tensorflow.python.client import session as sl from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import gradients_impl from tensorflow.python.ops import math_ops from tensorflow.python.ops import variables from tensorflow.python.ops import variable_scope from tensorflow.python.platform import googletest TEST_CASES = ({ 'testcase_name': 'a_columns', 'a_shape': [8, 16], 'b_shape': [16, 5], 'transpose_a': False, 'transpose_b': False, 'serialization_factor': 2, 'serialization_dimension': 'a_columns', }, { 'testcase_name': 'a_columns_tb', 'a_shape': [32, 8], 'b_shape': [1, 8], 'transpose_a': False, 'transpose_b': True, 'serialization_factor': 2, 'serialization_dimension': 'a_columns', }, { 'testcase_name': 'a_columns_ta', 'a_shape': [4, 8], 'b_shape': [4, 4], 'transpose_a': True, 'transpose_b': False, 'serialization_factor': 2, 'serialization_dimension': 'a_columns', }, { 'testcase_name': 'a_columns_ta_tb', 'a_shape': [64, 32], 'b_shape': [128, 64], 'transpose_a': True, 'transpose_b': True, 'serialization_factor': 8, 'serialization_dimension': 'a_columns', }, { 'testcase_name': 'a_rows_b_columns', 'a_shape': [4, 21], 'b_shape': [21, 8], 'transpose_a': False, 'transpose_b': False, 'serialization_factor': 3, 'serialization_dimension': 'a_rows_b_columns', }, { 'testcase_name': 'a_rows_b_columns_tb', 'a_shape': [4, 72], 'b_shape': [1, 72], 'transpose_a': False, 'transpose_b': True, 'serialization_factor': 2, 'serialization_dimension': 'a_rows_b_columns', }, { 'testcase_name': 'a_rows_b_columns_ta', 'a_shape': [4, 8], 'b_shape': [4, 4], 'transpose_a': True, 'transpose_b': False, 'serialization_factor': 2, 'serialization_dimension': 'a_rows_b_columns', }, { 'testcase_name': 'a_rows_b_columns_ta_tb', 'a_shape': [4, 5], 'b_shape': [5, 4], 'transpose_a': True, 'transpose_b': True, 'serialization_factor': 4, 'serialization_dimension': 'a_rows_b_columns', }, { 'testcase_name': 'b_rows', 'a_shape': [4, 4], 'b_shape': [4, 8], 'transpose_a': False, 'transpose_b': False, 'serialization_factor': 2, 'serialization_dimension': 'b_rows', }, { 'testcase_name': 'b_rows_tb', 'a_shape': [4, 4], 'b_shape': [44, 4], 'transpose_a': False, 'transpose_b': True, 'serialization_factor': 2, 'serialization_dimension': 'b_rows', }, { 'testcase_name': 'b_rows_ta', 'a_shape': [4, 8], 'b_shape': [4, 4], 'transpose_a': True, 'transpose_b': False, 'serialization_factor': 2, 'serialization_dimension': 'b_rows', }, { 'testcase_name': 'b_rows_ta_tb', 'a_shape': [4, 5], 'b_shape': [8, 4], 'transpose_a': True, 'transpose_b': True, 'serialization_factor': 4, 'serialization_dimension': 'b_rows', }, { 'testcase_name': 'a_columns_serial_factor_1', 'a_shape': [4, 5], 'b_shape': [5, 4], 'transpose_a': True, 'transpose_b': True, 'serialization_factor': 1, 'serialization_dimension': 'a_columns', }) def _getTestCases(): from copy import deepcopy test_cases = list(TEST_CASES) # Add test cases with a batch dim for a. for case in deepcopy(TEST_CASES): case['testcase_name'] += "_batch_a" case['a_shape'] = [2] + case['a_shape'] test_cases.append(case) # Add test cases with a batch dim for b. for case in deepcopy(TEST_CASES): case['testcase_name'] += "_batch_b" case['b_shape'] = [3] + case['b_shape'] test_cases.append(case) # Add test cases with a batch dim for a and b. for case in deepcopy(TEST_CASES): case['testcase_name'] += "_batch_a_batch_b" case['a_shape'] = [3] + case['a_shape'] case['b_shape'] = [3] + case['b_shape'] test_cases.append(case) return test_cases # Note that in this test we expect small numerical differences as serializing # means that some operations are done in a different order. class SerializedMatmulTest(test_util.TensorFlowTestCase, parameterized.TestCase): def setUp(self): super().setUp() np.random.seed(0xDEADBEEF) def _testOnCpu(self, model_fn, placeholders, inputs, sess, scope_name=None): scope_name = scope_name if scope_name else "cpu_vs" with variable_scope.variable_scope(scope_name, use_resource=True): output = model_fn(*placeholders) sess.run(variables.global_variables_initializer()) return sess.run(output, inputs) def _testOnIpu(self, model_fn, placeholders, inputs, sess, scope_name=None): with ipu.scopes.ipu_scope('/device:IPU:0'): scope_name = scope_name if scope_name else "ipu_vs" with variable_scope.variable_scope(scope_name, use_resource=True): output = ipu.ipu_compiler.compile(model_fn, placeholders) ipu.utils.move_variable_initialization_to_cpu() sess.run(variables.global_variables_initializer()) return sess.run(output, inputs) @parameterized.named_parameters(*_getTestCases()) @test_util.deprecated_graph_mode_only def testSerializedMatmul(self, a_shape, b_shape, transpose_a, transpose_b, serialization_factor, serialization_dimension): a = array_ops.placeholder(np.float32, a_shape) b = array_ops.placeholder(np.float32, b_shape) def cpu_matmul(a, b): return math_ops.matmul(a, b, transpose_a=transpose_a, transpose_b=transpose_b) def ipu_matmul(a, b): return ipu.math_ops.serialized_matmul(a, b, serialization_factor, serialization_dimension, transpose_a=transpose_a, transpose_b=transpose_b) a_val = np.random.normal(2.0, 2.0, a_shape) b_val = np.random.normal(2.0, 2.0, b_shape) with sl.Session() as sess: cpu_output = self._testOnCpu(cpu_matmul, [a, b], { a: a_val, b: b_val }, sess) ipu_output = self._testOnIpu(ipu_matmul, [a, b], { a: a_val, b: b_val }, sess) self.assertAllClose(cpu_output, ipu_output[0], atol=1.e-05, rtol=1.e-05) @parameterized.named_parameters(*_getTestCases()) @test_util.deprecated_graph_mode_only def testSerializedMatmulGrad(self, a_shape, b_shape, transpose_a, transpose_b, serialization_factor, serialization_dimension): a_val = array_ops.constant(np.random.normal(2.0, 2.0, a_shape), dtype=np.float32) b_val = array_ops.constant(np.random.normal(2.0, 2.0, b_shape), dtype=np.float32) def matmul(a, b): return math_ops.matmul(a, b, transpose_a=transpose_a, transpose_b=transpose_b) def serialized_matmul(a, b): return ipu.math_ops.serialized_matmul(a, b, serialization_factor, serialization_dimension, transpose_a=transpose_a, transpose_b=transpose_b) def model_fn(matmul_fn): a = variable_scope.get_variable("a", initializer=a_val) b = variable_scope.get_variable("b", initializer=b_val) c = matmul_fn(a, b) # Not a real loss function, but good enough for testing backprop. loss = math_ops.reduce_sum(c) outputs = gradients_impl.gradients(loss, [a, b]) outputs.append(loss) return outputs ipu_fn = functools.partial(model_fn, matmul) ipu_serial_fn = functools.partial(model_fn, serialized_matmul) with sl.Session() as sess: a, b, l = self._testOnIpu(ipu_fn, [], {}, sess, "normal") serial_a, serial_b, serial_l = self._testOnIpu(ipu_serial_fn, [], {}, sess, "serial") self.assertAllClose(a, serial_a, atol=1.e-05, rtol=1.e-05) self.assertAllClose(b, serial_b, atol=1.e-05, rtol=1.e-05) self.assertAllClose([l], [serial_l], atol=1.e-05, rtol=1.e-05) if __name__ == "__main__": googletest.main()
{ "alphanum_fraction": 0.6184533333, "author": null, "avg_line_length": 34.9813432836, "converted": null, "ext": "py", "file": null, "hexsha": "cf258429ebf930cd2b527e7584e2045e7a9afae7", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2b5a225c49d25273532d11c424d37ce394d7579a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "DebeshJha/tensorflow-1", "max_forks_repo_path": "tensorflow/python/ipu/tests/math_ops_test.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "2b5a225c49d25273532d11c424d37ce394d7579a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "DebeshJha/tensorflow-1", "max_issues_repo_path": "tensorflow/python/ipu/tests/math_ops_test.py", "max_line_length": 80, "max_stars_count": 2, "max_stars_repo_head_hexsha": "2b5a225c49d25273532d11c424d37ce394d7579a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "DebeshJha/tensorflow-1", "max_stars_repo_path": "tensorflow/python/ipu/tests/math_ops_test.py", "max_stars_repo_stars_event_max_datetime": "2022-01-13T03:43:49.000Z", "max_stars_repo_stars_event_min_datetime": "2021-03-08T23:32:06.000Z", "num_tokens": 2330, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 9375 }
import numpy as np import tensorflow as tf from sklearn.neighbors import NearestNeighbors import matplotlib.pyplot as plt from keras.preprocessing.image import load_img, img_to_array from keras.applications.vgg16 import preprocess_input def cosim(x,y): # a=np.sum(x*y.T) # b=np.sqrt(np.sum(x*x.T))*np.sqrt(np.sum(y*y.T)) d1 = np.dot(x, y) / (np.linalg.norm(x) * np.linalg.norm(y)) return d1 # 显示图片 A黑夜 B白天 def show(time,index): im = plt.imread('./raw_data/FRAMES'+time+'/'+'Image'+str(index+1).zfill(5)+'.jpg') print('./raw_data/FRAMES'+time+'/'+'Image'+str(index+1).zfill(5)+'.jpg') plt.imshow(im) plt.show() # fit KNN # 找到与查询图片最接近的前三张图片 def get_top3_match(query_code,database_codes): # n_neigh = 3 # top3 # nbrs = NearestNeighbors(n_neighbors=n_neigh).fit(database_codes) # distances, indices = nbrs.kneighbors(np.array(query_code)) distances =[] for dc in database_codes: dist = cosim(query_code,dc) distances.append(dist[0]) print("distances:",distances) print("sorted_distances:",sorted(distances,reverse=True)) print("sorted_distances_index:", np.array(distances).argsort()[::-1]) # indices 下标+1 即图片编号,即第n帧图片 # return distances,indices return sorted(distances,reverse=True)[:3],np.array(distances).argsort()[::-1][:3] def one_feature_match(encoder_path,day_feature_path,night_path,query_index,data_range): encoder = tf.keras.models.load_model(encoder_path,compile=False) #读取查询图片,并处理成输入encoder的形式 query_img = load_img(night_path + 'Image' + str(query_index+1).zfill(5) + '.jpg', target_size=(224, 224)) query_img = img_to_array(query_img) # query_img = preprocess_input(query_img) query_img = np.expand_dims(query_img, axis=0) # 提取查询的图片A(黑夜)的特征,并且拉直 query_code = encoder.predict(query_img) query_code = query_code.reshape(-1,3136) # 加载用于查询的数据库(白天的特征向量) database_codes = np.load(day_feature_path) database_codes = database_codes.reshape(-1,3136) # 找到与查询图片最接近的前三张图片 distances,indices = get_top3_match(query_code,database_codes) print('【距离,下标】',distances,indices+data_range[0]) # 显示查询的图片 show('A',query_index) # 显示匹配到的前三个图片 for x in range(3): show('B',indices[x]+data_range[0]) def get_sim_matrix(seqA_feature_path,seqB_feature_path,seqA_data_range,seqB_data_range,sim_path): seqA_codes = np.load(seqA_feature_path) seqA_codes = seqA_codes.reshape(-1, 3136) seqB_codes = np.load(seqB_feature_path) seqB_codes = seqB_codes.reshape(-1, 3136) # savepath = xxxx f1 = open(sim_path, 'wb') for seqA_index in range(seqA_data_range[1]-seqA_data_range[0]): distances =[] for seqB_index in range(seqB_data_range[1]-seqB_data_range[0]): dist = cosim(seqA_codes[seqA_index], seqB_codes[seqB_index]) distances.append(dist) # 保存seqA一个图片对应seqB所有图片的余弦值 np.save(f1,np.array(distances)) f1.close()
{ "alphanum_fraction": 0.696735106, "author": null, "avg_line_length": 31.9462365591, "converted": null, "ext": "py", "file": null, "hexsha": "c74a4000398786babced83f7b897381a04d75ab2", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "cb97b3571ac4fa8538729b56ff280673a3d72809", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "xzyslay/CNN_AE", "max_forks_repo_path": "encoder_feature_match.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "cb97b3571ac4fa8538729b56ff280673a3d72809", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "xzyslay/CNN_AE", "max_issues_repo_path": "encoder_feature_match.py", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "cb97b3571ac4fa8538729b56ff280673a3d72809", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "xzyslay/CNN_AE", "max_stars_repo_path": "encoder_feature_match.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 913, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 2971 }
#! /usr/bin/python3 TCP_IP = "localhost" TCP_PORT = 6100 from pyspark import SparkContext from pyspark.sql.session import SparkSession from pyspark.streaming import StreamingContext from sparknlp.annotator import * from sparknlp.base import * import json from pyspark.sql.functions import * from pyspark.sql.types import * from pipeline import PreProcess import classifier import cluster classifier = classifier.Classifier() clustering = cluster.Clustering() import numpy as np from sklearn.feature_extraction.text import HashingVectorizer, CountVectorizer # Create HashingVectorizer instance hv = HashingVectorizer(lowercase=False, alternate_sign = False) cv = CountVectorizer(lowercase=False) # Setting np seed to get reproducible models np.random.seed(5) def vectorize(df): # joined_df = df.withColumn('joined', array(col('finished'))) joined_df = df.withColumn('joined', concat_ws(' ', col('finished'))) docs = joined_df.select('joined').collect() corpus_batch = [doc['joined'] for doc in docs] hvect = hv.transform(corpus_batch) return hvect def process(rdd): # Array of elements of the dataset sent = rdd.collect() if len(sent) > 0: df = spark.createDataFrame(data=json.loads(sent[0]).values(), schema=['sentiment', 'tweet']) pipe = PreProcess(df) df = pipe() # vect = hv.fit_transform(df.select('finished').rdd.collect()) hv = vectorize(df) y = np.array(df.select('sentiment').collect()) y = np.reshape(y, (y.shape[0],)) classifier.fit(hv, y) # Uncomment only 1 of these lines NOT BOTH. plot=True and False used as a flag for plotting clusters of each batch clustering.fit(hv, y, plot=False) # clustering.fit(hv, y, plot=True) if __name__ == "__main__": sc = SparkContext(appName="tweetStream") sc.setLogLevel("ERROR") # remove useless logs clogging the STDOUT ssc = StreamingContext(sc, batchDuration= 3) spark = SparkSession.builder.getOrCreate() classifier.initClassifiers() # Creates a DStream lines = ssc.socketTextStream(TCP_IP, TCP_PORT) # Transformation applied to each DStream iteration words = lines.flatMap(lambda line : line.split("\n")) words.foreachRDD(process) # Start the computation ssc.start() #wait till over ssc.awaitTermination() ssc.stop(stopGraceFully=True) classifier.endClassifiers() clustering.endClustering()
{ "alphanum_fraction": 0.7448364888, "author": null, "avg_line_length": 26.4090909091, "converted": null, "ext": "py", "file": null, "hexsha": "4b04652466f3e0e82e7121b9febbaec585a460f2", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2021-12-09T14:21:58.000Z", "max_forks_repo_forks_event_min_datetime": "2021-12-09T09:04:42.000Z", "max_forks_repo_head_hexsha": "2bea874d383981d9dc249017d36ef329bbdcf5bc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Big-Data-Gang/Machine-Learning-with-Spark-Streaming", "max_forks_repo_path": "src/app.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "2bea874d383981d9dc249017d36ef329bbdcf5bc", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Big-Data-Gang/Machine-Learning-with-Spark-Streaming", "max_issues_repo_path": "src/app.py", "max_line_length": 117, "max_stars_count": 3, "max_stars_repo_head_hexsha": "2bea874d383981d9dc249017d36ef329bbdcf5bc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Big-Data-Gang/Machine-Learning-with-Spark-Streaming", "max_stars_repo_path": "src/app.py", "max_stars_repo_stars_event_max_datetime": "2022-01-29T13:14:34.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-09T09:02:20.000Z", "num_tokens": 580, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 2324 }
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np import sys import os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASE_DIR) ROOT_DIR = os.path.dirname(BASE_DIR) sys.path.append(os.path.join(ROOT_DIR, 'utils')) from box_util import get_3d_box class ScannetDatasetConfig(object): def __init__(self): self.dataset = 'scannet' self.num_class = 18 self.num_heading_bin = 24 # angle: -pi/2~pi/2, so divide 0~2*pi into 24 bin self.num_size_cluster = 18 self.type2class = {'cabinet':0, 'bed':1, 'chair':2, 'sofa':3, 'table':4, 'door':5, 'window':6,'bookshelf':7,'picture':8, 'counter':9, 'desk':10, 'curtain':11, 'refrigerator':12, 'showercurtrain':13, 'toilet':14, 'sink':15, 'bathtub':16, 'garbagebin':17} #self.type2class = {'wall':0, 'floor':1, 'cabinet':2, 'bed':3, 'chair':4, 'sofa':5, 'table':6, 'door':7,'window':8,'bookshelf':9,'picture':10, 'counter':11, 'blinds':12, 'desk':13, 'shelves':14, 'curtain':15, 'dresser':16, 'pillow':17, 'mirror':18, 'floormat':19, 'clothes':20, 'ceiling':21, 'books':22, 'refrigerator':23, 'television':24, 'paper':25, 'towel':26, 'showercurtrain':27, 'box':28, 'whiteboard':29, 'person':30, 'nightstand':31, 'toilet':32, 'sink':33, 'lamp':34, 'bathtub':35, 'bag':36} self.type2class_room = {'other':0, 'wall':1, 'floor':2} self.class2type = {self.type2class[t]:t for t in self.type2class} self.class2type_room = {self.type2class_room[t]:t for t in self.type2class_room} self.nyu40ids = np.array([3,4,5,6,7,8,9,10,11,12,14,16,24,28,33,34,36,39]) #self.nyu40ids = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]) self.nyu40ids_room = np.array([1,2]) self.nyu40id2class = {nyu40id: i for i,nyu40id in enumerate(list(self.nyu40ids))} self.nyu40id2class_sem = {nyu40id: i for i,nyu40id in enumerate(list(self.nyu40ids))} self.mean_size_arr = np.load(os.path.join(ROOT_DIR,'scannet/meta_data/scannet_means.npz'))['arr_0'] #self.mean_size_arr = np.load(os.path.join(ROOT_DIR,'scannet/meta_data/scannet_means_v2.npz.npy'))[:self.num_class,:] self.type_mean_size = {} for i in range(self.num_size_cluster): self.type_mean_size[self.class2type[i]] = self.mean_size_arr[i,:] def class2angle(self, pred_cls, residual, to_label_format=True): return 0 ''' def angle2class(self, angle): # assert(False) num_class = self.num_heading_bin angle = angle%(2*np.pi) assert(angle>=0 and angle<=2*np.pi) angle_per_class = 2*np.pi/float(num_class) shifted_angle = (angle+angle_per_class/2)%(2*np.pi) class_id = int(shifted_angle/angle_per_class) residual_angle = shifted_angle - (class_id*angle_per_class+angle_per_class/2) return class_id, residual_angle def class2angle(self, pred_cls, residual, to_label_format=True): num_class = self.num_heading_bin angle_per_class = 2*np.pi/float(num_class) angle_center = pred_cls * angle_per_class angle = angle_center + residual if to_label_format and angle>np.pi: angle = angle - 2*np.pi return angle ''' def angle2class2(self, angle): ''' modify according to sunrgbd scannet_angle: angle: -pi/2 ~ pi/2 1: angle += pi/2 -> 0~pi 2: class*(2pi/N) + number = angle + pi/2 ''' class_id, residual_angle = self.angle2class(angle + np.pi / 2) return class_id, residual_angle def class2angle2(self, pred_cls, residual, to_label_format=True): angle = self.class2angle(pred_cls, residual) angle = angle - np.pi / 2 return angle def size2class(self, size, type_name): ''' Convert 3D box size (l,w,h) to size class and size residual ''' size_class = self.type2class[type_name] size_residual = size - self.type_mean_size[type_name] return size_class, size_residual def class2size(self, pred_cls, residual): ''' Inverse function to size2class ''' return self.mean_size_arr[pred_cls, :] + residual def param2obb(self, center, heading_class, heading_residual, size_class, size_residual): heading_angle = self.class2angle(heading_class, heading_residual) box_size = self.class2size(int(size_class), size_residual) obb = np.zeros((7,)) obb[0:3] = center obb[3:6] = box_size obb[6] = heading_angle*-1 return obb def param2obb2(self, center, heading_class, heading_residual, size_class, size_residual): heading_angle = self.class2angle(heading_class, heading_residual) box_size = self.class2size(int(size_class), size_residual) obb = np.zeros((7,)) obb[0:3] = center obb[3:6] = box_size obb[6] = heading_angle return obb def rotate_aligned_boxes(input_boxes, rot_mat): centers, lengths = input_boxes[:,0:3], input_boxes[:,3:6] new_centers = np.dot(centers, np.transpose(rot_mat)) dx, dy = lengths[:,0]/2.0, lengths[:,1]/2.0 new_x = np.zeros((dx.shape[0], 4)) new_y = np.zeros((dx.shape[0], 4)) for i, crnr in enumerate([(-1,-1), (1, -1), (1, 1), (-1, 1)]): crnrs = np.zeros((dx.shape[0], 3)) crnrs[:,0] = crnr[0]*dx crnrs[:,1] = crnr[1]*dy crnrs = np.dot(crnrs, np.transpose(rot_mat)) new_x[:,i] = crnrs[:,0] new_y[:,i] = crnrs[:,1] new_dx = 2.0*np.max(new_x, 1) new_dy = 2.0*np.max(new_y, 1) new_lengths = np.stack((new_dx, new_dy, lengths[:,2]), axis=1) return np.concatenate([new_centers, new_lengths], axis=1)
{ "alphanum_fraction": 0.6235294118, "author": null, "avg_line_length": 47.5196850394, "converted": null, "ext": "py", "file": null, "hexsha": "beaac2037df8f8d7f71a1531452c5c328d008b0d", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 24, "max_forks_repo_forks_event_max_datetime": "2022-03-30T13:34:45.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-11T01:17:24.000Z", "max_forks_repo_head_hexsha": "872dabb37d8c2ca3581cf4e242014e6464debe57", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cheng052/H3DNet", "max_forks_repo_path": "scannet/model_util_scannet.py", "max_issues_count": 25, "max_issues_repo_head_hexsha": "872dabb37d8c2ca3581cf4e242014e6464debe57", "max_issues_repo_issues_event_max_datetime": "2022-03-10T05:44:05.000Z", "max_issues_repo_issues_event_min_datetime": "2020-06-15T13:35:13.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "cheng052/H3DNet", "max_issues_repo_path": "scannet/model_util_scannet.py", "max_line_length": 508, "max_stars_count": 212, "max_stars_repo_head_hexsha": "872dabb37d8c2ca3581cf4e242014e6464debe57", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cheng052/H3DNet", "max_stars_repo_path": "scannet/model_util_scannet.py", "max_stars_repo_stars_event_max_datetime": "2022-03-17T17:29:21.000Z", "max_stars_repo_stars_event_min_datetime": "2020-06-11T01:03:36.000Z", "num_tokens": 1842, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 6035 }
#include "InetAddress.h" #include <strings.h> // bzero #include <netinet/in.h> #include <arpa/inet.h> #include <boost/static_assert.hpp> using namespace Reactor; static const in_addr_t kInaddrAny = INADDR_ANY; InetAddress::InetAddress(uint16_t port) { bzero(&addr_, sizeof addr_); addr_.sin_family = AF_INET; addr_.sin_addr.s_addr = htonl(kInaddrAny); addr_.sin_port = htons(port); } std::string InetAddress::toHostPort() const { char buf[32]; char host[INET_ADDRSTRLEN] = "INVALID"; ::inet_ntop(AF_INET, &addr_.sin_addr, host, sizeof host); uint16_t port = ntohs(addr_.sin_port); snprintf(buf, sizeof buf, "%s:%u", host, port); return buf; }
{ "alphanum_fraction": 0.7153502235, "author": null, "avg_line_length": 21.6451612903, "converted": null, "ext": "cc", "file": null, "hexsha": "817a85da42fe7658e3967cf7a8b207765f2be0cf", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7da8b7fb72baca4a04cfde9ce27eec3bb207e056", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "HenryKing96/MiniDistributedStorage", "max_forks_repo_path": "storageServer/saveFile_2/src/InetAddress.cc", "max_issues_count": null, "max_issues_repo_head_hexsha": "7da8b7fb72baca4a04cfde9ce27eec3bb207e056", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "HenryKing96/MiniDistributedStorage", "max_issues_repo_path": "storageServer/saveFile_2/src/InetAddress.cc", "max_line_length": 59, "max_stars_count": null, "max_stars_repo_head_hexsha": "7da8b7fb72baca4a04cfde9ce27eec3bb207e056", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "HenryKing96/MiniDistributedStorage", "max_stars_repo_path": "storageServer/saveFile_2/src/InetAddress.cc", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 190, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 671 }
import mediapipe as mp import cv2 import numpy as np import uuid import os mp_drawing = mp.solutions.drawing_utils mp_hands = mp.solutions.hands cap = cv2.VideoCapture(0) with mp_hands.Hands(min_detection_confidence=0.8, min_tracking_confidence=0.5) as hands: while cap.isOpened(): ret, frame = cap.read() image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) image = cv2.flip(image, 1) image.flags.writeable = False results = hands.process(image) image.flags.writeable = True image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) print(results) if results.multi_hand_landmarks: for num, hand in enumerate(results.multi_hand_landmarks): mp_drawing.draw_landmarks(image, hand, mp_hands.HAND_CONNECTIONS, mp_drawing.DrawingSpec(color=(121, 22, 76), thickness=2, circle_radius=4), mp_drawing.DrawingSpec(color=(250, 44, 250), thickness=2, circle_radius=2), ) cv2.imshow('Hand Tracking', image) if cv2.waitKey(10) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
{ "alphanum_fraction": 0.6145662848, "author": null, "avg_line_length": 35.9411764706, "converted": null, "ext": "py", "file": null, "hexsha": "46090c35b7fa3437d287302ae00b895c137cd28d", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-03-12T04:59:55.000Z", "max_forks_repo_forks_event_min_datetime": "2022-02-15T15:39:48.000Z", "max_forks_repo_head_hexsha": "b7fd20f3eb830bf5387dba1579c041975348de14", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "teecha/Autonomous_Tello_Drone", "max_forks_repo_path": "gesture_controlled_tello/handpose.py", "max_issues_count": 1, "max_issues_repo_head_hexsha": "b7fd20f3eb830bf5387dba1579c041975348de14", "max_issues_repo_issues_event_max_datetime": "2022-02-21T23:30:55.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-16T07:47:30.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "teecha/Autonomous_Tello_Drone", "max_issues_repo_path": "gesture_controlled_tello/handpose.py", "max_line_length": 117, "max_stars_count": 10, "max_stars_repo_head_hexsha": "b7fd20f3eb830bf5387dba1579c041975348de14", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "teecha/Autonomous_Tello_Drone", "max_stars_repo_path": "gesture_controlled_tello/handpose.py", "max_stars_repo_stars_event_max_datetime": "2022-03-06T02:16:36.000Z", "max_stars_repo_stars_event_min_datetime": "2022-02-12T17:35:11.000Z", "num_tokens": 290, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1222 }
import numpy as np import subprocess, sys, os.path from itertools import * import pandas as pd import logging from .pstreader import PstReader def _default_empty_creator(count): return np.empty([count or 0, 0],dtype=str) def _default_empty_creator_val(row_count,col_count): return np.empty([row_count,col_count],dtype=str) class PstData(PstReader): '''A :class:`.PstReader` for holding values in-memory, along with related row and col information. It is usually created by calling the :meth:`.PstReader.read` method on another :class:`.PstReader`, for example, :class:`.PstNpz`. It can also be constructed. See :class:`.PstReader` for details and examples. **Constructor:** :Parameters: * **row** (an array of anything) -- The :attr:`.row` information * **col** (an array of anything) -- The :attr:`.col` information * **val** (a 2-D array of floats) -- The values * **row_property** (optional, an array of anything) -- Additional information associated with each row. * **col_property** (optional, an array of strings) -- Additional information associated with each col. * **name** (optional, string) -- Information to be display about the origin of this data * **copyinputs_function** (optional, function) -- *Used internally by optional clustering code* :Example: >>> from pysnptools.pstreader import PstData >>> pstdata = PstData(row=[['fam0','iid0'],['fam0','iid1']], col=['snp334','snp349','snp921'], val=[[0.,2.,0.],[0.,1.,2.]]) >>> print(pstdata.val[0,1], pstdata.row_count, pstdata.col_count) 2.0 2 3 **Equality:** Two PstData objects are equal if their five arrays (:attr:`.row`, :attr:`.col`, :attr:`.val`, :attr:`PstReader.row_property`, and :attr:`.col_property`) are 'array_equal'. (Their 'name' does not need to be the same). :Example: >>> from pysnptools.pstreader import PstData >>> pstdata1 = PstData(row=[['fam0','iid0'],['fam0','iid1']], col=['snp334','snp349','snp921'], val=[[0.,2.,0.],[0.,1.,2.]]) >>> pstdata2 = PstData(row=[['fam0','iid0'],['fam0','iid1']], col=['snp334','snp349','snp921'], val=[[0.,2.,0.],[0.,1.,2.]]) >>> print(pstdata1 == pstdata2) #True, because all the arrays have the same values. True >>> print(pstdata1.val is pstdata2.val) #False, because the two arrays have different memory. False >>> pstdata3 = PstData(row=['a','b'], col=['snp334','snp349','snp921'], val=[[0.,2.,0.],[0.,1.,2.]]) >>> pstdata4 = PstData(row=[['fam0','iid0'],['fam0','iid1']], col=['snp334','snp349','snp921'], val=[[0.,2.,0.],[0.,1.,2.]]) >>> print(pstdata3 == pstdata4) #False, because the rows have different ids. False **Methods beyond** :class:`.PstReader` ''' def __init__(self, row, col, val, row_property=None, col_property=None, name=None, parent_string=None, copyinputs_function=None): super(PstData, self).__init__() self.val = None self._row = PstData._fixup_input(row) self._col = PstData._fixup_input(col) self._row_property = PstData._fixup_input(row_property,count=len(self._row)) self._col_property = PstData._fixup_input(col_property,count=len(self._col)) self.val = PstData._fixup_input_val(val,row_count=len(self._row),col_count=len(self._col)) name = name or parent_string or "" if parent_string is not None: warnings.warn("'parent_string' is deprecated. Use 'name'", DeprecationWarning) self._name = name """The 2D NumPy array of floats that represents the values. >>> from pysnptools.pstreader import PstNpz >>> pstdata = PstNpz('pysnptools/examples/toydata.pst.npz')[:5,:].read() #read data for first 5 rows >>> print(pstdata.val[4,100]) #print one of the values 2.0 """ def __eq__(a,b): try: return (np.array_equal(a.row,b.row) and np.array_equal(a.col,b.col) and np.array_equal(a.row_property,b.row_property) and np.array_equal(a.col_property,b.col_property) and np.array_equal(a.val,b.val)) except: return False @staticmethod def _fixup_input(input,count=None, empty_creator=_default_empty_creator): if input is None: input = empty_creator(count) elif not isinstance(input,np.ndarray): input = np.array(input) assert count is None or len(input) == count, "Expect length of {0} for input {1}".format(count,input) return input @staticmethod def _fixup_input_val(input,row_count,col_count,empty_creator=_default_empty_creator_val): if input is None: assert row_count == 0 or col_count == 0, "If val is None, either row_count or col_count must be 0" input = _default_empty_creator_val(row_count, col_count) elif not isinstance(input,np.ndarray or (input.dtype not in [np.float32,np.float64])): input = np.array(input,dtype=np.float64) assert len(input.shape)==2, "Expect val to be two dimensional." assert input.shape[0] == row_count, "Expect number of rows ({0}) in val to match the number of row names given ({1})".format(input.shape[0], row_count) assert input.shape[1] == col_count, "Expect number of columns ({0}) in val to match the number of column names given ({1})".format(input.shape[1], col_count) return input def __repr__(self): if self._name == "": return "{0}()".format(self.__class__.__name__) else: return "{0}({1})".format(self.__class__.__name__,self._name) def copyinputs(self, copier): pass @property def row(self): return self._row @property def col(self): return self._col @property def row_property(self): return self._row_property @property def col_property(self): return self._col_property # Most _read's support only indexlists or None, but this one supports Slices, too. _read_accepts_slices = True def _read(self, row_index_or_none, col_index_or_none, order, dtype, force_python_only, view_ok): val, shares_memory = self._apply_sparray_or_slice_to_val(self.val, row_index_or_none, col_index_or_none, order, dtype, force_python_only) if shares_memory and not view_ok: val = val.copy(order='K') return val if __name__ == "__main__": logging.basicConfig(level=logging.INFO) import doctest doctest.testmod() # There is also a unit test case in 'pysnptools\test.py' that calls this doc test
{ "alphanum_fraction": 0.6322514319, "author": null, "avg_line_length": 42.0308641975, "converted": null, "ext": "py", "file": null, "hexsha": "4d810f74a9decd87e263ac8c103c29dcc767cca9", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "eaa770fb104f5b8a769be3d82437610e63eb83c1", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "limix/PySnpTools", "max_forks_repo_path": "pysnptools/pstreader/pstdata.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "eaa770fb104f5b8a769be3d82437610e63eb83c1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "limix/PySnpTools", "max_issues_repo_path": "pysnptools/pstreader/pstdata.py", "max_line_length": 179, "max_stars_count": 1, "max_stars_repo_head_hexsha": "eaa770fb104f5b8a769be3d82437610e63eb83c1", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "limix/PySnpTools", "max_stars_repo_path": "pysnptools/pstreader/pstdata.py", "max_stars_repo_stars_event_max_datetime": "2017-06-09T01:28:34.000Z", "max_stars_repo_stars_event_min_datetime": "2017-06-09T01:28:34.000Z", "num_tokens": 1788, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 6809 }
# -*- coding: utf-8 -*- # # # This source file is part of the FabSim software toolkit, which is # distributed under the BSD 3-Clause license. # Please refer to LICENSE for detailed information regarding the # licensing. # # fab.py contains general-purpose FabSim routines. import threading import base.AsyncThreadingPool from deploy.templates import * from deploy.machines import * from fabric.contrib.project import * from base.manage_remote_job import * from base.setup_fabsim import * from fabric.api import settings import time import re import numpy as np import yaml import tempfile import os.path import math from pprint import PrettyPrinter from pathlib import Path from shutil import copyfile pp = PrettyPrinter() mutex = threading.Lock() mutex_template = threading.Lock() def get_plugin_path(name, quiet=False): """ Get the local base path of plugin <name>. """ plugin_path = os.path.join(env.localroot, 'plugins', name) if not quiet: assert os.path.isdir(plugin_path), \ "The requested plugin %s does not exist (%s).\n \ you can install it by typing:\n\t \ fabsim localhost install_plugin:%s" % (name, plugin_path, name) return plugin_path def local_with_stdout(cmd, verbose=False): """ Runs Fabric's local() function, while capturing and returning stdout automatically. """ with settings(warn_only=True): output = local(cmd, capture=True) if verbose: print("stdout: %s" % output.stdout) print("stderr: %s" % output.stderr) return output.stdout def with_template_job(ensemble_mode=False, label=None): """ Determine a generated job name from environment parameters, and then define additional environment parameters based on it. """ # The name is now depending of the label name name = template(env.job_name_template) if label and not ensemble_mode: name = '_'.join((label, name)) job_results, job_results_local = with_job(name, ensemble_mode, label) return job_results, job_results_local def with_job(name, ensemble_mode=False, label=None): """Augment the fabric environment with information regarding a particular job name. Definitions created: job_results: the remote location where job results should be stored job_results_local: the local location where job results should be stored """ env.name = name if not ensemble_mode: job_results = env.pather.join(env.results_path, name) job_results_local = os.path.join(env.local_results, name) else: job_results = "%s/RUNS/%s" % (env.pather.join( env.results_path, name), label) job_results_local = "%s/RUNS/%s" % (os.path.join( env.local_results, name), label) env.job_results_contents = env.pather.join(job_results, '*') env.job_results_contents_local = os.path.join(job_results_local, '*') # Template name is now depending of the label of the job when needed if label is not None: env.job_name_template_sh = "%s_%s.sh" % (name, label) else: env.job_name_template_sh = "%s.sh" % (name) return job_results, job_results_local def with_template_config(): """ Determine the name of a used or generated config from environment parameters, and then define additional environment parameters based on it. """ with_config(template(env.config_name_template)) def find_config_file_path(name, ExceptWhenNotFound=True): # Prevent of executing localhost runs on the FabSim3 root directory if env.host == 'localhost' and env.work_path == env.localroot: print("Error : the localhost run dir is same as your FabSim3 folder") print("To avoid any conflict of config folder, please consider") print("changing your home_path_template variable") print("you can easily modify it by updating localhost entry in") print("your FabSim3/machines_user.yml file") print("Here is the suggested changes ") print("\nlocalhost:") print(" ...") print(" home_path_template: \"%s/localhost_exe\"\n" % (env.localroot)) exit() path_used = None for p in env.local_config_file_path: config_file_path = os.path.join(p, name) if os.path.exists(config_file_path): path_used = config_file_path if path_used is None: if ExceptWhenNotFound: raise Exception( "Error: config file directory not found in: ", env.local_config_file_path) else: return False return path_used def with_config(name): """ Internal: augment the fabric environment with information regarding a particular configuration name. Definitions created: job_config_path: the remote location where the config files for the job should be stored job_config_path_local: the local location where the config files for the job may be found """ env.config = name env.job_config_path = env.pather.join(env.config_path, name) path_used = find_config_file_path(name) env.job_config_path_local = os.path.join(path_used) env.job_config_contents = env.pather.join(env.job_config_path, '*') env.job_config_contents_local = os.path.join( env.job_config_path_local, '*') # name of the job sh submission script. env.job_name_template_sh = template("%s.sh" % env.job_name_template) def load_plugin_machine_vars(name): path_used = find_config_file_path(name) env.job_config_path_local = os.path.join(path_used) plugin_local_path = env.job_config_path_local.split("/config_files/")[0] plugin_name = plugin_local_path.split("/plugins/")[1] add_plugin_environment_variable(plugin_name, plugin_local_path, env.machine_name) def with_profile(name): """ Internal: augment the fabric environment with information regarding a particular profile name Definitions created: job_profile_path: the remote location where the profile should be stored job_profile_path_local: the local location where the profile files may be found """ env.profile = name env.job_profile_path = env.pather.join( env.profiles_path, name) env.job_profile_path_local = os.path.join( env.local_profiles, name) env.job_profile_contents = env.pather.join( env.job_profile_path, '*') env.job_profile_contents_local = os.path.join( env.job_profile_path_local, '*') @task def fetch_configs(config=''): """ Fetch config files from the remote, via rsync. Specify a config directory, such as 'cylinder' to copy just one config. Config files are stored as, e.g. cylinder/config.dat and cylinder/config.xml Local path to use is specified in machines_user.json, and should normally point to a mount on entropy, i.e. /store4/blood/username/config_files This method is not intended for normal use, but is useful when the local machine cannot have an entropy mount, so that files can be copied to a local machine from entropy, and then transferred to the compute machine, via 'fab entropy fetch_configs; fab legion put_configs' """ with_config(config) if env.manual_gsissh: local( template( "globus-url-copy -cd -r -sync \ gsiftp://$remote/$job_config_path/ \ file://$job_config_path_local/" ) ) else: local( template( "rsync -pthrvz $username@$remote:$job_config_path/ \ $job_config_path_local" ) ) @task def put_configs(config=''): """ Transfer config files to the remote. For use in launching jobs, via rsync. Specify a config directory, such as 'cylinder' to copy just one configuration. Config files are stored as, e.g. cylinder/config.dat and cylinder/config.xml Local path to find config directories is specified in machines_user.json, and should normally point to a mount on entropy, i.e. /store4/blood/username/config_files If you can't mount entropy, 'fetch_configs' can be useful, via 'fab entropy fetch_configs; fab legion put_configs' RECENT ADDITION: Added get_setup_fabsim_dirs_string() so that the Fabric Directories are now created automatically whenever a config file is uploaded. """ with_config(config) run( template( "%s; mkdir -p $job_config_path" % (get_setup_fabsim_dirs_string()) ) ) if env.manual_gsissh: local( template( "globus-url-copy -p 10 -cd -r -sync \ file://$job_config_path_local/ \ gsiftp://$remote/$job_config_path/" ) ) else: rsync_project( local_dir=env.job_config_path_local + '/', remote_dir=env.job_config_path ) @task def put_results(name=''): """ Transfer result files to a remote. Local path to find result directories is specified in machines_user.json. This method is not intended for normal use, but is useful when the local machine cannot have an entropy mount, so that results from a local machine can be sent to entropy, via 'fab legion fetch_results; fab entropy put_results' """ with_job(name) run(template("mkdir -p $job_results")) if env.manual_gsissh: local( template( "globus-url-copy -p 10 -cd -r -sync \ file://$job_results_local/ \ gsiftp://$remote/$job_results/")) else: rsync_project( local_dir=env.job_results_local + '/', remote_dir=env.job_results ) @task def fetch_results(name='', regex='', debug=False): """ Fetch results of remote jobs to local result store. Specify a job name to transfer just one job. Local path to store results is specified in machines_user.json, and should normally point to a mount on entropy, i.e. /store4/blood/username/results. If you can't mount entropy, 'put results' can be useful, via 'fab legion fetch_results; fab entropy put_results' """ if debug: pp.pprint(env) env.job_results, env.job_results_local = with_job(name) if env.manual_gsissh: local( template( "globus-url-copy -cd -r -sync \ gsiftp://$remote/$job_results/%s \ file://$job_results_local/" % regex ) ) else: local( template( # "rsync -pthrvz --port=$port \ "rsync -pthrvz -e 'ssh -p $port' \ $username@$remote:$job_results/%s \ $job_results_local" % regex ) ) @task def clear_results(name=''): """Completely wipe all result files from the remote.""" with_job(name) run(template('rm -rf $job_results_contents')) @task def fetch_profiles(name=''): """ Fetch results of remote jobs to local result store. Specify a job name to transfer just one job. Local path to store results is specified in machines_user.json, and should normally point to a mount on entropy, i.e. /store4/blood/username/results. If you can't mount entropy, 'put results' can be useful, via 'fab legion fetch_results; fab entropy put_results' """ with_profile(name) if env.manual_gsissh: local( template( "globus-url-copy -cd -r -sync \ gsiftp://$remote/$job_profile_path/ \ file://$job_profile_path_local/" ) ) else: local( template( "rsync -pthrvz $username@$remote:$job_profile_path/ \ $job_profile_path_local" ) ) @task def put_profiles(name=''): """ Transfer result files to a remote. Local path to find result directories is specified in machines_user.json. This method is not intended for normal use, but is useful when the local machine cannot have an entropy mount, so that results from a local machine can be sent to entropy, via 'fab legion fetch_results; fab entropy put_results' """ with_profile(name) run(template("mkdir -p $job_profile_path")) if env.manual_gsissh: local( template("globus-url-copy -p 10 -cd -r -sync \ file://$job_profile_path_local/ \ gsiftp://$remote/$job_profile_path/") ) else: rsync_project( local_dir=env.job_profile_path_local + '/', remote_dir=env.job_profile_path ) """ Returns the commands required to set up the fabric directories. This is not in the env, because modifying this is likely to break FabSim in most cases. This is stored in an individual function, so that the string can be appended in existing commands, reducing the performance overhead. """ return( 'mkdir -p $config_path; mkdir -p $results_path; mkdir -p $scripts_path' ) def update_environment(*dicts): for adict in dicts: env.update(adict) def calc_nodes(): # If we're not reserving whole nodes, then if we request less than one # node's worth of cores, need to keep N<=n env.coresusedpernode = env.corespernode if int(env.coresusedpernode) > int(env.cores): env.coresusedpernode = env.cores env.nodes = int(math.ceil(float(env.cores) / float(env.coresusedpernode))) def calc_total_mem(): # for qcg scheduler, #QCG memory requires total memory for all nodes if not hasattr(env, 'memory'): env.memory = '2GB' mem_size = int(re.findall("\d+", str(env.memory))[0]) try: mem_unit_str = re.findall("[a-zA-Z]+", str(env.memory))[0] except Exception: mem_unit_str = '' if mem_unit_str.upper() == 'GB' or mem_unit_str.upper() == 'G': mem_unit = 1000 else: mem_unit = 1 if(hasattr(env, 'PJ') and env.PJ.lower() == 'true'): env.total_mem = mem_size * int(env.PJ_size) * mem_unit else: env.total_mem = mem_size * int(env.nodes) * mem_unit @task def get_fabsim_git_hash(verbose=True): with settings(warn_only=True): return local_with_stdout("git rev-parse HEAD", verbose=True) @task def get_fabsim_command_history(): """ Parses the bash history, and returns all the instances that contain the phrase "fab ". """ return local_with_stdout( "cat %s/.bash_history | grep fab" % (env.localhome), verbose=True ) def removekey(d, key): r = dict(d) try: del r[key] except KeyError as ex: pass return r def job(sweep_length=1, *option_dictionaries): """ Internal low level job launcher. Parameters for the job are determined from the prepared fabric environment Execute a generic job on the remote machine. Use hemelb, regress, or test instead. Returns the name of the remote results directory. """ # env.fabsim_git_hash = get_fabsim_git_hash() env.submit_time = time.strftime('%Y%m%d%H%M%S%f') env.ensemble_mode = False # setting a default before reading in args. # Crapy, In the case where job() is call outside run_ensemble # and usually only with option_dictionnaries as arg if isinstance(sweep_length, dict) and not isinstance( option_dictionaries, dict): option_dictionaries = [sweep_length] sweep_length = 1 # Add label, mem, core to env. update_environment(*option_dictionaries) job_results_dir = {} # Save label as local variable since env.label is overwritten by the other # threads ! # all these variable are saved in a dict specific to the thread_id job_results_dir[threading.get_ident()] = {} job_results_dir[threading.get_ident()].update({'label': ''}) if 'label' in option_dictionaries[0]: job_results_dir[threading.get_ident( )]['label'] = option_dictionaries[0]['label'] # Use this to request more cores than we use, to measure performance # without sharing impact if env.get('cores_reserved') == 'WholeNode' and env.get('corespernode'): env.cores_reserved = ( (1 + (int(env.cores) - 1) / int(env.corespernode)) * env.corespernode ) # If cores_reserved is not specified, temporarily set it based on the # same as the number of cores # Needs to be temporary if there's another job with a different number # of cores which should also be defaulted to. with settings(cores_reserved=env.get('cores_reserved') or env.cores): # Make sure that prefix and module load definitions are properly # updated. for i in range(1, int(env.replicas) + 1): mutex_template.acquire() try: job_results, job_results_local = with_template_job( env.ensemble_mode, job_results_dir[threading.get_ident()]['label']) job_results_dir[threading.get_ident()].update( {'job_results': job_results}) if int(env.replicas) > 1: if env.ensemble_mode is False: job_results_dir[threading.get_ident()]['job_results'] \ = job_results_dir[threading.get_ident()][ 'job_results'] + '_replica_' + str(i) job_results_local = job_results_local + \ '_replica_' + str(i) else: job_results_dir[threading.get_ident()]['job_results'] \ = job_results_dir[threading.get_ident()][ 'job_results'] + '_' + str(i) job_results_local = job_results_local + '_' + str(i) finally: mutex_template.release() complete_environment() calc_nodes() if env.node_type: env.node_type_restriction = template( env.node_type_restriction_template) env['job_name'] = env.name[0:env.max_job_name_chars] with settings(cores=1): calc_nodes() env.run_command_one_proc = template(env.run_command) calc_nodes() calc_total_mem() env.run_command = template(env.run_command) # Mutex are used here to temporary set global variable # that will be used to create env.dest_name. # env.dest_name is save as a local variable # The script name is now depending of the job label --> Create N # script for N jobs mutex_template.acquire() try: # env variables have to be set here to set the template env.label = job_results_dir[threading.get_ident()]['label'] env.job_results = job_results_dir[threading.get_ident( )]['job_results'] env.job_results_local = job_results_local if (hasattr(env, 'NoEnvScript') and env.NoEnvScript): job_results_dir[threading.get_ident()].update( {'job_script': script_templates( env.batch_header, thread_data=job_results_dir[threading.get_ident()]) }) # Suppose to be in PJM mode --> no multithreading --> env # = ok env.job_script = job_results_dir[ threading.get_ident()]['job_script'] else: job_results_dir[threading.get_ident()].update({ 'job_script': script_templates( env.batch_header, env.script, thread_data=job_results_dir[threading.get_ident()] ) }) job_results_dir[threading.get_ident()].update({ 'dest_name': env.pather.join(env.scripts_path, env.pather.basename( job_results_dir[threading.get_ident()]['job_script']))} ) destname = job_results_dir[threading.get_ident()]['dest_name'] finally: mutex_template.release() put(job_results_dir[threading.get_ident()]['job_script'], job_results_dir[threading.get_ident()]['dest_name']) # in case of PJ=True, we don't need to copy app config files and # folders to PJ and PJ-PY folders if env.label in ['PJ_PYheader', 'PJ_header']: run( template( "mkdir -p %s && cp %s %s" % ( job_results_dir[threading.get_ident()][ 'job_results'], job_results_dir[threading.get_ident()][ 'dest_name'], job_results_dir[threading.get_ident()][ 'job_results'] ) ) ) else: run( template( "mkdir -p %s && rsync -av --progress \ $job_config_path/* %s/ --exclude SWEEP && \ cp %s %s" % ( job_results_dir[threading.get_ident()][ 'job_results'], job_results_dir[threading.get_ident()][ 'job_results'], job_results_dir[threading.get_ident()][ 'dest_name'], job_results_dir[threading.get_ident()][ 'job_results'] ) ) ) # In ensemble mode, also add run-specific file to the results dir. if env.ensemble_mode: run( template( "rsync -pthrvz \ $job_config_path/SWEEP/%s/ %s/" % ( job_results_dir[threading.get_ident()]['label'], job_results_dir[threading.get_ident()][ 'job_results'] ) ) ) try: del env["passwords"] except KeyError: pass try: del env["password"] except KeyError: pass # For curation purposes, we store env.yml, which # contains the FabSim3 env, for each job. with tempfile.NamedTemporaryFile(mode='r+') as tempf: tempf.write( yaml.dump(dict(env)) ) tempf.flush() # Flush the file before we copy it. put(tempf.name, env.pather.join(job_results_dir[ threading.get_ident()]['job_results'], 'env.yml')) run(template("chmod u+x %s" % job_results_dir[threading.get_ident()]['dest_name'])) # check for PilotJob option is true, DO NOT submit the job directly # only submit PJ script if (hasattr(env, 'submit_job') and isinstance(env.submit_job, bool) and env.submit_job is False): if ((hasattr(env, 'NoEnvScript') and not env.NoEnvScript) or not hasattr(env, 'NoEnvScript')): # Protect concurrent writting mutex.acquire() try: env.idsID = len(env.submitted_jobs_list) + 1 env.idsPath = env.pather.join( job_results_dir[threading.get_ident()] ['job_results'], env.pather.basename( job_results_dir[threading.get_ident()] ['job_script'])) if not hasattr(env, 'task_model'): env.task_model = 'default' env.submitted_jobs_list.append( script_template_content('qcg-PJ-task-template')) finally: mutex.release() if (i > int(env.replicas)): return if (hasattr(env, 'TestOnly') and env.TestOnly.lower() == 'true'): # return continue # We don't want to go next during replicas and pjm until the final # job if not (hasattr(env, 'submit_job') and isinstance(env.submit_job, bool) and env.submit_job is False): # Allow option to submit all preparations, # but not actually submit the job # job_info = '' if hasattr(env, 'dispatch_jobs_on_localhost') and \ isinstance(env.dispatch_jobs_on_localhost, bool) and \ env.dispatch_jobs_on_localhost: env.job_script = job_script local(template("$job_dispatch " + env.job_script)) print("job dispatch is done locally\n") elif not env.get("noexec", False): if env.remote == 'localhost': with cd(job_results_dir[threading.get_ident()] ['job_results']): with prefix(env.run_prefix): run( template("$job_dispatch %s" % job_results_dir[ threading.get_ident()] ['dest_name']) ) else: with cd(job_results_dir[threading.get_ident()] ['job_results']): run(template("$job_dispatch %s" % job_results_dir[ threading.get_ident()]['dest_name'])) print("JOB OUTPUT IS STORED REMOTELY IN: %s:%s " % (env.remote, job_results_dir[threading.get_ident()]['job_results']) ) print("Use `fab %s fetch_results` to copy the results back to %s on\ localhost." % (env.machine_name, job_results_local) ) if env.get("dumpenv", False) == "True": print("DUMPENV mode enabled. Dumping environment:") print(env) return job_results @task def ensemble2campaign(results_dir, campaign_dir, skip=0, **args): """ Converts FabSim3 ensemble results to EasyVVUQ campaign definition. results_dir: FabSim3 results root directory campaign_dir: EasyVVUQ root campaign directory. skip: The number of runs (run_1 to run_skip) not to copy to the campaign """ update_environment(args) # if skip > 0: only copy the run directories run_X for X > skip back # to the EasyVVUQ campaign dir if int(skip) > 0: # all run directories runs = os.listdir('%s/RUNS/' % results_dir) for run in runs: # extract X from run_X run_id = int(run.split('_')[-1]) # if X > skip copy results back if run_id > int(skip): local("rsync -pthrvz %s/RUNS/%s %s/runs" % (results_dir, run, campaign_dir)) # copy all runs from FabSim results directory to campaign directory else: local("rsync -pthrvz %s/RUNS/ %s/runs" % (results_dir, campaign_dir)) @task def campaign2ensemble(config, campaign_dir, skip=0, **args): """ Converts an EasyVVUQ campaign run set TO a FabSim3 ensemble definition. config: FabSim3 configuration name (will create in top level if non-existent, and overwrite existing content). campaign_dir: EasyVVUQ root campaign directory. skip: The number of runs (run_1 to run_skip) not to copy to the FabSim3 sweep directory. The first skip number of samples will then not be computed. """ update_environment(args) config_path = find_config_file_path(config, ExceptWhenNotFound=False) if config_path is False: local("mkdir -p %s/%s" % (env.local_config_file_path[-1], config)) config_path = "%s/%s" % (env.local_config_file_path[-1], config) sweep_dir = config_path + "/SWEEP" local("mkdir -p %s" % (sweep_dir)) # the previous ensemble in the sweep directory prev_runs = os.listdir(sweep_dir) # empty sweep directory for prev_run in prev_runs: local('rm -r %s/%s' % (sweep_dir, prev_run)) # if skip > 0: only copy the run directories run_X for X > skip to the # FabSim3 sweep directory. This avoids recomputing already computed samples # when the EasyVVUQ grid is refined adaptively. if int(skip) > 0: # all runs in the campaign dir runs = os.listdir('%s/runs/' % campaign_dir) for run in runs: # extract X from run_X run_id = int(run.split('_')[-1]) # if X > skip, copy run directory to the sweep dir if run_id > int(skip): print("Copying %s" % run) local("rsync -pthrz %s/runs/%s %s" % (campaign_dir, run, sweep_dir)) # if skip = 0: copy all runs from EasyVVUQ run directort to the sweep dir else: local("rsync -pthrz %s/runs/ %s" % (campaign_dir, sweep_dir)) def run_ensemble(config, sweep_dir, **args): """ Map and execute ensemble jobs. The job results will be stored with a name pattern as defined in the environment, e.g. water-abcd1234-legion-256 config : base config directory to use to define input files, e.g. config=water sweep_dir : directory containing inputs that will vary per ensemble simulation instance. These can either be stored as a range of files or as a range of subdirectories. Keyword arguments: input_name_in_config : name of included file once embedded in the simulation config. cores : number of compute cores to request wall_time : wall-time job limit memory : memory per node """ update_environment(args) if "script" not in env: print("ERROR: run_ensemble function has been called,\ but the parameter 'script' was not specified.") sys.exit() with_config(config) # check for PilotJob option if(hasattr(env, 'PJ') and env.PJ.lower() == 'true'): # env.batch_header = "no_batch" env.submitted_jobs_list = [] env.submit_job = False env.batch_header = "bash_header" # number of runs performed in this sweep sweep_length = 0 sweepdir_items = os.listdir(sweep_dir) # reorder an exec_first item for priority execution. if(hasattr(env, 'exec_first')): sweepdir_items.insert( 0, sweepdir_items.pop( sweepdir_items.index( env.exec_first))) # Prevention since some laptop doesn't support more than 4 threads # if int(env.nb_thread) > 4: # env.nb_thread = 4 atp = base.AsyncThreadingPool.ATP(ncpu=int(env.nb_thread)) for item in sweepdir_items: if os.path.isdir(os.path.join(sweep_dir, item)): sweep_length += 1 # It's only necessary to do that for the first iteration # The first iteration will create folders to the remote and launch # sequentialy the first job if sweep_length == 1: execute(put_configs, config) job(sweep_length, dict(ensemble_mode=True, label=item)) # All the other iteration will launch parallel jobs else: print(" Start multi threading job") atp.run_job(jobID=sweep_length, handler=job, args=(sweep_length, dict(ensemble_mode=True, label=item))) # Wait for all jobs to be done atp.awaitJobOver() atp.shutdownThreads() if sweep_length == 0: print( "ERROR: no files where found in the sweep_dir of this\ run_ensemble command." ) print("Sweep dir location: %s" % (sweep_dir)) elif (hasattr(env, 'PJ') and env.PJ.lower() == 'true'): # to avoid apply replicas functionality on PilotJob folders env.replicas = 1 backup_header = env.batch_header env.submitted_jobs_list = "\n".join( [str(i) for i in env.submitted_jobs_list]) env.batch_header = env.PJ_PYheader job(dict(label='PJ_PYheader', NoEnvScript=True), args) env.PJ_PATH = env.pather.join( env.job_results, env.pather.basename(env.job_script)) env.PJ_FileName = env.pather.basename(env.job_script) env.batch_header = env.PJ_header env.submit_job = True # load QCG-PJ-PY file PJ_CMD = [] if (hasattr(env, 'venv') and env.venv.lower() == 'true'): # QCG-PJ should load from virtualenv PJ_CMD.append('# unload any previous loaded python module') PJ_CMD.append('module unload python\n') PJ_CMD.append('# load QCG-PilotJob from VirtualEnv') PJ_CMD.append('eval "$(%s/bin/conda shell.bash hook)"\n' % (env.virtual_env_path)) PJ_CMD.append('# load QCG-PJ-Python file') PJ_CMD.append('%s/bin/python3 %s' % (env.virtual_env_path, env.PJ_PATH)) else: PJ_CMD.append('# Install QCG-PJ in user\'s home space') PJ_CMD.append('pip install --user --upgrade qcg-pilotjob\n') PJ_CMD.append('# load QCG-PJ-Python file') PJ_CMD.append('python3 %s' % (env.PJ_PATH)) env.run_QCG_PilotJob = "\n".join(PJ_CMD) job(dict(label='PJ_header', NoEnvScript=True), args) env.batch_header = backup_header env.NoEnvScript = False def input_to_range(arg, default): ttype = type(default) # regexp for a array generator like [1.2:3:0.2] gen_regexp = r"\[([\d\.]+):([\d\.]+):([\d\.]+)\]" if not arg: return [default] match = re.match(gen_regexp, str(arg)) if match: vals = list(map(ttype, match.groups())) if ttype == int: return range(*vals) else: return np.arange(*vals) return [ttype(arg)] @task def get_running_location(job=None): """ Returns the node name where a given job is running. """ if job: with_job(job) env.running_node = run(template("cat $job_results/env_details.asc")) def manual(cmd): # From the fabric wiki, bypass fabric internal ssh control commands = env.command_prefixes[:] if env.get('cwd'): commands.append("cd %s" % env.cwd) commands.append(cmd) manual_command = " && ".join(commands) pre_cmd = "ssh -Y -p %(port)s %(user)s@%(host)s " % env local(pre_cmd + "'" + manual_command + "'", capture=False) def manual_gsissh(cmd): # From the fabric wiki, bypass fabric internal ssh control commands = env.command_prefixes[:] if env.get('cwd'): commands.append("cd %s" % env.cwd) commands.append(cmd) manual_command = " && ".join(commands) pre_cmd = "gsissh -t -p %(port)s %(host)s " % env local(pre_cmd + "'" + manual_command + "'", capture=False) def run(cmd): if env.manual_gsissh: manual_gsissh(cmd) elif env.manual_ssh: manual(cmd) else: return fabric.api.run(cmd) def put(src, dest): if env.manual_gsissh: if os.path.isdir(src): if src[-1] != '/': env.manual_src = src + '/' env.manual_dest = dest + '/' else: env.manual_src = src env.manual_dest = dest local( template("globus-url-copy -sync -r -cd -p 10\ file://$manual_src gsiftp://$host/$manual_dest") ) elif env.manual_ssh: env.manual_src = src env.manual_dest = dest local(template("scp $manual_src $user@$host:$manual_dest")) else: fabric.api.put(src, dest) @task def blackbox(script='ibi.sh', args=''): """ black-box script execution. """ for p in env.local_blackbox_path: script_file_path = os.path.join(p, script) if os.path.exists(os.path.dirname(script_file_path)): local("%s %s" % (script_file_path, args)) return print( "FabSim Error: could not find blackbox() script file.\ FabSim looked for it in the following directories: ", env.local_blackbox_path) @task def probe(label="undefined"): """ Scans a remote site for the presence of certain software. """ return run("module avail 2>&1 | grep %s" % label) @task def archive(prefix, archive_location): """ Cleans results directories of core dumps and moves results to archive locations. """ if len(prefix) < 1: print("error: no prefix defined.") sys.exit() print("LOCAL %s %s %s*" % (env.local_results, prefix, archive_location)) local("rm -f %s/*/core" % (env.local_results)) local("mv -i %s/%s* %s/" % (env.local_results, prefix, archive_location)) parent_path = os.sep.join(env.results_path.split(os.sep)[:-1]) print("REMOTE MOVE: mv %s/%s %s/Backup" % (env.results_path, prefix, parent_path)) run("mkdir -p %s/Backup" % (parent_path)) run("mv -i %s/%s* %s/Backup/" % (env.results_path, prefix, parent_path)) @task def print_config(args=''): """ Prints local environment """ for x in env: print(x, ':', env[x]) @task def install_packages(venv='False'): """ Install list of packages defined in deploy/applications.yml note : if you got an error on your local machine during the build wheel for scipy, like this one ERROR: lapack_opt_info: Try to install BLAS and LAPACK first. by sudo apt-get install libblas-dev liblapack-dev libatlas-base-dev gfortran """ applications_yml_file = os.path.join(env.localroot, 'deploy', 'applications.yml') user_applications_yml_file = os.path.join(env.localroot, 'deploy', 'applications_user.yml') if not os.path.exists(user_applications_yml_file): copyfile(applications_yml_file, user_applications_yml_file) config = yaml.load(open(user_applications_yml_file), Loader=yaml.SafeLoader ) tmp_app_dir = "%s/tmp_app" % (env.localroot) local('mkdir -p %s' % (tmp_app_dir)) for dep in config['packages']: local('pip3 download --no-binary=:all: -d %s %s' % (tmp_app_dir, dep)) add_dep_list_compressed = sorted(Path(tmp_app_dir).iterdir(), key=lambda f: f.stat().st_mtime) for it in range(len(add_dep_list_compressed)): add_dep_list_compressed[it] = os.path.basename( add_dep_list_compressed[it]) # Create directory in the remote machine to store dependency packages run( template( "mkdir -p %s" % env.app_repository ) ) # Send the dependencies (and the dependencies of dependencies) to the # remote machine for whl in os.listdir(tmp_app_dir): local( template( "rsync -pthrvz -e 'ssh -p $port' %s/%s \ $username@$remote:$app_repository" % (tmp_app_dir, whl) ) # "rsync -pthrvz %s/%s eagle:$app_repository"%(tmp_app_dir, whl) ) # Set required env variable env.config = "Install_VECMA_App" # env.nodes = 1 env.nodes = env.cores script = os.path.join(tmp_app_dir, "script") # Write the Install command in a file with open(script, "w") as sc: install_dir = "--user" if venv == 'True': sc.write("if [ ! -d %s ]; then \n\t python -m virtualenv \ %s || echo 'WARNING : virtualenv is not installed \ or has a problem' \nfi\n\nsource %s/bin/activate\n" % (env.virtual_env_path, env.virtual_env_path, env.virtual_env_path)) install_dir = "" # First install the additional_dependencies for dep in reversed(add_dep_list_compressed): print(dep) if dep.endswith('.zip'): sc.write("\nunzip %s/%s -d %s && cd %s/%s \ && python3 setup.py install %s" % (env.app_repository, dep, env.app_repository, env.app_repository, dep.replace(".zip", ""), install_dir)) elif dep.endswith('.tar.gz'): sc.write("\ntar xf %s/%s -C %s && cd %s/%s \ && python3 setup.py install %s\n" % (env.app_repository, dep, env.app_repository, env.app_repository, dep.replace(".tar.gz", ""), install_dir)) # Add the tmp_app_dir directory in the local templates path because the # script is saved in it env.local_templates_path.insert(0, tmp_app_dir) install_dict = dict(script="script") # env.script = "script" update_environment(install_dict) # Determine a generated job name from environment parameters # and then define additional environment parameters based on it. env.job_results, env.job_results_local = with_template_job() # Create job script based on "sbatch header" and script created above in # deploy/.jobscript/ env.job_script = script_templates(env.batch_header_install_app, env.script) # Create script's destination path to remote machine based on env.dest_name = env.pather.join( env.scripts_path, env.pather.basename(env.job_script) ) # Send Install script to remote machine put(env.job_script, env.dest_name) # run(template("mkdir -p $job_results")) with cd(env.pather.dirname(env.job_results)): run(template("%s %s") % (env.job_dispatch, env.dest_name)) local('rm -rf %s' % tmp_app_dir) @task def install_app(name="", external_connexion='no', venv='False'): """ Install a specific Application through FasbSim3 """ applications_yml_file = os.path.join(env.localroot, 'deploy', 'applications.yml') user_applications_yml_file = os.path.join(env.localroot, 'deploy', 'applications_user.yml') if not os.path.exists(user_applications_yml_file): copyfile(applications_yml_file, user_applications_yml_file) config = yaml.load(open(user_applications_yml_file), Loader=yaml.SafeLoader ) info = config[name] # Offline cluster installation - --user install # Temporary folder tmp_app_dir = "%s/tmp_app" % (env.localroot) local('mkdir -p %s' % (tmp_app_dir)) # First download all the Miniconda3 installation script local('wget %s -O %s/miniconda.sh' % (config['Miniconda-installer']['repository'], tmp_app_dir)) # Next download all the additional dependencies for dep in info['additional_dependencies']: local('pip3 download --no-binary=:all: -d %s %s' % (tmp_app_dir, dep)) add_dep_list_compressed = sorted(Path(tmp_app_dir).iterdir(), key=lambda f: f.stat().st_mtime) for it in range(len(add_dep_list_compressed)): add_dep_list_compressed[it] = os.path.basename( add_dep_list_compressed[it]) # Download all the dependencies of the application # This first method should download all the dependencies needed # but for the local plateform ! # --> Possible Issue during the installation in the remote # (it's not a cross-plateform install yet) local('pip3 download --no-binary=:all: -d %s git+%s@v%s' % (tmp_app_dir, info['repository'], info['version'])) # Create directory in the remote machine to store dependency packages run( template( "mkdir -p %s" % env.app_repository ) ) # Send the dependencies (and the dependencies of dependencies) to the # remote machine for whl in os.listdir(tmp_app_dir): local( template( "rsync -pthrvz -e 'ssh -p $port' %s/%s \ $username@$remote:$app_repository" % (tmp_app_dir, whl) ) # "rsync -pthrvz %s/%s eagle:$app_repository"%(tmp_app_dir, whl) ) # Set required env variable env.config = "Install_VECMA_App" # env.nodes = 1 env.nodes = env.cores script = os.path.join(tmp_app_dir, "script") # Write the Install command in a file with open(script, "w") as sc: install_dir = "" if venv == 'True': # clean virtualenv and App_repo directory on remote machine side # To make sure everything is going to be installed from scratch ''' sc.write("find %s/ -maxdepth 1 -mindepth 1 -type d \ -exec rm -rf \"{}\" \\;\n" % (env.app_repository)) sc.write("rm -rf %s\n" % (env.virtual_env_path)) ''' # It seems some version of python/virtualenv doesn't support # the option --no-download. So there is sometime a problem : # from pip import main # ImportError: cannot import name 'main' # # TODO Check python version and raised a Warning if not the # right version ? # TODO # sc.write("if [ ! -d %s ]; then \n\t bash %s/miniconda.sh -b -p %s \ || echo 'WARNING : virtualenv is not installed \ or has a problem' \nfi" % (env.virtual_env_path, env.app_repository, env.virtual_env_path)) sc.write("\n\neval \"$$(%s/bin/conda shell.bash hook)\"\n\n" % (env.virtual_env_path)) # install_dir = "" ''' with the latest version of numpy, I got this error: 1. Check that you expected to use Python3.8 from ..., and that you have no directories in your PATH or PYTHONPATH that can interfere with the Python and numpy version "1.18.1" you're trying to use. so, since that we are using VirtualEnv, to avoid any conflict, it is better to clear PYTHONPATH ''' # sc.write("\nexport PYTHONPATH=\"\"\n") sc.write("\nmodule unload python\n") # First install the additional_dependencies for dep in reversed(add_dep_list_compressed): print(dep) if dep.endswith('.zip'): sc.write("\nunzip %s/%s -d %s && cd %s/%s \ && %s/bin/python3 setup.py install %s\n" % (env.app_repository, dep, env.app_repository, env.app_repository, dep.replace(".zip", ""), env.virtual_env_path, install_dir)) elif dep.endswith('.tar.gz'): sc.write("\ntar xf %s/%s -C %s && cd %s/%s \ && %s/bin/python3 setup.py install %s\n" % (env.app_repository, dep, env.app_repository, env.app_repository, dep.replace(".tar.gz", ""), env.virtual_env_path, install_dir)) sc.write("%s/bin/pip install --no-index --no-build-isolation \ --find-links=file:%s %s/%s-%s.zip %s \ || %s/bin/pip install --no-index --find-links=file:%s %s/%s-%s.zip" % (env.virtual_env_path, env.app_repository, env.app_repository, info['name'], info['version'], install_dir, env.virtual_env_path, env.app_repository, env.app_repository, info['name'], info['version'])) # Add the tmp_app_dir directory in the local templates path because the # script is saved in it env.local_templates_path.insert(0, tmp_app_dir) install_dict = dict(script="script") # env.script = "script" update_environment(install_dict) # Determine a generated job name from environment parameters # and then define additional environment parameters based on it. env.job_results, env.job_results_local = with_template_job() # Create job script based on "sbatch header" and script created above in # deploy/.jobscript/ env.job_script = script_templates(env.batch_header_install_app, env.script) # Create script's destination path to remote machine based on run(template("mkdir -p $scripts_path")) env.dest_name = env.pather.join( env.scripts_path, env.pather.basename(env.job_script) ) # Send Install script to remote machine put(env.job_script, env.dest_name) # run(template("mkdir -p $job_results")) with cd(env.pather.dirname(env.job_results)): run(template("%s %s") % (env.job_dispatch, env.dest_name)) local('rm -rf %s' % tmp_app_dir)
{ "alphanum_fraction": 0.5817241722, "author": null, "avg_line_length": 37.1655580192, "converted": null, "ext": "py", "file": null, "hexsha": "605285479ebcf09a438d1674621d4120e278208f", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "910fb162af5a9fb14e12a552c5c4ec9160122570", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "samcowger/FabSim3", "max_forks_repo_path": "base/fab.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "910fb162af5a9fb14e12a552c5c4ec9160122570", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "samcowger/FabSim3", "max_issues_repo_path": "base/fab.py", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "910fb162af5a9fb14e12a552c5c4ec9160122570", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "samcowger/FabSim3", "max_stars_repo_path": "base/fab.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 11019, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 50285 }
(* *********************************************************************) (* *) (* The Compcert verified compiler *) (* *) (* Xavier Leroy, INRIA Paris-Rocquencourt *) (* *) (* Copyright Institut National de Recherche en Informatique et en *) (* Automatique. All rights reserved. This file is distributed *) (* under the terms of the INRIA Non-Commercial License Agreement. *) (* *) (* *********************************************************************) (** Abstract specification of RTL generation *) (** In this module, we define inductive predicates that specify the translations from Cminor to RTL performed by the functions in module [RTLgen]. We then show that these functions satisfy these relational specifications. The relational specifications will then be used instead of the actual functions to show semantic equivalence between the source Cminor code and the the generated RTL code (see module [RTLgenproof]). *) Require Import Coqlib. Require Errors. Require Import Maps. Require Import AST. Require Import Integers. Require Import Values. Require Import Events. Require Import Memory. Require Import Globalenvs. Require Import Switch. Require Import Op. Require Import Registers. Require Import CminorSel. Require Import RTL. Require Import RTLgen. (** * Reasoning about monadic computations *) (** The tactics below simplify hypotheses of the form [f ... = OK x s i] where [f] is a monadic computation. For instance, the hypothesis [(do x <- a; b) s = OK y s' i] will generate the additional witnesses [x], [s1], [i1], [i'] and the additional hypotheses [a s = OK x s1 i1] and [b x s1 = OK y s' i'], reflecting the fact that both monadic computations [a] and [b] succeeded. *) Remark bind_inversion: forall (A B: Type) (f: mon A) (g: A -> mon B) (y: B) (s1 s3: state) (i: state_incr s1 s3), bind f g s1 = OK y s3 i -> exists x, exists s2, exists i1, exists i2, f s1 = OK x s2 i1 /\ g x s2 = OK y s3 i2. Proof. intros until i. unfold bind. destruct (f s1); intros. discriminate. exists a; exists s'; exists s. destruct (g a s'); inv H. exists s0; auto. Qed. Remark bind2_inversion: forall (A B C: Type) (f: mon (A*B)) (g: A -> B -> mon C) (z: C) (s1 s3: state) (i: state_incr s1 s3), bind2 f g s1 = OK z s3 i -> exists x, exists y, exists s2, exists i1, exists i2, f s1 = OK (x, y) s2 i1 /\ g x y s2 = OK z s3 i2. Proof. unfold bind2; intros. exploit bind_inversion; eauto. intros [[x y] [s2 [i1 [i2 [P Q]]]]]. simpl in Q. exists x; exists y; exists s2; exists i1; exists i2; auto. Qed. Ltac monadInv1 H := match type of H with | (OK _ _ _ = OK _ _ _) => inversion H; clear H; try subst | (Error _ _ = OK _ _ _) => discriminate | (ret _ _ = OK _ _ _) => inversion H; clear H; try subst | (error _ _ = OK _ _ _) => discriminate | (bind ?F ?G ?S = OK ?X ?S' ?I) => let x := fresh "x" in ( let s := fresh "s" in ( let i1 := fresh "INCR" in ( let i2 := fresh "INCR" in ( let EQ1 := fresh "EQ" in ( let EQ2 := fresh "EQ" in ( destruct (bind_inversion _ _ F G X S S' I H) as [x [s [i1 [i2 [EQ1 EQ2]]]]]; clear H; try (monadInv1 EQ2))))))) | (bind2 ?F ?G ?S = OK ?X ?S' ?I) => let x1 := fresh "x" in ( let x2 := fresh "x" in ( let s := fresh "s" in ( let i1 := fresh "INCR" in ( let i2 := fresh "INCR" in ( let EQ1 := fresh "EQ" in ( let EQ2 := fresh "EQ" in ( destruct (bind2_inversion _ _ _ F G X S S' I H) as [x1 [x2 [s [i1 [i2 [EQ1 EQ2]]]]]]; clear H; try (monadInv1 EQ2)))))))) end. Ltac monadInv H := match type of H with | (ret _ _ = OK _ _ _) => monadInv1 H | (error _ _ = OK _ _ _) => monadInv1 H | (bind ?F ?G ?S = OK ?X ?S' ?I) => monadInv1 H | (bind2 ?F ?G ?S = OK ?X ?S' ?I) => monadInv1 H | (?F _ _ _ _ _ _ _ _ = OK _ _ _) => ((progress simpl in H) || unfold F in H); monadInv1 H | (?F _ _ _ _ _ _ _ = OK _ _ _) => ((progress simpl in H) || unfold F in H); monadInv1 H | (?F _ _ _ _ _ _ = OK _ _ _) => ((progress simpl in H) || unfold F in H); monadInv1 H | (?F _ _ _ _ _ = OK _ _ _) => ((progress simpl in H) || unfold F in H); monadInv1 H | (?F _ _ _ _ = OK _ _ _) => ((progress simpl in H) || unfold F in H); monadInv1 H | (?F _ _ _ = OK _ _ _) => ((progress simpl in H) || unfold F in H); monadInv1 H | (?F _ _ = OK _ _ _) => ((progress simpl in H) || unfold F in H); monadInv1 H | (?F _ = OK _ _ _) => ((progress simpl in H) || unfold F in H); monadInv1 H end. (** * Monotonicity properties of the state *) Hint Resolve state_incr_refl: rtlg. Lemma instr_at_incr: forall s1 s2 n i, state_incr s1 s2 -> s1.(st_code)!n = Some i -> s2.(st_code)!n = Some i. Proof. intros. inv H. destruct (H3 n); congruence. Qed. Hint Resolve instr_at_incr: rtlg. (** The following tactic saturates the hypotheses with [state_incr] properties that follow by transitivity from the known hypotheses. *) Ltac saturateTrans := match goal with | H1: state_incr ?x ?y, H2: state_incr ?y ?z |- _ => match goal with | H: state_incr x z |- _ => fail 1 | _ => let i := fresh "INCR" in (generalize (state_incr_trans x y z H1 H2); intro i; saturateTrans) end | _ => idtac end. (** * Validity and freshness of registers *) (** An RTL pseudo-register is valid in a given state if it was created earlier, that is, it is less than the next fresh register of the state. Otherwise, the pseudo-register is said to be fresh. *) Definition reg_valid (r: reg) (s: state) : Prop := Plt r s.(st_nextreg). Definition reg_fresh (r: reg) (s: state) : Prop := ~(Plt r s.(st_nextreg)). Lemma valid_fresh_absurd: forall r s, reg_valid r s -> reg_fresh r s -> False. Proof. intros r s. unfold reg_valid, reg_fresh; case r; tauto. Qed. Hint Resolve valid_fresh_absurd: rtlg. Lemma valid_fresh_different: forall r1 r2 s, reg_valid r1 s -> reg_fresh r2 s -> r1 <> r2. Proof. unfold not; intros. subst r2. eauto with rtlg. Qed. Hint Resolve valid_fresh_different: rtlg. Lemma reg_valid_incr: forall r s1 s2, state_incr s1 s2 -> reg_valid r s1 -> reg_valid r s2. Proof. intros r s1 s2 INCR. inversion INCR. unfold reg_valid. intros; apply Plt_Ple_trans with (st_nextreg s1); auto. Qed. Hint Resolve reg_valid_incr: rtlg. Lemma reg_fresh_decr: forall r s1 s2, state_incr s1 s2 -> reg_fresh r s2 -> reg_fresh r s1. Proof. intros r s1 s2 INCR. inversion INCR. unfold reg_fresh; unfold not; intros. apply H4. apply Plt_Ple_trans with (st_nextreg s1); auto. Qed. Hint Resolve reg_fresh_decr: rtlg. (** Validity of a list of registers. *) Definition regs_valid (rl: list reg) (s: state) : Prop := forall r, In r rl -> reg_valid r s. Lemma regs_valid_nil: forall s, regs_valid nil s. Proof. intros; red; intros. elim H. Qed. Hint Resolve regs_valid_nil: rtlg. Lemma regs_valid_cons: forall r1 rl s, reg_valid r1 s -> regs_valid rl s -> regs_valid (r1 :: rl) s. Proof. intros; red; intros. elim H1; intro. subst r1; auto. auto. Qed. Lemma regs_valid_incr: forall s1 s2 rl, state_incr s1 s2 -> regs_valid rl s1 -> regs_valid rl s2. Proof. unfold regs_valid; intros; eauto with rtlg. Qed. Hint Resolve regs_valid_incr: rtlg. (** A register is ``in'' a mapping if it is associated with a Cminor local or let-bound variable. *) Definition reg_in_map (m: mapping) (r: reg) : Prop := (exists id, m.(map_vars)!id = Some r) \/ In r m.(map_letvars). (** A compilation environment (mapping) is valid in a given state if the registers associated with Cminor local variables and let-bound variables are valid in the state. *) Definition map_valid (m: mapping) (s: state) : Prop := forall r, reg_in_map m r -> reg_valid r s. Lemma map_valid_incr: forall s1 s2 m, state_incr s1 s2 -> map_valid m s1 -> map_valid m s2. Proof. unfold map_valid; intros; eauto with rtlg. Qed. Hint Resolve map_valid_incr: rtlg. (** * Properties of basic operations over the state *) (** Properties of [add_instr]. *) Lemma add_instr_at: forall s1 s2 incr i n, add_instr i s1 = OK n s2 incr -> s2.(st_code)!n = Some i. Proof. intros. monadInv H. simpl. apply PTree.gss. Qed. Hint Resolve add_instr_at: rtlg. (** Properties of [update_instr]. *) Lemma update_instr_at: forall n i s1 s2 incr u, update_instr n i s1 = OK u s2 incr -> s2.(st_code)!n = Some i. Proof. intros. unfold update_instr in H. destruct (plt n (st_nextnode s1)); try discriminate. destruct (check_empty_node s1 n); try discriminate. inv H. simpl. apply PTree.gss. Qed. Hint Resolve update_instr_at: rtlg. (** Properties of [new_reg]. *) Lemma new_reg_valid: forall s1 s2 r i, new_reg s1 = OK r s2 i -> reg_valid r s2. Proof. intros. monadInv H. unfold reg_valid; simpl. apply Plt_succ. Qed. Hint Resolve new_reg_valid: rtlg. Lemma new_reg_fresh: forall s1 s2 r i, new_reg s1 = OK r s2 i -> reg_fresh r s1. Proof. intros. monadInv H. unfold reg_fresh; simpl. exact (Plt_strict _). Qed. Hint Resolve new_reg_fresh: rtlg. Lemma new_reg_not_in_map: forall s1 s2 m r i, new_reg s1 = OK r s2 i -> map_valid m s1 -> ~(reg_in_map m r). Proof. unfold not; intros; eauto with rtlg. Qed. Hint Resolve new_reg_not_in_map: rtlg. (** * Properties of operations over compilation environments *) Lemma init_mapping_valid: forall s, map_valid init_mapping s. Proof. unfold map_valid, init_mapping. intros s r [[id A] | B]. simpl in A. rewrite PTree.gempty in A; discriminate. simpl in B. tauto. Qed. (** Properties of [find_var]. *) Lemma find_var_in_map: forall s1 s2 map name r i, find_var map name s1 = OK r s2 i -> reg_in_map map r. Proof. intros until r. unfold find_var; caseEq (map.(map_vars)!name). intros. inv H0. left; exists name; auto. intros. inv H0. Qed. Hint Resolve find_var_in_map: rtlg. Lemma find_var_valid: forall s1 s2 map name r i, find_var map name s1 = OK r s2 i -> map_valid map s1 -> reg_valid r s1. Proof. eauto with rtlg. Qed. Hint Resolve find_var_valid: rtlg. (** Properties of [find_letvar]. *) Lemma find_letvar_in_map: forall s1 s2 map idx r i, find_letvar map idx s1 = OK r s2 i -> reg_in_map map r. Proof. intros until r. unfold find_letvar. caseEq (nth_error (map_letvars map) idx); intros; monadInv H0. right; apply nth_error_in with idx; auto. Qed. Hint Resolve find_letvar_in_map: rtlg. Lemma find_letvar_valid: forall s1 s2 map idx r i, find_letvar map idx s1 = OK r s2 i -> map_valid map s1 -> reg_valid r s1. Proof. eauto with rtlg. Qed. Hint Resolve find_letvar_valid: rtlg. (** Properties of [add_var]. *) Lemma add_var_valid: forall s1 s2 map1 map2 name r i, add_var map1 name s1 = OK (r, map2) s2 i -> map_valid map1 s1 -> reg_valid r s2 /\ map_valid map2 s2. Proof. intros. monadInv H. split. eauto with rtlg. inversion EQ. subst. red. intros r' [[id A] | B]. simpl in A. rewrite PTree.gsspec in A. destruct (peq id name). inv A. eauto with rtlg. apply reg_valid_incr with s1. eauto with rtlg. apply H0. left; exists id; auto. simpl in B. apply reg_valid_incr with s1. eauto with rtlg. apply H0. right; auto. Qed. Lemma add_var_find: forall s1 s2 map name r map' i, add_var map name s1 = OK (r,map') s2 i -> map'.(map_vars)!name = Some r. Proof. intros. monadInv H. simpl. apply PTree.gss. Qed. Lemma add_vars_valid: forall namel s1 s2 map1 map2 rl i, add_vars map1 namel s1 = OK (rl, map2) s2 i -> map_valid map1 s1 -> regs_valid rl s2 /\ map_valid map2 s2. Proof. induction namel; simpl; intros; monadInv H. split. red; simpl; intros; tauto. auto. exploit IHnamel; eauto. intros [A B]. exploit add_var_valid; eauto. intros [C D]. split. apply regs_valid_cons; eauto with rtlg. auto. Qed. Lemma add_var_letenv: forall map1 id s1 r map2 s2 i, add_var map1 id s1 = OK (r, map2) s2 i -> map2.(map_letvars) = map1.(map_letvars). Proof. intros; monadInv H. reflexivity. Qed. Lemma add_vars_letenv: forall il map1 s1 rl map2 s2 i, add_vars map1 il s1 = OK (rl, map2) s2 i -> map2.(map_letvars) = map1.(map_letvars). Proof. induction il; simpl; intros; monadInv H. reflexivity. transitivity (map_letvars x0). eapply add_var_letenv; eauto. eauto. Qed. (** Properties of [add_letvar]. *) Lemma add_letvar_valid: forall map s r, map_valid map s -> reg_valid r s -> map_valid (add_letvar map r) s. Proof. intros; red; intros. destruct H1 as [[id A]|B]. simpl in A. apply H. left; exists id; auto. simpl in B. elim B; intro. subst r0; auto. apply H. right; auto. Qed. (** * Properties of [alloc_reg] and [alloc_regs] *) Lemma alloc_reg_valid: forall a s1 s2 map r i, map_valid map s1 -> alloc_reg map a s1 = OK r s2 i -> reg_valid r s2. Proof. intros until r. unfold alloc_reg. case a; eauto with rtlg. Qed. Hint Resolve alloc_reg_valid: rtlg. Lemma alloc_reg_fresh_or_in_map: forall map a s r s' i, map_valid map s -> alloc_reg map a s = OK r s' i -> reg_in_map map r \/ reg_fresh r s. Proof. intros until s'. unfold alloc_reg. destruct a; intros; try (right; eauto with rtlg; fail). left; eauto with rtlg. left; eauto with rtlg. Qed. Lemma alloc_regs_valid: forall al s1 s2 map rl i, map_valid map s1 -> alloc_regs map al s1 = OK rl s2 i -> regs_valid rl s2. Proof. induction al; simpl; intros; monadInv H0. apply regs_valid_nil. apply regs_valid_cons. eauto with rtlg. eauto with rtlg. Qed. Hint Resolve alloc_regs_valid: rtlg. Lemma alloc_regs_fresh_or_in_map: forall map al s rl s' i, map_valid map s -> alloc_regs map al s = OK rl s' i -> forall r, In r rl -> reg_in_map map r \/ reg_fresh r s. Proof. induction al; simpl; intros; monadInv H0. elim H1. elim H1; intro. subst r. eapply alloc_reg_fresh_or_in_map; eauto. exploit IHal. 2: eauto. apply map_valid_incr with s; eauto with rtlg. eauto. intros [A|B]. auto. right; eauto with rtlg. Qed. Lemma alloc_optreg_valid: forall dest s1 s2 map r i, map_valid map s1 -> alloc_optreg map dest s1 = OK r s2 i -> reg_valid r s2. Proof. intros until r. unfold alloc_reg. case dest; eauto with rtlg. Qed. Hint Resolve alloc_optreg_valid: rtlg. Lemma alloc_optreg_fresh_or_in_map: forall map dest s r s' i, map_valid map s -> alloc_optreg map dest s = OK r s' i -> reg_in_map map r \/ reg_fresh r s. Proof. intros until s'. unfold alloc_optreg. destruct dest; intros. left; eauto with rtlg. right; eauto with rtlg. Qed. Lemma alloc_regs_2addr_valid: forall al rd s1 s2 map rl i, map_valid map s1 -> reg_valid rd s1 -> alloc_regs_2addr map al rd s1 = OK rl s2 i -> regs_valid rl s2. Proof. unfold alloc_regs_2addr; intros. destruct al; monadInv H1. apply regs_valid_nil. apply regs_valid_cons. eauto with rtlg. eauto with rtlg. Qed. Hint Resolve alloc_regs_2addr_valid: rtlg. Lemma alloc_regs_2addr_fresh_or_in_map: forall map al rd s rl s' i, map_valid map s -> alloc_regs_2addr map al rd s = OK rl s' i -> forall r, In r rl -> r = rd \/ reg_in_map map r \/ reg_fresh r s. Proof. unfold alloc_regs_2addr; intros. destruct al; monadInv H0. elim H1. simpl in H1; destruct H1. auto. right. eapply alloc_regs_fresh_or_in_map; eauto. Qed. (** A register is an adequate target for holding the value of an expression if - either the register is associated with a Cminor let-bound variable or a Cminor local variable; - or the register is not associated with any Cminor variable and does not belong to the preserved set [pr]. *) Inductive target_reg_ok (map: mapping) (pr: list reg): expr -> reg -> Prop := | target_reg_var: forall id r, map.(map_vars)!id = Some r -> target_reg_ok map pr (Evar id) r | target_reg_letvar: forall idx r, nth_error map.(map_letvars) idx = Some r -> target_reg_ok map pr (Eletvar idx) r | target_reg_other: forall a r, ~(reg_in_map map r) -> ~In r pr -> target_reg_ok map pr a r. Inductive target_regs_ok (map: mapping) (pr: list reg): exprlist -> list reg -> Prop := | target_regs_nil: target_regs_ok map pr Enil nil | target_regs_cons: forall a1 al r1 rl, target_reg_ok map pr a1 r1 -> target_regs_ok map (r1 :: pr) al rl -> target_regs_ok map pr (Econs a1 al) (r1 :: rl). Lemma target_reg_ok_append: forall map pr a r, target_reg_ok map pr a r -> forall pr', (forall r', In r' pr' -> reg_in_map map r' \/ r' <> r) -> target_reg_ok map (pr' ++ pr) a r. Proof. induction 1; intros. constructor; auto. constructor; auto. constructor; auto. red; intros. elim (in_app_or _ _ _ H2); intro. generalize (H1 _ H3). tauto. tauto. Qed. Lemma target_reg_ok_cons: forall map pr a r, target_reg_ok map pr a r -> forall r', reg_in_map map r' \/ r' <> r -> target_reg_ok map (r' :: pr) a r. Proof. intros. change (r' :: pr) with ((r' :: nil) ++ pr). apply target_reg_ok_append; auto. intros r'' [A|B]. subst r''; auto. contradiction. Qed. Lemma new_reg_target_ok: forall map pr s1 a r s2 i, map_valid map s1 -> regs_valid pr s1 -> new_reg s1 = OK r s2 i -> target_reg_ok map pr a r. Proof. intros. constructor. red; intro. apply valid_fresh_absurd with r s1. eauto with rtlg. eauto with rtlg. red; intro. apply valid_fresh_absurd with r s1. auto. eauto with rtlg. Qed. Lemma alloc_reg_target_ok: forall map pr s1 a r s2 i, map_valid map s1 -> regs_valid pr s1 -> alloc_reg map a s1 = OK r s2 i -> target_reg_ok map pr a r. Proof. intros. unfold alloc_reg in H1. destruct a; try (eapply new_reg_target_ok; eauto; fail). (* Evar *) generalize H1; unfold find_var. caseEq (map_vars map)!i0; intros. inv H3. constructor. auto. inv H3. (* Elet *) generalize H1; unfold find_letvar. caseEq (nth_error (map_letvars map) n); intros. inv H3. constructor. auto. inv H3. Qed. Lemma alloc_regs_target_ok: forall map al pr s1 rl s2 i, map_valid map s1 -> regs_valid pr s1 -> alloc_regs map al s1 = OK rl s2 i -> target_regs_ok map pr al rl. Proof. induction al; intros; monadInv H1. constructor. constructor. eapply alloc_reg_target_ok; eauto. apply IHal with s s2 INCR1; eauto with rtlg. apply regs_valid_cons; eauto with rtlg. Qed. Lemma alloc_regs_2addr_target_ok: forall map al rd pr s1 rl s2 i, map_valid map s1 -> regs_valid pr s1 -> reg_valid rd s1 -> ~(reg_in_map map rd) -> ~In rd pr -> alloc_regs_2addr map al rd s1 = OK rl s2 i -> target_regs_ok map pr al rl. Proof. unfold alloc_regs_2addr; intros. destruct al; monadInv H4. constructor. constructor. constructor; auto. eapply alloc_regs_target_ok; eauto. apply regs_valid_cons; auto. Qed. Hint Resolve new_reg_target_ok alloc_reg_target_ok alloc_regs_target_ok alloc_regs_2addr_target_ok: rtlg. (** The following predicate is a variant of [target_reg_ok] used to characterize registers that are adequate for holding the return value of a function. *) Inductive return_reg_ok: state -> mapping -> option reg -> Prop := | return_reg_ok_none: forall s map, return_reg_ok s map None | return_reg_ok_some: forall s map r, ~(reg_in_map map r) -> reg_valid r s -> return_reg_ok s map (Some r). Lemma return_reg_ok_incr: forall s map rret, return_reg_ok s map rret -> forall s', state_incr s s' -> return_reg_ok s' map rret. Proof. induction 1; intros; econstructor; eauto with rtlg. Qed. Hint Resolve return_reg_ok_incr: rtlg. Lemma new_reg_return_ok: forall s1 r s2 map sig i, new_reg s1 = OK r s2 i -> map_valid map s1 -> return_reg_ok s2 map (ret_reg sig r). Proof. intros. unfold ret_reg. destruct (sig_res sig); constructor. eauto with rtlg. eauto with rtlg. Qed. (** * Relational specification of the translation *) (** We now define inductive predicates that characterize the fact that the control-flow graph produced by compilation of a Cminor function contains sub-graphs that correspond to the translation of each Cminor expression or statement in the original code. *) (** [tr_move c ns rs nd rd] holds if the graph [c], between nodes [ns] and [nd], contains instructions that move the value of register [rs] to register [rd]. *) Inductive tr_move (c: code): node -> reg -> node -> reg -> Prop := | tr_move_0: forall n r, tr_move c n r n r | tr_move_1: forall ns rs nd rd, c!ns = Some (Iop Omove (rs :: nil) rd nd) -> tr_move c ns rs nd rd. (** [reg_map_ok map r optid] characterizes the destination register for an expression: if [optid] is [None], the destination is a fresh register (not associated with any variable); if [optid] is [Some id], the destination is the register associated with local variable [id]. *) Inductive reg_map_ok: mapping -> reg -> option ident -> Prop := | reg_map_ok_novar: forall map rd, ~reg_in_map map rd -> reg_map_ok map rd None | reg_map_ok_somevar: forall map rd id, map.(map_vars)!id = Some rd -> reg_map_ok map rd (Some id). Hint Resolve reg_map_ok_novar: rtlg. (** [tr_expr c map pr expr ns nd rd optid] holds if the graph [c], between nodes [ns] and [nd], contains instructions that compute the value of the Cminor expression [expr] and deposit this value in register [rd]. [map] is a mapping from Cminor variables to the corresponding RTL registers. [pr] is a list of RTL registers whose values must be preserved during this computation. All registers mentioned in [map] must also be preserved during this computation. (Exception: if [optid = Some id], the register associated with local variable [id] can be assigned, but only at the end of the expression evaluation.) To ensure this property, we demand that the result registers of the instructions appearing on the path from [ns] to [nd] are not in [pr], and moreover that they satisfy the [reg_map_ok] predicate. *) Inductive tr_expr (c: code): mapping -> list reg -> expr -> node -> node -> reg -> option ident -> Prop := | tr_Evar: forall map pr id ns nd r rd dst, map.(map_vars)!id = Some r -> ((rd = r /\ dst = None) \/ (reg_map_ok map rd dst /\ ~In rd pr)) -> tr_move c ns r nd rd -> tr_expr c map pr (Evar id) ns nd rd dst | tr_Eop: forall map pr op al ns nd rd n1 rl dst, tr_exprlist c map pr al ns n1 rl -> c!n1 = Some (Iop op rl rd nd) -> reg_map_ok map rd dst -> ~In rd pr -> tr_expr c map pr (Eop op al) ns nd rd dst | tr_Eload: forall map pr chunk addr al ns nd rd n1 rl dst, tr_exprlist c map pr al ns n1 rl -> c!n1 = Some (Iload chunk addr rl rd nd) -> reg_map_ok map rd dst -> ~In rd pr -> tr_expr c map pr (Eload chunk addr al) ns nd rd dst | tr_Econdition: forall map pr b ifso ifnot ns nd rd ntrue nfalse dst, tr_condition c map pr b ns ntrue nfalse -> tr_expr c map pr ifso ntrue nd rd dst -> tr_expr c map pr ifnot nfalse nd rd dst -> tr_expr c map pr (Econdition b ifso ifnot) ns nd rd dst | tr_Elet: forall map pr b1 b2 ns nd rd n1 r dst, ~reg_in_map map r -> tr_expr c map pr b1 ns n1 r None -> tr_expr c (add_letvar map r) pr b2 n1 nd rd dst -> tr_expr c map pr (Elet b1 b2) ns nd rd dst | tr_Eletvar: forall map pr n ns nd rd r dst, List.nth_error map.(map_letvars) n = Some r -> ((rd = r /\ dst = None) \/ (reg_map_ok map rd dst /\ ~In rd pr)) -> tr_move c ns r nd rd -> tr_expr c map pr (Eletvar n) ns nd rd dst (** [tr_condition c map pr cond ns ntrue nfalse rd] holds if the graph [c], starting at node [ns], contains instructions that compute the truth value of the Cminor conditional expression [cond] and terminate on node [ntrue] if the condition holds and on node [nfalse] otherwise. *) with tr_condition (c: code): mapping -> list reg -> condexpr -> node -> node -> node -> Prop := | tr_CEtrue: forall map pr ntrue nfalse, tr_condition c map pr CEtrue ntrue ntrue nfalse | tr_CEfalse: forall map pr ntrue nfalse, tr_condition c map pr CEfalse nfalse ntrue nfalse | tr_CEcond: forall map pr cond bl ns ntrue nfalse n1 rl, tr_exprlist c map pr bl ns n1 rl -> c!n1 = Some (Icond cond rl ntrue nfalse) -> tr_condition c map pr (CEcond cond bl) ns ntrue nfalse | tr_CEcondition: forall map pr b ifso ifnot ns ntrue nfalse ntrue' nfalse', tr_condition c map pr b ns ntrue' nfalse' -> tr_condition c map pr ifso ntrue' ntrue nfalse -> tr_condition c map pr ifnot nfalse' ntrue nfalse -> tr_condition c map pr (CEcondition b ifso ifnot) ns ntrue nfalse (** [tr_exprlist c map pr exprs ns nd rds] holds if the graph [c], between nodes [ns] and [nd], contains instructions that compute the values of the list of Cminor expression [exprlist] and deposit these values in registers [rds]. *) with tr_exprlist (c: code): mapping -> list reg -> exprlist -> node -> node -> list reg -> Prop := | tr_Enil: forall map pr n, tr_exprlist c map pr Enil n n nil | tr_Econs: forall map pr a1 al ns nd r1 rl n1, tr_expr c map pr a1 ns n1 r1 None -> tr_exprlist c map (r1 :: pr) al n1 nd rl -> tr_exprlist c map pr (Econs a1 al) ns nd (r1 :: rl). (** Auxiliary for the compilation of [switch] statements. *) Definition tr_jumptable (nexits: list node) (tbl: list nat) (ttbl: list node) : Prop := forall v act, list_nth_z tbl v = Some act -> exists n, list_nth_z ttbl v = Some n /\ nth_error nexits act = Some n. Inductive tr_switch (c: code) (map: mapping) (r: reg) (nexits: list node): comptree -> node -> Prop := | tr_switch_action: forall act n, nth_error nexits act = Some n -> tr_switch c map r nexits (CTaction act) n | tr_switch_ifeq: forall key act t' n ncont nfound, tr_switch c map r nexits t' ncont -> nth_error nexits act = Some nfound -> c!n = Some(Icond (Ccompimm Ceq key) (r :: nil) nfound ncont) -> tr_switch c map r nexits (CTifeq key act t') n | tr_switch_iflt: forall key t1 t2 n n1 n2, tr_switch c map r nexits t1 n1 -> tr_switch c map r nexits t2 n2 -> c!n = Some(Icond (Ccompuimm Clt key) (r :: nil) n1 n2) -> tr_switch c map r nexits (CTiflt key t1 t2) n | tr_switch_jumptable: forall ofs sz tbl t n n1 n2 n3 rt ttbl, ~reg_in_map map rt -> rt <> r -> c!n = Some(Iop (if Int.eq ofs Int.zero then Omove else Oaddimm (Int.neg ofs)) (r ::nil) rt n1) -> c!n1 = Some(Icond (Ccompuimm Clt sz) (rt :: nil) n2 n3) -> c!n2 = Some(Ijumptable rt ttbl) -> tr_switch c map r nexits t n3 -> tr_jumptable nexits tbl ttbl -> tr_switch c map r nexits (CTjumptable ofs sz tbl t) n. (** [tr_stmt c map stmt ns ncont nexits nret rret] holds if the graph [c], starting at node [ns], contains instructions that perform the Cminor statement [stmt]. These instructions branch to node [ncont] if the statement terminates normally, to the [n]-th node in [nexits] if the statement terminates prematurely on a [exit n] statement, and to [nret] if the statement terminates prematurely on a [return] statement. Moreover, if the [return] statement has an argument, its value is deposited in register [rret]. *) Inductive tr_stmt (c: code) (map: mapping): stmt -> node -> node -> list node -> labelmap -> node -> option reg -> Prop := | tr_Sskip: forall ns nexits ngoto nret rret, tr_stmt c map Sskip ns ns nexits ngoto nret rret | tr_Sassign: forall id a ns nd nexits ngoto nret rret r, map.(map_vars)!id = Some r -> expr_is_2addr_op a = false -> tr_expr c map nil a ns nd r (Some id) -> tr_stmt c map (Sassign id a) ns nd nexits ngoto nret rret | tr_Sassign_2: forall id a ns n1 nd nexits ngoto nret rret rd r, map.(map_vars)!id = Some r -> tr_expr c map nil a ns n1 rd None -> tr_move c n1 rd nd r -> tr_stmt c map (Sassign id a) ns nd nexits ngoto nret rret | tr_Sstore: forall chunk addr al b ns nd nexits ngoto nret rret rd n1 rl n2, tr_exprlist c map nil al ns n1 rl -> tr_expr c map rl b n1 n2 rd None -> c!n2 = Some (Istore chunk addr rl rd nd) -> tr_stmt c map (Sstore chunk addr al b) ns nd nexits ngoto nret rret | tr_Scall: forall optid sig b cl ns nd nexits ngoto nret rret rd n1 rf n2 rargs, tr_expr c map nil b ns n1 rf None -> tr_exprlist c map (rf :: nil) cl n1 n2 rargs -> c!n2 = Some (Icall sig (inl _ rf) rargs rd nd) -> reg_map_ok map rd optid -> tr_stmt c map (Scall optid sig (inl _ b) cl) ns nd nexits ngoto nret rret | tr_Scall_imm: forall optid sig id cl ns nd nexits ngoto nret rret rd n2 rargs, tr_exprlist c map nil cl ns n2 rargs -> c!n2 = Some (Icall sig (inr _ id) rargs rd nd) -> reg_map_ok map rd optid -> tr_stmt c map (Scall optid sig (inr _ id) cl) ns nd nexits ngoto nret rret | tr_Stailcall: forall sig b cl ns nd nexits ngoto nret rret n1 rf n2 rargs, tr_expr c map nil b ns n1 rf None -> tr_exprlist c map (rf :: nil) cl n1 n2 rargs -> c!n2 = Some (Itailcall sig (inl _ rf) rargs) -> tr_stmt c map (Stailcall sig (inl _ b) cl) ns nd nexits ngoto nret rret | tr_Stailcall_imm: forall sig id cl ns nd nexits ngoto nret rret n2 rargs, tr_exprlist c map nil cl ns n2 rargs -> c!n2 = Some (Itailcall sig (inr _ id) rargs) -> tr_stmt c map (Stailcall sig (inr _ id) cl) ns nd nexits ngoto nret rret | tr_Sbuiltin: forall optid ef al ns nd nexits ngoto nret rret rd n1 rargs, tr_exprlist c map nil al ns n1 rargs -> c!n1 = Some (Ibuiltin ef rargs rd nd) -> reg_map_ok map rd optid -> tr_stmt c map (Sbuiltin optid ef al) ns nd nexits ngoto nret rret | tr_Sseq: forall s1 s2 ns nd nexits ngoto nret rret n, tr_stmt c map s2 n nd nexits ngoto nret rret -> tr_stmt c map s1 ns n nexits ngoto nret rret -> tr_stmt c map (Sseq s1 s2) ns nd nexits ngoto nret rret | tr_Sifthenelse: forall a strue sfalse ns nd nexits ngoto nret rret ntrue nfalse, tr_stmt c map strue ntrue nd nexits ngoto nret rret -> tr_stmt c map sfalse nfalse nd nexits ngoto nret rret -> tr_condition c map nil a ns ntrue nfalse -> tr_stmt c map (Sifthenelse a strue sfalse) ns nd nexits ngoto nret rret | tr_Sloop: forall sbody ns nd nexits ngoto nret rret nloop nend, tr_stmt c map sbody nloop nend nexits ngoto nret rret -> c!ns = Some(Inop nloop) -> c!nend = Some(Inop nloop) -> tr_stmt c map (Sloop sbody) ns nd nexits ngoto nret rret | tr_Sblock: forall sbody ns nd nexits ngoto nret rret, tr_stmt c map sbody ns nd (nd :: nexits) ngoto nret rret -> tr_stmt c map (Sblock sbody) ns nd nexits ngoto nret rret | tr_Sexit: forall n ns nd nexits ngoto nret rret, nth_error nexits n = Some ns -> tr_stmt c map (Sexit n) ns nd nexits ngoto nret rret | tr_Sswitch: forall a cases default ns nd nexits ngoto nret rret n r t, validate_switch default cases t = true -> tr_expr c map nil a ns n r None -> tr_switch c map r nexits t n -> tr_stmt c map (Sswitch a cases default) ns nd nexits ngoto nret rret | tr_Sreturn_none: forall nret nd nexits ngoto, tr_stmt c map (Sreturn None) nret nd nexits ngoto nret None | tr_Sreturn_some: forall a ns nd nexits ngoto nret rret, tr_expr c map nil a ns nret rret None -> tr_stmt c map (Sreturn (Some a)) ns nd nexits ngoto nret (Some rret) | tr_Slabel: forall lbl s ns nd nexits ngoto nret rret n, ngoto!lbl = Some n -> c!n = Some (Inop ns) -> tr_stmt c map s ns nd nexits ngoto nret rret -> tr_stmt c map (Slabel lbl s) ns nd nexits ngoto nret rret | tr_Sgoto: forall lbl ns nd nexits ngoto nret rret, ngoto!lbl = Some ns -> tr_stmt c map (Sgoto lbl) ns nd nexits ngoto nret rret. (** [tr_function f tf] specifies the RTL function [tf] that [RTLgen.transl_function] returns. *) Inductive tr_function: CminorSel.function -> RTL.function -> Prop := | tr_function_intro: forall f code rparams map1 s0 s1 i1 rvars map2 s2 i2 nentry ngoto nret rret orret, add_vars init_mapping f.(CminorSel.fn_params) s0 = OK (rparams, map1) s1 i1 -> add_vars map1 f.(CminorSel.fn_vars) s1 = OK (rvars, map2) s2 i2 -> orret = ret_reg f.(CminorSel.fn_sig) rret -> tr_stmt code map2 f.(CminorSel.fn_body) nentry nret nil ngoto nret orret -> code!nret = Some(Ireturn orret) -> tr_function f (RTL.mkfunction f.(CminorSel.fn_sig) rparams f.(CminorSel.fn_stackspace) code nentry). (** * Correctness proof of the translation functions *) (** We now show that the translation functions in module [RTLgen] satisfy the specifications given above as inductive predicates. *) Lemma tr_move_incr: forall s1 s2, state_incr s1 s2 -> forall ns rs nd rd, tr_move s1.(st_code) ns rs nd rd -> tr_move s2.(st_code) ns rs nd rd. Proof. induction 2; econstructor; eauto with rtlg. Qed. Lemma tr_expr_incr: forall s1 s2, state_incr s1 s2 -> forall map pr a ns nd rd dst, tr_expr s1.(st_code) map pr a ns nd rd dst -> tr_expr s2.(st_code) map pr a ns nd rd dst with tr_condition_incr: forall s1 s2, state_incr s1 s2 -> forall map pr a ns ntrue nfalse, tr_condition s1.(st_code) map pr a ns ntrue nfalse -> tr_condition s2.(st_code) map pr a ns ntrue nfalse with tr_exprlist_incr: forall s1 s2, state_incr s1 s2 -> forall map pr al ns nd rl, tr_exprlist s1.(st_code) map pr al ns nd rl -> tr_exprlist s2.(st_code) map pr al ns nd rl. Proof. intros s1 s2 EXT. pose (AT := fun pc i => instr_at_incr s1 s2 pc i EXT). induction 1; econstructor; eauto. eapply tr_move_incr; eauto. eapply tr_move_incr; eauto. intros s1 s2 EXT. pose (AT := fun pc i => instr_at_incr s1 s2 pc i EXT). induction 1; econstructor; eauto. intros s1 s2 EXT. pose (AT := fun pc i => instr_at_incr s1 s2 pc i EXT). induction 1; econstructor; eauto. Qed. Lemma add_move_charact: forall s ns rs nd rd s' i, add_move rs rd nd s = OK ns s' i -> tr_move s'.(st_code) ns rs nd rd. Proof. intros. unfold add_move in H. destruct (Reg.eq rs rd). inv H. constructor. constructor. eauto with rtlg. Qed. Lemma transl_expr_charact: forall a map rd nd s ns s' pr INCR (TR: transl_expr map a rd nd s = OK ns s' INCR) (WF: map_valid map s) (OK: target_reg_ok map pr a rd) (VALID: regs_valid pr s) (VALID2: reg_valid rd s), tr_expr s'.(st_code) map pr a ns nd rd None with transl_condexpr_charact: forall a map ntrue nfalse s ns s' pr INCR (TR: transl_condition map a ntrue nfalse s = OK ns s' INCR) (VALID: regs_valid pr s) (WF: map_valid map s), tr_condition s'.(st_code) map pr a ns ntrue nfalse with transl_exprlist_charact: forall al map rl nd s ns s' pr INCR (TR: transl_exprlist map al rl nd s = OK ns s' INCR) (WF: map_valid map s) (OK: target_regs_ok map pr al rl) (VALID1: regs_valid pr s) (VALID2: regs_valid rl s), tr_exprlist s'.(st_code) map pr al ns nd rl. Proof. induction a; intros; try (monadInv TR); saturateTrans. (* Evar *) generalize EQ; unfold find_var. caseEq (map_vars map)!i; intros; inv EQ1. econstructor; eauto. inv OK. left; split; congruence. right; eauto with rtlg. eapply add_move_charact; eauto. (* Eop *) inv OK. destruct (two_address_op o). econstructor; eauto with rtlg. eapply transl_exprlist_charact; eauto with rtlg. econstructor; eauto with rtlg. eapply transl_exprlist_charact; eauto with rtlg. (* Eload *) inv OK. econstructor; eauto with rtlg. eapply transl_exprlist_charact; eauto with rtlg. (* Econdition *) inv OK. econstructor; eauto with rtlg. apply tr_expr_incr with s1; auto. eapply transl_expr_charact; eauto 2 with rtlg. constructor; auto. apply tr_expr_incr with s0; auto. eapply transl_expr_charact; eauto 2 with rtlg. constructor; auto. (* Elet *) inv OK. econstructor. eapply new_reg_not_in_map; eauto with rtlg. eapply transl_expr_charact; eauto 3 with rtlg. apply tr_expr_incr with s1; auto. eapply transl_expr_charact. eauto. apply add_letvar_valid; eauto with rtlg. constructor; auto. red; unfold reg_in_map. simpl. intros [[id A] | [B | C]]. elim H. left; exists id; auto. subst x. apply valid_fresh_absurd with rd s. auto. eauto with rtlg. elim H. right; auto. eauto with rtlg. eauto with rtlg. (* Eletvar *) generalize EQ; unfold find_letvar. caseEq (nth_error (map_letvars map) n); intros; inv EQ0. monadInv EQ1. econstructor; eauto with rtlg. inv OK. left; split; congruence. right; eauto with rtlg. eapply add_move_charact; eauto. monadInv EQ1. (* Conditions *) induction a; intros; try (monadInv TR); saturateTrans. (* CEtrue *) constructor. (* CEfalse *) constructor. (* CEcond *) econstructor; eauto with rtlg. eapply transl_exprlist_charact; eauto with rtlg. (* CEcondition *) econstructor. eapply transl_condexpr_charact; eauto with rtlg. apply tr_condition_incr with s1; auto. eapply transl_condexpr_charact; eauto with rtlg. apply tr_condition_incr with s0; auto. eapply transl_condexpr_charact; eauto with rtlg. (* Lists *) induction al; intros; try (monadInv TR); saturateTrans. (* Enil *) destruct rl; inv TR. constructor. (* Econs *) destruct rl; simpl in TR; monadInv TR. inv OK. econstructor. eapply transl_expr_charact; eauto with rtlg. generalize (VALID2 r (in_eq _ _)). eauto with rtlg. apply tr_exprlist_incr with s0; auto. eapply transl_exprlist_charact; eauto with rtlg. apply regs_valid_cons. apply VALID2. auto with coqlib. auto. red; intros; apply VALID2; auto with coqlib. Qed. (** A variant of [transl_expr_charact], for use when the destination register is the one associated with a variable. *) Lemma transl_expr_assign_charact: forall id a map rd nd s ns s' INCR (TR: transl_expr map a rd nd s = OK ns s' INCR) (WF: map_valid map s) (OK: reg_map_ok map rd (Some id)) (NOT2ADDR: expr_is_2addr_op a = false), tr_expr s'.(st_code) map nil a ns nd rd (Some id). Proof. Opaque two_address_op. induction a; intros; monadInv TR; saturateTrans. (* Evar *) generalize EQ; unfold find_var. caseEq (map_vars map)!i; intros; inv EQ1. econstructor; eauto. eapply add_move_charact; eauto. (* Eop *) simpl in NOT2ADDR. rewrite NOT2ADDR in EQ. econstructor; eauto with rtlg. eapply transl_exprlist_charact; eauto with rtlg. (* Eload *) econstructor; eauto with rtlg. eapply transl_exprlist_charact; eauto with rtlg. (* Econdition *) simpl in NOT2ADDR. destruct (orb_false_elim _ _ NOT2ADDR). econstructor; eauto with rtlg. eapply transl_condexpr_charact; eauto with rtlg. apply tr_expr_incr with s1; auto. eapply IHa1; eauto 2 with rtlg. apply tr_expr_incr with s0; auto. eapply IHa2; eauto 2 with rtlg. (* Elet *) simpl in NOT2ADDR. econstructor. eapply new_reg_not_in_map; eauto with rtlg. eapply transl_expr_charact; eauto 3 with rtlg. apply tr_expr_incr with s1; auto. eapply IHa2; eauto. apply add_letvar_valid; eauto with rtlg. inv OK. constructor. auto. (* Eletvar *) generalize EQ; unfold find_letvar. caseEq (nth_error (map_letvars map) n); intros; inv EQ0. monadInv EQ1. econstructor; eauto with rtlg. eapply add_move_charact; eauto. monadInv EQ1. Qed. Lemma alloc_optreg_map_ok: forall map optid s1 r s2 i, map_valid map s1 -> alloc_optreg map optid s1 = OK r s2 i -> reg_map_ok map r optid. Proof. unfold alloc_optreg; intros. destruct optid. constructor. unfold find_var in H0. destruct (map_vars map)!i0; monadInv H0. auto. constructor. eapply new_reg_not_in_map; eauto. Qed. Lemma tr_switch_incr: forall s1 s2, state_incr s1 s2 -> forall map r nexits t ns, tr_switch s1.(st_code) map r nexits t ns -> tr_switch s2.(st_code) map r nexits t ns. Proof. induction 2; econstructor; eauto with rtlg. Qed. Lemma tr_stmt_incr: forall s1 s2, state_incr s1 s2 -> forall map s ns nd nexits ngoto nret rret, tr_stmt s1.(st_code) map s ns nd nexits ngoto nret rret -> tr_stmt s2.(st_code) map s ns nd nexits ngoto nret rret. Proof. intros s1 s2 EXT. generalize tr_expr_incr tr_condition_incr tr_exprlist_incr; intros I1 I2 I3. pose (AT := fun pc i => instr_at_incr s1 s2 pc i EXT). induction 1; try (econstructor; eauto; fail). eapply tr_Sassign_2; eauto. eapply tr_move_incr; eauto. econstructor; eauto. eapply tr_switch_incr; eauto. Qed. Lemma transl_exit_charact: forall nexits n s ne s' incr, transl_exit nexits n s = OK ne s' incr -> nth_error nexits n = Some ne /\ s' = s. Proof. intros until incr. unfold transl_exit. destruct (nth_error nexits n); intro; monadInv H. auto. Qed. Lemma transl_jumptable_charact: forall nexits tbl s nl s' incr, transl_jumptable nexits tbl s = OK nl s' incr -> tr_jumptable nexits tbl nl /\ s' = s. Proof. induction tbl; intros. monadInv H. split. red. simpl. intros. discriminate. auto. monadInv H. exploit transl_exit_charact; eauto. intros [A B]. exploit IHtbl; eauto. intros [C D]. split. red. simpl. intros. destruct (zeq v 0). inv H. exists x; auto. auto. congruence. Qed. Lemma transl_switch_charact: forall map r nexits t s ns s' incr, map_valid map s -> reg_valid r s -> transl_switch r nexits t s = OK ns s' incr -> tr_switch s'.(st_code) map r nexits t ns. Proof. induction t; simpl; intros; saturateTrans. exploit transl_exit_charact; eauto. intros [A B]. econstructor; eauto. monadInv H1. exploit transl_exit_charact; eauto. intros [A B]. subst s1. econstructor; eauto 2 with rtlg. apply tr_switch_incr with s0; eauto with rtlg. monadInv H1. econstructor; eauto 2 with rtlg. apply tr_switch_incr with s1; eauto with rtlg. apply tr_switch_incr with s0; eauto with rtlg. monadInv H1. exploit transl_jumptable_charact; eauto. intros [A B]. subst s1. econstructor. eauto with rtlg. apply sym_not_equal. apply valid_fresh_different with s; eauto with rtlg. eauto with rtlg. eauto with rtlg. eauto with rtlg. apply tr_switch_incr with s3. eauto with rtlg. eapply IHt with (s := s2); eauto with rtlg. auto. Qed. Lemma transl_stmt_charact: forall map stmt nd nexits ngoto nret rret s ns s' INCR (TR: transl_stmt map stmt nd nexits ngoto nret rret s = OK ns s' INCR) (WF: map_valid map s) (OK: return_reg_ok s map rret), tr_stmt s'.(st_code) map stmt ns nd nexits ngoto nret rret. Proof. induction stmt; intros; simpl in TR; try (monadInv TR); saturateTrans. (* Sskip *) constructor. (* Sassign *) revert EQ. unfold find_var. case_eq (map_vars map)!i; intros; monadInv EQ. remember (expr_is_2addr_op e) as is2a. destruct is2a. monadInv EQ0. eapply tr_Sassign_2; eauto. eapply transl_expr_charact; eauto with rtlg. apply tr_move_incr with s1; auto. eapply add_move_charact; eauto. eapply tr_Sassign; eauto. eapply transl_expr_assign_charact; eauto with rtlg. constructor. auto. (* Sstore *) econstructor; eauto with rtlg. eapply transl_exprlist_charact; eauto 3 with rtlg. apply tr_expr_incr with s3; auto. eapply transl_expr_charact; eauto 4 with rtlg. (* Scall *) destruct s0 as [b | id]; monadInv TR; saturateTrans. (* indirect *) econstructor; eauto 4 with rtlg. eapply transl_expr_charact; eauto 3 with rtlg. apply tr_exprlist_incr with s5. auto. eapply transl_exprlist_charact; eauto 3 with rtlg. eapply alloc_regs_target_ok with (s1 := s0); eauto 3 with rtlg. apply regs_valid_cons; eauto 3 with rtlg. apply regs_valid_incr with s0; eauto 3 with rtlg. apply regs_valid_cons; eauto 3 with rtlg. apply regs_valid_incr with s2; eauto 3 with rtlg. eapply alloc_optreg_map_ok with (s1 := s2); eauto 3 with rtlg. (* direct *) econstructor; eauto 4 with rtlg. eapply transl_exprlist_charact; eauto 3 with rtlg. eapply alloc_optreg_map_ok with (s1 := s0); eauto 3 with rtlg. (* Stailcall *) destruct s0 as [b | id]; monadInv TR; saturateTrans. (* indirect *) assert (RV: regs_valid (x :: nil) s0). apply regs_valid_cons; eauto 3 with rtlg. econstructor; eauto 3 with rtlg. eapply transl_expr_charact; eauto 3 with rtlg. apply tr_exprlist_incr with s4; auto. eapply transl_exprlist_charact; eauto 4 with rtlg. (* direct *) econstructor; eauto 3 with rtlg. eapply transl_exprlist_charact; eauto 4 with rtlg. (* Sbuiltin *) econstructor; eauto 4 with rtlg. eapply transl_exprlist_charact; eauto 3 with rtlg. eapply alloc_optreg_map_ok with (s1 := s0); eauto with rtlg. (* Sseq *) econstructor. apply tr_stmt_incr with s0; auto. eapply IHstmt2; eauto with rtlg. eapply IHstmt1; eauto with rtlg. (* Sifthenelse *) destruct (more_likely c stmt1 stmt2); monadInv TR. econstructor. apply tr_stmt_incr with s1; auto. eapply IHstmt1; eauto with rtlg. apply tr_stmt_incr with s0; auto. eapply IHstmt2; eauto with rtlg. eapply transl_condexpr_charact; eauto with rtlg. econstructor. apply tr_stmt_incr with s0; auto. eapply IHstmt1; eauto with rtlg. apply tr_stmt_incr with s1; auto. eapply IHstmt2; eauto with rtlg. eapply transl_condexpr_charact; eauto with rtlg. (* Sloop *) econstructor. apply tr_stmt_incr with s1; auto. eapply IHstmt; eauto with rtlg. eauto with rtlg. eauto with rtlg. (* Sblock *) econstructor. eapply IHstmt; eauto with rtlg. (* Sexit *) exploit transl_exit_charact; eauto. intros [A B]. econstructor. eauto. (* Sswitch *) generalize TR; clear TR. set (t := compile_switch n l). caseEq (validate_switch n l t); intro VALID; intros. monadInv TR. econstructor; eauto with rtlg. eapply transl_expr_charact; eauto with rtlg. apply tr_switch_incr with s1; auto with rtlg. eapply transl_switch_charact with (s := s0); eauto with rtlg. monadInv TR. (* Sreturn *) destruct o; destruct rret; inv TR. inv OK. econstructor; eauto with rtlg. eapply transl_expr_charact; eauto with rtlg. constructor. auto. simpl; tauto. constructor. (* Slabel *) generalize EQ0; clear EQ0. case_eq (ngoto!l); intros; monadInv EQ0. generalize EQ1; clear EQ1. unfold handle_error. case_eq (update_instr n (Inop ns) s0); intros; inv EQ1. econstructor. eauto. eauto with rtlg. eapply tr_stmt_incr with s0; eauto with rtlg. (* Sgoto *) generalize TR; clear TR. case_eq (ngoto!l); intros; monadInv TR. econstructor. auto. Qed. Lemma transl_function_charact: forall f tf, transl_function f = Errors.OK tf -> tr_function f tf. Proof. intros until tf. unfold transl_function. caseEq (reserve_labels (fn_body f) (PTree.empty node, init_state)). intros ngoto s0 RESERVE. caseEq (transl_fun f ngoto s0). congruence. intros [nentry rparams] sfinal INCR TR E. inv E. monadInv TR. exploit add_vars_valid. eexact EQ. apply init_mapping_valid. intros [A B]. exploit add_vars_valid. eexact EQ1. auto. intros [C D]. eapply tr_function_intro; eauto with rtlg. eapply transl_stmt_charact; eauto with rtlg. unfold ret_reg. destruct (sig_res (CminorSel.fn_sig f)). constructor. eauto with rtlg. eauto with rtlg. constructor. Qed.
{ "alphanum_fraction": null, "author": "Ptival", "avg_line_length": null, "converted": null, "ext": null, "file": null, "hexsha": null, "include": null, "lang": null, "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": "github-repos/coq/Ptival-compcert-alias/compcert-alias-c839efb9cd2a4c27add46a1868fe0444d1dfdd9e/backend/RTLgenspec.v", "reason": null, "repo": "compcert-alias", "save_path": "github-repos/coq/Ptival-compcert-alias", "sha": "c839efb9cd2a4c27add46a1868fe0444d1dfdd9e", "size": null }
[STATEMENT] lemma normal_ordinal_rec: assumes s: "\<forall>p x. x < s p x" shows "normal (ordinal_rec z s)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. normal (ordinal_rec z s) [PROOF STEP] apply (rule normalI) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>f. OrdinalInduct.strict_mono f \<Longrightarrow> ordinal_rec z s (oLimit f) = oLimit (\<lambda>n. ordinal_rec z s (f n)) 2. \<And>x. ordinal_rec z s x < ordinal_rec z s (oSuc x) [PROOF STEP] apply (rule ordinal_rec_oLimit) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>f. OrdinalInduct.strict_mono f \<Longrightarrow> \<forall>p x. x \<le> s p x 2. \<And>x. ordinal_rec z s x < ordinal_rec z s (oSuc x) [PROOF STEP] apply (simp add: s order_less_imp_le) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. ordinal_rec z s x < ordinal_rec z s (oSuc x) [PROOF STEP] apply (simp add: s) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "Ordinal_OrdinalRec", "hexsha": null, "include": null, "lang": null, "length": 5, "llama_tokens": 419, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": null }
import cv2 as cv import numpy as np import Module as m import time import dlib # variables COUNTER = 0 TOTAL_BLINK = 0 fonts = cv.FONT_HERSHEY_PLAIN frameCounter = 0 capID = 0 EyesClosedFrame = 3 # objects camera = cv.VideoCapture(capID) # Define the codec and create VideoWriter object fourcc = cv.VideoWriter_fourcc(*'XVID') Recoder = cv.VideoWriter('output.mp4', fourcc, 15.0, (640, 480)) # staring time staringTimer = time.time() while True: frameCounter += 1 ret, frame = camera.read() gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # cv.imshow("image", frame) image, data = m.faceDetector(frame, Draw=True) if data is not None: # m.BlinkingDetection(gray, data) # print('detected') image, PointsList = m.facePoint(gray, frame, data) RightEyeList = PointsList[36:42] LeftEyeList = PointsList[42:48] RightEye = m.blinkDetector(PointsList[42:48]) mask, RightCropd, EyePosition = m.EyesTracking(frame, RightEyeList) mask2, LeftCroped, LeftEyePos = m.EyesTracking(frame, LeftEyeList) CurrentPos, color = m.Position(LeftEyePos) indictor = np.zeros((200, 200, 3), dtype=np.uint8) indictor[:] = color[0] cv.line(frame, (30, 90), (100, 90), color[1], 30) if EyePosition is not None: # print(CurrentPos) cv.putText(frame, f"{CurrentPos}", (35, 95), m.fonts, 0.6, color[0], 2) if mask2 is not None: # cv.imshow('mask2', mask2) # cv.imshow("mask", mask) cv.imshow('Right', RightCropd) LeftEye = m.blinkDetector(LeftEyeList) BlinkRatio = (RightEye+LeftEye)/2 # print(BlinkRatio) cv.circle(frame, (40, 40), int(BlinkRatio*3), m.LIGHT_BLUE, 3) # cv.line(frame,(40, 70), (40,int(70-(BlinkRatio*6))),m.ORANGE,10) if BlinkRatio >= 4: COUNTER += 1 cv.putText(frame, f'Blink ', (50, 70), cv.FONT_HERSHEY_COMPLEX, 0.9, m.PINK, 2) else: if COUNTER > EyesClosedFrame: TOTAL_BLINK += 1 COUNTER = 0 # cv.circle(frame, RightEyeList[0], 3, m.GREEN, 2) # cv.circle(frame, RightEyeList[1], 3, m.YELLOW, 2) # # cv.circle(frame, RightEyeList[3], 3, m.RED, 2) # cv.circle(frame, RightEyeList[4], 4, m.BLUE, 2) # cv.circle(frame, RightEyeList[5], 4, m.LIGHT_BLUE, 2) # for center in LeftEyeList: # cv.circle(frame, center,3, m.ORANGE, 1) # cv.circle(frame, PointLis[0], 2,m.LIGHT_BLUE, 1) cv.putText(frame, f'Blink {TOTAL_BLINK}', (40, 40), m.fonts, 0.7, m.CHOCOLATE, 2) seconds = time.time() - staringTimer # print(seconds) fps = frameCounter/seconds # print(fps) cv.putText(frame, f'FPS: {round(fps, 2)}', (20, 20), fonts, 1.5, m.MAGENTA, 2) cv.imshow("image", image) # cv.imshow('Indicator', indictor) Recoder.write(frame) key = cv.waitKey(1) if key == ord('q'): break cv.destroyAllWindows() Recoder.release() camera.release()
{ "alphanum_fraction": 0.5908075327, "author": null, "avg_line_length": 33.329787234, "converted": null, "ext": "py", "file": null, "hexsha": "d414658fb2d78f83888b94ae4fdfcc70e98988d7", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e77ffd60fff1d236d263a344a16cd4d9504cf777", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Asadullah-Dal17/Track-Eyes", "max_forks_repo_path": "main.py", "max_issues_count": 1, "max_issues_repo_head_hexsha": "e77ffd60fff1d236d263a344a16cd4d9504cf777", "max_issues_repo_issues_event_max_datetime": "2021-04-13T23:35:51.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-13T23:35:51.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Asadullah-Dal17/Track-Eyes", "max_issues_repo_path": "main.py", "max_line_length": 75, "max_stars_count": null, "max_stars_repo_head_hexsha": "e77ffd60fff1d236d263a344a16cd4d9504cf777", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Asadullah-Dal17/Track-Eyes", "max_stars_repo_path": "main.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 942, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 3133 }
@testset "Appender Error" begin db = DBInterface.connect(DuckDB.DB) con = DBInterface.connect(db) @test_throws DuckDB.QueryException DuckDB.Appender(db, "nonexistanttable") @test_throws DuckDB.QueryException DuckDB.Appender(con, "t") end @testset "Appender Usage" begin db = DBInterface.connect(DuckDB.DB) DBInterface.execute(db, "CREATE TABLE integers(i INTEGER)") appender = DuckDB.Appender(db, "integers") DuckDB.close(appender) DuckDB.close(appender) appender = DuckDB.Appender(db, "integers") for i in 0:9 DuckDB.append(appender, i) DuckDB.end_row(appender) end DuckDB.flush(appender) results = DBInterface.execute(db, "SELECT * FROM integers") df = DataFrame(results) @test names(df) == ["i"] @test size(df, 1) == 10 @test df.i == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] end # @testset "Appender API" begin # # Open the database # db = DuckDB.open(":memory:") # con = DuckDB.connect(db) # # # Create the table the data is appended to # DuckDB.execute(con, "CREATE TABLE dtypes(bol BOOLEAN, tint TINYINT, sint SMALLINT, int INTEGER, bint BIGINT, utint UTINYINT, usint USMALLINT, uint UINTEGER, ubint UBIGINT, float FLOAT, double DOUBLE, date DATE, time TIME, vchar VARCHAR, nullval INTEGER)") # # # Create the appender # appender = DuckDB.appender_create(con, "dtypes") # # # Append the different data types # DuckDB.duckdb_append_bool(appender, true) # DuckDB.duckdb_append_int8(appender, 1) # DuckDB.duckdb_append_int16(appender, 2) # DuckDB.duckdb_append_int32(appender, 3) # DuckDB.duckdb_append_int64(appender, 4) # DuckDB.duckdb_append_uint8(appender, 1) # DuckDB.duckdb_append_uint16(appender, 2) # DuckDB.duckdb_append_uint32(appender, 3) # DuckDB.duckdb_append_uint64(appender, 4) # DuckDB.duckdb_append_float(appender, 1.0) # DuckDB.duckdb_append_double(appender, 2.0) # DuckDB.duckdb_append_date(appender, 100) # DuckDB.duckdb_append_time(appender, 200) # DuckDB.duckdb_append_varchar(appender, "Foo") # DuckDB.duckdb_append_null(appender) # # End the row of the appender # DuckDB.duckdb_appender_end_row(appender) # # Destroy the appender and flush the data # DuckDB.duckdb_appender_destroy(appender) # # # Retrive the data from the table and store it in a vector # df = DuckDB.toDataFrame(con, "select * from dtypes;") # data = Matrix(df) # # # Test if the correct types have been appended to the table # @test data[1] === true # @test data[2] === Int8(1) # @test data[3] === Int16(2) # @test data[4] === Int32(3) # @test data[5] === Int64(4) # @test data[6] === UInt8(1) # @test data[7] === UInt16(2) # @test data[8] === UInt32(3) # @test data[9] === UInt64(4) # @test data[10] === Float32(1.0) # @test data[11] === Float64(2.0) # @test data[12] === Dates.Date("1970-04-11") # @test data[13] === Dates.Time(0, 0, 0, 0, 200) # @test data[14] === "Foo" # @test data[15] === missing # # # Disconnect and close the database # DuckDB.disconnect(con) # DuckDB.close(db) # end
{ "alphanum_fraction": 0.6539552474, "author": null, "avg_line_length": 35.2555555556, "converted": null, "ext": "jl", "file": null, "hexsha": "0e7cf034f877ee4e378d3e34bb252c7b6b9322ad", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c2581dfebccaebae9468c924c2c722fcf0306944", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lokax/duckdb", "max_forks_repo_path": "tools/juliapkg/test/test_appender.jl", "max_issues_count": 32, "max_issues_repo_head_hexsha": "c2581dfebccaebae9468c924c2c722fcf0306944", "max_issues_repo_issues_event_max_datetime": "2022-03-29T09:37:26.000Z", "max_issues_repo_issues_event_min_datetime": "2021-09-24T23:50:09.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "lokax/duckdb", "max_issues_repo_path": "tools/juliapkg/test/test_appender.jl", "max_line_length": 261, "max_stars_count": 1, "max_stars_repo_head_hexsha": "c2581dfebccaebae9468c924c2c722fcf0306944", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lokax/duckdb", "max_stars_repo_path": "tools/juliapkg/test/test_appender.jl", "max_stars_repo_stars_event_max_datetime": "2022-01-06T17:44:07.000Z", "max_stars_repo_stars_event_min_datetime": "2022-01-06T17:44:07.000Z", "num_tokens": 1016, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 3173 }
from __future__ import print_function, division import numpy as np import os import cv2 from PIL import Image import random from functools import partial import tensorflow as tf from keras.models import Model, Sequential, load_model from keras.layers.merge import _Merge from keras.layers import Input, Conv2D, MaxPooling2D, ZeroPadding2D, Conv2D, BatchNormalization, UpSampling2D, Activation from keras.layers import Reshape, Dropout, Concatenate, Lambda, Multiply, Add, Flatten, Dense from keras_contrib.layers.normalization.instancenormalization import InstanceNormalization from keras.layers.advanced_activations import LeakyReLU, PReLU from keras.optimizers import Adam from keras import backend as K import keras import cv2 from sklearn.utils import shuffle import random import datetime from keras.applications.vgg16 import VGG16 from keras.applications.vgg19 import VGG19 from keras.applications.resnet50 import ResNet50 import math from skimage.measure import compare_psnr, compare_ssim from keras.utils import multi_gpu_model from scipy.stats import pearsonr def load_confocal(input_shape=None, set=None, z_depth=None): dir = './confocal/' + set lr_lq_set = [] hr_lq_set = [] lr_hq_set = [] hr_hq_set = [] for _, _, files in os.walk(dir+'/'+z_depth): for file in files: if int(file.split('_')[-1].split('.')[0]) < len(files) * 0.8: img_lq = cv2.imread(dir+'/'+z_depth + '/' + file) img = cv2.resize(img_lq, (input_shape[0], input_shape[1])) lr_lq_set.append(img) img = cv2.resize(img_lq, (input_shape[0]*4, input_shape[1]*4)) hr_lq_set.append(img) file = 'Z7_' + file.split('_')[1] img_hq = cv2.imread(dir+'/Z007' + '/' + file) img = cv2.resize(img_hq, (input_shape[0]*4, input_shape[1]*4)) hr_hq_set.append(img) img = cv2.resize(img_hq, (input_shape[0], input_shape[1])) lr_hq_set.append(img) hrhq, lrhq, hrlq, lrlq = hr_hq_set, lr_hq_set, hr_lq_set, lr_lq_set hrhq_train = hrhq lrhq_train = lrhq hrlq_train = hrlq lrlq_train = lrlq lr_lq_set = [] hr_lq_set = [] lr_hq_set = [] hr_hq_set = [] for _, _, files in os.walk(dir+'/'+z_depth): for file in files: if int(file.split('_')[-1].split('.')[0]) >= len(files) * 0.8: img_lq = cv2.imread(dir+'/'+z_depth + '/' + file) img = cv2.resize(img_lq, (input_shape[0], input_shape[1])) lr_lq_set.append(img) img = cv2.resize(img_lq, (input_shape[0]*4, input_shape[1]*4)) hr_lq_set.append(img) file = 'Z7_' + file.split('_')[1] img_hq = cv2.imread(dir+'/Z007' + '/' + file) img = cv2.resize(img_hq, (input_shape[0]*4, input_shape[1]*4)) hr_hq_set.append(img) img = cv2.resize(img_hq, (input_shape[0], input_shape[1])) lr_hq_set.append(img) hrhq, lrhq, hrlq, lrlq = hr_hq_set, lr_hq_set, hr_lq_set, lr_lq_set hrhq_test = hrhq lrhq_test = lrhq hrlq_test = hrlq lrlq_test = lrlq hrhq_train = np.array(hrhq_train) hrhq_train = hrhq_train.astype('float32') /127.5 - 1. hrhq_test = np.array(hrhq_test) hrhq_test = hrhq_test.astype('float32') /127.5 - 1. lrhq_train = np.array(lrhq_train) lrhq_train = lrhq_train.astype('float32') /127.5 - 1. lrhq_test = np.array(lrhq_test) lrhq_test = lrhq_test.astype('float32') /127.5 - 1. hrlq_train = np.array(hrlq_train) hrlq_train = hrlq_train.astype('float32') /127.5 - 1. hrlq_test = np.array(hrlq_test) hrlq_test = hrlq_test.astype('float32') /127.5 - 1. lrlq_train = np.array(lrlq_train) lrlq_train = lrlq_train.astype('float32') /127.5 - 1. lrlq_test = np.array(lrlq_test) lrlq_test = lrlq_test.astype('float32') /127.5 - 1. print(hrhq_train.shape) print(hrhq_test.shape) return hrhq_train, hrhq_test, lrhq_train, lrhq_test, hrlq_train, hrlq_test, lrlq_train, lrlq_test class RandomWeightedAverage(_Merge): """Provides a (random) weighted average between real and generated image samples""" def define_batch_size(self, bs): self.bs = bs def _merge_function(self, inputs): alpha = K.random_uniform((self.bs, 1, 1, 1)) return (alpha * inputs[0]) + ((1 - alpha) * inputs[1]) class StarGAN(object): def __init__(self): # Model configuration. self.channels = 3 self.lr_height = 128 # Low resolution height self.lr_width = 128 # Low resolution width self.lr_shape = (self.lr_height, self.lr_width, self.channels) self.hr_height = self.lr_height*4 # High resolution height self.hr_width = self.lr_width*4 # High resolution width self.hr_shape = (self.hr_height, self.hr_width, self.channels) self.n_residual_blocks = 9 optimizer = Adam(0.0001, 0.5, 0.99) # We use a pre-trained VGG19 model to extract image features from the high resolution # and the generated high resolution images and minimize the mse between them self.vgg_hq = self.build_vgg_hr(name='vgg_hq') self.vgg_hq.trainable = False self.vgg_lq = self.build_vgg_hr(name='vgg_lq') # Calculate output shape of D (PatchGAN) patch_hr_h = int(self.hr_height / 2 ** 4) patch_hr_w = int(self.hr_width / 2 ** 4) self.disc_patch_hr = (patch_hr_h, patch_hr_w, 1) # Number of filters in the first layer of G and D self.gf = 64 self.df = 64 self.discriminator_hq = self.build_discriminator(name='dis_hq') self.discriminator_lq = self.build_discriminator(name='dis_lq') # Build the generator self.generator_lq2hq = self.build_generator(name='gen_lq2hq') self.generator_hq2lq = self.build_generator(name='gen_hq2lq') # High res. and low res. images img_lq = Input(shape=self.hr_shape) img_hq = Input(shape=self.hr_shape) fake_hq = self.generator_lq2hq(img_lq) fake_lq = self.generator_hq2lq(img_hq) reconstr_lq = self.generator_hq2lq(fake_hq) reconstr_hq = self.generator_lq2hq(fake_lq) img_lq_id = self.generator_hq2lq(img_lq) img_hq_id = self.generator_lq2hq(img_hq) fake_hq_features = self.vgg_hq(fake_hq) fake_lq_features = self.vgg_lq(fake_lq) reconstr_hq_features = self.vgg_hq(reconstr_hq) reconstr_lq_features = self.vgg_lq(reconstr_lq) self.discriminator_hq.trainable = False self.discriminator_lq.trainable = False validity_hq = self.discriminator_hq(fake_hq) validity_lq = self.discriminator_lq(fake_lq) validity_reconstr_hq = self.discriminator_hq(reconstr_hq) validity_reconstr_lq = self.discriminator_lq(reconstr_lq) self.combined_hq = Model([img_lq, img_hq], [validity_hq, validity_reconstr_lq, fake_hq_features, reconstr_lq_features, img_lq_id]) self.combined_hq_m = multi_gpu_model(self.combined_hq, gpus=4) self.combined_hq_m.compile(loss=['mse', 'mse', 'mse', 'mse', 'mse'], loss_weights=[1e-3, 1e-3, 1, 1, 1], optimizer=optimizer) self.combined_lq = Model([img_lq, img_hq], [validity_lq, validity_reconstr_hq, fake_lq_features, reconstr_hq_features, img_hq_id]) self.combined_lq_m = multi_gpu_model(self.combined_lq, gpus=4) self.combined_lq_m.compile(loss=['mse', 'mse', 'mse', 'mse', 'mse'], loss_weights=[1e-3, 1e-3, 1, 1, 1], optimizer=optimizer) def build_vgg_hr(self, name=None): """ Builds a pre-trained VGG19 model that outputs image features extracted at the third block of the model """ vgg = VGG19(include_top=False, weights="./model/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5") vgg.outputs = [vgg.layers[9].output] img = Input(shape=self.hr_shape) # Extract image features img_features = vgg(img) model = Model(img, img_features, name=name) model.summary() return model def build_generator(self, name=None): def residual_block(layer_input, filters): """Residual block described in paper""" d = Conv2D(filters, kernel_size=3, strides=1, padding='same')(layer_input) d = InstanceNormalization()(d) d = Activation('relu')(d) d = Conv2D(filters, kernel_size=3, strides=1, padding='same')(d) d = InstanceNormalization()(d) d = Add()([d, layer_input]) return d # Low resolution image input img_lr = Input(shape=self.hr_shape) # Pre-residual block c1 = Conv2D(64, kernel_size=9, strides=1, padding='same')(img_lr) c1 = InstanceNormalization()(c1) c1 = Activation('relu')(c1) n_downsampling = 2 for i in range(n_downsampling): mult = 2 ** i c1 = Conv2D(filters=64 * mult * 2, kernel_size=(3, 3), strides=2, padding='same')(c1) c1 = InstanceNormalization()(c1) c1 = Activation('relu')(c1) # Propogate through residual blocks r = residual_block(c1, self.gf * (n_downsampling ** 2)) for _ in range(8): r = residual_block(r, self.gf * (n_downsampling ** 2)) for i in range(n_downsampling): mult = 2 ** (n_downsampling - i) r = UpSampling2D()(r) r = Conv2D(filters=int(64 * mult / 2), kernel_size=(3, 3), padding='same')(r) r = InstanceNormalization()(r) r = Activation('relu')(r) # Post-residual block c2 = Conv2D(self.channels, kernel_size=7, strides=1, padding='same')(r) c2 = Activation('tanh')(c2) c2 = Add()([c2, img_lr]) model = Model(img_lr, [c2], name=name) model.summary() return model def build_discriminator(self, name=None): n_layers, use_sigmoid = 3, False inputs = Input(shape=self.hr_shape) ndf=64 x = Conv2D(filters=ndf, kernel_size=(4, 4), strides=2, padding='same')(inputs) x = LeakyReLU(0.2)(x) nf_mult, nf_mult_prev = 1, 1 for n in range(n_layers): nf_mult_prev, nf_mult = nf_mult, min(2 ** n, 8) x = Conv2D(filters=ndf * nf_mult, kernel_size=(4, 4), strides=2, padding='same')(x) x = BatchNormalization()(x) x = LeakyReLU(0.2)(x) nf_mult_prev, nf_mult = nf_mult, min(2 ** n_layers, 8) x = Conv2D(filters=ndf * nf_mult, kernel_size=(4, 4), strides=1, padding='same')(x) x = BatchNormalization()(x) x = LeakyReLU(0.2)(x) x = Conv2D(filters=1, kernel_size=(4, 4), strides=1, padding='same')(x) if use_sigmoid: x = Activation('sigmoid')(x) x = Dense(1024, activation='tanh')(x) x = Dense(1, activation='sigmoid')(x) model = Model(inputs=inputs, outputs=x, name=name) model.summary() return model def build_discriminator_lr(self): def d_block(layer_input, filters, strides=1, bn=True): """Discriminator layer""" d = Conv2D(filters, kernel_size=3, strides=strides, padding='same')(layer_input) if bn: d = BatchNormalization()(d) d = LeakyReLU(alpha=0.2)(d) return d # Input img d0 = Input(shape=self.lr_shape) d1 = d_block(d0, self.df, bn=False) d2 = d_block(d1, self.df, strides=2) d4 = d_block(d2, self.df * 2, strides=2) d9 = Dense(self.df * 4)(d4) d10 = LeakyReLU(alpha=0.2)(d9) validity = Dense(1, activation='sigmoid')(d10) model = Model(d0, validity) model.summary() return Model(d0, validity) def test(self, model, epochs, batch_size, sample_interval, set=None, z_depth=None): input_shape = (128, 128, 3) start_time = datetime.datetime.now() weigths_dir = model + '_weights' img_dir = model + '_img' log_dir = model + '_logs/' + datetime.datetime.now().strftime('%Y%m%d-%H%M%S') output_dir = model + '_predict_img' if not os.path.exists(weigths_dir): os.makedirs(weigths_dir) if not os.path.exists(img_dir): os.makedirs(img_dir) if not os.path.exists(log_dir): os.makedirs(log_dir) if not os.path.exists(output_dir): os.makedirs(output_dir) # Load the dataset hrhq_train, hrhq_test, lrhq_train, lrhq_test, hrlq_train, hrlq_test, lrlq_train, lrlq_test = load_confocal( input_shape=input_shape, set=set, z_depth=z_depth) lq2hq = load_model(weigths_dir + '/' + 'generator_l2h.h5', custom_objects={'InstanceNormalization': InstanceNormalization}) hq2lq = load_model(weigths_dir + '/' + 'generator_h2l.h5', custom_objects={'InstanceNormalization': InstanceNormalization}) print('original hrlq') self.compute(hrhq_test, hrlq_test) gen_hrhq = lq2hq.predict(hrlq_test, batch_size=1) print('save_model generate hrhq : ') self.compute(hrhq_test, gen_hrhq) gen_hrlq = hq2lq.predict(hrhq_test, batch_size=1) print('save_model generate hrlq : ') self.compute(hrlq_test, gen_hrlq) reconstr_hrhq = lq2hq.predict(gen_hrlq, batch_size=1) print('save_model reconstr hrhq : ') self.compute(hrhq_test, reconstr_hrhq) dir = './confocal/' + set + '/' + z_depth num = 0 for _, _, files in os.walk(dir): for file in files: num += 1 img = [] img_lq = cv2.imread(dir + '/' + file) img_lq = cv2.resize(img_lq, (input_shape[0] * 4, input_shape[1] * 4)) img.append(img_lq) img = np.array(img) img = img.astype('float32') / 127.5 - 1. img = lq2hq.predict(img, batch_size=1) cv2.imwrite(output_dir + '/' + file, (0.5 * img[0] + 0.5) * 255) def compute(self, set1, set2): PSNR = 0 SSIM = 0 Pearson = 0 for i in range(set1.shape[0]): a = [] b = [] for x in range(set1[i].shape[0]): for y in range(set1[i].shape[1]): for z in range(set1[i].shape[2]): a.append(set1[i, x, y, z]) b.append(set2[i, x, y, z]) Pearson += pearsonr(a, b)[0] PSNR += self.PSNR(0.5 * set1[i] + 0.5, 0.5 * set2[i] + 0.5) SSIM += self.SSIM(0.5 * set1[i] + 0.5, 0.5 * set2[i] + 0.5) print('PSNR : ' + str(PSNR / set1.shape[0])) print('SSIM : ' + str(SSIM / set1.shape[0])) print('Pearson : ' + str(Pearson / set1.shape[0])) def PSNR(self, img1, img2): psnr = 0 for i in range(img1.shape[2]) : psnr += compare_psnr(img1[:,:,i], img2[:,:,i], 1) return psnr / img1.shape[2] def SSIM(self, img1, img2): return compare_ssim(img1, img2, data_range=1, multichannel=True) if __name__ == '__main__': # acgan + mnist dataset os.environ["CUDA_VISIBLE_DEVICES"] = "0" dcgan = StarGAN() save_num = 500 epoch = 25000 set = 'C0depth' z_depth = 'Z005' model = 'deblursrgan4' + '_' + set + '_' + z_depth batch_size = 4 dcgan.test(model=model, epochs=epoch, batch_size=batch_size, sample_interval=int(epoch / save_num), set=set, z_depth=z_depth)
{ "alphanum_fraction": 0.5973440241, "author": null, "avg_line_length": 38.7475728155, "converted": null, "ext": "py", "file": null, "hexsha": "04411afa68e3b80828f28ccf2b2d96df05fca881", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "35a88fad0107cdf2cfb4a786b1a3c8fc009653d8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jiangdat/COMI", "max_forks_repo_path": "test.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "35a88fad0107cdf2cfb4a786b1a3c8fc009653d8", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jiangdat/COMI", "max_issues_repo_path": "test.py", "max_line_length": 131, "max_stars_count": null, "max_stars_repo_head_hexsha": "35a88fad0107cdf2cfb4a786b1a3c8fc009653d8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jiangdat/COMI", "max_stars_repo_path": "test.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4519, "path": null, "reason": "import numpy,from scipy", "repo": null, "save_path": null, "sha": null, "size": 15964 }
import numpy as np import pandas as pd import argparse import os from pandas.tseries.holiday import USFederalHolidayCalendar as calendar def prepare_data(data_path): """Returns dataframe with features.""" # Get data df = pd.read_csv(data_path) # Remove NaNs df = df.dropna() # Convert date to datetime df['date'] = pd.to_datetime(df.date) # Create and age variable df['age'] = df.index.astype('int') # Create a day of week field df['day'] = df.date.dt.dayofweek # Create a month of year field df['month'] = df.date.dt.month # Create a boolean for US federal holidays holidays = calendar().holidays(start=df.date.min(), end=df.date.max()) df['holiday'] = df['date'].isin(holidays).apply(int) # Rearrange columns df = df[ [ 'date', 'count', 'age', 'month', 'day', 'holiday' ] ] # Create monthly dummies tmp = pd.get_dummies(df.month) tmp.columns = ['month' + str(value) for value in tmp.columns] df = pd.concat([df, tmp], axis=1) # Create daily dummies tmp = pd.get_dummies(df.day) tmp.columns = ['day' + str(value) for value in tmp.columns] df = pd.concat([df, tmp], axis=1) # Reset index df = df.reset_index(drop=True) # Log transform count data df['count'] = np.log1p(df['count']) # Drop unnecessary columns df = df.drop(['month', 'day', 'age'], axis=1) df = df.dropna() return df def run(): parser = argparse.ArgumentParser(description='Prepare data') parser.add_argument('--data_path', default='raw/github_dau_2011-2018.csv') parser.add_argument('--output_path', default='processed/github_dau_2011-2018.pkl') args = parser.parse_args() # Get the data df = prepare_data(args.data_path) # Store data path = os.path.dirname(args.output_path) if not os.path.exists(path): os.makedirs(path) df.to_pickle(args.output_path, protocol=4) if __name__ == '__main__': run()
{ "alphanum_fraction": 0.6011342155, "author": null, "avg_line_length": 23.7752808989, "converted": null, "ext": "py", "file": null, "hexsha": "aa496d17ddf182cf664f100e905f38fc7bf29387", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "8f79aaa87b01b19e8d7036724b558d887ba018ce", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "xiaoyongzhu/Deep4Cast", "max_forks_repo_path": "docs/examples/data/process_github.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "8f79aaa87b01b19e8d7036724b558d887ba018ce", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "xiaoyongzhu/Deep4Cast", "max_issues_repo_path": "docs/examples/data/process_github.py", "max_line_length": 74, "max_stars_count": null, "max_stars_repo_head_hexsha": "8f79aaa87b01b19e8d7036724b558d887ba018ce", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "xiaoyongzhu/Deep4Cast", "max_stars_repo_path": "docs/examples/data/process_github.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 533, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 2116 }
Load LFindLoad. Load LFindLoad. From adtind Require Import goal80. From lfind Require Import LFind. Lemma lfind_state (y:lst):@eq lst y (append y Nil). Admitted. From QuickChick Require Import QuickChick. QCInclude "/home/yousef/lemmafinder/benchmark/_lfind_clam_lf_goal80_theorem0_58_append_nil/". QCInclude ".". Extract Constant defNumTests => "50". Derive Show for lst. Derive Arbitrary for lst. Instance Dec_Eq_lst : Dec_Eq lst. Proof. dec_eq. Qed. Open Scope string_scope. Parameter print : lst -> string -> lst. Extract Constant print => "Extract.print". Definition collect_data (y:lst) := let lfind_var := "y:" ++ "(" ++ show y ++ ")" in let lfind_v := print y lfind_var in lfind_state lfind_v . QuickChick collect_data. Success.
{ "alphanum_fraction": null, "author": "yalhessi", "avg_line_length": null, "converted": null, "ext": null, "file": null, "hexsha": null, "include": null, "lang": null, "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": "github-repos/coq/yalhessi-lemmaranker/lemmaranker-53bc2ad63ad7faba0d7fc9af4e1e34216173574a/benchmark/clam/_lfind_clam_lf_goal80_theorem0_58_append_nil/lfind_quickchick_generator.v", "reason": null, "repo": "lemmaranker", "save_path": "github-repos/coq/yalhessi-lemmaranker", "sha": "53bc2ad63ad7faba0d7fc9af4e1e34216173574a", "size": null }
import copy import os import numpy as np import random import shutil import sys from src import trainer from keras import backend as K import tensorflow as tf import argparse from src.Logger import LOG from keras.layers import Input,concatenate,GaussianNoise from keras.models import load_model,Model import shutil os.environ['PYTHONHASHSEED'] = '0' np.random.seed(42) random.seed(12345) session_conf = tf.ConfigProto(intra_op_parallelism_threads=1, inter_op_parallelism_threads=1) tf.set_random_seed(1234) sess = tf.Session(graph=tf.get_default_graph(), config=session_conf) K.set_session(sess) def supervised_train(task_name,sed_model_name,augmentation): """" Training with only weakly-supervised learning Args: task_name: string the name of the task sed_model_name: string the name of the model augmentation: bool whether to add Gaussian noise Layer Return: """ LOG.info('config preparation for %s'%sed_model_name) #prepare for training train_sed=trainer.trainer(task_name,sed_model_name,False) #creat model using the model structure prepared in [train_sed] creat_model_sed=train_sed.model_struct.graph() LEN=train_sed.data_loader.LEN DIM=train_sed.data_loader.DIM inputs=Input((LEN,DIM)) #add Gaussian noise Layer if augmentation: inputs_t=GaussianNoise(0.15)(inputs) else: inputs_t=inputs outs=creat_model_sed(inputs_t,False) #the model used for training models=Model(inputs,outs) LOG.info('------------start training------------') train_sed.train(extra_model=models,train_mode='supervised') #predict results for validation set and test set train_sed.save_at_result() #audio tagging result train_sed.save_sed_result() #event detection result def semi_train(task_name,sed_model_name,at_model_name,augmentation): """" Training with semi-supervised learning (Guiding learning) Args: task_name: string the name of the task sed_model_name: string the name of the the PS-model at_model_name: string the name of the the PT-model augmentation: bool whether to add Gaussian noise to the input of the PT-model Return: """ #prepare for training of the PS-model LOG.info('config preparation for %s'%at_model_name) train_sed=trainer.trainer(task_name,sed_model_name,False) #prepare for training of the PT-model LOG.info('config preparation for %s'%sed_model_name) train_at=trainer.trainer(task_name,at_model_name,False) #connect the outputs of the two models to produce a model for end-to-end learning creat_model_at=train_at.model_struct.graph() creat_model_sed=train_sed.model_struct.graph() LEN=train_sed.data_loader.LEN DIM=train_sed.data_loader.DIM inputs=Input((LEN,DIM)) #add Gaussian noise if augmentation: at_inputs=GaussianNoise(0.15)(inputs) else: at_inputs=inputs at_out=creat_model_at(at_inputs,False) sed_out=creat_model_sed(inputs,False) out=concatenate([at_out,sed_out],axis=-1) models=Model(inputs,out) #start training (all intermediate files are saved in the PS-model dir) LOG.info('------------start training------------') train_sed.train(models) #copy the final model to the PT-model dir from the PS-model dir shutil.copyfile(train_sed.best_model_path,train_at.best_model_path) #predict results for validation set and test set (the PT-model) LOG.info('------------result of %s------------'%at_model_name) train_at.save_at_result() #audio tagging result #predict results for validation set and test set (the PS-model) LOG.info('------------result of %s------------'%sed_model_name) train_sed.save_at_result() #audio tagging result train_sed.save_sed_result() #event detection result def test(task_name, model_name, model_path = None, at_preds={}, sed_preds={}): """" Test with prepared model dir. The format of the model dir must be consistent with the required format. Args: task_name: string the name of the task model_name: string the name of the model model_path: string the path of model weights (if None, set defaults) at_preds: dict sed_preds: dict Return: at_preds: dict {'vali': numpy.array, 'test': numpy.array} audio tagging prediction (possibilities) on both set sed_preds: dict {'vali': numpy.array, 'test': numpy.array} detection prediction (possibilities) on both set """ #prepare for testing train = trainer.trainer(task_name,model_name,True) if not model_path == None: train.best_model_path = model_path #predict results for validation set and test set at_preds_out = train.save_at_result(at_preds) #audio tagging result sed_preds_out = train.save_sed_result(sed_preds) #event detection result return at_preds_out, sed_preds_out def bool_convert(value): """" Convert a string to a boolean type value Args: value: string in ['true','True','false','False'] the string to convert Return: rvalue: bool a bool type value """ if value=='true' or value=='True': rvalue=True elif value=='false' or value=='False': rvalue=False else: assert False return rvalue def test_models(task_name, model_name, model_list_path): """" Test with prepared model dir. The format of the model dir and model weights must be consistent with the required format. Args: task_name: string the name of the task model_name: string the name of the model model_list_path: string the path of file which keeps a list of paths of model weights Return: """ def predict(A): A[A >= 0.5 ] = 1 A[A < 0.5] = 0 return A if model_list_path == None: test(task_name,sed_model_name) else: with open(model_list_path) as f: model_list = f.readlines() model_list = [m.rstrip() for m in model_list] if len(model_list) == 1: LOG.info( 'ensemble results (just a single model)') test(task_name, sed_model_name, model_list[0]) return at_results={} sed_results={} mode = ['vali', 'test'] for model_path in model_list: LOG.info( 'decode for model : {}'.format(model_path)) at_preds, sed_preds = test(task_name, sed_model_name, model_path) for m in mode: if m not in at_results: at_results[m] = predict(at_preds[m]) sed_results[m] = sed_preds[m] else: at_results[m] += predict(at_preds[m]) sed_results[m] += sed_preds[m] for m in mode: at = copy.deepcopy(at_results[m]) #vote for boundary detection mask = np.reshape(at, [at.shape[0],1,at.shape[1]]) mask[mask == 0] = 1 sed_results[m] /= mask #vote for audio tagging at_results[m] = at / len(model_list) sed_results[m] = [at_results[m], sed_results[m]] LOG.info( 'ensemble results') test(task_name, sed_model_name, None, at_results, sed_results) if __name__=='__main__': LOG.info('Disentangled feature') parser = argparse.ArgumentParser(description='') parser.add_argument('-n', '--task_name', dest='task_name', help='task name') parser.add_argument('-s', '--PS_model_name', dest='PS_model_name', help='the name of the PS model') parser.add_argument('-t', '--PT_model_name', dest='PT_model_name', help='the name of the PT model') parser.add_argument('-md', '--mode', dest='mode', help='train or test') parser.add_argument('-g', '--augmentation', dest='augmentation', help='select [true or false] : whether to use augmentation (add Gaussian noise)') parser.add_argument('-u', '--semi_supervised', dest='semi_supervised', help='select [true or false] : whether to use unlabel data') parser.add_argument('-e', '--ensemble', dest='ensemble', help='select [true or false] : whether to ensembel several models when testing') parser.add_argument('-w', '--model_weights_list', dest='model_weights_list', help='the path of file containing a list of path of model weights to ensemble') f_args = parser.parse_args() task_name = f_args.task_name sed_model_name = f_args.PS_model_name at_model_name = f_args.PT_model_name mode = f_args.mode semi_supervised = f_args.semi_supervised augmentation = f_args.augmentation ensemble = f_args.ensemble model_weights_list = f_args.model_weights_list if mode not in ['train','test']: LOG.info('Invalid mode') assert LOG.info('try add --help to get usage') if task_name is None: LOG.info('task_name is required') assert LOG.info('try add --help to get usage') if sed_model_name is None: LOG.info('PS_model_name is required') assert LOG.info('try add --help to get usage') if mode == 'train': augmentation = bool_convert(augmentation) semi_supervised = bool_convert(semi_supervised) if semi_supervised and at_model_name is None: LOG.info('PT_model_name is required for semi-supervised learning') assert LOG.info('try add --help to get usage') assert LOG.info('try add --help to get usage') else: semi_supervised = False ensemble = bool_convert(ensemble) if not ensemble: model_weights_list = None LOG.info( 'task name: {}'.format(task_name)) LOG.info( 'PS-model name: {}'.format(sed_model_name)) if semi_supervised: LOG.info( 'PT-model name: {}'.format(at_model_name)) LOG.info( 'mode: {}'.format(mode)) LOG.info( 'semi_supervised: {}'.format(semi_supervised)) if mode=='train': if semi_supervised: semi_train(task_name, sed_model_name, at_model_name, augmentation) else: supervised_train(task_name, sed_model_name, augmentation) else: test_models(task_name, sed_model_name, model_weights_list)
{ "alphanum_fraction": 0.7296141926, "author": null, "avg_line_length": 30.1838709677, "converted": null, "ext": "py", "file": null, "hexsha": "965fb74dd09ce9e8523ff9cc538c02a3fcb3fdac", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7afeadd1eb9450f89bb159480d5a0ee0296e09dd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jells123/Sound_event_detection", "max_forks_repo_path": "main.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "7afeadd1eb9450f89bb159480d5a0ee0296e09dd", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jells123/Sound_event_detection", "max_issues_repo_path": "main.py", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "7afeadd1eb9450f89bb159480d5a0ee0296e09dd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jells123/Sound_event_detection", "max_stars_repo_path": "main.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2434, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 9357 }
##############written by fbb june 2011##### ########utility to bin and tophat smooth arrays of data. ########june 29 2011 so far it only works with oned array (e.g lighcurves!) ########################################################################## #function: onedsmooth # INPUT: # arr: the imput array numpy array or list, will be converted to # numpy array eitherway # bsz: bin size # bin: 1 for binning the data, 2 for smoothing the data ########################################################################## import numpy as np def onedsmooth(arr,bsz, bin): arr=np.array(arr) bszm1=bsz-1 newarr = arr[:-(bszm1)]+arr[(bszm1):] for i in range(1,bszm1): newarr+=arr[i:-(bszm1-i)] if bin>0: return newarr[::bsz] else: return newarr/float(bsz)
{ "alphanum_fraction": 0.4916267943, "author": null, "avg_line_length": 26.125, "converted": null, "ext": "py", "file": null, "hexsha": "ebb603fa3bcd3c09dae45535cea431892c8c6068", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "1dec967fc6f771060435842b01580bd05fcfcd08", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "fedhere/getlucky", "max_forks_repo_path": "HSPpipe/binandsmooth.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "1dec967fc6f771060435842b01580bd05fcfcd08", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "fedhere/getlucky", "max_issues_repo_path": "HSPpipe/binandsmooth.py", "max_line_length": 75, "max_stars_count": null, "max_stars_repo_head_hexsha": "1dec967fc6f771060435842b01580bd05fcfcd08", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "fedhere/getlucky", "max_stars_repo_path": "HSPpipe/binandsmooth.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 225, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 836 }
''' Brian Harder 5/24/2021 Description: This is a Python module that has 6 functions that I thought would be useful in my own life as a Choate student. There is are 6 math help functions, 2 standardized test simulation functions, a function for stock prices, a fortunte teller game, a function for walking time between Choate buildings, and a randomized visual design creator. In terms of my process, I think the coding was pretty smooth overall. The infinite_limit and Pascal_triangle functions in the mathClass were a little more difficult to execute due to the various possibilites of negative coefficients. However, the other funtions were pretty doable in conjunction with some code that I got from various sources. Also, getting the module onto PyPI for PIP installation was more difficult than I anticipated given that the first method I tried, based on a website I found, did not work. Given that this is the largest project we have done so far, I'd say my time management was pretty good overall. I did fall behind at one point during the process but was able to get back on schedule within a few days. If I were to do this again, I would try to create more cohesion in the project since the functions in the module are not very related to one another beyond the fact that I would find them all useful. Sources: I used several functions from the sympy library in the infiniteLimit function, including converting strings to sympy equations and getting coefficients: https://docs.sympy.org/latest/modules/parsing.html I used this website to figure out how to remove the extra + sign at the end of expanded_string in the Pascal function; the rstrip function was what I found: https://geekflare.com/python-remove-last-character/ I uesd the findOccurences function from this website in the Pascal function: https://stackoverflow.com/questions/13009675/find-all-the-occurrences-of-a-character-in-a-string I used these websites to get the data points for the SAT and ACT linear regression: https://www.albert.io/blog/sat-score-calculator/ https://www.albert.io/blog/act-score-calculator/ I used these functions to stop the yfinance.download function from printing to the console: https://stackoverflow.com/questions/8447185/to-prevent-a-function-from-printing-in-the-batch-console-in-python I used this website to make sure all the colors were different in the visual_design function's last option: https://www.geeksforgeeks.org/check-if-all-array-elements-are-distinct/ OMH ''' import math, sympy, cmath, random from sympy import * import yfinance, stockquotes import matplotlib.pyplot as plt import sys, os import geopy.distance from PIL import Image, ImageDraw #This class organizes all the math related functions. class mathClass: #This function evaluates limits to infinity by using the rules with the highest power in the numerator and denominator. Lists of the exponents and the sympy library are the main methods used here. def infinite_limit(self, numerator, denominator): numerator_powers, denominator_powers = [], [] #every time a "**" is found, the next term is recorded in powers since the double asterisk indicates an exponent for i in range(0, len(numerator)): if numerator[i] == "*" and numerator[i+1] == "*": numerator_powers.append(int(numerator[i+2])) if numerator[i] == "x": if i == len(numerator)-1: numerator_powers.append(1) elif numerator[i+1] != "*": numerator_powers.append(1) for i in range(0, len(denominator)): if denominator[i] == "*" and denominator[i+1] == "*": denominator_powers.append(int(denominator[i+2])) if denominator[i] == "x": if i == len(denominator)-1: denominator_powers.append(1) elif denominator[i+1] != "*": denominator_powers.append(1) highest_numerator, highest_denominator = max(numerator_powers), max(denominator_powers) x = symbols("x") #the coeff function in sympy is used to get the coefficients of the terms with the highest powers ; sympy.parsing.sympy_parser.parse_expr is used to convert the inputted strings to sympy expressions numerator_coefficient, denominator_coefficient = sympy.parsing.sympy_parser.parse_expr(numerator).coeff(x, highest_numerator), sympy.parsing.sympy_parser.parse_expr(denominator).coeff(x, highest_denominator) if highest_numerator < highest_denominator: return 0 elif highest_numerator > highest_denominator: if numerator_coefficient > 0: return math.inf else: return -math.inf else: return numerator_coefficient / denominator_coefficient #This function returns the value of a limit using direct substitution by substituting in the given x value. Try/except is used to deal with situations where direct substitution cannot be used (sqrt(neg), etc) def substitution_limit(self, numerator, denominator, x_val): numerator = numerator.replace("x", x_val) denominator = denominator.replace("x", x_val) try: return eval("(" + numerator + ")" + "/" + "(" + denominator + ")") except: return "Direct substitution cannot be used to evaluate this limit." #This function takes the 3 coefficients of a quadratic equation and uses the quadratic formula to return the solutions. def quadratic_formula(self, a, b, c): discriminant = (b**2) - (4*a*c) try: sqrt_d = math.sqrt(discriminant) except: #cmath is used to allow for complex numbers when the discriminant is negative sqrt_d = cmath.sqrt(discriminant) root_1 = (-b + sqrt_d) / (2*a) root_2 = (-b - sqrt_d) / (2*a) return [root_1, root_2] #This function returns an expression expanded to a given power via binomial theorem and increasing/decreasing exponents. Sympy is used for the math operations. def Pascal_triangle(self, power, expression): def C(n, r): return int(math.factorial(n) / (math.factorial(n-r)*math.factorial(r))) def find_occurrences(s, ch): return [i for i, letter in enumerate(s) if letter == ch] negatives = find_occurrences(expression, "-") neg_x, neg_y = False, False #whether or not the two terms of the binomial are negative is found by checking if there is a negative at index 0 (x) or somewhere else (y) if 0 in negatives: neg_x = True for element in negatives: if element != 0: neg_y = True coefficients = [] #the coefficients are created with binomial theorem, which uses combinations for each coefficient (0C0, 1C0, 1C1, 2C0, 2C1, 2C2, etc) for i in range(0, power+1): coefficients.append(C(power, i)) x_exponents, y_exponents = [], [] #the first term's exponents go from high to low, and the second term's are opposite for i in range(power, -1, -1): x_exponents.append(i) for i in range(0, power+1): y_exponents.append(i) expanded = [] #the expanded strings are x and y raised to the respective powers in order with negatives being included based on the boolean variables for i in range(0, len(coefficients)): if not neg_x and not neg_y: expanded_string = "x**" + str(x_exponents[i]) + " * " + expression[len(expression)-1] + "**" + str(y_exponents[i]) elif neg_x and not neg_y: #the negative coefficients are applied to odd powers if x_exponents[i] % 2 != 0: expanded_string = "-1 * x**" + str(x_exponents[i]) + " * " + expression[len(expression)-1] + "**" + str(y_exponents[i]) else: expanded_string = "x**" + str(x_exponents[i]) + " * " + expression[len(expression)-1] + "**" + str(y_exponents[i]) elif not neg_x and neg_y: if y_exponents[i] % 2 != 0: expanded_string = "x**" + str(x_exponents[i]) + " * -1 * " + expression[len(expression)-1] + "**" + str(y_exponents[i]) else: expanded_string = "x**" + str(x_exponents[i]) + " * " + expression[len(expression)-1] + "**" + str(y_exponents[i]) else: if x_exponents[i] % 2 != 0 and y_exponents[i] % 2 == 0: expanded_string = "-1 * x**" + str(x_exponents[i]) + " * " + expression[len(expression)-1] + "**" + str(y_exponents[i]) elif x_exponents[i] % 2 == 0 and y_exponents[i] % 2 != 0: expanded_string = "x**" + str(x_exponents[i]) + " * -1 * " + expression[len(expression)-1] + "**" + str(y_exponents[i]) elif x_exponents[i] % 2 != 0 and y_exponents[i] % 2 != 0: expanded_string = "-1 * x**" + str(x_exponents[i]) + " * -1 * " + expression[len(expression)-1] + "**" + str(y_exponents[i]) else: expanded_string = "x**" + str(x_exponents[i]) + " * " + expression[len(expression)-1] + "**" + str(y_exponents[i]) expanded.append(expanded_string) #the expanded strings are then multiplied by the coefficients that were found with Pascal's triangle for i in range(0, len(expanded)): sympy_expanded = sympy.parsing.sympy_parser.parse_expr(expanded[i]) element = expand(sympy_expanded * coefficients[i]) expanded[i] = element expanded_string = "" for element in expanded: expanded_string += str(element) expanded_string += " + " for i in range(-3, 0): expanded_string = expanded_string.rstrip(expanded_string[i]) return expanded_string #This function returns the nth term of an arithmetic or geometric series, denoted by the arithmetic boolean variable, using the t of n formulas. def sequences(self, t1, r, n, arithmetic): if arithmetic: return t1 + (r*(n-1)) else: return t1 * (r**(n-1)) ''' This function returns the sum of the first n terms of an arithmetic or geometric series, once again using the boolean arithmetic, with the s of n formulas. This function has another boolean infinite; when True, the function will return the infinite sum of a geometric series, using the formula t1 / 1-r. ''' def series(self, t1, tn, r, n, arithmetic, infinite): if arithmetic: return (n*(t1 + tn)) / 2 elif not arithmetic and not infinite: return (t1*(1-r**n)) / (1-r) elif not arithmetic and infinite: return t1 / (1-r) else: return "Only geometric sequences can be infinite." #This class organizes the SAT and ACT score simulation functions. class standardizedTestClass: #The SAT function returns the average score one would get, based on 10,000 trials, if they guessed every question on the SAT. The user can choose to input the same answer every time or have it be randomized. def SAT(self, same_answer, answer): trials, score = 10000, 0 def SAT_trial(): key, answers, count = [], [], 0 for i in range(154): key.append(random.randint(1, 4)) if same_answer: for i in range(154): answers.append(answer) else: for i in range(154): answers.append(random.randint(1, 4)) for i in range(154): if key[i] == answers[i]: count += 1 return count for i in range(trials): score += SAT_trial() average_raw = score / trials ''' I looked at a website that calculates SAT scaled scores based on raw scores, used that to get a bunch of data points, and used linear regression to get an equation for scaled score based on raw score. The r value was 0.994745175, so I think the regression model fit the SAT score data pretty well. ''' score_calculation = 417.835052 + (average_raw*7.68870819) if average_raw == 0: return 400 elif average_raw == 154: return 1600 else: return int(score_calculation) #This function serves the same purpose as the SAT function but for the ACT. An addition had to be made to account for the ACT math section having 5 answer choices. def ACT(self, same_answer, math_answer, other_answer): trials, score = 10000, 0 def ACT_trial(): #the correct and given answers are put in lists just like in the SAT function based on the same_answer boolean, but the math section is done separately to account for A-E answer choices, not A-D math_key, math_answers, count = [], [], 0 for i in range(60): math_key.append(random.randint(1, 5)) if same_answer: for i in range(60): math_answers.append(math_answer) else: for i in range(60): math_answers.append(random.randint(1, 5)) for i in range(60): if math_key[i] == math_answers[i]: count += 1 key, answers = [], [] for i in range(155): key.append(random.randint(1, 4)) if same_answer: for i in range(155): answers.append(other_answer) else: for i in range(155): answers.append(random.randint(1, 4)) for i in range(155): if key[i] == answers[i]: count += 1 return count for i in range(trials): score += ACT_trial() average_raw = score / trials #I did linear regression again for this ACT function. The r value was 0.9998002744, so once again I had a pretty good model. score_calculation = 0.195352576 + (average_raw*0.1653997383) if average_raw == 0: return 1 elif average_raw == 215: return 36 else: return int(score_calculation) #The stocks function displays a graph of the stocks's price over a given interval and returns the current share price. def stocks(ticker, start, end): stock = stockquotes.Stock(ticker) #If the user chooses to print the output of this function - share price -, a confirmation message for the yfinance.download function is also printed to the console. #To prevent this, I blocked printing for when the yfinance function is called. old_stdout = sys.stdout sys.stdout = open(os.devnull, "w") chart_data = yfinance.download(ticker, start, end) sys.stdout = old_stdout plt.plot(chart_data["Close"]) plt.show() return stock.current_price #This function is a fortunte teller game that I thought might be fun to play now and then, like the foldable paper ones. Lists are used instead of lots of nested if statements, which was my main goal here. def fortune_teller(): question1 = ["red", "blue"] #each question is a list of all the possible answer choices based on the previous response question2 = [ ["A", "B"], ["C", "D"], ] question3 = [ [ ["green", "purple"], ["magenta", "yellow"], ], [ ["grey", "black"], ["indigo", "maroon"], ], ] question4 = [ [ [ ["1", "2"], ["3", "4"], ], [ ["5", "6"], ["7", "8"], ], ], [ [ ["9", "10"], ["11", "12"], ], [ ["13", "14"], ["15", "16"], ], ], ] answers = [ "Each day, compel yourself to do something you would rather not do.", "Every wise man started out by asking many questions.", "From now on your kindness will lead you to success.", "Get your mind set – confidence will lead you on.", "If you think you can do a thing or think you can’t do a thing, you’re right.", "Every flower blooms in its own sweet time.", "The greatest achievement in life is to stand up again after falling.", "The only people who never fail are those who never try.", "There is no wisdom greater than kindness.", "A smile is your personal welcome mat.", "Accept something that you cannot change, and you will feel better.", "Miles are covered one step at a time.", "Put your mind into planning today. Look into the future.", "The sure way to predict the future is to invent it.", "If you want the rainbow, you have to tolerate the rain." "The fortune you seek is in another index." ] def question(options): while True: try: response = int(input("Pick 1) " + options[0] + " or 2) " + options[1] + ": ")) - 1 if response < len(options): return response except: pass #the questions are gone through one at a time with the previous responses as inputs first = question(question1) second = question(question2[first]) third = question(question3[first][second]) fourth = question(question4[first][second][third]) print(answers[int(question4[first][second][third][fourth]) - 1]) #This function will return how long it takes to walk from one building to another on the Choate campus using the distance between 2 points defined by latitude and longitude. def walking_time(building1, building2, seconds): choate_buildings = { "Memorial House" : (41.459799130887546, -72.81253950970536), "Hill House" : (41.45813565561544, -72.81336797843655), "Squire Stanley" : (41.45995268009463, -72.81315530337368), "Sally Hart Lodge" : (41.45775075458777, -72.81223178769596), "Chapel" : (41.456854743438235, -72.81316049021501), "WJAC" : (41.45465878917236, -72.80958048559658), "Colony Hall" : (41.45777834343251, -72.80732027781659), "PMAC" : (41.45790261089875, -72.80811321340957), "Steele Hall" : (41.45888279615266, -72.81400813253074), "Lanphier Center" : (41.45918845037742, -72.80975433000114), "Carl Icahn Science Center" : (41.459491535335864, -72.80853419325018), "Humanities Building" : (41.459386516160265, -72.81310335516075), "Andrew Mellon Library" : (41.45853003456271, -72.81341308415308), "St. John Hall" : (41.457511329055556, -72.81349263538527), "Tenney/Bernhard" : (41.45603055473527, -72.81274745557317), "Archbold" : (41.45871173929997, -72.80978442310364), "CK/McCook" : (41.458404856495854, -72.81037853238148), "Pratt Health Center" : (41.45833282443969, -72.81515393077808), "Pierce" : (41.45993804491732, -72.81093804141835), "Woodhouse/Combination" : (41.45725788267579, -72.81401686529755), "Logan Munroe" : (41.460507817639375, -72.81173217823357), "Hunt Tennis Center" : (41.46113232348608, -72.8120426847346), "Atwater/Mead" : (41.4588347173473, -72.81168353576032), "Spencer" : (41.456616116479665, -72.81182642820936), } coordinates_1, coordinates_2 = choate_buildings[building1], choate_buildings[building2] #the geopy library will return the distance between two lat/long coordinates distance = geopy.distance.distance(coordinates_1, coordinates_2).mi #I figured 3.5 mi/hr is a pretty reasonable average walking pace time = (distance / 3.5) * 60 #the user can choose to have a 2 digit decimal or a formatted string returned for the time in minutes and seconds if seconds: time_tuple = math.modf(time) seconds, minutes = time_tuple[0], int(time_tuple[1]) seconds = int(seconds*60) return str(minutes) + " minutes and " + str(seconds) + " seconds" else: return round(time, 2) #This function creates an appealing visual design based on a couple parameters and some randomness; there are 3 different options for the type of image created. def visual_design(vertices, layers, colors, option): img, img2 = Image.new("RGB", (1000, 1000), (255, 255, 255)), Image.new("RGB", (1000, 1000), (255, 255, 255)) image, image2 = ImageDraw.Draw(img), ImageDraw.Draw(img2) #option #1 uses the number of vertices to create regular polygons that spiral outwards with the rotation parameter if option == 1: color = random.choice(colors) for i in range(450): if i % layers == 0: color = random.choice(colors) image.regular_polygon((500, 500, 50+i), vertices, rotation = i*4, fill = color, outline = "black") #option #2 creates a bunch of circles in random positions and of random colors throughout the canvas elif option == 2: for i in range(layers): x, y, radius = random.randint(0, 1000), random.randint(0, 1000), 75 image.ellipse([x, y, x+radius, y+radius], fill = random.choice(colors), outline = "black") #option 3 uses rows and columsn of rectangles that slowly change in length from top to bottom and left to right to create 4 colored zones that are joined in an interesting way else: def distinct(arr) : n = len(arr) s = set() for i in range(0, n): s.add(arr[i]) return (len(s) == len(arr)) global color_list color_list = [] for i in range(4): color_list.append(random.choice(colors)) while not distinct(color_list): color_list.clear() for i in range(4): color_list.append(random.choice(colors)) def create_image(picture, iteration): dist = 1000/layers x_values, y_values = [], [] for i in range(0, int(1001-dist), int(dist)): x_values.append(i) for i in range(0, int(1001-dist), int(dist)): y_values.append(i/2) for i in range(0, len(y_values)): y_values[i] += random.randint(y_values[i]-1, y_values[i]+dist-1) for i in range(0, len(x_values)): if i == len(x_values) - 1: if iteration == 1: picture.rectangle([x_values[i], 1000, x_values[i] + dist, 0], fill = color_list[0]) else: picture.rectangle([x_values[i], 1000, x_values[i] + dist, 0], fill = color_list[2]) else: if iteration == 1: picture.rectangle([x_values[i], 1000, x_values[i] + dist, 1000-y_values[i]], fill = color_list[0]) picture.rectangle([x_values[i], 0, x_values[i] + dist, 1000-y_values[i]], fill = color_list[1]) else: picture.rectangle([x_values[i], 1000, x_values[i] + dist, 1000-y_values[i]], fill = color_list[2]) picture.rectangle([x_values[i], 0, x_values[i] + dist, 1000-y_values[i]], fill = color_list[3]) create_image(image, 1) create_image(image2, 2) #the horizontal rectangles are less bright img2 = img2.rotate(90) img2.putalpha(100) img.paste(img2, (0, 0), img2) img.show() #The two sets of functions that are organized into classes are defined here, and these are what the user would import to use either the math or SAT/ACT functions. Math = mathClass() standardizedTest = standardizedTestClass() ''' Peer Feedback: Enzo, 5/13 - Try putting in a bunch of data points with the SAT and ACT websites and using regression to come up with an equation instead of having 2 super long dictionaries. '''
{ "alphanum_fraction": 0.6703527937, "author": null, "avg_line_length": 29.6626826029, "converted": null, "ext": "py", "file": null, "hexsha": "df552a8729dc2b60fd2ddfe3a1330aa64ced547a", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "d0787e0f256688683fd12727e75031d953efa1e7", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "brianHarder/choateStudentHelp", "max_forks_repo_path": "ChoateStudentHelp/ChoateStudentHelp_module.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "d0787e0f256688683fd12727e75031d953efa1e7", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "brianHarder/choateStudentHelp", "max_issues_repo_path": "ChoateStudentHelp/ChoateStudentHelp_module.py", "max_line_length": 210, "max_stars_count": null, "max_stars_repo_head_hexsha": "d0787e0f256688683fd12727e75031d953efa1e7", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "brianHarder/choateStudentHelp", "max_stars_repo_path": "ChoateStudentHelp/ChoateStudentHelp_module.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 6000, "path": null, "reason": "from sympy", "repo": null, "save_path": null, "sha": null, "size": 22336 }
import matplotlib.pyplot as plt from matplotlib import colors, gridspec import matplotlib.ticker as mtick from oas_erf.util.naming_conventions.var_info import get_fancy_var_name, get_fancy_unit_xr from oas_erf.util.plot.plot_levlat import plot_levlat_diff, get_cbar_label, plot_levlat_abs, frelative, fdifference, \ get_vmin_vmax from useful_scit.plot.fig_manip import subp_insert_abc import numpy as np # noinspection DuplicatedCode def abs_diffs(di_dic, ctrl, cases_oth, varl, subfig_size=2.9, asp_ratio=.9, norm_dic=None, switch_diff=False, ylim=None, yticks=None ): if yticks is None: yticks = [900, 700, 500, 300] if ylim is None: ylim=[1e3,200] if norm_dic is None: print('must set norm_dic') return fig, axs = plt.subplots(4, len(varl), gridspec_kw={'height_ratios': [4, 3, 3, .3]}, figsize=[subfig_size * len(varl), subfig_size * 3 * asp_ratio]) axs_diff = axs[1:-1, :] axs_diff_cb = axs[-1, :] axs_plts = axs[0:-1, :] #axs_plts = np.delete(axs, 1, 0) # ctrl = 'OsloAeroSec' # cases_oth = ['OsloAero$_{imp}$','OsloAero$_{def}$'] for i, var in enumerate(varl): saxs = axs_diff[:, i] # noinspection DuplicatedCode for case_oth, ax in zip(cases_oth, saxs.flatten()): if switch_diff: from_c = case_oth to_c=ctrl else: from_c = ctrl to_c=case_oth _, im = plot_levlat_diff(var, from_c, to_c, di_dic, cbar_orientation='horizontal', # title=None, ax=ax, ylim=ylim, # figsize=None, cmap='RdBu_r', # use_ds_units=True, # add_colorbar=True, norm=norm_dic[var], add_colorbar=False ) # ax.set_title(f'{key}: PIaerPD-PI') lab = f'$\Delta${get_cbar_label(di_dic[ctrl][var], var, diff=True)}' # noinspection PyUnboundLocalVariable plt.colorbar(im, cax=axs_diff_cb[i], label=lab, orientation='horizontal', extend='both' ) for i, var in enumerate(varl): ax = axs[0, i] _, im = plot_levlat_abs(var, ctrl, di_dic, cbar_orientation='horizontal', # title=None, ax=ax, ylim=ylim, # figsize=None, cmap='PuOr_r', # use_ds_units=True, # add_colorbar=True, norm=norm_dic[var], add_colorbar=False ) # ax.set_title(f'{key}: PIaerPD-PI') lab = get_cbar_label(di_dic[ctrl][var], var, diff=True) plt.colorbar(im, ax=ax, label=lab, orientation='horizontal', extend='both' ) for i in range(len(axs_plts[:, 0])): for j in range(len(axs_plts[0, :])): ax = axs_plts[i, j] ax.set_yticks([],minor=True) ax.set_yticks(yticks,minor=False) if i < (len(axs_plts[:, 0]) - 1): ax.set_xlabel('') plt.setp(ax.get_xticklabels(), visible=False) if i == (len(axs_plts[:, 0]) - 1): ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.0f$^\circ$N')) ax.xaxis.set_minor_formatter(mtick.FormatStrFormatter('%.0f$^\circ$N')) ax.set_xlabel('Latitude [$^\circ$N]') if j==0: ax.set_yticklabels(yticks, minor=False) else: ax.yaxis.set_major_formatter(mtick.NullFormatter())#('%.0f')) #if j > 0: # plt.setp(ax.get_yticklabels(), visible=False) ax.set_ylabel('') for ax in axs[0, :]: ax.set_xlabel('') plt.setp(ax.get_xticklabels(), visible=False) for ax in axs[0, 1:]: ax.set_ylabel('') plt.setp(ax.get_yticklabels(), visible=False) subp_insert_abc(axs_plts, pos_x=-.05,pos_y=1.04 ) fig.tight_layout() return axs, fig def abs_diffs_PI_PD_sep(dic_type_mod, var, case_types=None, ctrl=None, cases_oth=None, sfg_size=2.9, asp_rat=.9, ylim=[1e3,200], relative=False, norm_abs=None, norm_diff=None, type_nndic=None, height_ratios=None, switch_diff=False, add_abc=True, yticks=None ): if yticks is None: yticks = [900, 700, 500, 300] if type_nndic is None: type_nndic={'PI':'Pre-industrial','PIaerPD':'Present day'} if case_types is None: case_types = ['PI', 'PD'] #for c in case_types: # if c not in sup_titles_dic.keys(): # sup_titles_dic[c]=c if norm_abs is None: norm_abs = None if cases_oth is None: cases_oth = ['OsloAero$_{imp}$', 'OsloAero$_{def}$'] if ctrl is None: ctrl = 'OsloAeroSec' if norm_diff is None: # noinspection DuplicatedCode plt_not_ctrl = [] if relative: func = frelative print('relative!!') else: func = fdifference for ct in case_types: _di = dic_type_mod[ct] if switch_diff: plt_not_ctrl = plt_not_ctrl + [func(_di[ctrl][var], _di[cs_o][var]) for cs_o in cases_oth] else: plt_not_ctrl = plt_not_ctrl + [func(_di[cs_o][var], _di[ctrl][var]) for cs_o in cases_oth] vmax, vmin = get_vmin_vmax(plt_not_ctrl) norm_diff = colors.Normalize(vmin=vmin, vmax=vmax) #height_ratios = [.3, 3, .3, 2, 3, .1, 3,.4, .3] # plt.rcParams['figure.constrained_layout.use'] = False if height_ratios is None: height_ratios = [.3, 3, .3, 1.]+[.6, 3]*len(cases_oth)+ [.4,.3] fg = plt.figure(figsize=[sfg_size * len(case_types), sfg_size * (len(cases_oth)+1) * asp_rat]) nrows = len(height_ratios) ncols = len(case_types) gs = gridspec.GridSpec(nrows=nrows, ncols=ncols, height_ratios=height_ratios, hspace=0.2, ) # width_ratios=width_ratios) axs_dict = {} for i, ct in enumerate(case_types): # gs_s = gs[:,i] axs_dict[ct] = {} axs_dict[ct][ctrl] = fg.add_subplot(gs[1, i], ) for j, ca in enumerate(cases_oth): axs_dict[ct][ca] = fg.add_subplot(gs[5 + j * 2, i], ) # axs_dic[var][cases_oth[1]] =fig.add_subplot(gs[5,i], projection=ccrs.Robinson()) axs_dict[ct]['cbar'] = fg.add_subplot(gs[-1, i]) axs_dict[ct]['cbar_abs'] = fg.add_subplot(gs[2, i]) axs_dict[ct]['type_tit'] = fg.add_subplot(gs[0, i]) for i, ct in enumerate(case_types): saxs = axs_dict[ct] for case_oth in cases_oth: ax = saxs[case_oth] if switch_diff: from_c = case_oth to_c = ctrl else: from_c = ctrl to_c=case_oth ax, im = plot_levlat_diff(var, from_c, to_c, dic_type_mod[ct], cbar_orientation='horizontal', # title=None, relative=relative, ylim=ylim, ax=ax, # ylim=None, # figsize=None, cmap='RdBu_r', # use_ds_units=True, # add_colorbar=True, norm=norm_diff, add_colorbar=False, yscale='log', #type_nndic=None ) ax.set_title(f'{to_c}-{from_c}') # cbar: # noinspection DuplicatedCode la = get_fancy_var_name(var) + ' [%s]' % get_fancy_unit_xr(dic_type_mod[ct][ctrl][var], var) if relative: la = get_fancy_var_name(var) + ' [%]' la = f'rel.$\Delta${la}' else: la = f'$\Delta${la}' # noinspection PyUnboundLocalVariable plt.colorbar(im, cax=axs_dict[ct]['cbar'], label=la, orientation='horizontal', extend='both' ) # axs_dict[ct]['cbar'].set_title(f'{ct}$\Updownarrow$') axs_dict[ct]['type_tit'].axis('off') if type_nndic is not None: if ct in type_nndic: ctnn = type_nndic[ct] else: ctnn = ct else: ctnn = ct ax = axs_dict[ct]['type_tit'] # noinspection PyUnboundLocalVariable ax.set_title(ctnn, fontsize=14) # axs_dict[ct]['type_tit'].set_xlabel(f'{ct} $\\Updownarrow$') for i, ct in enumerate(case_types): ax = axs_dict[ct][ctrl] # plt_map(di_dic[ctrl][var], ax=ax, ax, im = plot_levlat_abs(var, ctrl, dic_type_mod[ct], cbar_orientation='horizontal', # title=None, ax=ax, # ylim=None, # figsize=None, cmap='Reds', ylim=ylim, # use_ds_units=True, # add_colorbar=True, norm=norm_abs, add_colorbar=False, yscale='log' ) # cbar: _la = get_fancy_var_name(var) + ' [%s]' % get_fancy_unit_xr(dic_type_mod[ct][ctrl][var], var) la = f'{_la}' plt.colorbar(im, cax=axs_dict[ct]['cbar_abs'], label=la, orientation='horizontal', extend='both') saxs = axs_dict[ct] #for ax in saxs[1:]: # ax.set_yticklabels([]) for ct in case_types: saxs = axs_dict[ct] for case in cases_oth+ [ctrl]: ax = saxs[case] #ax.tick_params(labelbottom=False) ax.set_yticks([],minor=True) ax.set_yticks(yticks,minor=False) if ct !=case_types[0]: ax.yaxis.set_major_formatter(mtick.NullFormatter())#('%.0f')) ax.yaxis.set_minor_formatter(mtick.NullFormatter())#('%.0f')) ax.set_ylabel('') else: ax.set_yticklabels(yticks, minor=False) #ax.set_yticklabels([1000,500,200],minor=False) if case !=cases_oth[-1]: ax.set_xlabel('') #ax.set_yticklabels([]) ax.tick_params(labelbottom=False) else: ax.set_xlabel('')#Latitude [$^\circ$N]') ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.0f$^\circ$N')) ax.xaxis.set_minor_formatter(mtick.FormatStrFormatter('%.0f$^\circ$N')) ax = axs_dict[ct][ctrl] if ct !=case_types[0]: ax.yaxis.set_major_formatter(mtick.NullFormatter())#('%.0f')) ax.yaxis.set_minor_formatter(mtick.NullFormatter())#('%.0f')) ax.set_ylabel('') #if case !=cases_oth[-1]: # ax.set_yticklabels([]) ax.set_xlabel('') ax.set_xticklabels([]) md_ls = [ctrl] + cases_oth axs_abc = [] for ct in case_types: _axs = [axs_dict[ct][m] for m in md_ls] axs_abc = axs_abc + _axs if add_abc: subp_insert_abc(np.array(axs_abc), pos_x=-0.12,pos_y=.95) return fg, axs_dict
{ "alphanum_fraction": 0.4551902982, "author": null, "avg_line_length": 37.2471590909, "converted": null, "ext": "py", "file": null, "hexsha": "fd7730b206db218047ba159bba774fa6460e80d6", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7510c21a630748eda2961608166227ad77935a67", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sarambl/OAS-ERF", "max_forks_repo_path": "oas_erf/util/plot/levlat_PIPD.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "7510c21a630748eda2961608166227ad77935a67", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sarambl/OAS-ERF", "max_issues_repo_path": "oas_erf/util/plot/levlat_PIPD.py", "max_line_length": 118, "max_stars_count": null, "max_stars_repo_head_hexsha": "7510c21a630748eda2961608166227ad77935a67", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sarambl/OAS-ERF", "max_stars_repo_path": "oas_erf/util/plot/levlat_PIPD.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3032, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 13111 }
import os import logging import json import genutil import cdat_info import cdutil import MV2 import cdms2 import hashlib import numpy from collections import OrderedDict, Mapping import pcmdi_metrics import cdp.cdp_io from pcmdi_metrics import LOG_LEVEL import copy import re value = 0 cdms2.setNetcdfShuffleFlag(value) # where value is either 0 or 1 cdms2.setNetcdfDeflateFlag(value) # where value is either 0 or 1 # where value is a integer between 0 and 9 included cdms2.setNetcdfDeflateLevelFlag(value) logging.getLogger("pcmdi_metrics").setLevel(LOG_LEVEL) try: basestring # noqa except Exception: basestring = str # Convert cdms MVs to json def MV2Json(data, dic={}, struct=None): if struct is None: struct = [] if not isinstance(data, cdms2.tvariable.TransientVariable) and dic != {}: raise RuntimeError("MV2Json needs a cdms2 transient variable as input") if not isinstance(data, cdms2.tvariable.TransientVariable): return data, struct # we reach the end else: axis = data.getAxis(0) if axis.id not in struct: struct.append(axis.id) for i, name in enumerate(axis): dic[name], _ = MV2Json(data[i], {}, struct) return dic, struct # Group merged axes def groupAxes(axes, ids=None, separator="_"): if ids is None: ids = [ax.id for ax in axes] if len(ids) != len(axes): raise RuntimeError("You need to pass as many ids as axes") final = [] while len(axes) > 0: axis = axes.pop(-1) if final == []: final = [str(v) for v in axis] else: tmp = final final = [] for v1 in axis: for v2 in tmp: final += ["{}{}{}".format(v1, separator, v2)] return cdms2.createAxis(final, id=separator.join(ids)) # cdutil region object need a serializer def update_dict(d, u): for k, v in u.items(): if isinstance(v, Mapping): r = update_dict(d.get(k, {}), v) d[k] = r else: d[k] = u[k] return d def generateProvenance(): extra_pairs = { 'matplotlib': 'matplotlib ', 'scipy': 'scipy' } prov = cdat_info.generateProvenance(extra_pairs=extra_pairs) prov["packages"]["PMP"] = pcmdi_metrics.version.__git_tag_describe__ prov["packages"]["PMPObs"] = "See 'References' key below, for detailed obs provenance information." return prov def sort_human(input_list): lst = copy.copy(input_list) def convert(text): return int(text) if text.isdigit() else text def alphanum(key): return [convert(c) for c in re.split('([0-9]+)', key)] lst.sort(key=alphanum) return lst def scrap(data, axis=0): originalOrder = data.getOrder(ids=True) if axis not in ['x', 'y', 'z', 't'] and not isinstance(axis, int): order = "({})...".format(axis) else: order = "{}...".format(axis) new = data(order=order) axes = new.getAxisList() # Save for later new = MV2.array(new.asma()) # lose dims for i in range(new.shape[0] - 1, -1, -1): tmp = new[i] if not isinstance(tmp, (float, numpy.float)) and tmp.mask.all(): a = new[:i] b = new[i + 1:] if b.shape[0] == 0: new = a else: new = MV2.concatenate((a, b)) newAxis = [] for v in new.getAxis(0): newAxis.append(axes[0][int(v)]) ax = cdms2.createAxis(newAxis, id=axes[0].id) axes[0] = ax new.setAxisList(axes) return new(order=originalOrder) class CDMSDomainsEncoder(json.JSONEncoder): def default(self, o): components = o.components()[0].kargs args = ','.join( ['%s=%s' % (key, val) for key, val in components.items()] ) return {o.id: 'cdutil.region.domain(%s)' % args} class Base(cdp.cdp_io.CDPIO, genutil.StringConstructor): def __init__(self, root, file_template, file_mask_template=None): genutil.StringConstructor.__init__(self, root + '/' + file_template) self.target_grid = None self.mask = None self.target_mask = None self.regrid_tool = 'esmf' self.file_mask_template = file_mask_template self.root = root self.type = '' self.setup_cdms2() def __call__(self): path = os.path.abspath(genutil.StringConstructor.__call__(self)) if self.type in path: return path else: return path + '.' + self.type def read(self): pass def write(self, data, type='json', mode="w", *args, **kwargs): self.type = type.lower() file_name = self() dir_path = os.path.split(file_name)[0] if not os.path.exists(dir_path): try: os.makedirs(dir_path) except Exception: logging.getLogger("pcmdi_metrics").error( 'Could not create output directory: %s' % dir_path) if self.type == 'json': json_version = float( kwargs.get( "json_version", data.get( "json_version", 3.0))) json_structure = kwargs.get( "json_structure", data.get( "json_structure", None)) if json_version >= 3.0 and json_structure is None: raise Exception( "json_version 3.0 of PMP requires json_structure to be passed" + "to the write function or part of the dictionary dumped") for k in ["json_structure", "json_version"]: if k in kwargs: del(kwargs[k]) data["json_version"] = json_version data["json_structure"] = json_structure if mode == "r+" and os.path.exists(file_name): f = open(file_name) out_dict = json.load(f) else: out_dict = OrderedDict({"provenance": generateProvenance()}) f = open(file_name, "w") update_dict(out_dict, data) if "yaml" in out_dict["provenance"]["conda"]: out_dict["YAML"] = out_dict["provenance"]["conda"]["yaml"] del(out_dict["provenance"]["conda"]["yaml"]) # out_dict = OrderedDict({"provenance": generateProvenance()}) json.dump(out_dict, f, cls=CDMSDomainsEncoder, *args, **kwargs) f.close() elif self.type in ['asc', 'ascii', 'txt']: f = open(file_name, 'w') for key in list(data.keys()): f.write('%s %s\n' % (key, data[key])) f.close() elif self.type == 'nc': f = cdms2.open(file_name, 'w') f.write(data, *args, **kwargs) f.metrics_git_sha1 = pcmdi_metrics.__git_sha1__ f.uvcdat_version = cdat_info.get_version() f.close() else: logging.getLogger("pcmdi_metrics").error('Unknown type: %s' % type) raise RuntimeError('Unknown type: %s' % type) logging.getLogger("pcmdi_metrics").info( 'Results saved to a %s file: %s' % (type, file_name)) def write_cmec(self, *args, **kwargs): """Converts json file to cmec compliant format.""" file_name = self() # load json file try: f = open(file_name, "r") data = json.load(f) f.close() except Exception: logging.getLogger("pcmdi_metrics").error( 'Could not load metrics file: %s' % file_name) # create dimensions cmec_data = {"DIMENSIONS": {}, "SCHEMA": {}} cmec_data["DIMENSIONS"] = {"dimensions": {}, "json_structure": []} cmec_data["SCHEMA"] = {"name": "CMEC", "package": "PMP", "version": "v1"} # copy other fields except results for key in data: if key not in ["json_structure", "RESULTS"]: cmec_data[key] = data[key] # move json structure cmec_data["DIMENSIONS"]["json_structure"] = data["json_structure"] # recursively process json def recursive_replace(json_dict, extra_fields): new_dict = json_dict.copy() # replace blank keys with unspecified if "" in new_dict: new_dict["Unspecified"] = new_dict.pop("") for key in new_dict: if key != "attributes": if isinstance(new_dict[key], dict): # move extra fields into attributes key atts = {} for field in extra_fields: if field in new_dict[key]: atts[field] = new_dict[key].pop(field, None) if atts: new_dict[key]["attributes"] = atts # process sub-dictionary tmp_dict = recursive_replace(new_dict[key], extra_fields) new_dict[key] = tmp_dict # convert string metrics to float if (isinstance(new_dict[key], str)): new_dict[key] = float(new_dict[key]) return new_dict extra_fields = [ "source", "metadata", "units", "SimulationDescription", "InputClimatologyFileName", "InputClimatologyMD5", "InputRegionFileName", "InputRegionMD5", "best_matching_model_eofs__cor", "best_matching_model_eofs__rms", "best_matching_model_eofs__tcor_cbf_vs_eof_pc", "period", "target_model_eofs", "analysis_time_window_end_year", "analysis_time_window_start_year"] # clean up formatting in RESULTS section cmec_data["RESULTS"] = recursive_replace(data["RESULTS"], extra_fields) # Populate dimensions fields def get_dimensions(json_dict, json_structure): keylist = {} level = 0 while level < len(json_structure): if isinstance(json_dict, dict): first_key = list(json_dict.items())[0][0] # skip over attributes key when building dimensions if first_key == "attributes": first_key = list(json_dict.items())[1][0] dim = json_structure[level] keys = {key: {} for key in json_dict if key != "attributes"} keylist[dim] = keys json_dict = json_dict[first_key] level += 1 return keylist dimensions = get_dimensions(cmec_data["RESULTS"].copy(), data["json_structure"]) cmec_data["DIMENSIONS"]["dimensions"] = dimensions cmec_file_name = file_name.replace(".json", "_cmec.json") f_cmec = open(cmec_file_name, "w") json.dump(cmec_data, f_cmec, cls=CDMSDomainsEncoder, *args, **kwargs) f_cmec.close() logging.getLogger("pcmdi_metrics").info( 'CMEC results saved to a %s file: %s' % ('json', cmec_file_name)) def get(self, var, var_in_file=None, region={}, *args, **kwargs): self.variable = var self.var_from_file = self.extract_var_from_file( var, var_in_file, *args, **kwargs) self.region = region if self.region is None: self.region = {} self.value = self.region.get('value', None) if self.is_masking(): self.var_from_file = self.mask_var(self.var_from_file) self.var_from_file = \ self.set_target_grid_and_mask_in_var(self.var_from_file) self.var_from_file = \ self.set_domain_in_var(self.var_from_file, self.region) return self.var_from_file def extract_var_from_file(self, var, var_in_file, *args, **kwargs): if var_in_file is None: var_in_file = var # self.extension = 'nc' var_file = cdms2.open(self(), 'r') for att in ["var_in_file,", "varInFile"]: if att in kwargs: del(kwargs[att]) extracted_var = var_file(var_in_file, *args, **kwargs) var_file.close() return extracted_var def is_masking(self): if self.value is not None: return True else: return False def mask_var(self, var): if self.mask is None: self.set_file_mask_template() self.mask = self.get_mask_from_var(var) if self.mask.shape != var.shape: dummy, mask = genutil.grower(var, self.mask) else: mask = self.target_mask mask = MV2.not_equal(mask, self.value) return MV2.masked_where(mask, var) def set_target_grid_and_mask_in_var(self, var): if self.target_grid is not None: var = var.regrid(self.target_grid, regridTool=self.regrid_tool, regridMethod=self.regrid_method, coordSys='deg', diag={}, periodicity=1 ) if self.target_mask is not None: if self.target_mask.shape != var.shape: dummy, mask = genutil.grower(var, self.target_mask) else: mask = self.target_mask var = MV2.masked_where(mask, var) return var def set_domain_in_var(self, var, region): domain = region.get('domain', None) if domain is not None: if isinstance(domain, dict): var = var(**domain) elif isinstance(domain, (list, tuple)): var = var(*domain) elif isinstance(domain, cdms2.selectors.Selector): domain.id = region.get("id", "region") var = var(*[domain]) return var def set_file_mask_template(self): if isinstance(self.file_mask_template, basestring): self.file_mask_template = Base(self.root, self.file_mask_template, {'domain': self.region.get('domain', None)}) def get_mask_from_var(self, var): try: o_mask = self.file_mask_template.get('sftlf') except Exception: o_mask = cdutil.generateLandSeaMask( var, regridTool=self.regrid_tool).filled(1.) * 100. o_mask = MV2.array(o_mask) o_mask.setAxis(-1, var.getLongitude()) o_mask.setAxis(-2, var.getLatitude()) return o_mask def set_target_grid(self, target, regrid_tool='esmf', regrid_method='linear'): self.regrid_tool = regrid_tool self.regrid_method = regrid_method if target == '2.5x2.5': self.target_grid = cdms2.createUniformGrid( -88.875, 72, 2.5, 0, 144, 2.5 ) self.target_grid_name = target elif cdms2.isGrid(target): self.target_grid = target self.target_grid_name = target else: logging.getLogger("pcmdi_metrics").error( 'Unknown grid: %s' % target) raise RuntimeError('Unknown grid: %s' % target) def setup_cdms2(self): cdms2.setNetcdfShuffleFlag(0) # Argument is either 0 or 1 cdms2.setNetcdfDeflateFlag(0) # Argument is either 0 or 1 cdms2.setNetcdfDeflateLevelFlag(0) # Argument is int between 0 and 9 def hash(self, block_size=65536): self_file = open(self(), 'rb') buffer = self_file.read(block_size) hasher = hashlib.md5() while len(buffer) > 0: hasher.update(buffer) buffer = self_file.read(block_size) self_file.close() return hasher.hexdigest() class JSONs(object): def addDict2Self(self, json_dict, json_struct, json_version): if float(json_version) == 1.0: V = json_dict[list(json_dict.keys())[0]] for model in list(V.keys()): # loop through models m = V[model] for ref in list(m.keys()): aref = m[ref] if not(isinstance(aref, dict) and "source" in aref): # not an obs key continue reals = list(aref.keys()) src = reals.pop(reals.index("source")) for real in reals: areal = aref[real] areal2 = {"source": src} for region in list(areal.keys()): reg = areal[region] if region == "global": region2 = "" else: region2 = region + "_" areal2[region2 + "global"] = {} areal2[region2 + "NHEX"] = {} areal2[region2 + "SHEX"] = {} areal2[region2 + "TROPICS"] = {} key_stats = list(reg.keys()) for k in key_stats: if k[:7] == "custom_": continue else: sp = k.split("_") new_key = "_".join(sp[:-1]) domain = sp[-1] if domain == "GLB": domain = "global" sp = new_key.split("_") stat = "_".join(sp[:-1]) stat_dict = areal2[region2 + domain].get(stat, {}) season = sp[-1] season_dict = stat_dict stat_dict[season] = reg[k] if stat in areal2[region2 + domain]: areal2[region2 + domain][stat].update(stat_dict) else: areal2[region2 + domain][stat] = stat_dict # Now we can replace the realization with the correctly # formatted one aref[real] = areal2 # restore ref into model m[ref] = aref elif float(json_version) == 2.0: V = json_dict[list(json_dict.keys())[0]] for model in list(V.keys()): # loop through models m = V[model] for ref in list(m.keys()): aref = m[ref] if not(isinstance(aref, dict) and "source" in aref): # not an obs key continue reals = list(aref.keys()) src = reals.pop(reals.index("source")) for real in reals: areal = aref[real] for region in list(areal.keys()): reg = areal[region] key_stats = list(reg.keys()) for k in key_stats: if k[:7] == "custom_": continue sp = k.split("_") season = sp[-1] stat = "_".join(sp[:-1]) stat_dict = reg.get(stat, {}) season_dict = stat_dict.get(season, {}) season_dict[season] = reg[k] # if stat_dict.has_key(stat): # stat_dict[stat].update(season_dict) # else: # stat_dict[stat]=season_dict del(reg[k]) if stat in reg: reg[stat].update(season_dict) else: reg[stat] = season_dict aref[real] = areal # restore ref into model m[ref] = aref V[model] = m json_dict[list(json_dict.keys())[0]] = V update_dict(self.data, json_dict) def get_axes_values_recursive(self, depth, max_depth, data, values): for k in list(data.keys()): if k not in self.ignored_keys and ( isinstance(data[k], dict) or depth == max_depth): values[depth].add(k) if depth != max_depth: self.get_axes_values_recursive( depth + 1, max_depth, data[k], values) def get_array_values_from_dict_recursive(self, out, ids, nms, axval, axes): if len(axes) > 0: for i, val in enumerate(axes[0][:]): self.get_array_values_from_dict_recursive(out, list(ids) + [i, ], list(nms) + [axes[0].id], list(axval) + [val, ], axes[1:]) else: vals = self.data for k in axval: try: vals = vals[k] except Exception: vals = 9.99e20 try: out[tuple(ids)] = float(vals) except Exception: out[tuple(ids)] = 9.99e20 def __init__(self, files=[], structure=[], ignored_keys=[], oneVariablePerFile=True, sortHuman=True): self.json_version = 3.0 self.json_struct = structure self.data = {} self.axes = None self.ignored_keys = ignored_keys self.oneVariablePerFile = oneVariablePerFile self.sortHuman = sortHuman if len(files) == 0: raise Exception("You need to pass at least one file") for fnm in files: self.addJson(fnm) def addJson(self, filename): f = open(filename) tmp_dict = json.load(f) json_struct = tmp_dict.get("json_structure", list(self.json_struct)) json_version = tmp_dict.get("json_version", self.json_version) if self.oneVariablePerFile and json_struct[0] == "variable": json_struct = json_struct[1:] if self.oneVariablePerFile and json_struct[0] != "variable": json_struct.insert(0, "variable") var = tmp_dict.get("Variable", None) if var is None: # Not stored in json, need to get from file name fnm = os.path.basename(filename) varnm = fnm.split("_")[0] else: varnm = var["id"] if "level" in var: varnm += "-%i" % int(var["level"] / 100.) tmp_dict = {varnm: tmp_dict["RESULTS"]} else: tmp_dict = tmp_dict["RESULTS"] if json_struct != self.json_struct and self.json_struct == []: self.json_struct = json_struct self.addDict2Self(tmp_dict, json_struct, json_version) def getAxis(self, axis): axes = self.getAxisList() for a in axes: if a.id == axis: return a return None def getAxisIds(self): axes = self.getAxisList() return [ax.id for ax in axes] def getAxisList(self): values = [] axes = [] for a in self.json_struct: values.append(set()) self.get_axes_values_recursive( 0, len(self.json_struct) - 1, self.data, values) autoBounds = cdms2.getAutoBounds() cdms2.setAutoBounds("off") if self.sortHuman: sortFunc = sort_human else: sortFunc = sorted for i, nm in enumerate(self.json_struct): axes.append(cdms2.createAxis(sortFunc(list(values[i])), id=nm)) self.axes = axes cdms2.setAutoBounds(autoBounds) return self.axes def __call__(self, merge=[], **kargs): """ Returns the array of values""" # First clean up kargs if "merge" in kargs: merge = kargs["merge"] del(kargs["merge"]) order = None axes_ids = self.getAxisIds() if "order" in kargs: # If it's an actual axis assume that it's what user wants # Otherwise it's an out order keyword if "order" not in axes_ids: order = kargs["order"] del(kargs["order"]) ab = cdms2.getAutoBounds() cdms2.setAutoBounds("off") axes = self.getAxisList() if merge != []: if isinstance(merge[0], str): merge = [merge, ] if merge != []: for merger in merge: for merge_axis_id in merger: if merge_axis_id not in axes_ids: raise RuntimeError( "You requested to merge axis is '{}' which is not valid. Axes: {}".format( merge_axis_id, axes_ids)) sh = [] ids = [] used_ids = [] for a in axes: # Regular axis not a merged one sh.append(len(a)) # store length to construct array shape ids.append(a.id) # store ids used_ids.append(a.id) # first let's see which vars are actually asked for # for now assume all keys means restriction on dims if not isinstance(merge, (list, tuple)): raise RuntimeError( "merge keyword must be a list of dimensions to merge together") if len(merge) > 0 and not isinstance(merge[0], (list, tuple)): merge = [merge, ] for axis_id in kargs: if axis_id not in ids: raise ValueError("Invalid axis '%s'" % axis_id) index = ids.index(axis_id) value = kargs[axis_id] if isinstance(value, basestring): value = [value] if not isinstance(value, (list, tuple, slice)): raise TypeError( "Invalid subsetting type for axis '%s', axes can only be subsetted by string,list or slice" % axis_id) if isinstance(value, slice): axes[index] = axes[index].subAxis( value.start, value.stop, value.step) sh[index] = len(axes[index]) else: # ok it's a list for v in value: if v not in axes[index][:]: raise ValueError( "Unkwown value '%s' for axis '%s'" % (v, axis_id)) axis = cdms2.createAxis(value, id=axes[index].id) axes[index] = axis sh[index] = len(axis) array = numpy.ma.ones(sh, dtype=numpy.float) # Now let's fill this array self.get_array_values_from_dict_recursive(array, [], [], [], axes) # Ok at this point we need to take care of merged axes # First let's create the merged axes axes_to_group = [] for merger in merge: merged_axes = [] for axid in merger: for ax in axes: if ax.id == axid: merged_axes.append(ax) axes_to_group.append(merged_axes) new_axes = [groupAxes(grp_axes) for grp_axes in axes_to_group] sh2 = list(sh) for merger in merge: for merger in merge: # loop through all possible merging merged_indices = [] for id in merger: merged_indices.append(axes_ids.index(id)) for indx in merged_indices: sh2[indx] = 1 smallest = min(merged_indices) for indx in merged_indices: sh2[smallest] *= sh[indx] myorder = [] for index in range(len(sh)): if index in myorder: continue for merger in merge: merger = [axes_ids.index(x) for x in merger] if index in merger and index not in myorder: for indx in merger: myorder.append(indx) if index not in myorder: # ok did not find this one anywhere myorder.append(index) outData = numpy.transpose(array, myorder) outData = numpy.reshape(outData, sh2) yank = [] for merger in merge: merger = [axes_ids.index(x) for x in merger] mn = min(merger) merger.remove(mn) yank += merger yank = sorted(yank, reverse=True) for yk in yank: extract = (slice(0, None),) * yk extract += (0,) outData = outData[extract] # Ok now let's apply the newaxes sub = 0 outData = MV2.array(outData) merged_axis_done = [] for index in range(len(array.shape)): foundInMerge = False for imerge, merger in enumerate(merge): merger = [axes_ids.index(x) for x in merger] if index in merger: foundInMerge = True if imerge not in merged_axis_done: merged_axis_done.append(imerge) setMergedAxis = imerge else: setMergedAxis = -1 if not foundInMerge: outData.setAxis(index - sub, axes[index]) else: if setMergedAxis == -1: sub += 1 else: outData.setAxis(index - sub, new_axes[setMergedAxis]) outData = MV2.masked_greater(outData, 9.98e20) outData.id = "pmp" if order is not None: myorder = "".join(["({})".format(nm) for nm in order]) outData = outData(order=myorder) # Merge needs cleaning for extra dims crated if merge != []: for i in range(outData.ndim): outData = scrap(outData, axis=i) outData = MV2.masked_greater(outData, 9.9e19) cdms2.setAutoBounds(ab) return outData
{ "alphanum_fraction": 0.5002574334, "author": null, "avg_line_length": 38.6037267081, "converted": null, "ext": "py", "file": null, "hexsha": "dcb84c6c125ff10f0e45849bd06a8152a9cb218d", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 30, "max_forks_repo_forks_event_max_datetime": "2021-11-02T15:22:21.000Z", "max_forks_repo_forks_event_min_datetime": "2015-06-05T17:19:43.000Z", "max_forks_repo_head_hexsha": "34cdd56a78859db6417cbc7018c8ae8bbf2f09b5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "tomvothecoder/pcmdi_metrics", "max_forks_repo_path": "pcmdi_metrics/io/base.py", "max_issues_count": 524, "max_issues_repo_head_hexsha": "34cdd56a78859db6417cbc7018c8ae8bbf2f09b5", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:06:46.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-01T04:00:34.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "tomvothecoder/pcmdi_metrics", "max_issues_repo_path": "pcmdi_metrics/io/base.py", "max_line_length": 113, "max_stars_count": 47, "max_stars_repo_head_hexsha": "34cdd56a78859db6417cbc7018c8ae8bbf2f09b5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "tomvothecoder/pcmdi_metrics", "max_stars_repo_path": "pcmdi_metrics/io/base.py", "max_stars_repo_stars_event_max_datetime": "2022-01-30T04:35:05.000Z", "max_stars_repo_stars_event_min_datetime": "2015-03-18T22:44:51.000Z", "num_tokens": 6706, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 31076 }
import glob import logging import numpy as np import os import shlex import shutil import subprocess import sys from NPFitProduction.NPFitProduction.cross_sections import CrossSectionScan from NPFit.NPFit.parameters import conversion def annotate(args, config): """Annotate the output directory with a README The README includes instructions to reproduce the current version of the code. Any unstaged code changes will be saved as a git patch. """ start = os.getcwd() os.chdir(os.path.dirname(__file__)) head = subprocess.check_output(shlex.split('git rev-parse --short HEAD')).strip() diff = subprocess.check_output(shlex.split('git diff')) os.chdir(start) shared_filesystem = [] if 'shared-fs' in config: for directory in config['shared-fs']: if not directory.startswith('/'): raise Exception('absolute path required for shared filesystems: {}'.format(directory)) shared_filesystem += ["--shared-fs '/{}'".format(directory.split('/')[1])] info = """ # to run, go to your output directory: cd {outdir} # if you are using a batch queue, start a factory to submit workers # this does not need to be run every time; it can be left running in the background and will only # submit workers as needed nohup work_queue_factory -T {batch_type} -M {label} -C {factory} >& factory.log & # execute the makeflow makeflow -T wq -M {label} {shared} # alternatively, if you do not have much work to do, it may be faster to run locally instead: makeflow -T local # to reproduce the code: cd {code_dir} git checkout {head} """.format( batch_type=config['batch type'], outdir=config['outdir'], label=config['label'], factory=os.path.join(os.environ['LOCALRT'], 'src', 'NPFit', 'NPFit', 'data', 'factory.json'), shared=' '.join(shared_filesystem), code_dir=os.path.dirname(__file__), head=head ) if diff: with open(os.path.join(config['outdir'], 'patch.diff'), 'w') as f: f.write(diff) info += 'git apply {}\n'.format(os.path.join(config['outdir'], 'patch.diff')) with open(os.path.join(config['outdir'], 'README.txt'), 'w') as f: f.write(info) logging.info(info) def parse(args, config): import DataFormats.FWLite result = CrossSectionScan() def get_collection(run, ctype, label): handle = DataFormats.FWLite.Handle(ctype) try: run.getByLabel(label, handle) except: raise return handle.product() logging.info('parsing {}'.format(args.file)) for run in DataFormats.FWLite.Runs(args.file): cross_section = get_collection(run, 'LHERunInfoProduct', 'externalLHEProducer::LHE').heprup().XSECUP[0] coefficients = get_collection(run, 'vector<string>', 'annotator:wilsonCoefficients:LHE') process = str(get_collection(run, 'std::string', 'annotator:process:LHE')) point = np.array(get_collection(run, 'vector<double>', 'annotator:point:LHE')) result.add(point, cross_section, process, coefficients) outfile = os.path.join(config['outdir'], 'cross_sections', os.path.basename(args.file).replace('.root', '.npz')) result.dump(outfile) def concatenate(args, config): if args.files is not None: files = sum([glob.glob(x) for x in args.files], []) else: files = glob.glob(os.path.join(config['outdir'], 'cross_sections', '*.npz')) if 'indirs' in config: for indir in config['indirs']: for root, _, filenames in os.walk(indir): files += [os.path.join(root, fn) for fn in filenames if fn.endswith('.npz')] result = CrossSectionScan(files) result.fit() outfile = os.path.join(config['outdir'], args.output) result.dump(outfile) def combine(args, config): if len(args.coefficients) == 1: label = args.coefficients[0] else: label = '{}{}'.format('_'.join(args.coefficients), '_frozen' if args.freeze else '') all_coefficients = tuple(sorted(config['coefficients'])) scan = CrossSectionScan([os.path.join(config['outdir'], 'cross_sections.npz')]) mins = np.amin(scan.points[all_coefficients][config['processes'][-1]], axis=0) maxes = np.amax(scan.points[all_coefficients][config['processes'][-1]], axis=0) def call_combine(postfix, wspace=None): cmd = ['combine', '-M', 'MultiDimFit'] if len(args.coefficients) == 1: if wspace is None: wspace = os.path.join(config['outdir'], 'workspaces', '{}.root'.format(args.coefficients[0])) cmd += [ wspace, '--setParameters {}=0.0'.format(args.coefficients[0]), '--autoRange=20' ] else: if wspace is None: wspace = os.path.join(config['outdir'], 'workspaces', '{}.root'.format('_'.join(config['coefficients']))) cmd += [ wspace, '--setParameters', '{}'.format(','.join(['{}=0.0'.format(x) for x in config['coefficients']])), '--floatOtherPOIs={}'.format(int(not args.freeze)), '--robustFit=1', '--setRobustFitTolerance=0.001', '--cminApproxPreFitTolerance=0.1', '--cminPreScan' ] + ['-P {}'.format(p) for p in args.coefficients] ranges = [] if tuple(args.coefficients) in config.get('scan window', []): x = args.coefficients[0] y = args.coefficients[1] xmin, xmax, ymin, ymax = [np.array(i) for i in config['scan window'][tuple(args.coefficients)]] ranges += ['{c}={low},{high}'.format(c=x, low=xmin / conversion[x], high=xmax / conversion[x])] ranges += ['{c}={low},{high}'.format(c=y, low=ymin / conversion[y], high=ymax / conversion[y])] for c, low, high in zip(all_coefficients, mins, maxes): if (tuple(args.coefficients) not in config.get('scan window', [])) \ or (c not in args.coefficients) \ or (len(args.coefficients) != 2): ranges += ['{c}={low},{high}'.format(c=c, low=low * 10., high=high * 10.)] cmd += [ # '--autoBoundsPOIs=*', '--autoMaxPOIs=*',# , '--verbose=1' '--setParameterRanges', ':'.join(ranges) ] if config['asimov data']: cmd += ['-t', '-1'] cmd += postfix output = subprocess.check_output(' '.join(cmd), shell=True) if "MultiDimFit failed" in output: sys.exit(99) if args.snapshot: call_combine(['--saveWorkspace', '--saveInactivePOI=1']) shutil.move( 'higgsCombineTest.MultiDimFit.mH120.root', os.path.join(config['outdir'], 'snapshots', '{}.root'.format(label))) elif args.index is None: if len(args.coefficients) == 1 and args.cl is None: call_combine(['--saveFitResult', '--algo=singles']) shutil.move( 'multidimfit.root', os.path.join(config['outdir'], 'fit-result-{}.root'.format(label))) shutil.move( 'higgsCombineTest.MultiDimFit.mH120.root', os.path.join(config['outdir'], 'best-fit-{}.root'.format(label))) elif args.cl is None: call_combine(['--algo=cross']) shutil.move( 'higgsCombineTest.MultiDimFit.mH120.root', os.path.join(config['outdir'], 'best-fit-{}.root'.format(label))) else: call_combine(['--algo=cross', '--stepSize=0.01', '--cl={}'.format(args.cl)]) shutil.move( 'higgsCombineTest.MultiDimFit.mH120.root', os.path.join(config['outdir'], 'cl_intervals/{}-{}.root'.format(label, args.cl))) else: lowers = np.arange(1, args.points, config['np chunksize']) uppers = np.arange(config['np chunksize'], args.points + config['np chunksize'], config['np chunksize']) first, last = zip(lowers, uppers)[args.index] postfix = [ '--algo=grid', '--points={}'.format(args.points), '--firstPoint={}'.format(first), '--lastPoint={}'.format(last), ] if len(args.coefficients) == 1: call_combine(postfix) else: wspace = os.path.join(config['outdir'], 'snapshots', '{}.root'.format(label)) postfix += ['-w', 'w', '--snapshotName', 'MultiDimFit'] call_combine(postfix, wspace) shutil.move( 'higgsCombineTest.MultiDimFit.mH120.root', os.path.join(config['outdir'], 'scans', '{}_{}.root'.format(label, args.index)))
{ "alphanum_fraction": 0.5801036503, "author": null, "avg_line_length": 40.9032258065, "converted": null, "ext": "py", "file": null, "hexsha": "b86db4c944692aecde85466e0e14cd3cfda702ae", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "2295f5739ecfe03886d7060aa334951ef88e91d6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "annawoodard/NPFit", "max_forks_repo_path": "python/actionable.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "2295f5739ecfe03886d7060aa334951ef88e91d6", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "annawoodard/NPFit", "max_issues_repo_path": "python/actionable.py", "max_line_length": 121, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2295f5739ecfe03886d7060aa334951ef88e91d6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "annawoodard/EffectiveTTV", "max_stars_repo_path": "python/actionable.py", "max_stars_repo_stars_event_max_datetime": "2019-03-26T09:20:04.000Z", "max_stars_repo_stars_event_min_datetime": "2019-03-26T09:20:04.000Z", "num_tokens": 2113, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 8876 }
Every Friday afternoon the Davis Korean Church offers bags of produce to the community for a $1 donation. The produce is seasonal, but may include corn, potatoes, tomatoes, yams, etc. These are standard grocerysize bags, onethird filled (about 10 pounds), and they all have the same items. Cant beat the living cheaply value. They celebrated their One Year Anniversary on 20100806. The celebration included extra goodies such as cherry tomatoes from Grace Garden, cookies, popcorn, baked treats, snow cones, and a towel in each produce bag. Yolo County Food Bank had a tent too.
{ "alphanum_fraction": 0.795532646, "author": null, "avg_line_length": 97, "converted": null, "ext": "f", "file": null, "hexsha": "7a8dba25692038d10492451a851f54b178d3a9cb", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "voflo/Search", "max_forks_repo_path": "lab/davisWiki/Friday%27s_Harvest.f", "max_issues_count": null, "max_issues_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "voflo/Search", "max_issues_repo_path": "lab/davisWiki/Friday%27s_Harvest.f", "max_line_length": 325, "max_stars_count": null, "max_stars_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "voflo/Search", "max_stars_repo_path": "lab/davisWiki/Friday%27s_Harvest.f", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 126, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 582 }
""" Andrin Jenal, 2017 ETH Zurich """ import os import h5py from zipfile import ZipFile import numpy as np from scipy import misc class CelebDataset: def __init__(self, dataset_destination_dir, image_size=64, channels=1): self.dataset_dir = dataset_destination_dir self.image_size = image_size self.channels = channels def create_dataset_from_zip(self, path_to_zip_file, num_images=None, dataset_filename="celeb_dataset.h5"): images = [] image_names = [] with ZipFile(path_to_zip_file, 'r') as zfile: file_list = zfile.namelist() for ith, img_file in enumerate(file_list): if str(img_file).endswith('.jpg'): with zfile.open(img_file) as imf: img = misc.imread(imf, mode="RGB") image = self.get_normalized_image(img, self.image_size, self.image_size) if self.channels == 1: image = self.image2gray(image) images.append(image) image_names.append(img_file) if ith == num_images: break file_name_path = os.path.join(self.dataset_dir, dataset_filename) with h5py.File(file_name_path, 'a') as hfile: self.save_images_to_hdf5(hfile, zip(image_names, images)) def resize_width(self, image, width=64.): h, w = np.shape(image)[:2] return misc.imresize(image, [int((float(h) / w) * width), width]) def center_crop(self, x, height=64): h = np.shape(x)[0] j = int(round((h - height) / 2.)) return x[j:j + height, :, :] def get_normalized_image(self, img, width=64, height=64): return self.center_crop(self.resize_width(img, width=width), height=height) def save_images_to_hdf5(self, open_h5file, image_list): for img_name, img_data in image_list: dataset = open_h5file.create_dataset(self.get_filename(img_name), data=img_data, shape=img_data.shape) def get_filename(self, path): return os.path.splitext(os.path.basename(path))[0] def image2gray(self, image): return image[:, :, 0] * 0.299 + image[:, :, 1] * 0.587 + image[:, :, 2] * 0.114 if __name__ == '__main__': c = CelebDataset("/home/ajenal/NeuralNetworks/dcgan-vgg/datasets/", image_size=64, channels=3) c.create_dataset_from_zip("/home/ajenal/Downloads/img_align_celeba.zip", 20000, dataset_filename="celeb_dataset_20k_colored.h5")
{ "alphanum_fraction": 0.6189729518, "author": null, "avg_line_length": 38.6515151515, "converted": null, "ext": "py", "file": null, "hexsha": "bfdefbe74ff62e3ca6b7f6a6794e4938fefd5a17", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "c414696a38a48c3ff471e6ef56f04f9aef52e5c5", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "TheRiddance/dcgan", "max_forks_repo_path": "celeb_conversion.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "c414696a38a48c3ff471e6ef56f04f9aef52e5c5", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "TheRiddance/dcgan", "max_issues_repo_path": "celeb_conversion.py", "max_line_length": 132, "max_stars_count": null, "max_stars_repo_head_hexsha": "c414696a38a48c3ff471e6ef56f04f9aef52e5c5", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "TheRiddance/dcgan", "max_stars_repo_path": "celeb_conversion.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 625, "path": null, "reason": "import numpy,from scipy", "repo": null, "save_path": null, "sha": null, "size": 2551 }
import os import sys import logging import time import argparse import numpy as np from collections import OrderedDict import options.options as option import utils.util as util from data.util import bgr2ycbcr, ImageSplitter, patchify_tensor, recompose_tensor from data import create_dataset, create_dataloader from models import create_model from os import listdir from os.path import join import cv2 import torch import torchvision.transforms as transforms #from torchvision.transforms import Compose, ToTensor import torch.utils.data as utils from torch.autograd import Variable def chop_forward2(lowres_img, model, scale, patch_size = 200): batch_size, channels, img_height, img_width = lowres_img.size() # Patch size for patch-based testing of large images. # Make sure the patch size is small enough that your GPU memory is sufficient. # patch_size = 200 from BlindSR, 64 for ABPN patch_size = min(img_height, img_width, patch_size) overlap = patch_size // 4 # print("lowres_img: ",lowres_img.size()) lowres_patches = patchify_tensor(lowres_img, patch_size, overlap=overlap) # print("lowres_patches: ",lowres_patches.size()) n_patches = lowres_patches.size(0) highres_patches = [] with torch.no_grad(): for p in range(n_patches): lowres_input = lowres_patches[p:p + 1] model.feed_data_batch(lowres_input, need_HR=False) model.test() # test visuals = model.get_current_visuals_batch(need_HR=False) prediction = visuals['SR'] highres_patches.append(prediction) highres_patches = torch.cat(highres_patches, 0) # print("highres_patches: ",highres_patches.size()) highres_output = recompose_tensor(highres_patches, scale*img_height, scale*img_width, overlap=scale*overlap) return highres_output def main(): # options parser = argparse.ArgumentParser() parser.add_argument('-opt', type=str, required=True, help='Path to options JSON file.') opt = option.parse(parser.parse_args().opt, is_train=False) util.mkdirs((path for key, path in opt['path'].items() if not key == 'pretrain_model_G')) opt = option.dict_to_nonedict(opt) chop2 = opt['chop'] chop_patch_size = opt['chop_patch_size'] multi_upscale = opt['multi_upscale'] scale = opt['scale'] util.setup_logger(None, opt['path']['log'], 'test.log', level=logging.INFO, screen=True) logger = logging.getLogger('base') logger.info(option.dict2str(opt)) # Create test dataset and dataloader test_loaders = [] # znorm = False for phase, dataset_opt in sorted(opt['datasets'].items()): test_set = create_dataset(dataset_opt) test_loader = create_dataloader(test_set, dataset_opt) logger.info('Number of test images in [{:s}]: {:d}'.format(dataset_opt['name'], len(test_set))) test_loaders.append(test_loader) #Temporary, will turn znorm on for all the datasets. Will need to introduce a variable for each dataset and differentiate each one later in the loop. # if dataset_opt['znorm'] and znorm == False: # znorm = True # Create model model = create_model(opt) for test_loader in test_loaders: test_set_name = test_loader.dataset.opt['name'] logger.info('\nTesting [{:s}]...'.format(test_set_name)) test_start_time = time.time() dataset_dir = os.path.join(opt['path']['results_root'], test_set_name) util.mkdir(dataset_dir) test_results = OrderedDict() test_results['psnr'] = [] test_results['ssim'] = [] test_results['psnr_y'] = [] test_results['ssim_y'] = [] for data in test_loader: need_HR = False if test_loader.dataset.opt['dataroot_HR'] is None else True img_path = data['LR_path'][0] # because there's only 1 image per "data" dataset loader? img_name = os.path.splitext(os.path.basename(img_path))[0] znorm = test_loader.dataset.opt['znorm'] if chop2==True: lowres_img = data['LR'] #.to('cuda') if multi_upscale: # Upscale 8 times in different rotations/flips and average the results in a single image LR_90 = lowres_img.transpose(2, 3).flip(2) #PyTorch > 0.4.1 LR_180 = LR_90.transpose(2, 3).flip(2) #PyTorch > 0.4.1 LR_270 = LR_180.transpose(2, 3).flip(2) #PyTorch > 0.4.1 LR_f = lowres_img.flip(3) # horizontal mirror (flip), dim=3 (B,C,H,W=0,1,2,3) #PyTorch > 0.4.1 LR_90f = LR_90.flip(3) # horizontal mirror (flip), dim=3 (B,C,H,W=0,1,2,3) #PyTorch > 0.4.1 LR_180f = LR_180.flip(3) # horizontal mirror (flip), dim=3 (B,C,H,W=0,1,2,3) #PyTorch > 0.4.1 LR_270f = LR_270.flip(3) # horizontal mirror (flip), dim=3 (B,C,H,W=0,1,2,3) #PyTorch > 0.4.1 pred = chop_forward2(lowres_img, model, scale=scale, patch_size=chop_patch_size) pred_90 = chop_forward2(LR_90, model, scale=scale, patch_size=chop_patch_size) pred_180 = chop_forward2(LR_180, model, scale=scale, patch_size=chop_patch_size) pred_270 = chop_forward2(LR_270, model, scale=scale, patch_size=chop_patch_size) pred_f = chop_forward2(LR_f, model, scale=scale, patch_size=chop_patch_size) pred_90f = chop_forward2(LR_90f, model, scale=scale, patch_size=chop_patch_size) pred_180f = chop_forward2(LR_180f, model, scale=scale, patch_size=chop_patch_size) pred_270f = chop_forward2(LR_270f, model, scale=scale, patch_size=chop_patch_size) #convert to numpy array if znorm: #opt['datasets']['train']['znorm']: # If the image range is [-1,1] # In testing, each "dataset" can have a different name (not train, val or other) pred = util.tensor2img(pred,min_max=(-1, 1)).clip(0, 255) # uint8 pred_90 = util.tensor2img(pred_90,min_max=(-1, 1)).clip(0, 255) # uint8 pred_180 = util.tensor2img(pred_180,min_max=(-1, 1)).clip(0, 255) # uint8 pred_270 = util.tensor2img(pred_270,min_max=(-1, 1)).clip(0, 255) # uint8 pred_f = util.tensor2img(pred_f,min_max=(-1, 1)).clip(0, 255) # uint8 pred_90f = util.tensor2img(pred_90f,min_max=(-1, 1)).clip(0, 255) # uint8 pred_180f = util.tensor2img(pred_180f,min_max=(-1, 1)).clip(0, 255) # uint8 pred_270f = util.tensor2img(pred_270f,min_max=(-1, 1)).clip(0, 255) # uint8 else: # Default: Image range is [0,1] pred = util.tensor2img(pred).clip(0, 255) # uint8 pred_90 = util.tensor2img(pred_90).clip(0, 255) # uint8 pred_180 = util.tensor2img(pred_180).clip(0, 255) # uint8 pred_270 = util.tensor2img(pred_270).clip(0, 255) # uint8 pred_f = util.tensor2img(pred_f).clip(0, 255) # uint8 pred_90f = util.tensor2img(pred_90f).clip(0, 255) # uint8 pred_180f = util.tensor2img(pred_180f).clip(0, 255) # uint8 pred_270f = util.tensor2img(pred_270f).clip(0, 255) # uint8 pred_90 = np.rot90(pred_90, 3) pred_180 = np.rot90(pred_180, 2) pred_270 = np.rot90(pred_270, 1) pred_f = np.fliplr(pred_f) pred_90f = np.rot90(np.fliplr(pred_90f), 3) pred_180f = np.rot90(np.fliplr(pred_180f), 2) pred_270f = np.rot90(np.fliplr(pred_270f), 1) #The reason for overflow is that your NumPy arrays (im1arr im2arr) are of the uint8 type (i.e. 8-bit). This means each element of the array can only hold values up to 255, so when your sum exceeds 255, it loops back around 0: #To avoid overflow, your arrays should be able to contain values beyond 255. You need to convert them to floats for instance, perform the blending operation and convert the result back to uint8: # sr_img = (pred + pred_90 + pred_180 + pred_270 + pred_f + pred_90f + pred_180f + pred_270f) / 8.0 sr_img = (pred.astype('float') + pred_90.astype('float') + pred_180.astype('float') + pred_270.astype('float') + pred_f.astype('float') + pred_90f.astype('float') + pred_180f.astype('float') + pred_270f.astype('float')) / 8.0 sr_img = sr_img.astype('uint8') else: highres_output = chop_forward2(lowres_img, model, scale=scale, patch_size=chop_patch_size) #convert to numpy array #highres_image = highres_output[0].permute(1, 2, 0).clamp(0.0, 1.0).cpu() if znorm: #opt['datasets']['train']['znorm']: # If the image range is [-1,1] # In testing, each "dataset" can have a different name (not train, val or other) sr_img = util.tensor2img(highres_output,min_max=(-1, 1)) # uint8 else: # Default: Image range is [0,1] sr_img = util.tensor2img(highres_output) # uint8 else: # will upscale each image in the batch without chopping model.feed_data(data, need_HR=need_HR) model.test() # test visuals = model.get_current_visuals(need_HR=need_HR) if znorm: #opt['datasets']['train']['znorm']: # If the image range is [-1,1] # In testing, each "dataset" can have a different name (not train, val or other) sr_img = util.tensor2img(visuals['SR'],min_max=(-1, 1)) # uint8 else: # Default: Image range is [0,1] sr_img = util.tensor2img(visuals['SR']) # uint8 # save images suffix = opt['suffix'] if suffix: save_img_path = os.path.join(dataset_dir, img_name + suffix + '.png') else: save_img_path = os.path.join(dataset_dir, img_name + '.png') util.save_img(sr_img, save_img_path) # calculate PSNR and SSIM if need_HR: if znorm: #opt['datasets']['train']['znorm']: # If the image range is [-1,1] # In testing, each "dataset" can have a different name (not train, val or other) gt_img = util.tensor2img(visuals['HR'],min_max=(-1, 1)) # uint8 else: # Default: Image range is [0,1] gt_img = util.tensor2img(visuals['HR']) # uint8 gt_img = gt_img / 255. sr_img = sr_img / 255. crop_border = test_loader.dataset.opt['scale'] cropped_sr_img = sr_img[crop_border:-crop_border, crop_border:-crop_border, :] cropped_gt_img = gt_img[crop_border:-crop_border, crop_border:-crop_border, :] psnr = util.calculate_psnr(cropped_sr_img * 255, cropped_gt_img * 255) ssim = util.calculate_ssim(cropped_sr_img * 255, cropped_gt_img * 255) test_results['psnr'].append(psnr) test_results['ssim'].append(ssim) if gt_img.shape[2] == 3: # RGB image sr_img_y = bgr2ycbcr(sr_img, only_y=True) gt_img_y = bgr2ycbcr(gt_img, only_y=True) cropped_sr_img_y = sr_img_y[crop_border:-crop_border, crop_border:-crop_border] cropped_gt_img_y = gt_img_y[crop_border:-crop_border, crop_border:-crop_border] psnr_y = util.calculate_psnr(cropped_sr_img_y * 255, cropped_gt_img_y * 255) ssim_y = util.calculate_ssim(cropped_sr_img_y * 255, cropped_gt_img_y * 255) test_results['psnr_y'].append(psnr_y) test_results['ssim_y'].append(ssim_y) logger.info('{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}; PSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}.'\ .format(img_name, psnr, ssim, psnr_y, ssim_y)) else: logger.info('{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}.'.format(img_name, psnr, ssim)) else: logger.info(img_name) if need_HR: # metrics # Average PSNR/SSIM results ave_psnr = sum(test_results['psnr']) / len(test_results['psnr']) ave_ssim = sum(test_results['ssim']) / len(test_results['ssim']) logger.info('----Average PSNR/SSIM results for {}----\n\tPSNR: {:.6f} dB; SSIM: {:.6f}\n'\ .format(test_set_name, ave_psnr, ave_ssim)) if test_results['psnr_y'] and test_results['ssim_y']: ave_psnr_y = sum(test_results['psnr_y']) / len(test_results['psnr_y']) ave_ssim_y = sum(test_results['ssim_y']) / len(test_results['ssim_y']) logger.info('----Y channel, average PSNR/SSIM----\n\tPSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}\n'\ .format(ave_psnr_y, ave_ssim_y)) if __name__ == '__main__': main()
{ "alphanum_fraction": 0.5814089448, "author": null, "avg_line_length": 57.7383966245, "converted": null, "ext": "py", "file": null, "hexsha": "a62701eb1408d1d880ae2aa2a96adafa0400bda8", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "e8fec2f11702e4928d3ce488caf4b897c8023efd", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "AlphaAtlas/BasicSR", "max_forks_repo_path": "codes/test_abpn.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "e8fec2f11702e4928d3ce488caf4b897c8023efd", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "AlphaAtlas/BasicSR", "max_issues_repo_path": "codes/test_abpn.py", "max_line_length": 245, "max_stars_count": null, "max_stars_repo_head_hexsha": "e8fec2f11702e4928d3ce488caf4b897c8023efd", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "AlphaAtlas/BasicSR", "max_stars_repo_path": "codes/test_abpn.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3593, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 13684 }
[STATEMENT] lemma map_inv_map_inv [simp]: assumes "inj_on f (dom f)" shows "map_inv (map_inv f) = f" [PROOF STATE] proof (prove) goal (1 subgoal): 1. map_inv (map_inv f) = f [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. map_inv (map_inv f) = f [PROOF STEP] from assms [PROOF STATE] proof (chain) picking this: inj_on f (dom f) [PROOF STEP] have "inj_on (map_inv f) (ran f)" [PROOF STATE] proof (prove) using this: inj_on f (dom f) goal (1 subgoal): 1. inj_on (map_inv f) (ran f) [PROOF STEP] by auto [PROOF STATE] proof (state) this: inj_on (map_inv f) (ran f) goal (1 subgoal): 1. map_inv (map_inv f) = f [PROOF STEP] thus ?thesis [PROOF STATE] proof (prove) using this: inj_on (map_inv f) (ran f) goal (1 subgoal): 1. map_inv (map_inv f) = f [PROOF STEP] apply (rule_tac ext) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. inj_on (map_inv f) (ran f) \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (rename_tac x) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. inj_on (map_inv f) (ran f) \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (case_tac "\<exists> y. map_inv f y = Some x") [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>x. \<lbrakk>inj_on (map_inv f) (ran f); \<exists>y. map_inv f y = Some x\<rbrakk> \<Longrightarrow> map_inv (map_inv f) x = f x 2. \<And>x. \<lbrakk>inj_on (map_inv f) (ran f); \<nexists>y. map_inv f y = Some x\<rbrakk> \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (auto)[1] [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>x y. \<lbrakk>inj_on (map_inv f) (ran f); map_inv f y = Some x\<rbrakk> \<Longrightarrow> Some y = f x 2. \<And>x. \<lbrakk>inj_on (map_inv f) (ran f); \<nexists>y. map_inv f y = Some x\<rbrakk> \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (simp add:map_inv_def) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>x y. \<lbrakk>inj_on (\<lambda>y. if y \<in> ran f then Some (SOME x. f x = Some y) else None) (ran f); (if y \<in> ran f then Some (SOME x. f x = Some y) else None) = Some x\<rbrakk> \<Longrightarrow> Some y = f x 2. \<And>x. \<lbrakk>inj_on (map_inv f) (ran f); \<nexists>y. map_inv f y = Some x\<rbrakk> \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (rename_tac x y) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>x y. \<lbrakk>inj_on (\<lambda>y. if y \<in> ran f then Some (SOME x. f x = Some y) else None) (ran f); (if y \<in> ran f then Some (SOME x. f x = Some y) else None) = Some x\<rbrakk> \<Longrightarrow> Some y = f x 2. \<And>x. \<lbrakk>inj_on (map_inv f) (ran f); \<nexists>y. map_inv f y = Some x\<rbrakk> \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (case_tac "y \<in> ran f", simp_all) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>x y. \<lbrakk>inj_on (\<lambda>y. if y \<in> ran f then Some (SOME x. f x = Some y) else None) (ran f); (SOME x. f x = Some y) = x; y \<in> ran f\<rbrakk> \<Longrightarrow> Some y = f x 2. \<And>x. \<lbrakk>inj_on (map_inv f) (ran f); \<forall>y. map_inv f y \<noteq> Some x\<rbrakk> \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (auto) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>y. \<lbrakk>inj_on (\<lambda>y. if y \<in> ran f then Some (SOME x. f x = Some y) else None) (ran f); y \<in> ran f\<rbrakk> \<Longrightarrow> Some y = f (SOME x. f x = Some y) 2. \<And>x. \<lbrakk>inj_on (map_inv f) (ran f); \<forall>y. map_inv f y \<noteq> Some x\<rbrakk> \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (rule someI2_ex) [PROOF STATE] proof (prove) goal (3 subgoals): 1. \<And>y. \<lbrakk>inj_on (\<lambda>y. if y \<in> ran f then Some (SOME x. f x = Some y) else None) (ran f); y \<in> ran f\<rbrakk> \<Longrightarrow> \<exists>a. f a = Some y 2. \<And>y x. \<lbrakk>inj_on (\<lambda>y. if y \<in> ran f then Some (SOME x. f x = Some y) else None) (ran f); y \<in> ran f; f x = Some y\<rbrakk> \<Longrightarrow> Some y = f x 3. \<And>x. \<lbrakk>inj_on (map_inv f) (ran f); \<forall>y. map_inv f y \<noteq> Some x\<rbrakk> \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (simp add:ran_def) [PROOF STATE] proof (prove) goal (2 subgoals): 1. \<And>y x. \<lbrakk>inj_on (\<lambda>y. if y \<in> ran f then Some (SOME x. f x = Some y) else None) (ran f); y \<in> ran f; f x = Some y\<rbrakk> \<Longrightarrow> Some y = f x 2. \<And>x. \<lbrakk>inj_on (map_inv f) (ran f); \<forall>y. map_inv f y \<noteq> Some x\<rbrakk> \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (simp) [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x. \<lbrakk>inj_on (map_inv f) (ran f); \<forall>y. map_inv f y \<noteq> Some x\<rbrakk> \<Longrightarrow> map_inv (map_inv f) x = f x [PROOF STEP] apply (metis assms dom_image_ran dom_map_inv image_iff map_add_dom_app_simps(2) map_add_dom_app_simps(3) ran_map_inv) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done [PROOF STATE] proof (state) this: map_inv (map_inv f) = f goal: No subgoals! [PROOF STEP] qed
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "UTP_toolkit_Map_Extra", "hexsha": null, "include": null, "lang": null, "length": 19, "llama_tokens": 2279, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": null }
using CLBLAS const clblas = CLBLAS import OpenCL using OpenCL: cl function testDirectCall() device, ctx, queue = clblas.get_next_compute_context() A = rand(Float32, 1) B = rand(Float32, 1) C = rand(Float32, 1) println(A, B, C) a = cl.cl_float(6.6) b = cl.cl_float(7.2) bufA = cl.Buffer(Float32, ctx, (:r, :copy),hostbuf=A) bufB = cl.Buffer(Float32, ctx, (:r, :copy),hostbuf=B) bufC = cl.Buffer(Float32, ctx, (:rw, :copy),hostbuf=C) event = cl.UserEvent(ctx, retain=true) ptrEvent = [event.id] println("ccalling!!!") clblas.clblasSgemm(1, 0, 0, convert(Csize_t, 1), convert(Csize_t, 1), convert(Csize_t, 1), a, bufA.id, convert(Csize_t, 0), convert(Csize_t, 1), bufB.id, convert(Csize_t, 0), convert(Csize_t, 1), b, bufC.id, convert(Csize_t, 0), convert(Csize_t, 1), cl.cl_uint(1), [queue.id], cl.cl_uint(0), C_NULL, ptrEvent) println("ccall was ok") cl.api.clWaitForEvents(cl.cl_uint(1), ptrEvent) println("wait was ok") result = Vector{Float32}(1) cl.enqueue_read_buffer(queue, bufC, result, Unsigned(0), nothing, true) println("read was ok") println(result[1]) end function testRandMul() a = float32(3) A = float32([3]) println(A) println(eltype(A)) B = float32([3]) b = float32(3) C = float32([3]) println("Normal:", (a*A[1]*B[1] + b*C[1])) startT = time_ns() futBuf = clblas.clblasSgemm(clblas.clblasColumnMajor.n, clblas.clblasNoTrans.n, clblas.clblasNoTrans.n, 1, a, A, 1, B, 1, b, C) result = fetch(futBuf) endT = time_ns() println("RandMul took:", (endT - startT)/1000000) println("Result:", result) end clblas.setup(true) function testRandBuf(x, y) #startT = time_ns() futBuf = clblas.randBuf(x, y) #futBuf = clblas.clblasSscal(futBuf, cl.cl_float(13.13)) mat = clblas.fetch(futBuf) #endT = time_ns() #println(futBuf.actualEvent[:status]) #println(futBuf.actualEvent[:profile_duration]) #println("RandBuf took:", (endT - startT)/1000000) #println(mat) end function testRand(x, y) startT = time_ns() test = rand(x, y) * 13.13 endT = time_ns() println("Rand took:", (endT - startT)/1000000) end #result = Vector{Float32}(length(futBuf.resultMem)) #cl.enqueue_read_buffer(futBuf.queue, futBuf.resultMem, result, Unsigned(0), nothing, true) #println(result)
{ "alphanum_fraction": 0.5590379009, "author": null, "avg_line_length": 29.1914893617, "converted": null, "ext": "jl", "file": null, "hexsha": "1b041da0d203888d8744ffa01beeac4c473b6821", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 16, "max_forks_repo_forks_event_max_datetime": "2021-10-01T18:22:08.000Z", "max_forks_repo_forks_event_min_datetime": "2015-07-10T07:53:05.000Z", "max_forks_repo_head_hexsha": "144ebcbb9f69a2dd372a6a530c705534fa4438e6", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "JuliaTagBot/CLBLAS.jl", "max_forks_repo_path": "examples/randomBuffer.jl", "max_issues_count": 28, "max_issues_repo_head_hexsha": "144ebcbb9f69a2dd372a6a530c705534fa4438e6", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:29:18.000Z", "max_issues_repo_issues_event_min_datetime": "2015-11-04T20:52:40.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "JuliaTagBot/CLBLAS.jl", "max_issues_repo_path": "examples/randomBuffer.jl", "max_line_length": 108, "max_stars_count": 17, "max_stars_repo_head_hexsha": "144ebcbb9f69a2dd372a6a530c705534fa4438e6", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "JuliaTagBot/CLBLAS.jl", "max_stars_repo_path": "examples/randomBuffer.jl", "max_stars_repo_stars_event_max_datetime": "2021-05-17T20:39:59.000Z", "max_stars_repo_stars_event_min_datetime": "2015-02-01T07:58:08.000Z", "num_tokens": 808, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2744 }
import os, urllib import mxnet as mx import cv2 import numpy as np import sys def download(url,prefix=''): filename = prefix+url.split("/")[-1] if not os.path.exists(filename): urllib.urlretrieve(url, filename) def get_image(url, show=False): filename = url.split("/")[-1] urllib.urlretrieve(url, filename) img = cv2.imread(filename) if img is None: print('failed to download ' + url) if show: plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) plt.axis('off') return filename def predict(filename, mod, synsets, Batch, resize_shape=(224, 224)): # Oops!!! cv2 crashed! img = cv2.cvtColor(cv2.imread(filename), cv2.COLOR_BGR2RGB) #from skimage import io #img = io.imread(filename) if img is None: return None img = cv2.resize(img, resize_shape) img = np.swapaxes(img, 0, 2) img = np.swapaxes(img, 1, 2) img = img[np.newaxis, :] mod.forward(Batch([mx.nd.array(img)])) prob = mod.get_outputs()[0].asnumpy() prob = np.squeeze(prob) #print ",".join(['0.jpg'] + map(str, prob)) #a = np.argsort(prob)[::-1] #for i in a[0:5]: #print('probability=%f, class=%s' %(prob[i], synsets[i])) return prob def main(): # inialization paramter test_dir = '/home/yuanshuai/data/ccs/test_seg_224' resize_shape = (224, 224) batch_size = 1 num_gpus = 1 data_shape = resize_shape #model_prefix = "./models/resnet-50-train-seg-224/resnet-50-train-seg-224" print sys.argv, len(sys.argv) model_prefix = sys.argv[1] #"./inception-resnet-v2-50-train-seg-224-lr-0.01/inception-resnet-v2-50-train-add-seg-224-lr-0.01" epoch = int(sys.argv[2]) # sys.argv[0] is this python-file-self name csv_name = "".join([ model_prefix[:model_prefix.index("/", 2)+1], "[result]", model_prefix.split('/')[-1], "-"+str(epoch)] )+".csv" with open('full-synset.txt', 'r') as f: synsets = [l.rstrip() for l in f] sym, arg_params, aux_params = mx.model.load_checkpoint(model_prefix, epoch) # Create a model for this model on GPU 0. #devs = [mx.gpu(i) for i in xrange(num_gpus)] devs = [mx.gpu(2)] mod = mx.mod.Module(symbol=sym, context=devs) #mod = mx.mod.Module(symbol=sym, context=mx.cpu()) mod.bind(for_training=False, data_shapes=[('data', (batch_size, 3,data_shape[0],data_shape[1]))]) mod.set_params(arg_params, aux_params) # Next we define the function to obtain an image by a given URL and the function for predicting. import matplotlib matplotlib.rc("savefig", dpi=100) import matplotlib.pyplot as plt from collections import namedtuple Batch = namedtuple('Batch', ['data']) # We are able to classify an image and output the top predicted classes. #url = 'http://writm.com/wp-content/uploads/2016/08/Cat-hd-wallpapers.jpg' #predict(get_image(url), mod, synsets) #predict('./Cat-hd-wallpapers.jpg', mod, synsets, Batch) # make prediction for a collection of images #test_dir = '/home/yuanshuai/data/ccs/test' test_img_dir_list = map(lambda test_img_name: "/".join([test_dir, test_img_name]), os.listdir(test_dir)) test_img_prob_list = [] import csv csvfile = open(csv_name,'wb') csvfile.write(",".join(['image_name', 'Type_1', 'Type_2', 'Type_3\n'])) for test_img_idx in xrange(len(test_img_dir_list)):#xrange(3): #test_img_dir = test_img_dir_list[test_img_idx] test_img_dir = test_dir+'/'+str(test_img_idx)+".jpg" print test_img_dir test_img_prob = predict(test_img_dir, mod, synsets, Batch) row = ",".join([test_img_dir.split('/')[-1]] + map(str, test_img_prob))+'\n' #print row csvfile.write(row) csvfile.close() if __name__ == "__main__": main()
{ "alphanum_fraction": 0.6444502755, "author": null, "avg_line_length": 33.7256637168, "converted": null, "ext": "py", "file": null, "hexsha": "3d39e3fdcaa6e58fbc8a5dd5d51e5b7c8172f5f1", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "782a15998900fcb60de6fc1cb9fd8a3eb525435c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ysh329/kaggle-invasive-species-monitoring-classification", "max_forks_repo_path": "train-or-finetune-model/tmp/run_inference_tmp.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "782a15998900fcb60de6fc1cb9fd8a3eb525435c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ysh329/kaggle-invasive-species-monitoring-classification", "max_issues_repo_path": "train-or-finetune-model/tmp/run_inference_tmp.py", "max_line_length": 135, "max_stars_count": null, "max_stars_repo_head_hexsha": "782a15998900fcb60de6fc1cb9fd8a3eb525435c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ysh329/kaggle-invasive-species-monitoring-classification", "max_stars_repo_path": "train-or-finetune-model/tmp/run_inference_tmp.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1072, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 3811 }
*DECK DBI DOUBLE PRECISION FUNCTION DBI (X) C***BEGIN PROLOGUE DBI C***PURPOSE Evaluate the Bairy function (the Airy function of the C second kind). C***LIBRARY SLATEC (FNLIB) C***CATEGORY C10D C***TYPE DOUBLE PRECISION (BI-S, DBI-D) C***KEYWORDS BAIRY FUNCTION, FNLIB, SPECIAL FUNCTIONS C***AUTHOR Fullerton, W., (LANL) C***DESCRIPTION C C DBI(X) calculates the double precision Airy function of the C second kind for double precision argument X. C C Series for BIF on the interval -1.00000E+00 to 1.00000E+00 C with weighted error 1.45E-32 C log weighted error 31.84 C significant figures required 30.85 C decimal places required 32.40 C C Series for BIG on the interval -1.00000E+00 to 1.00000E+00 C with weighted error 1.29E-33 C log weighted error 32.89 C significant figures required 31.48 C decimal places required 33.45 C C Series for BIF2 on the interval 1.00000E+00 to 8.00000E+00 C with weighted error 6.08E-32 C log weighted error 31.22 C approx significant figures required 30.8 C decimal places required 31.80 C C Series for BIG2 on the interval 1.00000E+00 to 8.00000E+00 C with weighted error 4.91E-33 C log weighted error 32.31 C approx significant figures required 31.6 C decimal places required 32.90 C C***REFERENCES (NONE) C***ROUTINES CALLED D1MACH, D9AIMP, DBIE, DCSEVL, INITDS, XERMSG C***REVISION HISTORY (YYMMDD) C 770701 DATE WRITTEN C 890531 Changed all specific intrinsics to generic. (WRB) C 890531 REVISION DATE from Version 3.2 C 891214 Prologue converted to Version 4.0 format. (BAB) C 900315 CALLs to XERROR changed to CALLs to XERMSG. (THJ) C***END PROLOGUE DBI DOUBLE PRECISION X, BIFCS(13), BIGCS(13), BIF2CS(15), BIG2CS(15), 1 THETA, XM, XMAX, X3SML, Z, D1MACH, DCSEVL, DBIE LOGICAL FIRST SAVE BIFCS, BIGCS, BIF2CS, BIG2CS, NBIF, NBIG, 1 NBIF2, NBIG2, X3SML, XMAX, FIRST DATA BIFCS( 1) / -.1673021647 1986649483 5374239281 76 D-1 / DATA BIFCS( 2) / +.1025233583 4249445611 4263627777 57 D+0 / DATA BIFCS( 3) / +.1708309250 7381516539 4296502420 13 D-2 / DATA BIFCS( 4) / +.1186254546 7744681179 2164592100 40 D-4 / DATA BIFCS( 5) / +.4493290701 7792133694 5318879272 42 D-7 / DATA BIFCS( 6) / +.1069820714 3387889067 5677676636 28 D-9 / DATA BIFCS( 7) / +.1748064339 9771824706 0105176285 73 D-12 / DATA BIFCS( 8) / +.2081023107 1761711025 8818918343 99 D-15 / DATA BIFCS( 9) / +.1884981469 5665416509 9279717333 33 D-18 / DATA BIFCS( 10) / +.1342577917 3097804625 8826666666 66 D-21 / DATA BIFCS( 11) / +.7715959342 9658887893 3333333333 33 D-25 / DATA BIFCS( 12) / +.3653387961 7478566399 9999999999 99 D-28 / DATA BIFCS( 13) / +.1449756592 7953066666 6666666666 66 D-31 / DATA BIGCS( 1) / +.2246622324 8574522283 4682201390 24 D-1 / DATA BIGCS( 2) / +.3736477545 3019545441 7275616667 52 D-1 / DATA BIGCS( 3) / +.4447621895 7212285696 2152943266 39 D-3 / DATA BIGCS( 4) / +.2470807563 6329384245 4945919488 82 D-5 / DATA BIGCS( 5) / +.7919135339 5149635134 8624262855 96 D-8 / DATA BIGCS( 6) / +.1649807985 1827779880 8878724027 06 D-10 / DATA BIGCS( 7) / +.2411990666 4835455909 2475011228 41 D-13 / DATA BIGCS( 8) / +.2610373623 6091436985 1847812693 33 D-16 / DATA BIGCS( 9) / +.2175308297 7160323853 1237920000 00 D-19 / DATA BIGCS( 10) / +.1438694640 0390433219 4837333333 33 D-22 / DATA BIGCS( 11) / +.7734912561 2083468629 3333333333 33 D-26 / DATA BIGCS( 12) / +.3446929203 3849002666 6666666666 66 D-29 / DATA BIGCS( 13) / +.1293891927 3216000000 0000000000 00 D-32 / DATA BIF2CS( 1) / +.0998457269 3816041044 6828425799 3 D+0 / DATA BIF2CS( 2) / +.4786249778 6300553772 2114673182 31 D+0 / DATA BIF2CS( 3) / +.2515521196 0433011771 3244154366 75 D-1 / DATA BIF2CS( 4) / +.5820693885 2326456396 5156978722 16 D-3 / DATA BIF2CS( 5) / +.7499765964 4377865943 8614573782 17 D-5 / DATA BIF2CS( 6) / +.6134602870 3493836681 4030103564 74 D-7 / DATA BIF2CS( 7) / +.3462753885 1480632900 4342687333 59 D-9 / DATA BIF2CS( 8) / +.1428891008 0270254287 7708467489 31 D-11 / DATA BIF2CS( 9) / +.4496270429 8334641895 0564721792 00 D-14 / DATA BIF2CS( 10) / +.1114232306 5833011708 4283001066 66 D-16 / DATA BIF2CS( 11) / +.2230479106 6175002081 5178666666 66 D-19 / DATA BIF2CS( 12) / +.3681577873 6393142842 9226666666 66 D-22 / DATA BIF2CS( 13) / +.5096086844 9338261333 3333333333 33 D-25 / DATA BIF2CS( 14) / +.6000338692 6288554666 6666666666 66 D-28 / DATA BIF2CS( 15) / +.6082749744 6570666666 6666666666 66 D-31 / DATA BIG2CS( 1) / +.0333056621 4551434046 5176188111 647 D+0 / DATA BIG2CS( 2) / +.1613092151 2319706761 3287532084 943 D+0 / DATA BIG2CS( 3) / +.6319007309 6134286912 1615634921 173 D-2 / DATA BIG2CS( 4) / +.1187904568 1625173638 9780192304 567 D-3 / DATA BIG2CS( 5) / +.1304534588 6200265614 7116485012 843 D-5 / DATA BIG2CS( 6) / +.9374125995 5352172954 6809615508 936 D-8 / DATA BIG2CS( 7) / +.4745801886 7472515378 8510169834 595 D-10 / DATA BIG2CS( 8) / +.1783107265 0948139980 0065667560 946 D-12 / DATA BIG2CS( 9) / +.5167591927 8495818037 4276356640 000 D-15 / DATA BIG2CS( 10) / +.1190045083 8682712512 9496251733 333 D-17 / DATA BIG2CS( 11) / +.2229828806 6640351727 7063466666 666 D-20 / DATA BIG2CS( 12) / +.3465519230 2768941972 2666666666 666 D-23 / DATA BIG2CS( 13) / +.4539263363 2050451413 3333333333 333 D-26 / DATA BIG2CS( 14) / +.5078849965 1352234666 6666666666 666 D-29 / DATA BIG2CS( 15) / +.4910206746 9653333333 3333333333 333 D-32 / DATA FIRST /.TRUE./ C***FIRST EXECUTABLE STATEMENT DBI IF (FIRST) THEN ETA = 0.1*REAL(D1MACH(3)) NBIF = INITDS (BIFCS, 13, ETA) NBIG = INITDS (BIGCS, 13, ETA) NBIF2 = INITDS (BIF2CS, 15, ETA) NBIG2 = INITDS (BIG2CS, 15, ETA) C X3SML = ETA**0.3333 XMAX = (1.5*LOG(D1MACH(2)))**0.6666D0 ENDIF FIRST = .FALSE. C IF (X.GE.(-1.0D0)) GO TO 20 CALL D9AIMP (X, XM, THETA) DBI = XM * SIN(THETA) RETURN C 20 IF (X.GT.1.0D0) GO TO 30 Z = 0.D0 IF (ABS(X).GT.X3SML) Z = X**3 DBI = 0.625 + DCSEVL (Z, BIFCS, NBIF) + X*(0.4375D0 + 1 DCSEVL (Z, BIGCS, NBIG)) RETURN C 30 IF (X.GT.2.0D0) GO TO 40 Z = (2.0D0*X**3 - 9.0D0)/7.D0 DBI = 1.125D0 + DCSEVL (Z, BIF2CS, NBIF2) + X*(0.625D0 + 1 DCSEVL (Z, BIG2CS, NBIG2)) RETURN C 40 IF (X .GT. XMAX) CALL XERMSG ('SLATEC', 'DBI', + 'X SO BIG THAT BI OVERFLOWS', 1, 2) C DBI = DBIE(X) * EXP(2.0D0*X*SQRT(X)/3.0D0) RETURN C END
{ "alphanum_fraction": 0.5875016411, "author": null, "avg_line_length": 51.1208053691, "converted": null, "ext": "f", "file": null, "hexsha": "fa1d79aceeeb5f3ef0c53c1197b3ebffbdd10fd8", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_forks_repo_licenses": [ "Unlicense" ], "max_forks_repo_name": "andremirt/v_cond", "max_forks_repo_path": "slatec/src/dbi.f", "max_issues_count": null, "max_issues_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense" ], "max_issues_repo_name": "andremirt/v_cond", "max_issues_repo_path": "slatec/src/dbi.f", "max_line_length": 72, "max_stars_count": null, "max_stars_repo_head_hexsha": "6b5c364d7cd4243686488b2bd4318be3927e07ea", "max_stars_repo_licenses": [ "Unlicense" ], "max_stars_repo_name": "andremirt/v_cond", "max_stars_repo_path": "slatec/src/dbi.f", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3099, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 7617 }
""" ================== Animate Trajectory ================== Animates a trajectory. """ print(__doc__) import numpy as np import pytransform3d.visualizer as pv from pytransform3d.rotations import matrix_from_angle, R_id from pytransform3d.transformations import transform_from, concat def update_trajectory(step, n_frames, trajectory): progress = 1 - float(step + 1) / float(n_frames) H = np.zeros((100, 4, 4)) H0 = transform_from(R_id, np.zeros(3)) H_mod = np.eye(4) for i, t in enumerate(np.linspace(0, progress, len(H))): H0[:3, 3] = np.array([t, 0, t]) H_mod[:3, :3] = matrix_from_angle(2, 8 * np.pi * t) H[i] = concat(H0, H_mod) trajectory.set_data(H) return trajectory n_frames = 200 fig = pv.figure() H = np.empty((100, 4, 4)) H[:] = np.eye(4) # set initial trajectory to extend view box H[:, 0, 3] = np.linspace(-2, 2, len(H)) H[:, 1, 3] = np.linspace(-2, 2, len(H)) H[:, 2, 3] = np.linspace(0, 4, len(H)) trajectory = pv.Trajectory(H, s=0.2, c=[0, 0, 0]) trajectory.add_artist(fig) fig.view_init() fig.set_zoom(0.5) if "__file__" in globals(): fig.animate( update_trajectory, n_frames, fargs=(n_frames, trajectory), loop=True) fig.show() else: fig.save_image("__open3d_rendered_image.jpg")
{ "alphanum_fraction": 0.6349453978, "author": null, "avg_line_length": 24.6538461538, "converted": null, "ext": "py", "file": null, "hexsha": "1c579a7dafa4e09e5c5b3d828b776ab0879e98af", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 37, "max_forks_repo_forks_event_max_datetime": "2022-03-16T02:29:53.000Z", "max_forks_repo_forks_event_min_datetime": "2018-12-09T23:58:40.000Z", "max_forks_repo_head_hexsha": "c6fb10b1d17713bd8a2d6becb928c4f6dcf611f9", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "alek5k/pytransform3d", "max_forks_repo_path": "examples/visualizations/vis_moving_trajectory.py", "max_issues_count": 94, "max_issues_repo_head_hexsha": "c6fb10b1d17713bd8a2d6becb928c4f6dcf611f9", "max_issues_repo_issues_event_max_datetime": "2022-03-19T22:38:20.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-07T14:54:05.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "alek5k/pytransform3d", "max_issues_repo_path": "examples/visualizations/vis_moving_trajectory.py", "max_line_length": 77, "max_stars_count": 304, "max_stars_repo_head_hexsha": "c6fb10b1d17713bd8a2d6becb928c4f6dcf611f9", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "alek5k/pytransform3d", "max_stars_repo_path": "examples/visualizations/vis_moving_trajectory.py", "max_stars_repo_stars_event_max_datetime": "2022-03-31T16:14:37.000Z", "max_stars_repo_stars_event_min_datetime": "2019-01-16T15:14:31.000Z", "num_tokens": 401, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1282 }
# Author: Igor Andreoni # email: andreoni@caltech.edu import glob from astropy.io import fits import numpy as np import matplotlib.pyplot as plt def str2bool(v): if v.lower() in ('yes', 'true', 't', 'y', '1', 'Yes', 'True'): return True elif v.lower() in ('no', 'false', 'f', 'n', '0', 'No', 'False'): return False else: raise argparse.ArgumentTypeError('Boolean value expected.') if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Crop DBSP spectra, \ prepare them for upload on Fritz, and plot them up. If no option \ is given, all spectra in the format ./ZTF*fits will be processed') parser.add_argument("--doPlot", action="store_true", default=False, help='Plot up the spectra') parser.add_argument('-n', dest='names', nargs='+', required=False, help='Names of the spectra; if not provided, \ all spectra in the format ./ZTF*fits will be processed', default=None) parser.add_argument('--suffix', dest='out_suffix', type=str, required=False, help="suffix for the output; \ default = '_crop.txt'", default="_crop.txt") args = parser.parse_args() # Input files if args.names is None: list_files = glob.glob("ZTF*fits") else: list_files = args.names print("The spectra currently range from 2,788A to 10,805A.") docrop = str2bool(input("Would you like to crop the spectra? \n")) # Define the ranges to crop the spectra if docrop is True: print("The default crop is from 3,200A to 10,000A and \ the interval [5190, 5572] is also removed.") default_crop = str2bool(input("Are you happy with this? \n")) if default_crop is True: ranges = [(3200, 5190), (5572, 10000)] else: happy = False while happy is False: nranges = int(input("Desired number of ranges: \n")) ranges = [] for nr in np.arange(nranges): raw_range = input(f"Range {nr+1} (two numbers, \ comma-separated): \n").split(",") new_range = tuple([int(s) for s in raw_range]) ranges.append(new_range) print(f"Your rages for cropping are {ranges}") happy = str2bool(input(f"Are you happy with these ranges?\n")) else: ranges = None # Iterate over the spectra for filename in list_files: hdulist = fits.open(filename) # No cropping if docrop is False: wav = [p[0] for p in hdulist[1].data] flux = [p[1] for p in hdulist[1].data] fluxerr = [p[2] for p in hdulist[1].data] else: wav, flux, fluxerr = [], [], [] for r in ranges: wav_crop = [p[0] for p in hdulist[1].data if (p[0] > r[0] and p[0] < r[1])] flux_crop = [p[1] for p in hdulist[1].data if (p[0] > r[0] and p[0] < r[1])] fluxerr_crop = [p[2] for p in hdulist[1].data if (p[0] > r[0] and p[0] < r[1])] wav += wav_crop flux += flux_crop fluxerr += fluxerr_crop # Plot if args.doPlot is True: plt.errorbar(wav, flux, yerr=fluxerr, color='grey', alpha=0.5) plt.plot(wav, flux, 'b') plt.xlabel("Wavelength") plt.ylabel("Flux") plt.show() plt.close() # Write the chopped spectra with open(filename.replace(".fits", args.out_suffix), 'w') as out: for w, f, fe in zip(wav, flux, fluxerr): out.write(f"{w}, {f}, {fe}\n")
{ "alphanum_fraction": 0.5428420775, "author": null, "avg_line_length": 36.8252427184, "converted": null, "ext": "py", "file": null, "hexsha": "0a8bbaac75f99b8e681a0a7db61f9c6ff972778d", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "5228af9ba929eaa407ff78cb00d0d7fb2d5bf43a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dekishalay/snippets", "max_forks_repo_path": "dbsp_crop_spec.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "5228af9ba929eaa407ff78cb00d0d7fb2d5bf43a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "dekishalay/snippets", "max_issues_repo_path": "dbsp_crop_spec.py", "max_line_length": 78, "max_stars_count": null, "max_stars_repo_head_hexsha": "5228af9ba929eaa407ff78cb00d0d7fb2d5bf43a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dekishalay/snippets", "max_stars_repo_path": "dbsp_crop_spec.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 974, "path": null, "reason": "import numpy,from astropy", "repo": null, "save_path": null, "sha": null, "size": 3793 }
"""Methods for testing the subroutines in the grouptheory module.""" import unittest as ut from phenum.grouptheory import ArrowPerm, RotPermList, OpList import pytest import numpy as np gpath = "tests/grouptheory/" def _read_fixOp_1D(fname): import os i = 1 growing = True out = [] while growing: if os.path.isfile(fname+"/_-"+str(i)+"-rot") or os.path.isfile(fname+"/_-"+str(i)+"-shift"): i += 1 else: growing = False for j in range(1,i): if os.path.isfile(fname+"/_-"+str(j)+"-rot"): rot = [np.transpose(t) for t in _read_float_3D(fname+"/_-"+str(j)+"-rot")] else: rot = None if os.path.isfile(fname+"/_-"+str(j)+"-shift"): shift = list(map(list,zip(*_read_float_2D(fname+"/_-"+str(j)+"-shift")))) else: shift = None temp = OpList(rot=rot,shift=shift) out.append(temp) return out def _read_RotPermList_1D(fname,arrowp = None): import os i = 1 growing = True out = [] while growing : if os.path.isfile(fname+"/_-"+str(i)+"-nL") or os.path.isfile(fname+"/_-"+str(i)+"-v") or os.path.isfile(fname+"/_-"+str(i)+"-RotIndx") or os.path.isfile(fname+"/_-"+str(i)+"-perm"): i += 1 else: growing = False for j in range(1,i): if os.path.isfile(fname+"/_-"+str(j)+"-nL"): nL = _read_int(fname+"/_-"+str(j)+"-nL") else: nL = None if os.path.isfile(fname+"/_-"+str(j)+"-v"): v = _read_float_3D(fname+"/_-"+str(j)+"-v") else: v = None if os.path.isfile(fname+"/_-"+str(j)+"-perm"): perm = _read_int_2D(fname+"/_-"+str(j)+"-perm") perm = [[i-1 for i in t] for t in perm] else: perm = None if arrowp == None: a_perm = None if os.path.isfile(fname+"/_-"+str(j)+"-RotIndx"): RotIndx = _read_int_1D(fname+"/_-"+str(j)+"-RotIndx") RotIndx = [i-1 for i in RotIndx] else: RotIndx = None temp = RotPermList(nL = nL, v = v, perm = perm, arrows=a_perm, RotIndx= RotIndx) out.append(temp) return out def _read_fixOp(fname): import os if os.path.isfile(fname+"/_-rot"): rot = _read_float_3D(fname+"/_-rot") else: rot = None if os.path.isfile(fname+"/_-shift"): shift = list(map(list,zip(*_read_float_2D(fname+"/_-shift")))) else: shift = None out = OpList(rot=rot,shift=shift) return out def _read_RotPermList(fname,arrowp = None): import os if os.path.isfile(fname+"/_-nL"): nL = _read_int(fname+"/_-nL") else: nL = None if os.path.isfile(fname+"/_-v"): v = _read_float_3D(fname+"/_-v") else: v = None if os.path.isfile(fname+"/_-perm"): perm = _read_int_2D(fname+"/_-perm") perm = [[i-1 for i in j] for j in perm] else: perm = None if arrowp == None: a_perm = None if os.path.isfile(fname+"/_-RotIndx"): RotIndx = _read_int_1D(fname+"/_-RotIndx") RotIndx = [i-1 for i in RotIndx] else: RotIndx = None out = RotPermList(nL = nL, v = v, perm = perm, arrows=a_perm, RotIndx= RotIndx) return out def _read_float_3D(fname): with open(fname,"r") as inf: temp = inf.readline() sizes = inf.readline() sizes = [int(x) for x in sizes.strip().split() if x !="##"] temp = inf.readline() in_data = [] in_temp = [] for line in inf: if "#" not in line: in_temp.append([float(i) for i in line.strip().split()]) else: in_data.append(in_temp) in_temp = [] in_data.append(in_temp) out = [] for i in range(sizes[2]): out_t = [] for j in range(sizes[1]): out_t.append([k[j][i] for k in in_data]) out.append(out_t) return(out) def _read_int_3D(fname): with open(fname,"r") as inf: temp = inf.readline() sizes = inf.readline() sizes = [int(x) for x in sizes.strip().split() if x !="##"] temp = inf.readline() in_data = [] in_temp = [] for line in inf: if "#" not in line: in_temp.append([int(i) for i in line.strip().split()]) else: in_data.append(in_temp) in_temp = [] in_data.append(in_temp) out = [] for i in range(sizes[2]): out_t = [] for j in range(sizes[1]): out_t.append([k[j][i] for k in in_data]) out.append(np.transpose(out_t)) return(out) def _read_output(test): values = [] with open("tests/grouptheory/"+test) as f: for line in f: values.append(eval(line)) return values def _read_float_2D(fname): array = [] with open(fname,"r") as f1: for line in f1: if "#" not in line: array.append([float(i) for i in line.strip().split()]) return array def _read_float_1D(fname): array = [] from os import getcwd with open(fname,"r") as f1: for line in f1: if "#" not in line: array = [float(i) for i in line.strip().split()] return array def _read_int_2D(fname): array = [] with open(fname,"r") as f1: for line in f1: if "#" not in line: array.append([int(i) for i in line.strip().split()]) return array def _read_int_1D(fname): array = [] with open(fname,"r") as f1: for line in f1: if "#" not in line: array = [int(i) for i in line.strip().split()] return array def _read_int(fname): with open(fname,"r") as f1: line = f1.readline() if "#" in line: line = f1.readline() val = int(line.strip()) return val def _read_float(fname): with open(fname,"r") as f1: line = f1.readline() if "#" in line: line = f1.readline() val = float(line.strip()) return val def _read_logical(fname): with open(fname,"r") as f1: line = f1.readline() if "#" in line: line = f1.readline() if "t" in line.lower(): val = True else: val = False return val class TestGetFullHNF(ut.TestCase): """ Tests of the get_full_HNF subroutine.""" def test_1(self): from phenum.grouptheory import get_full_HNF from numpy import array HNF = array([1,0,1,0,0,1]) out = [[1,0,0],[0,1,0],[0,0,1]] self.assertEqual(get_full_HNF(HNF),out) def test_2(self): from phenum.grouptheory import get_full_HNF from numpy import array HNF = array([2,1,2,1,0,4]) out = [[2,0,0],[1,2,0],[1,0,4]] self.assertEqual(get_full_HNF(HNF),out) def test_3(self): from phenum.grouptheory import get_full_HNF from numpy import array HNF = array([1,0,3,1,2,3]) out = [[1,0,0],[0,3,0],[1,2,3]] self.assertEqual(get_full_HNF(HNF),out) def test_4(self): from phenum.grouptheory import get_full_HNF from numpy import array HNF = [0,0,0,0,0,0] out = [[0,0,0],[0,0,0],[0,0,0]] self.assertEqual(get_full_HNF(HNF),out) def test_5(self): from phenum.grouptheory import get_full_HNF from numpy import array HNF = array([3,0,3,0,0,3]) out = [[3,0,0],[0,3,0],[0,0,3]] self.assertEqual(get_full_HNF(HNF),out) def test_1(self): from phenum.grouptheory import get_full_HNF from numpy import array HNF = array([1,1,2,0,2,2]) out = [[1,0,0],[1,2,0],[0,2,2]] self.assertEqual(get_full_HNF(HNF),out) def test_1(self): from phenum.grouptheory import get_full_HNF from numpy import array HNF = array([2,0,2,0,2,4]) out = [[2,0,0],[0,2,0],[0,2,4]] self.assertEqual(get_full_HNF(HNF),out) class TestSmithNormalForm(ut.TestCase): """ Tests of the SmithNormalForm subroutine.""" def test_1(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] out = ([[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_2(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, 0, 0], [0, 1, 0], [0, 1, 2]] out = ([[1, 0, 0], [0, 1, 0], [0, 0, 2]], [[1, 0, 0], [0, 1, 0], [0, -1, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_3(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, 0, 0], [0, 1, 0], [0, 0, 3]] out = ([[1, 0, 0], [0, 1, 0], [0, 0, 3]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_4(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, 0, 0], [0, 2, 0], [0, 0, 2]] out = ([[1, 0, 0], [0, 2, 0], [0, 0, 2]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_5(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, 0, 0], [0, 1, 0], [1, 2, 5]] out = ([[1, 0, 0], [0, 1, 0], [0, 0, 5]], [[1, 0, 0], [0, 1, 0], [-1, -2, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_6(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, 0, 0], [0, 1, 0], [2, 3, 6]] out = ([[1, 0, 0], [0, 1, 0], [0, 0, 6]], [[1, 0, 0], [0, 1, 0], [-2, -3, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_7(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, 0, 0], [0, 1, 0], [0, 6, 7]] out = ([[1, 0, 0], [0, 1, 0], [0, 0, 7]], [[1, 0, 0], [0, 1, 0], [0, -6, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_8(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, 0, 0], [1, 2, 0], [1, 0, 4]] out = ([[1, 0, 0], [0, 2, 0], [0, 0, 4]], [[1, 0, 0], [-1, 1, 0], [-1, 0, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_9(self): from phenum.grouptheory import SmithNormalForm HNF = [[2, 0, 0], [0, 2, 0], [0, 0, 2]] out = ([[2, 0, 0], [0, 2, 0], [0, 0, 2]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_10(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, 0, 0], [0, 1, 0], [1, 5, 10]] out = ([[1, 0, 0], [0, 1, 0], [0, 0, 10]], [[1, 0, 0], [0, 1, 0], [-1, -5, 1]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_11(self): from phenum.grouptheory import SmithNormalForm HNF = [[-1, 0, 0], [0, 1, 0], [0, 0, 1]] out = () with pytest.raises(ValueError): self.assertEqual(SmithNormalForm(HNF),out) def test_12(self): from phenum.grouptheory import SmithNormalForm HNF = [[0, 1, 0], [0, 0, 1], [1, 0, 0]] out = ([[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[0, 0, 1], [1, 0, 0], [0, 1, 0]], [[1, 0, 0], [0, 1, 0], [0, 0, 1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_13(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, -1, -2], [1, 2, -3], [1, 2, 4]] out = ([[1, 0, 0], [0, 1, 0], [0, 0, 21]], [[1, 0, 0], [-1, 1, 0], [-7, 6, 1]], [[1, -2, 7], [0, 0, 1], [0, -1, 3]]) self.assertEqual(SmithNormalForm(HNF),out) def test_14(self): from phenum.grouptheory import SmithNormalForm HNF = [[-1, -2, -3], [-1, -1, -2], [-1, -2, -4]] out = ([[1, 0, 0], [0, 1, 0], [0, 0, 1]], [[1, 0, 0], [-1, 1, 0], [-1, 0, 1]], [[-1, -2, 1], [0, 1, 1], [0, 0, -1]]) self.assertEqual(SmithNormalForm(HNF),out) def test_15(self): from phenum.grouptheory import SmithNormalForm HNF = [[1, 2.5, 0], [0, 1.5, 1.66], [1.5, 1.25, 1.3]] with pytest.raises(ValueError): SmithNormalForm(HNF) def test_16(self): from phenum.grouptheory import SmithNormalForm HNF = [[2, 0, 0], [0, 2, 0], [0, 0, 1]] out = ([[1, 0, 0], [0, 2, 0], [0, 0, 2]], [[1, 0, 1], [0, 1, 0], [-1, 0, 0]], [[0, 0, -1], [0, 1, 0], [1, 0, 2]]) self.assertEqual(SmithNormalForm(HNF),out) def test_17(self): """Test of the bug reported in issue #56.""" from phenum.grouptheory import SmithNormalForm HNF = [[1,2,4],[3,3,4],[3,4,2]] S, L, R = SmithNormalForm(HNF) self.assertTrue(np.allclose(list(np.dot(np.dot(L,HNF),R)),S)) def test_17(self): """Test of the bug reported in issue #61.""" from phenum.grouptheory import SmithNormalForm HNF = [[41,0,0],[0,21,0],[0,0,41]] out = ([[1, 0, 0], [0, 41, 0], [0, 0, 861]], [[1, 1, 0], [-42, -41, 1], [42, 41, 0]], [[-1, 0, 21], [2, 0, -41], [0, 1, 21]]) self.assertEqual(SmithNormalForm(HNF),out) class TestAGroup(ut.TestCase): """ Tests of the a_group subroutine.""" def test_1(self): from phenum.grouptheory import a_group trans = [[0,1],[1,0]] rots = [[[0,1],[0,1,2,3,4,5]],[[1,0],[2,3,0,1,5,4]],[[1,0],[2,1,0,3,5,4]],[[0,1],[0,3,2,1,5,4]]] out = _read_output("agroup.out.1") self.assertEqual(a_group(trans,rots),out) def test_2(self): from phenum.grouptheory import a_group trans = [[j-1 for j in i] for i in [[1, 2, 3, 4], [2, 1, 4, 3], [3, 4, 1, 2], [4, 3, 2, 1]]] rots = [[[j-1 for j in i] for i in t] for t in [[[1, 2, 3, 4], [1, 2, 3, 4, 5, 6]], [[1, 4, 3, 2], [1, 3, 2, 4, 6, 5]], [[1, 2, 3, 4], [4, 2, 3, 1, 5, 6]], [[1, 4, 3, 2], [4, 3, 2, 1, 6, 5]], [[1, 2, 3, 4], [1, 5, 3, 4, 2, 6]], [[1, 4, 3, 2], [1, 3, 5, 4, 6, 2]], [[1, 2, 3, 4], [4, 5, 3, 1, 2, 6]], [[1, 4, 3, 2], [4, 3, 5, 1, 6, 2]], [[1, 2, 3, 4], [1, 2, 6, 4, 5, 3]], [[1, 4, 3, 2], [1, 6, 2, 4, 3, 5]], [[1, 2, 3, 4], [4, 2, 6, 1, 5, 3]], [[1, 4, 3, 2], [4, 6, 2, 1, 3, 5]], [[1, 2, 3, 4], [1, 5, 6, 4, 2, 3]], [[1, 4, 3, 2], [1, 6, 5, 4, 3, 2]], [[1, 2, 3, 4], [4, 5, 6, 1, 2, 3]], [[1, 4, 3, 2], [4, 6, 5, 1, 3, 2]]]] out = _read_output("agroup.out.2") self.assertEqual(a_group(trans,rots),out) def test_3(self): from phenum.grouptheory import a_group trans = [[j-1 for j in i] for i in [[1, 2, 3, 4, 5, 6, 7, 8], [2, 1, 4, 3, 6, 5, 8, 7], [3, 4, 5, 6, 7, 8, 1, 2], [4, 3, 6, 5, 8, 7, 2, 1], [5, 6, 7, 8, 1, 2, 3, 4], [6, 5, 8, 7, 2, 1, 4, 3], [7, 8, 1, 2, 3, 4, 5, 6], [8, 7, 2, 1, 4, 3, 6, 5]]] rots = [[[j-1 for j in i] for i in t] for t in [[[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6]], [[1, 2, 3, 4, 5, 6, 7, 8], [4, 2, 3, 1, 5, 6]], [[1, 2, 3, 4, 5, 6, 7, 8], [1, 5, 3, 4, 2, 6]], [[1, 2, 3, 4, 5, 6, 7, 8], [4, 5, 3, 1, 2, 6]], [[1, 2, 7, 8, 5, 6, 3, 4], [1, 2, 6, 4, 5, 3]], [[1, 2, 7, 8, 5, 6, 3, 4], [4, 2, 6, 1, 5, 3]], [[1, 2, 7, 8, 5, 6, 3, 4], [1, 5, 6, 4, 2, 3]], [[1, 2, 7, 8, 5, 6, 3, 4], [4, 5, 6, 1, 2, 3]]]] out = _read_output("agroup.out.3") self.assertEqual(a_group(trans,rots),out) def test_4(self): from phenum.grouptheory import a_group trans =[[j - 1 for j in i] for i in[[1,2,3,4,5,6,7,8], [2,1,4,3,6,5,8,7], [3,4,5,6,7,8,1,2], [4,3,6,5,8,7,2,1], [5,6,7,8,1,2,3,4], [6,5,8,7,2,1,4,3], [7,8,1,2,3,4,5,6], [8,7,2,1,4,3,6,5]]] rots = [[[0,1,2,3,4,5,6,7],[0,1,2,3]],[[0,1,2,3,4,5,6,7],[2,1,0,3]],[[0,1,6,7,4,5,2,3],[0,3,2,1]],[[0,1,6,7,4,5,2,3],[2,3,0,1]]] out = _read_output("agroup.out.4") self.assertEqual(a_group(trans,rots),out) def test_5(self): from phenum.grouptheory import a_group trans =[[j - 1 for j in i] for i in[[1, 2, 3, 4, 5, 6, 7, 8], [2, 1, 4, 3, 6, 5, 8, 7], [3, 4, 5, 6, 7, 8, 1, 2], [4, 3, 6, 5, 8, 7, 2, 1], [5, 6, 7, 8, 1, 2, 3, 4], [6, 5, 8, 7, 2, 1, 4, 3], [7, 8, 1, 2, 3, 4, 5, 6], [8, 7, 2, 1, 4, 3, 6, 5]]] rots = [[[0,1,2,3,4,5,6,7],[0,1,2,3]],[[0,1,2,3,4,5,6,7],[2,1,0,3]],[[0,1,6,7,4,5,2,3],[0,3,2,1]],[[0,1,6,7,4,5,2,3],[2,3,0,1]]] out = _read_output("agroup.out.5") self.assertEqual(a_group(trans,rots),out) class TestAGroupGen(ut.TestCase): """ Tests of the a_group subroutine.""" def test_1(self): from phenum.grouptheory import a_group_gen trans = [[0,1],[1,0]] rots = [[[0,1],[0,1,2,3,4,5]],[[1,0],[2,3,0,1,5,4]],[[1,0],[2,1,0,3,5,4]],[[0,1],[0,3,2,1,5,4]]] out = _read_output("agroupgen.out.1") self.assertEqual(a_group_gen(trans,rots),out) def test_2(self): from phenum.grouptheory import a_group_gen trans = [[j-1 for j in i] for i in [[1, 2, 3, 4], [2, 1, 4, 3], [3, 4, 1, 2], [4, 3, 2, 1]]] rots = [[[j-1 for j in i] for i in t] for t in [[[1, 2, 3, 4], [1, 2, 3, 4, 5, 6]], [[1, 4, 3, 2], [1, 3, 2, 4, 6, 5]], [[1, 2, 3, 4], [4, 2, 3, 1, 5, 6]], [[1, 4, 3, 2], [4, 3, 2, 1, 6, 5]], [[1, 2, 3, 4], [1, 5, 3, 4, 2, 6]], [[1, 4, 3, 2], [1, 3, 5, 4, 6, 2]], [[1, 2, 3, 4], [4, 5, 3, 1, 2, 6]], [[1, 4, 3, 2], [4, 3, 5, 1, 6, 2]], [[1, 2, 3, 4], [1, 2, 6, 4, 5, 3]], [[1, 4, 3, 2], [1, 6, 2, 4, 3, 5]], [[1, 2, 3, 4], [4, 2, 6, 1, 5, 3]], [[1, 4, 3, 2], [4, 6, 2, 1, 3, 5]], [[1, 2, 3, 4], [1, 5, 6, 4, 2, 3]], [[1, 4, 3, 2], [1, 6, 5, 4, 3, 2]], [[1, 2, 3, 4], [4, 5, 6, 1, 2, 3]], [[1, 4, 3, 2], [4, 6, 5, 1, 3, 2]]]] out = _read_output("agroupgen.out.2") self.assertEqual(a_group_gen(trans,rots),out) def test_3(self): from phenum.grouptheory import a_group_gen trans = [[j-1 for j in i] for i in [[1, 2, 3, 4, 5, 6, 7, 8], [2, 1, 4, 3, 6, 5, 8, 7], [3, 4, 5, 6, 7, 8, 1, 2], [4, 3, 6, 5, 8, 7, 2, 1], [5, 6, 7, 8, 1, 2, 3, 4], [6, 5, 8, 7, 2, 1, 4, 3], [7, 8, 1, 2, 3, 4, 5, 6], [8, 7, 2, 1, 4, 3, 6, 5]]] rots = [[[j-1 for j in i] for i in t] for t in [[[1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6]], [[1, 2, 3, 4, 5, 6, 7, 8], [4, 2, 3, 1, 5, 6]], [[1, 2, 3, 4, 5, 6, 7, 8], [1, 5, 3, 4, 2, 6]], [[1, 2, 3, 4, 5, 6, 7, 8], [4, 5, 3, 1, 2, 6]], [[1, 2, 7, 8, 5, 6, 3, 4], [1, 2, 6, 4, 5, 3]], [[1, 2, 7, 8, 5, 6, 3, 4], [4, 2, 6, 1, 5, 3]], [[1, 2, 7, 8, 5, 6, 3, 4], [1, 5, 6, 4, 2, 3]], [[1, 2, 7, 8, 5, 6, 3, 4], [4, 5, 6, 1, 2, 3]]]] out = _read_output("agroupgen.out.3") self.assertEqual(a_group_gen(trans,rots),out) def test_4(self): from phenum.grouptheory import a_group_gen trans =[[j - 1 for j in i] for i in[[1,2,3,4,5,6,7,8], [2,1,4,3,6,5,8,7], [3,4,5,6,7,8,1,2], [4,3,6,5,8,7,2,1], [5,6,7,8,1,2,3,4], [6,5,8,7,2,1,4,3], [7,8,1,2,3,4,5,6], [8,7,2,1,4,3,6,5]]] rots = [[[0,1,2,3,4,5,6,7],[0,1,2,3]],[[0,1,2,3,4,5,6,7],[2,1,0,3]],[[0,1,6,7,4,5,2,3],[0,3,2,1]],[[0,1,6,7,4,5,2,3],[2,3,0,1]]] out = _read_output("agroupgen.out.4") self.assertEqual(a_group_gen(trans,rots),out) def test_5(self): from phenum.grouptheory import a_group_gen trans =[[j - 1 for j in i] for i in[[1, 2, 3, 4, 5, 6, 7, 8], [2, 1, 4, 3, 6, 5, 8, 7], [3, 4, 5, 6, 7, 8, 1, 2], [4, 3, 6, 5, 8, 7, 2, 1], [5, 6, 7, 8, 1, 2, 3, 4], [6, 5, 8, 7, 2, 1, 4, 3], [7, 8, 1, 2, 3, 4, 5, 6], [8, 7, 2, 1, 4, 3, 6, 5]]] rots = [[[0,1,2,3,4,5,6,7],[0,1,2,3]],[[0,1,2,3,4,5,6,7],[2,1,0,3]],[[0,1,6,7,4,5,2,3],[0,3,2,1]],[[0,1,6,7,4,5,2,3],[2,3,0,1]]] out = _read_output("agroupgen.out.5") self.assertEqual(a_group_gen(trans,rots),out) class TestMakeMemberList(ut.TestCase): """Tests of the _make_member_list subroutine.""" def test_1(self): from phenum.grouptheory import _make_member_list case = 1 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_2(self): from phenum.grouptheory import _make_member_list case = 2 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_3(self): from phenum.grouptheory import _make_member_list case = 3 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_4(self): from phenum.grouptheory import _make_member_list case = 4 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_5(self): from phenum.grouptheory import _make_member_list case = 5 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_6(self): from phenum.grouptheory import _make_member_list case = 6 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_7(self): from phenum.grouptheory import _make_member_list case = 7 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_8(self): from phenum.grouptheory import _make_member_list case = 8 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_9(self): from phenum.grouptheory import _make_member_list case = 9 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_10(self): from phenum.grouptheory import _make_member_list case = 10 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_11(self): from phenum.grouptheory import _make_member_list case = 11 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_12(self): from phenum.grouptheory import _make_member_list case = 12 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_13(self): from phenum.grouptheory import _make_member_list case = 13 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_14(self): from phenum.grouptheory import _make_member_list case = 14 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_15(self): from phenum.grouptheory import _make_member_list case = 15 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_16(self): from phenum.grouptheory import _make_member_list case = 16 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_17(self): from phenum.grouptheory import _make_member_list case = 17 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_18(self): from phenum.grouptheory import _make_member_list case = 18 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_19(self): from phenum.grouptheory import _make_member_list case = 19 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) def test_20(self): from phenum.grouptheory import _make_member_list case = 20 n = _read_float_1D(gpath+"make_member_list_n.in."+str(case)) out = list(map(list,zip(*_read_float_2D(gpath+"make_member_list_p.out."+str(case))))) self.assertTrue(np.allclose(_make_member_list(n),out)) class TestFindPermutationOfGroup(ut.TestCase): """Tests of the _find_permutation_of_group subroutine.""" def test_1(self): from phenum.grouptheory import _find_permutation_of_group case = 1 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_2(self): from phenum.grouptheory import _find_permutation_of_group case = 2 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_3(self): from phenum.grouptheory import _find_permutation_of_group case = 3 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_4(self): from phenum.grouptheory import _find_permutation_of_group case = 4 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_5(self): from phenum.grouptheory import _find_permutation_of_group case = 5 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_6(self): from phenum.grouptheory import _find_permutation_of_group case = 6 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_7(self): from phenum.grouptheory import _find_permutation_of_group case = 7 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_8(self): from phenum.grouptheory import _find_permutation_of_group case = 8 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_9(self): from phenum.grouptheory import _find_permutation_of_group case = 9 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_10(self): from phenum.grouptheory import _find_permutation_of_group case = 10 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_11(self): from phenum.grouptheory import _find_permutation_of_group case = 11 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_12(self): from phenum.grouptheory import _find_permutation_of_group case = 12 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_13(self): from phenum.grouptheory import _find_permutation_of_group case = 13 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_14(self): from phenum.grouptheory import _find_permutation_of_group case = 14 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_15(self): from phenum.grouptheory import _find_permutation_of_group case = 15 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_16(self): from phenum.grouptheory import _find_permutation_of_group case = 16 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_17(self): from phenum.grouptheory import _find_permutation_of_group case = 17 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_18(self): from phenum.grouptheory import _find_permutation_of_group case = 18 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_19(self): from phenum.grouptheory import _find_permutation_of_group case = 19 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) def test_20(self): from phenum.grouptheory import _find_permutation_of_group case = 20 g = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_g.in."+str(case))))) gp = list(map(list,zip(*_read_float_2D(gpath+"find_permutation_of_group_gp.in."+str(case))))) out = [i-1 for i in _read_int_1D(gpath+"find_permutation_of_group_perm.out."+str(case))] self.assertEqual(_find_permutation_of_group(g,gp),out) class TestIsEquivLattice(ut.TestCase): """Tests of the _is_equiv_lattice subroutine.""" def test_1(self): from phenum.grouptheory import _is_equiv_lattice case = 1 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_2(self): from phenum.grouptheory import _is_equiv_lattice case = 2 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_3(self): from phenum.grouptheory import _is_equiv_lattice case = 3 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_4(self): from phenum.grouptheory import _is_equiv_lattice case = 4 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_5(self): from phenum.grouptheory import _is_equiv_lattice case = 5 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_6(self): from phenum.grouptheory import _is_equiv_lattice case = 6 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_7(self): from phenum.grouptheory import _is_equiv_lattice case = 7 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_8(self): from phenum.grouptheory import _is_equiv_lattice case = 8 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_9(self): from phenum.grouptheory import _is_equiv_lattice case = 9 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_10(self): from phenum.grouptheory import _is_equiv_lattice case = 10 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_11(self): from phenum.grouptheory import _is_equiv_lattice case = 11 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_12(self): from phenum.grouptheory import _is_equiv_lattice case = 12 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_13(self): from phenum.grouptheory import _is_equiv_lattice case = 13 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_14(self): from phenum.grouptheory import _is_equiv_lattice case = 14 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_15(self): from phenum.grouptheory import _is_equiv_lattice case = 15 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_16(self): from phenum.grouptheory import _is_equiv_lattice case = 16 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_17(self): from phenum.grouptheory import _is_equiv_lattice case = 17 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_18(self): from phenum.grouptheory import _is_equiv_lattice case = 18 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_19(self): from phenum.grouptheory import _is_equiv_lattice case = 19 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) def test_20(self): from phenum.grouptheory import _is_equiv_lattice case = 20 lat1 = _read_float_2D(gpath+"is_equiv_lattice_lat1.in."+str(case)) lat2 = _read_float_2D(gpath+"is_equiv_lattice_lat2.in."+str(case)) eps = _read_float(gpath+"is_equiv_lattice_eps.in."+str(case)) out = _read_logical(gpath+"is_equiv_lattice.out."+str(case)) self.assertEqual(_is_equiv_lattice(lat1,lat2,eps),out) class TestGetSLVFixingOperations(ut.TestCase): """Tests of the _get_sLV_fixing_operations subroutine.""" def _compare_outputs(self,out1,out2): fix1 = out1[0] fix2 = out2[0] rot1 = out1[1] rot2 = out2[1] deg1 = out1[2] deg2 = out2[2] self.assertEqual(deg1,deg2) if len(fix1.rot) == len(fix2.rot): for i in range(len(fix1.rot)): for j in range(3): for k in range(3): self.assertAlmostEqual(fix1.rot[i][j][k],fix2.rot[i][j][k],places=12) else: self.assertEqual(len(fix1.rot),len(fix2.rot)) if len(fix1.shift) == len(fix2.shift): for i in range(len(fix1.shift)): for j in range(3): self.assertAlmostEqual(fix1.shift[i][j],fix2.shift[i][j],places=12) else: self.assertEqual(len(fix1.shift),len(fix2.shift)) self.assertEqual(rot1.nL,rot2.nL) self.assertEqual(rot1.RotIndx, rot2.RotIndx) if (rot1.v != None) and (rot2.v != None): if len(rot1.v) == len(rot2.v): for i in range(len(rot1.v)): for j in range(len(rot1.v[i])): for k in range(len(rot1.v[i][j])): self.assertAlmostEqual(rot1.v[i][j][k],rot2.v[i][j][k],places=12) else: self.assertEqual(len(rot1.v),len(rot2.v)) else: self.assertEqual(rot1.v,rot2.v) # if (rot1.perm.site_perm != None) and (rot2.perm.site_perm != None): # if len(rot1.perm.site_perm) == len(rot2.perm.site_perm): # for i in range(len(rot1.perm.site_perm)): # for j in range(len(rot1.perm.site_perm[i])): # self.assertEqual(rot1.perm.site_perm[i][j],rot2.perm.site_perm[i][j]) # else: # self.assertEqual(len(rot1.perm.site_perm),len(rot2.perm.site_perm)) # else: # self.assertEqual(rot1.perm.site_perm,rot2.perm.site_perm) if (rot1.perm.arrow_perm != None) and (rot2.perm.arrow_perm != None): if len(rot1.perm.arrow_perm) == len(rot2.perm.arrow_perm): for i in range(len(rot1.perm.arrow_perm)): for j in range(len(rot1.perm.arrow_perm[i])): self.assertEqual(rot1.perm.arrow_perm[i][j],rot2.perm.arrow_perm[i][j]) else: self.assertEqual(len(rot1.perm.arrow_perm),len(rot2.perm.arrow_perm)) else: self.assertEqual(rot1.perm.arrow_perm,rot2.perm.arrow_perm) def test_1(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 1 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_2(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 10 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_3(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 20 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_4(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 30 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_5(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 40 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_6(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 50 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_7(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 60 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_8(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 70 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_9(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 80 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_10(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 90 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_11(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 100 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_12(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 110 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_13(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 120 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_14(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 130 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_15(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 140 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) def test_16(self): from phenum.grouptheory import _get_sLV_fixing_operations case = 150 HNF = _read_int_2D(gpath+"get_sLV_fixing_operations_HNF.in."+str(case)) pLV = np.transpose(_read_float_2D(gpath+"get_sLV_fixing_operations_pLV.in."+str(case))) nD = _read_int(gpath+"get_sLV_fixing_operations_nD.in."+str(case)) rot = _read_float_3D(gpath+"get_sLV_fixing_operations_rot.in."+str(case)) shift = list(map(list,zip(*_read_float_2D(gpath+"get_sLV_fixing_operations_shift.in."+str(case))))) eps = _read_float(gpath+"get_sLV_fixing_operations_eps.in."+str(case)) dPerm = _read_RotPermList(gpath+"get_sLV_fixing_operations_dPerm.in."+str(case)) fixOp, rotPerm, degeneracy = _get_sLV_fixing_operations(HNF,pLV,rot,shift,dPerm,eps) rotPerm_out = _read_RotPermList(gpath+"get_sLV_fixing_operations_rotPerm.out."+str(case)) degen_out = _read_int(gpath+"get_sLV_fixing_operations_degeneracy.out."+str(case)) fixOp_out = _read_fixOp(gpath+"get_sLV_fixing_operations_fixOp.out."+str(case)) self._compare_outputs([fixOp,rotPerm,degeneracy],[fixOp_out,rotPerm_out,degen_out]) class TestMapDvectorPermutation(ut.TestCase): """Tests of the _map_dvector_permutation subroutine.""" def _compare_outputs(self,out1,out2): if len(out1) == len(out2): for i in range(len(out1)): self.assertEqual(out1[i],out2[i]) else: self.assertEqual(len(out1),len(out2)) def test_1(self): from phenum.grouptheory import _map_dvector_permutation case = 1 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_2(self): from phenum.grouptheory import _map_dvector_permutation case = 10 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_3(self): from phenum.grouptheory import _map_dvector_permutation case = 20 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_4(self): from phenum.grouptheory import _map_dvector_permutation case = 30 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_5(self): from phenum.grouptheory import _map_dvector_permutation case = 40 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_6(self): from phenum.grouptheory import _map_dvector_permutation case = 50 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_7(self): from phenum.grouptheory import _map_dvector_permutation case = 60 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_8(self): from phenum.grouptheory import _map_dvector_permutation case = 70 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_9(self): from phenum.grouptheory import _map_dvector_permutation case = 80 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_10(self): from phenum.grouptheory import _map_dvector_permutation case = 90 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_11(self): from phenum.grouptheory import _map_dvector_permutation case = 100 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_12(self): from phenum.grouptheory import _map_dvector_permutation case = 110 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_13(self): from phenum.grouptheory import _map_dvector_permutation case = 120 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_14(self): from phenum.grouptheory import _map_dvector_permutation case = 130 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_15(self): from phenum.grouptheory import _map_dvector_permutation case = 140 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_16(self): from phenum.grouptheory import _map_dvector_permutation case = 150 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_17(self): from phenum.grouptheory import _map_dvector_permutation case = 160 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_18(self): from phenum.grouptheory import _map_dvector_permutation case = 170 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_19(self): from phenum.grouptheory import _map_dvector_permutation case = 180 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_20(self): from phenum.grouptheory import _map_dvector_permutation case = 190 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) def test_21(self): from phenum.grouptheory import _map_dvector_permutation case = 200 rd = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_rd.in."+str(case))))) d = list(map(list,zip(*_read_float_2D(gpath+"map_dvector_permutation_d.in."+str(case))))) eps = _read_float(gpath+"map_dvector_permutation_eps.in."+str(case)) n = len(rd) out = _read_int_1D(gpath+"map_dvector_permutation_RP.out."+str(case)) out = [i-1 for i in out] self._compare_outputs(_map_dvector_permutation(rd,d,eps),out) class TestFindMinmaxIndices(ut.TestCase): """Tests of the _find_minmax_indices subroutine.""" def test_1(self): from phenum.grouptheory import _find_minmax_indices case = 1 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) def test_2(self): from phenum.grouptheory import _find_minmax_indices case = 5 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) def test_3(self): from phenum.grouptheory import _find_minmax_indices case = 10 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) def test_4(self): from phenum.grouptheory import _find_minmax_indices case = 15 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) def test_5(self): from phenum.grouptheory import _find_minmax_indices case = 20 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) def test_6(self): from phenum.grouptheory import _find_minmax_indices case = 25 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) def test_7(self): from phenum.grouptheory import _find_minmax_indices case = 30 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) def test_8(self): from phenum.grouptheory import _find_minmax_indices case = 35 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) def test_9(self): from phenum.grouptheory import _find_minmax_indices case = 40 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) def test_10(self): from phenum.grouptheory import _find_minmax_indices case = 45 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) def test_11(self): from phenum.grouptheory import _find_minmax_indices case = 50 invec = _read_int_1D(gpath+"get_minmax_indices_invec.in."+str(case)) min,max = _find_minmax_indices(invec) min_out = _read_int(gpath+"get_minmax_indices_min.out."+str(case))-1 max_out = _read_int(gpath+"get_minmax_indices_max.out."+str(case))-1 self.assertEqual(min,min_out) self.assertEqual(max,max_out) class TestGetDvectorPermutations(ut.TestCase): """Tests of the _get_dvector_permutations subroutine.""" def _compare_outputs(self,rot1,rot2): # self.assertEqual(rot1.nL,rot2.nL) self.assertEqual(rot1.RotIndx, rot2.RotIndx) if (rot1.v != None) and (rot2.v != None): if len(rot1.v) == len(rot2.v): for i in range(len(rot1.v)): for j in range(len(rot1.v[i])): for k in range(len(rot1.v[i][j])): self.assertAlmostEqual(rot1.v[i][j][k],rot2.v[i][j][k],places=12) else: self.assertEqual(len(rot1.v),len(rot2.v)) else: self.assertEqual(rot1.v,rot2.v) if (rot1.perm.site_perm != None) and (rot2.perm.site_perm != None): if len(rot1.perm.site_perm) == len(rot2.perm.site_perm): for i in range(len(rot1.perm.site_perm)): for j in range(len(rot1.perm.site_perm[i])): self.assertEqual(rot1.perm.site_perm[i][j],rot2.perm.site_perm[i][j]) else: self.assertEqual(len(rot1.perm.site_perm),len(rot2.perm.site_perm)) else: self.assertEqual(rot1.perm.site_perm,rot2.perm.site_perm) if (rot1.perm.arrow_perm != None) and (rot2.perm.arrow_perm != None): if len(rot1.perm.arrow_perm) == len(rot2.perm.arrow_perm): for i in range(len(rot1.perm.arrow_perm)): for j in range(len(rot1.perm.arrow_perm[i])): self.assertEqual(rot1.perm.arrow_perm[i][j],rot2.perm.arrow_perm[i][j]) else: self.assertEqual(len(rot1.perm.arrow_perm),len(rot2.perm.arrow_perm)) else: self.assertEqual(rot1.perm.arrow_perm,rot2.perm.arrow_perm) def test_1(self): from phenum.grouptheory import _get_dvector_permutations case = 1 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_2(self): from phenum.grouptheory import _get_dvector_permutations case = 2 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_3(self): from phenum.grouptheory import _get_dvector_permutations case = 3 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_4(self): from phenum.grouptheory import _get_dvector_permutations case = 4 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_5(self): from phenum.grouptheory import _get_dvector_permutations case = 5 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_6(self): from phenum.grouptheory import _get_dvector_permutations case = 6 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_7(self): from phenum.grouptheory import _get_dvector_permutations case = 7 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_8(self): from phenum.grouptheory import _get_dvector_permutations case = 8 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_9(self): from phenum.grouptheory import _get_dvector_permutations case = 9 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) self._compare_outputs(dRPList,dRPList_out) def test_10(self): from phenum.grouptheory import _get_dvector_permutations case = 10 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_11(self): from phenum.grouptheory import _get_dvector_permutations case = 11 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_12(self): from phenum.grouptheory import _get_dvector_permutations case = 12 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_13(self): from phenum.grouptheory import _get_dvector_permutations case = 13 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_14(self): from phenum.grouptheory import _get_dvector_permutations case = 14 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_15(self): from phenum.grouptheory import _get_dvector_permutations case = 15 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_16(self): from phenum.grouptheory import _get_dvector_permutations case = 16 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_17(self): from phenum.grouptheory import _get_dvector_permutations case = 17 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_18(self): from phenum.grouptheory import _get_dvector_permutations case = 18 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_19(self): from phenum.grouptheory import _get_dvector_permutations case = 19 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) def test_20(self): from phenum.grouptheory import _get_dvector_permutations case = 20 par_lat = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pLV.in."+str(case))))) bas_vecs = list(map(list,zip(*_read_float_2D(gpath+"get_dvector_permutations_pd.in."+str(case))))) LatDim = _read_int(gpath+"get_dvector_permutations_LatDim.in."+str(case)) eps = _read_float(gpath+"get_dvector_permutations_eps.in."+str(case)) dRPList_out = _read_RotPermList(gpath+"get_dvector_permutations_dRPList.out."+str(case)) dRPList = _get_dvector_permutations(par_lat,bas_vecs,LatDim,eps) self._compare_outputs(dRPList,dRPList_out) class TestGetRotationPermsLists(ut.TestCase): """Tests of the _get_rotation_perms_lists subroutine.""" def _compare_outputs(self,out1,out2): if len(out1) == len(out2): for t in range(len(out1)): rot1 = out1[t] rot2 = out2[t] if rot1.nL == 0 or rot1.nL == None: if rot2.nL == 0 or rot2.nL == None: self.assertEqual(True,True) else: self.assertEqual(rot1.nL,rot2.nL) else: self.assertEqual(rot1.nL,rot2.nL) self.assertEqual(rot1.RotIndx, rot2.RotIndx) if (rot1.v != None) and (rot2.v != None): if len(rot1.v) == len(rot2.v): for i in range(len(rot1.v)): for j in range(len(rot1.v[i])): for k in range(len(rot1.v[i][j])): self.assertAlmostEqual(rot1.v[i][j][k],rot2.v[i][j][k],places=12) else: self.assertEqual(len(rot1.v),len(rot2.v)) else: self.assertEqual(rot1.v,rot2.v) if (rot1.perm.site_perm != None) and (rot2.perm.site_perm != None): if len(rot1.perm.site_perm) == len(rot2.perm.site_perm): rot1.perm.site_perm = sorted(rot1.perm.site_perm) rot2.perm.site_perm = sorted(rot2.perm.site_perm) for i in range(len(rot1.perm.site_perm)): for j in range(len(rot1.perm.site_perm[i])): self.assertEqual(rot1.perm.site_perm[i][j],rot2.perm.site_perm[i][j]) else: self.assertEqual(len(rot1.perm.site_perm),len(rot2.perm.site_perm)) else: self.assertEqual(rot1.perm.site_perm,rot2.perm.site_perm) if (rot1.perm.arrow_perm != None) and (rot2.perm.arrow_perm != None): if len(rot1.perm.arrow_perm) == len(rot2.perm.arrow_perm): for i in range(len(rot1.perm.arrow_perm)): for j in range(len(rot1.perm.arrow_perm[i])): self.assertEqual(rot1.perm.arrow_perm[i][j],rot2.perm.arrow_perm[i][j]) else: self.assertEqual(len(rot1.perm.arrow_perm),len(rot2.perm.arrow_perm)) else: self.assertEqual(rot1.perm.arrow_perm,rot2.perm.arrow_perm) else: self.assertEqual(len(out1),len(out2)) def test_1(self): from phenum.grouptheory import _get_rotation_perms_lists case = 1 A = [[10,0,0],[0,10,0],[0,0,10]] HNF = [[[1,0,0],[0,1,0],[0,0,1]]] L = [[[1,0,0],[0,1,0],[0,0,1]]] SNF = [[[1,0,0],[0,1,0],[0,0,1]]] Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) for out in out1: out.perm.arrow_perm = None out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) self._compare_outputs(out1,out2) def test_2(self): from phenum.grouptheory import _get_rotation_perms_lists case = 2 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) for out in out1: out.perm.arrow_perm = None out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) self._compare_outputs(out1,out2) def test_3(self): from phenum.grouptheory import _get_rotation_perms_lists case = 3 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_4(self): from phenum.grouptheory import _get_rotation_perms_lists case = 4 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_5(self): from phenum.grouptheory import _get_rotation_perms_lists case = 5 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_6(self): from phenum.grouptheory import _get_rotation_perms_lists case = 6 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_7(self): from phenum.grouptheory import _get_rotation_perms_lists case = 7 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_8(self): from phenum.grouptheory import _get_rotation_perms_lists case = 8 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_9(self): from phenum.grouptheory import _get_rotation_perms_lists case = 9 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_10(self): from phenum.grouptheory import _get_rotation_perms_lists case = 10 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_11(self): from phenum.grouptheory import _get_rotation_perms_lists case = 11 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_12(self): from phenum.grouptheory import _get_rotation_perms_lists case = 12 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_13(self): from phenum.grouptheory import _get_rotation_perms_lists case = 13 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_14(self): from phenum.grouptheory import _get_rotation_perms_lists case = 14 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_15(self): from phenum.grouptheory import _get_rotation_perms_lists case = 15 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_16(self): from phenum.grouptheory import _get_rotation_perms_lists case = 16 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_17(self): from phenum.grouptheory import _get_rotation_perms_lists case = 17 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_18(self): from phenum.grouptheory import _get_rotation_perms_lists case = 18 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_19(self): from phenum.grouptheory import _get_rotation_perms_lists case = 19 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_20(self): from phenum.grouptheory import _get_rotation_perms_lists case = 20 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_21(self): from phenum.grouptheory import _get_rotation_perms_lists case = 21 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_22(self): from phenum.grouptheory import _get_rotation_perms_lists case = 22 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_23(self): from phenum.grouptheory import _get_rotation_perms_lists case = 23 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_24(self): from phenum.grouptheory import _get_rotation_perms_lists case = 24 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_25(self): from phenum.grouptheory import _get_rotation_perms_lists case = 25 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_26(self): from phenum.grouptheory import _get_rotation_perms_lists case = 26 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_27(self): from phenum.grouptheory import _get_rotation_perms_lists case = 27 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_28(self): from phenum.grouptheory import _get_rotation_perms_lists case = 28 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_29(self): from phenum.grouptheory import _get_rotation_perms_lists case = 29 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_30(self): from phenum.grouptheory import _get_rotation_perms_lists case = 30 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_31(self): from phenum.grouptheory import _get_rotation_perms_lists case = 31 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_32(self): from phenum.grouptheory import _get_rotation_perms_lists case = 32 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_33(self): from phenum.grouptheory import _get_rotation_perms_lists case = 33 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_34(self): from phenum.grouptheory import _get_rotation_perms_lists case = 34 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_35(self): from phenum.grouptheory import _get_rotation_perms_lists case = 35 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_36(self): from phenum.grouptheory import _get_rotation_perms_lists case = 36 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_37(self): from phenum.grouptheory import _get_rotation_perms_lists case = 37 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_38(self): from phenum.grouptheory import _get_rotation_perms_lists case = 38 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_39(self): from phenum.grouptheory import _get_rotation_perms_lists case = 39 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_50(self): from phenum.grouptheory import _get_rotation_perms_lists case = 50 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_51(self): from phenum.grouptheory import _get_rotation_perms_lists case = 51 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_52(self): from phenum.grouptheory import _get_rotation_perms_lists case = 52 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_53(self): from phenum.grouptheory import _get_rotation_perms_lists case = 53 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_54(self): from phenum.grouptheory import _get_rotation_perms_lists case = 54 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_55(self): from phenum.grouptheory import _get_rotation_perms_lists case = 55 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_56(self): from phenum.grouptheory import _get_rotation_perms_lists case = 56 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_57(self): from phenum.grouptheory import _get_rotation_perms_lists case = 57 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) def test_58(self): from phenum.grouptheory import _get_rotation_perms_lists case = 58 A = list(map(list,zip(*_read_float_2D(gpath+"get_rotation_perms_lists_A.in."+str(case))))) HNF = _read_int_3D(gpath+"get_rotation_perms_lists_HNF.in."+str(case)) L = _read_int_3D(gpath+"get_rotation_perms_lists_L.in."+str(case)) SNF = _read_int_3D(gpath+"get_rotation_perms_lists_SNF.in."+str(case)) Op = _read_fixOp_1D(gpath+"get_rotation_perms_lists_Op.in."+str(case)) dperms = _read_RotPermList(gpath+"get_rotation_perms_lists_dperms.in."+str(case)) RPlist = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.in."+str(case)) eps = _read_float(gpath+"get_rotation_perms_lists_eps.in."+str(case)) out1 = _get_rotation_perms_lists(A,HNF,L,SNF,Op,RPlist,dperms,eps) out2 = _read_RotPermList_1D(gpath+"get_rotation_perms_lists_RPlist.out."+str(case)) for out in out1: out.perm.arrow_perm = None self._compare_outputs(out1,out2) class TestRM3DOperations(ut.TestCase): """Tests of the _rm_3D_operations subroutine.""" def test_1(self): from phenum.grouptheory import _rm_3D_operations with pytest.raises(ValueError): _rm_3D_operations([[1,1,0],[1,1,1],[0,1,1]],[0],[0],1E-7) class TestGetSymGroup(ut.TestCase): """ Tests of the get_sym_group subroutine.""" def test_1(self): from phenum.grouptheory import get_sym_group par_lat = [[0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.0, 0.5, 0.5]] bas_vacs = [[0.0, 0.0, 0.0]] HNF = [[1, 0, 0], [0, 1, 0], [2, 3, 6]] LatDim = 3 out = _read_output("arrow_group.out.1") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out) def test_2(self): from phenum.grouptheory import get_sym_group par_lat = [[0.5, 0.5, 0.0], [0.5, 0.0, 0.5], [0.0, 0.5, 0.5]] bas_vacs = [[0.0, 0.0, 0.0]] HNF = [[1, 0, 0], [0, 1, 0], [0, 5, 6]] LatDim = 3 out = _read_output("arrow_group.out.2") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out) def test_3(self): from phenum.grouptheory import get_sym_group par_lat = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] bas_vacs = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]] HNF = [[1, 0, 0], [0, 1, 0], [0, 1, 2]] LatDim = 3 out = _read_output("arrow_group.out.3") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out) def test_4(self): from phenum.grouptheory import get_sym_group par_lat = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] bas_vacs = [[0.0, 0.0, 0.0]] HNF = [[1, 0, 0], [0, 1, 0], [0, 0, 7]] LatDim = 3 out = _read_output("arrow_group.out.4") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out) def test_5(self): from phenum.grouptheory import get_sym_group par_lat = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] bas_vacs = [[0.0, 0.0, 0.0]] HNF = [[1, 0, 0], [1, 2, 0], [1, 0, 2]] LatDim = 3 out = _read_output("arrow_group.out.5") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out) def test_6(self): from phenum.grouptheory import get_sym_group par_lat = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] bas_vacs = [[0.0, 0.0, 0.0]] HNF = [[1, 0, 0], [0, 2, 0], [0, 0, 2]] LatDim = 3 out = _read_output("arrow_group.out.6") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out) def test_7(self): from phenum.grouptheory import get_sym_group par_lat = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] bas_vacs = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0.25, 0.25, 0.75]] HNF = [[1, 0, 0], [0, 1, 0], [0, 1, 2]] LatDim = 3 out = _read_output("arrow_group.out.7") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out) def test_8(self): from phenum.grouptheory import get_sym_group par_lat = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] bas_vacs = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0.25, 0.25, 0.75]] HNF = [[1, 0, 0], [0, 1, 0], [0, 0, 3]] LatDim = 3 out = _read_output("arrow_group.out.8") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out) def test_9(self): from phenum.grouptheory import get_sym_group par_lat = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] bas_vacs = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0.25, 0.25, 0.75]] HNF = [[1, 0, 0], [0, 1, 0], [0, 2, 3]] LatDim = 3 out = _read_output("arrow_group.out.9") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out) def test_10(self): from phenum.grouptheory import get_sym_group par_lat = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] bas_vacs = [[0.0, 0.0, 0.0]] HNF = [[2, 0, 0], [0, 2, 0], [0, 0, 2]] LatDim = 3 out = _read_output("arrow_group.out.10") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out) def test_11(self): from phenum.grouptheory import get_sym_group par_lat = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] bas_vacs = [[2.0, 2.0, 2.0]] HNF = [[2, 0, 0], [0, 2, 0], [0, 0, 2]] LatDim = 3 out = _read_output("arrow_group.out.10") symm = get_sym_group(par_lat,bas_vacs,HNF,LatDim) agroup = [] for i in range(len(symm.perm.site_perm)): agroup.append([symm.perm.site_perm[i],[int(j) for j in symm.perm.arrow_perm[i]]]) for perm in agroup: self.assertIn(perm,out)
{ "alphanum_fraction": 0.6601426367, "author": null, "avg_line_length": 54.3048327138, "converted": null, "ext": "py", "file": null, "hexsha": "36321fd33563137f6af1603c89ad0ef4f0bd6035", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2020-01-09T14:44:45.000Z", "max_forks_repo_forks_event_min_datetime": "2017-03-15T21:28:44.000Z", "max_forks_repo_head_hexsha": "5d7a8d8e3403cc387bdd58cf98a23e4751ea34dd", "max_forks_repo_licenses": [ "MIT-0" ], "max_forks_repo_name": "wsmorgan/phonon-enumeration", "max_forks_repo_path": "tests/test_grouptheory.py", "max_issues_count": 66, "max_issues_repo_head_hexsha": "5d7a8d8e3403cc387bdd58cf98a23e4751ea34dd", "max_issues_repo_issues_event_max_datetime": "2018-07-05T19:43:09.000Z", "max_issues_repo_issues_event_min_datetime": "2016-04-02T05:02:08.000Z", "max_issues_repo_licenses": [ "MIT-0" ], "max_issues_repo_name": "wsmorgan/phonon-enumeration", "max_issues_repo_path": "tests/test_grouptheory.py", "max_line_length": 632, "max_stars_count": 5, "max_stars_repo_head_hexsha": "5d7a8d8e3403cc387bdd58cf98a23e4751ea34dd", "max_stars_repo_licenses": [ "MIT-0" ], "max_stars_repo_name": "wsmorgan/phonon-enumeration", "max_stars_repo_path": "tests/test_grouptheory.py", "max_stars_repo_stars_event_max_datetime": "2021-05-30T21:02:08.000Z", "max_stars_repo_stars_event_min_datetime": "2016-06-17T05:39:27.000Z", "num_tokens": 48670, "path": null, "reason": "import numpy,from numpy", "repo": null, "save_path": null, "sha": null, "size": 160688 }
MODULE GreyVariables !----------------------------------------------------------------------- ! ! File: GreyVariables ! Module: GreyVariables ! Type: Module ! Author: R. Chu, Dept of Physics, UTK ! ! Date: 8/21/16 ! ! Purpose: ! Subroutines needed for GreyMoment_Number/Energy ! and GreyOpacity_Number/Energy ! Mudules used: ! wlKindModule ! gaquad !----------------------------------------------------------------------- USE wlKindModule, ONLY: dp USE B85_Absorption USE B85_scattIso PUBLIC :: & GreyMomentWithGaussianQuadrature,& GreyOpacityWithGaussianQuadrature CONTAINS SUBROUTINE GreyMomentWithGaussianQuadrature& ( nquad, bb, outcome, func, debug ) INTEGER, INTENT(in) :: nquad REAL(dp), INTENT(in) :: bb CHARACTER(18), INTENT(in) :: func LOGICAL, INTENT(in) :: debug REAL(dp), INTENT(out) :: outcome INTEGER, PARAMETER :: npiece = 47 REAL(dp), DIMENSION(nquad) :: roots, weights, FD REAL(dp), DIMENSION(npiece):: lim INTEGER :: ii, jj REAL(dp) :: llim, ulim IF (debug) THEN PRINT*,"Calculating ", func PRINT*,"with bb = ",bb END IF outcome = 0.0_dp lim(1) = 0.0_dp DO jj = 1,10 lim(jj+1) = lim(jj) + 0.1_dp END DO DO jj = 12, 20 lim(jj) = lim(jj-1) + 1.0_dp END DO DO jj = 21, 29 lim(jj) = lim(jj-1) + 10.0_dp END DO DO jj = 30, 38 lim(jj) = lim(jj-1) + 100.0_dp END DO DO jj = 39, 47 lim(jj) = lim(jj-1) + 1000.0_dp END DO DO jj = 1,(npiece-1) llim = lim(jj) ulim = lim(jj+1) CALL gaquad( nquad, roots, weights, llim, ulim ) DO ii = 1, nquad IF (func == "GreyMoment_Number ") THEN FD(ii) = Number_FD( roots(ii), bb) outcome = outcome + weights(ii) * & Number_FD( roots(ii), bb) ELSE IF (func == "GreyMoment_Energy ") THEN FD(ii) = Energy_FD( roots(ii), bb) outcome = outcome + weights(ii) * & Energy_FD( roots(ii), bb) END IF END DO ! ii (nquad) END DO ! jj IF (debug) THEN WRITE(*,'(A24,F7.1,A2,F7.1,A1)')& " Integration domain is [",lim(1),", ",lim(47),"]" print*,"divided into", lim PRINT*, "with nquad=", nquad PRINT*, "and the outcome is", outcome END IF END SUBROUTINE GreyMomentWithGaussianQuadrature SUBROUTINE GreyOpacityWithGaussianQuadrature_NuEAb& ( nquad, bb, & rho, T, Z, A, chem_e, chem_n,& chem_p, xheavy, xn, xp,& outcome, func, debug ) INTEGER, INTENT(in) :: nquad REAL(dp), INTENT(in) :: bb, rho, T, Z, A, & chem_e, chem_n, & chem_p, xheavy, xn,& xp CHARACTER(18), INTENT(in) :: func LOGICAL, INTENT(in) :: debug REAL(dp), INTENT(out) :: outcome INTEGER, PARAMETER :: npiece = 47 REAL(dp), DIMENSION(nquad) :: roots, weights, opacity REAL(dp), DIMENSION(npiece):: lim INTEGER :: ii, jj REAL(dp) :: llim, ulim IF (debug) THEN PRINT*,"Calculating ", func PRINT*,"with bb =", bb END IF outcome = 0.0_dp lim(1) = 0.0_dp DO jj = 1,10 lim(jj+1) = lim(jj) + 0.1_dp END DO DO jj = 12, 20 lim(jj) = lim(jj-1) + 1.0_dp END DO DO jj = 21, 29 lim(jj) = lim(jj-1) + 10.0_dp END DO DO jj = 30, 38 lim(jj) = lim(jj-1) + 100.0_dp END DO DO jj = 39, 47 lim(jj) = lim(jj-1) + 1000.0_dp END DO DO jj = 1,(npiece-1) llim = lim(jj) ulim = lim(jj+1) CALL gaquad( nquad, roots, weights, llim, ulim ) DO ii = 1, nquad opacity(ii) = TotalNuEAbsorption(roots(ii), rho, T, Z, A,& chem_e, chem_n, chem_p, & xheavy, xn, xp ) IF (func == "GreyOpacity_Number ") THEN outcome = outcome + weights(ii) * & Number_FD( roots(ii), bb) * opacity(ii) ELSE IF (func == "GreyOpacity_Energy ") THEN outcome = outcome + weights(ii) * & Energy_FD( roots(ii), bb) * opacity(ii) END IF END DO ! ii (nquad) END DO ! jj IF (debug) THEN WRITE(*,'(A24,F7.1,A2,F7.1,A1)') & " Integration domain is [",lim(1),", ",lim(47),"]" print*,"divided into", lim PRINT*, "with nquad=", nquad PRINT*, "and the outcome is", outcome END IF END SUBROUTINE GreyOpacityWithGaussianQuadrature_NuEAb SUBROUTINE GreyOpacityWithGaussianQuadrature_scattIso& ( nquad, bb, & rho, T, xh, A, Z, xn, xp, l,& outcome, func, debug ) USE, INTRINSIC :: ieee_arithmetic, ONLY: IEEE_IS_NAN INTEGER, INTENT(in) :: nquad, l REAL(dp), INTENT(in) :: bb, rho, T, xh, A, Z, xn, xp CHARACTER(18), INTENT(in) :: func LOGICAL, INTENT(in) :: debug REAL(dp), INTENT(out) :: outcome INTEGER, PARAMETER :: npiece = 47 REAL(dp), DIMENSION(nquad) :: roots, weights, opacity REAL(dp), DIMENSION(npiece):: lim INTEGER :: ii, jj REAL(dp) :: llim, ulim IF (debug) THEN PRINT*,"Calculating ", func PRINT*,"with bb =", bb END IF outcome = 0.0_dp lim(1) = 0.0_dp DO jj = 1,10 lim(jj+1) = lim(jj) + 0.1_dp END DO DO jj = 12, 20 lim(jj) = lim(jj-1) + 1.0_dp END DO DO jj = 21, 29 lim(jj) = lim(jj-1) + 10.0_dp END DO DO jj = 30, 38 lim(jj) = lim(jj-1) + 100.0_dp END DO DO jj = 39, 47 lim(jj) = lim(jj-1) + 1000.0_dp END DO DO jj = 1,(npiece-1) llim = lim(jj) ulim = lim(jj+1) CALL gaquad( nquad, roots, weights, llim, ulim ) DO ii = 1, nquad opacity(ii) = TotalIsoScatteringKernel& ( roots(ii), rho, T, xh, A, Z, xn, xp, l ) IF (func == "GreyOpacity_Number ") THEN outcome = outcome + weights(ii) * & Number_FD( roots(ii), bb) * opacity(ii) ELSE IF (func == "GreyOpacity_Energy ") THEN outcome = outcome + weights(ii) * & Energy_FD( roots(ii), bb) * opacity(ii) END IF END DO ! ii (nquad) IF ( l == 0 ) THEN outcome = outcome * (4.0*pi) END IF END DO ! jj IF (debug) THEN WRITE(*,'(A24,F7.1,A2,F7.1,A1)') & " Integration domain is [",lim(1),", ",lim(47),"]" print*,"divided into", lim PRINT*, "with nquad=", nquad PRINT*, "and the outcome is", outcome END IF IF ( IEEE_IS_NAN(outcome) )THEN WRITE(*,*)"STOP for data error" STOP END IF END SUBROUTINE GreyOpacityWithGaussianQuadrature_scattIso ! SUBROUTINE GreyOpacityWithGaussianQuadrature_NES& ! ( nquad, bb, & ! TMeV, chem_e, l,& ! outcome, species, func, debug ) ! INTEGER, INTENT(in) :: nquad, l, species ! REAL(dp), INTENT(in) :: bb, TMeV, chem_e ! CHARACTER(18), INTENT(in) :: func ! LOGICAL, INTENT(in) :: debug ! ! REAL(dp), INTENT(out) :: outcome ! ! INTEGER, PARAMETER :: npiece = 47 ! REAL(dp), DIMENSION(nquad) :: roots, weights, opacity ! REAL(dp), DIMENSION(npiece):: lim ! INTEGER :: ii, jj ! REAL(dp) :: llim, ulim ! ! IF (debug) THEN ! PRINT*,"Calculating ", func ! PRINT*,"with bb =", bb ! END IF ! ! outcome = 0.0_dp ! lim(1) = 0.0_dp ! ! DO jj = 1,10 ! lim(jj+1) = lim(jj) + 0.1_dp ! END DO ! DO jj = 12, 20 ! lim(jj) = lim(jj-1) + 1.0_dp ! END DO ! DO jj = 21, 29 ! lim(jj) = lim(jj-1) + 10.0_dp ! END DO ! DO jj = 30, 38 ! lim(jj) = lim(jj-1) + 100.0_dp ! END DO ! DO jj = 39, 47 ! lim(jj) = lim(jj-1) + 1000.0_dp ! END DO ! ! DO jj = 1,(npiece-1) ! ! llim = lim(jj) ! ulim = lim(jj+1) ! ! CALL gaquad( nquad, roots, weights, llim, ulim ) ! ! opacity(ii) = totalNESKernel& ! ( roots(ii), TMeV, chem_e, l, species ) !!! ! ! DO ii = 1, nquad ! ! IF (func == "GreyOpacity_Number ") THEN ! ! outcome = outcome + weights(ii) * & ! Number_FD( roots(ii), bb) * opacity(ii) ! ! ELSE IF (func == "GreyOpacity_Energy ") THEN ! ! outcome = outcome + weights(ii) * & ! Energy_FD( roots(ii), bb) * opacity(ii) ! ! END IF ! END DO ! ii (nquad) ! ! IF ( l == 0 ) THEN ! ! outcome = outcome * (4.0*pi) ! ! END IF ! ! END DO ! jj ! ! END SUBROUTINE GreyOpacityWithGaussianQuadrature_NES !------------------------------------------------------- ! Declear GrayFunctions !------------------------------------------------------- FUNCTION Number_FD( x, b ) USE wlKindModule, ONLY: dp REAL(dp), INTENT(in) :: x,b ! function argument REAL(dp) :: fexp, Number_FD Number_FD = ( x*x )/( fexp(x-b) + 1.0 ) END FUNCTION Number_FD FUNCTION Energy_FD( x, b ) USE wlKindModule, ONLY: dp REAL(dp), INTENT(in) :: x,b ! function argument REAL(dp) :: fexp, Energy_FD Energy_FD = ( x*x*x )/( fexp(x-b) + 1.0 ) END FUNCTION Energy_FD END MODULE GreyVariables
{ "alphanum_fraction": 0.4990028341, "author": null, "avg_line_length": 24.6175710594, "converted": null, "ext": "f90", "file": null, "hexsha": "68920285befa42b843d4375991f024ff5953a1de", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-04-28T01:37:37.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-16T14:59:05.000Z", "max_forks_repo_head_hexsha": "cfd3d600fef4dbd9789462270e0ef469878b2f53", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "ranchu1/weaklib", "max_forks_repo_path": "TableCreator/OpacitySource/Bruenn85/GreyVariables.f90", "max_issues_count": 7, "max_issues_repo_head_hexsha": "cfd3d600fef4dbd9789462270e0ef469878b2f53", "max_issues_repo_issues_event_max_datetime": "2021-07-23T19:08:53.000Z", "max_issues_repo_issues_event_min_datetime": "2020-07-13T22:42:06.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "ranchu1/weaklib", "max_issues_repo_path": "TableCreator/OpacitySource/Bruenn85/GreyVariables.f90", "max_line_length": 72, "max_stars_count": 6, "max_stars_repo_head_hexsha": "4a26ff17d3224d8fe90b922cb55ea9d865200154", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "srichers/weaklib", "max_stars_repo_path": "TableCreator/OpacitySource/Bruenn85/GreyVariables.f90", "max_stars_repo_stars_event_max_datetime": "2022-02-21T11:59:44.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-08T16:16:26.000Z", "num_tokens": 3090, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 9527 }
\chapter{Constructing an formula} \label{chapter:constructingaformula} The class \formulaClass represents SMT formulas, which are defined according to the following abstract grammar \[ \begin{array}{rccccccccccccc} p &\quad ::=\quad & a & | & b & | & x & | & (p + p) & | & (p \cdot p) & | & (p^e) \\ v &\quad ::=\quad & u & | & x \\ s &\quad ::=\quad & f(v,\ldots,v) & | & u & | & x \\ e &\quad ::=\quad & s = s \\ c &\quad ::=\quad & p = 0 & | & p < 0 & | & p \leq 0 & | & p > 0 & | & p \geq 0 & | & p \neq 0 \\ \varphi &\quad ::=\quad & c & | & (\neg \varphi) & | & (\varphi\land\varphi) & | & (\varphi\lor\varphi) & | & (\varphi\rightarrow\varphi) & | \\ && (\varphi\leftrightarrow\varphi) & | & (\varphi\oplus\varphi) \end{array} \] where $a$ is a rational number, $e$ is a natural number greater one, $b$ is a \emph{Boolean variable} and the \emph{arithmetic variable} $x$ is an inherently existential quantified and either real- or integer-valued. We call $p$ a \emph{polynomial} and use a \carl multivariate polynomial with \cln rationals as coefficients to represent it. The \emph{uninterpreted function} $f$ is of a certain \emph{order} $o(f)$ and each of its $o(f)$ arguments are either an arithmetic variable or an \emph{uninterpreted variable} $u$, which is also inherently existential quantified, but has no domain specified. Than an \emph{uninterpreted equation} $e$ has either an uninterpreted function, an uninterpreted variable or an arithmetic variable as left-hand respectively right-hand side. A \emph{constraint} $c$ compares a polynomial to zero, using a \emph{relation symbol}. Furthermore, we keep constraints in a normalized representation to be able to differ them better. \section{Normalized constraints} A normalized constraint has the form \[a_1\overbrace{x_{1,1}^{e_{1,1}}\cdot\ldots\cdot x_{1,k_1}^{e_{1,k_1}}}^{m_1}+\ldots+a_n\overbrace{x_{n,1}^{e_{n,1}}\cdot\ldots\cdot x_{n,k_n}^{e_{n,k_n}}}^{m_n}\ + \ d\ \sim \ 0\] with $n\geq0$, the \emph{$i$th coefficient} $a_i$ being an integral number ($\neq 0$), $d$ being a integral number, $x_{i,j_i}$ being a real- or integer-valued variable and $e_{i,j_i}$ being a natural number greater zero (for all $1\leq i\leq n$ and $1\leq j_i\leq k_i$). Furthermore, it holds that $x_{i,j_i}\neq x_{i,l_i}$ if $j_i\neq l_i$ (for all $1\leq i\leq n$ and $1\leq j_i, l_i\leq k_i$) and $m_{i_1}\neq m_{i_2}$ if $i_1\neq i_2$ (for all $1\leq i_1,i_2\leq n$). If $n$ is $0$ then $d$ is $0$ and $\sim$ is either $=$ or $<$. In the former case we have the normalized representation of any variable-free consistent constraint, which semantically equals \true, and in the latter case we have the normalized representation of any variable-free inconsistent constraint, which semantically equals \false. Note that the monomials and the variables in them are ordered according the \polynomialOrder of \carl. Moreover, the first coefficient of a normalized constraint (with respect to this order) is always positive and the greatest common divisor of $a_1,\ldots,\ a_n,\ d$ is $1$. If all variable are integer valued the constraint is further simplified to \[\frac{a_1}{g}\cdot m_1\ +\ \ldots\ +\ \frac{a_n}{g}\cdot m_n\ + \ d'\ \sim' \ 0,\] where $g$ is the greatest common divisor of $a_1,\ldots,\ a_n$, \[\sim'=\left\{ \begin{array}{ll} \leq, &\text{ if }\sim\text{ is }< \\ \geq, &\text{ if }\sim\text{ is }> \\ \sim, &\text{ otherwise } \end{array} \right.\] and \[ d' = \left\{ \begin{array}{ll} \lceil\frac{d}{g}\rceil &\text{ if }\sim'\text{ is }\leq \\[1.5ex] \lfloor\frac{d}{g}\rfloor &\text{ if }\sim'\text{ is }\geq \\[1.5ex] \frac{d}{g} &\text{ otherwise } \end{array} \right.\] If additionally $\frac{d}{g}$ is not integral and $\sim'$ is $=$, the constraint is simplified $0<0$, or if $\sim'$ is $\neq$, the constraint is simplified $0=0$. We do some further simplifactions, such as the elimination of multiple roots of the left-hand sides in equations and inequalities with the relation symbol $\neq$, e.g., $x^3=0$ is simplified to $x=0$. We also simplify constraints whose left-hand sides are obviously positive (semi)/negative (semi) definite, e.g., $x^2\leq 0$ is simplified to $x^2=0$, which again can be simplified to $x=0$ according to the first simplification rule. \section{Boolean combinations of constraints and Boolean variables} A formula is stored as a directed acyclic graph, where the intermediate nodes represent the Boolean operations on the sub-formulas represented by the successors of this node. The leaves (nodes without successor) contain either a Boolean variable, a constraint or an uninterpreted equality. Equal formulas, that is formulas being leaves and containing the same element or formulas representing the same operation on the same sub-formulas, are stored only once. The construction of formulas, which are represented by the \formulaClass, is mainly based on the presented abstract grammar. A formula being a leaf wraps the corresponding objects representing a Boolean variable, a constraint or an uninterpreted equality. A Boolean combination of Boolean variables, constraints and uninterpreted equalities consists of a Boolean operator and the sub-formulas it interconnects. For this purpose we either firstly create a set of formulas containing all sub-formulas and then construct the Formula or (if the formula shall not have more than three sub-formulas) construct the formula directly passing the operator and sub-formulas. Formulas, constraints and uninterpreted equalities are non-mutable, once they are constructed. %TODO: explain mutable member of formulas for information storage We give a small example constructing the formula \[(\neg b\ \land\ x^2-y<0\ \land\ 4x+y-8y^7=0 )\ \rightarrow\ (\neg(x^2-y<0)\ \lor\ b ),\] with the Boolean variable $b$ and the real-valued variables $x$ and $y$, for demonstration. Furthermore, we construct the UF formula \[v = f(u,u)\ \oplus\ w \neq u\] with $u$, $v$ and $w$ being uninterpreted variables of not specified domains $S$ and $T$, respectively, and $f$ is an uninterpreted function with not specified domain $T^{S\times S}$. Firstly, we show how to create real valued (integer valued analogously with \texttt{VT\_INT}), Boolean and uninterpreted variables: \scriptsize \begin{verbatim} carl::Variable x = smtrat::newVariable( "x", carl::VariableType::VT_REAL ); carl::Variable y = smtrat::newVariable( "y", carl::VariableType::VT_REAL ); carl::Variable b = smtrat::newVariable( "b", carl::VariableType::VT_BOOL ); carl::Variable u = smtrat::newVariable( "u", carl::VariableType::VT_UNINTERPRETED ); carl::Variable v = smtrat::newVariable( "v", carl::VariableType::VT_UNINTERPRETED ); carl::Variable w = smtrat::newVariable( "w", carl::VariableType::VT_UNINTERPRETED ); \end{verbatim} \normalsize Uninterpreted variables, functions and function instances combined in equations or inequalities comparing them are constructed the following way. \scriptsize \begin{verbatim} carl::Sort sortS = smtrat::newSort( "S" ); carl::Sort sortT = smtrat::newSort( "T" ); carl::UVariable uu( u, sortS ); carl::UVariable uv( v, sortT ); carl::UVariable uw( w, sortS ); carl::UninterpretedFunction f = smtrat::newUF( "f", sortS, sortS, sortT ); carl::UFInstance f1 = smtrat::newUFInstance( f, uu, uw ); carl::UEquality ueqA( uv, f1, false ); carl::UEquality ueqB( uw, uu, true ); \end{verbatim} \normalsize Next we see an example how to create polynomials, which form the left-hand sides of the constraints: \scriptsize \begin{verbatim} smtrat::Poly px( x ); smtrat::Poly py( y ); smtrat::Poly lhsA = px.pow(2) - py; smtrat::Poly lhsB = smtrat::Rational(4) * px + py - smtrat::Rational(8) * py.pow(7); \end{verbatim} \normalsize Constraints can then be constructed as follows: \scriptsize \begin{verbatim} smtrat::ConstraintT constraintA( lhsA, carl::Relation::LESS ); smtrat::ConstraintT constraintB( lhsB, carl::Relation::EQ ); \end{verbatim} \normalsize Now, we can construct the atoms of the Boolean formula \scriptsize \begin{verbatim} smtrat::FormulaT atomA( constraintA ); smtrat::FormulaT atomB( constraintB ); smtrat::FormulaT atomC( b ); smtrat::FormulaT atomD( ueqA ); smtrat::FormulaT atomE( ueqB ); \end{verbatim} \normalsize and the formulas itself (either with a set of arguments or directly): \scriptsize \begin{verbatim} smtrat::FormulasT subformulasA; subformulasA.insert( smtrat::FormulaT( carl::FormulaType::NOT, atomC ) ); subformulasA.insert( atomA ); subformulasA.insert( atomB ); smtrat::FormulaT phiA( carl::FormulaType::AND, std::move(subformulasA) ); smtrat::FormulaT phiB( carl::FormulaType::NOT, atomA ) smtrat::FormulaT phiC( carl::FormulaType::OR, phiB, atomC ); smtrat::FormulaT phiD( carl::FormulaType::IMPLIES, phiA, phiC ); smtrat::FormulaT phiE( carl::FormulaType::XOR, atomD, atomE ); \end{verbatim} \normalsize Note, that $\land$ and $\lor$ are $n$-ary constructors, $\neg$ is a unary constructor and all the other Boolean operators are binary.
{ "alphanum_fraction": 0.7234873856, "author": null, "avg_line_length": 68.9076923077, "converted": null, "ext": "tex", "file": null, "hexsha": "a386713f08ee5608914bf385bda64818ef350a2e", "include": null, "lang": "TeX", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "minemebarsha/smtrat", "max_forks_repo_path": "manual/constructingformulas.tex", "max_issues_count": null, "max_issues_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "minemebarsha/smtrat", "max_issues_repo_path": "manual/constructingformulas.tex", "max_line_length": 961, "max_stars_count": null, "max_stars_repo_head_hexsha": "eaada50cdf9bbfe4dd4f6a54776387484c37b0f2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "minemebarsha/smtrat", "max_stars_repo_path": "manual/constructingformulas.tex", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2732, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 8958 }
# -*- coding: utf-8 -*- """ Created on Thu Dec 19 10:59:27 2019 @author: ykrempp """ import cv2 import numpy as np from matplotlib import pyplot as plt img_path = 'images\qupath_image.tif' img = cv2.imread(img_path, 0) scale_percent = 25 # percent of original size width = int(img.shape[1] * scale_percent / 100) height = int(img.shape[0] * scale_percent / 100) dim = (width, height) img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA) eq_img = cv2.equalizeHist(img) clahe = cv2.createCLAHE(clipLimit = 2.0, tileGridSize=(8,8)) cl_img = clahe.apply(img) cv2.imshow("original", img) cv2.imshow("equalized", eq_img) cv2.imshow("CLAHE", cl_img) plt.hist(cl_img.flat, bins=100) ret, thresh1 = cv2.threshold(cl_img, 50, 255, cv2.THRESH_BINARY) ret, thresh2 = cv2.threshold(cl_img, 100, 255, cv2.THRESH_BINARY) otsu_thresh, thresh3 = cv2.threshold(cl_img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU) cv2.imshow("Threshold 1", thresh1) cv2.imshow("Threshold 2", thresh2) cv2.imshow("OTSU", thresh3) cv2.waitKey(0) cv2.destroyAllWindows()
{ "alphanum_fraction": 0.7091078067, "author": null, "avg_line_length": 22.4166666667, "converted": null, "ext": "py", "file": null, "hexsha": "104645290d28f286bf2d7932be92dccedea4468b", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-02-11T02:18:12.000Z", "max_forks_repo_forks_event_min_datetime": "2021-02-11T02:18:12.000Z", "max_forks_repo_head_hexsha": "d2809beca1f140a45087be18041748249230cc0a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "UniversalBuilder/Python-and-Microscopy", "max_forks_repo_path": "work-in-progress/CLAHE_and_thresholding.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "d2809beca1f140a45087be18041748249230cc0a", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "UniversalBuilder/Python-and-Microscopy", "max_issues_repo_path": "work-in-progress/CLAHE_and_thresholding.py", "max_line_length": 87, "max_stars_count": 1, "max_stars_repo_head_hexsha": "d2809beca1f140a45087be18041748249230cc0a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "UniversalBuilder/Python-and-Microscopy", "max_stars_repo_path": "work-in-progress/CLAHE_and_thresholding.py", "max_stars_repo_stars_event_max_datetime": "2020-03-27T17:50:58.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-27T17:50:58.000Z", "num_tokens": 339, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1076 }
theory GabrielaLimonta2 imports Main "Repeat_Big_Step" "~~/src/HOL/IMP/Star" begin subsection "List setup" text {* In the following, we use the length of lists as integers instead of natural numbers. Instead of converting @{typ nat} to @{typ int} explicitly, we tell Isabelle to coerce @{typ nat} automatically when necessary. *} declare [[coercion_enabled]] declare [[coercion "int :: nat \<Rightarrow> int"]] text {* Similarly, we will want to access the ith element of a list, where @{term i} is an @{typ int}. *} fun inth :: "'a list \<Rightarrow> int \<Rightarrow> 'a" (infixl "!!" 100) where "(x # xs) !! i = (if i = 0 then x else xs !! (i - 1))" text {* The only additional lemma we need about this function is indexing over append: *} lemma inth_append [simp]: "0 \<le> i \<Longrightarrow> (xs @ ys) !! i = (if i < size xs then xs !! i else ys !! (i - size xs))" by (induction xs arbitrary: i) (auto simp: algebra_simps) text{* We hide coercion @{const int} applied to @{const length}: *} abbreviation (output) "isize xs == int (length xs)" notation isize ("size") subsection "Instructions and Stack Machine" text_raw{*\snip{instrdef}{0}{1}{% *} datatype instr = LOADI int | LOAD vname | ADD | STORE vname | JMP int | JMPLESS int | JMPGE int text_raw{*}%endsnip*} type_synonym stack = "val list" type_synonym config = "int \<times> state \<times> stack" abbreviation "hd2 xs == hd(tl xs)" abbreviation "tl2 xs == tl(tl xs)" fun iexec :: "instr \<Rightarrow> config \<Rightarrow> config" where "iexec instr (i,s,stk) = (case instr of LOADI n \<Rightarrow> (i+1,s, n#stk) | LOAD x \<Rightarrow> (i+1,s, s x # stk) | ADD \<Rightarrow> (i+1,s, (hd2 stk + hd stk) # tl2 stk) | STORE x \<Rightarrow> (i+1,s(x := hd stk),tl stk) | JMP n \<Rightarrow> (i+1+n,s,stk) | JMPLESS n \<Rightarrow> (if hd2 stk < hd stk then i+1+n else i+1,s,tl2 stk) | JMPGE n \<Rightarrow> (if hd2 stk >= hd stk then i+1+n else i+1,s,tl2 stk))" definition exec1 :: "instr list \<Rightarrow> config \<Rightarrow> config \<Rightarrow> bool" ("(_/ \<turnstile> (_ \<rightarrow>/ _))" [59,0,59] 60) where "P \<turnstile> c \<rightarrow> c' = (\<exists>i s stk. c = (i,s,stk) \<and> c' = iexec(P!!i) (i,s,stk) \<and> 0 \<le> i \<and> i < size P)" lemma exec1I [intro, code_pred_intro]: "c' = iexec (P!!i) (i,s,stk) \<Longrightarrow> 0 \<le> i \<Longrightarrow> i < size P \<Longrightarrow> P \<turnstile> (i,s,stk) \<rightarrow> c'" by (simp add: exec1_def) abbreviation exec :: "instr list \<Rightarrow> config \<Rightarrow> config \<Rightarrow> bool" ("(_/ \<turnstile> (_ \<rightarrow>*/ _))" 50) where "exec P \<equiv> star (exec1 P)" declare star.step[intro] lemmas exec_induct = star.induct [of "exec1 P", split_format(complete)] code_pred exec1 by (metis exec1_def) values "{(i,map t [''x'',''y''],stk) | i t stk. [LOAD ''y'', STORE ''x''] \<turnstile> (0, <''x'' := 3, ''y'' := 4>, []) \<rightarrow>* (i,t,stk)}" subsection{* Verification infrastructure *} text{* Below we need to argue about the execution of code that is embedded in larger programs. For this purpose we show that execution is preserved by appending code to the left or right of a program. *} lemma iexec_shift [simp]: "((n+i',s',stk') = iexec x (n+i,s,stk)) = ((i',s',stk') = iexec x (i,s,stk))" by(auto split:instr.split) lemma exec1_appendR: "P \<turnstile> c \<rightarrow> c' \<Longrightarrow> P@P' \<turnstile> c \<rightarrow> c'" by (auto simp: exec1_def) lemma exec_appendR: "P \<turnstile> c \<rightarrow>* c' \<Longrightarrow> P@P' \<turnstile> c \<rightarrow>* c'" by (induction rule: star.induct) (fastforce intro: exec1_appendR)+ lemma exec1_appendL: fixes i i' :: int shows "P \<turnstile> (i,s,stk) \<rightarrow> (i',s',stk') \<Longrightarrow> P' @ P \<turnstile> (size(P')+i,s,stk) \<rightarrow> (size(P')+i',s',stk')" unfolding exec1_def by (auto simp del: iexec.simps) lemma exec_appendL: fixes i i' :: int shows "P \<turnstile> (i,s,stk) \<rightarrow>* (i',s',stk') \<Longrightarrow> P' @ P \<turnstile> (size(P')+i,s,stk) \<rightarrow>* (size(P')+i',s',stk')" by (induction rule: exec_induct) (blast intro!: exec1_appendL)+ text{* Now we specialise the above lemmas to enable automatic proofs of @{prop "P \<turnstile> c \<rightarrow>* c'"} where @{text P} is a mixture of concrete instructions and pieces of code that we already know how they execute (by induction), combined by @{text "@"} and @{text "#"}. Backward jumps are not supported. The details should be skipped on a first reading. If we have just executed the first instruction of the program, drop it: *} lemma exec_Cons_1 [intro]: "P \<turnstile> (0,s,stk) \<rightarrow>* (j,t,stk') \<Longrightarrow> instr#P \<turnstile> (1,s,stk) \<rightarrow>* (1+j,t,stk')" by (drule exec_appendL[where P'="[instr]"]) simp lemma exec_appendL_if[intro]: fixes i i' j :: int shows "size P' <= i \<Longrightarrow> P \<turnstile> (i - size P',s,stk) \<rightarrow>* (j,s',stk') \<Longrightarrow> i' = size P' + j \<Longrightarrow> P' @ P \<turnstile> (i,s,stk) \<rightarrow>* (i',s',stk')" by (drule exec_appendL[where P'=P']) simp text{* Split the execution of a compound program up into the excution of its parts: *} lemma exec_append_trans[intro]: fixes i' i'' j'' :: int shows "P \<turnstile> (0,s,stk) \<rightarrow>* (i',s',stk') \<Longrightarrow> size P \<le> i' \<Longrightarrow> P' \<turnstile> (i' - size P,s',stk') \<rightarrow>* (i'',s'',stk'') \<Longrightarrow> j'' = size P + i'' \<Longrightarrow> P @ P' \<turnstile> (0,s,stk) \<rightarrow>* (j'',s'',stk'')" by(metis star_trans[OF exec_appendR exec_appendL_if]) declare Let_def[simp] subsection "Compilation" fun acomp :: "aexp \<Rightarrow> instr list" where "acomp (N n) = [LOADI n]" | "acomp (V x) = [LOAD x]" | "acomp (Plus a1 a2) = acomp a1 @ acomp a2 @ [ADD]" lemma acomp_correct[intro]: "acomp a \<turnstile> (0,s,stk) \<rightarrow>* (size(acomp a),s,aval a s#stk)" by (induction a arbitrary: stk) fastforce+ fun bcomp :: "bexp \<Rightarrow> bool \<Rightarrow> int \<Rightarrow> instr list" where "bcomp (Bc v) f n = (if v=f then [JMP n] else [])" | "bcomp (Not b) f n = bcomp b (\<not>f) n" | "bcomp (And b1 b2) f n = (let cb2 = bcomp b2 f n; m = (if f then size cb2 else (size cb2::int)+n); cb1 = bcomp b1 False m in cb1 @ cb2)" | "bcomp (Less a1 a2) f n = acomp a1 @ acomp a2 @ (if f then [JMPLESS n] else [JMPGE n])" value "bcomp (And (Less (V ''x'') (V ''y'')) (Not(Less (V ''u'') (V ''v'')))) False 3" lemma bcomp_correct[intro]: fixes n :: int shows "0 \<le> n \<Longrightarrow> bcomp b f n \<turnstile> (0,s,stk) \<rightarrow>* (size(bcomp b f n) + (if f = bval b s then n else 0),s,stk)" proof(induction b arbitrary: f n) case Not from Not(1)[where f="~f"] Not(2) show ?case by fastforce next case (And b1 b2) from And(1)[of "if f then size(bcomp b2 f n) else size(bcomp b2 f n) + n" "False"] And(2)[of n f] And(3) show ?case by fastforce qed fastforce+ fun ccomp :: "com \<Rightarrow> instr list" where "ccomp SKIP = []" | "ccomp (x ::= a) = acomp a @ [STORE x]" | "ccomp (c\<^sub>1;;c\<^sub>2) = ccomp c\<^sub>1 @ ccomp c\<^sub>2" | "ccomp (IF b THEN c\<^sub>1 ELSE c\<^sub>2) = (let cc\<^sub>1 = ccomp c\<^sub>1; cc\<^sub>2 = ccomp c\<^sub>2; cb = bcomp b False (size cc\<^sub>1 + 1) in cb @ cc\<^sub>1 @ JMP (size cc\<^sub>2) # cc\<^sub>2)" | "ccomp (WHILE b DO c) = (let cc = ccomp c; cb = bcomp b False (size cc + 1) in cb @ cc @ [JMP (-(size cb + size cc + 1))])" | (* begin mod *) "ccomp (REPEAT c UNTIL b) = (let cc = ccomp c; cb = bcomp b True 1 in cc @ cb @ [JMP (-(size cb + size cc + 1))])" (* end mod *) value "ccomp (REPEAT ''u'' ::= Plus (V ''u'') (N 1) UNTIL Less (N 0) (V ''u''))" subsection "Preservation of semantics" lemma ccomp_bigstep: "(c,s) \<Rightarrow> t \<Longrightarrow> ccomp c \<turnstile> (0,s,stk) \<rightarrow>* (size(ccomp c),t,stk)" proof(induction arbitrary: stk rule: big_step_induct) case (Assign x a s) show ?case by (fastforce simp:fun_upd_def cong: if_cong) next case (Seq c1 s1 s2 c2 s3) let ?cc1 = "ccomp c1" let ?cc2 = "ccomp c2" have "?cc1 @ ?cc2 \<turnstile> (0,s1,stk) \<rightarrow>* (size ?cc1,s2,stk)" using Seq.IH(1) by fastforce moreover have "?cc1 @ ?cc2 \<turnstile> (size ?cc1,s2,stk) \<rightarrow>* (size(?cc1 @ ?cc2),s3,stk)" using Seq.IH(2) by fastforce ultimately show ?case by simp (blast intro: star_trans) next case (WhileTrue b s1 c s2 s3) let ?cc = "ccomp c" let ?cb = "bcomp b False (size ?cc + 1)" let ?cw = "ccomp(WHILE b DO c)" have "?cw \<turnstile> (0,s1,stk) \<rightarrow>* (size ?cb,s1,stk)" using `bval b s1` by fastforce moreover have "?cw \<turnstile> (size ?cb,s1,stk) \<rightarrow>* (size ?cb + size ?cc,s2,stk)" using WhileTrue.IH(1) by fastforce moreover have "?cw \<turnstile> (size ?cb + size ?cc,s2,stk) \<rightarrow>* (0,s2,stk)" by fastforce moreover have "?cw \<turnstile> (0,s2,stk) \<rightarrow>* (size ?cw,s3,stk)" by(rule WhileTrue.IH(2)) ultimately show ?case by(blast intro: star_trans) next case (RepeatTrue c s1 s2 b) let ?cc = "ccomp c" let ?cb = "bcomp b True 1" let ?cr = "ccomp(REPEAT c UNTIL b)" have "?cr \<turnstile> (0, s1, stk) \<rightarrow>* (size ?cc, s2, stk)" using RepeatTrue.IH and ccomp.simps(6) by fastforce moreover have "?cr \<turnstile> (size ?cc, s2, stk) \<rightarrow>* (size ?cr, s2, stk)" using `bval b s2` by fastforce ultimately show ?case by(blast intro: star_trans) next case (RepeatFalse c s1 s2 b s3) let ?cc = "ccomp c" let ?cb = "bcomp b True 1" let ?cr = "ccomp(REPEAT c UNTIL b)" have "?cr \<turnstile> (0, s1, stk) \<rightarrow>* (size ?cc, s2, stk)" using RepeatFalse.IH by fastforce moreover have "?cr \<turnstile> (size ?cc, s2, stk) \<rightarrow>* (size ?cc + size ?cb, s2, stk)" using `\<not>bval b s2` by fastforce moreover have "?cr \<turnstile> (size ?cc + size ?cb, s2, stk) \<rightarrow>* (0, s2, stk)" using RepeatFalse.IH by fastforce moreover have "?cr \<turnstile> (0, s2, stk) \<rightarrow>* (size ?cr, s3, stk)" using RepeatFalse.IH by fastforce ultimately show ?case by(blast intro: star_trans) qed fastforce+ end
{ "alphanum_fraction": null, "author": "glimonta", "avg_line_length": null, "converted": null, "ext": null, "file": null, "hexsha": null, "include": null, "lang": null, "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": "github-repos/isabelle/glimonta-Semantics/Semantics-68d3cacdb2101c7e7c67fd3065266bb37db5f760/Exercise7/GabrielaLimonta2.thy", "reason": null, "repo": "Semantics", "save_path": "github-repos/isabelle/glimonta-Semantics", "sha": "68d3cacdb2101c7e7c67fd3065266bb37db5f760", "size": null }
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed May 6 08:19:34 2020 @author: firo """ import sys import argparse import numpy as np import networkx as nx from joblib import Parallel, delayed from wickingpnm.model import PNM from wickingpnm.simulation import Simulation, Material if __name__ == '__main__': ### Parse arguments parser = argparse.ArgumentParser(description = 'Simulation parameters') parser.add_argument('-v', '--verbose', action = 'store_true', help = 'Be verbose during the simulation') parser.add_argument('-G', '--generate-network', action = 'store_true', help = 'Generate an artificial pore network model and ignore -E, -P and -S') parser.add_argument('-f', '--sqrt-factor', type = float, default = 0, help = 'Show a square root with the given factor with the plots') parser.add_argument('-n', '--node-count', type = int, default = 100, help = 'The amount of nodes in the random graph (default to 100)') parser.add_argument('-c', '--iteration-count', type = int, default = 1, help = 'The amount of times to run the simulation (default to 1)') parser.add_argument('-s', '--time-step', type = float, default = 1E-3, help = 'The atomic time step to use throughout the simulation in seconds (default to 0.001)') parser.add_argument('-t', '--max-time', type = float, default = 1600, help = 'The amount of time to simulate in seconds (default to 1600)') parser.add_argument('-R', '--upstream-resistance', type = int, default = 2E17, help = 'Upstream resistance affecting the inlet pores (default to 2E17)') parser.add_argument('-i', '--inlets', type = str, default = '', help = 'Labels for inlet pores (random by default)') parser.add_argument('-m', '--material', type = str, default = '', help = 'Material parameters written as eta,gamma,theta,px') parser.add_argument('-j', '--job-count', type = int, default = 4, help = 'The amount of jobs to use (default to 4)') parser.add_argument('-E', '--exp-data', default = None, help = 'Path to the experimental data') parser.add_argument('-P', '--pore-data', default = None, help = 'Path to the pore network data') parser.add_argument('-S', '--stats-data', default = None, help = 'Path to the network statistics') parser.add_argument('-Np', '--no-plot', action = 'store_true', help = 'Don\'t plot the results') args = parser.parse_args() if args.iteration_count < 0: raise ValueError('-c has to be greater or equal to 0.') if args.job_count <= 0: raise ValueError('-j has to be greater or equal to 1.') # These are global variables that remain constant from here job_count = args.job_count verbose = args.verbose ### Initialize the PNM results = [] R_inlet = args.upstream_resistance # Pas/m3 inlets = args.inlets.split(',') # Previously [162, 171, 207] if '' in inlets: inlets = [] else: for inlet in inlets: inlet = int(inlet) pnm_params = { 'exp_data_path': args.exp_data, 'pore_data_path': args.pore_data, 'inlets': inlets, 'R_inlet': R_inlet, 'job_count': job_count, 'verbose': verbose } if args.stats_data is None: print('No network statistics were given, using random waiting times.') if args.generate_network: print('Generating an artificial network'); n = args.node_count pnm_params['graph'] = nx.random_regular_graph(4, n) elif pnm_params['exp_data_path'] is None: raise ValueError('Please use either -G or -E to choose a graph model') pnm = PNM(args.stats_data, **pnm_params) if verbose: print('\nre', pnm.radi, '\n') print('\nh0e', pnm.heights, '\n') print('\nwaiting times', pnm.waiting_times, '\n') print('\ninlets', pnm.inlets, '\n') if args.material: mp = [] for param in args.material.split(','): mp.append(np.float64(param)) material = Material(*mp) else: material = Material() print('Using material {}'.format(material)); simulation = Simulation(pnm, material = material, sqrt_factor = args.sqrt_factor, max_time = args.max_time, time_step = args.time_step, verbose = verbose ) ### Get simulation results I = args.iteration_count if I == 0: # We just wanted to build the network sys.exit() if I == 1: print('Starting the simulation to run once with a timestep of {}s.'.format(args.time_step)) results = [simulation.run()] else: njobs = min(I, job_count) print('Starting the simulation with a timestep of {}s for {} times with {} jobs.'.format(args.time_step, I, njobs)) results = Parallel(n_jobs=njobs)(delayed(simulation.run)() for i in range(I)) if not args.no_plot: simulation.plot_all(results)
{ "alphanum_fraction": 0.6400651466, "author": null, "avg_line_length": 41.6271186441, "converted": null, "ext": "py", "file": null, "hexsha": "b4e3072aa597db020667b970ac427fa457d3ce6c", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-05-14T16:05:23.000Z", "max_forks_repo_forks_event_min_datetime": "2020-05-14T16:05:23.000Z", "max_forks_repo_head_hexsha": "a6198350ae5a882e53ae2c59e83463540631e3b1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Pescatore23/wicking_pnm", "max_forks_repo_path": "network_script.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "a6198350ae5a882e53ae2c59e83463540631e3b1", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Pescatore23/wicking_pnm", "max_issues_repo_path": "network_script.py", "max_line_length": 168, "max_stars_count": null, "max_stars_repo_head_hexsha": "a6198350ae5a882e53ae2c59e83463540631e3b1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Pescatore23/wicking_pnm", "max_stars_repo_path": "network_script.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1235, "path": null, "reason": "import numpy,import networkx", "repo": null, "save_path": null, "sha": null, "size": 4912 }
[STATEMENT] lemma remove_shadow_root_get_child_nodes_is_l_remove_shadow_root_get_child_nodes [instances]: "l_remove_shadow_root_get_child_nodes get_child_nodes_locs remove_shadow_root_locs" [PROOF STATE] proof (prove) goal (1 subgoal): 1. l_remove_shadow_root_get_child_nodes Shadow_DOM.get_child_nodes_locs remove_shadow_root_locs [PROOF STEP] apply(auto simp add: l_remove_shadow_root_get_child_nodes_def instances )[1] [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>ptr shadow_root_ptr w element_ptr h h' r. \<lbrakk>ptr \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r shadow_root_ptr; w \<in> remove_shadow_root_locs element_ptr shadow_root_ptr; h \<turnstile> w \<rightarrow>\<^sub>h h'; r \<in> Shadow_DOM.get_child_nodes_locs ptr\<rbrakk> \<Longrightarrow> r h h' [PROOF STEP] using remove_shadow_root_get_child_nodes_different_pointers [PROOF STATE] proof (prove) using this: \<lbrakk>?ptr \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r ?shadow_root_ptr; ?w \<in> remove_shadow_root_locs ?element_ptr ?shadow_root_ptr; ?h \<turnstile> ?w \<rightarrow>\<^sub>h ?h'; ?r \<in> Shadow_DOM.get_child_nodes_locs ?ptr\<rbrakk> \<Longrightarrow> ?r ?h ?h' goal (1 subgoal): 1. \<And>ptr shadow_root_ptr w element_ptr h h' r. \<lbrakk>ptr \<noteq> cast\<^sub>s\<^sub>h\<^sub>a\<^sub>d\<^sub>o\<^sub>w\<^sub>_\<^sub>r\<^sub>o\<^sub>o\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r\<^sub>2\<^sub>o\<^sub>b\<^sub>j\<^sub>e\<^sub>c\<^sub>t\<^sub>_\<^sub>p\<^sub>t\<^sub>r shadow_root_ptr; w \<in> remove_shadow_root_locs element_ptr shadow_root_ptr; h \<turnstile> w \<rightarrow>\<^sub>h h'; r \<in> Shadow_DOM.get_child_nodes_locs ptr\<rbrakk> \<Longrightarrow> r h h' [PROOF STEP] apply fast [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "Shadow_DOM_Shadow_DOM", "hexsha": null, "include": null, "lang": null, "length": 4, "llama_tokens": 906, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": null }
import random import time import os import numpy as np from . import preprocess import torch import torch.nn.functional as F from torchvision.transforms.functional import hflip import torch.utils.data as data from PIL import Image from scipy import sparse from dsgn.utils.numpy_utils import * from dsgn.utils.numba_utils import * from dsgn.utils.torch_utils import * from dsgn.dataloader.kitti_dataset import kitti_dataset from dsgn.dataloader.KITTILoader3D import get_kitti_annos from dsgn.utils.bounding_box import Box3DList, compute_corners, quan_to_angle, \ angle_to_quan, quan_to_rotation, compute_corners_sc IMG_EXTENSIONS = [ '.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', ] def is_image_file(filename): return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) def default_loader(path): return Image.open(path).convert('RGB') def disparity_loader(path): return np.load(path).astype(np.float32) def convert_to_viewpoint_torch(alpha, z, x): return alpha + torch.atan2(z, x) - np.pi / 2 def convert_to_ry_torch(alpha, z, x): return alpha - torch.atan2(z, x) + np.pi / 2 class myImageFloder(data.Dataset): def __init__(self, left, right, left_disparity, training, loader=default_loader, dploader=disparity_loader, split=None, cfg=None, generate_target=False): self.left = left self.right = right self.disp_L = left_disparity self.loader = loader self.dploader = dploader self.training = training self.cfg = cfg self.num_classes = self.cfg.num_classes self.num_angles = self.cfg.num_angles if 'train.txt' in split: self.kitti_dataset = kitti_dataset('train').train_dataset elif 'val.txt' in split: self.kitti_dataset = kitti_dataset('train').val_dataset elif 'trainval.txt' in split: self.kitti_dataset = kitti_dataset('trainval').train_dataset elif 'test.txt' in split: self.kitti_dataset = kitti_dataset('trainval').val_dataset self.generate_target = generate_target self.save_path = './outputs/temp/anchor_{}angles'.format(self.cfg.num_angles) self.flip = getattr(self.cfg, 'flip', False) if 'trainval.txt' in split: self.save_path += '_trainval' self.valid_classes = getattr(self.cfg, 'valid_classes', None) if self.valid_classes is not None: self.save_path += '_validclass_{}'.format('_'.join(list( map(lambda x:str(x), self.valid_classes) ))) if 2 in self.valid_classes: self.less_car = getattr(cfg, 'less_car_pos', False) if self.less_car: self.save_path += '_lesscar' if 1 in self.valid_classes or 3 in self.valid_classes: self.less_human = getattr(cfg, 'less_human_pos', False) if self.less_human: self.save_path += '_lesshuman' if self.generate_target: os.system('mkdir {}'.format(self.save_path)) def __getitem__(self, index): left = self.left[index] right = self.right[index] disp_L = self.disp_L[index] image_index = int(left.split('/')[-1].split('.')[0]) if self.generate_target: if self.flip: self.flip_this_image = self.cfg.flip_this_image else: self.flip_this_image = False else: if self.flip and self.training: self.flip_this_image = np.random.randint(2) > 0.5 else: self.flip_this_image = False calib = self.kitti_dataset.get_calibration(image_index) calib_R = self.kitti_dataset.get_right_calibration(image_index) if self.flip_this_image: calib, calib_R = calib_R, calib baseline = np.fabs(calib.P[0,3]-calib_R.P[0,3])/calib.P[0,0] # ~ 0.54 t_cam2_from_cam0 = calib.t_cam2_from_cam0 left_img = self.loader(left) right_img = self.loader(right) if not self.flip_this_image: dataL = self.dploader(disp_L) else: disp_R = disp_L[:-4] + '_r.npy' dataL = self.dploader(disp_R) # box labels if self.training or self.generate_target: if self.cfg.RPN3D_ENABLE: labels = self.kitti_dataset.get_label_objects(image_index) boxes, box3ds, ori_classes = get_kitti_annos(labels, valid_classes= self.valid_classes) if len(boxes) > 0: boxes[:, [2,3]] = boxes[:, [0,1]] + boxes[:, [2,3]] boxes = clip_boxes(boxes, left_img.size, remove_empty=False) # sort(far -> near) inds = box3ds[:, 5].argsort()[::-1] box3ds = box3ds[inds] boxes = boxes[inds] ori_classes = ori_classes[inds] # sort by classes inds = ori_classes.argsort(kind='stable') box3ds = box3ds[inds] boxes = boxes[inds] ori_classes = ori_classes[inds] boxes = torch.as_tensor(boxes).reshape(-1, 4) # guard against no boxes box3ds = torch.as_tensor(box3ds).reshape(-1, 7) #transform to viewpoint from camera if self.cfg.learn_viewpoint: h, w, l, x, y, z, alpha = torch.split(box3ds, [1,1,1,1,1,1,1], 1) box3ds[:, 6:] = convert_to_viewpoint_torch(alpha, z, x) target = Box3DList(boxes, left_img.size, mode="xyxy", box3d=box3ds, Proj=calib.P, Proj_R=calib_R.P) classes = torch.as_tensor(ori_classes) target.add_field('labels', classes) if self.flip_this_image: target = target.transpose(0) if not self.flip_this_image: save_file = '{}/{:06d}.npz'.format(self.save_path, image_index) save_label_file = '{}/{:06d}_labels.npz'.format(self.save_path, image_index) else: save_file = '{}/{:06d}_flip.npz'.format(self.save_path, image_index) save_label_file = '{}/{:06d}_flip_labels.npz'.format(self.save_path, image_index) if self.generate_target: locations = compute_locations_bev(self.cfg.Z_MIN, self.cfg.Z_MAX, self.cfg.VOXEL_Z_SIZE, self.cfg.X_MIN, self.cfg.X_MAX, self.cfg.VOXEL_X_SIZE, torch.device('cpu')) xs, zs = locations[:, 0], locations[:, 1] labels_maps = [] dist_bevs = [] ious = [] for cls in self.valid_classes: ANCHORS_Y = self.cfg.RPN3D.ANCHORS_Y[cls-1] ANCHORS_HEIGHT, ANCHORS_WIDTH, ANCHORS_LENGTH = self.cfg.RPN3D.ANCHORS_HEIGHT[cls-1], self.cfg.RPN3D.ANCHORS_WIDTH[cls-1], self.cfg.RPN3D.ANCHORS_LENGTH[cls-1] ys = torch.zeros_like(xs) + ANCHORS_Y locations3d = torch.stack([xs, ys, zs], dim=1) locations3d = locations3d[:, None].repeat(1, self.cfg.num_angles, 1) hwl = torch.as_tensor([ANCHORS_HEIGHT, ANCHORS_WIDTH, ANCHORS_LENGTH]) hwl = hwl[None, None].repeat(len(locations3d), self.cfg.num_angles, 1) angles = torch.as_tensor(self.cfg.ANCHOR_ANGLES) angles = angles[None].repeat(len(locations3d), 1) sin, cos = torch.sin(angles), torch.cos(angles) z_size, y_size, x_size = self.cfg.GRID_SIZE anchors = torch.cat([hwl, locations3d, angles[:, :, None]], dim=2) anchors[:, :, 4] += anchors[:, :, 0] / 2. anchors = anchors.reshape(-1, 7) anchors_boxlist = Box3DList(torch.zeros(len(anchors), 4), left_img.size, mode='xyxy', box3d=anchors, Proj=calib.P, Proj_R=calib_R.P) inds_this_class = target.get_field('labels') == cls target_box3ds = target.box3d[inds_this_class] target_corners = (target.box_corners() + target.box3d[:, None, 3:6])[inds_this_class] anchor_corners = anchors_boxlist.box_corners() + anchors_boxlist.box3d[:, None, 3:6] dist_bev = torch.norm(anchor_corners[:, None, :4, [0,2]] - target_corners[None, :, :4, [0,2]], dim=-1) dist_bev = dist_bev.mean(dim=-1) dist_bev[dist_bev > 5.] = 5. dist_bevs.append(dist_bev) # note that this can one anchor <-> many labels labels_map = torch.zeros((len(dist_bev), len(target_box3ds)), dtype=torch.uint8) for i in range(len(target_box3ds)): if (cls == 2 and self.less_car) or ((cls == 1 or cls == 3) and self.less_human): box_pixels = (target_box3ds[i, 1] * target_box3ds[i, 2]) / np.fabs(self.cfg.VOXEL_X_SIZE * self.cfg.VOXEL_Z_SIZE) / 4. else: box_pixels = (target_box3ds[i, 1] * target_box3ds[i, 2]) / np.fabs(self.cfg.VOXEL_X_SIZE * self.cfg.VOXEL_Z_SIZE) box_pixels = int(box_pixels) topk_mindistance, topk_mindistance_ind = torch.topk(dist_bev[:, i], box_pixels, largest=False, sorted=False) labels_map[topk_mindistance_ind[topk_mindistance < 5.], i] = cls labels_maps.append(labels_map) dist_bev = torch.cat(dist_bevs, dim=1) sparse.save_npz(save_file, sparse.csr_matrix(dist_bev)) print('Saved {}'.format(save_file)) labels_map = torch.cat(labels_maps, dim=1) sparse.save_npz(save_label_file, sparse.csr_matrix(labels_map)) print('Saved {}'.format(save_label_file)) else: if self.training: iou = sparse.load_npz(save_file) labels_map = sparse.load_npz(save_label_file) w, h = left_img.size if self.flip_this_image: left_img, right_img = hflip(right_img), hflip(left_img) dataL = np.ascontiguousarray(dataL[:, ::-1]) processed = preprocess.get_transform(augment=False) left_img = processed(left_img) right_img = processed(right_img) left_img = torch.reshape(left_img,[1,3,left_img.shape[1],left_img.shape[2]]) right_img = torch.reshape(right_img,[1,3,right_img.shape[1],right_img.shape[2]]) img_size = (left_img.shape[2], left_img.shape[3]) top_pad = 384-left_img.shape[2] left_pad = 1248-left_img.shape[3] left_img = F.pad(left_img,(0,left_pad, 0,top_pad),'constant',0) right_img = F.pad(right_img,(0,left_pad, 0,top_pad),'constant',0) dataL = F.pad(torch.as_tensor(dataL), (0,left_pad, 0,top_pad), 'constant', -389.63037) outputs = [left_img, right_img, dataL, calib, calib_R] if self.training: outputs.append(image_index) if self.cfg.RPN3D_ENABLE: outputs.append(target) if self.cfg.RPN3D_ENABLE: outputs.append(iou) outputs.append(labels_map) else: outputs.extend([img_size, image_index]) return outputs def __len__(self): return len(self.left)
{ "alphanum_fraction": 0.5581299472, "author": null, "avg_line_length": 43.6258992806, "converted": null, "ext": "py", "file": null, "hexsha": "0ef628f7aac6e9ce4a7336caa4e69acf4dcae81d", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 35, "max_forks_repo_forks_event_max_datetime": "2021-05-16T07:45:02.000Z", "max_forks_repo_forks_event_min_datetime": "2020-04-27T13:11:42.000Z", "max_forks_repo_head_hexsha": "ac693e748ff3a7372b1292c2b7b3796854072030", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "joshliu11/DSGN", "max_forks_repo_path": "dsgn/dataloader/KITTILoader_dataset3d.py", "max_issues_count": 15, "max_issues_repo_head_hexsha": "ac693e748ff3a7372b1292c2b7b3796854072030", "max_issues_repo_issues_event_max_datetime": "2021-05-05T12:03:51.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-12T23:58:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "joshliu11/DSGN", "max_issues_repo_path": "dsgn/dataloader/KITTILoader_dataset3d.py", "max_line_length": 187, "max_stars_count": 166, "max_stars_repo_head_hexsha": "ac693e748ff3a7372b1292c2b7b3796854072030", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "joshliu11/DSGN", "max_stars_repo_path": "dsgn/dataloader/KITTILoader_dataset3d.py", "max_stars_repo_stars_event_max_datetime": "2021-05-16T07:42:15.000Z", "max_stars_repo_stars_event_min_datetime": "2020-04-20T09:30:54.000Z", "num_tokens": 2825, "path": null, "reason": "import numpy,from scipy", "repo": null, "save_path": null, "sha": null, "size": 12128 }
# src: https://github.com/facebookresearch/DrQA/blob/master/drqa/reader/data.py import numpy as np from torch.utils.data import Dataset from torch.utils.data.sampler import Sampler from .vector import vectorize # ------------------------------------------------------------------------------ # PyTorch dataset class for MSMARCO data. # ------------------------------------------------------------------------------ class RankerDataset(Dataset): def __init__(self, examples, model, shuffle=False): self.model = model self.examples = examples self.shuffle = shuffle def __len__(self): return len(self.examples) def __getitem__(self, index): return vectorize(self.examples[index], self.model, shuffle=self.shuffle) def lengths(self): return [(max([len(doc.tokens) for doc in ex.documents]), len(ex.tokens)) for ex in self.examples] # ------------------------------------------------------------------------------ # PyTorch sampler returning batched of sorted lengths (by doc and query). # ------------------------------------------------------------------------------ class SortedBatchSampler(Sampler): def __init__(self, lengths, batch_size, shuffle=True): self.lengths = lengths self.batch_size = batch_size self.shuffle = shuffle def __iter__(self): lengths = np.array( [(-l[0], -l[1], np.random.random()) for l in self.lengths], dtype=[('l1', np.int_), ('l2', np.int_), ('rand', np.float_)] ) indices = np.argsort(lengths, order=('l1', 'l2', 'rand')) batches = [indices[i:i + self.batch_size] for i in range(0, len(indices), self.batch_size)] if self.shuffle: np.random.shuffle(batches) return iter([i for batch in batches for i in batch]) def __len__(self): return len(self.lengths)
{ "alphanum_fraction": 0.5024606299, "author": null, "avg_line_length": 35.649122807, "converted": null, "ext": "py", "file": null, "hexsha": "f7c335b390063b50c4b185305a34e53ec458cfad", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 22, "max_forks_repo_forks_event_max_datetime": "2021-09-14T05:52:44.000Z", "max_forks_repo_forks_event_min_datetime": "2019-10-03T03:37:30.000Z", "max_forks_repo_head_hexsha": "989fbfee5a0ac6b7ac7429bdee36fe6ed93ee234", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "niazangels/context_attentive_ir", "max_forks_repo_path": "neuroir/inputters/ranker/data.py", "max_issues_count": 11, "max_issues_repo_head_hexsha": "989fbfee5a0ac6b7ac7429bdee36fe6ed93ee234", "max_issues_repo_issues_event_max_datetime": "2021-12-14T02:41:55.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-13T09:34:15.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "niazangels/context_attentive_ir", "max_issues_repo_path": "neuroir/inputters/ranker/data.py", "max_line_length": 81, "max_stars_count": 77, "max_stars_repo_head_hexsha": "989fbfee5a0ac6b7ac7429bdee36fe6ed93ee234", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "niazangels/context_attentive_ir", "max_stars_repo_path": "neuroir/inputters/ranker/data.py", "max_stars_repo_stars_event_max_datetime": "2021-12-16T06:51:29.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-23T09:40:31.000Z", "num_tokens": 395, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 2032 }
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc c Write res to IBIS file (out=res) subroutine write_res(res,ids) implicit none c Inputs... real res(2,202) !reseau locations integer*4 ids(5) !frame,camera,filter,year,day integer runit,ibis !VICAR and IBIS unit numbers for res integer nrows/1/ !res is an IBIS file of 1 row integer ind character*80 msg character*6 format(409) /5*'full',404*'real'/ c ...open runit as a VICAR file to write history label call xvunit(runit,'out',1,ind,0) !out=(res,geo) call xvopen(runit,ind,'op','write','open_act','sa', & 'io_act','sa',' ') call xladd(runit,'history','title','**RESLOC COORDINATES**', . ind,'format','string',0) call xvclose(runit,ind,0 ) c ...open res as an IBIS file to write res call xvunit(runit,'out',1,ind,0) call ibis_file_open(runit,ibis,'write',409,nrows,format,0,ind) if (ind.ne.1) call ibis_signal_u(runit,ind,1) call putlocv2(runit,ibis,nrows,ids,res) !write the record call ibis_file_close(ibis,' ',ind) return end
{ "alphanum_fraction": 0.6527777778, "author": null, "avg_line_length": 36, "converted": null, "ext": "f", "file": null, "hexsha": "80ad1771887683a8e3faf811b2288da065ff75d2", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-03-23T00:23:24.000Z", "max_forks_repo_forks_event_min_datetime": "2021-03-09T01:51:08.000Z", "max_forks_repo_head_hexsha": "4504c1f558855d9c6eaef89f4460217aa4909f8e", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "NASA-AMMOS/VICAR", "max_forks_repo_path": "vos/p2/prog/resloc/write_res.f", "max_issues_count": null, "max_issues_repo_head_hexsha": "4504c1f558855d9c6eaef89f4460217aa4909f8e", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "NASA-AMMOS/VICAR", "max_issues_repo_path": "vos/p2/prog/resloc/write_res.f", "max_line_length": 74, "max_stars_count": 16, "max_stars_repo_head_hexsha": "4504c1f558855d9c6eaef89f4460217aa4909f8e", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "NASA-AMMOS/VICAR", "max_stars_repo_path": "vos/p2/prog/resloc/write_res.f", "max_stars_repo_stars_event_max_datetime": "2022-03-31T10:02:01.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-21T05:56:26.000Z", "num_tokens": 372, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 1152 }
import pytest import numpy as np from scipy.special import zeta from scipy.optimize import fsolve from scipy.constants import speed_of_light from options_tails.PowerLaw import PowerLaw __author__ = "JNSFilipe" __copyright__ = "JNSFilipe" __license__ = "mit" def test_PowerLaw(): ## Create a Normal Random Distribution with Fat Tails, ## for falues above 2 standard deviations. It is assumed ## that the normal dist has mean 0 and std 1. Only right ## tail is considered. True Value of alpha must be prev. ## computed, by solvig the equation that equals the ## normal distribution and the power law distribution. ## Lastly, we check if the error of the estimated alpha ## and x_min are within 10% of the true values # Set random seed for reproducibility np.random.seed(int(speed_of_light)) # Set number of standard deviations where we transition # from normal distribution to the power law n_std = 2 # Compute true value of alpha def f(a,x): z = a*np.log(x)-x**2/2-np.log(np.sqrt(2*np.pi)/zeta(a)) return z alpha = fsolve(lambda a: f(a,n_std), 1.0000001)[0] # Generate random samples of the Normal Distribution g = np.random.normal(0,1, 1000) # Drop values below 0 and above the transition point g = g[(g>0) & (g<n_std)] # Compute true x_min x_min = len(g) # Generate random samples of the Power Law Distribution p = np.random.zipf(alpha, 1000) # Drop values below the transition point p = p[p>2] # Join the values of the two distrubutions into one x = np.concatenate([g,p]) # Estimate power law parameters pl = PowerLaw() pl.fit(x) # Define function to compute percentual difference def pct_diff(ref, val): return np.abs((val-ref)/ref)*100 # Verify that estimated vales are within +/-10% error assert pct_diff(alpha, pl._alpha) <= 15 assert pct_diff(x_min, pl._xmin) <= 15
{ "alphanum_fraction": 0.6668331668, "author": null, "avg_line_length": 30.8, "converted": null, "ext": "py", "file": null, "hexsha": "28cac688fe523ec6b03e396e0f2c29ae3284a1ee", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "9a48718af3a42f57363afaa40e89ca8cc866b9bd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JNSFilipe/options-tails", "max_forks_repo_path": "tests/test_PowerLaw.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "9a48718af3a42f57363afaa40e89ca8cc866b9bd", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "JNSFilipe/options-tails", "max_issues_repo_path": "tests/test_PowerLaw.py", "max_line_length": 63, "max_stars_count": null, "max_stars_repo_head_hexsha": "9a48718af3a42f57363afaa40e89ca8cc866b9bd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "JNSFilipe/options-tails", "max_stars_repo_path": "tests/test_PowerLaw.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 529, "path": null, "reason": "import numpy,from scipy", "repo": null, "save_path": null, "sha": null, "size": 2002 }
module Mandrill using Requests using JSON using Compat if VERSION < v"0.4.0" Base.split(str, spl; limit=0, keep=true) = split(str, spl, limit, keep) end global const api = "https://mandrillapp.com/api/1.0" # package code goes here function __init__() global mandrill_key = get(ENV, "MANDRILL_KEY", "") end function key() if !isdefined(Mandrill, :mandrill_key) || isempty(mandrill_key) error("""API Key not provided Please define MANDRILL_KEY as an environment variable Or call Mandrill.key(k) before using any other function""") else return mandrill_key::ASCIIString end end key(k::ASCIIString) = global mandrill_key = k macro mandrill_api(endpoint) splt = split(string(endpoint), '/'; keep=false) @assert size(splt, 1) == 2 fn = symbol(string(splt[1], "_", splt[2])) d = quote function $(esc(fn))(req=Dict{ASCIIString, Any}()) mandrill_api_request($(string(api, endpoint)), req) end end end function mandrill_api_request{T <: AbstractString, S <:Any}(endpoint, req::Dict{T,S}) req["key"] = key() res = Requests.post(URI(endpoint), JSON.json(req)) if res.status == 200 return Requests.json(res) else mandrill_error(Requests.json(res)) end end function mandrill_error(res::Dict) error("""Mandrill API $(res["status"]) $(res["code"]): $(res["name"]) $(res["message"])""") end @mandrill_api "/users/ping2" @mandrill_api "/users/info" @mandrill_api "/users/senders" @mandrill_api "/messages/send" @mandrill_api "/messages/send-template" @mandrill_api "/messages/search" @mandrill_api "/messages/search-time-series" @mandrill_api "/messages/info" @mandrill_api "/messages/content" @mandrill_api "/messages/parse" @mandrill_api "/messages/send-raw" @mandrill_api "/messages/list-scheduled" @mandrill_api "/messages/cancel-scheduled" @mandrill_api "/messages/reschedule" @mandrill_api "/tags/list" @mandrill_api "/tags/delete" @mandrill_api "/tags/info" @mandrill_api "/tags/time-series" @mandrill_api "/tags/all-time-series" @mandrill_api "/rejects/add" @mandrill_api "/rejects/list" @mandrill_api "/rejects/delete" @mandrill_api "/whitelists/add" @mandrill_api "/whitelists/list" @mandrill_api "/whitelists/delete" @mandrill_api "/senders/list" @mandrill_api "/senders/domains" @mandrill_api "/senders/add-domain" @mandrill_api "/senders/check-domain" @mandrill_api "/senders/verify-domain" @mandrill_api "/senders/info" @mandrill_api "/senders/time-series" @mandrill_api "/urls/list" @mandrill_api "/urls/search" @mandrill_api "/urls/time-series" @mandrill_api "/urls/tracking-domains" @mandrill_api "/urls/add-tracking-domain" @mandrill_api "/urls/check-tracking-domain" @mandrill_api "/templates/add" @mandrill_api "/templates/info" @mandrill_api "/templates/update" @mandrill_api "/templates/publish" @mandrill_api "/templates/delete" @mandrill_api "/templates/list" @mandrill_api "/templates/time-series" @mandrill_api "/templates/render" @mandrill_api "/webhooks/list" @mandrill_api "/webhooks/add" @mandrill_api "/webhooks/info" @mandrill_api "/webhooks/update" @mandrill_api "/webhooks/delete" @mandrill_api "/subaccounts/list" @mandrill_api "/subaccounts/add" @mandrill_api "/subaccounts/info" @mandrill_api "/subaccounts/update" @mandrill_api "/subaccounts/delete" @mandrill_api "/subaccounts/pause" @mandrill_api "/subaccounts/resume" @mandrill_api "/inbound/domains" @mandrill_api "/inbound/add-domain" @mandrill_api "/inbound/check-domain" @mandrill_api "/inbound/delete-domain" @mandrill_api "/inbound/routes" @mandrill_api "/inbound/add-route" @mandrill_api "/inbound/update-route" @mandrill_api "/inbound/delete-route" @mandrill_api "/inbound/send-raw" @mandrill_api "/exports/info" @mandrill_api "/exports/list" @mandrill_api "/exports/rejects" @mandrill_api "/exports/whitelist" @mandrill_api "/exports/activity" @mandrill_api "/ips/list" @mandrill_api "/ips/info" @mandrill_api "/ips/provision" @mandrill_api "/ips/start-warmup" @mandrill_api "/ips/cancel-warmup" @mandrill_api "/ips/set-pool" @mandrill_api "/ips/delete" @mandrill_api "/ips/list-pools" @mandrill_api "/ips/pool-info" @mandrill_api "/ips/create-pool" @mandrill_api "/ips/delete-pool" @mandrill_api "/ips/check-custom-dns" @mandrill_api "/ips/set-custom-dns" @mandrill_api "/metadata/list" @mandrill_api "/metadata/add" @mandrill_api "/metadata/update" @mandrill_api "/metadata/delete" end # module
{ "alphanum_fraction": 0.7428311334, "author": null, "avg_line_length": 29.8911564626, "converted": null, "ext": "jl", "file": null, "hexsha": "a9d9723fa7ef725631a79eaf0be47c64249c94cb", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2021-10-01T12:41:55.000Z", "max_forks_repo_forks_event_min_datetime": "2015-11-17T20:43:12.000Z", "max_forks_repo_head_hexsha": "0c8d9f08d588f5ccc3d87e26dd01b88f81366eee", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "UnofficialJuliaMirrorSnapshots/Mandrill.jl-abae6431-9fef-548a-acae-ed4840f45913", "max_forks_repo_path": "src/Mandrill.jl", "max_issues_count": 2, "max_issues_repo_head_hexsha": "0c8d9f08d588f5ccc3d87e26dd01b88f81366eee", "max_issues_repo_issues_event_max_datetime": "2019-10-09T08:33:12.000Z", "max_issues_repo_issues_event_min_datetime": "2018-06-22T08:30:55.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "UnofficialJuliaMirrorSnapshots/Mandrill.jl-abae6431-9fef-548a-acae-ed4840f45913", "max_issues_repo_path": "src/Mandrill.jl", "max_line_length": 85, "max_stars_count": 2, "max_stars_repo_head_hexsha": "0c8d9f08d588f5ccc3d87e26dd01b88f81366eee", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "UnofficialJuliaMirrorSnapshots/Mandrill.jl-abae6431-9fef-548a-acae-ed4840f45913", "max_stars_repo_path": "src/Mandrill.jl", "max_stars_repo_stars_event_max_datetime": "2019-05-22T09:28:54.000Z", "max_stars_repo_stars_event_min_datetime": "2016-01-14T13:05:37.000Z", "num_tokens": 1320, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 4394 }
import numpy from coopihc.inference.GoalInferenceWithUserPolicyGiven import ( GoalInferenceWithUserPolicyGiven, ) from coopihc.policy.ELLDiscretePolicy import ELLDiscretePolicy from coopihc.base.State import State from coopihc.base.elements import discrete_array_element, array_element # ----- needed before testing engine action_state = State() action_state["action"] = discrete_array_element(init=0, low=-3, high=3) user_policy = ELLDiscretePolicy(action_state=action_state) ERROR_RATE = 0.05 def compute_likelihood(self, action, observation, error_rate=ERROR_RATE): # convert actions and observations action = action.squeeze().tolist() position = observation["task_state"]["position"].tolist() if action == -position: return 1 - error_rate else: return error_rate # Attach likelihood function to the policy user_policy.attach_likelihood_function(compute_likelihood) def test_init(): inference_engine = GoalInferenceWithUserPolicyGiven() assert inference_engine.user_policy_model is None inference_engine = GoalInferenceWithUserPolicyGiven(user_policy_model=user_policy) assert inference_engine.user_policy_model is user_policy assistant_state = State() assistant_state["beliefs"] = array_element( init=numpy.array([1 / 7 for i in range(7)]), low=numpy.zeros((7,)), high=numpy.ones((7,)), out_of_bounds_mode="silent", # may go outside of [0,1] e.g. prior to renormalizing. ) chosen_action = 1 user_action = State() user_action["action"] = discrete_array_element(init=chosen_action, low=-3, high=3) observation = State(**{"assistant_state": assistant_state, "user_action": user_action}) set_theta = [ {("task_state", "position"): discrete_array_element(init=t, low=-3, high=3)} for t in [-3, -2, -1, 0, 1, 2, 3] ] def test_infer(): inference_engine = GoalInferenceWithUserPolicyGiven(user_policy_model=user_policy) inference_engine.attach_set_theta(set_theta) inference_engine.buffer = [] inference_engine.buffer.append(observation) state, reward = inference_engine.infer() assert reward == 0 prior = [1 / 7 for i in range(7)] posterior = [1 / 7 * ERROR_RATE for i in range(7)] posterior[2] = 1 / 7 * (1 - ERROR_RATE) posterior = [p / sum(posterior) for p in posterior] assert ( numpy.linalg.norm( state["beliefs"].reshape( -1, ) - numpy.array(posterior) ) < 1e-6 ) if __name__ == "__main__": test_init() test_infer()
{ "alphanum_fraction": 0.7096900745, "author": null, "avg_line_length": 30.7108433735, "converted": null, "ext": "py", "file": null, "hexsha": "5930b854ac44251c768023edd1841c17b33486b9", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-03-08T11:10:24.000Z", "max_forks_repo_forks_event_min_datetime": "2022-03-08T11:10:24.000Z", "max_forks_repo_head_hexsha": "0fe24c618a430517c1394625275faff3ce344f7f", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jgori-ouistiti/CoopIHC", "max_forks_repo_path": "test/components/inference/test_GIWUPG.py", "max_issues_count": 52, "max_issues_repo_head_hexsha": "0fe24c618a430517c1394625275faff3ce344f7f", "max_issues_repo_issues_event_max_datetime": "2022-03-15T12:28:18.000Z", "max_issues_repo_issues_event_min_datetime": "2021-11-23T13:49:50.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "jgori-ouistiti/CoopIHC", "max_issues_repo_path": "test/components/inference/test_GIWUPG.py", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "0fe24c618a430517c1394625275faff3ce344f7f", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jgori-ouistiti/CoopIHC", "max_stars_repo_path": "test/components/inference/test_GIWUPG.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 632, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 2549 }
# Adapted from https://github.com/sniklaus/pytorch-pwc/blob/master/run.py import math import os import sys import tempfile import numpy as np import torch import sys from tqdm import tqdm arguments_strModel = 'default' ########################################################## Backward_tensorGrid = {} Backward_tensorPartial = {} def Backward(tensorInput, tensorFlow): if str(tensorFlow.size()) not in Backward_tensorGrid: tensorHorizontal = torch.linspace(-1.0, 1.0, tensorFlow.size(3)).view( 1, 1, 1, tensorFlow.size(3)).expand(tensorFlow.size(0), -1, tensorFlow.size(2), -1) tensorVertical = torch.linspace(-1.0, 1.0, tensorFlow.size(2)).view( 1, 1, tensorFlow.size(2), 1).expand(tensorFlow.size(0), -1, -1, tensorFlow.size(3)) Backward_tensorGrid[str(tensorFlow.size())] = torch.cat( [tensorHorizontal, tensorVertical], 1).cuda() # end if str(tensorFlow.size()) not in Backward_tensorPartial: Backward_tensorPartial[str(tensorFlow.size())] = tensorFlow.new_ones( [tensorFlow.size(0), 1, tensorFlow.size(2), tensorFlow.size(3)]) # end tensorFlow = torch.cat([tensorFlow[:, 0:1, :, :] / ((tensorInput.size(3) - 1.0) / 2.0), tensorFlow[:, 1:2, :, :] / ((tensorInput.size(2) - 1.0) / 2.0)], 1) tensorInput = torch.cat( [tensorInput, Backward_tensorPartial[str(tensorFlow.size())]], 1) tensorOutput = torch.nn.functional.grid_sample(input=tensorInput, grid=(Backward_tensorGrid[str( tensorFlow.size())] + tensorFlow).permute(0, 2, 3, 1), mode='bilinear', padding_mode='zeros') tensorMask = tensorOutput[:, -1:, :, :] tensorMask[tensorMask > 0.999] = 1.0 tensorMask[tensorMask < 1.0] = 0.0 return tensorOutput[:, :-1, :, :] * tensorMask # end ########################################################## class Network(torch.nn.Module): def __init__(self): super(Network, self).__init__() class Extractor(torch.nn.Module): def __init__(self): super(Extractor, self).__init__() self.moduleOne = torch.nn.Sequential( torch.nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=2, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) self.moduleTwo = torch.nn.Sequential( torch.nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=2, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) self.moduleThr = torch.nn.Sequential( torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) self.moduleFou = torch.nn.Sequential( torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) self.moduleFiv = torch.nn.Sequential( torch.nn.Conv2d(in_channels=96, out_channels=128, kernel_size=3, stride=2, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) self.moduleSix = torch.nn.Sequential( torch.nn.Conv2d(in_channels=128, out_channels=196, kernel_size=3, stride=2, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) # end def forward(self, tensorInput): tensorOne = self.moduleOne(tensorInput) tensorTwo = self.moduleTwo(tensorOne) tensorThr = self.moduleThr(tensorTwo) tensorFou = self.moduleFou(tensorThr) tensorFiv = self.moduleFiv(tensorFou) tensorSix = self.moduleSix(tensorFiv) return [tensorOne, tensorTwo, tensorThr, tensorFou, tensorFiv, tensorSix] # end # end class Decoder(torch.nn.Module): def __init__(self, intLevel): super(Decoder, self).__init__() intPrevious = [None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None][intLevel + 1] intCurrent = [None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None][intLevel + 0] if intLevel < 6: self.moduleUpflow = torch.nn.ConvTranspose2d( in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1) if intLevel < 6: self.moduleUpfeat = torch.nn.ConvTranspose2d( in_channels=intPrevious + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=4, stride=2, padding=1) if intLevel < 6: self.dblBackward = [None, None, None, 5.0, 2.5, 1.25, 0.625, None][intLevel + 1] self.moduleOne = torch.nn.Sequential( torch.nn.Conv2d( in_channels=intCurrent, out_channels=128, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) self.moduleTwo = torch.nn.Sequential( torch.nn.Conv2d(in_channels=intCurrent + 128, out_channels=128, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) self.moduleThr = torch.nn.Sequential( torch.nn.Conv2d(in_channels=intCurrent + 128 + 128, out_channels=96, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) self.moduleFou = torch.nn.Sequential( torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96, out_channels=64, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) self.moduleFiv = torch.nn.Sequential( torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64, out_channels=32, kernel_size=3, stride=1, padding=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1) ) self.moduleSix = torch.nn.Sequential( torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=3, stride=1, padding=1) ) # end def forward(self, tensorFirst, tensorSecond, objectPrevious): try: from correlation import correlation # the custom cost volume layer except: sys.path.insert(0, './correlation'); import correlation # you should consider upgrading python tensorFlow = None tensorFeat = None if objectPrevious is None: tensorFlow = None tensorFeat = None tensorVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation( tensorFirst=tensorFirst, tensorSecond=tensorSecond), negative_slope=0.1, inplace=False) tensorFeat = torch.cat([tensorVolume], 1) elif objectPrevious is not None: tensorFlow = self.moduleUpflow( objectPrevious['tensorFlow']) tensorFeat = self.moduleUpfeat( objectPrevious['tensorFeat']) tensorVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tensorFirst=tensorFirst, tensorSecond=Backward( tensorInput=tensorSecond, tensorFlow=tensorFlow * self.dblBackward)), negative_slope=0.1, inplace=False) tensorFeat = torch.cat( [tensorVolume, tensorFirst, tensorFlow, tensorFeat], 1) # end tensorFeat = torch.cat( [self.moduleOne(tensorFeat), tensorFeat], 1) tensorFeat = torch.cat( [self.moduleTwo(tensorFeat), tensorFeat], 1) tensorFeat = torch.cat( [self.moduleThr(tensorFeat), tensorFeat], 1) tensorFeat = torch.cat( [self.moduleFou(tensorFeat), tensorFeat], 1) tensorFeat = torch.cat( [self.moduleFiv(tensorFeat), tensorFeat], 1) tensorFlow = self.moduleSix(tensorFeat) return { 'tensorFlow': tensorFlow, 'tensorFeat': tensorFeat } # end # end class Refiner(torch.nn.Module): def __init__(self): super(Refiner, self).__init__() self.moduleMain = torch.nn.Sequential( torch.nn.Conv2d(in_channels=81 + 32 + 2 + 2 + 128 + 128 + 96 + 64 + 32, out_channels=128, kernel_size=3, stride=1, padding=1, dilation=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=2, dilation=2), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=4, dilation=4), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=128, out_channels=96, kernel_size=3, stride=1, padding=8, dilation=8), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=96, out_channels=64, kernel_size=3, stride=1, padding=16, dilation=16), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1, dilation=1), torch.nn.LeakyReLU(inplace=False, negative_slope=0.1), torch.nn.Conv2d(in_channels=32, out_channels=2, kernel_size=3, stride=1, padding=1, dilation=1) ) # end def forward(self, tensorInput): return self.moduleMain(tensorInput) # end # end self.moduleExtractor = Extractor() self.moduleTwo = Decoder(2) self.moduleThr = Decoder(3) self.moduleFou = Decoder(4) self.moduleFiv = Decoder(5) self.moduleSix = Decoder(6) self.moduleRefiner = Refiner() # self.load_state_dict(torch.load('./network-' + arguments_strModel + '.pytorch')) self.load_state_dict(torch.load( './checkpoints/network-' + arguments_strModel + '.pytorch')) # end def forward(self, tensorFirst, tensorSecond): tensorFirst = self.moduleExtractor(tensorFirst) tensorSecond = self.moduleExtractor(tensorSecond) objectEstimate = self.moduleSix( tensorFirst[-1], tensorSecond[-1], None) objectEstimate = self.moduleFiv( tensorFirst[-2], tensorSecond[-2], objectEstimate) objectEstimate = self.moduleFou( tensorFirst[-3], tensorSecond[-3], objectEstimate) objectEstimate = self.moduleThr( tensorFirst[-4], tensorSecond[-4], objectEstimate) objectEstimate = self.moduleTwo( tensorFirst[-5], tensorSecond[-5], objectEstimate) return objectEstimate['tensorFlow'] + self.moduleRefiner(objectEstimate['tensorFeat']) # end # end ########################################################## def estimate(moduleNetwork, tensorFirst, tensorSecond): assert(tensorFirst.size(1) == tensorSecond.size(1)) assert(tensorFirst.size(2) == tensorSecond.size(2)) intWidth = tensorFirst.size(2) intHeight = tensorFirst.size(1) # assert(intWidth == 1024) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue # assert(intHeight == 436) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue tensorPreprocessedFirst = tensorFirst.cuda().view(1, 3, intHeight, intWidth) tensorPreprocessedSecond = tensorSecond.cuda().view(1, 3, intHeight, intWidth) intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 64.0) * 64.0)) intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 64.0) * 64.0)) tensorPreprocessedFirst = torch.nn.functional.interpolate(input=tensorPreprocessedFirst, size=( intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False) tensorPreprocessedSecond = torch.nn.functional.interpolate(input=tensorPreprocessedSecond, size=( intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False) tensorFlow = 20.0 * torch.nn.functional.interpolate(input=moduleNetwork( tensorPreprocessedFirst, tensorPreprocessedSecond), size=(intHeight, intWidth), mode='bilinear', align_corners=False) tensorFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth) tensorFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight) return tensorFlow[0, :, :, :].cpu() # New code for tracking and warping def tensor_from_im(im): return torch.FloatTensor(im[:, :, ::-1].transpose(2, 0, 1).astype(np.float32) * (1.0 / 255.0)) def calculate_flow_on_video(ims): moduleNetwork = Network().cuda().eval() # make sure to not compute gradients for computational performance torch.set_grad_enabled(False) # make sure to use cudnn for computational performance torch.backends.cudnn.enabled = True flows = [] base = np.mgrid[:ims[0].shape[0], :ims[0].shape[1]].astype(np.float32) base = base[::-1] for t in tqdm(range(len(ims) - 1), desc='Calculating Flow'): flow = estimate(moduleNetwork, tensor_from_im( ims[t]), tensor_from_im(ims[t + 1])) flow = flow.numpy() # convert flow from relative to absolute coordinates flow = flow + base flows.append(flow) flows = np.array(flows) flows_relative = flows - base[None, :] return flows_relative def main(): input_path = sys.argv[1] output_path = sys.argv[2] gpu_id = sys.argv[3] # set up gpu os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id) global device device = torch.device('cuda') import numpy as np ims = np.load(input_path) flow = calculate_flow_on_video(ims) np.save(output_path, flow) if __name__ == '__main__': main()
{ "alphanum_fraction": 0.5563076587, "author": null, "avg_line_length": 45.3440594059, "converted": null, "ext": "py", "file": null, "hexsha": "ef884d0b0f0e7cfa34588430c1532d2e5f24f315", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 22, "max_forks_repo_forks_event_max_datetime": "2022-03-18T03:28:21.000Z", "max_forks_repo_forks_event_min_datetime": "2020-09-15T01:55:16.000Z", "max_forks_repo_head_hexsha": "4a9d0d5af373d682be29487e68b9233809552e08", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ruizewang/avobjects", "max_forks_repo_path": "flow/pwcnet.py", "max_issues_count": 8, "max_issues_repo_head_hexsha": "4a9d0d5af373d682be29487e68b9233809552e08", "max_issues_repo_issues_event_max_datetime": "2022-01-29T13:30:25.000Z", "max_issues_repo_issues_event_min_datetime": "2020-11-13T08:54:38.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ruizewang/avobjects", "max_issues_repo_path": "flow/pwcnet.py", "max_line_length": 152, "max_stars_count": 88, "max_stars_repo_head_hexsha": "4a9d0d5af373d682be29487e68b9233809552e08", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "noammy/avobjects", "max_stars_repo_path": "flow/pwcnet.py", "max_stars_repo_stars_event_max_datetime": "2022-03-29T02:38:12.000Z", "max_stars_repo_stars_event_min_datetime": "2020-08-26T15:51:39.000Z", "num_tokens": 4147, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 18319 }
# import libraries import pandas as pd import numpy as np from sqlalchemy import create_engine from nltk.tokenize import word_tokenize from nltk.stem import WordNetLemmatizer import nltk import pickle from joblib import dump, load nltk.download('punkt') nltk.download('wordnet') nltk.download('omw-1.4') from sklearn.multioutput import MultiOutputClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import SGDClassifier from sklearn.model_selection import train_test_split from sklearn.pipeline import Pipeline, FeatureUnion from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer from sklearn.metrics import classification_report, recall_score, precision_score, f1_score, average_precision_score from sklearn.feature_extraction.text import HashingVectorizer from sklearn.model_selection import GridSearchCV def LoadData(dataBasePath, databaseTableName): '''Loads the data from the database. Returns a pandas dataframe.''' # load data from database engine = create_engine(dataBasePath) df = pd.read_sql(databaseTableName, engine) return df def PreprocessData(df): '''Preprocesses a pandas dataframe. Outputs features X and targets Y.''' X = df['message'] Y = df.drop(columns=['id', 'message','original', 'genre']) #Remove classes that are not binary columns_to_remove = [] for name in Y.columns: if(Y[name].min() != 0 or Y[name].max() != 1): print(f'This is not a binary feature, will remove it: {name}') columns_to_remove.append(name) if len(columns_to_remove) > 0: print(f'dropping {len(columns_to_remove)} Columns') Y.drop(columns=columns_to_remove, inplace=True) return X, Y def tokenize(text): '''This will take a text string and tokenize it. A list of clean tokens are returned.''' tokens = word_tokenize(text) lemmatizer = WordNetLemmatizer() clean_tokens = [lemmatizer.lemmatize(x).lower().strip() for x in tokens] return clean_tokens def CreatePipeline(): '''This creates and returns a full pipeline object.''' pipeline = Pipeline([ ('features', FeatureUnion([ ('text_pipeline', Pipeline([ ('vect', CountVectorizer(tokenizer=tokenize)), ('tfidf', TfidfTransformer()) ])), ('hashing_vectorizer', HashingVectorizer()) ])), ('clf', MultiOutputClassifier(SGDClassifier(penalty='l2', loss='log', alpha=1e-5, random_state=42, max_iter=5, tol=None) ))]) #Create parameters to use during grid search parameters = { 'clf__estimator__loss': ['hinge', 'log', 'perceptron'], 'clf__estimator__alpha': [1e-3, 1e-4, 1e-5], 'clf__estimator__penalty': ['l1', 'l2'], } #Create a grid search object cv = GridSearchCV(pipeline, param_grid=parameters, n_jobs=-1, verbose=2, scoring='f1_weighted') return cv def EvaluateModel(model, X_test, Y_test): '''This takes a model as input, along with the X and Y test sets. It then evaluates the model and outputs some metrics.''' Y_pred = model.predict(X_test) total_hits = np.sum(np.sum(Y_pred == Y_test)) total_misses = np.sum(np.sum(Y_pred != Y_test)) total_accuracy = total_hits/(total_hits + total_misses) target_names = [name for name in Y_test.columns] precisions = [] recalls = [] f1scores = [] for (name, col) in zip(target_names, range(len(target_names))): y_test = Y_test[name].values y_pred = Y_pred[:, col] if(np.max(y_test) <= 1): #Only one category precisions.append(precision_score(y_test, y_pred)) recalls.append(recall_score(y_test, y_pred)) f1scores.append(f1_score(y_test, y_pred)) print(f'Category: {name}') print(classification_report(y_test, y_pred)) print('-'*42) print(f'Total Accuracy: {total_accuracy}') print(f'Average Precission: {np.average(precisions)}') print(f'Average Recall: {np.average(recalls)}') print(f'Average F1 Score: {np.average(f1scores)}') def main(modelName, dataBasePath, databaseTableName): '''This runs the full train pipeline and writes a pickled model.''' #Load data print(f'Loading data from db: {dataBasePath} table: {databaseTableName}') df = LoadData(dataBasePath, databaseTableName) #Create Features/Targets print('Preprocessing data') X, Y = PreprocessData(df) #Split into Train/test sets X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42) #Create model pipeline print('Creating pipeline') pipeline = CreatePipeline() #Fit to data print('Training model') pipeline.fit(X_train, Y_train) print('Evaluating model...') EvaluateModel(pipeline, X_test, Y_test) #Save model to file print(f'Saving model as: {modelName}') dump(pipeline, modelName) if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description='Trains a model to classify disaster responses.') parser.add_argument('--modelName', help='Name of the model', default='model.pkl') parser.add_argument('--dataBasePath', help='Path to the database', default='sqlite:///Data/DisasterResponse.db') parser.add_argument('--databaseTableName', help='Name of the database table', default='messagesDataTable') args = parser.parse_args() print('Training Model...') main(args.modelName, args.dataBasePath, args.databaseTableName) print('Program terminated...')
{ "alphanum_fraction": 0.6538786547, "author": null, "avg_line_length": 35.6445783133, "converted": null, "ext": "py", "file": null, "hexsha": "b9b7e5f8a991c10dd0fe0915721c2db83a4826df", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "344fa7b3b5204337178f1b3746baedffd00fe389", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "cerionXLII/DisasterResponseMLPipeline", "max_forks_repo_path": "src/train.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "344fa7b3b5204337178f1b3746baedffd00fe389", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "cerionXLII/DisasterResponseMLPipeline", "max_issues_repo_path": "src/train.py", "max_line_length": 126, "max_stars_count": null, "max_stars_repo_head_hexsha": "344fa7b3b5204337178f1b3746baedffd00fe389", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "cerionXLII/DisasterResponseMLPipeline", "max_stars_repo_path": "src/train.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1359, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 5917 }
! @expect error subroutine addfive(x) implicit none integer, intent(inout) :: x x = x + 5 end subroutine addfive program main use smack implicit none integer :: x = 2 call addfive(x) !print *, x == 7 call assert(x /= 7) end program main
{ "alphanum_fraction": 0.6536964981, "author": null, "avg_line_length": 15.1176470588, "converted": null, "ext": "f90", "file": null, "hexsha": "0f5306e67883a7d05cf5a70b52b564aec396cd6b", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-01-19T16:51:19.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-19T16:51:19.000Z", "max_forks_repo_head_hexsha": "0eba287949dafd9a4eb0ce3a4678392634903eea", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "soarlab/gandalv", "max_forks_repo_path": "fortran/inout_fail.f90", "max_issues_count": null, "max_issues_repo_head_hexsha": "0eba287949dafd9a4eb0ce3a4678392634903eea", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "soarlab/gandalv", "max_issues_repo_path": "fortran/inout_fail.f90", "max_line_length": 29, "max_stars_count": 2, "max_stars_repo_head_hexsha": "0eba287949dafd9a4eb0ce3a4678392634903eea", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "soarlab/gandalv", "max_stars_repo_path": "fortran/inout_fail.f90", "max_stars_repo_stars_event_max_datetime": "2020-01-20T20:27:08.000Z", "max_stars_repo_stars_event_min_datetime": "2020-01-18T22:40:40.000Z", "num_tokens": 84, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 257 }
import pandas as pd import numpy as np import gresearch_crypto import xgboost as xgb import traceback import datetime TRAIN_CSV = '/kaggle/input/g-research-crypto-forecasting/train.csv' ASSET_DETAILS_CSV = '/kaggle/input/g-research-crypto-forecasting/asset_details.csv' df = pd.read_csv(TRAIN_CSV) df_asset_details = pd.read_csv(ASSET_DETAILS_CSV).sort_values("Asset_ID") asset_to_weight = df_asset_details.Weight.values asset_to_weight = asset_to_weight / np.sum(asset_to_weight) df['Weight'] = df['Asset_ID'].map(asset_to_weight) def clean_data(df): df = df.drop(['Asset_ID'], axis=1) df = df.dropna(axis=0) df = df.drop_duplicates() df = df.reset_index(drop=True) return df def train_test_split(df): df_train = df[:int(len(df)*0.8)] df_test = df[int(len(df)*0.8):] return df_train, df_test from pandas import DataFrame from pandas import concat def time_lag(data, data_in, data_out, dropnan=True, interpolate=False): """ Time lag the data. """ if data_in is None: data_in = data.columns if data_out is None: data_out = data.columns if type(data_in) is not list: data_in = [data_in] if type(data_out) is not list: data_out = [data_out] if interpolate: data_out = data_out + ['interpolate'] data_out = data_out + ['weight'] data_out = data_out + ['time_lag'] data_out = data_out + ['time_lag_weight'] for i in data_in: for j in data_out: if i == j: continue data[i+'_'+j] = data[i].shift(1).fillna(0) if dropnan: data = data.dropna(axis=0) return data def process(df): df.loc[df["VWAP"] <= 0, "VWAP"] = df.loc[df["VWAP"] <= 0, "Close"] df["Unity"] = 1 df["Open"] = np.log(df["Open"]) df["High"] = np.log(df["High"]) df["Low"] = np.log(df["Low"]) df["Close"] = np.log(df["Close"]) df["VWAP"] = np.log(df["VWAP"]) process(X_train) process(X_test) def get_data(df): df = df.drop(['Asset_ID'], axis=1) df = df.dropna(axis=0) df = df.drop_duplicates() df = df.reset_index(drop=True) return df def get_data_train(df): df = df.drop(['Asset_ID'], axis=1) df = df.dropna(axis=0) df = df.drop_duplicates() df = df.reset_index(drop=True) return df def get_data_test(df): df = df.drop(['Asset_ID'], axis=1) df = df.dropna(axis=0) df = df.drop_duplicates() df = df.reset_index(drop=True) return df def get_data_train_test(df): df = df.drop(['Asset_ID'], axis=1) df = df.dropna(axis=0) df = df.drop_duplicates() df = df.reset_index(drop=True) return df def get_data_train_test_split(df): df = df.drop(['Asset_ID'], axis=1) df = df.dropna(axis=0) df = df.drop_duplicates() df = df.reset_index(drop=True) return df from sklearn.preprocessing import StandardScaler class BestModel: def __init__(self):
{ "alphanum_fraction": 0.6343283582, "author": null, "avg_line_length": 24.7731092437, "converted": null, "ext": "py", "file": null, "hexsha": "d53e03dee18e65ea5d1d233b8d1eaf423b14e47c", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "120f08a4a297045e979bfd842a6620e3919c1914", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "techthumb1/money_maker", "max_forks_repo_path": "scripts/g-res_example.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "120f08a4a297045e979bfd842a6620e3919c1914", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "techthumb1/money_maker", "max_issues_repo_path": "scripts/g-res_example.py", "max_line_length": 83, "max_stars_count": null, "max_stars_repo_head_hexsha": "120f08a4a297045e979bfd842a6620e3919c1914", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "techthumb1/money_maker", "max_stars_repo_path": "scripts/g-res_example.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 830, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 2948 }
# Copyright 2016 James Hensman, Valentine Svensson, alexggmatthews, Mark van der Wilk # # 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 .param import DataHolder class IndexManager(object): """ Base clase for methods of batch indexing data. rng is an instance of np.random.RandomState, defaults to seed 0. """ def __init__(self, minibatch_size, total_points, rng=None): self.minibatch_size = minibatch_size self.total_points = total_points self.rng = rng or np.random.RandomState(0) def nextIndices(self): raise NotImplementedError class ReplacementSampling(IndexManager): def nextIndices(self): return self.rng.randint(self.total_points, size=self.minibatch_size) class NoReplacementSampling(IndexManager): def __init__(self, minibatch_size, total_points, rng=None): # Can't sample without replacement is minibatch_size is larger # than total_points assert(minibatch_size <= total_points) IndexManager.__init__(self, minibatch_size, total_points, rng) def nextIndices(self): permutation = self.rng.permutation(self.total_points) return permutation[:self.minibatch_size] class SequenceIndices(IndexManager): """ A class that maintains the state necessary to manage sequential indexing of data holders. """ def __init__(self, minibatch_size, total_points, rng=None): self.counter = 0 IndexManager.__init__(self, minibatch_size, total_points, rng) def nextIndices(self): """ Written so that if total_points changes this will still work """ firstIndex = self.counter lastIndex = self.counter + self.minibatch_size self.counter = lastIndex % self.total_points return np.arange(firstIndex, lastIndex) % self.total_points class MinibatchData(DataHolder): """ A special DataHolder class which feeds a minibatch to tensorflow via update_feed_dict(). """ # List of valid specifiers for generation methods. _generation_methods = ['replace', 'noreplace', 'sequential'] def __init__(self, array, minibatch_size, rng=None, batch_manager=None): """ array is a numpy array of data. minibatch_size (int) is the size of the minibatch batch_manager specified data sampling scheme and is a subclass of IndexManager. Note: you may want to randomize the order of the data if using sequential generation. """ DataHolder.__init__(self, array, on_shape_change='pass') total_points = self._array.shape[0] self.parseGenerationMethod(batch_manager, minibatch_size, total_points, rng) def parseGenerationMethod(self, input_batch_manager, minibatch_size, total_points, rng): # Logic for default behaviour. # When minibatch_size is a small fraction of total_point # ReplacementSampling should give similar results to # NoReplacementSampling and the former can be much faster. if input_batch_manager is None: fraction = float(minibatch_size) / float(total_points) if fraction < 0.5: self.index_manager = ReplacementSampling(minibatch_size, total_points, rng) else: self.index_manager = NoReplacementSampling(minibatch_size, total_points, rng) else: # Explicitly specified behaviour. if input_batch_manager.__class__ not in IndexManager.__subclasses__(): raise NotImplementedError self.index_manager = input_batch_manager def update_feed_dict(self, key_dict, feed_dict): next_indices = self.index_manager.nextIndices() feed_dict[key_dict[self]] = self._array[next_indices]
{ "alphanum_fraction": 0.6315240084, "author": null, "avg_line_length": 38.32, "converted": null, "ext": "py", "file": null, "hexsha": "eef4b706bf05f0e52453b455cfa7319d03c98d8f", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 12, "max_forks_repo_forks_event_max_datetime": "2019-10-30T16:09:52.000Z", "max_forks_repo_forks_event_min_datetime": "2018-11-30T00:40:13.000Z", "max_forks_repo_head_hexsha": "2a18db0f2cffb7d20888a44bd4e4c74f207908b2", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "dalnoguer/my-GPflow", "max_forks_repo_path": "GPflow/minibatch.py", "max_issues_count": 1, "max_issues_repo_head_hexsha": "2a18db0f2cffb7d20888a44bd4e4c74f207908b2", "max_issues_repo_issues_event_max_datetime": "2018-12-04T11:51:21.000Z", "max_issues_repo_issues_event_min_datetime": "2018-12-04T11:51:21.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "dalnoguer/my-GPflow", "max_issues_repo_path": "GPflow/minibatch.py", "max_line_length": 85, "max_stars_count": 24, "max_stars_repo_head_hexsha": "2a18db0f2cffb7d20888a44bd4e4c74f207908b2", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "dalnoguer/my-GPflow", "max_stars_repo_path": "GPflow/minibatch.py", "max_stars_repo_stars_event_max_datetime": "2021-04-22T19:12:31.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-29T07:00:59.000Z", "num_tokens": 928, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 4790 }
\documentclass[12pt]{article} \newlength{\blackoutwidth} \newcommand{\blackout}[1] {%necessary comment \settowidth{\blackoutwidth}{#1}%necessary comment \rule[-0.3em]{\blackoutwidth}{1.125em}%necessary comment } \PassOptionsToPackage{usenames,dvipsnames}{xcolor} \PassOptionsToPackage{colorlinks,linktoc=all}{hyperref} \usepackage{balance} % to better equalize the last page \usepackage{graphics} % for EPS, load graphicx instead \usepackage[T1]{fontenc} % for umlauts and other diaeresis \usepackage{txfonts} \usepackage{color} \usepackage{booktabs} \usepackage{textcomp} \usepackage{cuted} \usepackage{capt-of} \usepackage[pdflang={en-US},pdftex]{hyperref} \title{Comparing Novel Machine-Learning Approaches for Recommending Quality Writing} \author{Rohan Bansal} \date{September 2020} \input{preamble/preamble} \input{preamble/preamble_math} \input{preamble/preamble_acronyms} \input{preamble/preamble_biblatex} \bibliography{bib} \begin{document} \input{sections/titlepage} \tableofcontents \newpage \section{Introduction} \input{sections/intro} \section{Theory} \input{sections/theory} \section{Approaches} \subsection{NLP Fundamentals} \input{sections/theory/nlp-fundamentals} \subsection{RankFromSets (RFS)} \input{sections/theory/rankfromsets} \subsection{Bidirectional Encoder Representations from Transformers (BERT)} \input{sections/theory/bert} \section{Hypothesis/Applied Theory} \input{sections/hypothesis} \section{Data Collection and Processing} \input{sections/processing} \section{Experiments} \input{sections/experiment} \section{Discussion} \input{sections/discussion} \section{Conclusion} \input{sections/conclusion} \newpage \printbibliography[heading=bibintoc, title={Bibliography}] \cleardoublepage \appendix \input{appendix/appendix} \end{document}{}
{ "alphanum_fraction": 0.7933884298, "author": null, "avg_line_length": 22.6875, "converted": null, "ext": "tex", "file": null, "hexsha": "7b0a8032385bdaea5506eac44cd8f124e975e069", "include": null, "lang": "TeX", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "03848a1c9f4dafe8db0a9ad263e8776681139659", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rohanbansal12/extended_essay", "max_forks_repo_path": "EE/proceedings.tex", "max_issues_count": null, "max_issues_repo_head_hexsha": "03848a1c9f4dafe8db0a9ad263e8776681139659", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "rohanbansal12/extended_essay", "max_issues_repo_path": "EE/proceedings.tex", "max_line_length": 84, "max_stars_count": null, "max_stars_repo_head_hexsha": "03848a1c9f4dafe8db0a9ad263e8776681139659", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rohanbansal12/extended_essay", "max_stars_repo_path": "EE/proceedings.tex", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 523, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 1815 }
[STATEMENT] lemma solve_depressed_quartic_complex: "x \<in> set (solve_depressed_quartic_complex p q r) \<longleftrightarrow> (x^4 + p * x^2 + q * x + r = 0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] note powers = field_simps power4_eq_xxxx power3_eq_cube power2_eq_square [PROOF STATE] proof (state) this: ?a + ?b + ?c = ?a + (?b + ?c) ?a + ?b = ?b + ?a ?b + (?a + ?c) = ?a + (?b + ?c) ?a * ?b * ?c = ?a * (?b * ?c) ?a * ?b = ?b * ?a ?b * (?a * ?c) = ?a * (?b * ?c) ?a - ?b - ?c = ?a - (?b + ?c) ?a + (?b - ?c) = ?a + ?b - ?c (?a - ?b = ?c) = (?a = ?c + ?b) (?a = ?c - ?b) = (?a + ?b = ?c) ?a - (?b - ?c) = ?a + ?c - ?b ?a - ?b + ?c = ?a + ?c - ?b (?a - ?b < ?c) = (?a < ?c + ?b) (?a < ?c - ?b) = (?a + ?b < ?c) (?a - ?b \<le> ?c) = (?a \<le> ?c + ?b) (?a \<le> ?c - ?b) = (?a + ?b \<le> ?c) NO_MATCH (?x div ?y) ?a \<Longrightarrow> ?a * (?b + ?c) = ?a * ?b + ?a * ?c NO_MATCH (?x div ?y) ?c \<Longrightarrow> (?a + ?b) * ?c = ?a * ?c + ?b * ?c NO_MATCH (?x div ?y) ?c \<Longrightarrow> (?a - ?b) * ?c = ?a * ?c - ?b * ?c NO_MATCH (?x div ?y) ?a \<Longrightarrow> ?a * (?b - ?c) = ?a * ?b - ?a * ?c inverse ?a = (1::?'a) / ?a ?c \<noteq> (0::?'a) \<Longrightarrow> (?a = ?b / ?c) = (?a * ?c = ?b) ?c \<noteq> (0::?'a) \<Longrightarrow> (?b / ?c = ?a) = (?b = ?a * ?c) ?b \<noteq> (0::?'a) \<Longrightarrow> (- (?a / ?b) = ?c) = (- ?a = ?c * ?b) ?b \<noteq> (0::?'a) \<Longrightarrow> (?c = - (?a / ?b)) = (?c * ?b = - ?a) ?z \<noteq> (0::?'a) \<Longrightarrow> ?x + ?y / ?z = (?x * ?z + ?y) / ?z ?z \<noteq> (0::?'a) \<Longrightarrow> ?x / ?z + ?y = (?x + ?y * ?z) / ?z ?z \<noteq> (0::?'a) \<Longrightarrow> ?x - ?y / ?z = (?x * ?z - ?y) / ?z ?z \<noteq> (0::?'a) \<Longrightarrow> - (?x / ?z) + ?y = (- ?x + ?y * ?z) / ?z ?z \<noteq> (0::?'a) \<Longrightarrow> ?x / ?z - ?y = (?x - ?y * ?z) / ?z ?z \<noteq> (0::?'a) \<Longrightarrow> - (?x / ?z) - ?y = (- ?x - ?y * ?z) / ?z (0::?'a) < ?c \<Longrightarrow> (?a \<le> ?b / ?c) = (?a * ?c \<le> ?b) (0::?'a) < ?c \<Longrightarrow> (?a < ?b / ?c) = (?a * ?c < ?b) ?c < (0::?'a) \<Longrightarrow> (?a < ?b / ?c) = (?b < ?a * ?c) ?c < (0::?'a) \<Longrightarrow> (?a \<le> ?b / ?c) = (?b \<le> ?a * ?c) (0::?'a) < ?c \<Longrightarrow> (?b / ?c \<le> ?a) = (?b \<le> ?a * ?c) (0::?'a) < ?c \<Longrightarrow> (?b / ?c < ?a) = (?b < ?a * ?c) ?c < (0::?'a) \<Longrightarrow> (?b / ?c \<le> ?a) = (?a * ?c \<le> ?b) ?c < (0::?'a) \<Longrightarrow> (?b / ?c < ?a) = (?a * ?c < ?b) (0::?'a) < ?c \<Longrightarrow> (?a \<le> - (?b / ?c)) = (?a * ?c \<le> - ?b) ?c < (0::?'a) \<Longrightarrow> (?a \<le> - (?b / ?c)) = (- ?b \<le> ?a * ?c) (0::?'a) < ?c \<Longrightarrow> (?a < - (?b / ?c)) = (?a * ?c < - ?b) ?c < (0::?'a) \<Longrightarrow> (?a < - (?b / ?c)) = (- ?b < ?a * ?c) (0::?'a) < ?c \<Longrightarrow> (- (?b / ?c) < ?a) = (- ?b < ?a * ?c) ?c < (0::?'a) \<Longrightarrow> (- (?b / ?c) < ?a) = (?a * ?c < - ?b) (0::?'a) < ?c \<Longrightarrow> (- (?b / ?c) \<le> ?a) = (- ?b \<le> ?a * ?c) ?c < (0::?'a) \<Longrightarrow> (- (?b / ?c) \<le> ?a) = (?a * ?c \<le> - ?b) (?a * ?b) ^ ?n = ?a ^ ?n * ?b ^ ?n inverse ?a ^ ?n = inverse (?a ^ ?n) ((1::?'a) / ?a) ^ ?n = (1::?'a) / ?a ^ ?n (?a / ?b) ^ ?n = ?a ^ ?n / ?b ^ ?n inverse ?x powi ?n = inverse (?x powi ?n) ((1::?'a) / ?x) powi ?n = (1::?'a) / ?x powi ?n NO_MATCH (?x div ?y) ?c \<Longrightarrow> (?a + ?b) *\<^sub>R ?x = ?a *\<^sub>R ?x + ?b *\<^sub>R ?x NO_MATCH (?x div ?y) ?a \<Longrightarrow> ?a *\<^sub>R (?x + ?y) = ?a *\<^sub>R ?x + ?a *\<^sub>R ?y NO_MATCH (?x div ?y) ?c \<Longrightarrow> (?a - ?b) *\<^sub>R ?x = ?a *\<^sub>R ?x - ?b *\<^sub>R ?x NO_MATCH (?x div ?y) ?a \<Longrightarrow> ?a *\<^sub>R (?x - ?y) = ?a *\<^sub>R ?x - ?a *\<^sub>R ?y ?c \<noteq> 0 \<Longrightarrow> (?a = ?b /\<^sub>R ?c) = (?c *\<^sub>R ?a = ?b) ?c \<noteq> 0 \<Longrightarrow> (?b /\<^sub>R ?c = ?a) = (?b = ?c *\<^sub>R ?a) ?c \<noteq> 0 \<Longrightarrow> ?a + ?b /\<^sub>R ?c = (?c *\<^sub>R ?a + ?b) /\<^sub>R ?c ?c \<noteq> 0 \<Longrightarrow> ?a /\<^sub>R ?c + ?b = (?a + ?c *\<^sub>R ?b) /\<^sub>R ?c ?c \<noteq> 0 \<Longrightarrow> ?a - ?b /\<^sub>R ?c = (?c *\<^sub>R ?a - ?b) /\<^sub>R ?c ?c \<noteq> 0 \<Longrightarrow> ?a /\<^sub>R ?c - ?b = (?a - ?c *\<^sub>R ?b) /\<^sub>R ?c ?c \<noteq> 0 \<Longrightarrow> - (?a /\<^sub>R ?c) + ?b = (- ?a + ?c *\<^sub>R ?b) /\<^sub>R ?c ?c \<noteq> 0 \<Longrightarrow> - (?a /\<^sub>R ?c) - ?b = (- ?a - ?c *\<^sub>R ?b) /\<^sub>R ?c 0 < ?c \<Longrightarrow> (?a \<le> ?b /\<^sub>R ?c) = (?c *\<^sub>R ?a \<le> ?b) 0 < ?c \<Longrightarrow> (?a < ?b /\<^sub>R ?c) = (?c *\<^sub>R ?a < ?b) 0 < ?c \<Longrightarrow> (?b /\<^sub>R ?c \<le> ?a) = (?b \<le> ?c *\<^sub>R ?a) 0 < ?c \<Longrightarrow> (?b /\<^sub>R ?c < ?a) = (?b < ?c *\<^sub>R ?a) 0 < ?c \<Longrightarrow> (?a \<le> - (?b /\<^sub>R ?c)) = (?c *\<^sub>R ?a \<le> - ?b) 0 < ?c \<Longrightarrow> (?a < - (?b /\<^sub>R ?c)) = (?c *\<^sub>R ?a < - ?b) 0 < ?c \<Longrightarrow> (- (?b /\<^sub>R ?c) \<le> ?a) = (- ?b \<le> ?c *\<^sub>R ?a) 0 < ?c \<Longrightarrow> (- (?b /\<^sub>R ?c) < ?a) = (- ?b < ?c *\<^sub>R ?a) ?c < 0 \<Longrightarrow> (?a \<le> ?b /\<^sub>R ?c) = (?b \<le> ?c *\<^sub>R ?a) ?c < 0 \<Longrightarrow> (?a < ?b /\<^sub>R ?c) = (?b < ?c *\<^sub>R ?a) ?c < 0 \<Longrightarrow> (?b /\<^sub>R ?c \<le> ?a) = (?c *\<^sub>R ?a \<le> ?b) ?c < 0 \<Longrightarrow> (?b /\<^sub>R ?c < ?a) = (?c *\<^sub>R ?a < ?b) ?c < 0 \<Longrightarrow> (?a \<le> - (?b /\<^sub>R ?c)) = (- ?b \<le> ?c *\<^sub>R ?a) ?c < 0 \<Longrightarrow> (?a < - (?b /\<^sub>R ?c)) = (- ?b < ?c *\<^sub>R ?a) ?c < 0 \<Longrightarrow> (- (?b /\<^sub>R ?c) \<le> ?a) = (?c *\<^sub>R ?a \<le> - ?b) ?c < 0 \<Longrightarrow> (- (?b /\<^sub>R ?c) < ?a) = (?c *\<^sub>R ?a < - ?b) ?x ^ 4 = ?x * ?x * ?x * ?x ?a ^ 3 = ?a * ?a * ?a ?a\<^sup>2 = ?a * ?a goal (1 subgoal): 1. (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] proof (cases "q = 0") [PROOF STATE] proof (state) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] case True [PROOF STATE] proof (state) this: q = 0 goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] have csqrt: "z = x^2 \<longleftrightarrow> (x = csqrt z \<or> x = - csqrt z)" for z [PROOF STATE] proof (prove) goal (1 subgoal): 1. (z = x\<^sup>2) = (x = csqrt z \<or> x = - csqrt z) [PROOF STEP] by (metis power2_csqrt power2_eq_iff) [PROOF STATE] proof (state) this: (?z = x\<^sup>2) = (x = csqrt ?z \<or> x = - csqrt ?z) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] have "(x ^ 4 + p * x\<^sup>2 + q * x + r = 0) \<longleftrightarrow> (x ^ 4 + p * x\<^sup>2 + r = 0)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) = (x ^ 4 + p * x\<^sup>2 + r = 0) [PROOF STEP] unfolding True [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x ^ 4 + p * x\<^sup>2 + 0 * x + r = 0) = (x ^ 4 + p * x\<^sup>2 + r = 0) [PROOF STEP] by simp [PROOF STATE] proof (state) this: (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) = (x ^ 4 + p * x\<^sup>2 + r = 0) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] also [PROOF STATE] proof (state) this: (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) = (x ^ 4 + p * x\<^sup>2 + r = 0) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] have "\<dots> \<longleftrightarrow> (\<exists>z. z\<^sup>2 + p * z + r = 0 \<and> z = x\<^sup>2)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x ^ 4 + p * x\<^sup>2 + r = 0) = (\<exists>z. z\<^sup>2 + p * z + r = 0 \<and> z = x\<^sup>2) [PROOF STEP] unfolding biquadratic_solution [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>z. z\<^sup>2 + p * z + r = 0 \<and> z = x\<^sup>2) = (\<exists>z. z\<^sup>2 + p * z + r = 0 \<and> z = x\<^sup>2) [PROOF STEP] by simp [PROOF STATE] proof (state) this: (x ^ 4 + p * x\<^sup>2 + r = 0) = (\<exists>z. z\<^sup>2 + p * z + r = 0 \<and> z = x\<^sup>2) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] also [PROOF STATE] proof (state) this: (x ^ 4 + p * x\<^sup>2 + r = 0) = (\<exists>z. z\<^sup>2 + p * z + r = 0 \<and> z = x\<^sup>2) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] have "\<dots> \<longleftrightarrow> (\<exists> z. poly [:r,p,1:] z = 0 \<and> z = x^2)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>z. z\<^sup>2 + p * z + r = 0 \<and> z = x\<^sup>2) = (\<exists>z. poly [:r, p, 1:] z = 0 \<and> z = x\<^sup>2) [PROOF STEP] by (simp add: powers) [PROOF STATE] proof (state) this: (\<exists>z. z\<^sup>2 + p * z + r = 0 \<and> z = x\<^sup>2) = (\<exists>z. poly [:r, p, 1:] z = 0 \<and> z = x\<^sup>2) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] also [PROOF STATE] proof (state) this: (\<exists>z. z\<^sup>2 + p * z + r = 0 \<and> z = x\<^sup>2) = (\<exists>z. poly [:r, p, 1:] z = 0 \<and> z = x\<^sup>2) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] have "\<dots> \<longleftrightarrow> (\<exists> z \<in> set (croots2 [:r,p,1:]). z = x^2)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>z. poly [:r, p, 1:] z = 0 \<and> z = x\<^sup>2) = (\<exists>z\<in>set (croots2 [:r, p, 1:]). z = x\<^sup>2) [PROOF STEP] by (subst croots2[symmetric], auto) [PROOF STATE] proof (state) this: (\<exists>z. poly [:r, p, 1:] z = 0 \<and> z = x\<^sup>2) = (\<exists>z\<in>set (croots2 [:r, p, 1:]). z = x\<^sup>2) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] also [PROOF STATE] proof (state) this: (\<exists>z. poly [:r, p, 1:] z = 0 \<and> z = x\<^sup>2) = (\<exists>z\<in>set (croots2 [:r, p, 1:]). z = x\<^sup>2) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] have "\<dots> \<longleftrightarrow> (\<exists> z \<in> set (croots2 [:r,p,1:]). x = csqrt z \<or> x = - csqrt z)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>z\<in>set (croots2 [:r, p, 1:]). z = x\<^sup>2) = (\<exists>z\<in>set (croots2 [:r, p, 1:]). x = csqrt z \<or> x = - csqrt z) [PROOF STEP] unfolding csqrt [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>z\<in>set (croots2 [:r, p, 1:]). x = csqrt z \<or> x = - csqrt z) = (\<exists>z\<in>set (croots2 [:r, p, 1:]). x = csqrt z \<or> x = - csqrt z) [PROOF STEP] .. [PROOF STATE] proof (state) this: (\<exists>z\<in>set (croots2 [:r, p, 1:]). z = x\<^sup>2) = (\<exists>z\<in>set (croots2 [:r, p, 1:]). x = csqrt z \<or> x = - csqrt z) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] also [PROOF STATE] proof (state) this: (\<exists>z\<in>set (croots2 [:r, p, 1:]). z = x\<^sup>2) = (\<exists>z\<in>set (croots2 [:r, p, 1:]). x = csqrt z \<or> x = - csqrt z) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] have "\<dots> \<longleftrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>z\<in>set (croots2 [:r, p, 1:]). x = csqrt z \<or> x = - csqrt z) = (x \<in> set (solve_depressed_quartic_complex p q r)) [PROOF STEP] unfolding solve_depressed_quartic_complex_def id [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>z\<in>set (croots2 [:r, p, 1:]). x = csqrt z \<or> x = - csqrt z) = (x \<in> set (remdups (if q = 0 then concat (map (\<lambda>z. let y = csqrt z in [y, - y]) (croots2 [:r, p, 1:])) else let cubics = croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]; m = hd cubics; a = csqrt (2 * m); p2m = p / 2 + m; q2a = q / (2 * a); b1 = p2m - q2a; b2 = p2m + q2a in croots2 [:b1, a, 1:] @ croots2 [:b2, - a, 1:]))) [PROOF STEP] unfolding True Let_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<exists>z\<in>set (croots2 [:r, p, 1:]). x = csqrt z \<or> x = - csqrt z) = (x \<in> set (remdups (if 0 = 0 then concat (map (\<lambda>z. [csqrt z, - csqrt z]) (croots2 [:r, p, 1:])) else croots2 [:p / 2 + hd (croots3 [:- 0\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]) - 0 / (2 * csqrt (2 * hd (croots3 [:- 0\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]))), csqrt (2 * hd (croots3 [:- 0\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:])), 1:] @ croots2 [:p / 2 + hd (croots3 [:- 0\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]) + 0 / (2 * csqrt (2 * hd (croots3 [:- 0\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]))), - csqrt (2 * hd (croots3 [:- 0\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:])), 1:]))) [PROOF STEP] by auto [PROOF STATE] proof (state) this: (\<exists>z\<in>set (croots2 [:r, p, 1:]). x = csqrt z \<or> x = - csqrt z) = (x \<in> set (solve_depressed_quartic_complex p q r)) goal (2 subgoals): 1. q = 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) 2. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) = (x \<in> set (solve_depressed_quartic_complex p q r)) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) = (x \<in> set (solve_depressed_quartic_complex p q r)) goal (1 subgoal): 1. (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] .. [PROOF STATE] proof (state) this: (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] case q0: False [PROOF STATE] proof (state) this: q \<noteq> 0 goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] hence id: "(if q = 0 then x else y) = y" for x y :: "complex list" [PROOF STATE] proof (prove) using this: q \<noteq> 0 goal (1 subgoal): 1. (if q = 0 then x else y) = y [PROOF STEP] by auto [PROOF STATE] proof (state) this: (if q = 0 then ?x else ?y) = ?y goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] note powers = field_simps power4_eq_xxxx power3_eq_cube power2_eq_square [PROOF STATE] proof (state) this: ?a + ?b + ?c = ?a + (?b + ?c) ?a + ?b = ?b + ?a ?b + (?a + ?c) = ?a + (?b + ?c) ?a * ?b * ?c = ?a * (?b * ?c) ?a * ?b = ?b * ?a ?b * (?a * ?c) = ?a * (?b * ?c) ?a - ?b - ?c = ?a - (?b + ?c) ?a + (?b - ?c) = ?a + ?b - ?c (?a - ?b = ?c) = (?a = ?c + ?b) (?a = ?c - ?b) = (?a + ?b = ?c) ?a - (?b - ?c) = ?a + ?c - ?b ?a - ?b + ?c = ?a + ?c - ?b (?a - ?b < ?c) = (?a < ?c + ?b) (?a < ?c - ?b) = (?a + ?b < ?c) (?a - ?b \<le> ?c) = (?a \<le> ?c + ?b) (?a \<le> ?c - ?b) = (?a + ?b \<le> ?c) NO_MATCH (?x div ?y) ?a \<Longrightarrow> ?a * (?b + ?c) = ?a * ?b + ?a * ?c NO_MATCH (?x div ?y) ?c \<Longrightarrow> (?a + ?b) * ?c = ?a * ?c + ?b * ?c NO_MATCH (?x div ?y) ?c \<Longrightarrow> (?a - ?b) * ?c = ?a * ?c - ?b * ?c NO_MATCH (?x div ?y) ?a \<Longrightarrow> ?a * (?b - ?c) = ?a * ?b - ?a * ?c inverse ?a = (1::?'a) / ?a ?c \<noteq> (0::?'a) \<Longrightarrow> (?a = ?b / ?c) = (?a * ?c = ?b) ?c \<noteq> (0::?'a) \<Longrightarrow> (?b / ?c = ?a) = (?b = ?a * ?c) ?b \<noteq> (0::?'a) \<Longrightarrow> (- (?a / ?b) = ?c) = (- ?a = ?c * ?b) ?b \<noteq> (0::?'a) \<Longrightarrow> (?c = - (?a / ?b)) = (?c * ?b = - ?a) ?z \<noteq> (0::?'a) \<Longrightarrow> ?x + ?y / ?z = (?x * ?z + ?y) / ?z ?z \<noteq> (0::?'a) \<Longrightarrow> ?x / ?z + ?y = (?x + ?y * ?z) / ?z ?z \<noteq> (0::?'a) \<Longrightarrow> ?x - ?y / ?z = (?x * ?z - ?y) / ?z ?z \<noteq> (0::?'a) \<Longrightarrow> - (?x / ?z) + ?y = (- ?x + ?y * ?z) / ?z ?z \<noteq> (0::?'a) \<Longrightarrow> ?x / ?z - ?y = (?x - ?y * ?z) / ?z ?z \<noteq> (0::?'a) \<Longrightarrow> - (?x / ?z) - ?y = (- ?x - ?y * ?z) / ?z (0::?'a) < ?c \<Longrightarrow> (?a \<le> ?b / ?c) = (?a * ?c \<le> ?b) (0::?'a) < ?c \<Longrightarrow> (?a < ?b / ?c) = (?a * ?c < ?b) ?c < (0::?'a) \<Longrightarrow> (?a < ?b / ?c) = (?b < ?a * ?c) ?c < (0::?'a) \<Longrightarrow> (?a \<le> ?b / ?c) = (?b \<le> ?a * ?c) (0::?'a) < ?c \<Longrightarrow> (?b / ?c \<le> ?a) = (?b \<le> ?a * ?c) (0::?'a) < ?c \<Longrightarrow> (?b / ?c < ?a) = (?b < ?a * ?c) ?c < (0::?'a) \<Longrightarrow> (?b / ?c \<le> ?a) = (?a * ?c \<le> ?b) ?c < (0::?'a) \<Longrightarrow> (?b / ?c < ?a) = (?a * ?c < ?b) (0::?'a) < ?c \<Longrightarrow> (?a \<le> - (?b / ?c)) = (?a * ?c \<le> - ?b) ?c < (0::?'a) \<Longrightarrow> (?a \<le> - (?b / ?c)) = (- ?b \<le> ?a * ?c) (0::?'a) < ?c \<Longrightarrow> (?a < - (?b / ?c)) = (?a * ?c < - ?b) ?c < (0::?'a) \<Longrightarrow> (?a < - (?b / ?c)) = (- ?b < ?a * ?c) (0::?'a) < ?c \<Longrightarrow> (- (?b / ?c) < ?a) = (- ?b < ?a * ?c) ?c < (0::?'a) \<Longrightarrow> (- (?b / ?c) < ?a) = (?a * ?c < - ?b) (0::?'a) < ?c \<Longrightarrow> (- (?b / ?c) \<le> ?a) = (- ?b \<le> ?a * ?c) ?c < (0::?'a) \<Longrightarrow> (- (?b / ?c) \<le> ?a) = (?a * ?c \<le> - ?b) (?a * ?b) ^ ?n = ?a ^ ?n * ?b ^ ?n inverse ?a ^ ?n = inverse (?a ^ ?n) ((1::?'a) / ?a) ^ ?n = (1::?'a) / ?a ^ ?n (?a / ?b) ^ ?n = ?a ^ ?n / ?b ^ ?n inverse ?x powi ?n = inverse (?x powi ?n) ((1::?'a) / ?x) powi ?n = (1::?'a) / ?x powi ?n NO_MATCH (?x div ?y) ?c \<Longrightarrow> (?a + ?b) *\<^sub>R ?x = ?a *\<^sub>R ?x + ?b *\<^sub>R ?x NO_MATCH (?x div ?y) ?a \<Longrightarrow> ?a *\<^sub>R (?x + ?y) = ?a *\<^sub>R ?x + ?a *\<^sub>R ?y NO_MATCH (?x div ?y) ?c \<Longrightarrow> (?a - ?b) *\<^sub>R ?x = ?a *\<^sub>R ?x - ?b *\<^sub>R ?x NO_MATCH (?x div ?y) ?a \<Longrightarrow> ?a *\<^sub>R (?x - ?y) = ?a *\<^sub>R ?x - ?a *\<^sub>R ?y ?c \<noteq> 0 \<Longrightarrow> (?a = ?b /\<^sub>R ?c) = (?c *\<^sub>R ?a = ?b) ?c \<noteq> 0 \<Longrightarrow> (?b /\<^sub>R ?c = ?a) = (?b = ?c *\<^sub>R ?a) ?c \<noteq> 0 \<Longrightarrow> ?a + ?b /\<^sub>R ?c = (?c *\<^sub>R ?a + ?b) /\<^sub>R ?c ?c \<noteq> 0 \<Longrightarrow> ?a /\<^sub>R ?c + ?b = (?a + ?c *\<^sub>R ?b) /\<^sub>R ?c ?c \<noteq> 0 \<Longrightarrow> ?a - ?b /\<^sub>R ?c = (?c *\<^sub>R ?a - ?b) /\<^sub>R ?c ?c \<noteq> 0 \<Longrightarrow> ?a /\<^sub>R ?c - ?b = (?a - ?c *\<^sub>R ?b) /\<^sub>R ?c ?c \<noteq> 0 \<Longrightarrow> - (?a /\<^sub>R ?c) + ?b = (- ?a + ?c *\<^sub>R ?b) /\<^sub>R ?c ?c \<noteq> 0 \<Longrightarrow> - (?a /\<^sub>R ?c) - ?b = (- ?a - ?c *\<^sub>R ?b) /\<^sub>R ?c 0 < ?c \<Longrightarrow> (?a \<le> ?b /\<^sub>R ?c) = (?c *\<^sub>R ?a \<le> ?b) 0 < ?c \<Longrightarrow> (?a < ?b /\<^sub>R ?c) = (?c *\<^sub>R ?a < ?b) 0 < ?c \<Longrightarrow> (?b /\<^sub>R ?c \<le> ?a) = (?b \<le> ?c *\<^sub>R ?a) 0 < ?c \<Longrightarrow> (?b /\<^sub>R ?c < ?a) = (?b < ?c *\<^sub>R ?a) 0 < ?c \<Longrightarrow> (?a \<le> - (?b /\<^sub>R ?c)) = (?c *\<^sub>R ?a \<le> - ?b) 0 < ?c \<Longrightarrow> (?a < - (?b /\<^sub>R ?c)) = (?c *\<^sub>R ?a < - ?b) 0 < ?c \<Longrightarrow> (- (?b /\<^sub>R ?c) \<le> ?a) = (- ?b \<le> ?c *\<^sub>R ?a) 0 < ?c \<Longrightarrow> (- (?b /\<^sub>R ?c) < ?a) = (- ?b < ?c *\<^sub>R ?a) ?c < 0 \<Longrightarrow> (?a \<le> ?b /\<^sub>R ?c) = (?b \<le> ?c *\<^sub>R ?a) ?c < 0 \<Longrightarrow> (?a < ?b /\<^sub>R ?c) = (?b < ?c *\<^sub>R ?a) ?c < 0 \<Longrightarrow> (?b /\<^sub>R ?c \<le> ?a) = (?c *\<^sub>R ?a \<le> ?b) ?c < 0 \<Longrightarrow> (?b /\<^sub>R ?c < ?a) = (?c *\<^sub>R ?a < ?b) ?c < 0 \<Longrightarrow> (?a \<le> - (?b /\<^sub>R ?c)) = (- ?b \<le> ?c *\<^sub>R ?a) ?c < 0 \<Longrightarrow> (?a < - (?b /\<^sub>R ?c)) = (- ?b < ?c *\<^sub>R ?a) ?c < 0 \<Longrightarrow> (- (?b /\<^sub>R ?c) \<le> ?a) = (?c *\<^sub>R ?a \<le> - ?b) ?c < 0 \<Longrightarrow> (- (?b /\<^sub>R ?c) < ?a) = (?c *\<^sub>R ?a < - ?b) ?x ^ 4 = ?x * ?x * ?x * ?x ?a ^ 3 = ?a * ?a * ?a ?a\<^sup>2 = ?a * ?a goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] let ?poly = "[:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]" [PROOF STATE] proof (state) goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] from croots3[of ?poly] [PROOF STATE] proof (chain) picking this: degree [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] = 3 \<Longrightarrow> set (croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]) = {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} [PROOF STEP] have croots: "set (croots3 ?poly) = {x. poly ?poly x = 0}" [PROOF STATE] proof (prove) using this: degree [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] = 3 \<Longrightarrow> set (croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]) = {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} goal (1 subgoal): 1. set (croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]) = {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} [PROOF STEP] by auto [PROOF STATE] proof (state) this: set (croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]) = {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] from fundamental_theorem_of_algebra_alt[of ?poly] [PROOF STATE] proof (chain) picking this: \<nexists>a l. a \<noteq> 0 \<and> l = 0 \<and> [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] = pCons a l \<Longrightarrow> \<exists>z. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] z = 0 [PROOF STEP] have "{x. poly ?poly x = 0} \<noteq> {}" [PROOF STATE] proof (prove) using this: \<nexists>a l. a \<noteq> 0 \<and> l = 0 \<and> [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] = pCons a l \<Longrightarrow> \<exists>z. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] z = 0 goal (1 subgoal): 1. {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} \<noteq> {} [PROOF STEP] by auto [PROOF STATE] proof (state) this: {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} \<noteq> {} goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] with croots [PROOF STATE] proof (chain) picking this: set (croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]) = {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} \<noteq> {} [PROOF STEP] have "croots3 ?poly \<noteq> []" [PROOF STATE] proof (prove) using this: set (croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]) = {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} \<noteq> {} goal (1 subgoal): 1. croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] \<noteq> [] [PROOF STEP] by auto [PROOF STATE] proof (state) this: croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] \<noteq> [] goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] \<noteq> [] [PROOF STEP] obtain m rest where rts: "croots3 ?poly = m # rest" [PROOF STATE] proof (prove) using this: croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] \<noteq> [] goal (1 subgoal): 1. (\<And>m rest. croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] = m # rest \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by (cases "croots3 ?poly", auto) [PROOF STATE] proof (state) this: croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] = m # rest goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] hence hd: "hd (croots3 ?poly) = m" [PROOF STATE] proof (prove) using this: croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] = m # rest goal (1 subgoal): 1. hd (croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]) = m [PROOF STEP] by auto [PROOF STATE] proof (state) this: hd (croots3 [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:]) = m goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] from croots[unfolded rts] [PROOF STATE] proof (chain) picking this: set (m # rest) = {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} [PROOF STEP] have "poly ?poly m = 0" [PROOF STATE] proof (prove) using this: set (m # rest) = {x. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] x = 0} goal (1 subgoal): 1. poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] m = 0 [PROOF STEP] by auto [PROOF STATE] proof (state) this: poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] m = 0 goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] hence mrt: "8*m^3 + (8 * p) * m^2 + (2 * p^2 - 8 * r) * m - q^2 = 0" and m0: "m \<noteq> 0" [PROOF STATE] proof (prove) using this: poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] m = 0 goal (1 subgoal): 1. 8 * m ^ 3 + 8 * p * m\<^sup>2 + (2 * p\<^sup>2 - 8 * r) * m - q\<^sup>2 = 0 &&& m \<noteq> 0 [PROOF STEP] using q0 [PROOF STATE] proof (prove) using this: poly [:- q\<^sup>2, 2 * p\<^sup>2 - 8 * r, 8 * p, 8:] m = 0 q \<noteq> 0 goal (1 subgoal): 1. 8 * m ^ 3 + 8 * p * m\<^sup>2 + (2 * p\<^sup>2 - 8 * r) * m - q\<^sup>2 = 0 &&& m \<noteq> 0 [PROOF STEP] by (auto simp: powers) [PROOF STATE] proof (state) this: 8 * m ^ 3 + 8 * p * m\<^sup>2 + (2 * p\<^sup>2 - 8 * r) * m - q\<^sup>2 = 0 m \<noteq> 0 goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] define b1 where "b1 = p / 2 + m - q / (2 * csqrt (2 * m))" [PROOF STATE] proof (state) this: b1 = p / 2 + m - q / (2 * csqrt (2 * m)) goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] define b2 where "b2 = p / 2 + m + q / (2 * csqrt (2 * m))" [PROOF STATE] proof (state) this: b2 = p / 2 + m + q / (2 * csqrt (2 * m)) goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] have csqrt: "csqrt x * csqrt x = x" for x [PROOF STATE] proof (prove) goal (1 subgoal): 1. csqrt x * csqrt x = x [PROOF STEP] by (metis power2_csqrt power2_eq_square) [PROOF STATE] proof (state) this: csqrt ?x * csqrt ?x = ?x goal (1 subgoal): 1. q \<noteq> 0 \<Longrightarrow> (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] unfolding solve_depressed_quartic_complex_def id Let_def set_remdups set_append hd [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<in> set (croots2 [:p / 2 + m - q / (2 * csqrt (2 * m)), csqrt (2 * m), 1:]) \<union> set (croots2 [:p / 2 + m + q / (2 * csqrt (2 * m)), - csqrt (2 * m), 1:])) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] unfolding b1_def[symmetric] b2_def[symmetric] [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<in> set (croots2 [:b1, csqrt (2 * m), 1:]) \<union> set (croots2 [:b2, - csqrt (2 * m), 1:])) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) [PROOF STEP] apply (subst depressed_quartic_Ferrari[OF mrt q0 csqrt b1_def b2_def]) [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x \<in> set (croots2 [:b1, csqrt (2 * m), 1:]) \<union> set (croots2 [:b2, - csqrt (2 * m), 1:])) = (poly [:b1, csqrt (2 * m), 1:] x = 0 \<or> poly [:b2, - csqrt (2 * m), 1:] x = 0) [PROOF STEP] apply (subst (1 2) croots2[symmetric], auto) [PROOF STATE] proof (prove) goal: No subgoals! [PROOF STEP] done [PROOF STATE] proof (state) this: (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: (x \<in> set (solve_depressed_quartic_complex p q r)) = (x ^ 4 + p * x\<^sup>2 + q * x + r = 0) goal: No subgoals! [PROOF STEP] qed
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "Cubic_Quartic_Equations_Quartic_Polynomials", "hexsha": null, "include": null, "lang": null, "length": 70, "llama_tokens": 15784, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": null }
import pandas as pd import numpy as np def df_info(df: pd.DataFrame, return_info=False, shape=True, cols=True, info_prefix=''): """ Print a string to describe a df. """ info = info_prefix if shape: info = f'{info}Shape = {df.shape}' if cols: info = f'{info} , Cols = {df.columns.tolist()}' print(info) if return_info: return info def df_dummy_ts(start='2019-01-01', end='2019-01-02', freq='1s', n_cols=5, smooth_n: int = 100, smooth_f: str = 'mean', dropna: bool = True): """ Make dummy ts df. """ time_range = pd.DataFrame(pd.date_range(start, end, freq=freq), columns=['time']) data = pd.DataFrame(np.random.randn(len(time_range), n_cols), columns=[f'col{n}' for n in range(n_cols)]) df = pd.concat([time_range, data], axis=1) df = df.set_index('time') if smooth_n: if smooth_f == 'mean': df = df.rolling(smooth_n).mean() elif smooth_f == 'min': df = df.rolling(smooth_n).min() elif smooth_f == 'max': df = df.rolling(smooth_n).max() elif smooth_f == 'median': df = df.rolling(smooth_n).median() else: raise NotImplementedError(f'... {smooth_f} not implemented ...') if dropna: df = df.dropna() return df
{ "alphanum_fraction": 0.5750943396, "author": null, "avg_line_length": 31.5476190476, "converted": null, "ext": "py", "file": null, "hexsha": "957acd78c0f76d4da3ef2f328e31fbb96358c869", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "7397abe0e1a0c1dee049c63c6d987eb62cf01e31", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "andrewm4894/am4894pd", "max_forks_repo_path": "am4894pd/utils.py", "max_issues_count": 215, "max_issues_repo_head_hexsha": "7397abe0e1a0c1dee049c63c6d987eb62cf01e31", "max_issues_repo_issues_event_max_datetime": "2022-03-31T15:26:02.000Z", "max_issues_repo_issues_event_min_datetime": "2019-11-24T09:41:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "andrewm4894/am4894pd", "max_issues_repo_path": "am4894pd/utils.py", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "7397abe0e1a0c1dee049c63c6d987eb62cf01e31", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "andrewm4894/am4894pd", "max_stars_repo_path": "am4894pd/utils.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 357, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1325 }
\subsection{Implementing Small DB File IO in C} % (fold) \label{sub:implementing_small_db_file_io_in_c} \sref{sec:using_input_and_output} presented an altered version of the Small DB program from \cref{cha:dynamic_memory_allocation}. The changes introduced four new procedures used to save the programs data to file, and to reload the data from file. The new code is presented in \lref{lst:c-small-db3}. \straightcode{\ccode{lst:c-small-db3}{New C code for the Small DB program with file loading and saving}{code/c/file-io/small-db-changes.c}} \mynote{ \begin{itemize} \item The \texttt{FILE} type is used to refer to files that have been opened for the application. See \sref{sub:c_file_type} \nameref{sub:c_file_type}. \item \end{itemize} } % subsection implementing_small_db_file_io_in_c (end)
{ "alphanum_fraction": 0.7826086957, "author": null, "avg_line_length": 53.6666666667, "converted": null, "ext": "tex", "file": null, "hexsha": "8093747787808066de233c135bf647f0cfcd89fa", "include": null, "lang": "TeX", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2022-03-24T07:42:53.000Z", "max_forks_repo_forks_event_min_datetime": "2020-06-02T03:18:37.000Z", "max_forks_repo_head_hexsha": "8f3040983d420129f90bcc4bd69a96d8743c412c", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "macite/programming-arcana", "max_forks_repo_path": "topics/file-io/c/small-db-3.tex", "max_issues_count": 1, "max_issues_repo_head_hexsha": "bb5c0d45355bf710eff01947e67b666122901b07", "max_issues_repo_issues_event_max_datetime": "2021-12-29T19:45:10.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-29T19:45:10.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "thoth-tech/programming-arcana", "max_issues_repo_path": "topics/file-io/c/small-db-3.tex", "max_line_length": 299, "max_stars_count": 1, "max_stars_repo_head_hexsha": "bb5c0d45355bf710eff01947e67b666122901b07", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "thoth-tech/programming-arcana", "max_stars_repo_path": "topics/file-io/c/small-db-3.tex", "max_stars_repo_stars_event_max_datetime": "2021-08-10T04:50:54.000Z", "max_stars_repo_stars_event_min_datetime": "2021-08-10T04:50:54.000Z", "num_tokens": 215, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 805 }
import numpy as np from modules.image_processor import ImageProcessor from time import time,sleep import random import sys sys.path.append(r"./sign_lane") import sign as SN import lane import math import cv2 import bird from collections import Counter # escape obstacle OBSTACLE_RATIO = 2 CROSS_ANGLE = False # fork turn SIGN_FRAMES = 6 SIGN_RATIO = 5 # angle switch LANES_FRAMES = 6 # mid line cut LINE_RATIO = 0.545 # escape fork obstacle count FORK_OBSTACLE = 10 # wrong way check WRONG_MARK_CNT = 10 #hit wall delay HIT_WALL_DELAY = 10 my_debug = False def im_show(name, img): if my_debug: cv2.imshow(name, img) class AutoDrive(object): def __init__(self, car, debug=False): self.MAX_SPEED_HISTORY = 18 self.MAX_COLOR_HISTORY = 120 self.MAX_STEERING_HISTORY=50 self.MAX_STEERING=6.5 self.BACKTIME=0.066 self._car = car self._car.register(self) self.debug = debug self.half_pi = np.pi / 2 self._speed_history = [] self._color_history = [] self.dead=0 self._back1=0 self._back2=0 self._back=0 self.tt=-1 self.last_tt=0 self.obstacle=0 self.cputime=0 self.lastlap=-1 self.lastlap_time=-300 self.lastlap_time6=-300 self.bestlap_time=300 self.bestlap_time6=300 self.lap_gap=0 self.last_speed=0 self.laptime=0 self.last_laptime=0 self.distance=0 self.hitwall=0 self.total_hitwall=0 self.steering_history=[] self.last_steering_angle = 0 self.class_id=-1 self.throttle=0 self.steering_angle=0 self._uturn=0 self._uturn_d=0 self.roadcheck=0 self.roadcheck0=0 # vars self.wall_counts = [] self.sign_class = SN.Sign() self.sign_history = [] self.last_lanes = -1 self.lanes_history = [] self.lanes_frames = LANES_FRAMES self.on_obstacle = True self.mark_class = lane.Mark() self.lane_id = -1 self.on_which = -1 self.last_lane_id = -1 self.hit_wall_delay = 0 self.f = open("./log/mylog.txt", "w") self.fork_cnt = 0 self.fork_id = None self.last_fork_id = None self.follow_fork = 0 self.red_conts = None self.fork_run = 0 self.last_sign_time = None self.start_locate = False self.last_hit_wall = False # switch to red lane, and follow it (direct = 0) def _on_red_lane(self, lanes): lane_thresh = 9000 wtrend = self.wall_trend(lanes) red_conts = self.red_lanes(lanes) if red_conts is None or len(red_conts) == 0: return 0 num = len(red_conts) if num == 1: return wtrend else: #if red_conts[0].type() == lanes.RED_LANE and red_conts[0].area() > lane_thresh: if red_conts[0].area() > lane_thresh: return -1 #if red_conts[-1].type() == lanes.RED_LANE and red_conts[-1].area() > lane_thresh: if red_conts[-1].area() > lane_thresh: return 1 return 0 def on_red_lane(self, lanes, direct): lane_thresh = 9000 wtrend = self.wall_trend(lanes) red_conts = self.red_lanes(lanes) if red_conts is None or len(red_conts) == 0: return False num = len(red_conts) if num == 1: idx = 0 if direct == -1 else 1 wc = self.wall_counts[idx] if wc > 9000: return True return False else: #if red_conts[0].type() == lanes.RED_LANE and red_conts[0].area() > lane_thresh: if red_conts[0].area() > lane_thresh: return -1 == direct #if red_conts[-1].type() == lanes.RED_LANE and red_conts[-1].area() > lane_thresh: if red_conts[-1].area() > lane_thresh: return 1 == direct return False def red_lanes(self, lanes): if self.red_conts is not None: return self.red_conts red_mask = lanes.red_mask() h,w = red_mask.shape[:2] red_conts = [] binary, contours, hierarchy = cv2.findContours(red_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) areas = [] for i in range(len(contours)): areas.append(cv2.contourArea(contours[i])) if len(areas) == 0: return None areas = np.array(areas) idx = np.argsort(-areas) for i in idx: cont = contours[i] cont = lane.Contour(lanes, cont) cmask = cont.mask() if cont.area() < 150: continue wmask = lanes.mask_add(cmask, lanes.white_mask()) if np.sum(wmask > 0) > cont.area()/3: continue locs = np.where(cmask > 0) loc_y = np.sum(locs[0])/len(locs[0]) if loc_y < h*4/5: red_conts.append(cont) if len(red_conts) == 0: return None if len(red_conts) > 3: red_conts = red_conts[0:3] # sort contour with min x with bird view if len(red_conts) > 1: red_conts.sort(key=lambda x : x.min_location()[0]) #red_conts = sorted(sorted(red_conts, key = lambda x:x.min_location()[0]), key = lambda y:y.min_location()[1], reverse = True) num = len(red_conts) if num == 3: if red_conts[0].type() != lanes.RED_LANE: red_conts[0].ctype = lanes.RED_LANE if red_conts[2].type() != lanes.RED_LANE: red_conts[2].ctype = lanes.RED_LANE if red_conts[1].type() != lanes.RED_LINE: red_conts[1].ctype = lanes.RED_LINE elif num == 2: if red_conts[0].type() == lanes.RED_LINE and red_conts[1].type() == lanes.RED_LINE: if red_conts[0].bird_area() > red_conts[1].bird_area(): red_conts[0].ctype = lanes.RED_LANE else: red_conts[1].ctype = lanes.RED_LANE elif red_conts[0].type() == lanes.RED_LANE and red_conts[1].type() == lanes.RED_LANE: if red_conts[0].bird_area() < red_conts[1].bird_area(): red_conts[0].ctype = lanes.RED_LINE else: red_conts[1].ctype = lanes.RED_LINE elif num == 1: red_conts[0].ctype = lanes.RED_LANE self.red_conts = red_conts i = 0 for cont in red_conts: im_show("red cont " + str(i), cont.mask()) i += 1 return self.red_conts def wall_count(self, lanes): wmask = lanes.wall_mask() h,w = wmask.shape[:2] left_mask = wmask[:, 0:int(w/2)] right_mask = wmask[:, int(w/2):w] left_count = np.sum(left_mask > 0) right_count = np.sum(right_mask > 0) return left_count, right_count def entrance_fork_lane(self, lanes, direct): red_conts = self.red_lanes(lanes) if red_conts is None: return True if len(red_conts) != 1: return False left, right = self.wall_counts[0], self.wall_counts[1] diff = left - right val = direct * diff if val > 0: return True return False def wall_trend(self, lanes): left_count, right_count = self.wall_counts[0], self.wall_counts[1] return right_count - left_count def red_lane_angle(self, lanes, direct = 0): red_conts = self.red_lanes(lanes) if red_conts is None: return None num = len(red_conts) if num == 0: return None wtrend = self.wall_trend(lanes) fix_angle = 5 * direct target_cont = None bird_max_cont = None if bird_max_cont is None: area = 0 for cont in red_conts: if cont.area() > area: area = cont.area() bird_max_cont = cont #decide red lane if direct == 0: target_cont = bird_max_cont elif self.on_which == 0: #if direct * wtrend > 0: if self.on_red_lane(lanes, direct): idx = 0 if direct == -1 else -1 target_cont = red_conts[idx] else: return fix_angle * 2 else: if direct == 1: if num == 3: target_cont = red_conts[-1] elif num == 2: if red_conts[1].type() == lanes.RED_LANE: target_cont = red_conts[1] elif red_conts[0].type() == lanes.RED_LANE: return fix_angle else: if direct * wtrend > 0: target_cont = bird_max_cont else: return fix_angle if direct == -1: if num == 3: target_cont = red_conts[0] elif num == 2: if red_conts[0].type() == lanes.RED_LANE: target_cont = red_conts[0] elif red_conts[1].type() == lanes.RED_LANE: return fix_angle else: if direct * wtrend > 0: target_cont = bird_max_cont else: return fix_angle angle = None if target_cont is not None: mask = target_cont.mask() angle = self.red_angle(mask) #print("target cont area",target_cont.area()) #img = lanes.crop_img() #cv2.drawContours(img, [target_cont.cont], -1, (255,0,0), 3) #im_show("target lane", img) if angle is None: return fix_angle return angle def red_angle(self, mask): red_mask = mask red_mask = bird.view(red_mask) h,w = red_mask.shape[:2] line = red_mask[ int(LINE_RATIO * h), :] locs = np.where(line > 0) if locs is None or len(locs[0].tolist()) < 10: return None x = sum(locs[0].tolist()) / len(locs[0].tolist()) angle = (x - 160) * 0.1 return angle def max_red_lane_angle(self, lanes): red_conts = self.red_lanes(lanes) if red_conts is None: return None target_cont = None area = 0 for cont in red_conts: carea = cont.area() if carea > area: area = carea target_cont = cont if target_cont is None: return None #img = lanes.crop_img().copy() #cv2.drawContours(img, [target_cont.cont], -1, (0,255,0), 3) #im_show("follow max cont", img) #bird_img = bird.view(img) #im_show("bird follow max cont", bird_img) return self.red_angle(target_cont.mask()) def on_main_lanes(self): if len(self.lanes_history) < self.lanes_frames: return 1 history = np.array(self.lanes_history) num = len(self.lanes_history) first_half = self.lanes_history[int(num/2):num] second_half = self.lanes_history[0:int(num/2)] main_sum = np.sum(np.array(first_half) == 2) fork_sum = np.sum(np.array(second_half) == 1) main = main_sum > self.lanes_frames / 4 or main_sum > fork_sum if main: return 1 fork_sum = np.sum(np.array(first_half) == 1) main_sum = np.sum(np.array(second_half) == 2) fork = fork_sum > main_sum if fork: return 0 return -1 def on_lane_id(self, lanes): self.lane_id = lanes.locate() if self.lane_id == -1 and self.last_lane_id != -1: if self.last_steering_angle > 0: if self.last_lane_id > -1: if self.last_lane_id == 5: self.lane_id = 5 elif self.last_lane_id == 2.5: self.lane_id = 3 else: self.lane_id = self.last_lane_id + 1 elif self.last_steering_angle < 0: if self.last_lane_id > -1: if self.last_lane_id == 0: self.lane_id = 0 elif self.last_lane_id == 2.5: self.lane_id = 2 else: self.lane_id = self.last_lane_id - 1 self.last_lane_id = self.lane_id return self.lane_id def hit_wall_reset(self): self.fork_id = self.last_fork_id self.hit_wall_delay = HIT_WALL_DELAY #self.lanes_history = [] self.on_which = -1 self.roadcheck=0 self.roadcheck0=0 self.last_hit_wall = True print("# hit wall") def on_dashboard(self, src_img,dashboard): start_time = time() self.laptime=float(dashboard["time"]) speed = float(dashboard["speed"]) lap= int(dashboard["lap"]) if "lap" in dashboard else 0 self.distance=self.distance+(speed+self.last_speed)/2.*(self.laptime-self.last_laptime) self.last_speed=speed self.last_laptime=self.laptime if self.lastlap!= lap and lap>0: if lap>2 : self.lap_gap=self.lap_gap+abs(float(dashboard['time'])-self.lastlap_time-self.bestlap_time ) if float(dashboard['time'])-self.lastlap_time < self.bestlap_time : self.bestlap_time=float(dashboard['time'])-self.lastlap_time self.total_hitwall= self.total_hitwall+ self.hitwall print("lap= ",lap," %3.3f"%(float(dashboard['time'])-self.lastlap_time),"best lap=%3.3f"%self.bestlap_time,"D=%4.3f"%self.distance,"avg gap=%3.3f"%(self.lap_gap/max(lap-2.,1.)),"TH=", self.total_hitwall,"sp=",self.MAX_STEERING) self.lastlap_time=float(dashboard['time']) self.lastlap=lap self.lastlap_time6=float(dashboard['time']) self.distance=0 self.hitwall=0 # reset state if self.hit_wall_delay > 0: self.hit_wall_delay -= 1 self.red_conts = None #preprocess track_img = ImageProcessor.preprocess(src_img) lanes = lane.Lanes(src_img) #blanes = bird.view(lanes.crop_img(),1) #im_show("bird lanes", blanes) #self.red_lanes(lanes) on_which = lanes.on_main_lanes() if len(self.lanes_history) > 30: self.lanes_history = self.lanes_history[1:-1] #if not self.start_locate: # on_which = 1 self.lanes_history.append(on_which + 1) # lanes info self.lane_id = self.on_lane_id(lanes) self.on_which = self.on_main_lanes() if self.on_which == -1: self.on_which = self.last_lanes self.last_lanes = self.on_which if self.on_which == 1: self.start_locate = False if self.on_which == 0: self.fork_run += 1 else: self.fork_run = 0 class_id = self.sign_class.predict(src_img) obs = None if class_id == 0 or class_id == 1: obs = lanes.detect_obstacle() else: obs = lanes.obstacle_mask() obs = lanes.detect_obstacle(True) #print("# on which", self.on_which) #print("# lane id", self.lane_id) #print("# self.fork id", self.fork_id) #print("wall counts", self.wall_counts) # wall angle start left_wall_distance, right_wall_distance, left_wall_count, right_wall_count = self.wall_detector(track_img) self.wall_counts = [left_wall_count, right_wall_count] # escape obstacle if not obs is None: obs_ratio = OBSTACLE_RATIO # fork obstacle if self.on_which == 0: obs_ratio /= 2 obs_mask = obs h, w = obs_mask.shape[:2] left_mask = obs_mask[:, 0:int(w/2)] right_mask = obs_mask[:, int(w/2) : w] left_mask_count = np.sum(left_mask > 0) * obs_ratio right_mask_count = np.sum(right_mask > 0) *obs_ratio left_wall_count += left_mask_count right_wall_count += right_mask_count base = h * 0.2 *w left_wall_distance = left_wall_count/base right_wall_distance = right_wall_count/base # fork turn sign_frames = SIGN_FRAMES if len(self.sign_history) >= sign_frames: string=''' num = len(self.sign_history) class0 = np.sum(np.array(self.sign_history) == 1) class1 = np.sum(np.array(self.sign_history) == 2) cid = -1 if class1 > class0 and class1 > num/4: cid = 1 if class0 > class1 and class0 > num/4: cid = 0 ''' num = len(self.sign_history) before = np.array(self.sign_history[0:int(num/2)]) after = np.array(self.sign_history)[int(num/2):num] turn = np.sum(after) == 0 fork = False class1 = np.sum(before == 2) class0 = np.sum(before == 1) cid = -1 if class1 > class0 and class1 > num/4: cid = 1 if class0 > class1 and class0 > num/4: cid = 0 if cid != -1: fork = True fork = turn and fork repeat = False if self.last_sign_time is not None: if start_time - self.last_sign_time < 3.000: repeat = True if fork and not repeat and self.fork_id is None and self.follow_fork == 0 and cid != -1: self.fork_id = 1 if cid == 0 else -1 self.last_sign_time = start_time self.start_locate = True self.sign_history = self.sign_history[1:-1] if len(self.sign_history) < sign_frames: if class_id >= 2: class_id = -1 self.sign_history.append(class_id +1) # fork lane obstacle escape loc = SN.detect_obstacle(src_img) if True: if loc != [-1, -1]: self.on_obstacle = True self.fork_id = None else: self.on_obstacle = False # angle switch switch = False # cross angle if CROSS_ANGLE and not self.on_obstacle and self.fork_id is not None and self.on_which == 1: cross = lanes.cross_angle() angle = cross[0] if angle is not None: switch = True print("# cross angle") self.throttle = 1 self.steering_angle = angle else: switch = False # mid red angle # print("# hit wall delay", self.hit_wall_delay) # print("# on which", self.on_which) need_follow = self.follow_fork > 0 or self.fork_id is not None need_mid = self.hit_wall_delay == 0 and not self.on_obstacle and self.on_which == 0 #print("# need follow", need_follow) #print("# need mid", need_mid) if switch: pass #elif self.follow_fork > 0 or self.fork_id is not None or self.hit_wall_delay == 0 and not self.on_obstacle and (self.on_which + self.last_lanes) < 2: elif need_follow or need_mid: angle = None if self.fork_id is not None: #if self.on_red_lane(lanes) == self.fork_id or self.on_which + self.last_lanes < 2: entrance = self.entrance_fork_lane(lanes, self.fork_id) if entrance: pass #print("# fork lane entrance") if self.on_red_lane(lanes, self.fork_id): #print("# strick to red lane") self.last_fork_id = self.fork_id self.fork_id = None self.follow_fork = 20 if entrance: self.last_fork_id = None self.follow_fork = 0 # now need follow max contour else: #print("# switch to red lane") angle = self.red_lane_angle(lanes, self.fork_id) self.follow_fork = 0 if self.last_fork_id is not None or self.fork_id is not None: direct = self.fork_id if self.fork_id is not None else self.last_fork_id if self.entrance_fork_lane(lanes, direct): self.last_fork_id = None self.fork_id = None self.follow_fork = 0 if self.fork_run > 8: pass # print("predict on fork") # self.last_fork_id = None #add # self.follow_fork = 0 # self.fork_id = None # on target lane and follow it if self.fork_id is None: angle = self.max_red_lane_angle(lanes) #print("# follow red lane") if angle is not None: direct = 1 if angle > 0 else -1 if math.fabs(angle) >=15.9: angle = None if angle is not None: self.throttle = 1 self.steering_angle = angle switch = True else: switch = False if self.follow_fork > 0: self.follow_fork -=1 # mid wall angle if not switch: self.steering_angle = self.find_wall_angle(left_wall_distance, right_wall_distance) self.throttle = 1 if left_wall_count < 2450 and right_wall_count < 2450: self.steering_angle = self.steering_angle / 5 if left_wall_count > 3400 and right_wall_count > 3400: self.steering_angle = self.steering_angle * 6 if right_wall_distance == left_wall_distance == 1: self.steering_angle = self.last_steering_angle else: self.last_steering_angle= self.steering_angle # print("# wall angle") if my_debug: im_show("source", src_img) cv2.waitKey(1) self._car.control(0,0) return # mark detection if self.last_hit_wall: mark = self.mark_class direct = mark.predict(src_img) if direct == 1 : self.roadcheck=self.roadcheck+1 elif direct == 0: self.roadcheck0 -= 1 if self.roadcheck0 < -5: self.roadcheck0 = 0 self.last_hit_wall = False ############# Hit wall recover ########## if self.debug: ImageProcessor.show_image(track_img, "track") track_count = 6 self.tt=self.tt+1 if self.tt>15*60 : self.tt=0 self.roadcheck=0 self.cputime=0 if self._uturn>0 or self.roadcheck>5 : self.roadcheck=0 if self._uturn==0 : self._uturn=10 for (cc,cc1) in reversed(self._color_history): if cc>cc1 : self._uturn_d=0 break elif cc1>cc: self._uturn_d=1 break if track_count==3 : self._uturn=self._uturn-1 self._uturn=self._uturn-1 if self._uturn_d==0 : print("wrong road u-turn,left") self._back2=self.MAX_SPEED_HISTORY/2+4 x=self.BACKTIME-(time()-start_time) if x>0: sleep(x) self._car.control(-40, 1) else : print("wrong road u-turn,right") self._back1=self.MAX_SPEED_HISTORY/2+4 x=self.BACKTIME-(time()-start_time) if x>0: sleep(x) self._car.control(40, 1) self.steering_angle=0 self.cputime=self.cputime+time()-start_time return self._color_history.append((left_wall_distance,right_wall_distance)) self._color_history = self._color_history[-self.MAX_COLOR_HISTORY:] if len(self._color_history)<2 : self._color_history.append((left_wall_distance,right_wall_distance)) self._speed_history.append(speed) self._speed_history = self._speed_history[-self.MAX_SPEED_HISTORY:] if sum(self._speed_history[-3:-1])/3>0.04 : self.dead=0 if (sum(self._speed_history[-3:-1])/3<0.04 and (self.dead==0 or self.obstacle>0) and len(self._speed_history)==self.MAX_SPEED_HISTORY) \ or self._back>0 or self._back1>0 or self._back2>0 : self.hitwall=self.hitwall+1 if self.hitwall > 0: self.hit_wall_reset() if self._back1>0 : self._back1=self._back1-1 if track_count==3 and self._back1>6 : self._back1=self._back1-1 if self._back>0 : self._back=self._back-1 self.cputime=self.cputime+time()-start_time x=self.BACKTIME-(time()-start_time) if x>0: sleep(x) if self._back1>6 :self._car.control(-40, -0.4) else: self._car.control(40, 1) return if self._back2>0 : self._back2=self._back2-1 if track_count==3 and self._back2>6 : self._back2=self._back2-1 if self._back>0 : self._back=self._back-1 self.cputime=self.cputime+time()-start_time x=self.BACKTIME-(time()-start_time) if x>0: sleep(x) if self._back2>6 :self._car.control(40, -0.4) else: self._car.control(-40, 1) return if self._back>0 : self._back=self._back-1 self.cputime=self.cputime+time()-start_time x=self.BACKTIME-(time()-start_time) if x>0: sleep(x) self._car.control(0, -1) return if self.obstacle>=0: for (cc,cc1) in reversed(self._color_history): if (cc>cc1): if self._back1==0 : self._back1=self.MAX_SPEED_HISTORY/2+4 self._car.control(-40, -1) self.steering_angle=0 self.cputime=self.cputime+time()-start_time self.last_tt=self.tt return if cc1>cc : if self._back2==0 : self._back2=self.MAX_SPEED_HISTORY/2+4 self._car.control(40, -1) self.steering_angle=0 self.cputime=self.cputime+time()-start_time self.last_tt=self.tt return if self._back==0 : if self.dead==1 : if (random.randint(10, 20)>=18) : self._back2=self.MAX_SPEED_HISTORY/2+4 elif (random.randint(10, 20)<=13) : self._back1=self.MAX_SPEED_HISTORY/2+4 else: self._back=int(self.MAX_SPEED_HISTORY)+random.randint(10, 20) else: self._back=int(self.MAX_SPEED_HISTORY) self.cputime=self.cputime+time()-start_time x=self.BACKTIME-(time()-start_time) if x>0: sleep(x) self._car.control(0, -1) return ########################## if self.on_which == 0: abs_angle = math.fabs(self.steering_angle) if abs_angle > 45: abs_angle = 45 beta = 1/(1+ math.exp(-(45 - abs_angle))/3) self.throttle *= beta if not switch and self.on_which == 1: direct = 1 if self.steering_angle > 0 else -1 if direct > 0 and self.steering_angle > 22: self.steering_angle = direct * (direct * self.steering_angle + 10) #print(self.steering_angle, self.throttle) self.last_steering_angle = self.steering_angle self._car.control(self.steering_angle, self.throttle) return def wall_detector(self,img, ratio = 0.5): img_height = img.shape[0] img_width = img.shape[1] half_width = int(img_width * ratio) half_height = int(img_height * 0.2) img_left = img[half_height:img_height, 0:half_width].copy() img_right = img[half_height:img_height, half_width:img_width].copy() black_wall = [(0, 0, 0), (10, 10, 10)] yellow_wall = [(0, 160, 160), (0, 180, 180)] max_color_count = half_height * half_width * 4 left_color_count = float(ImageProcessor.count_color(img_left, black_wall, yellow_wall)) right_color_count = float(ImageProcessor.count_color(img_right, black_wall, yellow_wall)) left_wall_distance = left_color_count / max_color_count right_wall_distance = right_color_count / max_color_count return left_wall_distance, right_wall_distance, left_color_count, right_color_count def find_wall_angle(self,left_wall_distance, right_wall_distance): #global steering_history count_rate = (right_wall_distance / left_wall_distance) if left_wall_distance > 0 else 0 count_rate = max(min(count_rate * 40 , self.MAX_STEERING), 0) steering_angle = -count_rate if right_wall_distance > left_wall_distance else count_rate ''' self.steering_history.append(steering_angle) self.steering_history = self.steering_history[-self.MAX_STEERING_HISTORY:] if abs(sum(self.steering_history))>self.MAX_STEERING_HISTORY*self.MAX_STEERING-0.01 : steering_angle=-0.7 if right_wall_distance > left_wall_distance else 0.7 self.steering_history[0]=0 ''' #print(steering_angle,abs(sum(self.steering_history))) return steering_angle
{ "alphanum_fraction": 0.5284278768, "author": null, "avg_line_length": 34.5078299776, "converted": null, "ext": "py", "file": null, "hexsha": "97a4c7dbbe88cb6792322160644c0a2b2a409d9a", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "0c45030c9f761a1e38abf7fc3957244389bb1165", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "YingshuLu/self-driving-formula-racing", "max_forks_repo_path": "auto_drive/ai_drive/modules/auto_drive.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "0c45030c9f761a1e38abf7fc3957244389bb1165", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "YingshuLu/self-driving-formula-racing", "max_issues_repo_path": "auto_drive/ai_drive/modules/auto_drive.py", "max_line_length": 236, "max_stars_count": null, "max_stars_repo_head_hexsha": "0c45030c9f761a1e38abf7fc3957244389bb1165", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "YingshuLu/self-driving-formula-racing", "max_stars_repo_path": "auto_drive/ai_drive/modules/auto_drive.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 7620, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 30850 }
SUBROUTINE CloseVariables ! By Allan P. Engsig-Karup. USE GlobalVariables USE MGlevels IMPLICIT NONE DEALLOCATE(Wavefield%E,Wavefield%W,Wavefield%P,FineGrid%h,tmp2D) IF (FineGrid%Nx>1) THEN DEALLOCATE(Wavefield%Ex,Wavefield%Exx,Wavefield%Px) DEALLOCATE(FineGrid%hx,FineGrid%hxx) ! DEALLOCATE(FineGrid%DiffStencils%StencilX) ! DEALLOCATE(FullRankStencils%StencilX) END IF IF (FineGrid%Ny>1) THEN DEALLOCATE(Wavefield%Ey,Wavefield%Eyy,Wavefield%Py) DEALLOCATE(FineGrid%hy,FineGrid%hyy) ! DEALLOCATE(FineGrid%DiffStencils%StencilY) ! DEALLOCATE(FullRankStencils%StencilY) END IF !DEALLOCATE(FullRankStencils%StencilZ) !DEALLOCATE(FullRankStencils%Indexes) !DEALLOCATE(FullRankStencils%Indexesnew) !DEALLOCATE(FullRankStencils%StencilXZorYZ) DEALLOCATE(rhsE,rhsP,PHI,RHS) !DEALLOCATE(FineGrid%dsigma) IF (Precond==3) THEN DEALLOCATE(arrLevels) ! From Multigrid part ENDIF DEALLOCATE(COLSCA, ROWSCA,workspace) ! Deallocate grid information (FIXME) IF (relaxONOFF==1) THEN DEALLOCATE(RelaxZones) ENDIF ! GD: New variable definition, SWENSE part IF(swenseONOFF==1) THEN !We deallocate the incident wavefields values DEALLOCATE(Wavefield%E_I,Wavefield%Et_I,Wavefield%P_I_s,Wavefield%Pz_I_s,Wavefield%Pt_I_s,Wavefield%E_I_bp,Wavefield%Pz_I_bp) IF (FineGrid%Nx>1) THEN DEALLOCATE(Wavefield%Ex_I, Wavefield%Exx_I, Wavefield%Px_I_s, Wavefield%Ex_I_bp,Wavefield%Px_I_bp) ENDIF IF (FineGrid%Ny>1) THEN DEALLOCATE(Wavefield%Ey_I, Wavefield%Eyy_I, Wavefield%Py_I_s, Wavefield%Ey_I_bp, Wavefield%Py_I_bp) ENDIF ! Deallocate the surfacic source terms ! FIXME: Define even if non-SWENSE ? ! APEK: moved lines below inside loop as these are only allocated in SWENSE? IF (FineGrid%Nx>1) THEN DEALLOCATE(Wavefield%SourceEx, Wavefield%SourcePx) ENDIF IF (FineGrid%Ny>1) THEN DEALLOCATE(Wavefield%SourceEy, Wavefield%SourcePy) ENDIF ENDIF END SUBROUTINE CloseVariables
{ "alphanum_fraction": 0.8048780488, "author": null, "avg_line_length": 35.5849056604, "converted": null, "ext": "f90", "file": null, "hexsha": "2160b2ee9e1ccb66853945a7df3ab3c6886518d4", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 26, "max_forks_repo_forks_event_max_datetime": "2021-12-02T16:23:37.000Z", "max_forks_repo_forks_event_min_datetime": "2015-10-01T12:17:08.000Z", "max_forks_repo_head_hexsha": "91979da3ede3215b2ae65bffab89b695ff17f112", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "apengsigkarup/OceanWave3D", "max_forks_repo_path": "src/initialization/CloseVariables.f90", "max_issues_count": 7, "max_issues_repo_head_hexsha": "91979da3ede3215b2ae65bffab89b695ff17f112", "max_issues_repo_issues_event_max_datetime": "2021-06-07T07:37:11.000Z", "max_issues_repo_issues_event_min_datetime": "2015-10-10T19:45:08.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "apengsigkarup/OceanWave3D", "max_issues_repo_path": "src/initialization/CloseVariables.f90", "max_line_length": 129, "max_stars_count": 46, "max_stars_repo_head_hexsha": "91979da3ede3215b2ae65bffab89b695ff17f112", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "apengsigkarup/OceanWave3D", "max_stars_repo_path": "src/initialization/CloseVariables.f90", "max_stars_repo_stars_event_max_datetime": "2022-03-30T06:56:45.000Z", "max_stars_repo_stars_event_min_datetime": "2016-01-08T12:36:39.000Z", "num_tokens": 673, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 1886 }
import open3d as o3d import argparse import os import sys import logging import numpy import numpy as np import torch import torch.utils.data import torchvision from torch.utils.data import DataLoader from tqdm import tqdm from sklearn.neighbors import NearestNeighbors from scipy.spatial.distance import minkowski import transforms3d # Only if the files are in example folder. BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(BASE_DIR, os.pardir)) from learning3d.data_utils import RegistrationData, ModelNet40Data, KittiDataset from learning3d.ops import se3 # Class to apply transformations. class PNLKTransform: """ rigid motion """ def __init__(self, mag=1, mag_randomly=False): self.mag = mag # Angle in radians. self.randomly = mag_randomly # Random angles < mag. # Choose random translation in certain range or in [-0.3, 0.3] if not self.randomly: self.max_trans = 0.3 else: self.max_trans = self.mag self.gt = None # Source -> Template self.igt = None # Template -> Source def generate_transform(self): # return: a twist-vector amp = self.mag if self.randomly: amp = torch.rand(1, 1) * self.mag # Create vector for rotation. x = torch.randn(1, 3) x = x / x.norm(p=2, dim=1, keepdim=True) * amp # Create vector for translation. t = torch.rand(1, 3) * self.max_trans x = torch.cat((x, t), dim=1) return x # [1, 6] def apply_transform(self, p0, x): # p0: Template [N, 3] # x: Twist Vector [1, 6] # p1: Source [N, 3] g = se3.exp(x).to(p0) # [1, 4, 4] gt = se3.exp(-x).to(p0) # [1, 4, 4] p1 = se3.transform(g, p0[:, :3]) # p1 = Tgt * p0 if p0.shape[1] == 6: # Need to rotate normals also g_n = g.clone() g_n[:, :3, 3] = 0.0 n1 = se3.transform(g_n, p0[:, 3:6]) p1 = torch.cat([p1, n1], axis=-1) self.gt = gt.squeeze(0) # gt: p1 -> p0 self.igt = g.squeeze(0) # igt: p0 -> p1 return p1 def transform(self, tensor): # tensor: Point Cloud [N, 3] # x: Twist Vector [1, 6] x = self.generate_transform() return self.apply_transform(tensor, x) def __call__(self, tensor): # tensor: Point Cloud [N, 3] return self.transform(tensor) # Create partial point cloud by sampling knn points near a random point. def farthest_subsample_points(pointcloud1, num_subsampled_points=768): # pointcloud1: Point Cloud [N, 3] (tensor or ndarray) # gt_mask: Mask [N, 1] (tensor) pointcloud1 = pointcloud1 num_points = pointcloud1.shape[0] # obj to find nearest neigbours. nbrs1 = NearestNeighbors(n_neighbors=num_subsampled_points, algorithm='auto', metric=lambda x, y: minkowski(x, y)).fit(pointcloud1[:, :3]) # Chose random point to find "num_subsampled_points" points near it. random_p1 = np.random.random(size=(1, 3)) + np.array([[500, 500, 500]]) * np.random.choice([1, -1, 1, -1]) # Find indices of nearest neighbours for the random point. idx1 = nbrs1.kneighbors(random_p1, return_distance=False).reshape((num_subsampled_points,)) gt_mask = torch.zeros(num_points).scatter_(0, torch.tensor(idx1), 1) # Create a mask of 1's or 0's return pointcloud1[idx1, :], gt_mask def add_outliers(pointcloud, gt_mask, size=100): # pointcloud: Point Cloud (ndarray) [NxC] # size: Number of outliers to be added (int) # output: Corrupted Point Cloud (ndarray) [(N+300)xC] if size == 0: return pointcloud, gt_mask # If size is 0 then, don't do anything. if not torch.is_tensor(pointcloud): pointcloud = torch.tensor(pointcloud) N, C = pointcloud.shape outliers = 2*torch.rand(size, C)-1 # Sample points in a cube [-0.5, 0.5] pointcloud = torch.cat([pointcloud, outliers], dim=0) gt_mask = torch.cat([gt_mask, torch.zeros(size)]) idx = torch.randperm(pointcloud.shape[0]) pointcloud, gt_mask = pointcloud[idx], gt_mask[idx] return pointcloud.detach().cpu().numpy(), gt_mask def pc2open3d(data): if torch.is_tensor(data): data = data.detach().cpu().numpy() if len(data.shape) == 2: pc = o3d.geometry.PointCloud() pc.points = o3d.utility.Vector3dVector(data) return pc else: print("Error in the shape of data given to Open3D!, Shape is ", data.shape) # Visualize data points. def visualize_result(template, source, est_T): template, source, est_T = template, source, est_T transformed_template = np.matmul(est_T[0:3, 0:3], template.T).T + est_T[0:3, 3] # Rotate template as per inverse ground truth est_T. template = pc2open3d(template) source = pc2open3d(source) transformed_template = pc2open3d(transformed_template) template.paint_uniform_color([1, 0, 0]) source.paint_uniform_color([0, 1, 0]) transformed_template.paint_uniform_color([0, 0, 1]) o3d.visualization.draw_geometries([template, source, transformed_template]) # Add data in h5py file. def save_dataset(testdata, group_name, file): # testdata: data to be stored (list of list) # group_name: group in h5py hierarchy # file: h5py File object group = file.create_group(group_name) # Create a group inside h5py File. t_list, s_list, igt_list, mask_list = testdata # seperate lists. group.create_dataset('templates', data=np.array(t_list)) # create_dataset with name 'templates' and associated data. group.create_dataset('sources', data=np.array(s_list)) group.create_dataset('igt', data=np.array(igt_list)) group.create_dataset('masks', data=np.array(mask_list)) return file # Create random axes for axangle transformation. def create_axes(size=1000): axes = [] for _ in range(size): axis = np.random.randn(1,3) axis = axis/np.sqrt(np.mean(np.square(axis))) axes.append(axis[0]) return np.array(axes) # Add noise in point cloud. def jitter_pointcloud(pointcloud, sigma=0.0): # pointcloud: [B, N, 3] or [N, 3] (ndarray) pointcloud = torch.tensor(pointcloud).float() if sigma > 0: pointcloud += torch.empty(pointcloud.shape).normal_(mean=0, std=sigma) return pointcloud.detach().cpu().numpy() # Create random translations. def create_translations(size=1000): return np.array([np.random.rand(3) for _ in range(size)]) # Define range of angles to be tested. def angle_range(): return np.arange(0, 100, 10) # Define range of noises to be tested. def noise_range(): return [0, 0.02, 0.04, 0.06, 0.1, 0.15, 0.2] # Define range of noises to be tested. def outlier_range(): return np.arange(0, 100, 10).tolist() + np.arange(100, 1100, 100).tolist() # Function to apply ax-angle transformation on template. def transform_axangle(template, axis, angle, translation): # template, source: Point Cloud [N, 3] (ndarray) # axis: Axis of rotation [3,] (ndarray) # angle: Magnitude of rotation in radians (scalar) # translation: Vector for translation [3, ] (ndarray) # igt: Inverse ground truth transformation [4, 4] (ndarray) (template -> source.) igt = np.eye(4) igt[0:3, 0:3] = transforms3d.axangles.axangle2mat(axis, angle) igt[0:3, 3] = translation source = np.matmul(igt[0:3, 0:3], template.T).T + igt[0:3, 3] return source, igt # Function to appply twist-vector transformation on template. def transform_pnlk(template, transform): # template, source: Point Cloud [N, 3] (ndarray) # transform: object of PNLKTransform class. # igt: Inverse ground truth transformation [4, 4] (ndarray) (template -> source.) source = transform(template) igt = transform.igt return source.detach().cpu().numpy(), igt.detach().cpu().numpy() # Create a dataset for a particular angle or a noise value. def create_one_dataset(args, test_loader, axes, angle, translations, noise=0.0, outlier_size=100): # args: Arguments used to create dataset. # test_loader: Contains template point clouds (object of RegistrationData class) # axes: Axes of rotation [B, 3] (ndarray) # angle: Magnitude of angle (scalar) # translations: Translation vectors [B, 3] (ndarray) # noise: Std. Dev. of noise in source point cloud. t_list, s_list, igt_list, mask_list = [], [], [], [] # templates, sources, inverse gt transformations, masks for partial sources. count = 0 if args.case == 'various_noises': mag_randomly = True # If testing for noise levels then random angles. elif args.case == 'various_rotations': mag_randomly = False # If testing for misalignment levels then fix angle. elif args.case == 'various_outliers': mag_randomly = True # If testing for outliers then random angles. transform = PNLKTransform(mag=angle, mag_randomly=mag_randomly) for i, data in enumerate(tqdm(test_loader)): if count > args.data_size - 1: print("\n") break # break as the dataset size is reached. if args.transform_type == 'axis_angle': # For Axis Angle Transfomation. data_ = [d.detach().cpu().numpy() for d in data] template = data_[0] source, igt = transform_axangle(template, axes[i], angle, translations[i]) # source = T * template elif args.transform_type == 'twist_vector': # For PNLK Transformation. template = data[0] source, igt = transform_pnlk(template, transform) # source = T * template template = template.detach().cpu().numpy() gt_mask = torch.ones(template.shape[0]) # by default all ones. if args.case == 'various_rotations' or args.case == 'various_noises': source, gt_mask = farthest_subsample_points(source) # Create partial source. if args.case == 'various_outliers': template, gt_mask = add_outliers(template, gt_mask, size=outlier_size) # Add outliers in template. source = jitter_pointcloud(source, sigma=noise) # Add noise to source. # Add data points to lists. t_list.append(template) s_list.append(source) igt_list.append(igt) mask_list.append(gt_mask.detach().cpu().numpy()) # visualize_result(template, source, igt) # Uncomment to visualize data point. count += 1 return t_list, s_list, igt_list, mask_list # Create entire dataset. def create(args, test_loader): # args: Arguments used to create dataset. # test_loader: Contains template point clouds (object of RegistrationData class) axes = create_axes(args.data_size) # create axes of rotation. translations = create_translations(args.data_size) # create translation vectors. import h5py file = h5py.File(args.name, 'w') # create h5py dataset file. # If testing for initial misalignment levels. if args.case == 'various_rotations': for angle in angle_range(): print("Angle: {} in degrees".format(angle)) testdata = create_one_dataset(args, test_loader, axes, angle*(np.pi/180), translations) # create dataset. group_name = 'angle_'+str(angle) # create group name. file = save_dataset(testdata, group_name, file) # save data under group. # If testing for noise levels. elif args.case == 'various_noises': angle = 20 # max angular misalignment. for noise in noise_range(): print("Noise Level: {}".format(noise)) testdata = create_one_dataset(args, test_loader, axes, angle*(np.pi/180), translations, noise=noise) # create dataset. group_name = 'noise_'+str(noise) # create group name. file = save_dataset(testdata, group_name, file) # save data under group. # If testing for various outliers in template. elif args.case == 'various_outliers': angle = 45 for outliers in outlier_range(): print("Size of outliers: {}".format(outliers)) testdata = create_one_dataset(args, test_loader, axes, angle*(np.pi/180), translations, outlier_size=outliers) # create dataset. group_name = 'outliers_'+str(outliers) file = save_dataset(testdata, group_name, file) file.close() def create_dataset(args, test_loader): create(args, test_loader) def options(): parser = argparse.ArgumentParser(description='Point Cloud Registration') # settings for input data parser.add_argument('--num_points', default=1024, type=int, metavar='N', help='points in point-cloud (default: 1024)') # settings for on training parser.add_argument('--device', default='cuda:0', type=str, metavar='DEVICE', help='use CUDA if available') parser.add_argument('--version', default='v0', type=str, help='Specify version of SampleNet') parser.add_argument('--name', default='testdata_various_angles.h5', type=str, help='Specify name of file for testdata') parser.add_argument('--data_size', default=1000, type=int, help='Specify size of dataset') # Settings for data. parser.add_argument('--case', default='various_rotations', type=str, help='Choose which dataset to create', choices=['various_rotations', 'various_noises', 'various_outliers']) parser.add_argument('--transform_type', default='twist_vector', type=str, help='Choose which type of transform to be used.', choices=['twist_vector', 'axis_angle']) # Useful for generalization experiments. parser.add_argument('--unseen', default=False, type=bool, help='False: Use all 40 categories and True: Split data into first and last 20 categories.') parser.add_argument('--train_data', default=False, type=bool, help='True for first 20 categories and False for last 20 categories') args = parser.parse_args() return args def main(): args = options() torch.backends.cudnn.deterministic = True trainset = RegistrationData(ModelNet40Data(train=True, num_points=args.num_points, unseen=args.unseen, use_normals=False)) testset = RegistrationData(ModelNet40Data(train=False, num_points=args.num_points, unseen=args.unseen, use_normals=False)) if args.unseen: if args.train_data: test_loader = trainset else: test_loader = testset else: test_loader = testset # Check for size of dataset. assert args.data_size <= len(test_loader), "Given invalid data_size (> size of test_loader)" if not torch.cuda.is_available(): args.device = 'cpu' args.device = torch.device(args.device) create_dataset(args, test_loader) if __name__ == '__main__': main()
{ "alphanum_fraction": 0.7051669545, "author": null, "avg_line_length": 37.7608695652, "converted": null, "ext": "py", "file": null, "hexsha": "a1f9e3b8dd195f871ab7cbc84fa069c4c6ed6709", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-05-28T20:20:40.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-26T05:01:21.000Z", "max_forks_repo_head_hexsha": "f70324cfecd9c91dce532284efec02636c04af65", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "kidpaul94/masknet", "max_forks_repo_path": "evaluation/create_statistical_data.py", "max_issues_count": 2, "max_issues_repo_head_hexsha": "f70324cfecd9c91dce532284efec02636c04af65", "max_issues_repo_issues_event_max_datetime": "2022-02-16T21:44:22.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-17T12:52:16.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "kidpaul94/masknet", "max_issues_repo_path": "evaluation/create_statistical_data.py", "max_line_length": 135, "max_stars_count": 26, "max_stars_repo_head_hexsha": "f70324cfecd9c91dce532284efec02636c04af65", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "kidpaul94/masknet", "max_stars_repo_path": "evaluation/create_statistical_data.py", "max_stars_repo_stars_event_max_datetime": "2021-12-20T07:03:09.000Z", "max_stars_repo_stars_event_min_datetime": "2020-10-21T00:40:54.000Z", "num_tokens": 3874, "path": null, "reason": "import numpy,from scipy", "repo": null, "save_path": null, "sha": null, "size": 13896 }
#!/usr/bin/env python ''' File name: fetch_and_transform_data.py Author: Varun Jampani ''' # --------------------------------------------------------------------------- # Video Propagation Networks #---------------------------------------------------------------------------- # Copyright 2017 Max Planck Society # Distributed under the BSD-3 Software license [see LICENSE.txt for details] # --------------------------------------------------------------------------- import sys import numpy as np import scipy.io as sio from PIL import Image import cv2 from davis_data import * from init_caffe import * # Load all the features, gt and spixels import time print('Loading Data...') t1 = time.time() all_seqs_features = np.load(SPIXELFEATURE_FOLDER + 'all_seqs_features.npy').item() all_seqs_gt = np.load(SPIXEL_GT_FOLDER + 'all_seqs_spixel_gt.npy').item() all_seqs_spixels = np.load(SUPERPIXEL_FOLDER + 'all_seqs_spixels.npy').item() print(time.time() - t1) print('Finished Loading Data.') max_spixels = MAX_SPIXELS def transform_and_get_image(im_file, out_size): im = caffe.io.load_image(im_file) out_height = out_size[0] out_width = out_size[1] height = im.shape[0] width = im.shape[1] mean_color_values = np.load('../lib/caffe/python/caffe/imagenet/\ ilsvrc_2012_mean.npy').mean(1).mean(1) transformer = caffe.io.Transformer({'img': (1, 3, out_size[0], out_size[1])}) transformer.set_mean('img', mean_color_values) transformer.set_transpose('img', (2, 0, 1)) transformer.set_channel_swap('img', (2, 1, 0)) transformer.set_raw_scale('img', 255.0) pad_height = out_height - height pad_width = out_width - width im = np.lib.pad(im, ((0, pad_height), (0, pad_width), (0, 0)), 'constant', constant_values=-5) for i in range(0, 3): temp = im[:, :, i] temp[temp == -5] = mean_color_values[2-i] / 255.0 im[:, :, i] = temp im = np.asarray(transformer.preprocess('img', im)) im = np.expand_dims(im, axis=0) return [im, im[:,:,:480,:854]] def transform_and_get_unary(seqname): # First frame ground-truth gt = all_seqs_gt[seqname][0, :] unary = np.zeros((1, 2, 1, gt.shape[0])) unary[0,0,0,:][gt==0] = 1 unary[0,1,0,:][gt==1] = 1 return unary # For YUVXYT features def transform_and_get_features(seqname, frame_idx, feature_scales, num_frames=None): in_features = np.zeros((6, 1, max_spixels)) in_features[:, :, :] = all_seqs_features[seqname][:, [frame_idx], :] if num_frames is None: num_out_frames = all_seqs_features[seqname].shape[1] out_features = np.zeros((6, num_out_frames, max_spixels)) out_features[:, :, :] = all_seqs_features[seqname] else: num_out_frames = num_frames out_features = np.zeros((6, num_frames, max_spixels)) out_features[:, :, :] = all_seqs_features[seqname][:, frame_idx: frame_idx + num_frames, :] for t in range(6): in_features[t, :, :] = in_features[t, :, :] * feature_scales[t] out_features[t, :, :] = out_features[t, :, :] * feature_scales[t] in_features = in_features[None,:,:,:] out_features = out_features[None,:,:,:] return [in_features, out_features, num_out_frames] def transform_and_get_spixels(seqname, frame_idx, num_frames): num_out_frames = num_frames if num_frames is None: num_out_frames = all_seqs_spixels[seqname].shape[0] spixels = np.zeros((num_out_frames, 480, 854)) spixels = all_seqs_spixels[seqname][:, :, :] else: spixels = np.zeros((num_frames, 480, 854)) spixels = all_seqs_spixels[seqname][frame_idx: frame_idx + num_frames, :, :] spixels = spixels[None, :, :, :] return spixels def fetch_and_transform_data(seqname, frame_idx, out_types, feature_scales, fix_num_frames=None): inputs = {} num_out_frames = 0 for in_name in out_types: if in_name == 'unary': inputs['unary'] = transform_and_get_unary(seqname) if in_name == 'spixel_indices': inputs['spixel_indices'] = transform_and_get_spixels(seqname, frame_idx, fix_num_frames) if in_name == 'in_features': [inputs['in_features'], inputs['out_features'], num_out_frames] = \ transform_and_get_features(seqname, frame_idx, feature_scales, fix_num_frames) return [inputs, num_out_frames]
{ "alphanum_fraction": 0.5992655001, "author": null, "avg_line_length": 34.5447761194, "converted": null, "ext": "py", "file": null, "hexsha": "6056fe30171156e3eeb8c97de594e7bac6ea7a6b", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 29, "max_forks_repo_forks_event_max_datetime": "2020-05-19T04:03:34.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-26T00:45:23.000Z", "max_forks_repo_head_hexsha": "4f4a39842bd9112932abe40bad746c174a242bf6", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "varunjampani/video_prop_networks", "max_forks_repo_path": "seg_propagation/fetch_and_transform_data.py", "max_issues_count": 7, "max_issues_repo_head_hexsha": "4f4a39842bd9112932abe40bad746c174a242bf6", "max_issues_repo_issues_event_max_datetime": "2020-05-04T14:29:56.000Z", "max_issues_repo_issues_event_min_datetime": "2017-04-29T05:16:53.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "varunjampani/video_prop_networks", "max_issues_repo_path": "seg_propagation/fetch_and_transform_data.py", "max_line_length": 99, "max_stars_count": 99, "max_stars_repo_head_hexsha": "4f4a39842bd9112932abe40bad746c174a242bf6", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "varunjampani/video_prop_networks", "max_stars_repo_path": "seg_propagation/fetch_and_transform_data.py", "max_stars_repo_stars_event_max_datetime": "2021-11-08T10:41:15.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-19T21:08:48.000Z", "num_tokens": 1175, "path": null, "reason": "import numpy,import scipy", "repo": null, "save_path": null, "sha": null, "size": 4629 }
SUBROUTINE W3FI82 (IFLD,FVAL1,FDIFF1,NPTS) C$$$ SUBPROGRAM DOCUMENTATION BLOCK C . . . . C SUBPROGRAM: W3FI82 CONVERT TO SECOND DIFF ARRAY C PRGMMR: CAVANAUGH ORG: NMC421 DATE:93-08-18 C C ABSTRACT: ACCEPT AN INPUT ARRAY, CONVERT TO ARRAY OF SECOND C DIFFERENCES. RETURN THE ORIGINAL FIRST VALUE AND THE FIRST C FIRST-DIFFERENCE AS SEPARATE VALUES. C C PROGRAM HISTORY LOG: C 93-07-14 CAVANAUGH C 93-08-18 R.E.JONES RECOMPILE FOR SiliconGraphics C 95-10-31 IREDELL REMOVED SAVES AND PRINTS C C USAGE: CALL W3FI82 (IFLD,FVAL1,FDIFF1,NPTS) C INPUT ARGUMENT LIST: C IFLD - INTEGER INPUT ARRAY C NPTS - NUMBER OF POINTS IN ARRAY C C OUTPUT ARGUMENT LIST: C IFLD - SECOND DIFFERENCED FIELD C FVAL1 - FLOATING POINT ORIGINAL FIRST VALUE C FDIFF1 - " " FIRST FIRST-DIFFERENCE C C REMARKS: SUBPROGRAM CAN BE CALLED FROM A MULTIPROCESSING ENVIRONMENT. C C ATTRIBUTES: C LANGUAGE: SiliconGraphics 3.5 FORTRAN 77 C MACHINE: SiliconGraphics model 25, 35, INDIGO C C$$$ C REAL FVAL1,FDIFF1 C INTEGER IFLD(*),NPTS C C --------------------------------------------- DO 4000 I = NPTS, 2, -1 IFLD(I) = IFLD(I) - IFLD(I-1) 4000 CONTINUE DO 5000 I = NPTS, 3, -1 IFLD(I) = IFLD(I) - IFLD(I-1) 5000 CONTINUE C PRINT *,'IFLD(1) =',IFLD(1),' IFLD(2) =',IFLD(2) C C SPECIAL FOR GRIB C FLOAT OUTPUT OF FIRST POINTS TO ANTICIPATE C GRIB FLOATING POINT OUTPUT C FVAL1 = IFLD(1) FDIFF1 = IFLD(2) C C SET FIRST TWO POINTS TO SECOND DIFF VALUE FOR BETTER PACKING C IFLD(1) = IFLD(3) IFLD(2) = IFLD(3) C ----------------------------------------------------------- RETURN END
{ "alphanum_fraction": 0.5507470376, "author": null, "avg_line_length": 31.8196721311, "converted": null, "ext": "f", "file": null, "hexsha": "838a426f2be3d61f994d547a440c90caaf5f8b46", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2021-09-07T09:30:17.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-21T22:39:53.000Z", "max_forks_repo_head_hexsha": "69f5da12997d6685cb0640132c5ef398ba12c341", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "WRF-CMake/WPS", "max_forks_repo_path": "ungrib/src/ngl/w3/w3fi82.f", "max_issues_count": 6, "max_issues_repo_head_hexsha": "8bddbdbb612a0e019ae110df481461d5d904053a", "max_issues_repo_issues_event_max_datetime": "2020-04-23T15:13:01.000Z", "max_issues_repo_issues_event_min_datetime": "2019-07-07T20:49:18.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "martinremy/wps", "max_issues_repo_path": "ungrib/src/ngl/w3/w3fi82.f", "max_line_length": 71, "max_stars_count": 38, "max_stars_repo_head_hexsha": "8bddbdbb612a0e019ae110df481461d5d904053a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "martinremy/wps", "max_stars_repo_path": "ungrib/src/ngl/w3/w3fi82.f", "max_stars_repo_stars_event_max_datetime": "2022-02-13T23:09:46.000Z", "max_stars_repo_stars_event_min_datetime": "2020-11-30T21:49:56.000Z", "num_tokens": 638, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 1941 }
[STATEMENT] lemma hRe_add: "\<And>x y. hRe (x + y) = hRe x + hRe y" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<And>x y. hRe (x + y) = hRe x + hRe y [PROOF STEP] by transfer simp
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": null, "hexsha": null, "include": null, "lang": null, "length": 1, "llama_tokens": 90, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": null }
[STATEMENT] lemma pvar_trans_eval: assumes "a \<in> carrier R" assumes "b \<in> carrier (R\<^bsup>n\<^esup>)" assumes "i < n" shows "eval_at_point R b (pvar_trans n i a) = (b!i) \<ominus> a" [PROOF STATE] proof (prove) goal (1 subgoal): 1. eval_at_point R b (pvar_trans n i a) = b ! i \<ominus> a [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. eval_at_point R b (pvar_trans n i a) = b ! i \<ominus> a [PROOF STEP] have "eval_at_point R b (pvar_trans n i a) = (eval_at_point R b (pvar R i)) \<oplus> (eval_at_point R b (\<ominus>\<^bsub>R[\<X>\<^bsub>n\<^esub>]\<^esub> (coord_const a)))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. eval_at_point R b (pvar_trans n i a) = eval_at_point R b (pvar R i) \<oplus> eval_at_point R b (\<ominus>\<^bsub>R [\<X>\<^bsub>n\<^esub>]\<^esub> R.indexed_const a) [PROOF STEP] unfolding pvar_trans_def a_minus_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. eval_at_point R b (pvar R i \<oplus>\<^bsub>R [\<X>\<^bsub>n\<^esub>]\<^esub> \<ominus>\<^bsub>R [\<X>\<^bsub>n\<^esub>]\<^esub> R.indexed_const a) = eval_at_point R b (pvar R i) \<oplus> eval_at_point R b (\<ominus>\<^bsub>R [\<X>\<^bsub>n\<^esub>]\<^esub> R.indexed_const a) [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: a \<in> carrier R b \<in> carrier (R\<^bsup>n\<^esup>) i < n goal (1 subgoal): 1. eval_at_point R b (pvar R i \<oplus>\<^bsub>R [\<X>\<^bsub>n\<^esub>]\<^esub> \<ominus>\<^bsub>R [\<X>\<^bsub>n\<^esub>]\<^esub> R.indexed_const a) = eval_at_point R b (pvar R i) \<oplus> eval_at_point R b (\<ominus>\<^bsub>R [\<X>\<^bsub>n\<^esub>]\<^esub> R.indexed_const a) [PROOF STEP] by (metis MP.add.inv_closed coord_ring_def eval_at_point_add R.indexed_const_closed local.pvar_closed) [PROOF STATE] proof (state) this: eval_at_point R b (pvar_trans n i a) = eval_at_point R b (pvar R i) \<oplus> eval_at_point R b (\<ominus>\<^bsub>R [\<X>\<^bsub>n\<^esub>]\<^esub> R.indexed_const a) goal (1 subgoal): 1. eval_at_point R b (pvar_trans n i a) = b ! i \<ominus> a [PROOF STEP] then [PROOF STATE] proof (chain) picking this: eval_at_point R b (pvar_trans n i a) = eval_at_point R b (pvar R i) \<oplus> eval_at_point R b (\<ominus>\<^bsub>R [\<X>\<^bsub>n\<^esub>]\<^esub> R.indexed_const a) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: eval_at_point R b (pvar_trans n i a) = eval_at_point R b (pvar R i) \<oplus> eval_at_point R b (\<ominus>\<^bsub>R [\<X>\<^bsub>n\<^esub>]\<^esub> R.indexed_const a) goal (1 subgoal): 1. eval_at_point R b (pvar_trans n i a) = b ! i \<ominus> a [PROOF STEP] by (metis a_minus_def assms(1) assms(2) assms(3) coord_ring_def eval_at_point_a_inv eval_at_point_const eval_pvar R.indexed_const_closed) [PROOF STATE] proof (state) this: eval_at_point R b (pvar_trans n i a) = b ! i \<ominus> a goal: No subgoals! [PROOF STEP] qed
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "Padic_Field_Ring_Powers", "hexsha": null, "include": null, "lang": null, "length": 9, "llama_tokens": 1294, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": null }
# -*- coding: utf-8 -*- """This example script demonstrates plotting echograms using fake data.""" import numpy as np from matplotlib.pyplot import figure, show from echolab2.processing import processed_data, line from echolab2.plotting.matplotlib import echogram test_data_pings = 100 test_data_samples = 1000 sample_thickness_m = 0.5 ping_interval_ms = 1000.0 fake_Sv = processed_data.ProcessedData('Fake Data', 120000, 'Sv') fake_Sv.n_samples = test_data_samples fake_Sv.n_pings = test_data_pings # Create some fake data arrays. ranges = np.arange(test_data_samples) * sample_thickness_m times = (np.arange(test_data_pings) * ping_interval_ms) + \ np.datetime64('2018-03-21T03:30:30', 'ms').astype('float') data = np.zeros((test_data_pings, test_data_samples), dtype='float32') data[:, 1::2] = 10.0 # Add the fake data to the ProcessedData object. fake_Sv.add_attribute('range', ranges) fake_Sv.add_attribute('ping_time', times.astype('datetime64[ms]')) fake_Sv.add_attribute('data', data) # Create lines. a_line = line.Line(ping_time=np.array([times[0], times[-1]]), data=np.array([ 0, 0])) n_lines = int((ranges[-1] / (sample_thickness_m * 10)) + 0.5) # Create a matplotlib figure to plot our echograms on. fig_1 = figure() eg = echogram.Echogram(fig_1, fake_Sv, threshold=[0, 20]) eg.axes.set_title("Echogram Plot Test") for i in range(n_lines): eg.plot_line(a_line, linewidth=1.0) a_line = a_line + (sample_thickness_m * 10) # Display figure. show()
{ "alphanum_fraction": 0.7385752688, "author": null, "avg_line_length": 31, "converted": null, "ext": "py", "file": null, "hexsha": "0b95fbf51679162d3c25ef5cc9d97038a962f101", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 22, "max_forks_repo_forks_event_max_datetime": "2022-02-02T19:20:50.000Z", "max_forks_repo_forks_event_min_datetime": "2019-01-31T21:07:27.000Z", "max_forks_repo_head_hexsha": "d8454984c17c8454cbaaf296232777afc48ca0cc", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "nlauffenburger/pyEcholab", "max_forks_repo_path": "examples/python code/echogram_plotting_test.py", "max_issues_count": 14, "max_issues_repo_head_hexsha": "d8454984c17c8454cbaaf296232777afc48ca0cc", "max_issues_repo_issues_event_max_datetime": "2021-11-04T15:16:36.000Z", "max_issues_repo_issues_event_min_datetime": "2019-08-30T15:27:54.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "nlauffenburger/pyEcholab", "max_issues_repo_path": "examples/python code/echogram_plotting_test.py", "max_line_length": 77, "max_stars_count": 20, "max_stars_repo_head_hexsha": "d8454984c17c8454cbaaf296232777afc48ca0cc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "nlauffenburger/pyEcholab", "max_stars_repo_path": "examples/python code/echogram_plotting_test.py", "max_stars_repo_stars_event_max_datetime": "2022-03-17T01:11:20.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-06T23:16:28.000Z", "num_tokens": 432, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1488 }
#include <boost/spirit/home/classic/actor/swap_actor.hpp>
{ "alphanum_fraction": 0.8103448276, "author": null, "avg_line_length": 29, "converted": null, "ext": "hpp", "file": null, "hexsha": "73179f5b5225af3bd233bd7fc5a393d61a85ee41", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 4, "max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z", "max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z", "max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "miathedev/BoostForArduino", "max_forks_repo_path": "src/boost_spirit_home_classic_actor_swap_actor.hpp", "max_issues_count": 2, "max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "miathedev/BoostForArduino", "max_issues_repo_path": "src/boost_spirit_home_classic_actor_swap_actor.hpp", "max_line_length": 57, "max_stars_count": 10, "max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "miathedev/BoostForArduino", "max_stars_repo_path": "src/boost_spirit_home_classic_actor_swap_actor.hpp", "max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z", "max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z", "num_tokens": 15, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 58 }
using ..SymEngine using ..SymEngine: @vars, Basic export @vars, Basic, subs include("register.jl") include("instruct.jl") include("blocks.jl") include("patch.jl")
{ "alphanum_fraction": 0.7256097561, "author": null, "avg_line_length": 18.2222222222, "converted": null, "ext": "jl", "file": null, "hexsha": "14c46ae0167f7351ee5d81bd4d1907d504e20e88", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2021-12-16T04:32:45.000Z", "max_forks_repo_forks_event_min_datetime": "2020-02-08T11:57:56.000Z", "max_forks_repo_head_hexsha": "f1975d50627ca271ac524866dc64ca96ece0a05a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "wildart/Yao.jl", "max_forks_repo_path": "lib/YaoSym/src/symengine/backend.jl", "max_issues_count": 35, "max_issues_repo_head_hexsha": "f1975d50627ca271ac524866dc64ca96ece0a05a", "max_issues_repo_issues_event_max_datetime": "2021-12-02T18:48:56.000Z", "max_issues_repo_issues_event_min_datetime": "2019-09-11T05:14:55.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "wildart/Yao.jl", "max_issues_repo_path": "lib/YaoSym/src/symengine/backend.jl", "max_line_length": 31, "max_stars_count": 8, "max_stars_repo_head_hexsha": "f1975d50627ca271ac524866dc64ca96ece0a05a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "wildart/Yao.jl", "max_stars_repo_path": "lib/YaoSym/src/symengine/backend.jl", "max_stars_repo_stars_event_max_datetime": "2021-12-16T04:30:06.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-11T04:51:22.000Z", "num_tokens": 48, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 164 }
function out = sampleInSeconds(stimList,ISI,varargin) % out = sampleInSeconds(stimList,ISI,varargin) % input: stimList, output: stimlist sampled in .1 seconds % OR sampled at your specified frequency scale = ceil(ISI*10); if nargin > 2 scale = round(ISI/varargin{1}); end numstim = size(stimList,1); out = zeros(numstim*scale,1); for i = 0:numstim-1 out(i*scale+1,1) = stimList(i+1,1); end return
{ "alphanum_fraction": null, "author": "canlab", "avg_line_length": null, "converted": null, "ext": null, "file": null, "hexsha": null, "include": null, "lang": null, "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": null, "max_forks_repo_licenses": null, "max_forks_repo_name": null, "max_forks_repo_path": null, "max_issues_count": null, "max_issues_repo_head_hexsha": null, "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": null, "max_issues_repo_name": null, "max_issues_repo_path": null, "max_line_length": null, "max_stars_count": null, "max_stars_repo_head_hexsha": null, "max_stars_repo_licenses": null, "max_stars_repo_name": null, "max_stars_repo_path": null, "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": null, "path": "github-repos/MATLAB/canlab-CanlabCore/CanlabCore-af242e120f0480c4feaeea90471c015a14f1f60e/CanlabCore/OptimizeDesign11/core_functions/sampleInSeconds.m", "reason": null, "repo": "CanlabCore", "save_path": "github-repos/MATLAB/canlab-CanlabCore", "sha": "af242e120f0480c4feaeea90471c015a14f1f60e", "size": null }
Describe Users/kmitchell here. Hi. Im nice, and I dont really know how to use this thing. YAY! 20080715 13:44:26 nbsp Welcome to the Wiki Howdy, Mr. or Ms. Mitchell, and Welcome to the Wiki! My names Evan, pleased to meet you. Everybody starts off not knowing how to use this thing, but being nice gets you plenty of people willing to help you out! Just ask if you have any questions, and once again, welcome to the wiki. Users/JabberWokky Evan JabberWokky Edwards 20090206 12:35:02 nbsp Hi, Im from Saratoga Apartments. You left a comment on our board and I wanted to clarify something. I dont know what you had been told in the past, but you are now able to have 2 cats per apartment with a deposit of $400 per animal. Im sorry if you were given incorrect information in the past. If you have any other questions please come into the office. Users/SaraRoscoe
{ "alphanum_fraction": 0.7659090909, "author": null, "avg_line_length": 97.7777777778, "converted": null, "ext": "f", "file": null, "hexsha": "3f99800698f105bcacdea7dd9e30a27244be6a39", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": null, "max_forks_repo_forks_event_max_datetime": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "voflo/Search", "max_forks_repo_path": "lab/davisWiki/kmitchell.f", "max_issues_count": null, "max_issues_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "voflo/Search", "max_issues_repo_path": "lab/davisWiki/kmitchell.f", "max_line_length": 402, "max_stars_count": null, "max_stars_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "voflo/Search", "max_stars_repo_path": "lab/davisWiki/kmitchell.f", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 233, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 880 }