text
stringlengths
0
27.1M
meta
dict
import abc import math import os from concurrent.futures.process import ProcessPoolExecutor from typing import Tuple, Union import numpy as np import tensorflow as tf import tensorflow_datasets as tfds from emp_uncertainty.case_studies.case_study import ClassificationCaseStudy IMAGENET_CORRUPTION_TYPES = [ 'gaussian_noise', 'shot_noise', 'impulse_noise', 'defocus_blur', 'glass_blur', # 'motion_blur', # TODO Requires ImageMagick 'zoom_blur', # 'snow', # TODO Requires ImageMagick 'frost', 'fog', 'brightness', 'contrast', 'elastic_transform', 'pixelate', 'jpeg_compression', 'gaussian_blur', 'saturate', # 'spatter', # TODO Requires cv2.cv2 'speckle_noise' ] class ImagenetPretrainedCaseStudy(ClassificationCaseStudy, abc.ABC): y_test = None def __init__(self) -> None: super().__init__() @classmethod def _get_train_and_val_data(cls) -> Tuple[tf.data.Dataset, tf.data.Dataset]: raise RuntimeError("For pretrained Imagenet Studies, the training data should never be requested.") @classmethod def get_test_data(cls) -> Tuple[Union[np.ndarray, tf.data.Dataset], np.ndarray]: # Cite # Olga Russakovsky*, Jia Deng*, Hao Su, Jonathan Krause, Sanjeev Satheesh, # Sean Ma, Zhiheng Huang, Andrej Karpathy, Aditya Khosla, Michael Bernstein, # Alexander C. Berg and Li Fei-Fei. (* = equal contribution) # ImageNet Large Scale Visual Recognition Challenge. arXiv:1409.0575, 2014. # Test set not publicly available. We use val set. 2 % of 50'000 images => 1000 images imagenet_val = tfds.load('imagenet2012', split='validation[:2%]', shuffle_files=False, as_supervised=True) x_test_resized, y_test = cls._preprocess_tfds(imagenet_val) return x_test_resized, y_test @classmethod def _preprocess_tfds(cls, imagenet_val): x_test = imagenet_val.map(lambda x, _: x).prefetch(tf.data.experimental.AUTOTUNE) x_test_resized = x_test.map(lambda x: tf.image.resize(x, [224, 224], method='bicubic'), num_parallel_calls=tf.data.experimental.AUTOTUNE) x_test_resized = x_test_resized.prefetch(tf.data.experimental.AUTOTUNE) y_test_iter = imagenet_val.map(lambda _, y: y).as_numpy_iterator() y_test = np.fromiter(y_test_iter, dtype=int) return x_test_resized, y_test @classmethod def get_val_data(cls) -> Tuple[Union[np.ndarray, tf.data.Dataset], np.ndarray]: imagenet_val = tfds.load('imagenet2012', split='validation[98%:]', shuffle_files=False, as_supervised=True) x_test_resized, y_test = cls._preprocess_tfds(imagenet_val) cls.y_test = y_test return x_test_resized, y_test @classmethod def get_val_labels(cls) -> np.ndarray: if cls.y_test is None: cls.get_val_data() return cls.y_test @classmethod def get_outlier_data(cls, severity: str) -> Tuple[Union[np.ndarray, tf.data.Dataset], np.ndarray]: img_per_corr = math.floor(1000 / len(IMAGENET_CORRUPTION_TYPES)) all_images = None for i, corr_type in enumerate(IMAGENET_CORRUPTION_TYPES): ds = tfds.load(f'imagenet2012_corrupted/{corr_type}_{severity}', split=tfds.core.ReadInstruction('validation', from_=i * img_per_corr, to=(i + 1) * img_per_corr, unit='abs'), as_supervised=True) if all_images is None: all_images = ds else: all_images = all_images.concatenate(ds) x, y = cls._preprocess_tfds(all_images) return x, y def load_imagenet_model(self): self.ensemble_model = None self.stochastic_model = self._create_stochastic_model() @classmethod def _create_ensemble_model(cls) -> None: return None def run_imgnet_inference(self): val_set = self.get_val_data() self.run_nn_inference(epoch=None, ood_severities=["1", "2", "3", "4", "5"], val_dataset=val_set) def download_and_prepare(c, s): tfds.builder(f"imagenet2012_corrupted/{c}_{s}").download_and_prepare() if __name__ == '__main__': # os.environ["CUDA_VISIBLE_DEVICES"] = "-1" futures = [] with ProcessPoolExecutor(max_workers=20) as executor: for severity in ["1", "2", "3", "4", "5"]: for c_type in IMAGENET_CORRUPTION_TYPES: future = executor.submit(download_and_prepare, c_type, severity) futures.append(future) [future.result() for future in futures] print("Done")
{ "alphanum_fraction": 0.640381822, "author": null, "avg_line_length": 37.3565891473, "converted": null, "ext": "py", "file": null, "hexsha": "90770a05dc81538813119bc1988d76d398c72920", "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": "6841c90556a3558185573e15336b057528d49b79", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "testingautomated-usi/repli-icst2021-uncertainty", "max_forks_repo_path": "emp_uncertainty/case_studies/pre_trained/imagenet_pretrained_cs.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "6841c90556a3558185573e15336b057528d49b79", "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": "testingautomated-usi/repli-icst2021-uncertainty", "max_issues_repo_path": "emp_uncertainty/case_studies/pre_trained/imagenet_pretrained_cs.py", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "6841c90556a3558185573e15336b057528d49b79", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "testingautomated-usi/repli-icst2021-uncertainty", "max_stars_repo_path": "emp_uncertainty/case_studies/pre_trained/imagenet_pretrained_cs.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1188, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 4819 }
import unittest import numpy as np from ocgis.util.helpers import iter_array class Test(unittest.TestCase): def test_iter_array(self): values = np.random.rand(2,2,4,4) mask = np.random.random_integers(0,1,values.shape) values = np.ma.array(values,mask=mask) for idx in iter_array(values): self.assertFalse(values.mask[idx]) self.assertEqual(len(list(iter_array(values,use_mask=True))),len(values.compressed())) self.assertEqual(len(list(iter_array(values,use_mask=False))),len(values.data.flatten())) if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
{ "alphanum_fraction": 0.6812030075, "author": null, "avg_line_length": 33.25, "converted": null, "ext": "py", "file": null, "hexsha": "fb78edc81525b2d36d422484eeb47a84895f74e4", "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": "989573258e6fcbeeb8b92d66bf5f6a43a34c2662", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "doutriaux1/ocgis", "max_forks_repo_path": "src/ocgis/test/test_util.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "989573258e6fcbeeb8b92d66bf5f6a43a34c2662", "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": "doutriaux1/ocgis", "max_issues_repo_path": "src/ocgis/test/test_util.py", "max_line_length": 97, "max_stars_count": 1, "max_stars_repo_head_hexsha": "989573258e6fcbeeb8b92d66bf5f6a43a34c2662", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "doutriaux1/ocgis", "max_stars_repo_path": "src/ocgis/test/test_util.py", "max_stars_repo_stars_event_max_datetime": "2016-09-08T14:35:44.000Z", "max_stars_repo_stars_event_min_datetime": "2016-09-08T14:35:44.000Z", "num_tokens": 150, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 665 }
program test_below use simsphere_mod, only: nlvls, frveg, otemp, tt, tg, heat, rnet, kappa, & xfun, del, dzeta, ptime, wmax, w2g, wgg, eq use mod_testing, only: assert, initialize_tests, report_tests implicit none logical, dimension(:), allocatable :: tests logical :: test_failed integer :: n, ntests real :: arg1, arg2, arg3 !time, BareRadioTemp, BareEvapFlux real :: waterwin real :: belowte(9) ! Expected values real, parameter :: w2g_wmax_exp = 99.99 real, parameter :: wgg_wmax_exp = 99.99 real, parameter, dimension(9) :: tt_exp = (/222.837555,1.0,1.0,1.0,1.0, & 1.0,1.0,1.0,1.0/) real, parameter, dimension(9) :: tt_time0_exp = 222.837555 real, parameter :: tt_frveg0_exp = 265.0 real, parameter :: tt_frveg_exp = 222.837555 real, parameter :: tt_frveg1_exp = 1.0 real, parameter :: tt_low_heat_exp = 265.0 n = 1 ntests = 7 call initialize_tests(tests,ntests) ! wmax > 1 ! 0 < frveg < 1 call below_init arg1 = 1.5 wmax = 2.0 call below(arg1,arg2,arg3,waterwin,belowte) tests(n) = assert(eq(w2g,w2g_wmax_exp), 'w2g high wmax') n = n + 1 tests(n) = assert(eq(wgg,wgg_wmax_exp), 'wgg high wmax') n = n + 1 tests(n) = assert(eq(tt,tt_exp), 'tt') n = n + 1 tests(n) = assert(eq(tt(1),tt_frveg_exp), 'tt(1) 0 < frveg < 1') n = n + 1 ! time == 0.0 call below_init arg1 = 0.0 call below(arg1,arg2,arg3,waterwin,belowte) tests(n) = assert(eq(tt,tt_exp), 'tt time == 0') n = n + 1 ! Frveg == 0.0 call below_init frveg = 0.0 call below(arg1,arg2,arg3,waterwin,belowte) tests(n) = assert(eq(tt(1),tt_frveg0_exp), 'tt(1) frveg == 0') n = n + 1 ! frveg == 1 call below_init frveg = 1.0 call below(arg1,arg2,arg3,waterwin,belowte) tests(n) = assert(eq(tt(1),tt_frveg1_exp), 'tt(1) frveg == 1') n = n + 1 ! frveg > 1 ! Commented code in subroutine stops execution in this case. Frveg ! may not exceed 1. This should be checked and enforced when frveg is ! read into the program. ! heat < 0 call below_init heat = -1.0 call below(arg1,arg2,arg3,waterwin,belowte) tests(n) = assert(eq(tt(1),tt_low_heat_exp), 'tt(1) heat < 0') n = n + 1 test_failed = .false. call report_tests(tests,test_failed) if (test_failed) stop 1 contains subroutine below_init nlvls = 1 frveg = 0.5 otemp = 265.0 tt = 1.0 tg = 1.0 heat = 1800.0 kappa = 1.0 xfun = 1.0 del = 10.0 dzeta = 5.0 wmax = 1.0 wgg = 0.75 w2g = 0.25 ptime = 16 arg2 = 265.0 arg3 = 1800.0 waterwin = 0.0 belowte = 0.0 return end subroutine below_init end program test_below
{ "alphanum_fraction": 0.6123348018, "author": null, "avg_line_length": 25.2222222222, "converted": null, "ext": "f90", "file": null, "hexsha": "7167c5e3c1c9ac27e4bd1a664e598dea9756fdae", "include": null, "lang": "FORTRAN", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2021-12-01T01:33:53.000Z", "max_forks_repo_forks_event_min_datetime": "2018-10-06T18:43:14.000Z", "max_forks_repo_head_hexsha": "ca29c920e148110b48c162c46e56529ddcf3b8a4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tjc181/simsphere", "max_forks_repo_path": "tests/test_below.f90", "max_issues_count": 17, "max_issues_repo_head_hexsha": "ca29c920e148110b48c162c46e56529ddcf3b8a4", "max_issues_repo_issues_event_max_datetime": "2021-04-06T15:15:02.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-04T15:35:55.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "tjc181/simsphere", "max_issues_repo_path": "tests/test_below.f90", "max_line_length": 76, "max_stars_count": 7, "max_stars_repo_head_hexsha": "ca29c920e148110b48c162c46e56529ddcf3b8a4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tjc181/simsphere", "max_stars_repo_path": "tests/test_below.f90", "max_stars_repo_stars_event_max_datetime": "2022-03-18T04:19:21.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-04T05:08:50.000Z", "num_tokens": 1085, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2724 }
[STATEMENT] lemma harm_aux_ineq_1: fixes k :: real assumes "k > 1" shows "1 / k < ln (1 + 1 / (k - 1))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] have "k-1 > 0" \<open>k > 0\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. 0 < k - 1 &&& 0 < k [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: 1 < k goal (1 subgoal): 1. 0 < k - 1 &&& 0 < k [PROOF STEP] by simp+ [PROOF STATE] proof (state) this: 0 < k - 1 0 < k goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] from exp_1_bounds(2)[OF \<open>k-1 > 0\<close>] [PROOF STATE] proof (chain) picking this: exp 1 < (1 + 1 / (k - 1)) powr (k - 1 + 1) [PROOF STEP] have "exp 1 < (1 + 1 / (k - 1)) powr k" [PROOF STATE] proof (prove) using this: exp 1 < (1 + 1 / (k - 1)) powr (k - 1 + 1) goal (1 subgoal): 1. exp 1 < (1 + 1 / (k - 1)) powr k [PROOF STEP] by simp [PROOF STATE] proof (state) this: exp 1 < (1 + 1 / (k - 1)) powr k goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: exp 1 < (1 + 1 / (k - 1)) powr k [PROOF STEP] have n_z: "(1 + 1 / (k - 1)) powr k > 0" [PROOF STATE] proof (prove) using this: exp 1 < (1 + 1 / (k - 1)) powr k goal (1 subgoal): 1. 0 < (1 + 1 / (k - 1)) powr k [PROOF STEP] using assms not_exp_less_zero [PROOF STATE] proof (prove) using this: exp 1 < (1 + 1 / (k - 1)) powr k 1 < k \<not> exp ?x < 0 goal (1 subgoal): 1. 0 < (1 + 1 / (k - 1)) powr k [PROOF STEP] by auto [PROOF STATE] proof (state) this: 0 < (1 + 1 / (k - 1)) powr k goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] have "(1::real) = ln (exp(1))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 1 = ln (exp 1) [PROOF STEP] using ln_exp [PROOF STATE] proof (prove) using this: ln (exp ?x) = ?x goal (1 subgoal): 1. 1 = ln (exp 1) [PROOF STEP] by auto [PROOF STATE] proof (state) this: 1 = ln (exp 1) goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] also [PROOF STATE] proof (state) this: 1 = ln (exp 1) goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] have "\<dots> < ln ((1 + 1 / (k - 1)) powr k)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ln (exp 1) < ln ((1 + 1 / (k - 1)) powr k) [PROOF STEP] using ln_less_cancel_iff[of "exp(1)",simplified,OF \<open>(1 + 1 / (k - 1)) powr k > 0\<close>] exp_1_bounds[OF \<open>k - 1 > 0\<close>] [PROOF STATE] proof (prove) using this: (1 < ln ((1 + 1 / (k - 1)) powr k)) = (exp 1 < (1 + 1 / (k - 1)) powr k) (1 + 1 / (k - 1)) powr (k - 1) < exp 1 exp 1 < (1 + 1 / (k - 1)) powr (k - 1 + 1) goal (1 subgoal): 1. ln (exp 1) < ln ((1 + 1 / (k - 1)) powr k) [PROOF STEP] by simp [PROOF STATE] proof (state) this: ln (exp 1) < ln ((1 + 1 / (k - 1)) powr k) goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] also [PROOF STATE] proof (state) this: ln (exp 1) < ln ((1 + 1 / (k - 1)) powr k) goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] have "\<dots> = k * ln (1 + 1 / (k - 1))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ln ((1 + 1 / (k - 1)) powr k) = k * ln (1 + 1 / (k - 1)) [PROOF STEP] using ln_powr n_z [PROOF STATE] proof (prove) using this: ?x \<noteq> 0 \<Longrightarrow> ln (?x powr ?y) = ?y * ln ?x 0 < (1 + 1 / (k - 1)) powr k goal (1 subgoal): 1. ln ((1 + 1 / (k - 1)) powr k) = k * ln (1 + 1 / (k - 1)) [PROOF STEP] by simp [PROOF STATE] proof (state) this: ln ((1 + 1 / (k - 1)) powr k) = k * ln (1 + 1 / (k - 1)) goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: 1 < k * ln (1 + 1 / (k - 1)) [PROOF STEP] have "1 < k * ln (1 + 1 / (k - 1))" [PROOF STATE] proof (prove) using this: 1 < k * ln (1 + 1 / (k - 1)) goal (1 subgoal): 1. 1 < k * ln (1 + 1 / (k - 1)) [PROOF STEP] by blast [PROOF STATE] proof (state) this: 1 < k * ln (1 + 1 / (k - 1)) goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] then [PROOF STATE] proof (chain) picking this: 1 < k * ln (1 + 1 / (k - 1)) [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: 1 < k * ln (1 + 1 / (k - 1)) goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] using assms [PROOF STATE] proof (prove) using this: 1 < k * ln (1 + 1 / (k - 1)) 1 < k goal (1 subgoal): 1. 1 / k < ln (1 + 1 / (k - 1)) [PROOF STEP] by (simp add: field_simps) [PROOF STATE] proof (state) this: 1 / k < ln (1 + 1 / (k - 1)) goal: No subgoals! [PROOF STEP] qed
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "Gauss_Sums_Polya_Vinogradov", "hexsha": null, "include": null, "lang": null, "length": 30, "llama_tokens": 2468, "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 }
# Machine Learning/Data Science Precourse Work import numpy as np # ### # LAMBDA SCHOOL # ### # MIT LICENSE # ### # Free example function definition # This function passes one of the 11 tests contained inside of test.py. Write the rest, defined in README.md, here, and execute python test.py to test. Passing this precourse work will greatly increase your odds of acceptance into the program. def f(x): return x**2 def f_2(x): return x**3 def f_3(x): return x**3 + 5*x def d_f(x): return 2 * x def d_f_2(x): return 3*x**2 def d_f_3(x): return 3*x**2 + 5 def vector_sum(x,y): return np.add(x,y) def vector_sum(x,y): return np.add(x,y) def vector_less(x,y): return np.subtract(x,y) def vector_magnitude(x): return np.linalg.norm(x) def vec5(): return np.array([1,1,1,1,1]) def vec3(): return np.array([0,0,0]) def vec2_1(): return np.array([1,0]) def vec2_2(): return np.array([0,1]) def matrix_multiply(vec,matrix): return np.dot(vec,matrix)
{ "alphanum_fraction": 0.657480315, "author": null, "avg_line_length": 18.4727272727, "converted": null, "ext": "py", "file": null, "hexsha": "3866a65165804c09e3af909c03808897b62d1b5e", "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": "30adf83b922e90cd1a7e4276bfe7a8c85f66df7c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "lmm78/ML-Precourse", "max_forks_repo_path": "precourse.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "30adf83b922e90cd1a7e4276bfe7a8c85f66df7c", "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": "lmm78/ML-Precourse", "max_issues_repo_path": "precourse.py", "max_line_length": 243, "max_stars_count": null, "max_stars_repo_head_hexsha": "30adf83b922e90cd1a7e4276bfe7a8c85f66df7c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "lmm78/ML-Precourse", "max_stars_repo_path": "precourse.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 302, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1016 }
import ast import os import joblib import json import datetime import numpy as np import pandas as pd from joblib import Parallel, delayed from bgp.rl.rlkit_platform import simulate_policy, get_best_itr from bgp.rl import reward_functions BGP_DIR = '/bgp/dir' def process_filename(file, splitlast): """ Extracts variable parameters from filename scheme """ processed = {} characteristics = file.split(';')[:-1] if splitlast: characteristics += [file.split(';')[-1].split('.')[0]] processed['experiment_name'] = characteristics[0] for i in range(1, len(characteristics)): key, val = characteristics[i].split('=') try: processed[key] = ast.literal_eval(val) except: # messy processed[key] = val return processed def rlkit_load_it_up(path, itr=None, n_jobs=10, run_if_absent=False, replace_if_present=False, save_q=False, cpu_only=False, gpu_remap=None, new_eval=True, bgp_dir='/bgp/dir', eval_seed=None, n_eval_runs=None, night_only=False, meal_only=False, n_eval_start=0, n_days=10, suffix='', use_min=True): """ A helper function to load up a dataframe containing result summaries from a run """ directory = '{}/rl_res/{}'.format(bgp_dir, path) files = os.listdir(directory) files = list(filter(lambda x: '_' in x, files)) list_files = Parallel(n_jobs=n_jobs, verbose=1)(delayed(rlkit_load_and_summarize)(directory, f, itr, run_if_absent, replace_if_present, save_q, cpu_only, gpu_remap, new_eval, bgp_dir, eval_seed, n_eval_runs, night_only, meal_only, n_eval_start, n_days, suffix, use_min) for f in files) if n_eval_runs is not None: list_files_exp = [] for l in list_files: list_files_exp += l list_files = list_files_exp list_files = list(filter(lambda x: len(x) > 0, list_files)) df = pd.DataFrame.from_dict(list_files) # get variables that change over run variable_grid = {} for fl in files: processed = process_filename(file=fl, splitlast=False) for key in processed: if key not in variable_grid: variable_grid[key] = set({}) variable_grid[key].add(processed[key]) variable_grid_nontrivial = {k: v for k, v in variable_grid.items() if len(v) > 1} return df, variable_grid_nontrivial def old_variant_update(variant, bgp_dir): """ This function is used to allow loading old variant schemas after code updates. It inserts default values for new parameters """ data_dir = bgp_dir.split('/')[1] log_dir_arr = variant['log_dir'].split('/') log_dir_arr[1] = data_dir log_dir = '/'.join(log_dir_arr) variant['log_dir'] = log_dir if 'n_sim_days' not in variant: variant['n_sim_days'] = 10 if 'sim_seed_mod' not in variant: variant['sim_seed_mod'] = 1 if 'model_type' not in variant: variant['model_type'] = 'dqn' if 'include_time' not in variant: variant['include_time'] = False if 'include_meal' not in variant: variant['include_meal'] = False if 'action_dim' not in variant: variant['action_dim'] = 'old' if 'use_ground_truth' not in variant: variant['use_ground_truth'] = False if 'net_size' not in variant: variant['net_size'] = 32 if 'reset_lim' not in variant: variant['reset_lim'] = {'lower_lim': 20, 'upper_lim': 500} if 'bw_meals' not in variant: variant['bw_meals'] = False if 'norm' not in variant: variant['norm'] = False if 'time_std' not in variant: variant['time_std'] = None if 'action_repeat' not in variant: variant['action_repeat'] = 1 if 'load' not in variant: variant['load'] = True if 'use_pid_load' not in variant: variant['use_pid_load'] = False if 'hist_init' not in variant: variant['hist_init'] = False if 'use_old_patient_env' not in variant: variant['use_old_patient_env'] = True if 'action_cap' not in variant: variant['action_cap'] = 0.1 if 'action_bias' not in variant: variant['action_bias'] = 0 if 'action_scale' not in variant: variant['action_scale'] = 1 if 'meal_announce' not in variant: variant['meal_announce'] = None if 'residual_basal' not in variant: variant['residual_basal'] = False if 'residual_bolus' not in variant: variant['residual_bolus'] = False if 'residual_PID' not in variant: variant['residual_PID'] = False if 'fake_gt' not in variant: variant['fake_gt'] = False if 'fake_real' not in variant: variant['fake_real'] = False if 'suppress_carbs' not in variant: variant['suppress_carbs'] = False if 'limited_gt' not in variant: variant['limited_gt'] = False if 'termination_penalty' not in variant: variant['termination_penalty'] = None if 'warm_start' not in variant: variant['warm_start'] = None if 'weekly' not in variant: variant['weekly'] = None if 'update_seed_on_reset' not in variant: variant['update_seed_on_reset'] = False if 'num_eval_runs' not in variant: variant['num_eval_runs'] = 1 if 'deterministic_meal_size' not in variant: variant['deterministic_meal_size'] = False if 'deterministic_meal_time' not in variant: variant['deterministic_meal_time'] = False if 'deterministic_meal_occurrence' not in variant: variant['deterministic_meal_occurrence'] = False if 'basal_scaling' not in variant: variant['basal_scaling'] = 43.2 if 'deterministic_init' not in variant: variant['deterministic_init'] = False if 'harrison_benedict_sched' not in variant: variant['harrison_benedict_sched'] = False if 'unrealistic' not in variant: variant['unrealistic'] = False if 'restricted_sched' not in variant: variant['restricted_sched'] = False if 'meal_duration' not in variant: variant['meal_duration'] = 1 if 'independent_init' not in variant: variant['independent_init'] = None if 'rolling_insulin_lim' not in variant: variant['rolling_insulin_lim'] = None if 'universal' not in variant: variant['universal'] = False if 'finish_mod' not in variant: variant['finish_mod'] = None if 'reward_bias' not in variant: variant['reward_bias'] = 0 if 'finish_iter' not in variant: variant['finish_itr'] = 'best' if 'use_min' not in variant: variant['use_min'] = True if 'carb_error_std' not in variant: variant['carb_error_std'] = 0 if 'carb_miss_prob' not in variant: variant['carb_miss_prob'] = 0 return variant def rlkit_evaluate(directory, fl, itr, save_q, cpu_only, gpu_remap, new_eval, bgp_dir, submod, use_min): """ This is a helper function to perform evaluation when loading results for evaluations that failed (or when we wish to change evaluation schemes) """ print('evaluating') with open('{}/{}/variant.json'.format(directory, fl)) as f: variant = json.load(f) variant = old_variant_update(variant, bgp_dir=bgp_dir) simulate = simulate_policy(variant, itr, save_q, cpu_only=cpu_only, gpu_remap=gpu_remap, new_eval=new_eval, sim_seed_submod=submod, use_min=use_min) if save_q: simulate, q_save, adv_save = simulate if itr is None: joblib.dump((q_save, adv_save), '{}/{}/q_and_adv.pkl'.format(directory, fl)) else: joblib.dump((q_save, adv_save), '{}/{}/q_and_adv_{}.pkl'.format(directory, fl, itr)) if itr is None: joblib.dump(simulate, '{}/{}/simulate.pkl'.format(directory, fl)) else: if submod is not None: if submod == 0: # some backwards compatibility joblib.dump(simulate, '{}/simulate_best.pkl'.format(variant['log_dir'])) joblib.dump(simulate, '{}/simulate_best_{}.pkl'.format(variant['log_dir'], submod)) else: joblib.dump(simulate, '{}/{}/simulate_{}.pkl'.format(directory, fl, itr)) def get_res_dict(simulate): res = {} # mag_risk risk_arr = [] bg = simulate['BG'] for j in range(len(bg)): risk_arr.append(-1 * reward_functions.magni_reward([max(bg.values[j], 1)])) res['mean_mag_risk'] = np.mean(risk_arr) res['mean_risk'] = np.mean(simulate['Risk']) res['mean_lbgi'] = np.mean(simulate['LBGI']) res['mean_hbgi'] = np.mean(simulate['HBGI']) res['hist_risk'] = np.histogram(simulate['Risk']) res['mean_bg'] = np.mean(simulate['BG']) res['min_bg'] = np.min(simulate['BG']) res['max_bg'] = np.max(simulate['BG']) res['mean_insulin'] = np.mean(simulate['insulin']) hypo_percent = (simulate['BG'] < 70).sum() / len(simulate['BG']) hyper_percent = (simulate['BG'] > 180).sum() / len(simulate['BG']) res['hypo'] = hypo_percent res['hyper'] = hyper_percent res['event'] = hypo_percent + hyper_percent # detect collapse res['fail_index'] = np.inf if min(simulate['BG']) < 10: res['fail_index'] = np.where(simulate['BG'] < 10)[0][0] idx_bool = simulate['CHO'].rolling(window=12).max().fillna(0) > 0 ins = simulate['insulin'].sum() meal_ins = simulate[idx_bool]['insulin'].sum() res['insulin'] = ins res['meal_ins'] = meal_ins/ins return res def _rlkit_load_and_summarize(directory, fl, itr, run_if_absent, replace_if_present, save_q, cpu_only, gpu_remap, new_eval, bgp_dir, eval_seed, submod, night_only, meal_only, n_days, suffix, use_min): res = process_filename(fl, splitlast=False) with open('{}/{}/variant.json'.format(directory, fl)) as f: variant = json.load(f) variant = old_variant_update(variant, bgp_dir) if itr is None: if not os.path.exists('{}/{}/simulate.pkl'.format(directory, fl)) and run_if_absent: rlkit_evaluate(directory, fl, itr, save_q, cpu_only=cpu_only, gpu_remap=gpu_remap, new_eval=new_eval, bgp_dir=bgp_dir, submod=submod, use_min=use_min) elif replace_if_present: rlkit_evaluate(directory, fl, itr, save_q, cpu_only=cpu_only, gpu_remap=gpu_remap, new_eval=new_eval, bgp_dir=bgp_dir, submod=submod, use_min=use_min) else: if not os.path.exists('{}/{}/simulate_{}{}.pkl'.format(directory, fl, itr, suffix)) and run_if_absent: rlkit_evaluate(directory, fl, itr, save_q, cpu_only=cpu_only, gpu_remap=gpu_remap, new_eval=new_eval, bgp_dir=bgp_dir, submod=submod, use_min=use_min) elif replace_if_present: rlkit_evaluate(directory, fl, itr, save_q, cpu_only=cpu_only, gpu_remap=gpu_remap, new_eval=new_eval, bgp_dir=bgp_dir, submod=submod, use_min=use_min) try: progress = pd.read_csv('{}/{}/progress.csv'.format(directory, fl)) if itr is None: simulate = joblib.load('{}/{}/simulate.pkl'.format(directory, fl)) else: if eval_seed is not None: simulate = joblib.load('{}/{}/simulate_rerun_seed{}.pkl'.format(directory, fl, eval_seed)) else: if submod is not None: res['submod'] = submod simulate = joblib.load('{}/{}/simulate_{}_{}{}.pkl'.format(directory, fl, itr, submod, suffix)) else: simulate = joblib.load('{}/{}/simulate_{}.pkl'.format(directory, fl, itr)) if simulate is -1: return {} if itr is None: # used last itr available, should be rare res['itr'] = '-2' # TODO: could replace with last observed itr, too much trouble for now else: if 'best' in itr: if itr == 'best': best_itr = get_best_itr(variant, use_min=use_min) res['itr'] = best_itr else: # assuming form 'best<[X]' assert '<' in itr best_itr_max = int(itr.split('<')[1]) best_itr = get_best_itr(variant, max=best_itr_max, use_min=use_min) res['itr'] = best_itr else: res['itr'] = itr simulate = simulate[288:288*(n_days+1)] if night_only: idx = simulate.index idx_bool = idx.time < datetime.time(hour=6) simulate = simulate[idx_bool] if meal_only: idx_bool = simulate['CHO'].rolling(window=48).max().fillna(0) > 0 simulate = simulate[idx_bool] sim_res = get_res_dict(simulate) res.update(sim_res) pairs = [('return', 'Test Returns Mean'), ('glen', 'GLen'), ('progress_euglycemic', 'Euglycemic'), ('progress_hypo', 'Hypoglycemic'), ('progress_hyper', 'Hyperglycemic'), ] for pair in pairs: label_name, progress_name = pair if progress_name in progress: res['{}_final'.format(label_name)] = progress[progress_name].values[-1] try: res['{}_max'.format(label_name)] = progress[progress_name].max() res['{}_max_ind'.format(label_name)] = progress[progress_name].idxmax() except: raise ValueError('{}, {}'.format(fl, progress_name)) except: print(res) # raise return {} return res def rlkit_load_and_summarize(directory, fl, itr, run_if_absent, replace_if_present, save_q, cpu_only, gpu_remap, new_eval, bgp_dir, eval_seed, n_eval_runs, night_only, meal_only, n_eval_start, n_days, suffix, use_min): if n_eval_runs is None: return _rlkit_load_and_summarize(directory, fl, itr, run_if_absent, replace_if_present, save_q, cpu_only, gpu_remap, new_eval, bgp_dir, eval_seed, None, night_only, meal_only, n_days, suffix, use_min) else: res_arr = [] for i in range(n_eval_start, n_eval_start+n_eval_runs): res = _rlkit_load_and_summarize(directory, fl, itr, run_if_absent, replace_if_present, save_q, cpu_only, gpu_remap, new_eval, bgp_dir, eval_seed, i, night_only, meal_only, n_days, suffix, use_min) res_arr.append(res) return res_arr
{ "alphanum_fraction": 0.5948258837, "author": null, "avg_line_length": 44.8112094395, "converted": null, "ext": "py", "file": null, "hexsha": "82b4af5972d1ec23a724f1dc57e4839803769541", "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": "240a67ecf99b178fe0c4ced2bfd1dd50453fbdfe", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "aypan17/value_learning", "max_forks_repo_path": "bgp/evaluation/result_helpers.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "240a67ecf99b178fe0c4ced2bfd1dd50453fbdfe", "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": "aypan17/value_learning", "max_issues_repo_path": "bgp/evaluation/result_helpers.py", "max_line_length": 124, "max_stars_count": null, "max_stars_repo_head_hexsha": "240a67ecf99b178fe0c4ced2bfd1dd50453fbdfe", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "aypan17/value_learning", "max_stars_repo_path": "bgp/evaluation/result_helpers.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3768, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 15191 }
module TestDatumStorage using Mimi using Test comp_first = 2003 comp_last = 2008 @defcomp foo begin v = Variable(index = [time]) function run_timestep(p, v, d, ts) # implement "short component" via time checking if TimestepValue(comp_first) <= ts <= TimestepValue(comp_last) v.v[ts] = gettime(ts) end end end @defcomp bar begin region = Index() v = Variable(index = [time, region]) function run_timestep(p, v, d, ts) v.v[ts, :] .= gettime(ts) end end years = 2001:2010 regions = [:A, :B] nyears = length(years) nregions = length(regions) #------------------------------------------------------------------------------ # 1. Single dimension case, fixed timesteps #------------------------------------------------------------------------------ m = Model() set_dimension!(m, :time, years) add_comp!(m, foo) run(m) v = m[:foo, :v] @test length(v) == nyears # Test that the array allocated for variable v is the full length of the time dimension # Test that the missing values were filled in before/after the first/last values for (i, y) in enumerate(years) if y < comp_first || y > comp_last @test ismissing(v[i]) else @test v[i] == y end end #------------------------------------------------------------------------------ # 2. Multi-dimension case, fixed timesteps #------------------------------------------------------------------------------ m2 = Model() @defcomp baz begin region = Index() v = Variable(index = [time, region]) function run_timestep(p, v, d, ts) # implement "short component" via time checking if TimestepValue(comp_first) <= ts <= TimestepValue(comp_last) v.v[ts, :] .= gettime(ts) end end end set_dimension!(m2, :time, years) set_dimension!(m2, :region, regions) add_comp!(m2, baz) run(m2) v2 = m2[:baz, :v] @test size(v2) == (nyears, nregions) # Test that the array allocated for variable v is the full length of the time dimension # Test that the missing values were filled in before/after the first/last values for (i, y) in enumerate(years) if y < comp_first || y > comp_last [@test ismissing(v2[i, j]) for j in 1:nregions] else [@test v2[i, j]==y for j in 1:nregions] end end #------------------------------------------------------------------------------ # 3. Single dimension case, variable timesteps #------------------------------------------------------------------------------ years_variable = [2000:2004..., 2005:5:2030...] foo2_first = 2003 foo2_last = 2010 m = Model() set_dimension!(m, :time, years_variable) @defcomp foo2 begin v = Variable(index = [time]) function run_timestep(p, v, d, ts) # implement "short component" via time checking if TimestepValue(foo2_first) <= ts <= TimestepValue(foo2_last) v.v[ts] = gettime(ts) end end end add_comp!(m, foo2) run(m) v = m[:foo2, :v] @test length(v) == length(years_variable) # Test that the array allocated for variable v is the full length of the time dimension # Test that the missing values were filled in before/after the first/last values for (i, y) in enumerate(years_variable) if y < foo2_first || y > foo2_last @test ismissing(v[i]) else @test v[i] == y end end #------------------------------------------------------------------------------ # 4. Multi-dimension case, variable timesteps #------------------------------------------------------------------------------ m2 = Model() buz_first = 2003 buz_last = 2010 @defcomp buz begin region = Index() v = Variable(index = [time, region]) function run_timestep(p, v, d, ts) # implement "short component" via time checking if TimestepValue(buz_first) <= ts <= TimestepValue(buz_last) v.v[ts, :] .= gettime(ts) end end end set_dimension!(m2, :time, years_variable) set_dimension!(m2, :region, regions) add_comp!(m2, buz) run(m2) v2 = m2[:buz, :v] @test size(v2) == (length(years_variable), nregions) # Test that the array allocated for variable v is the full length of the time dimension # Test that the missing values were filled in before/after the first/last values for (i, y) in enumerate(years_variable) if y < buz_first || y > buz_last [@test ismissing(v2[i, j]) for j in 1:nregions] else [@test v2[i, j]==y for j in 1:nregions] end end end # module
{ "alphanum_fraction": 0.5570755775, "author": null, "avg_line_length": 27.524691358, "converted": null, "ext": "jl", "file": null, "hexsha": "c1eb0be0b926af20f83de143218f740462cfa9ac", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 21, "max_forks_repo_forks_event_max_datetime": "2019-02-21T16:49:53.000Z", "max_forks_repo_forks_event_min_datetime": "2016-07-12T02:15:17.000Z", "max_forks_repo_head_hexsha": "39472d51580274cbd43ab0d55ff82f749eb15201", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Mechachleopteryx/Mimi.jl", "max_forks_repo_path": "test/test_datum_storage.jl", "max_issues_count": 383, "max_issues_repo_head_hexsha": "39472d51580274cbd43ab0d55ff82f749eb15201", "max_issues_repo_issues_event_max_datetime": "2022-03-31T07:23:20.000Z", "max_issues_repo_issues_event_min_datetime": "2019-03-05T00:36:06.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "Mechachleopteryx/Mimi.jl", "max_issues_repo_path": "test/test_datum_storage.jl", "max_line_length": 140, "max_stars_count": 42, "max_stars_repo_head_hexsha": "39472d51580274cbd43ab0d55ff82f749eb15201", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Mechachleopteryx/Mimi.jl", "max_stars_repo_path": "test/test_datum_storage.jl", "max_stars_repo_stars_event_max_datetime": "2022-03-06T16:44:47.000Z", "max_stars_repo_stars_event_min_datetime": "2019-03-05T18:48:04.000Z", "num_tokens": 1147, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 4459 }
[STATEMENT] lemma points_in_long_chain: assumes "[f\<leadsto>Q|x..y..z]" shows "x\<in>Q" and "y\<in>Q" and "z\<in>Q" [PROOF STATE] proof (prove) goal (1 subgoal): 1. x \<in> Q &&& y \<in> Q &&& z \<in> Q [PROOF STEP] using points_in_chain finite_long_chain_with_def assms [PROOF STATE] proof (prove) using this: [?f\<leadsto>?Q|?x .. ?z] \<Longrightarrow> ?x \<in> ?Q \<and> ?z \<in> ?Q [?f\<leadsto>?Q|?x..?y..?z] \<equiv> [?f\<leadsto>?Q|?x .. ?z] \<and> ?x \<noteq> ?y \<and> ?y \<noteq> ?z \<and> ?y \<in> ?Q [f\<leadsto>Q|x..y..z] goal (1 subgoal): 1. x \<in> Q &&& y \<in> Q &&& z \<in> Q [PROOF STEP] by meson+
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "Schutz_Spacetime_Minkowski", "hexsha": null, "include": null, "lang": null, "length": 2, "llama_tokens": 315, "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 symfit import parameters, variables, log, Fit, Model from sympy import * import os class CaseModels(): def __init__(self, csv_medium_door, csv_medium_open, csv_low_01, csv_low_02): self.csv_medium_door = csv_medium_door self.csv_medium_open = csv_medium_open self.csv_low_01 = csv_low_01 self.csv_low_02 = csv_low_02 self.csv_path_base = os.path.dirname(os.path.abspath(__file__)) def read_case_data(self, csv_file): """csv_file needs to follow the format for columns: foodT, caseT, saT, raT, zoneT, zoneHumid""" """this function will be used a lot to read data for different cases""" csv_file_full_path = os.path.join(self.csv_path_base, csv_file) with open(csv_file_full_path, encoding='utf-8', mode='r') as f: mydata = f.readlines() mydata = np.asarray(mydata) foodT = [] caseT = [] saT = [] raT = [] zoneT = [] zoneW=[] for i in range(len(mydata)): x = mydata[i] tmp = x.split(',') if i > 2: foodT.append(float(tmp[0])) caseT.append(float(tmp[1])) saT.append(float(tmp[2])) raT.append(float(tmp[3])) zoneT.append(float(tmp[4])) zoneW.append( float(tmp[5]) ) foodT = np.asarray(foodT) caseT = np.asarray(caseT) saT = np.asarray(saT) raT = np.asarray(raT) zoneT = np.asarray(zoneT) zoneW = np.asarray(zoneW) if 'mt-door' in csv_file: from scipy.signal import savgol_filter foodT = savgol_filter(foodT, 51, 3) return (foodT, caseT, saT, raT, zoneT, zoneW) def read_case_medium_door(self): if self.csv_medium_door ==None: self.csv_medium_door= "mt-door_data.csv" (self.medium_door_foodT, self.medium_door_caseT, self.medium_door_saT, self.medium_door_raT, self.medium_door_zoneT, self.medium_door_zoneW ) = \ self.read_case_data(self.csv_medium_door) from scipy.signal import savgol_filter self.medium_door_foodT = savgol_filter(self.medium_door_foodT, 51, 3) return (self.medium_door_foodT, self.medium_door_caseT, self.medium_door_saT, self.medium_door_raT, self.medium_door_zoneT, self.medium_door_zoneW) def read_case_medium_open(self): if self.csv_medium_open==None: self.csv_medium_open = "mt-open_data.csv" (self.medium_open_foodT, self.medium_open_caseT, self.medium_open_saT, self.medium_open_raT, self.medium_open_zoneT, self.medium_open_zoneW ) = \ self.read_case_data(self.csv_medium_open) return(self.medium_open_foodT, self.medium_open_caseT, self.medium_open_saT, self.medium_open_raT, self.medium_open_zoneT, self.medium_open_zoneW) def read_case_low_01(self): if self.csv_low_01==None: self.csv_low_01 = "lt1_data.csv" (self.low_01_foodT, self.low_01_caseT, self.low_01_saT, self.low_01_raT, self.low_01_zoneT, self.low_01_zoneW ) = \ self.read_case_data(self.csv_low_01) return (self.low_01_foodT, self.low_01_caseT, self.low_01_saT, self.low_01_raT, self.low_01_zoneT, self.low_01_zoneW) def read_case_low_02(self): if self.csv_low_02==None: self.csv_low_02 = "lt2_data.csv" (self.low_02_foodT, self.low_02_caseT, self.low_02_saT, self.low_02_raT, self.low_02_zoneT, self.low_02_zoneW ) = \ self.read_case_data(self.csv_low_02) return (self.low_02_foodT, self.low_02_caseT, self.low_02_saT, self.low_02_raT, self.low_02_zoneT, self.low_02_zoneW ) def case_medium_door(self): """learn the foodT, based on sat/rat/zoneT/zoneW""" x_sat, x_rat, x_case_t, x_zone_t, food_t = variables('x_sat, x_rat, x_case_t, x_zone_t, food_t') a, b, c, d = parameters('a, b, c, d') z_component = a * x_sat + b * x_rat + c * x_case_t + d * exp(-x_zone_t*0.1) model_dict = { food_t: z_component, } self.fit_medium_door = Fit(model_dict, x_sat=self.medium_door_saT, x_rat = self.medium_door_raT, \ x_case_t= self.medium_door_caseT, x_zone_t = self.medium_door_zoneT, \ food_t = self.medium_door_foodT) self.fit_result_medium_door = self.fit_medium_door.execute() return (self.fit_medium_door, self.fit_result_medium_door) def predict_case_medium_door(self, sat, rat, case_t, zone_t): model = self.fit_medium_door.model(x_sat=sat, x_rat= rat, x_case_t=case_t, x_zone_t = zone_t, **self.fit_result_medium_door.params) print('hey foodT: ', model.food_t) return model.food_t def case_medium_open(self): """learn the foodT, based on sat/rat/zoneT/zoneW""" x_sat, x_rat, x_case_t, x_zone_t, x_zone_w, food_t = \ variables('x_sat, x_rat, x_case_t, x_zone_t, x_zone_w, food_t') a, b, c, d, e = parameters('a, b, c, d, e') z_component = a * x_sat + b * x_rat + c * x_case_t + d * exp(-x_zone_t*0.001) + e * cos(-x_zone_w*0.01) model_dict = { food_t: z_component, } self.fit_medium_open = Fit(model_dict, x_sat=self.medium_open_saT, x_rat=self.medium_open_raT, x_case_t=self.medium_open_caseT, x_zone_t=self.medium_open_zoneT, x_zone_w=self.medium_open_zoneW, food_t=self.medium_open_foodT) self.fit_result_medium_open = self.fit_medium_open.execute() return ( self.fit_medium_open, self.fit_result_medium_open) def predict_case_medium_open(self, sat, rat, case_t, zone_t, zone_w): model = self.fit_medium_open.model(x_sat=sat, x_rat=rat, x_case_t=case_t, x_zone_t=zone_t, x_zone_w= zone_w, **self.fit_result_medium_open.params) return model.food_t def case_low_01(self): """learn the foodT, based on sat/rat/zoneT/zoneW""" x_sat, x_rat, x_case_t, x_zone_t, food_t = \ variables('x_sat, x_rat, x_case_t, x_zone_t, food_t') a, b, c, d = parameters('a, b, c, d') z_component = a * x_sat + b * x_rat + c * x_case_t + d * sin(-x_zone_t*0.01) model_dict = { food_t: z_component, } self.fit_low_01 = Fit(model_dict, x_sat=self.low_01_saT, x_rat=self.low_01_raT, x_case_t=self.low_01_caseT, x_zone_t=self.low_01_zoneT, food_t=self.low_01_foodT) self.fit_result_low_01 = self.fit_low_01.execute() return (self.fit_low_01, self.fit_result_low_01) def predict_case_low_01(self,sat, rat, case_t, zone_t, zone_w): model = self.fit_low_01.model(x_sat=sat, x_rat=rat, x_case_t=case_t, x_zone_t=zone_t, **self.fit_result_low_01.params) return model.food_t def case_low_02(self): """learn the foodT, based on sat/rat/zoneT/zoneW""" x_sat, x_rat, x_case_t, x_zone_t, food_t = \ variables('x_sat, x_rat, x_case_t, x_zone_t, food_t') a, b, c, d = parameters('a, b, c, d') z_component = a * x_sat + b * x_rat + c * x_case_t + d * sin(-x_zone_t*0.01) model_dict = { food_t: z_component, } self.fit_low_02 = Fit(model_dict, x_sat=self.low_02_saT, x_rat=self.low_02_raT, x_case_t=self.low_02_caseT, x_zone_t=self.low_02_zoneT, food_t=self.low_02_foodT) self.fit_result_low_02 = self.fit_low_02.execute() return (self.fit_low_02, self.fit_result_low_02) def predict_case_low_02(self, sat, rat, case_t, zone_t, zone_w): model = self.fit_low_02.model(x_sat=sat, x_rat=rat, x_case_t=case_t, x_zone_t=zone_t, \ **self.fit_result_low_02.params) return model.food_t
{ "alphanum_fraction": 0.6290042215, "author": null, "avg_line_length": 38.7211538462, "converted": null, "ext": "py", "file": null, "hexsha": "280662eb0cf1d30090832cf9d28fce5006edc630", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2021-09-08T21:10:08.000Z", "max_forks_repo_forks_event_min_datetime": "2018-09-24T17:51:52.000Z", "max_forks_repo_head_hexsha": "5f049c12cb7f8baf00ea35208ebe86a26ff0c923", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "henze-research-group/alfalfa", "max_forks_repo_path": "tests/integration/models/refrig_case_osw/python/case_models.py", "max_issues_count": 203, "max_issues_repo_head_hexsha": "5f049c12cb7f8baf00ea35208ebe86a26ff0c923", "max_issues_repo_issues_event_max_datetime": "2022-03-31T22:26:52.000Z", "max_issues_repo_issues_event_min_datetime": "2019-03-19T20:49:58.000Z", "max_issues_repo_licenses": [ "BSD-3-Clause" ], "max_issues_repo_name": "henze-research-group/alfalfa", "max_issues_repo_path": "tests/integration/models/refrig_case_osw/python/case_models.py", "max_line_length": 111, "max_stars_count": 17, "max_stars_repo_head_hexsha": "5f049c12cb7f8baf00ea35208ebe86a26ff0c923", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "henze-research-group/alfalfa", "max_stars_repo_path": "tests/integration/models/refrig_case_osw/python/case_models.py", "max_stars_repo_stars_event_max_datetime": "2022-03-28T23:21:32.000Z", "max_stars_repo_stars_event_min_datetime": "2018-10-02T08:10:51.000Z", "num_tokens": 2200, "path": null, "reason": "import numpy,from scipy,from sympy", "repo": null, "save_path": null, "sha": null, "size": 8054 }
abstract type Command end """ Operation lazily executed, for example recorded in a [`CommandRecord`](@ref). """ abstract type LazyOperation <: Command end """ Operation that sets rendering state for invoking further operations, but which does not do any work by itself. """ abstract type StateCommand <: Command end """ Copy operation from one source to a destination. """ abstract type Copy{S,D} <: LazyOperation end """ Type that records command lazily, for them to be flushed into an Vulkan command buffer later. """ abstract type CommandRecord <: LavaAbstraction end abstract type DrawCommand end """ Record that compacts action commands according to their state before flushing. This allows to group e.g. draw calls that use the exact same rendering state. """ struct CompactRecord <: CommandRecord programs::Dictionary{Program, Dictionary{DrawState,Vector{Pair{DrawCommand,TargetAttachments}}}} other_ops::Vector{LazyOperation} state::Ref{DrawState} program::Ref{Program} fg::FrameGraph pass::Int end CompactRecord(fg::FrameGraph, pass::Int) = CompactRecord(Dictionary(), [], Ref(DrawState()), Ref{Program}(), fg, pass) Base.show(io::IO, record::CompactRecord) = print(io, "CompactRecord(", length(record.programs), " programs, $(sum(x -> sum(length, values(x); init = 0), values(record.programs); init = 0)) draw commands)") function set_program(record::CompactRecord, program::Program) record.program[] = program end function set_material(record::CompactRecord, @nospecialize(args...); alignment = 16) (; gd) = record.fg.frame # replace resource specifications with indices for (i, arg) in enumerate(args) if arg isa Texture @reset args[i] = texture_id!(record.fg, arg, record.pass) elseif arg isa Sampling @reset args[i] = sampler_id!(record.fg, arg, record.pass) end end sub = copyto!(gd.allocator, args, alignment) state = record.state[] record.state[] = @set state.push_data.material_data = device_address(sub) end function set_draw_state(record::CompactRecord, state::DrawState) record.state[] = state end draw_state(record::CompactRecord) = record.state[] function draw(record::CompactRecord, targets::TargetAttachments, vdata, idata; alignment = 16) (; gd) = record.fg.frame state = record.state[] # vertex data sub = copyto!(gd.allocator, align_blocks(vdata, alignment), alignment) record.state[] = @set state.push_data.vertex_data = device_address(sub) state = record.state[] # save draw command with its state program_draws = get!(Dictionary, record.programs, record.program[]) commands = get!(Vector{DrawCommand}, program_draws, state) # index data first_index = length(gd.index_list) + 1 append!(gd.index_list, idata) # draw call push!(commands, DrawIndexed(0, first_index:first_index + length(idata) - 1, 1:1) => targets) end """ Insert padding bytes after each element so that they each start on an offset that is a multiple of `alignment`. """ function align_blocks(data::AbstractArray, alignment) size = sizeof(eltype(data)) size % alignment == 0 && return reinterpret(UInt8, data) bytes = UInt8[] for el in data append!(bytes, reinterpret(UInt8, [el])) append!(bytes, zeros(UInt8, alignment - size % alignment)) end bytes end struct Draw <: DrawCommand vertices::UnitRange{Int} instances::UnitRange{Int} end function apply(cb::CommandBuffer, draw::Draw) buffer = draw.parameters Vk.cmd_draw(cb, 1 + draw.vertices.stop - draw.vertices.start, 1 + draw.instances.stop - draw.instances.start, draw.vertices.start - 1, draw.instances.start - 1) end struct DrawIndirect{B<:Buffer} <: DrawCommand parameters::B count::Int end function apply(cb::CommandBuffer, draw::DrawIndirect) buffer = draw.parameters Vk.cmd_draw_indirect(cb, buffer, offset(buffer), draw.count, stride(buffer)) end struct DrawIndexed <: DrawCommand vertex_offset::Int indices::UnitRange{Int} instances::UnitRange{Int} end function apply(cb::CommandBuffer, draw::DrawIndexed) Vk.cmd_draw_indexed(cb, 1 + draw.indices.stop - draw.indices.start, 1 + draw.instances.stop - draw.instances.start, draw.indices.start - 1, draw.vertex_offset, draw.instances.start - 1) end struct DrawIndexedIndirect{B<:Buffer} <: DrawCommand parameters::B count::Int end function apply(cb::CommandBuffer, draw::DrawIndexedIndirect) buffer = draw.parameters Vk.cmd_draw_indexed_indirect(cb, buffer, offset(buffer), draw.count, stride(buffer)) end function submit_pipelines!(device::Device, pass::RenderPass, record::CompactRecord) pipeline_hashes = Dictionary{ProgramInstance,UInt64}() for (program, calls) in pairs(record.programs) for (state, draws) in pairs(calls) for targets in unique!(last.(draws)) rp = pass_attribute(record.fg.resource_graph, record.pass, :render_pass_handle) hash = submit_pipeline!(device, pass, program, state.render_state, state.program_state, record.fg.frame.gd.resources, targets, rp) set!(pipeline_hashes, ProgramInstance(program, state, targets), hash) end end end pipeline_hashes end """ Submit a pipeline create info for creation in the next batch. A hash is returned to serve as the key to get the corresponding pipeline from the hash table. """ function submit_pipeline!(device::Device, pass::RenderPass, program::Program, state::RenderState, invocation_state::ProgramInvocationState, resources::ResourceDescriptors, targets::TargetAttachments, rp::Vk.RenderPass) shader_stages = Vk.PipelineShaderStageCreateInfo.(collect(program.shaders)) # bindless: no vertex data vertex_input_state = Vk.PipelineVertexInputStateCreateInfo([], []) attachments = map(1:length(targets.color)) do attachment if isnothing(state.blending_mode) Vk.PipelineColorBlendAttachmentState( true, Vk.BLEND_FACTOR_SRC_ALPHA, Vk.BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, Vk.BLEND_OP_ADD, Vk.BLEND_FACTOR_SRC_ALPHA, Vk.BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, Vk.BLEND_OP_ADD; color_write_mask = state.color_write_mask, ) else error("Color blending not supported") end end input_assembly_state = Vk.PipelineInputAssemblyStateCreateInfo(invocation_state.primitive_topology, false) (; x, y) = pass.area.offset (; width, height) = pass.area.extent viewport_state = Vk.PipelineViewportStateCreateInfo(viewports = [Vk.Viewport(x, y, width, height, 0, 1)], scissors = [pass.area]) rasterizer = Vk.PipelineRasterizationStateCreateInfo(false, false, invocation_state.polygon_mode, invocation_state.triangle_orientation, state.enable_depth_bias, 1.0, 0.0, 0.0, 1.0, cull_mode = invocation_state.face_culling) multisample_state = Vk.PipelineMultisampleStateCreateInfo(Vk.SampleCountFlag(pass.samples), false, 1.0, false, false) color_blend_state = Vk.PipelineColorBlendStateCreateInfo(false, Vk.LOGIC_OP_AND, attachments, ntuple(Returns(1f0), 4)) layout = pipeline_layout(device, resources) info = Vk.GraphicsPipelineCreateInfo( shader_stages, rasterizer, layout.handle, rp, 0, 0; vertex_input_state, multisample_state, color_blend_state, input_assembly_state, viewport_state, ) push!(device.pending_pipelines, info) hash(info) end function Base.flush(cb::CommandBuffer, record::CompactRecord, device::Device, binding_state::BindState, pipeline_hashes) for op in record.other_ops apply(cb, op) end for (program, calls) in pairs(record.programs) for (state, draws) in pairs(calls) for (call, targets) in draws hash = pipeline_hashes[ProgramInstance(program, state, targets)] pipeline = device.pipeline_ht[hash] reqs = BindRequirements(pipeline, state.push_data) bind(cb, reqs, binding_state) binding_state = reqs apply(cb, call) end end end binding_state end function initialize(cb::CommandBuffer, device::Device, gd::GlobalData, first_pipeline::Pipeline) allocate_index_buffer(gd, device) Vk.cmd_bind_index_buffer(cb, gd.index_buffer[], 0, Vk.INDEX_TYPE_UINT32) populate_descriptor_sets!(gd) Vk.cmd_bind_descriptor_sets(cb, Vk.PipelineBindPoint(first_pipeline.type), first_pipeline.layout, 0, [gd.resources.gset.set], []) end
{ "alphanum_fraction": 0.7014136306, "author": null, "avg_line_length": 37.0255319149, "converted": null, "ext": "jl", "file": null, "hexsha": "6db80f533b258beefb998ef38ef496cc26c7616e", "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": "6dc3b27c660a6b555178bb738b634aaa588dc4b2", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "serenity4/Lava.jl", "max_forks_repo_path": "src/command.jl", "max_issues_count": null, "max_issues_repo_head_hexsha": "6dc3b27c660a6b555178bb738b634aaa588dc4b2", "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": "serenity4/Lava.jl", "max_issues_repo_path": "src/command.jl", "max_line_length": 228, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6dc3b27c660a6b555178bb738b634aaa588dc4b2", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "serenity4/Lava.jl", "max_stars_repo_path": "src/command.jl", "max_stars_repo_stars_event_max_datetime": "2021-11-17T01:23:02.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-17T01:23:02.000Z", "num_tokens": 2047, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 8701 }
# Reference: https://github.com/tianlinyang/DKVMN import json import numpy as np import torch import torch.nn as nn # import torch.nn.init # Utils def varible(tensor, device): return torch.autograd.Variable(tensor).to(device) # def to_scalar(var): # return var.view(-1).data.tolist()[0] # def save_checkpoint(state, track_list, filename): # with open(filename + '.json', 'w') as f: # json.dump(track_list, f) # torch.save(state, filename + '.model') # def adjust_learning_rate(optimizer, lr): # for param_group in optimizer.param_groups: # param_group['lr'] = lr # Memory class DKVMNHeadGroup(nn.Module): def __init__(self, memory_size, memory_state_dim, is_write): super(DKVMNHeadGroup, self).__init__() """" Parameters memory_size: scalar memory_state_dim: scalar is_write: boolean """ self.memory_size = memory_size self.memory_state_dim = memory_state_dim self.is_write = is_write if self.is_write: self.erase = torch.nn.Linear( self.memory_state_dim, self.memory_state_dim, bias=True) self.add = torch.nn.Linear( self.memory_state_dim, self.memory_state_dim, bias=True) nn.init.kaiming_normal_(self.erase.weight) nn.init.kaiming_normal_(self.add.weight) nn.init.constant_(self.erase.bias, 0) nn.init.constant_(self.add.bias, 0) def addressing(self, control_input, memory): """ Parameters control_input: Shape (batch_size, control_state_dim) memory: Shape (memory_size, memory_state_dim) Returns correlation_weight: Shape (batch_size, memory_size) """ similarity_score = torch.matmul(control_input, torch.t(memory)) correlation_weight = torch.nn.functional.softmax( similarity_score, dim=1) # Shape: (batch_size, memory_size) return correlation_weight def read(self, memory, control_input=None, read_weight=None): """ Parameters control_input: Shape (batch_size, control_state_dim) memory: Shape (batch_size, memory_size, memory_state_dim) read_weight: Shape (batch_size, memory_size) Returns read_content: Shape (batch_size, memory_state_dim) """ if read_weight is None: read_weight = self.addressing( control_input=control_input, memory=memory) read_weight = read_weight.view(-1, 1) memory = memory.view(-1, self.memory_state_dim) rc = torch.mul(read_weight, memory) read_content = rc.view(-1, self.memory_size, self.memory_state_dim) read_content = torch.sum(read_content, dim=1) return read_content def write(self, control_input, memory, write_weight=None): """ Parameters control_input: Shape (batch_size, control_state_dim) write_weight: Shape (batch_size, memory_size) memory: Shape (batch_size, memory_size, memory_state_dim) Returns new_memory: Shape (batch_size, memory_size, memory_state_dim) """ assert self.is_write if write_weight is None: write_weight = self.addressing( control_input=control_input, memory=memory) erase_signal = torch.sigmoid(self.erase(control_input)) add_signal = torch.tanh(self.add(control_input)) erase_reshape = erase_signal.view(-1, 1, self.memory_state_dim) add_reshape = add_signal.view(-1, 1, self.memory_state_dim) write_weight_reshape = write_weight.view(-1, self.memory_size, 1) erase_mult = torch.mul(erase_reshape, write_weight_reshape) add_mul = torch.mul(add_reshape, write_weight_reshape) new_memory = memory * (1 - erase_mult) + add_mul return new_memory class DKVMN(nn.Module): def __init__(self, memory_size, memory_key_state_dim, memory_value_state_dim, init_memory_key): super(DKVMN, self).__init__() """ :param memory_size: scalar :param memory_key_state_dim: scalar :param memory_value_state_dim: scalar :param init_memory_key: Shape (memory_size, memory_value_state_dim) :param init_memory_value: Shape (batch_size, memory_size, memory_value_state_dim) """ self.memory_size = memory_size self.memory_key_state_dim = memory_key_state_dim self.memory_value_state_dim = memory_value_state_dim self.key_head = DKVMNHeadGroup(memory_size=self.memory_size, memory_state_dim=self.memory_key_state_dim, is_write=False) self.value_head = DKVMNHeadGroup(memory_size=self.memory_size, memory_state_dim=self.memory_value_state_dim, is_write=True) self.memory_key = init_memory_key # self.memory_value = self.init_memory_value self.memory_value = None def init_value_memory(self, memory_value): self.memory_value = memory_value def attention(self, control_input): correlation_weight = self.key_head.addressing( control_input=control_input, memory=self.memory_key) return correlation_weight def read(self, read_weight): read_content = self.value_head.read( memory=self.memory_value, read_weight=read_weight) return read_content def write(self, write_weight, control_input, if_write_memory): memory_value = self.value_head.write(control_input=control_input, memory=self.memory_value, write_weight=write_weight) # if_write_memory = torch.cat([if_write_memory.unsqueeze(1) for _ in range(self.memory_value_state_dim)], 1) self.memory_value = nn.Parameter(memory_value.data) return self.memory_value # Model class MODEL(nn.Module): def __init__(self, config, device): super(MODEL, self).__init__() self.config = config self.device = device self.n_question = config.n_skills self.batch_size = config.batch_size self.q_embed_dim = 50 self.qa_embed_dim = 200 self.memory_size = 20 self.memory_key_state_dim = self.q_embed_dim self.memory_value_state_dim = self.qa_embed_dim self.final_fc_dim = 50 self.student_num = None self.input_embed_linear = nn.Linear( self.q_embed_dim, self.final_fc_dim, bias=True) self.read_embed_linear = nn.Linear( self.memory_value_state_dim + self.final_fc_dim, self.final_fc_dim, bias=True) self.predict_linear = nn.Linear(self.final_fc_dim, 1, bias=True) self.init_memory_key = nn.Parameter(torch.randn( self.memory_size, self.memory_key_state_dim)) nn.init.kaiming_normal_(self.init_memory_key) self.init_memory_value = nn.Parameter(torch.randn( self.memory_size, self.memory_value_state_dim)) nn.init.kaiming_normal_(self.init_memory_value) self.mem = DKVMN(memory_size=self.memory_size, memory_key_state_dim=self.memory_key_state_dim, memory_value_state_dim=self.memory_value_state_dim, init_memory_key=self.init_memory_key) memory_value = nn.Parameter(torch.cat( [self.init_memory_value.unsqueeze(0) for _ in range(self.batch_size)], 0).data) self.mem.init_value_memory(memory_value) self.q_embed = nn.Embedding( self.n_question + 1, self.q_embed_dim, padding_idx=0) self.qa_embed = nn.Embedding( 2 * self.n_question + 1, self.qa_embed_dim, padding_idx=0) self.init_embeddings() self.init_params() def init_params(self): nn.init.kaiming_normal_(self.predict_linear.weight) nn.init.kaiming_normal_(self.read_embed_linear.weight) nn.init.constant_(self.read_embed_linear.bias, 0) nn.init.constant_(self.predict_linear.bias, 0) # nn.init.constant(self.input_embed_linear.bias, 0) # nn.init.normal(self.input_embed_linear.weight, std=0.02) def init_embeddings(self): nn.init.kaiming_normal_(self.q_embed.weight) nn.init.kaiming_normal_(self.qa_embed.weight) def forward(self, q_data, qa_data, target, student_id=None): assert q_data.shape == (self.config.batch_size, self.config.sequence_size), q_data.shape batch_size = q_data.shape[0] seqlen = q_data.shape[1] q_embed_data = self.q_embed(q_data) qa_embed_data = self.qa_embed(qa_data) memory_value = nn.Parameter(torch.cat( [self.init_memory_value.unsqueeze(0) for _ in range(batch_size)], 0).data) self.mem.init_value_memory(memory_value) slice_q_data = torch.chunk(q_data, seqlen, 1) slice_q_embed_data = torch.chunk(q_embed_data, seqlen, 1) slice_qa_embed_data = torch.chunk(qa_embed_data, seqlen, 1) value_read_content_l = [] input_embed_l = [] predict_logs = [] for i in range(seqlen): # Attention q = slice_q_embed_data[i].squeeze(1) correlation_weight = self.mem.attention(q) if_memory_write = slice_q_data[i].squeeze(1).ge(1) if_memory_write = varible(torch.FloatTensor( if_memory_write.data.tolist()), self.device) # Read Process read_content = self.mem.read(correlation_weight) value_read_content_l.append(read_content) input_embed_l.append(q) # Write Process qa = slice_qa_embed_data[i].squeeze(1) new_memory_value = self.mem.write( correlation_weight, qa, if_memory_write) # read_content_embed = torch.tanh(self.read_embed_linear(torch.cat([read_content, q], 1))) # pred = self.predict_linear(read_content_embed) # predict_logs.append(pred) all_read_value_content = torch.cat( [value_read_content_l[i].unsqueeze(1) for i in range(seqlen)], 1) input_embed_content = torch.cat( [input_embed_l[i].unsqueeze(1) for i in range(seqlen)], 1) # input_embed_content = input_embed_content.view(batch_size * seqlen, -1) # input_embed_content = torch.tanh(self.input_embed_linear(input_embed_content)) # input_embed_content = input_embed_content.view(batch_size, seqlen, -1) predict_input = torch.cat( [all_read_value_content, input_embed_content], 2) read_content_embed = torch.tanh(self.read_embed_linear( predict_input.view(batch_size*seqlen, -1))) pred = self.predict_linear(read_content_embed) # predicts = torch.cat([predict_logs[i] for i in range(seqlen)], 1) target_1d = target # [batch_size * seq_len, 1] mask = target_1d.ge(0) # [batch_size * seq_len, 1] # pred_1d = predicts.view(-1, 1) # [batch_size * seq_len, 1] pred_1d = pred.view(-1, 1) # [batch_size * seq_len, 1] assert pred.shape == (self.batch_size * seqlen, 1) assert target_1d.shape == (self.batch_size * seqlen, 1) assert mask.shape == (self.batch_size * seqlen, 1) assert pred_1d.shape == (self.batch_size * seqlen, 1) filtered_pred = torch.masked_select(pred_1d, mask) filtered_target = torch.masked_select(target_1d, mask) loss = torch.nn.functional.binary_cross_entropy_with_logits( filtered_pred, filtered_target) # print(filtered_pred, filtered_pred.shape) #-> torch.Size([6399]) out = { 'loss': loss, 'filtered_pred': torch.sigmoid(filtered_pred), 'filtered_target': filtered_target, # 'pred_vect': pred_vect, # (20, 100, 124) 'pred_prob': pred.view(seqlen, batch_size), # (20, 100) } return out def loss_batch(self, xseq, yseq, mask, opt=None): i_skill = self.config.n_skills device = self.device # q_one_seq = q_data[idx * params.batch_size:(idx + 1) * params.batch_size, :] q_one_seq = torch.matmul(yseq.float().to(device), torch.Tensor( [[1], [0]]).to(device)).long().to(device) # qa_batch_seq = qa_data[idx * params.batch_size:(idx + 1) * params.batch_size, :] qa_batch_seq = torch.matmul(yseq.float().to(device), torch.Tensor( [[1], [i_skill]]).to(device)).long().to(device) # target = qa_data[idx * params.batch_size:(idx + 1) * params.batch_size, :] target = torch.matmul(yseq.float().to(device), torch.Tensor( [[1], [i_skill]]).to(device)).long().to(device) # [[24. 24. 24. ... 0. 0. 0.] # ... # [29. 3. 29. ... 59. 41. 41.]] (32, 200) # [[ 24. 134. 24. ... 0. 0. 0.] # ... # [ 29. 3. 29. ... 169. 41. 151.]] (32, 200) # [[ 24. 134. 24. ... 0. 0. 0.] # ... # [ 29. 3. 29. ... 169. 41. 151.]] (32, 200) q_one_seq = q_one_seq.squeeze(2) qa_batch_seq = qa_batch_seq.squeeze(2) target = target.squeeze(2) # print(q_one_seq, q_one_seq.shape) # print(qa_batch_seq, qa_batch_seq.shape) # print(target, target.shape) target = (target.float().cpu().numpy() - 1) / self.n_question target = np.floor(target) input_q = varible((q_one_seq), self.device) input_qa = varible((qa_batch_seq), self.device) target = varible(torch.FloatTensor(target), self.device) target_to_1d = torch.chunk(target, self.batch_size, 0) target_1d = torch.cat([target_to_1d[i] for i in range(self.batch_size)], 1) target_1d = target_1d.permute(1, 0) out = self.forward(input_q, input_qa, target_1d) loss = out['loss'] if opt: opt.zero_grad() loss.backward() opt.step() return out
{ "alphanum_fraction": 0.6219936049, "author": null, "avg_line_length": 41.9416909621, "converted": null, "ext": "py", "file": null, "hexsha": "0058921db74d18a51cb097f4cb9629b6261aff24", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-01-23T13:05:21.000Z", "max_forks_repo_forks_event_min_datetime": "2022-01-23T13:05:21.000Z", "max_forks_repo_head_hexsha": "cecdb9af0c44efffd1ce3359f331d7d7782f551b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "qqhann/KnowledgeTracing", "max_forks_repo_path": "model/dkvmn.py", "max_issues_count": 25, "max_issues_repo_head_hexsha": "cecdb9af0c44efffd1ce3359f331d7d7782f551b", "max_issues_repo_issues_event_max_datetime": "2021-08-23T21:14:24.000Z", "max_issues_repo_issues_event_min_datetime": "2021-08-15T10:57:48.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "qqhann/KnowledgeTracing", "max_issues_repo_path": "model/dkvmn.py", "max_line_length": 116, "max_stars_count": 3, "max_stars_repo_head_hexsha": "cecdb9af0c44efffd1ce3359f331d7d7782f551b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "qqhann/KnowledgeTracing", "max_stars_repo_path": "model/dkvmn.py", "max_stars_repo_stars_event_max_datetime": "2022-01-12T06:53:05.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-24T09:49:03.000Z", "num_tokens": 3362, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 14386 }
# -*- utf-8 -*- import matplotlib.pyplot as plt import tensorflow as tf import numpy as np def img_endecoding(): image_raw_data = tf.gfile.FastGFile("backGround.jpg", 'rb').read() img_data = tf.image.decode_jpeg(image_raw_data) print(type(img_data.eval())) print(img_data.eval().ndim) print(img_data.eval().dtype) print(img_data.eval().size) print(img_data.eval().shape) # plt.imshow(img_data.eval()) # plt.show() encoded_image = tf.image.encode_jpeg(img_data) with tf.gfile.GFile("backGround2.jpg", 'wb') as f: f.write(encoded_image.eval()) return img_data def img_proc(img_data): # sugggest to convert img to real number domain 0.0-1.0, so as not to lose too much accuracy img_data = tf.image.convert_image_dtype(img_data, dtype=tf.float32) # change size resized = tf.image.resize_images(img_data, [300, 300], method=0) croped = tf.image.resize_image_with_crop_or_pad(img_data, 500, 500) padded = tf.image.resize_image_with_crop_or_pad(img_data, 1000, 1000) central_cropped = tf.image.central_crop(img_data, 0.5) # flip flipped_ud = tf.image.flip_up_down(img_data) flipped_lr = tf.image.flip_left_right(img_data) transpose = tf.image.transpose_image(img_data) flipped_rndup = tf.image.random_flip_up_down(img_data) flipped_rndlr = tf.image.random_flip_left_right(img_data) # brightness bright_adjusted = tf.image.adjust_brightness(img_data, -0.5) bright_adjusted = tf.image.random_brightness(img_data, 0.5) # -0.5 - 0.5 bright_adjusted_clip = tf.clip_by_value(bright_adjusted, 0.0, 1.0) # contrast contrast_adjusted = tf.image.adjust_contrast(img_data, 0.5) contrast_adjusted = tf.image.random_contrast(img_data, 0.5, 5) # hue 色相 hue_adjusted = tf.image.adjust_hue(img_data, 0.1) hue_adjusted = tf.image.random_hue(img_data, 0.5) # 0-0.5 # saturation 饱和度 saturation_adjusted = tf.image.adjust_saturation(img_data, -5) saturation_adjusted = tf.image.random_saturation(img_data, 0, 5) # standardization, N~(0,1) adjusted = tf.image.per_image_standardization(img_data) # labelling, 输入四维矩阵 batched = tf.expand_dims(tf.image.convert_image_dtype(img_data, dtype=tf.float32), 0) print(batched.eval().ndim) # Ymin, Xmin, Ymax, Xmax boxes = tf.constant([[[0.1, 0.5, 0.85, 0.8], [0.35, 0.47, 0.5, 0.56]]]) result = tf.image.draw_bounding_boxes(batched, boxes) # clip by boxes, 0.4 means at least contain 40% area begin, size, box = tf.image.sample_distorted_bounding_box( tf.shape(img_data), bounding_boxes=boxes, min_object_covered=0.4 ) image_with_box = tf.image.draw_bounding_boxes(batched, box) distorted_img = tf.slice(img_data, begin, size) plt.imshow(result[0].eval()) plt.show() img_data = tf.image.convert_image_dtype(resized, dtype=tf.uint8) return img_data def distort_color(image, color_ordering=0): if color_ordering == 0: image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) image = tf.image.random_contrast(image, lower=0.5, upper=1.5) elif color_ordering == 1: image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_brightness(image, max_delta=32. / 255.) image = tf.image.random_contrast(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) elif color_ordering == 2: image = tf.image.random_contrast(image, lower=0.5, upper=1.5) image = tf.image.random_hue(image, max_delta=0.2) image = tf.image.random_saturation(image, lower=0.5, upper=1.5) image = tf.image.random_brightness(image, max_delta=32. / 255.) return tf.clip_by_value(image, 0.0, 1.0) def process_for_train(image, height, width, bbox, channels=3): if bbox is None: bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4]) if image.dtype != tf.float32: image = tf.image.convert_image_dtype(image, dtype=tf.float32) bbox_begin, bbox_size, _ = tf.image.sample_distorted_bounding_box( tf.shape(image), bounding_boxes=bbox, min_object_covered=0.1 ) distorted_img = tf.slice(image, bbox_begin, bbox_size) # resize input image for train, all kinds of interpolation distorted_img = tf.image.resize_images( distorted_img, [height, width], method=np.random.randint(4) ) # filp img distorted_img = tf.image.random_flip_left_right(distorted_img) distorted_img = tf.image.random_flip_up_down(distorted_img) if channels == 3: distorted_img = distort_color(distorted_img, np.random.randint(3)) # distorted_img = tf.image.convert_image_dtype(distorted_img, dtype=tf.uint8) # print(distorted_img.shape) distorted_img.set_shape([height, width, channels]) return distorted_img def main(): # with tf.device('/cpu:0'): with tf.Session() as sess: img_data = img_endecoding() boxes = tf.constant([[[0.1, 0.5, 0.85, 0.8]]]) # img_data = img_proc(img_data) for i in range(6): plt.figure(i) result = process_for_train(img_data, 500, 300, boxes) plt.imshow(result.eval()) plt.show() # print(img_data) # plt.imshow(trans.eval()) # plt.show() if __name__ == '__main__': main()
{ "alphanum_fraction": 0.6803545586, "author": null, "avg_line_length": 36.6092715232, "converted": null, "ext": "py", "file": null, "hexsha": "6b86b1ce4a0853e8a8e9de2bf6ac673d2d42f86c", "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": "56ebfc253615b22fc3a55ba5e952837c47bf85cf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "carbo-T/TF", "max_forks_repo_path": "img_proc/preprocessing.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "56ebfc253615b22fc3a55ba5e952837c47bf85cf", "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": "carbo-T/TF", "max_issues_repo_path": "img_proc/preprocessing.py", "max_line_length": 96, "max_stars_count": 1, "max_stars_repo_head_hexsha": "56ebfc253615b22fc3a55ba5e952837c47bf85cf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "carbo-T/TF", "max_stars_repo_path": "img_proc/preprocessing.py", "max_stars_repo_stars_event_max_datetime": "2018-11-01T04:16:58.000Z", "max_stars_repo_stars_event_min_datetime": "2018-11-01T04:16:58.000Z", "num_tokens": 1557, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 5528 }
\input{permve-ntnu-latex-assignment.tex} \usepackage{float} \title{ \normalfont \normalsize \textsc{Norwegian University of Science and Technology\\IT3105 -- Artificial Intelligence Programming} \horrule{0.5pt} \\[0.4cm] \huge Module 2:\\Combining Constraint-Satisfaction Problem-Solving with Best-First Search\\ \horrule{2pt} \\[0.5cm] } \author{Per Magnus Veierland\\permve@stud.ntnu.no} \date{\normalsize\today} \newacro{CSP}{Constraint Satisfaction Problem} \newacro{GAC}{General Arc Consistency} \begin{document} \maketitle \section*{Generality of A* implementation} The \ac{CSP} and \ac{GAC} related code is implemented in the \texttt{vi.csp} namespace. A \texttt{Network} object holds all \texttt{Variable} and \texttt{Constraint} objects, as well as a \texttt{domains} mapping from \texttt{Variable} objects to the domains of the variables. The values within a domain can be of any type. Also within the \texttt{vi.csp} namespace are the functions implementing \textsc{REVISE*} and \ac{GAC}. None of this code is tied to search code; and it can be used in full isolation where needed. A \texttt{Constraint} holds the list of variables it is linked to, as well as a condition which can be evaluated. A \texttt{Variable} has an identity which can be of any type suiting the problem, as well as the list of contraints it is involved in. Fusing the \ac{GAC} algorithm with A* is done by the \texttt{vi.search.gac.Problem} class, which is constructed from a \texttt{vi.csp.Network} object -- see Figure~\ref{figure:vi_astar_gac}. The \texttt{Network} object serves as the state of each search node. The \texttt{Problem} class provides the methods \texttt{goal\_test}, \texttt{heuristic}, \texttt{initial\_node}, and \texttt{successors} -- which forms the interface to the A* search class. No problem specific code exists in the \texttt{vi.search.gac.Problem} class. It has a goal test which checks that all domains in the current state has a size of one. It has a heuristic which returns the sum of the length of all domains minus one. The initial search node returned from the \texttt{Problem} class is simply the initial network passed through one iteration of the \texttt{general\_arc\_consistency} function. The crucial part of the \texttt{Problem} class implementation lies in the \texttt{successors} method. All successors generated from a search node is based on assumptions made about a single variable. The implementation selects the variable which has the smallest domain which contains more than one value. A successor state is generated for each value in the assumed variable's domain. The \ac{GAC} domain filtering loop is then warm rebooted to revise the domains of all variables which share a constraint with the assumed variable. \begin{figure}[H] \centering \includegraphics[scale=0.7]{images/vi_astar_gac} \caption{VI CSP and A*-GAC classes} \label{figure:vi_astar_gac} \end{figure} \section*{Generality of A*-GAC implementation} The input to the vertex coloring problem is a pure graph description; with no direct relation to the vertex coloring problem. The file input is parsed and used to construct a graph using the \texttt{vi.graph.Vertex}, \texttt{vi.graph.Edge} and \texttt{vi.graph.Graph} classes; which are fully problem independent. A single function in the \texttt{vi.app.vertex\_coloring} namespace takes the \texttt{vi.graph.Graph} object constructed from the file input, together with a $K$-value describing the number of colors -- and builds a \texttt{vi.csp.Network} which contains the variables, constraints and domains which describes the vertex coloring problem. It simply generates one \texttt{Variable} for each \texttt{Vertex} object; with the \texttt{Vertex} object as the variable's identity. For each \texttt{Edge} object a \texttt{Constraint} object is built which binds the two \texttt{Variable} objects associated with each \texttt{Vertex} in the edge together. The condition assigned to each constraint simply verifies that the values assigned to each of the two variables are different. \section*{Constraint network} A constraint network consists of constraints, variables, and domains. Much of this information is identical between search states. The assignment specifies that the variables and constraints will be the same in all states. The difference between the states is the sizes of the domains belonging to the different variables. The constraint network is represented with the \texttt{vi.csp.Network} class. It holds a all variables involved in the network; a list of all constraints involved in the network; and it holds the mapping from variables to their respective domains. It is important to note that there is no direct connection from a \texttt{Variable} instance to its domain; this connection is only made by the mapping which exists in each \texttt{Network} instance. A \texttt{Network} instance is the state for each search node in the A*-GAC implementation. However importance is place on how the \texttt{Network} object is copied and which data is shared between states. All \texttt{vi.csp.Network} instances which belong to the same problem share the list of variables and the list of constraints. There is only a single list of variables and a single list of constraints; and each instance of the \texttt{Network} class points to the same two lists. It is still important that each instance contains these two pointers since \texttt{Network} objects belonging to different problems will necessarily maintain different lists of variables and constraints. The \texttt{Network.copy()} member function returns a new instance of the class which points to the same lists of variables and constraints; but which takes a shallow copy of the domains mapping. This means that no actual domains are copied, only the mapping from variables to domains. When applying the GAC algorithm to a \texttt{Network} instance, the relevant mappings of revised domains is updated to point at the new revised domain for the involved variables. This ensures high reuse in representation and avoids redundant information, without increasing the complexity of the implementation. \section*{Code chunks} In the given implementation a \texttt{Constraint} class instance holds a single condition and a list of variables involved in the condition. The condition must be callable and must accept one parameter. The parameter passed to a condition is a mapping of variables to specific values for all variables involved in the constraint. This makes the \texttt{Constraint} interface very general and allows any hashable type to be used as the \texttt{Variable} identity and in variable domains. Since all variables involved in a \texttt{Constraint} is explicitly specified it is easy to generate the required permutations of values from variable domains in the \textsc{REVISE*} algorithm. The interface was chosen for its semantical purity and generality. It can be used with both interpreters parsing user input as well as direct \texttt{eval} approaches simply by adding code to build the necessary \texttt{Constraint} objects and callable conditions. Since no parsing of user input was necessary for the given problem; only a simple lambda verifying the inequality of two variable values in the given value set was used. \end{document}
{ "alphanum_fraction": 0.7980309039, "author": null, "avg_line_length": 104.4714285714, "converted": null, "ext": "tex", "file": null, "hexsha": "0d9f8a068f24a21cc1f78bbe3080e71681d110c7", "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": "6a7e4751de47b091c1c9c59560c19a8452698d81", "max_forks_repo_licenses": [ "CC0-1.0" ], "max_forks_repo_name": "pveierland/permve-ntnu-it3105", "max_forks_repo_path": "module_2/report/permve-ntnu-it3105-module-2.tex", "max_issues_count": null, "max_issues_repo_head_hexsha": "6a7e4751de47b091c1c9c59560c19a8452698d81", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "CC0-1.0" ], "max_issues_repo_name": "pveierland/permve-ntnu-it3105", "max_issues_repo_path": "module_2/report/permve-ntnu-it3105-module-2.tex", "max_line_length": 773, "max_stars_count": null, "max_stars_repo_head_hexsha": "6a7e4751de47b091c1c9c59560c19a8452698d81", "max_stars_repo_licenses": [ "CC0-1.0" ], "max_stars_repo_name": "pveierland/permve-ntnu-it3105", "max_stars_repo_path": "module_2/report/permve-ntnu-it3105-module-2.tex", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1670, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 7313 }
import albumentations as A from torchvision import transforms import numpy as np from drishtypy.data.data_utils import find_stats from albumentations.pytorch import ToTensor import cv2 ''' # A.Resize(input_size,input_size), # A.CoarseDropout(max_holes=1,max_height=16,max_width=16,min_holes=None,min_height=4,min_width=4,always_apply=True,p=0.7,), # A.RGBShift(r_shift_limit=50, g_shift_limit=50, b_shift_limit=50, p=0.5), ''' class AlbumCompose(): def __init__(self, transform=None): self.transform = transform def __call__(self, img): img = np.array(img) img = self.transform(image=img)['image'] return img def get_data_transform(path): mean, stdev = find_stats(path) input_size = 32 train_albumentation_transform = A.Compose([ # CoarseDropout(max_holes=3, max_height=8, max_width=8, min_holes=None, min_height=None, min_width=None, # fill_value=[i * 255 for i in mean], always_apply=True, p=0.5), A.PadIfNeeded (min_height=40, min_width=40, border_mode=cv2.BORDER_REPLICATE, always_apply=True, p=1.0), A.RandomCrop(height=32,width=32,p=1,always_apply=False), A.Cutout(num_holes=1, max_h_size=16, max_w_size=16, always_apply=True, p=1), A.HorizontalFlip(p=0.7, always_apply=True), # A.ShiftScaleRotate(shift_limit=0.0625, scale_limit=0, rotate_limit=45, p=0.5), A.Normalize(mean=tuple(mean), std=tuple(stdev), max_pixel_value=255, always_apply=True, p=1.0), A.Resize(input_size,input_size), ToTensor()]) A.Resize(input_size, input_size), train_transforms = AlbumCompose(train_albumentation_transform) # Test Phase transformation test_transforms = transforms.Compose([ transforms.ToTensor(), transforms.Normalize(tuple(mean), tuple(stdev)) ]) return train_transforms, test_transforms
{ "alphanum_fraction": 0.704135737, "author": null, "avg_line_length": 36.9803921569, "converted": null, "ext": "py", "file": null, "hexsha": "2ef85d1b555ed7bbb635a7da328c26082e37437b", "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": "5956afe24916bf40dde8d857ed6030de57dea353", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Abhinavl3v3l/Drishtipy", "max_forks_repo_path": "drishtypy/data/does_augmentation.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "5956afe24916bf40dde8d857ed6030de57dea353", "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": "Abhinavl3v3l/Drishtipy", "max_issues_repo_path": "drishtypy/data/does_augmentation.py", "max_line_length": 123, "max_stars_count": null, "max_stars_repo_head_hexsha": "5956afe24916bf40dde8d857ed6030de57dea353", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Abhinavl3v3l/Drishtipy", "max_stars_repo_path": "drishtypy/data/does_augmentation.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 506, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1886 }
import os import sys import numpy as np import tensorflow as tf from tensorflow.python.keras.utils import losses_utils ''' These are custom Loss functions ''' class MultiTaskLoss(tf.keras.losses.Loss): def __init__(self, loss_num=2, scale_factor = 0.01, lam = 0.00001, sigmas_sq = None, reduction=tf.keras.losses.Reduction.NONE, reduction_type = None, name='multiTaskMse', **kwargs): super(MultiTaskLoss, self).__init__(reduction=reduction,name=name, **kwargs) self._loss_num = loss_num self._scale_factor = scale_factor self._lambda = lam self.reduction_type = reduction_type if sigmas_sq: self._sigmas_sq = tf.Variable(name = 'Sigma_sq_', dtype=tf.float32, trainable= True, validate_shape = False, initial_value = sigmas_sq) else: self._sigmas_sq = tf.Variable(name = 'Sigma_sq_', dtype=tf.float32, trainable= True, validate_shape = False, initial_value = tf.initializers.random_uniform(minval=0.25, maxval=1.0)(shape = [loss_num,])) def call(self, y_true, y_pred): y_pred = tf.convert_to_tensor(y_pred) y_true = tf.cast(y_true, y_pred.dtype) assert(len(y_true.shape) == 4), 'channel dimension mismatch!! recieved shape as {}'.format(y_true.shape) assert(len(y_pred.shape) == 4), 'channel dimension mismatch!! recieved shape as {}'.format(y_pred.shape) assert(y_pred.shape[-1] == self._loss_num), 'Please check the number of tasks are not same as the number of channels in the prediction' assert(y_true.shape[-1] == y_pred.shape[-1]), 'Dimensions of true and predicted outputs do not match!! expected {} but recieved {}'.format(y_true.shape,y_pred.shape) self.batch_size = y_true.shape[0] factor = tf.multiply(self._scale_factor, tf.divide(1.0, tf.multiply(2.0, self._sigmas_sq[0]))) l2 = tf.math.square(y_true[:,:,:,0] - y_pred[:,:,:,0]) loss = tf.add(tf.multiply(factor, l2), tf.math.log(self._sigmas_sq[0]+self._lambda)) for i in range(1, self._loss_num): factor = tf.divide(1.0, tf.multiply(2.0, self._sigmas_sq[i])) l2 = tf.multiply(tf.math.square(y_true[:,:,:,i] - y_pred[:,:,:,i]), y_true[:,:,:,0]) loss = tf.add(loss, tf.add(tf.multiply(factor, l2), tf.math.log(self._sigmas_sq[i]+self._lambda))) if self.reduction_type == 'distributed': loss = tf.reduce_mean(loss, axis = [1,2]) loss = tf.reduce_sum(loss)* (1. / self.batch_size) return loss def print_config(self): print('sigmas_sq: {}'.format(self._sigmas_sq)) print('batch_size: {}'.format(self.batch_size)) ''' def get_config(self): """Returns the config dictionary for a `Loss` instance.""" return {'reduction': self.reduction, 'name': self.name, 'loss_num': self._loss_num, 'scale_factor': self._scale_factor, 'lam': self._lambda, 'sigmas_sq': tf.io.serialize_tensor(self._sigmas_sq, name='sigma')} ''' class CustomL1Loss(tf.keras.losses.Loss): def call(self, y_true, y_pred): y_pred = tf.convert_to_tensor(y_pred) y_true = tf.cast(y_true, y_pred.dtype) return tf.math.reduce_mean(tf.math.abs(y_true - y_pred), axis=-1) class customSSIMLoss(tf.keras.losses.Loss): def call(self, y_true, y_pred): y_pred = tf.convert_to_tensor(y_pred) y_true = tf.cast(y_true, y_pred.dtype) data_range = tf.math.reduce_max(y_true) - tf.math.reduce_min(y_true) ssim_loss = 1-tf.image.ssim(y_true, y_pred, max_val=data_range) return ssim_loss class CustomSSIML1ELoss(tf.keras.losses.Loss): def call(self, y_true, y_pred): y_pred = tf.convert_to_tensor(y_pred) y_true = tf.cast(y_true, y_pred.dtype) data_range = tf.math.reduce_max(y_true) - tf.math.reduce_min(y_true) ssim_loss = 1-tf.image.ssim(y_true, y_pred, max_val=data_range) mse_loss = tf.math.reduce_mean(tf.math.abs(y_true - y_pred), axis=(1,2,3)) loss = ssim_loss + mse_loss return loss
{ "alphanum_fraction": 0.5718243819, "author": null, "avg_line_length": 44.6857142857, "converted": null, "ext": "py", "file": null, "hexsha": "56ab0de2866bb417cd9f512978588747fe02618b", "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": "03eed92c16d8e96625f1be71d4f81397ae474b66", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "AI-ML-4DSTEM/crystal4D", "max_forks_repo_path": "crystal4D/utils/loss_utils.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "03eed92c16d8e96625f1be71d4f81397ae474b66", "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": "AI-ML-4DSTEM/crystal4D", "max_issues_repo_path": "crystal4D/utils/loss_utils.py", "max_line_length": 173, "max_stars_count": null, "max_stars_repo_head_hexsha": "03eed92c16d8e96625f1be71d4f81397ae474b66", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "AI-ML-4DSTEM/crystal4D", "max_stars_repo_path": "crystal4D/utils/loss_utils.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1093, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 4692 }
""" Contains functions to run likelihood modules. """ import glob import os.path import time import warnings import numpy as np import like_cl_gauss as like_g import like_cl_wishart as like_w import posteriors def run_like_cl_wishart(grid_dir, varied_params, save_path, n_zbin, obs_pos_pos_dir, obs_she_she_dir, obs_pos_she_dir, pos_nl_path, she_nl_path, noise_ell_path, lmax, leff_path=None): """ Evaluate Wishart likelhood on a CosmoSIS output grid and save the result as a text file. Args: grid_dir (str): Path to CosmoSIS grid. varied_params (list): List of varied parameter names as they appear in the cosmological_parameters/values.txt file. save_path (str): Path to save output to. n_zbin (int): Number of redshift bins. It will be assumed that there is one position field and one shear field per redshift bin. obs_pos_pos_dir (str): Path to the directory containing the observed position-position power spectra. obs_she_she_dir (str): Path to the directory containing the observed shear-shear power spectra. obs_pos_she_dir (str): Path to the directory containing the observed position-shear power spectra. pos_nl_path (str): Path to the position noise power spectrum. she_nl_path (str): Path to the shear noise power spectrum. noise_ell_path (str): Path to the file containing the ells for the noise power spectra. lmax (int): Maximum l to use in the likelihood. leff_path (str, optional): Path to ell-ell_effective mapping, to replace each l with its corresponding l_eff when calculating the covariance. """ print(f'Starting at {time.strftime("%c")}', flush=True) # Setup the likelihood module print(f'Setting up likelihood module at {time.strftime("%c")}') config_w = like_w.setup(n_zbin, obs_pos_pos_dir, obs_she_she_dir, obs_pos_she_dir, pos_nl_path, she_nl_path, noise_ell_path, lmax, leff_path=leff_path) print(f'Setup complete at {time.strftime("%c")}') # Loop over every input directory source_dirs = glob.glob(os.path.join(grid_dir, '_[0-9]*/')) n_dirs = len(source_dirs) if n_dirs == 0: warnings.warn(f'No matching directories. Terminating at {time.strftime("%c")}') return n_params = len(varied_params) if n_params == 0: warnings.warn(f'No parameters specified. Terminating at {time.strftime("%c")}') return first_dir = True res = [] for i, source_dir in enumerate(source_dirs): print(f'Calculating likelihood {i + 1} / {n_dirs} at {time.strftime("%c")}', flush=True) # Extract cosmological parameters params = [None]*n_params values_path = os.path.join(source_dir, 'cosmological_parameters/values.txt') with open(values_path) as f: for line in f: for param_idx, param in enumerate(varied_params): param_str = f'{param} = ' if param_str in line: params[param_idx] = float(line[len(param_str):]) err_str = f'Not all parameters in varied_params found in {values_path}' assert np.all([param is not None for param in params]), err_str # Check the ells for consistency if first_dir: ells_pos = np.loadtxt(os.path.join(source_dir, 'galaxy_cl/ell.txt')) ells_she = np.loadtxt(os.path.join(source_dir, 'shear_cl/ell.txt')) ells_pos_she = np.loadtxt(os.path.join(source_dir, 'galaxy_shear_cl/ell.txt')) assert np.allclose(ells_pos, ells_she) assert np.allclose(ells_pos, ells_pos_she) first_dir = False else: ells_pos_test = np.loadtxt(os.path.join(source_dir, 'galaxy_cl/ell.txt')) ells_she_test = np.loadtxt(os.path.join(source_dir, 'shear_cl/ell.txt')) ells_pos_she_test = np.loadtxt(os.path.join(source_dir, 'galaxy_shear_cl/ell.txt')) assert np.allclose(ells_pos, ells_pos_test) assert np.allclose(ells_she, ells_she_test) assert np.allclose(ells_pos_she, ells_pos_she_test) # Load theory Cls pos_pos_dir = os.path.join(source_dir, 'galaxy_cl/') she_she_dir = os.path.join(source_dir, 'shear_cl/') pos_she_dir = os.path.join(source_dir, 'galaxy_shear_cl/') theory_cls = like_w.load_cls(n_zbin, pos_pos_dir, she_she_dir, pos_she_dir) # Evaluate likelihood log_like_wish = like_w.execute(ells_pos, theory_cls, config_w) # Store cosmological params & likelihood res.append([*params, log_like_wish]) # Save results to file res_grid = np.asarray(res) param_names = ' '.join(varied_params) header = f'Output from {__file__}.run_like_cl_wishart for input grid {grid_dir} at {time.strftime("%c")} \n' header += f'{param_names} log_like_wishart' np.savetxt(save_path, res_grid, header=header) print('Saved ' + save_path) print(f'Done at {time.strftime("%c")}', flush=True) def run_like_cl_gauss(grid_dir, varied_params, save_path, n_zbin, obs_pos_pos_dir, obs_she_she_dir, obs_pos_she_dir, pos_nl_path, she_nl_path, noise_ell_path, fid_pos_pos_dir, fid_she_she_dir, fid_pos_she_dir, lmax, leff_path=None): """ Evaluate Gaussian likelhood on a CosmoSIS output grid and save the result as a text file. Args: grid_dir (str): Path to CosmoSIS grid. varied_params (list): List of varied parameter names as they appear in the cosmological_parameters/values.txt file. save_path (str): Path to save output to. n_zbin (int): Number of redshift bins. It will be assumed that there is one position field and one shear field per redshift bin. obs_pos_pos_dir (str): Path to the directory containing the observed position-position power spectra. obs_she_she_dir (str): Path to the directory containing the observed shear-shear power spectra. obs_pos_she_dir (str): Path to the directory containing the observed position-shear power spectra. pos_nl_path (str): Path to the position noise power spectrum. she_nl_path (str): Path to the shear noise power spectrum. noise_ell_path (str): Path to the file containing the ells for the noise power spectra. fid_pos_pos_dir (str): Path to the directory containing the fiducial theory position-position power spectra, used for the covariance. fid_she_she_dir (str): Path to the directory containing the fiducial theory shear-shear power spectra. fid_pos_she_dir (str): Path to the directory containing the fiducial theory position-shear power spectra. lmax (int): Maximum l to use in the likelihood. leff_path (str, optional): Path to ell-ell_effective mapping, to replace each l with its corresponding l_eff when calculating the covariance. """ print(f'Starting at {time.strftime("%c")}') # Setup the likelihood module print(f'Setting up likelihood module at {time.strftime("%c")}') config = like_g.setup(n_zbin, obs_pos_pos_dir, obs_she_she_dir, obs_pos_she_dir, pos_nl_path, she_nl_path, noise_ell_path, fid_pos_pos_dir, fid_she_she_dir, fid_pos_she_dir, lmax, leff_path=leff_path) print(f'Setup complete at {time.strftime("%c")}') # Loop over every input directory source_dirs = glob.glob(os.path.join(grid_dir, '_[0-9]*/')) n_dirs = len(source_dirs) if n_dirs == 0: warnings.warn(f'No matching directories. Terminating at {time.strftime("%c")}') return n_params = len(varied_params) if n_params == 0: warnings.warn(f'No parameters specified. Terminating at {time.strftime("%c")}') return first_dir = True res = [] for i, source_dir in enumerate(source_dirs): print(f'Calculating likelihood {i + 1} / {n_dirs} at {time.strftime("%c")}') # Extract cosmological parameters params = [None]*n_params values_path = os.path.join(source_dir, 'cosmological_parameters/values.txt') with open(values_path) as f: for line in f: for param_idx, param in enumerate(varied_params): param_str = f'{param} = ' if param_str in line: params[param_idx] = float(line[len(param_str):]) err_str = f'Not all parameters in varied_params found in {values_path}' assert np.all([param is not None for param in params]), err_str # Check the ells for consistency if first_dir: ells_pos = np.loadtxt(os.path.join(source_dir, 'galaxy_cl/ell.txt')) ells_she = np.loadtxt(os.path.join(source_dir, 'shear_cl/ell.txt')) ells_pos_she = np.loadtxt(os.path.join(source_dir, 'galaxy_shear_cl/ell.txt')) assert np.allclose(ells_pos, ells_she) assert np.allclose(ells_pos, ells_pos_she) first_dir = False else: ells_pos_test = np.loadtxt(os.path.join(source_dir, 'galaxy_cl/ell.txt')) ells_she_test = np.loadtxt(os.path.join(source_dir, 'shear_cl/ell.txt')) ells_pos_she_test = np.loadtxt(os.path.join(source_dir, 'galaxy_shear_cl/ell.txt')) assert np.allclose(ells_pos, ells_pos_test) assert np.allclose(ells_she, ells_she_test) assert np.allclose(ells_pos_she, ells_pos_she_test) # Load theory Cls pos_pos_dir = os.path.join(source_dir, 'galaxy_cl/') she_she_dir = os.path.join(source_dir, 'shear_cl/') pos_she_dir = os.path.join(source_dir, 'galaxy_shear_cl/') theory_cls = like_w.load_cls(n_zbin, pos_pos_dir, she_she_dir, pos_she_dir) # Evaluate likelihood log_like_gauss = like_g.execute(ells_pos, theory_cls, config) # Store cosmological params & likelihood res.append([*params, log_like_gauss]) # Save results to file res_grid = np.asarray(res) param_names = ' '.join(varied_params) header = f'Output from {__file__}.run_like_cl_gauss for input grid {grid_dir} at {time.strftime("%c")} \n' header += f'{param_names} log_like_gauss' np.savetxt(save_path, res_grid, header=header) print('Saved ' + save_path) print(f'Done at {time.strftime("%c")}') def run_likes_cl_wishart_gauss(grid_dir, varied_params, save_path, n_zbin, obs_pos_pos_dir, obs_she_she_dir, obs_pos_she_dir, pos_nl_path, she_nl_path, noise_ell_path, fid_pos_pos_dir, fid_she_she_dir, fid_pos_she_dir, lmax, leff_path=None): """ Evaluate both the Wishart and Gaussian likelhoods on a CosmoSIS output grid and save the result as a text file. Args: grid_dir (str): Path to CosmoSIS grid. varied_params (list): List of varied parameter names as they appear in the cosmological_parameters/values.txt file. save_path (str): Path to save output to. n_zbin (int): Number of redshift bins. It will be assumed that there is one position field and one shear field per redshift bin. obs_pos_pos_dir (str): Path to the directory containing the observed position-position power spectra. obs_she_she_dir (str): Path to the directory containing the observed shear-shear power spectra. obs_pos_she_dir (str): Path to the directory containing the observed position-shear power spectra. pos_nl_path (str): Path to the position noise power spectrum. she_nl_path (str): Path to the shear noise power spectrum. noise_ell_path (str): Path to the file containing the ells for the noise power spectra. fid_pos_pos_dir (str): Path to the directory containing the fiducial theory position-position power spectra, used for the covariance. fid_she_she_dir (str): Path to the directory containing the fiducial theory shear-shear power spectra. fid_pos_she_dir (str): Path to the directory containing the fiducial theory position-shear power spectra. lmax (int): Maximum l to use in the likelihood. leff_path (str, optional): Path to ell-ell_effective mapping, to replace each l with its corresponding l_eff when calculating the covariance. """ print(f'Starting at {time.strftime("%c")}') # Setup the likelihood modules print(f'Setting up likelihood module 1/2 at {time.strftime("%c")}') config_w = like_w.setup(n_zbin, obs_pos_pos_dir, obs_she_she_dir, obs_pos_she_dir, pos_nl_path, she_nl_path, noise_ell_path, lmax, leff_path=leff_path) print(f'Setting up likelihood module 2/2 at {time.strftime("%c")}') config_g = like_g.setup(n_zbin, obs_pos_pos_dir, obs_she_she_dir, obs_pos_she_dir, pos_nl_path, she_nl_path, noise_ell_path, fid_pos_pos_dir, fid_she_she_dir, fid_pos_she_dir, lmax, leff_path=leff_path) print(f'Setup complete at {time.strftime("%c")}') # Loop over every input directory source_dirs = glob.glob(os.path.join(grid_dir, '_[0-9]*/')) n_dirs = len(source_dirs) if n_dirs == 0: warnings.warn(f'No matching directories. Terminating at {time.strftime("%c")}') return n_params = len(varied_params) if n_params == 0: warnings.warn(f'No parameters specified. Terminating at {time.strftime("%c")}') return first_dir = True res = [] for i, source_dir in enumerate(source_dirs): print(f'Calculating likelihood {i + 1} / {n_dirs} at {time.strftime("%c")}', flush=True) # Extract cosmological parameters params = [None]*n_params values_path = os.path.join(source_dir, 'cosmological_parameters/values.txt') with open(values_path) as f: for line in f: for param_idx, param in enumerate(varied_params): param_str = f'{param} = ' if param_str in line: params[param_idx] = float(line[len(param_str):]) err_str = f'Not all parameters in varied_params found in {values_path}' assert np.all([param is not None for param in params]), err_str # Check the ells for consistency if first_dir: ells_pos = np.loadtxt(os.path.join(source_dir, 'galaxy_cl/ell.txt')) ells_she = np.loadtxt(os.path.join(source_dir, 'shear_cl/ell.txt')) ells_pos_she = np.loadtxt(os.path.join(source_dir, 'galaxy_shear_cl/ell.txt')) assert np.allclose(ells_pos, ells_she) assert np.allclose(ells_pos, ells_pos_she) first_dir = False else: ells_pos_test = np.loadtxt(os.path.join(source_dir, 'galaxy_cl/ell.txt')) ells_she_test = np.loadtxt(os.path.join(source_dir, 'shear_cl/ell.txt')) ells_pos_she_test = np.loadtxt(os.path.join(source_dir, 'galaxy_shear_cl/ell.txt')) assert np.allclose(ells_pos, ells_pos_test) assert np.allclose(ells_she, ells_she_test) assert np.allclose(ells_pos_she, ells_pos_she_test) # Load theory Cls pos_pos_dir = os.path.join(source_dir, 'galaxy_cl/') she_she_dir = os.path.join(source_dir, 'shear_cl/') pos_she_dir = os.path.join(source_dir, 'galaxy_shear_cl/') theory_cls = like_w.load_cls(n_zbin, pos_pos_dir, she_she_dir, pos_she_dir) # Evaluate likelihoods log_like_wish = like_w.execute(ells_pos, theory_cls, config_w) log_like_gauss = like_g.execute(ells_pos, theory_cls, config_g) # Store cosmological params & likelihood res.append([*params, log_like_wish, log_like_gauss]) print() # Save results to file res_grid = np.asarray(res) param_names = ' '.join(varied_params) header = f'Output from {__file__}.run_likes_cl_wishart_gauss for input grid {grid_dir} at {time.strftime("%c")} \n' header += f'{param_names} log_like_wishart log_like_gauss' np.savetxt(save_path, res_grid, header=header) print('Saved ' + save_path) print(f'Done at {time.strftime("%c")}', flush=True) def max_like_1d(theory_filemask, obs_filemask, varied_param, save_dir, batch_size, n_zbin, fid_dir, pos_subdir, she_subdir, pos_she_subdir, ell_filename, pos_nl_path, she_nl_path, noise_ell_path, lmax, lmin): """ Run Wishart and Gaussian likelihoods for a single parameter repeatedly for many observations, and save a text file with the maximum likelihood parameter values. Designed to process output from simulation.sim_cls_fullsky. Args: theory_filemask (str): Filemask for subdirectories of a 1D CosmoSIS output grid to iterate over. obs_filemask (str): Filemask for observations to iterate over. varied_param (str): Name of the parameter being varied, as it appears in the cosmological_parameters/values.txt file. save_dir (str): Path to directory to save output to. batch_size (int): Number of observations per batch, where one text file is output per batch. n_zbin (int): Number of redshift bins. fid_dir (str): Path to directory containing fiducial power spectra, for Gaussian covariance. pos_subdir (str): Name of the sub-directory containing position-position power spectra. she_subdir (str): Name of the sub-directory containing shear-shear power spectra. pos_she_subdir (str): Name of the sub-directory containing position-shear power spectra. ell_filename (str): Filename containing ells within each sub-directory. pos_nl_path (str): Path to position noise power spectrum. she_nl_path (str): Path to shear noise power spectrum. noise_ell_path (str): Path to noise ells. lmax (int): Maximum ell for likelihood. lmin (int): Minimum ell for likelihood. """ # Calculate some useful quantities n_field = 2 * n_zbin n_spec = n_field * (n_field + 1) // 2 n_ell = lmax - lmin + 1 # Calculate ell range ell = np.arange(lmin, lmax + 1) # Load fiducial ells and Cls, and trim to correct ell range fid_pos_pos_dir = os.path.join(fid_dir, pos_subdir) fid_she_she_dir = os.path.join(fid_dir, she_subdir) fid_pos_she_dir = os.path.join(fid_dir, pos_she_subdir) # Check ells for consistency fid_pos_ell = np.loadtxt(os.path.join(fid_pos_pos_dir, ell_filename)) fid_she_ell = np.loadtxt(os.path.join(fid_she_she_dir, ell_filename)) fid_pos_she_ell = np.loadtxt(os.path.join(fid_pos_she_dir, ell_filename)) assert np.allclose(fid_pos_ell, fid_she_ell) assert np.allclose(fid_pos_ell, fid_pos_she_ell) assert min(fid_pos_ell) <= lmin assert max(fid_pos_ell) >= lmax # Load fiducial Cls and trim to correct ell range fid_lmin_in = int(min(fid_pos_ell)) fid_cl = like_w.load_cls(n_zbin, fid_pos_pos_dir, fid_she_she_dir, fid_pos_she_dir, lmax, fid_lmin_in)[:, lmin:] assert fid_cl.shape == (n_spec, n_ell) # Calculate scaling factor used for numerical precision and apply to fiducial Cls scaling = 10 ** (2 + np.ceil(-np.log10(np.amax(fid_cl)))) fid_cl *= scaling # Load noise ells and cls, and trim to correct ell range noise_ell = np.loadtxt(noise_ell_path) pos_nl = np.loadtxt(pos_nl_path) she_nl = np.loadtxt(she_nl_path) assert len(noise_ell) == len(pos_nl) assert len(noise_ell) == len(she_nl) assert min(noise_ell) <= lmin assert max(noise_ell) >= lmax nl_idxs = (noise_ell >= lmin) & (noise_ell <= lmax) pos_nl = pos_nl[nl_idxs] she_nl = she_nl[nl_idxs] # Convert noise cls to matrices, nonzero only for auto-spectra pos_nl *= scaling she_nl *= scaling nl_nonzero = np.array([pos_nl, she_nl]*n_zbin) nl_zero = np.zeros((n_spec - n_field, n_ell)) nl = np.concatenate((nl_nonzero, nl_zero)) nl_mats = like_w.cl_matrix(nl, n_field) nl = nl.t # Calculate inverse covariance matrix from fiducial cls + noise inv_cov = like_g.cl_invcov(ell, fid_cl.t, nl, n_field) assert inv_cov.shape == (n_ell, n_spec, n_spec) # Load theory cls and parameter values theory_dirs = glob.glob(theory_filemask) n_theory = len(theory_dirs) param_vals = np.full(n_theory, np.nan) param_str = f'{varied_param} = ' theory_cls = np.full((n_theory, n_ell, n_spec), np.nan) theory_mats = np.full((n_theory, n_ell, n_field, n_field), np.nan) for theory_idx, theory_dir in enumerate(theory_dirs): pos_pos_dir = os.path.join(theory_dir, pos_subdir) she_she_dir = os.path.join(theory_dir, she_subdir) pos_she_dir = os.path.join(theory_dir, pos_she_subdir) # Extract parameter value with open(os.path.join(theory_dir, 'cosmological_parameters/values.txt')) as f: for line in f: if param_str in line: param_vals[theory_idx] = float(line[len(param_str):]) break # Check ells for consistency pos_ell = np.loadtxt(os.path.join(pos_pos_dir, ell_filename)) she_ell = np.loadtxt(os.path.join(she_she_dir, ell_filename)) pos_she_ell = np.loadtxt(os.path.join(pos_she_dir, ell_filename)) assert np.allclose(pos_ell, she_ell) assert np.allclose(pos_ell, pos_she_ell) assert min(pos_ell) <= lmin assert max(pos_ell) >= lmax # Load theory cls, trim to correct ell range and convert to matrices lmin_in = int(min(pos_ell)) theory_cl = like_w.load_cls(n_zbin, pos_pos_dir, she_she_dir, pos_she_dir, lmax, lmin_in)[:, lmin:] assert theory_cl.shape == (n_spec, n_ell) theory_cl *= scaling theory_cls[theory_idx] = theory_cl.t theory_mats[theory_idx] = like_w.cl_matrix(theory_cl, n_field) assert np.all(np.isfinite(param_vals)) assert np.all(np.isfinite(theory_cls)) assert np.all(np.isfinite(theory_mats)) # Loop over obs files matching filemask obs_file_paths = glob.glob(obs_filemask) n_obs_file = len(obs_file_paths) for obs_file_idx, obs_file_path in enumerate(obs_file_paths): print(f'opening obs file {obs_file_idx} / {n_obs_file} at {time.strftime("%c")}') # Load file and apply scaling with np.load(obs_file_path) as obs_file: obs_cl = obs_file['obs_cl'] n_real = obs_cl.shape[0] assert obs_cl.shape[1:] == (n_spec, n_ell) obs_cl *= scaling n_batch = n_real // batch_size assert n_real % n_batch == 0 # Loop over observations within batches for batch_idx in range(n_batch): print(f'obs file {obs_file_idx}: starting batch {batch_idx} / {n_batch} at {time.strftime("%c")}') maxlike_paramval_w = np.full(batch_size, np.nan) maxlike_paramval_g = np.full(batch_size, np.nan) for obs_idx_within_batch in range(batch_size): obs_idx = batch_idx * batch_size + obs_idx_within_batch print(f'obs file {obs_file_idx}; batch {batch_idx}: starting obs {obs_idx_within_batch} / {batch_size}' f' at {time.strftime("%c")}') # Calculate obs Cl matrices obs_mats = like_w.cl_matrix(obs_cl[obs_idx], n_field) # Loop over theory directories and calculate the two log-likelihoods loglike_w = np.full(n_theory, np.nan) loglike_g = np.full(n_theory, np.nan) for i, (theory_cl, theory_mat) in enumerate(zip(theory_cls, theory_mats)): loglike_w[i] = like_w.joint_log_likelihood(ell, theory_mat, nl_mats, obs_mats, lmax) loglike_g[i] = like_g.joint_log_likelihood(ell, theory_cl, nl, obs_cl[obs_idx].t, inv_cov, lmax) assert np.all(np.isfinite(loglike_w)) assert np.all(np.isfinite(loglike_g)) # Find the param value corresponding to max of each likelihood maxlike_paramval_w[obs_idx_within_batch] = param_vals[np.argmax(loglike_w)] maxlike_paramval_g[obs_idx_within_batch] = param_vals[np.argmax(loglike_g)] # Save batch results to file assert np.all(np.isfinite(maxlike_paramval_w)) assert np.all(np.isfinite(maxlike_paramval_g)) save_path = os.path.join(save_dir, f'{obs_file_idx}_{batch_idx}.txt') to_save = np.column_stack((maxlike_paramval_w, maxlike_paramval_g)) header = 'wishart_posterior_max gaussian_posterior_max' np.savetxt(save_path, to_save, header=header) print(f'Saved {save_path} at {time.strftime("%c")}') print(f'Closing obs file {obs_file_idx} at {time.strftime("%c")}') print(f'Done at {time.strftime("%c")}') def post_mean_std_1d(theory_filemask, obs_filemask, varied_param, save_dir, batch_size, n_zbin, fid_dir, pos_subdir, she_subdir, pos_she_subdir, ell_filename, pos_nl_path, she_nl_path, noise_ell_path, lmax, lmin): """ Run Wishart and Gaussian likelihoods for a single parameter repeatedly for many observations, and save a text file with the posterior mean and standard deviation for each observation. Designed to process output from simulation.sim_cls_fullsky. Args: theory_filemask (str): Filemask for subdirectories of a 1D CosmoSIS output grid to iterate over. obs_filemask (str): Filemask for observations to iterate over. varied_param (str): Name of the parameter being varied, as it appears in the cosmological_parameters/values.txt file. save_dir (str): Path to directory to save output to. batch_size (int): Number of observations per batch, where one text file is output per batch. n_zbin (int): Number of redshift bins. fid_dir (str): Path to directory containing fiducial power spectra, for Gaussian covariance. pos_subdir (str): Name of the sub-directory containing position-position power spectra. she_subdir (str): Name of the sub-directory containing shear-shear power spectra. pos_she_subdir (str): Name of the sub-directory containing position-shear power spectra. ell_filename (str): Filename containing ells within each sub-directory. pos_nl_path (str): Path to position noise power spectrum. she_nl_path (str): Path to shear noise power spectrum. noise_ell_path (str): Path to noise ells. lmax (int): Maximum ell for likelihood. lmin (int): Minimum ell for likelihood. """ # Calculate some useful quantities n_field = 2 * n_zbin n_spec = n_field * (n_field + 1) // 2 n_ell = lmax - lmin + 1 # Calculate ell range ell = np.arange(lmin, lmax + 1) # Load fiducial ells and Cls, and trim to correct ell range fid_pos_pos_dir = os.path.join(fid_dir, pos_subdir) fid_she_she_dir = os.path.join(fid_dir, she_subdir) fid_pos_she_dir = os.path.join(fid_dir, pos_she_subdir) # Check ells for consistency fid_pos_ell = np.loadtxt(os.path.join(fid_pos_pos_dir, ell_filename)) fid_she_ell = np.loadtxt(os.path.join(fid_she_she_dir, ell_filename)) fid_pos_she_ell = np.loadtxt(os.path.join(fid_pos_she_dir, ell_filename)) assert np.allclose(fid_pos_ell, fid_she_ell) assert np.allclose(fid_pos_ell, fid_pos_she_ell) assert min(fid_pos_ell) <= lmin assert max(fid_pos_ell) >= lmax # Load fiducial Cls and trim to correct ell range fid_lmin_in = int(min(fid_pos_ell)) fid_cl = like_w.load_cls(n_zbin, fid_pos_pos_dir, fid_she_she_dir, fid_pos_she_dir, lmax, fid_lmin_in)[:, lmin:] assert fid_cl.shape == (n_spec, n_ell) # Calculate scaling factor used for numerical precision and apply to fiducial Cls scaling = 10 ** (2 + np.ceil(-np.log10(np.amax(fid_cl)))) fid_cl *= scaling # Load noise ells and cls, and trim to correct ell range noise_ell = np.loadtxt(noise_ell_path) pos_nl = np.loadtxt(pos_nl_path) she_nl = np.loadtxt(she_nl_path) assert len(noise_ell) == len(pos_nl) assert len(noise_ell) == len(she_nl) assert min(noise_ell) <= lmin assert max(noise_ell) >= lmax nl_idxs = (noise_ell >= lmin) & (noise_ell <= lmax) pos_nl = pos_nl[nl_idxs] she_nl = she_nl[nl_idxs] # Convert noise cls to matrices, nonzero only for auto-spectra pos_nl *= scaling she_nl *= scaling nl_nonzero = np.array([pos_nl, she_nl]*n_zbin) nl_zero = np.zeros((n_spec - n_field, n_ell)) nl = np.concatenate((nl_nonzero, nl_zero)) nl_mats = like_w.cl_matrix(nl, n_field) nl = nl.t # Calculate inverse covariance matrix from fiducial cls + noise inv_cov = like_g.cl_invcov(ell, fid_cl.t, nl, n_field) assert inv_cov.shape == (n_ell, n_spec, n_spec) # Load theory cls and parameter values theory_dirs = glob.glob(theory_filemask) n_theory = len(theory_dirs) param_vals = np.full(n_theory, np.nan) param_str = f'{varied_param} = ' theory_cls = np.full((n_theory, n_ell, n_spec), np.nan) theory_mats = np.full((n_theory, n_ell, n_field, n_field), np.nan) for theory_idx, theory_dir in enumerate(theory_dirs): pos_pos_dir = os.path.join(theory_dir, pos_subdir) she_she_dir = os.path.join(theory_dir, she_subdir) pos_she_dir = os.path.join(theory_dir, pos_she_subdir) # Extract parameter value with open(os.path.join(theory_dir, 'cosmological_parameters/values.txt')) as f: for line in f: if param_str in line: param_vals[theory_idx] = float(line[len(param_str):]) break # Check ells for consistency pos_ell = np.loadtxt(os.path.join(pos_pos_dir, ell_filename)) she_ell = np.loadtxt(os.path.join(she_she_dir, ell_filename)) pos_she_ell = np.loadtxt(os.path.join(pos_she_dir, ell_filename)) assert np.allclose(pos_ell, she_ell) assert np.allclose(pos_ell, pos_she_ell) assert min(pos_ell) <= lmin assert max(pos_ell) >= lmax # Load theory cls, trim to correct ell range and convert to matrices lmin_in = int(min(pos_ell)) theory_cl = like_w.load_cls(n_zbin, pos_pos_dir, she_she_dir, pos_she_dir, lmax, lmin_in)[:, lmin:] assert theory_cl.shape == (n_spec, n_ell) theory_cl *= scaling theory_cls[theory_idx] = theory_cl.t theory_mats[theory_idx] = like_w.cl_matrix(theory_cl, n_field) assert np.all(np.isfinite(param_vals)) assert np.all(np.isfinite(theory_cls)) assert np.all(np.isfinite(theory_mats)) # Calculate parameter step size, used to normalise posterior param_steps = np.diff(np.unique(param_vals)) param_step = np.mean(param_steps) assert np.allclose(param_steps, param_step) # Loop over obs files matching filemask obs_file_paths = glob.glob(obs_filemask) n_obs_file = len(obs_file_paths) for obs_file_idx, obs_file_path in enumerate(obs_file_paths): print(f'opening obs file {obs_file_idx} / {n_obs_file} at {time.strftime("%c")}') # Load file and apply scaling with np.load(obs_file_path) as obs_file: obs_cl = obs_file['obs_cl'] n_real = obs_cl.shape[0] assert obs_cl.shape[1:] == (n_spec, n_ell) obs_cl *= scaling n_batch = n_real // batch_size assert n_real % n_batch == 0 # Loop over observations within batches for batch_idx in range(n_batch): print(f'obs file {obs_file_idx}: starting batch {batch_idx} / {n_batch} at {time.strftime("%c")}') means_w = np.full(batch_size, np.nan) means_g = np.full(batch_size, np.nan) stds_w = np.full(batch_size, np.nan) stds_g = np.full(batch_size, np.nan) for obs_idx_within_batch in range(batch_size): obs_idx = batch_idx * batch_size + obs_idx_within_batch print(f'obs file {obs_file_idx}; batch {batch_idx}: starting obs {obs_idx_within_batch} / {batch_size}' f' at {time.strftime("%c")}') # Calculate obs Cl matrices obs_mats = like_w.cl_matrix(obs_cl[obs_idx], n_field) # Loop over theory directories and calculate the two log-likelihoods loglike_w = np.full(n_theory, np.nan) loglike_g = np.full(n_theory, np.nan) for i, (theory_cl, theory_mat) in enumerate(zip(theory_cls, theory_mats)): loglike_w[i] = like_w.joint_log_likelihood(ell, theory_mat, nl_mats, obs_mats, lmax) loglike_g[i] = like_g.joint_log_likelihood(ell, theory_cl, nl, obs_cl[obs_idx].t, inv_cov, lmax) assert np.all(np.isfinite(loglike_w)) assert np.all(np.isfinite(loglike_g)) # Convert log-likelihood to normalised posterior post_w = posteriors.log_like_to_post(loglike_w, param_step) post_g = posteriors.log_like_to_post(loglike_g, param_step) # Integrate to find the mean and variance mean_w = np.sum(param_vals * post_w) * param_step mean_g = np.sum(param_vals * post_g) * param_step var_w = np.sum(param_vals ** 2 * post_w) * param_step - mean_w ** 2 var_g = np.sum(param_vals ** 2 * post_g) * param_step - mean_g ** 2 # Store mean and standard deviation means_w[obs_idx_within_batch] = mean_w means_g[obs_idx_within_batch] = mean_g stds_w[obs_idx_within_batch] = np.sqrt(var_w) stds_g[obs_idx_within_batch] = np.sqrt(var_g) # Save batch results to file assert np.all(np.isfinite(means_w)) assert np.all(np.isfinite(means_g)) assert np.all(np.isfinite(stds_w)) assert np.all(np.isfinite(stds_g)) save_path = os.path.join(save_dir, f'{obs_file_idx}_{batch_idx}.txt') to_save = np.column_stack((means_w, means_g, stds_w, stds_g)) header = 'mean_wishart mean_gauss std_wishart std_gauss' np.savetxt(save_path, to_save, header=header) print(f'Saved {save_path} at {time.strftime("%c")}') print(f'Closing obs file {obs_file_idx} at {time.strftime("%c")}') print(f'Done at {time.strftime("%c")}')
{ "alphanum_fraction": 0.6626938541, "author": null, "avg_line_length": 49.3201133144, "converted": null, "ext": "py", "file": null, "hexsha": "d70409d4b2434ebd8951bb380daea49aad01cd3e", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2022-02-03T14:10:49.000Z", "max_forks_repo_forks_event_min_datetime": "2022-02-03T14:10:49.000Z", "max_forks_repo_head_hexsha": "91fb635f9360340555eb0c920925f37fda69a8a5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "robinupham/gaussian_cl_likelihood", "max_forks_repo_path": "python/run_likelihoods.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "91fb635f9360340555eb0c920925f37fda69a8a5", "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": "robinupham/gaussian_cl_likelihood", "max_issues_repo_path": "python/run_likelihoods.py", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "91fb635f9360340555eb0c920925f37fda69a8a5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "robinupham/gaussian_cl_likelihood", "max_stars_repo_path": "python/run_likelihoods.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 8777, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 34820 }
"""Test the timeseries divider transformer.""" import numpy as np import numpy.testing as nt import pandas as pd import pandas.testing as pt import pytest import src.preprocessing as pp import src.preprocessing.divide_dataset as dd def test_it_raises_wrong_date_col(): l = 1000 t = 750 s = 250 with pytest.raises(ValueError): dd.TimeseriesDateIntervalComputer('', l, s, t) with pytest.raises(TypeError): dd.TimeseriesDateIntervalComputer(1, l, s, t) with pytest.raises(TypeError): dd.TimeseriesDateIntervalComputer(['date'], l, s, t) with pytest.raises(TypeError): dd.TimeseriesDateIntervalComputer('date', 2.5, s, t) with pytest.raises(TypeError): dd.TimeseriesDateIntervalComputer('date', l, 2.5, t) with pytest.raises(ValueError): dd.TimeseriesDateIntervalComputer('date', -4, s, t) with pytest.raises(ValueError): dd.TimeseriesDateIntervalComputer('date', l, 0, t) with pytest.raises(TypeError): dd.TimeseriesDateIntervalComputer('date', l, s, '250') with pytest.raises(ValueError): dd.TimeseriesDateIntervalComputer('date', l, s, l)
{ "alphanum_fraction": 0.6925704526, "author": null, "avg_line_length": 26.6136363636, "converted": null, "ext": "py", "file": null, "hexsha": "bcf9c8357f9f884dedf6e34c7b20425655b8bf54", "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": "6d212f22ed97af9b9e59b6c2e77198e472c3f628", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "PieCampi/dl-toolkit", "max_forks_repo_path": "tests/test_timeseries_interval_computer.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "6d212f22ed97af9b9e59b6c2e77198e472c3f628", "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": "PieCampi/dl-toolkit", "max_issues_repo_path": "tests/test_timeseries_interval_computer.py", "max_line_length": 62, "max_stars_count": null, "max_stars_repo_head_hexsha": "6d212f22ed97af9b9e59b6c2e77198e472c3f628", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "PieCampi/dl-toolkit", "max_stars_repo_path": "tests/test_timeseries_interval_computer.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 288, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1171 }
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2003 RiskMap srl Copyright (C) 2015 CompatibL This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #ifndef cl_adjoint_term_structure_impl_hpp #define cl_adjoint_term_structure_impl_hpp #pragma once #include <ql/quantlib.hpp> #include "utilities.hpp" #include "adjointtermstructuretest.hpp" #include "adjointtestutilities.hpp" #include "adjointtestbase.hpp" #include <boost/make_shared.hpp> using namespace QuantLib; using namespace boost::unit_test_framework; #define OUTPUT_FOLDER_NAME "AdjointTermStructure" namespace { struct RateDiscount { static std::deque<std::string > get_columns() { static std::deque<std::string > columns = { "Swap Rate", "Base Discount", "Discount", "Implied Discount" }; return columns; } template <typename stream_type> friend inline stream_type& operator << (stream_type& stm, RateDiscount& v) { stm << v.inputRate_ << ";" << v.baseDiscount_ << ";" << v.discount_ << ";" << v.impliedDiscount_ << std::endl; return stm; } Real inputRate_; Real baseDiscount_; Real discount_; Real impliedDiscount_; }; struct RateConsistency { static std::deque<std::string > get_columns() { static std::deque<std::string > columns = { "Swap Rate", "" }; return columns; } template <typename stream_type> friend inline stream_type& operator << (stream_type& stm, RateConsistency& v) { stm << v.inputRate_ << ";" << v.functionValue_ << std::endl; return stm; } Real inputRate_; Real functionValue_; }; struct Datum { Integer n; TimeUnit units; Rate rate; }; struct TermStructureData { TermStructureData() : calendar_(TARGET()) , settlementDays_(2) { } std::vector<Datum> createSwapData(std::vector<Real> rateValues) { Size rateSize = rateValues.size(); std::vector<Datum> swapData(rateSize); for (Integer i = 0; i < rateSize; i++) { swapData[i] = { i * 3 + 10, Months, rateValues[i] }; } return swapData; } void setTermStructure(std::vector<Datum> swapData) { std::vector<Datum> depositData = { { 1, Months, 4.581 }, { 2, Months, 4.573 }, { 3, Months, 4.557 }, { 6, Months, 4.496 }, { 9, Months, 4.490 } }; Date today = calendar_.adjust(Date::todaysDate()); Settings::instance().evaluationDate() = today; Date settlement = calendar_.advance(today, settlementDays_, Days); Size deposits = depositData.size(), swaps = swapData.size(); std::vector<boost::shared_ptr<RateHelper> > instruments(deposits + swaps); for (Size i = 0; i < deposits; i++) { instruments[i] = boost::make_shared<DepositRateHelper>( depositData[i].rate / 100 , depositData[i].n*depositData[i].units , settlementDays_ , calendar_ , ModifiedFollowing , true , Actual360()); } boost::shared_ptr<IborIndex> index(new IborIndex("dummy" , 6 * Months , settlementDays_ , Currency() , calendar_ , ModifiedFollowing , false , Actual360())); for (Size i = 0; i < swaps; ++i) { instruments[i + deposits] = boost::make_shared<SwapRateHelper>( swapData[i].rate / 100 , swapData[i].n*swapData[i].units , calendar_ , Annual , Unadjusted , Thirty360() , index); } termStructure_ = boost::make_shared<PiecewiseYieldCurve<Discount, LogLinear>>(settlement, instruments, Actual360()); } std::vector<double> getDoubleVector(Size size) { std::vector<double> vec = { 0.50, 0.69, 0.57, 0.27, 0.48, 0.85, 0.07, 0.74, 0.47, 0.78, 0.07, 0.68 , 0.92, 0.10, 0.93, 0.33, 0.20, 0.40, 0.04, 0.73, 0.91, 0.19, 0.50, 0.87 , 0.81, 0.34, 0.10, 0.52, 0.43, 0.54, 0.34, 0.31, 0.75, 0.51, 0.30, 0.69 , 0.36, 0.16, 0.90, 0.32, 0.40, 0.20, 0.64, 0.64, 0.72, 0.90, 0.78, 0.74 , 0.27, 0.39, 0.24, 0.60, 0.88, 0.20, 0.97, 0.33, 0.59, 0.52, 0.91, 0.77 , 0.73, 0.63, 0.89, 0.88, 0.54, 0.72, 0.92, 0.32, 0.09, 0.56, 0.68, 0.91 , 0.82, 0.72, 0.35, 0.41, 0.42, 0.23, 0.92, 0.25, 0.67, 0.35, 0.58, 0.52 , 0.65, 0.74, 0.19, 0.75, 0.06, 0.08, 0.51, 0.97, 0.10, 0.99, 0.32, 0.40 , 0.69, 0.71, 0.83, 0.64, 0.08, 0.61, 0.56, 0.27, 0.15, 0.69, 0.70, 0.89 , 0.52, 0.15 }; return std::vector<double>(vec.begin(), vec.begin() + size); } std::vector<Real> calculateZeroValue(std::vector<Datum> swapData) { setTermStructure(swapData); Handle<Quote> spread(boost::make_shared<SimpleQuote>(0.01)); boost::shared_ptr<YieldTermStructure> spreaded( new ZeroSpreadedTermStructure(Handle<YieldTermStructure>(termStructure_), spread)); Date testDate = termStructure_->referenceDate() + 5 * Years; DayCounter resultDayCounter = termStructure_->dayCounter(); Rate zero = termStructure_->zeroRate(testDate, resultDayCounter, Continuous, NoFrequency); return std::vector<Real>(1, zero); } std::vector<Real> calculateForwardValue(std::vector<Datum> swapData) { setTermStructure(swapData); Handle<Quote> spread(boost::shared_ptr<Quote>(new SimpleQuote(0.01))); boost::shared_ptr<YieldTermStructure> spreaded( new ForwardSpreadedTermStructure(Handle<YieldTermStructure>(termStructure_), spread)); Date testDate = termStructure_->referenceDate() + 5 * Years; DayCounter resultDayCounter = termStructure_->dayCounter(); Rate forward = termStructure_->forwardRate(testDate, testDate, resultDayCounter, Continuous, NoFrequency); return std::vector<Real>(1, forward); } std::vector<Real> calculateDiscountValues(std::vector<Datum> swapData) { setTermStructure(swapData); Date today = Settings::instance().evaluationDate(); Date newToday = today + 3 * Years; Date newSettlement = calendar_.advance(newToday, settlementDays_, Days); Date testDate = newSettlement + 5 * Years; boost::shared_ptr<YieldTermStructure> implied( new ImpliedTermStructure(Handle<YieldTermStructure>(termStructure_), newSettlement)); DiscountFactor baseDiscount = termStructure_->discount(newSettlement); DiscountFactor discount = termStructure_->discount(testDate); DiscountFactor impliedDiscount = implied->discount(testDate); return std::vector<Real>{ baseDiscount, discount, impliedDiscount }; } template <class Func> void calculateFinDiff(std::vector<Real>& rateValues , Real h , std::vector<Real>& sf_Finite , Func getValue) { Size sizeX = rateValues.size(); std::vector<Real> value = getValue(createSwapData(rateValues)); Size sizeY = value.size(); sf_Finite.resize(sizeX * sizeY); for (Size i = 0; i < sizeX; i++) { rateValues[i] += h; std::vector<Real> finiteValue = getValue(createSwapData(rateValues)); rateValues[i] -= h; for (Size j = 0; j < sizeY; j++) { sf_Finite[sizeX*j + i] = (finiteValue[j] - value[j]) / h; } } } // Global data. Calendar calendar_; Natural settlementDays_; boost::shared_ptr<YieldTermStructure> termStructure_; // Cleanup. SavedSettings backup_; }; struct ZSpreadedTestData : public TermStructureData { struct Test : public cl::AdjointTest<Test> { Test(Size size, ZSpreadedTestData* data) : size_(size) , data_(data) , rate_(size) , iterNumFactor_(10) { setLogger(&data_->outPerform_); std::vector<double> doubleRate = data_->getDoubleVector(size); for (Size i = 0; i < size; i++) rate_[i] = doubleRate[i]; } Size indepVarNumber() { return size_; } Size depVarNumber() { return 1; } Size minPerfIteration() { return iterNumFactor_; } void recordTape() { cl::Independent(rate_); calculateZeroValue(); f_ = std::make_unique<cl::tape_function<double>>(rate_, zeroValue_); } // Calculates total calibration error. void calculateZeroValue() { zeroValue_ = data_->calculateZeroValue(data_->createSwapData(rate_)); } // Calculates derivatives using finite difference method. void calcAnalytical() { double h = 1.0e-6; // shift for finite diff. method analyticalResults_.resize(size_); data_->calculateFinDiff(rate_ , h , analyticalResults_ , [this] (std::vector<Datum>& v) -> std::vector<Real> { return data_->calculateZeroValue(v); }); } double relativeTol() const { return 1e-2; } double absTol() const { return 1e-5; } Size size_; Size iterNumFactor_; ZSpreadedTestData* data_; std::vector<cl::tape_double> rate_; std::vector<cl::tape_double> zeroValue_; }; ZSpreadedTestData() : TermStructureData() , outPerform_(OUTPUT_FOLDER_NAME "//ConsistencyZeroSpreadedTermStructure" , { { "filename", "AdjointPerformance" } , { "not_clear", "Not" } , { "cleanlog", "true" } , { "title", "Zero rate differentiation performance with respect to swap rate" } , { "xlabel", "Number of swap rates" } , { "ylabel", "Time (s)" } , { "smooth", "default" } , { "line_box_width", "-5" } }) , outAdjoint_(OUTPUT_FOLDER_NAME "//ConsistencyZeroSpreadedTermStructure" , { { "filename", "Adjoint" } , { "not_clear", "Not" } , { "cleanlog", "false" } , { "title", " Zero rate adjoint differentiation performance with respect to swap rate" } , { "xlabel", "Number of swap rates" } , { "smooth", "default" } , { "ylabel", "Time (s)" } }) , outSize_(OUTPUT_FOLDER_NAME "//ConsistencyZeroSpreadedTermStructure" , { { "filename", "TapeSize" } , { "not_clear", "Not" } , { "cleanlog", "false" } , { "title", "Tape size dependence on number of swap rates" } , { "xlabel", "Number of swap rates" } , { "ylabel", "Memory(MB)" } }) , out_(OUTPUT_FOLDER_NAME "//ConsistencyZeroSpreadedTermStructure//output" , { { "filename", "zeroRateOnSwapRate" } , { "not_clear", "Not" } , { "cleanlog", "false" } , { "title", "Zero Rate dependence on Swap Rate" } , { "ylabel", "Zero Rate" } }) #if defined CL_GRAPH_GEN , pointNo_(80) , iterNo_(80) , step_(1) #else , pointNo_(1) , iterNo_(1) , step_(1) #endif { } bool makeOutput() { bool ok = true; if (pointNo_ > 0) { ok &= recordDependencePlot(); } ok &= cl::recordPerformance(*this, iterNo_, step_); return ok; } std::shared_ptr<Test> getTest(size_t size) { return std::make_shared<Test>(size + 30, this); } // Makes plots for strike sensitivity dependence. bool recordDependencePlot() { std::vector<RateConsistency> outData(pointNo_); auto test = getTest(pointNo_); Rate rate = 0.0; for (Size i = 0; i < pointNo_; rate += 1.0, i++) { outData[i] = { rate / 100, test->data_->calculateZeroValue({ { 10, Years, rate } })[0] }; } out_ << outData; return true; } Size pointNo_; Size iterNo_; Size step_; cl::tape_empty_test_output outPerform_; cl::tape_empty_test_output outAdjoint_; cl::tape_empty_test_output outSize_; cl::tape_empty_test_output out_; }; typedef ZSpreadedTestData::Test ZSpreadedTest; struct FSpreadedTestData : public TermStructureData { struct Test : public cl::AdjointTest<Test> { Test(Size size, FSpreadedTestData* data) : size_(size) , data_(data) , rate_(size) , iterNumFactor_(10) { setLogger(&data_->outPerform_); std::vector<double> doubleRate = data_->getDoubleVector(size); for (Size i = 0; i < size; i++) rate_[i] = doubleRate[i]; } Size indepVarNumber() { return size_; } Size depVarNumber() { return 1; } Size minPerfIteration() { return iterNumFactor_; } void recordTape() { cl::Independent(rate_); calculateForwardValue(); f_ = std::make_unique<cl::tape_function<double>>(rate_, forwardValue_); } // Calculates total calibration error. void calculateForwardValue() { forwardValue_ = data_->calculateForwardValue(data_->createSwapData(rate_)); } // Calculates derivatives using finite difference method. void calcAnalytical() { double h = 1.0e-6; // shift for finite diff. method analyticalResults_.resize(size_); data_->calculateFinDiff(rate_ , h , analyticalResults_ , [this] (std::vector<Datum>& v) -> std::vector<Real> { return data_->calculateForwardValue(v); }); } double relativeTol() const { return 1e-2; } double absTol() const { return 1e-5; } Size size_; Size iterNumFactor_; FSpreadedTestData* data_; std::vector<cl::tape_double> rate_; std::vector<cl::tape_double> forwardValue_; }; FSpreadedTestData() : TermStructureData() , outPerform_(OUTPUT_FOLDER_NAME "//ConsistencyForwardSpreadedTermStructure" , { { "filename", "AdjointPerformance" } , { "not_clear", "Not" } , { "cleanlog", "true" } , { "title", "Forward rate differentiation performance with respect to swap rate" } , { "xlabel", "Number of swap rates" } , { "ylabel", "Time (s)" } , { "smooth", "default" } , { "line_box_width", "-5" } }) , outAdjoint_(OUTPUT_FOLDER_NAME "//ConsistencyForwardSpreadedTermStructure" , { { "filename", "Adjoint" } , { "not_clear", "Not" } , { "cleanlog", "false" } , { "title", " Forward rate adjoint differentiation performance with respect to swap rate" } , { "xlabel", "Number of swap rates" } , { "smooth", "default" } , { "ylabel", "Time (s)" } }) , outSize_(OUTPUT_FOLDER_NAME "//ConsistencyForwardSpreadedTermStructure" , { { "filename", "TapeSize" } , { "not_clear", "Not" } , { "cleanlog", "false" } , { "title", "Tape size dependence on number of swap rates" } , { "xlabel", "Number of swap rates" } , { "ylabel", "Memory(MB)" } }) , out_(OUTPUT_FOLDER_NAME "//ConsistencyForwardSpreadedTermStructure//output" , { { "filename", "forwardRateOnSwapRate" } , { "not_clear", "Not" } , { "cleanlog", "false" } , { "title", "Forward Rate dependence on Swap Rate" } , { "ylabel", "Forward Rate" } }) #if defined CL_GRAPH_GEN , pointNo_(80) , iterNo_(80) , step_(1) #else , pointNo_(1) , iterNo_(1) , step_(1) #endif { } bool makeOutput() { bool ok = true; if (pointNo_ > 0) { ok &= recordDependencePlot(); } ok &= cl::recordPerformance(*this, iterNo_, step_); return ok; } std::shared_ptr<Test> getTest(size_t size) { return std::make_shared<Test>(size + 30, this); } // Makes plots for strike sensitivity dependence. bool recordDependencePlot() { std::vector<RateConsistency> outData(pointNo_); auto test = getTest(pointNo_); Rate rate = 0.0; for (Size i = 0; i < pointNo_; rate += 1.0, i++) { outData[i] = { rate / 100, test->data_->calculateForwardValue({ { 10, Years, rate } })[0] }; } out_ << outData; return true; } Size pointNo_; Size iterNo_; Size step_; cl::tape_empty_test_output outPerform_; cl::tape_empty_test_output outAdjoint_; cl::tape_empty_test_output outSize_; cl::tape_empty_test_output out_; }; typedef FSpreadedTestData::Test FSpreadedTest; struct ImpliedTestData : public TermStructureData { struct Test : public cl::AdjointTest<Test> { static const CalcMethod default_method = other; Test(Size size, ImpliedTestData* data) : size_(size) , data_(data) , rate_(size) , iterNumFactor_(10) { setLogger(&data_->outPerform_); doubleRate_ = data_->getDoubleVector(size); std::copy(doubleRate_.begin(), doubleRate_.end(), rate_.begin()); } Size indepVarNumber() { return size_; } Size depVarNumber() { return 3; } Size minPerfIteration() { return iterNumFactor_; } void recordTape() { cl::Independent(rate_); calculateDiscountValues(); f_ = std::make_unique<cl::tape_function<double>>(rate_, discountValues_); } // Calculates total calibration error. void calculateDiscountValues() { discountValues_ = data_->calculateDiscountValues(data_->createSwapData(rate_)); } // Calculates derivatives using finite difference method. void calcAnalytical() { double h = 1.0e-6; // shift for finite diff. method analyticalResults_.resize(size_ * depVarNumber()); data_->calculateFinDiff(rate_ , h , analyticalResults_ , [this] (std::vector<Datum>& v) -> std::vector<Real> { return data_->calculateDiscountValues(v); }); } // Calculates derivatives using adjoint. void calcAdjoint() { adjointResults_ = f_->Jacobian(doubleRate_); } double relativeTol() const { return 1e-2; } double absTol() const { return 1e-5; } Size size_; Size iterNumFactor_; ImpliedTestData* data_; std::vector<double> doubleRate_; std::vector<cl::tape_double> rate_; std::vector<cl::tape_double> discountValues_; }; ImpliedTestData() : TermStructureData() , outPerform_(OUTPUT_FOLDER_NAME "//ConsistencyYieldTermStructure" , { { "filename", "AdjointPerformance" } , { "not_clear", "Not" } , { "cleanlog", "true" } , { "title", "Base discount, discount, implied discount\\ndifferentiation performance with respect to swap rate" } , { "xlabel", "Number of swap rates" } , { "ylabel", "Time (s)" } , { "smooth", "default" } , { "line_box_width", "-5" } }) , outAdjoint_(OUTPUT_FOLDER_NAME "//ConsistencyYieldTermStructure" , { { "filename", "Adjoint" } , { "not_clear", "Not" } , { "cleanlog", "false" } , { "title", "Base discount, discount, implied discount\\nadjoint differentiation performance with respect to swap rate" } , { "xlabel", "Number of swap rates" } , { "smooth", "default" } , { "ylabel", "Time (s)" } }) , outSize_(OUTPUT_FOLDER_NAME "//ConsistencyYieldTermStructure" , { { "filename", "TapeSize" } , { "not_clear", "Not" } , { "cleanlog", "false" } , { "title", "Tape size dependence on number of swap rates" } , { "xlabel", "Number of swap rates" } , { "ylabel", "Memory(MB)" } }) , out_(OUTPUT_FOLDER_NAME "//ConsistencyYieldTermStructure//output" , { { "filename", "discountOnSwapRate" } , { "not_clear", "Not" } , { "cleanlog", "false" } , { "title", "Discount values dependence on Swap Rate" } , { "ylabel", "Forward Rate" } }) #if defined CL_GRAPH_GEN , pointNo_(80) , iterNo_(80) , step_(1) #else , pointNo_(1) , iterNo_(1) , step_(1) #endif { } bool makeOutput() { bool ok = true; if (pointNo_ > 0) { ok &= recordDependencePlot(); } ok &= cl::recordPerformance(*this, iterNo_, step_); return ok; } std::shared_ptr<Test> getTest(size_t size) { return std::make_shared<Test>(size + 30, this); } // Makes plots for strike sensitivity dependence. bool recordDependencePlot() { std::vector<RateDiscount> outData(pointNo_); auto test = getTest(pointNo_); Rate rate = 0.0; for (Size i = 0; i < pointNo_; rate += 1.0, i++) { std::vector<Real> out = test->data_->calculateDiscountValues({ { 10, Years, rate } }); outData[i] = { rate / 100 , out[0] , out[1] , out[2] }; } out_ << outData; return true; } Size pointNo_; Size iterNo_; Size step_; cl::tape_empty_test_output outPerform_; cl::tape_empty_test_output outAdjoint_; cl::tape_empty_test_output outSize_; cl::tape_empty_test_output out_; }; typedef ImpliedTestData::Test ImpliedTest; } #endif
{ "alphanum_fraction": 0.5098116634, "author": null, "avg_line_length": 33.5456953642, "converted": null, "ext": "hpp", "file": null, "hexsha": "5e9a18907e307634d54bb320dcaf35d03e437db9", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 22, "max_forks_repo_forks_event_max_datetime": "2022-03-28T10:33:19.000Z", "max_forks_repo_forks_event_min_datetime": "2016-03-17T14:14:36.000Z", "max_forks_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "fduffy/QuantLibAdjoint", "max_forks_repo_path": "test-suite-adjoint/adjointtermstructureimpl.hpp", "max_issues_count": null, "max_issues_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "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": "fduffy/QuantLibAdjoint", "max_issues_repo_path": "test-suite-adjoint/adjointtermstructureimpl.hpp", "max_line_length": 130, "max_stars_count": 41, "max_stars_repo_head_hexsha": "d9d355db4f46824bb5e607e28381943aef994ed4", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "fduffy/QuantLibAdjoint", "max_stars_repo_path": "test-suite-adjoint/adjointtermstructureimpl.hpp", "max_stars_repo_stars_event_max_datetime": "2022-01-20T13:23:20.000Z", "max_stars_repo_stars_event_min_datetime": "2016-03-19T02:31:54.000Z", "num_tokens": 5962, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 25327 }
/- Copyright (c) 2019 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.continued_fractions.basic import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Basic Translation Lemmas Between Functions Defined for Continued Fractions ## Summary Some simple translation lemmas between the different definitions of functions defined in `algebra.continued_fractions.basic`. -/ namespace generalized_continued_fraction /-! ### Translations Between General Access Functions Here we give some basic translations that hold by definition between the various methods that allow us to access the numerators and denominators of a continued fraction. -/ theorem terminated_at_iff_s_terminated_at {α : Type u_1} {g : generalized_continued_fraction α} {n : ℕ} : terminated_at g n ↔ seq.terminated_at (s g) n := iff.refl (terminated_at g n) theorem terminated_at_iff_s_none {α : Type u_1} {g : generalized_continued_fraction α} {n : ℕ} : terminated_at g n ↔ seq.nth (s g) n = none := iff.refl (terminated_at g n) theorem part_num_none_iff_s_none {α : Type u_1} {g : generalized_continued_fraction α} {n : ℕ} : seq.nth (partial_numerators g) n = none ↔ seq.nth (s g) n = none := sorry theorem terminated_at_iff_part_num_none {α : Type u_1} {g : generalized_continued_fraction α} {n : ℕ} : terminated_at g n ↔ seq.nth (partial_numerators g) n = none := sorry theorem part_denom_none_iff_s_none {α : Type u_1} {g : generalized_continued_fraction α} {n : ℕ} : seq.nth (partial_denominators g) n = none ↔ seq.nth (s g) n = none := sorry theorem terminated_at_iff_part_denom_none {α : Type u_1} {g : generalized_continued_fraction α} {n : ℕ} : terminated_at g n ↔ seq.nth (partial_denominators g) n = none := sorry theorem part_num_eq_s_a {α : Type u_1} {g : generalized_continued_fraction α} {n : ℕ} {gp : pair α} (s_nth_eq : seq.nth (s g) n = some gp) : seq.nth (partial_numerators g) n = some (pair.a gp) := sorry theorem part_denom_eq_s_b {α : Type u_1} {g : generalized_continued_fraction α} {n : ℕ} {gp : pair α} (s_nth_eq : seq.nth (s g) n = some gp) : seq.nth (partial_denominators g) n = some (pair.b gp) := sorry theorem exists_s_a_of_part_num {α : Type u_1} {g : generalized_continued_fraction α} {n : ℕ} {a : α} (nth_part_num_eq : seq.nth (partial_numerators g) n = some a) : ∃ (gp : pair α), seq.nth (s g) n = some gp ∧ pair.a gp = a := sorry theorem exists_s_b_of_part_denom {α : Type u_1} {g : generalized_continued_fraction α} {n : ℕ} {b : α} (nth_part_denom_eq : seq.nth (partial_denominators g) n = some b) : ∃ (gp : pair α), seq.nth (s g) n = some gp ∧ pair.b gp = b := sorry /-! ### Translations Between Computational Functions Here we give some basic translations that hold by definition for the computational methods of a continued fraction. -/ theorem nth_cont_eq_succ_nth_cont_aux {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] : continuants g n = continuants_aux g (n + 1) := rfl theorem num_eq_conts_a {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] : numerators g n = pair.a (continuants g n) := rfl theorem denom_eq_conts_b {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] : denominators g n = pair.b (continuants g n) := rfl theorem convergent_eq_num_div_denom {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] : convergents g n = numerators g n / denominators g n := rfl theorem convergent_eq_conts_a_div_conts_b {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] : convergents g n = pair.a (continuants g n) / pair.b (continuants g n) := rfl theorem exists_conts_a_of_num {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {A : K} (nth_num_eq : numerators g n = A) : ∃ (conts : pair K), continuants g n = conts ∧ pair.a conts = A := eq.mpr (id (propext exists_eq_left')) nth_num_eq theorem exists_conts_b_of_denom {K : Type u_1} {g : generalized_continued_fraction K} {n : ℕ} [division_ring K] {B : K} (nth_denom_eq : denominators g n = B) : ∃ (conts : pair K), continuants g n = conts ∧ pair.b conts = B := eq.mpr (id (propext exists_eq_left')) nth_denom_eq @[simp] theorem zeroth_continuant_aux_eq_one_zero {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] : continuants_aux g 0 = pair.mk 1 0 := rfl @[simp] theorem first_continuant_aux_eq_h_one {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] : continuants_aux g 1 = pair.mk (h g) 1 := rfl @[simp] theorem zeroth_continuant_eq_h_one {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] : continuants g 0 = pair.mk (h g) 1 := rfl @[simp] theorem zeroth_numerator_eq_h {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] : numerators g 0 = h g := rfl @[simp] theorem zeroth_denominator_eq_one {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] : denominators g 0 = 1 := rfl @[simp] theorem zeroth_convergent_eq_h {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] : convergents g 0 = h g := sorry theorem second_continuant_aux_eq {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] {gp : pair K} (zeroth_s_eq : seq.nth (s g) 0 = some gp) : continuants_aux g (bit0 1) = pair.mk (pair.b gp * h g + pair.a gp) (pair.b gp) := sorry theorem first_continuant_eq {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] {gp : pair K} (zeroth_s_eq : seq.nth (s g) 0 = some gp) : continuants g 1 = pair.mk (pair.b gp * h g + pair.a gp) (pair.b gp) := sorry theorem first_numerator_eq {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] {gp : pair K} (zeroth_s_eq : seq.nth (s g) 0 = some gp) : numerators g 1 = pair.b gp * h g + pair.a gp := sorry theorem first_denominator_eq {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] {gp : pair K} (zeroth_s_eq : seq.nth (s g) 0 = some gp) : denominators g 1 = pair.b gp := sorry @[simp] theorem zeroth_convergent'_aux_eq_zero {K : Type u_1} [division_ring K] {s : seq (pair K)} : convergents'_aux s 0 = 0 := rfl @[simp] theorem zeroth_convergent'_eq_h {K : Type u_1} {g : generalized_continued_fraction K} [division_ring K] : convergents' g 0 = h g := sorry
{ "alphanum_fraction": null, "author": "AurelienSaue", "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/lean/AurelienSaue-Mathlib4_auto/Mathlib4_auto-590df64109b08190abe22358fabc3eae000943f2/Mathlib/algebra/continued_fractions/translations.lean", "reason": null, "repo": "Mathlib4_auto", "save_path": "github-repos/lean/AurelienSaue-Mathlib4_auto", "sha": "590df64109b08190abe22358fabc3eae000943f2", "size": null }
""" image generated by each "observation" """ import numpy as np import matplotlib.pyplot as plt class image(): def __init__(self,w,h): self.width = w self.height = h self.image = np.zeros(shape=(self.height,self.width)) def add_random_noise(self): self.image def generate_image(self): return self.image def generate_image(): w = 150 h = 100 img = image(w,h) im = img.generate_image() plt.imshow(im) plt.show() if __name__ == "__main__": generate_image()
{ "alphanum_fraction": 0.4970149254, "author": null, "avg_line_length": 12.1818181818, "converted": null, "ext": "py", "file": null, "hexsha": "5425032907c594d33990d18aadd2083f535046ad", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-01-04T17:32:31.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-04T17:32:31.000Z", "max_forks_repo_head_hexsha": "d844ceecc54a475a5384925f45a2078eef3416ee", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "azariven/SEAS", "max_forks_repo_path": "deprecated/observation_effects/image.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "d844ceecc54a475a5384925f45a2078eef3416ee", "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": "azariven/SEAS", "max_issues_repo_path": "deprecated/observation_effects/image.py", "max_line_length": 61, "max_stars_count": 1, "max_stars_repo_head_hexsha": "d844ceecc54a475a5384925f45a2078eef3416ee", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zhuchangzhan/SEAS", "max_stars_repo_path": "deprecated/observation_effects/image.py", "max_stars_repo_stars_event_max_datetime": "2020-12-06T23:09:08.000Z", "max_stars_repo_stars_event_min_datetime": "2020-12-06T23:09:08.000Z", "num_tokens": 145, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 670 }
import numpy as np from scipy.integrate import odeint from matplotlib import pyplot as plt def dx_MAPK(x,t,a=1000,k=150,d=150,l=0): KKK = x[0] E1 = x[1] KKK_E1 = x[2] KKKP = x[3] E2 = x[4] KKKP_E2 = x[5] KK = x[6] KK_KKKP = x[7] KKP = x[8] KKPase = x[9] KKP_KKPase = x[10] KKP_KKKP = x[11] KKPP = x[12] KKPP_KKPase = x[13] K = x[14] K_KKPP = x[15] KP = x[16] KPase = x[17] KP_KPase = x[18] KP_KKPP = x[19] KPP = x[20] KPP_KPase = x[21] v1a = a*KKK*E1 - d*KKK_E1 v1b = k*KKK_E1 - l*KKKP*E1 v2a = a*KKKP*E2 - d*KKKP_E2 v2b = k*KKKP_E2 - l*KKK*E2 v3a = a*KK*KKKP - d*KK_KKKP v3b = k*KK_KKKP - l*KKP*KKKP v4a = a*KKP*KKPase - d*KKP_KKPase v4b = k*KKP_KKPase - l*KK*KKPase v5a = a*KKP*KKKP - d*KKP_KKKP v5b = k*KKP_KKKP - l*KKPP*KKKP v6a = a*KKPP*KKPase - d*KKPP_KKPase v6b = k*KKPP_KKPase - l*KKP*KKPase v7a = a*K*KKPP - d*K_KKPP v7b = k*K_KKPP - l*KP*KKPP v8a = a*KP*KPase - d*KP_KPase v8b = k*KP_KPase - l*K*KPase v9a = a*KP*KKPP - d*KP_KKPP v9b = k*KP_KKPP - l*KPP*KKPP v10a = a*KPP*KPase - d*KPP_KPase v10b = k*KPP_KPase - l*KP*KPase d_KKK = -v1a +v2b d_E1 = -v1a + v1b d_KKK_E1 = v1a - v1b d_KKKP = v1b -v2a -v3a +v3b -v5a +v5b d_E2 = -v2a +v2b d_KKKP_E2 = v2a - v2b d_KK = -v3a +v4b d_KK_KKKP = v3a -v3b d_KKP = v3b -v4a -v5a +v6b d_KKPase = -v4a +v4b -v6a +v6b d_KKP_KKPase = v4a -v4b d_KKP_KKKP = v5a -v5b d_KKPP = v5b -v6a -v7a +v7b -v9a +v9b d_KKPP_KKPase = v6a -v6b d_K = -v7a +v8b d_K_KKPP = v7a - v7b d_KP = v7b -v8a -v9a +v10b d_KPase = -v8a +v8b -v10a +v10b d_KP_KPase = v8a - v8b d_KP_KKPP = v9a - v9b d_K_PP = v9b -v10a d_KPP_KPase = v10a - v10b dx = [ d_KKK, d_E1, d_KKK_E1, d_KKKP, d_E2, d_KKKP_E2, d_KK, d_KK_KKKP, d_KKP, d_KKPase, d_KKP_KKPase, d_KKP_KKKP, d_KKPP, d_KKPP_KKPase, d_K,d_K_KKPP, d_KP, d_KPase, d_KP_KPase, d_KP_KKPP, d_K_PP,d_KPP_KPase, ] return dx x0 = np.array([0.0]*22) x0[1] = 3e-5 x0[0] = 3e-3 x0[6] = 1.2 x0[14] = 1.2 x0[4] = 3e-4 x0[9] = 3e-4 x0[17] = 0.12 def generate_activation_curve(E1_vals = np.logspace(-7,-1,num=100)): MKKKP = np.array(len(E1_vals)*[0.]) MKKPP = np.array(len(E1_vals)*[0.]) MKPP = np.array(len(E1_vals)*[0.]) t = np.arange(0.,1000.,0.1) a = 1000 d = 150 k = 150 DG_ATP = -50000 R = 8.314 T = 310 D = (a*k/d)**2*np.exp(DG_ATP/R/T) l = np.sqrt(D) for i,E1 in enumerate(E1_vals): x0[1] = E1 x = odeint(dx_MAPK,x0,t,args=(a,k,d,l)) MKKKP[i] = x[-1,3] MKKPP[i] = x[-1,12] MKPP[i] = x[-1,20] MKKKP_ideal = np.array(len(E1_vals)*[0.]) MKKPP_ideal = np.array(len(E1_vals)*[0.]) MKPP_ideal = np.array(len(E1_vals)*[0.]) for i,E1 in enumerate(E1_vals): x0[1] = E1 x = odeint(dx_MAPK,x0,t) MKKKP_ideal[i] = x[-1,3] MKKPP_ideal[i] = x[-1,12] MKPP_ideal[i] = x[-1,20] return E1_vals, (MKKKP,MKKPP,MKPP), (MKKKP_ideal,MKKPP_ideal,MKPP_ideal)
{ "alphanum_fraction": 0.556749921, "author": null, "avg_line_length": 25.304, "converted": null, "ext": "py", "file": null, "hexsha": "4769fb0e7c78b186223a3806cbe892f68c695f9c", "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": "5d38c6d03cd5d9680cb44a5f0e07bfad52c6a7c8", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mic-pan/Modularity-SysBio", "max_forks_repo_path": "Huang_Ferrell_MAPK.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "5d38c6d03cd5d9680cb44a5f0e07bfad52c6a7c8", "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": "mic-pan/Modularity-SysBio", "max_issues_repo_path": "Huang_Ferrell_MAPK.py", "max_line_length": 76, "max_stars_count": null, "max_stars_repo_head_hexsha": "5d38c6d03cd5d9680cb44a5f0e07bfad52c6a7c8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mic-pan/Modularity-SysBio", "max_stars_repo_path": "Huang_Ferrell_MAPK.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1623, "path": null, "reason": "import numpy,from scipy", "repo": null, "save_path": null, "sha": null, "size": 3163 }
# -*- coding: utf-8 -*- import numpy as np IPART = 2 class LightMatrix: def __init__(self): self.maxrows = 100 self.maxcols = 100 self.lights = np.zeros( (self.maxrows,self.maxcols), dtype=int) def readCurrentState(self, myfilename): with open(myfilename) as datafile: irow = 0 for thisstring in datafile: icol = 0 thisstring = thisstring.rstrip() for thischar in thisstring: if (thischar == '#'): self.lights[irow,icol] = 1 elif (thischar == '.'): self.lights[irow,icol] = 0 else: print("WHAA? {0},{1}:{2}".format(irow,icol,thischar)) icol += 1 irow +=1 def countActiveNeighbors(self, irow, icol): neighbors = [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)] thecount = 0 for inc_row, inc_col in neighbors: neighbor_row = irow + inc_row neighbor_col = icol + inc_col if (neighbor_row >= self.maxrows) or (neighbor_row < 0): continue if (neighbor_col >= self.maxcols) or (neighbor_col < 0): continue #print("---- {0}x{1} inspecting {2}x{3}={4}".format(irow,icol,neighbor_row,neighbor_col,self.lights[neighbor_row,neighbor_col])) thecount += self.lights[neighbor_row,neighbor_col] return thecount def makeStep(self): global IPART nextlights = np.copy(self.lights) it = np.nditer(self.lights, flags=['multi_index']) while not it.finished: thisvalue = it[0] neighborcount = self.countActiveNeighbors(it.multi_index[0], it.multi_index[1]) #print("{0}x{1} value {2} neighborcount {3}".format(it.multi_index[0], it.multi_index[1], thisvalue, neighborcount)) if thisvalue ==1: if (neighborcount == 2) or (neighborcount == 3): # stay on nextlights[it.multi_index[0], it.multi_index[1]] = 1 else: nextlights[it.multi_index[0], it.multi_index[1]] = 0 else: if neighborcount == 3: nextlights[it.multi_index[0], it.multi_index[1]] = 1 else: # stay off nextlights[it.multi_index[0], it.multi_index[1]] = 0 it.iternext() if IPART==2: nextlights[0,0] = 1 nextlights[self.maxrows-1,0] = 1 nextlights[0,self.maxcols-1] = 1 nextlights[self.maxrows-1,self.maxcols-1] = 1 self.lights = nextlights if __name__ == "__main__": """Day18: Game-of-life""" print("-----------Testing-----------") testlights = LightMatrix() testlights.maxrows = 6 testlights.maxcols = 6 #testlights.lights = np.zeros( (6,6), dtype=int) testlights.lights = np.array( [[0,1,0,1,0,1], \ [0,0,0,1,1,0], \ [1,0,0,0,0,1], \ [0,0,1,0,0,0], \ [1,0,1,0,0,1], \ [1,1,1,1,0,0] ], dtype=int) print(testlights.lights) testlights.makeStep() print(testlights.lights) testlights.makeStep() print(testlights.lights) print("----------Day One -----------") lights = LightMatrix() lights.readCurrentState('day18.dat') for i in range(1,101): lights.makeStep() counton = 0 for thisval in np.nditer(lights.lights): counton += thisval print("After {0} iterations: {1} on".format(i,counton) )
{ "alphanum_fraction": 0.4844387755, "author": null, "avg_line_length": 34.0869565217, "converted": null, "ext": "py", "file": null, "hexsha": "6d96819d4654c4caf838c142151ae5fff8255a9f", "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": "01677494ca042cd4372e2281fc4923899b75c9db", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "jborlik/AdventOfCode2015", "max_forks_repo_path": "day18.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "01677494ca042cd4372e2281fc4923899b75c9db", "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": "jborlik/AdventOfCode2015", "max_issues_repo_path": "day18.py", "max_line_length": 140, "max_stars_count": null, "max_stars_repo_head_hexsha": "01677494ca042cd4372e2281fc4923899b75c9db", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "jborlik/AdventOfCode2015", "max_stars_repo_path": "day18.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1015, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 3920 }
import numpy as np ####################################################################### # # ClusterFit class class ClusterFit: """ container class for fitting PCA, clustering """ def __init__(self, data, # could be deaths/cases, raw/adjusted Npca = 10, fft = None, # optionally True to do PCA on Fourier transformed data outfile = ''): self.Npca = Npca self.data = data self.outfile = outfile self.dat = np.array([data[cc] for cc in data]) self.pca = PCA(Npca) if fft == 'fft' or fft == 'powfft': self.fftdat = np.fft.rfft(self.dat) # last axis by default self.nfft = len(self.fftdat[0]) if fft == 'powfft': self.fftpow = np.square(np.abs(self.fftdat)) for i in range(len(self.fftpow)): # normalize data ignoring DC component mx = max(self.fftpow[i]) self.fftpow[i] = [dd/mx for dd in self.fftpow[i]] self.lfftpow = np.log(self.fftpow) # self.pca.fit(self.fftpow) self.fitted = self.pca.fit_transform(self.lfftpow) self.smoothed = self.pca.inverse_transform(self.fitted) self.fft = 'powfft' else: # 'fft' # consider scaling data from all countries to same max freq amplitude per country of fft self.rfft = np.concatenate((np.real(self.fftdat),np.imag(self.fftdat)),axis = 1) # concatenate along 2nd axis # self.pca.fit(self.rfft) maxvals = np.zeros(len(self.dat)) dcvals = np.zeros(len(self.dat)) for i in range(len(self.rfft)): # normalize data ignoring DC component, scaling data from all countries to same max freq amplitude per country dcvals[i] = self.rfft[i,0] # ignore DC component self.rfft[i,0] = 0. mx = maxvals[i] = max(self.rfft[i]) # mx = maxvals[i] = 1.0 self.rfft[i] = [dd/mx for dd in self.rfft[i]] self.fitted = self.pca.fit_transform(self.rfft) self.rsmoothed = self.pca.inverse_transform(self.fitted) self.fftsmoothed = np.transpose(np.array([self.rsmoothed[:,k] + self.rsmoothed[:,self.nfft+k]*1j for k in range(self.nfft)], dtype=np.cdouble)) for i in range(len(data)): self.fftsmoothed[i,:] = self.fftsmoothed[i,:]*maxvals[i] self.fftsmoothed[:,0] = dcvals self.smoothed = np.fft.irfft(self.fftsmoothed,len(self.dat[0])) self.fft = 'fft' else: for i in range(len(self.dat)): # normalize data mx = max(self.dat[i]) self.dat[i] = [dd/mx for dd in self.dat[i]] # self.pca.fit(self.dat) self.fitted = self.pca.fit_transform(self.dat) self.smoothed = self.pca.inverse_transform(self.fitted) self.nfft = 0 self.fft = None #print('explained_variance_ratio:') #print('explained_variance_ratio_' in dir(self.pca)) #print([x for x in dir(self.pca) if '__' not in x]) #print(self.pca.explained_variance_ratio_) #print('singular values:') #print(self.pca.singular_values_) def plot_2components(self): plt.scatter(self.fitted[:,0],fitted[:,1]); def cluster_plot_all(self): max_cols=6 max_rows=int(len(self.dat)/max_cols) + 1 fig, axes = plt.subplots(nrows=max_rows, ncols=max_cols, figsize=(20,3.5*max_rows)) if self.fft == 'powfft' or self.fft == 'fft': axes2 = np.array([[ax.twinx() for ax in axesrow] for axesrow in axes]) countries = [cc for cc in self.data] if len(self.clus_labels) == len(countries): print('sorting countries according to cluster labels') self.clus_argsort = np.lexsort((countries,self.clus_labels)) scountries = [countries[self.clus_argsort[i]] for i in range(len(countries))] else: scountries = countries for id, countrycode in enumerate(countries): row = id // max_cols col = id % max_cols if len(self.clus_labels) == len(countries): idx = self.clus_argsort[id] else: idx = id axes[row, col].plot(self.dat[idx]) if self.fft == 'powfft': axes2[row, col].plot(self.smoothed[idx],color='red') # axes2[row, col].set_yscale('log') # not required, data is already logarithmic elif self.fft == 'fit': axes2[row, col].plot(self.smoothed[idx],color='orange') else: axes[row, col].plot(self.smoothed[idx]) axes[row, col].set_title(countries[idx]) for idx in range(len(countries),max_rows*max_cols): row = idx // max_cols col = idx % max_cols axes[row, col].axis("off") if self.fft == 'powfft': axes2[row, col].axis("off") #plt.subplots_adjust(wspace=.05, hspace=.05) if self.outfile != '': plt.savefig(self.outfile) plt.show() def hdbscan(self,min_size=4): self.clusterer = hdbscan.HDBSCAN(min_cluster_size=min_size) tdat = self.dat self.clus_labels = self.clusterer.fit_predict(tdat) validity = hdbscan.validity.validity_index(tdat, self.clus_labels) print('cluster validity index =',validity) print('cluster validity of each cluster:') validity = hdbscan.validity.validity_index(tdat, self.clus_labels,per_cluster_scores=True) for i,v in enumerate(validity): print('cluster',self.clus_labels[i],'validity =',validity[i]) def plot_fpca(self): dat_disc = skfda.representation.grid.FDataGrid(dat,list(range(len(dat[0])))) fpca_disc = FPCA(n_components=10) fpca_disc.fit(dat_disc) fpca_disc.components_.plot() def hdbscan_fpca(self,min_size=4,min_samples=3,n_components=5,diag=True): self.clusterer = hdbscan.HDBSCAN(min_cluster_size=min_size,min_samples=min_samples) dat_disc = skfda.representation.grid.FDataGrid(dat,list(range(len(dat[0])))) fpca_disc = FPCA(n_components=n_components) fpca_disc.fit(dat_disc) self.fpca_transform = fpca_disc.transform(dat_disc) self.clus_labels = self.clusterer.fit_predict(self.fpca_transform) if diag: try: validity = hdbscan.validity.validity_index(self.fpca_transform, self.clus_labels) labels = self.clus_labels print('hdbscan_min_clus=',min_size,': ',n_components ,'FPCAcomponents: ', len(set([x for x in labels if x>-1])),'clusters; ', sum([1 for x in labels if x>-1]),'clustered; ',sum([1 for x in labels if x==-1]),'unclustered; ','validity =',np.round(validity,3)) except: validity=None labels = self.clus_labels print('hdbscan_min_clus=',min_size,': ',n_components ,'FPCAcomponents: ', len(set([x for x in labels if x>-1])),'clusters; ', sum([1 for x in labels if x>-1]),'clustered; ',sum([1 for x in labels if x==-1]),'unclustered; ','validity =',validity) def hdbscan_pca(self,min_size=4): self.clusterer = hdbscan.HDBSCAN(min_cluster_size=min_size) tdat = self.fitted print('shape of cluster data = ',tdat.shape) self.clus_labels = self.clusterer.fit_predict(tdat) validity = hdbscan.validity.validity_index(tdat, self.clus_labels) print('cluster validity index =',validity) print('cluster validity of each cluster:') validity = hdbscan.validity.validity_index(tdat, self.clus_labels,per_cluster_scores=True) for i,v in enumerate(validity): print('cluster',self.clus_labels[i],'validity =',validity[i]) def umap(self,random_state=0,n_neighbors=10): self.um_fit = umap.UMAP(random_state=random_state,n_neighbors=n_neighbors).fit(self.fitted) self.um_dat = [self.um_fit.embedding_[:,i] for i in range(2)] def umap_cluster(self,random_state=0,min_size=4,diag=True,n_neighbors=10): self.um_fit = umap.UMAP(random_state=random_state,n_neighbors=n_neighbors).fit(self.fitted) self.um_dat = [self.um_fit.embedding_[:,i] for i in range(2)] tdat = np.transpose(self.um_dat) self.clusterer = hdbscan.HDBSCAN(min_cluster_size=min_size) self.clus_labels = self.clusterer.fit_predict(tdat) self.clus_probs = self.clusterer.probabilities_ if diag: print('hdbscan found',len(set(self.clus_labels)),'clusters.') def umap_best_cluster(self,Nclus=3,Ntries=50,minsize=4,ranstate=0,n_neighbors=10): clusall = [] clus = {} clus['probs'] = [] clus['idx'] = [] for i in range(ranstate,ranstate+Ntries): self.umap_cluster(random_state=i,min_size=minsize,diag=False,n_neighbors=n_neighbors) if len(set(self.clus_labels)) == Nclus: clus['probs'].append(np.mean(self.clus_probs)) clus['idx'].append(i) print('found',len(clus['probs']),'clusterings with size',Nclus,'clusters') if len(clus['probs'])>1: idx = np.argsort(clus['probs'])[-1:][0] elif len(clus['probs']) == 1: idx = 0 else: print("Failed to find a cluster with",Nclus,"components") return self.umap_cluster(random_state=clus['idx'][idx],min_size=minsize,diag=False,n_neighbors=n_neighbors) def plot_umap(self): labs = [x for x in self.clus_labels] for i in range(len(labs)): if labs[i]<0: labs[i] = None plt.scatter(self.um_dat[0],self.um_dat[1],c=labs) xx = [self.um_dat[0][i] for i in range(len(labs)) if labs[i]==None] yy = [self.um_dat[0][i] for i in range(len(labs)) if labs[i]==None] #print(xx) #print(yy) plt.scatter(xx,yy,color='red') def plot_pcas(self): max_cols = 5 max_rows = self.Npca // max_cols if self.Npca%max_cols>0: max_rows = max_rows+1 fig, axes = plt.subplots(nrows=max_rows, ncols=max_cols, figsize=(20,max_rows*3.5)) for i in range(10): foo = np.zeros(10) foo[i] = 1 mypca = self.pca.inverse_transform(foo) if self.fft == 'fft': fftmypca = np.array([mypca[k] + mypca[self.nfft+k]*1j for k in range(self.nfft)], dtype=np.cdouble) mypca = np.fft.irfft(fftmypca) row = i // max_cols col = i % max_cols #axes[row, col].axis("off") axes[row, col].plot(mypca)
{ "alphanum_fraction": 0.5735889819, "author": null, "avg_line_length": 47.4743589744, "converted": null, "ext": "py", "file": null, "hexsha": "3e896f3a776fcd560e7d95ef287263507cac1b45", "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": "b3989f110c6961cc51da673fc33c6384cf7d6de6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ProtoLife/covid-recovery", "max_forks_repo_path": "Notebooks/covid-19-caution/ClusterFit.py", "max_issues_count": 1, "max_issues_repo_head_hexsha": "b3989f110c6961cc51da673fc33c6384cf7d6de6", "max_issues_repo_issues_event_max_datetime": "2020-05-25T19:59:44.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-24T00:06:54.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ProtoLife/covid-recovery", "max_issues_repo_path": "Notebooks/covid-19-caution/ClusterFit.py", "max_line_length": 159, "max_stars_count": null, "max_stars_repo_head_hexsha": "b3989f110c6961cc51da673fc33c6384cf7d6de6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ProtoLife/covid-recovery", "max_stars_repo_path": "Notebooks/covid-19-caution/ClusterFit.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2794, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 11109 }
#!/usr/bin/env python # CREATED:2013-03-08 15:25:18 by Brian McFee <brm2132@columbia.edu> # unit tests for librosa.filters # # This test suite verifies that librosa core routines match (numerically) the output # of various DPWE matlab implementations on a broad range of input parameters. # # All test data is generated by the Matlab script "makeTestData.m". # Each test loads in a .mat file which contains the input and desired output for a given # function. The test then runs the librosa implementation and verifies the results # against the desired output, typically via numpy.allclose(). # # Disable cache import os try: os.environ.pop("LIBROSA_CACHE_DIR") except KeyError: pass from contextlib2 import nullcontext as dnr import glob import numpy as np import scipy.io import pytest import librosa # -- utilities --# def files(pattern): test_files = glob.glob(pattern) test_files.sort() return test_files def load(infile): DATA = scipy.io.loadmat(infile, chars_as_strings=True) return DATA # -- --# # -- Tests --# @pytest.mark.parametrize( "infile", files(os.path.join("tests", "data", "feature-hz_to_mel-*.mat")) ) def test_hz_to_mel(infile): DATA = load(infile) z = librosa.hz_to_mel(DATA["f"], DATA["htk"]) assert np.allclose(z, DATA["result"]) @pytest.mark.parametrize( "infile", files(os.path.join("tests", "data", "feature-mel_to_hz-*.mat")) ) def test_mel_to_hz(infile): DATA = load(infile) z = librosa.mel_to_hz(DATA["f"], DATA["htk"]) assert np.allclose(z, DATA["result"]) # Test for scalar conversion too z0 = librosa.mel_to_hz(DATA["f"][0], DATA["htk"]) assert np.allclose(z0, DATA["result"][0]) @pytest.mark.parametrize( "infile", files(os.path.join("tests", "data", "feature-hz_to_octs-*.mat")) ) def test_hz_to_octs(infile): DATA = load(infile) z = librosa.hz_to_octs(DATA["f"]) assert np.allclose(z, DATA["result"]) @pytest.mark.parametrize( "infile", files(os.path.join("tests", "data", "feature-melfb-*.mat")) ) def test_melfb(infile): DATA = load(infile) wts = librosa.filters.mel( DATA["sr"][0, 0], DATA["nfft"][0, 0], n_mels=DATA["nfilts"][0, 0], fmin=DATA["fmin"][0, 0], fmax=DATA["fmax"][0, 0], htk=DATA["htk"][0, 0], ) # Our version only returns the real-valued part. # Pad out. wts = np.pad(wts, [(0, 0), (0, int(DATA["nfft"][0] // 2 - 1))], mode="constant") assert wts.shape == DATA["wts"].shape assert np.allclose(wts, DATA["wts"]) @pytest.mark.parametrize( "infile", files(os.path.join("tests", "data", "feature-melfbnorm-*.mat")) ) def test_melfbnorm(infile): DATA = load(infile) # if DATA['norm'] is empty, pass None. if DATA["norm"].shape[-1] == 0: norm = None else: norm = DATA["norm"][0, 0] wts = librosa.filters.mel( DATA["sr"][0, 0], DATA["nfft"][0, 0], n_mels=DATA["nfilts"][0, 0], fmin=DATA["fmin"][0, 0], fmax=DATA["fmax"][0, 0], htk=DATA["htk"][0, 0], norm=norm, ) # Pad out. wts = np.pad(wts, [(0, 0), (0, int(DATA["nfft"][0] // 2 - 1))], mode="constant") assert wts.shape == DATA["wts"].shape assert np.allclose(wts, DATA["wts"]) @pytest.mark.parametrize("norm", [1, 2, np.inf]) def test_mel_norm(norm): M = librosa.filters.mel(22050, 2048, norm=norm) if norm == 1: assert np.allclose(np.sum(np.abs(M), axis=1), 1) elif norm == 2: assert np.allclose(np.sum(np.abs(M ** 2), axis=1), 1) elif norm == np.inf: assert np.allclose(np.max(np.abs(M), axis=1), 1) @pytest.mark.xfail(raises=librosa.ParameterError) def test_mel_badnorm(): librosa.filters.mel(22050, 2048, norm="garbage") def test_mel_gap(): # This configuration should trigger some empty filters sr = 44100 n_fft = 1024 fmin = 0 fmax = 2000 n_mels = 128 htk = True with pytest.warns(UserWarning, match="Empty filters"): librosa.filters.mel(sr, n_fft, n_mels=n_mels, fmin=fmin, fmax=fmax, htk=htk) @pytest.mark.parametrize( "infile", files(os.path.join("tests", "data", "feature-chromafb-*.mat")) ) def test_chromafb(infile): DATA = load(infile) octwidth = DATA["octwidth"][0, 0] if octwidth == 0: octwidth = None # Convert A440 parameter to tuning parameter A440 = DATA["a440"][0, 0] tuning = DATA["nchroma"][0, 0] * (np.log2(A440) - np.log2(440.0)) wts = librosa.filters.chroma( DATA["sr"][0, 0], DATA["nfft"][0, 0], DATA["nchroma"][0, 0], tuning=tuning, ctroct=DATA["ctroct"][0, 0], octwidth=octwidth, norm=2, base_c=False, ) # Our version only returns the real-valued part. # Pad out. wts = np.pad(wts, [(0, 0), (0, int(DATA["nfft"][0, 0] // 2 - 1))], mode="constant") assert wts.shape == DATA["wts"].shape assert np.allclose(wts, DATA["wts"]) # Testing two tones, 261.63 Hz and 440 Hz @pytest.mark.parametrize("freq", [261.63, 440]) def test_chroma_issue1295(freq): tone_1 = librosa.tone(frequency=freq, sr=22050, duration=1) chroma_1 = librosa.feature.chroma_stft( y=tone_1, sr=22050, n_chroma=120, base_c=True ) actual_argmax = np.unravel_index(chroma_1.argmax(), chroma_1.shape) if freq == 261.63: assert actual_argmax == (118, 0) elif freq == 440: assert actual_argmax == (90, 0) @pytest.mark.parametrize("n", [16, 16.0, 16.25, 16.75]) @pytest.mark.parametrize( "window_name", [ "barthann", "bartlett", "blackman", "blackmanharris", "bohman", "boxcar", "cosine", "flattop", "hamming", "hann", "hanning", "nuttall", "parzen", "triang", ], ) def test__window(n, window_name): window = getattr(scipy.signal.windows, window_name) wdec = librosa.filters.__float_window(window) if n == int(n): n = int(n) assert np.allclose(wdec(n), window(n)) else: wf = wdec(n) fn = int(np.floor(n)) assert not np.any(wf[fn:]) @pytest.mark.parametrize("sr", [11025]) @pytest.mark.parametrize("fmin", [None, librosa.note_to_hz("C3")]) @pytest.mark.parametrize("n_bins", [12, 24]) @pytest.mark.parametrize("bins_per_octave", [12, 24]) @pytest.mark.parametrize("filter_scale", [1, 2]) @pytest.mark.parametrize("norm", [1, 2]) @pytest.mark.parametrize("pad_fft", [False, True]) def test_constant_q(sr, fmin, n_bins, bins_per_octave, filter_scale, pad_fft, norm): F, lengths = librosa.filters.constant_q( sr, fmin=fmin, n_bins=n_bins, bins_per_octave=bins_per_octave, filter_scale=filter_scale, pad_fft=pad_fft, norm=norm, ) assert np.all(lengths <= F.shape[1]) assert len(F) == n_bins if not pad_fft: return assert np.mod(np.log2(F.shape[1]), 1.0) == 0.0 # Check for vanishing negative frequencies F_fft = np.abs(np.fft.fft(F, axis=1)) # Normalize by row-wise peak F_fft = F_fft / np.max(F_fft, axis=1, keepdims=True) assert not np.any(F_fft[:, -F_fft.shape[1] // 2 :] > 1e-4) @pytest.mark.parametrize("sr", [11025]) @pytest.mark.parametrize("fmin", [librosa.note_to_hz("C3")]) @pytest.mark.parametrize("n_bins", [12, 24]) @pytest.mark.parametrize("bins_per_octave", [12, 24]) @pytest.mark.parametrize("filter_scale", [1, 2]) @pytest.mark.parametrize("norm", [1, 2]) @pytest.mark.parametrize("pad_fft", [False, True]) @pytest.mark.parametrize("gamma", [0, 10, None]) def test_wavelet(sr, fmin, n_bins, bins_per_octave, filter_scale, pad_fft, norm, gamma): freqs = librosa.cqt_frequencies(fmin=fmin, n_bins=n_bins, bins_per_octave=bins_per_octave) F, lengths = librosa.filters.wavelet( freqs, sr=sr, filter_scale=filter_scale, pad_fft=pad_fft, norm=norm, gamma=gamma ) assert np.all(lengths <= F.shape[1]) assert len(F) == n_bins if not pad_fft: return assert np.mod(np.log2(F.shape[1]), 1.0) == 0.0 # Check for vanishing negative frequencies F_fft = np.abs(np.fft.fft(F, axis=1)) # Normalize by row-wise peak F_fft = F_fft / np.max(F_fft, axis=1, keepdims=True) assert np.max(F_fft[:, -F_fft.shape[1] // 2 :]) < 1e-3 @pytest.mark.xfail(raises=librosa.ParameterError) def test_wavelet_lengths_badscale(): librosa.filters.wavelet_lengths(2**np.arange(3), filter_scale=-1) @pytest.mark.xfail(raises=librosa.ParameterError) def test_wavelet_lengths_badgamma(): librosa.filters.wavelet_lengths(2**np.arange(3), gamma=-1) @pytest.mark.xfail(raises=librosa.ParameterError) def test_wavelet_lengths_badfreqs(): librosa.filters.wavelet_lengths(2**np.arange(3) -20) @pytest.mark.xfail(raises=librosa.ParameterError) def test_wavelet_lengths_badfreqsorder(): librosa.filters.wavelet_lengths(2**np.arange(3)[::-1]) @pytest.mark.xfail(raises=librosa.ParameterError) def test_wavelet_lengths_noalpha(): librosa.filters.wavelet_lengths(freqs=[64], alpha=None) @pytest.mark.xfail(raises=librosa.ParameterError) @pytest.mark.parametrize( "sr,fmin,n_bins,bins_per_octave,filter_scale,norm", [ (11025, 11025 / 2.0, 1, 12, 1, 1), (11025, -60, 1, 12, 1, 1), (11025, 60, 1, -12, 1, 1), (11025, 60, -1, 12, 1, 1), (11025, 60, 1, 12, -1, 1), (11025, 60, 1, 12, 1, -1), ], ) def test_constant_q_badparams(sr, fmin, n_bins, bins_per_octave, filter_scale, norm): librosa.filters.constant_q( sr, fmin=fmin, n_bins=n_bins, bins_per_octave=bins_per_octave, filter_scale=filter_scale, pad_fft=True, norm=norm, ) def test_window_bandwidth(): hann_bw = librosa.filters.window_bandwidth("hann") hann_scipy_bw = librosa.filters.window_bandwidth(scipy.signal.hann) assert hann_bw == hann_scipy_bw def test_window_bandwidth_dynamic(): # Test with a window constructor guaranteed to not exist in # the dictionary. # should behave like a box filter, which has enbw == 1 assert librosa.filters.window_bandwidth(lambda n: np.ones(n)) == 1 @pytest.mark.xfail(raises=ValueError) def test_window_bandwidth_missing(): librosa.filters.window_bandwidth("made up window name") def binstr(m): out = [] for row in m: line = [" "] * len(row) for i in np.flatnonzero(row): line[i] = "." out.append("".join(line)) return "\n".join(out) @pytest.mark.parametrize("n_octaves", [2, 3, 4]) @pytest.mark.parametrize("semitones", [1, 3]) @pytest.mark.parametrize("n_chroma", [12, 24, 36]) @pytest.mark.parametrize("fmin", [None] + list(librosa.midi_to_hz(range(48, 61)))) @pytest.mark.parametrize("base_c", [False, True]) @pytest.mark.parametrize("window", [None, [1]]) def test_cq_to_chroma(n_octaves, semitones, n_chroma, fmin, base_c, window): bins_per_octave = 12 * semitones n_bins = n_octaves * bins_per_octave if np.mod(bins_per_octave, n_chroma) != 0: ctx = pytest.raises(librosa.ParameterError) else: ctx = dnr() with ctx: # Fake up a cqt matrix with the corresponding midi notes if fmin is None: midi_base = 24 # C2 else: midi_base = librosa.hz_to_midi(fmin) midi_notes = np.linspace( midi_base, midi_base + n_bins * 12.0 / bins_per_octave, endpoint=False, num=n_bins, ) # We don't care past 2 decimals here. # the log2 inside hz_to_midi can cause problems though. midi_notes = np.around(midi_notes, decimals=2) C = np.diag(midi_notes) cq2chr = librosa.filters.cq_to_chroma( n_input=C.shape[0], bins_per_octave=bins_per_octave, n_chroma=n_chroma, fmin=fmin, base_c=base_c, window=window, ) chroma = cq2chr.dot(C) for i in range(n_chroma): v = chroma[i][chroma[i] != 0] v = np.around(v, decimals=2) if base_c: resid = np.mod(v, 12) else: resid = np.mod(v - 9, 12) resid = np.round(resid * n_chroma / 12.0) assert np.allclose(np.mod(i - resid, 12), 0.0), i - resid @pytest.mark.xfail(raises=librosa.ParameterError) def test_get_window_fail(): librosa.filters.get_window(None, 32) @pytest.mark.parametrize("window", ["hann", "hann", 4.0, ("kaiser", 4.0)]) def test_get_window(window): w1 = librosa.filters.get_window(window, 32) w2 = scipy.signal.get_window(window, 32) assert np.allclose(w1, w2) def test_get_window_func(): w1 = librosa.filters.get_window(scipy.signal.boxcar, 32) w2 = scipy.signal.get_window("boxcar", 32) assert np.allclose(w1, w2) @pytest.mark.parametrize( "pre_win", [scipy.signal.hann(16), list(scipy.signal.hann(16)), [1, 1, 1]] ) def test_get_window_pre(pre_win): win = librosa.filters.get_window(pre_win, len(pre_win)) assert np.allclose(win, pre_win) def test_semitone_filterbank(): # We test against Chroma Toolbox' elliptical semitone filterbank # load data from chroma toolbox gt_fb = scipy.io.loadmat( os.path.join( "tests", "data", "filter-muliratefb-MIDI_FB_ellip_pitch_60_96_22050_Q25" ), squeeze_me=True, )["h"] # standard parameters reproduce settings from chroma toolbox mut_ft_ba, mut_srs_ba = librosa.filters.semitone_filterbank(flayout="ba") mut_ft_sos, mut_srs_sos = librosa.filters.semitone_filterbank(flayout="sos") for cur_filter_id in range(len(mut_ft_ba)): cur_filter_gt = gt_fb[cur_filter_id + 23] cur_filter_mut = mut_ft_ba[cur_filter_id] cur_filter_mut_sos = scipy.signal.sos2tf(mut_ft_sos[cur_filter_id]) cur_a_gt = cur_filter_gt[0] cur_b_gt = cur_filter_gt[1] cur_a_mut = cur_filter_mut[1] cur_b_mut = cur_filter_mut[0] cur_a_mut_sos = cur_filter_mut_sos[1] cur_b_mut_sos = cur_filter_mut_sos[0] # we deviate from the chroma toolboxes for pitches 94 and 95 # (filters 70 and 71) by processing them with a higher samplerate if (cur_filter_id != 70) and (cur_filter_id != 71): assert np.allclose(cur_a_gt, cur_a_mut) assert np.allclose(cur_b_gt, cur_b_mut, atol=1e-4) assert np.allclose(cur_a_gt, cur_a_mut_sos) assert np.allclose(cur_b_gt, cur_b_mut_sos, atol=1e-4) @pytest.mark.parametrize("n", [9, 17]) @pytest.mark.parametrize("window", ["hann", "rect"]) @pytest.mark.parametrize("angle", [None, np.pi / 4, np.pi / 6]) @pytest.mark.parametrize("slope", [1, 2, 0.5]) @pytest.mark.parametrize("zero_mean", [False, True]) def test_diagonal_filter(n, window, angle, slope, zero_mean): kernel = librosa.filters.diagonal_filter( window, n, slope=slope, angle=angle, zero_mean=zero_mean ) # In the no-rotation case, check that the filter is shaped correctly if angle == np.pi / 4 and not zero_mean: win_unnorm = librosa.filters.get_window(window, n, fftbins=False) win_unnorm /= win_unnorm.sum() assert np.allclose(np.diag(kernel), win_unnorm) # First check: zero-mean if zero_mean: assert np.isclose(kernel.sum(), 0) else: assert np.isclose(kernel.sum(), 1) and np.all(kernel >= 0) # Now check if the angle transposes correctly if angle is None: # If we're using the slope API, then the transposed kernel # will have slope 1/slope k2 = librosa.filters.diagonal_filter( window, n, slope=1.0 / slope, angle=angle, zero_mean=zero_mean ) else: # If we're using the angle API, then the transposed kernel # will have angle pi/2 - angle k2 = librosa.filters.diagonal_filter( window, n, slope=slope, angle=np.pi / 2 - angle, zero_mean=zero_mean ) assert np.allclose(k2, kernel.T)
{ "alphanum_fraction": 0.6316634752, "author": null, "avg_line_length": 28.6530973451, "converted": null, "ext": "py", "file": null, "hexsha": "d4add1475bc08cdcb7bb43debf073199a4737f0b", "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": "76029d35ce4c76a7475f07aab67fe2df3f73c25c", "max_forks_repo_licenses": [ "0BSD" ], "max_forks_repo_name": "oriolcolomefont/librosa", "max_forks_repo_path": "tests/test_filters.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "76029d35ce4c76a7475f07aab67fe2df3f73c25c", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "0BSD" ], "max_issues_repo_name": "oriolcolomefont/librosa", "max_issues_repo_path": "tests/test_filters.py", "max_line_length": 94, "max_stars_count": 1, "max_stars_repo_head_hexsha": "76029d35ce4c76a7475f07aab67fe2df3f73c25c", "max_stars_repo_licenses": [ "0BSD" ], "max_stars_repo_name": "oriolcolomefont/librosa", "max_stars_repo_path": "tests/test_filters.py", "max_stars_repo_stars_event_max_datetime": "2022-02-23T15:10:32.000Z", "max_stars_repo_stars_event_min_datetime": "2022-02-23T15:10:32.000Z", "num_tokens": 4747, "path": null, "reason": "import numpy,import scipy", "repo": null, "save_path": null, "sha": null, "size": 16189 }
import numpy as np import matplotlib.pyplot as plt from astropy.io import ascii, fits import math from importlib import reload import multiprocessing as mp import os from tqdm import tqdm import numpy.ma as ma from scipy.interpolate import interp1d from ..lib import plots from scipy.optimize import leastsq from .sort_nicely import sort_nicely as sn import glob import pickle from scipy.signal import find_peaks #s00 def readfiles(meta): """ Reads in the files saved in datadir and saves them into a list Parameters ----------- meta metadata object Returns ---------- meta metadata object but adds segment_list to metadata containing the sorted data fits files Notes: ---------- History: Written by Sebastian Zieba December 2021 """ meta.segment_list = [] for fname in os.listdir(str(meta.datadir)): if fname.endswith(meta.suffix + '.fits'): meta.segment_list.append(str(meta.datadir) +'/'+ fname) return meta #s02 def ancil(meta, s10=False, s20=False): """ This function loads in a lot of useful arrays and values into meta The following additional information are being loading into meta: - **norbit:** number of orbits - **nvisit:** number of visits - **files_sp:** all spectra files - **files_di:** all direct image files - **ra:** RA of the target in radians (from the header) (Note: this data is taken from the first spectrum file) - **dec:** DEC of the target in radians (from the header) (Note: this data is taken from the first spectrum file) - **coordtable:** a list of files containing the vector information of HST downloaded in s01 Parameters ----------- meta metadata object s10: bool Is set to True when s10 is being performed s20: bool Is set to True when s20 is being performed Returns ---------- meta metadata object Notes: ---------- History: Written by Sebastian Zieba December 2021 """ filelist = ascii.read(meta.workdir + '/filelist.txt') aa = filelist['iorbit'].data bb = np.diff(aa) meta.norbit, meta.nvisit = len(np.insert(aa[1:][np.where(bb != 0)], 0, aa[0])), len(set(filelist['ivisit'].data)) meta.mask_sp = np.array([i[0] for i in filelist['instr']]) == 'G' meta.mask_di = np.array([i[0] for i in filelist['instr']]) == 'F' meta.files_sp = [meta.datadir + '/' + i for i in filelist['filenames'][meta.mask_sp].data] meta.files_di = [meta.datadir + '/' + i for i in filelist['filenames'][meta.mask_di].data] f = fits.open(meta.files_sp[0]) meta.ra = f[0].header['ra_targ'] * math.pi / 180.0 # stores right ascension meta.dec = f[0].header['dec_targ'] * math.pi / 180.0 # stores declination meta.coordtable = [] # table of spacecraft coordinates for i in range(max(filelist['ivisit']) + 1): meta.coordtable.append( meta.workdir + '/ancil/horizons/' + "/horizons_results_v" + str(i) + ".txt") ### # 03 # TODO: Q: Is it okay if I assume everything in datadir uses same Filter Grism pair? meta.filter = filelist['instr'][meta.mask_di][0] meta.grism = filelist['instr'][meta.mask_sp][0] meta.scans_sp = filelist['scan'][meta.mask_sp].data meta.iorbit_sp = filelist['iorbit'][meta.mask_sp].data meta.ivisit_sp = filelist['ivisit'][meta.mask_sp].data # the following list stores the cumulative orbit number meta.iorbit_sp_cumulative = np.zeros(len(meta.iorbit_sp), dtype=int) c = 0 for i in range(len(meta.iorbit_sp) - 1): if meta.iorbit_sp[i + 1] != meta.iorbit_sp[i]: c = c + 1 meta.iorbit_sp_cumulative[i + 1] = c # the following lists store the indices of spectral files where the orbit/visit increases meta.new_orbit_idx_sp = np.concatenate(([0], np.where(np.diff(meta.iorbit_sp)!=0)[0]+1)) meta.new_visit_idx_sp = np.concatenate(([0], np.where(np.diff(meta.ivisit_sp)!=0)[0]+1)) meta.iorbit_di = filelist['iorbit'][meta.mask_di].data meta.ivisit_di = filelist['ivisit'][meta.mask_di].data # the following list stores the cumulative orbit number for the direct images meta.iorbit_di_cumulative = np.zeros(len(meta.iorbit_di), dtype=int) c = 0 for i in range(len(meta.iorbit_di) - 1): if meta.iorbit_di[i + 1] != meta.iorbit_di[i]: c = c + 1 meta.iorbit_di_cumulative[i + 1] = c meta.t_mjd_sp = filelist['t_mjd'][meta.mask_sp].data meta.t_orbit_sp = filelist['t_orbit'][meta.mask_sp].data meta.t_visit_sp = filelist['t_visit'][meta.mask_sp].data meta.platescale = 0.13 # IR detector has plate scale of 0.13 arcsec/pixel meta.POSTARG1 = f[0].header['POSTARG1'] # x-coordinate of the observer requested target offset meta.POSTARG2 = f[0].header['POSTARG2'] # y-coordinate of the observer requested target offset meta.LTV1 = int(f[1].header['LTV1']) # X offset to get into physical pixels meta.LTV2 = int(f[1].header['LTV2']) # Y offset to get into physical pixels meta.subarray_size = f[1].header['SIZAXIS1'] # size of subarray if meta.grism == 'G102': meta.BEAMA_i = 41 meta.BEAMA_f = 248 elif meta.grism == 'G141': meta.BEAMA_i = 15 meta.BEAMA_f = 196 if s10: if 't_bjd' in filelist.keys(): meta.t_bjd_sp = filelist['t_bjd'][meta.mask_sp].data if 't_bjd' in filelist.keys(): meta.t_bjd_di = filelist['t_bjd'][meta.mask_di].data if s20: meta.rdnoise = 22.0 #read noise if meta.grism == 'G102': meta.flat = meta.pacmandir + '/data/flats/WFC3.IR.G102.flat.2.fits' elif meta.grism == 'G141': meta.flat = meta.pacmandir + '/data/flats/WFC3.IR.G141.flat.2.fits' return meta #03 def gaussian_kernel(meta, x, y): """ https://stackoverflow.com/questions/24143320/gaussian-sum-filter-for-irregular-spaced-points """ y = y / max(y) x.sort() resolution = min(len(x), 3000) x_eval = np.linspace(min(x), max(x), resolution) sigma = meta.smooth_sigma * 1e-10 /5 delta_x = x_eval[:, None] - x weights = np.exp(-delta_x*delta_x / (2*sigma*sigma)) / (np.sqrt(2*np.pi) * sigma) weights /= np.sum(weights, axis=1, keepdims=True) y_eval = np.dot(weights, y) y_eval = y_eval / max(y_eval) if meta.save_smooth_plot: plots.smooth(meta, x, y, x_eval, y_eval) return (x_eval, y_eval) # def gaussian_kernel_old(meta, x, y): # """ # https://matthew-brett.github.io/teaching/smoothing_intro.html # """ # # sigma = meta.smooth_sigma * 1e-10 # # y = y / max(y) # y_smoothed = np.zeros(y.shape) # for x_idx, x_val in tqdm(enumerate(x), desc='smoothing...', total=len(x)): # kernel = np.exp(-(x - x_val) ** 2 / (2 * sigma ** 2)) # kernel = kernel / sum(kernel) # y_smoothed[x_idx] = sum(y * kernel) # y_smoothed = y_smoothed / max(y_smoothed) # # if meta.save_smooth_plot: # plots.smooth(meta, x, y, x, y_smoothed) # # return (x, y_smoothed) #s10 def di_reformat(meta): """ This function was introduced because some observations have several DIs per orbit. The user can set in the pcf how they want to determine the DI target position in this case. """ iorbit_max = max(meta.iorbit_sp_cumulative) ivisit_max = max(meta.ivisit_sp) control_one_per_orbit = np.arange(iorbit_max + 1) control_one_per_visit = np.arange(ivisit_max + 1) reffile = ascii.read(meta.workdir + '/xrefyref.txt') #f = open(meta.workdir + "/xrefyref.txt", 'w') meta.ivisits_new_orbit = meta.iorbit_sp[meta.new_visit_idx_sp] meta.nvisits_in_orbit = np.diff(np.append(meta.iorbit_sp[meta.new_visit_idx_sp], np.array([max(meta.iorbit_sp) + 1]))) # First case: Every orbit has just one DI if np.array_equal(reffile['iorbit_cumul'], control_one_per_orbit): print('There is one DI per orbit.') meta.refpix = np.zeros((iorbit_max + 1, 3)) for i in range(iorbit_max + 1): meta.refpix[i] = [reffile['t_bjd'][i], reffile['pos1'][i], reffile['pos2'][i]] #print(reffile['t_bjd'][i], reffile['pos1'][i], reffile['pos2'][i], file=f) #f.close() # Second case: Every visit has just one DI elif np.array_equal(reffile['iorbit_cumul'], control_one_per_visit): print('There is one DI per visit.') meta.refpix = [] counter = 0 for i in range(len(meta.nvisits_in_orbit)): for j in range(meta.nvisits_in_orbit[counter]): meta.refpix.append([reffile['t_bjd'][counter], reffile['pos1'][counter], reffile['pos2'][counter]]) counter = counter + 1 meta.refpix = np.array(meta.refpix) # Third case: Every orbit contains at least one DI. But there is at least one orbit with more than one DI. elif set(control_one_per_orbit) == set(reffile['iorbit_cumul']): print('There is at least one orbit with at least more than one DI') meta.refpix = np.zeros((iorbit_max + 1, 3)) for i in range(iorbit_max + 1): mask_i = reffile['iorbit'] == i if meta.di_multi == 'median': meta.refpix[i] = [np.median(reffile['t_bjd'][mask_i]), np.median(reffile['pos1'][mask_i]), np.median(reffile['pos2'][mask_i])] #print(np.median(reffile['t_bjd'][mask_i]), np.median(reffile['pos1'][mask_i]), np.median(reffile['pos2'][mask_i]), file=f) elif meta.di_multi == 'latest': meta.refpix[i] = [reffile['t_bjd'][mask_i][-1], reffile['pos1'][mask_i][-1], reffile['pos2'][mask_i][-1]] #print(reffile['t_bjd'][mask_i][-1], reffile['pos1'][mask_i][-1], reffile['pos2'][mask_i][-1], file=f) #f.close() # TODO add this check # Third case. Not every orbit has a DI. if set(control_one_per_orbit) != set(reffile['iorbit_cumul']) and len(set(control_one_per_orbit)) < len( set(reffile['iorbit_cumul'])): print('Not every orbit has a DI.') #f.close() #s20 def get_wave_grid(meta): """ Gets grid of wavelength solutions for each orbit and row. """ if meta.grism == 'G102': from ..lib import geometry102 as geo elif meta.grism == 'G141': from ..lib import geometry141 as geo wave_grid = np.empty((meta.norbit*meta.nvisit, meta.subarray_size, meta.subarray_size)) #calculates wavelength solution row by row for each orbit for i in range(meta.norbit): for j in range(meta.subarray_size): disp_solution = geo.dispersion(meta.refpix[i,1], -meta.LTV2+j) delx = 0.5 + np.arange(meta.subarray_size) - (meta.refpix[i,2] + meta.LTV1 + meta.POSTARG1/meta.platescale) wave_grid[i, j, :] = disp_solution[0] + delx*disp_solution[1] return wave_grid def get_flatfield(meta): #function that flatfields a data array D, which starts at [minr, cmin] of hdu[1].data """ Opens the flat file and uses it for bad pixel masking. """ flat = fits.open(meta.flat) #reads in flatfield cube WMIN = flat[0].header['WMIN'] #constants for computing flatfield coefficients WMAX = flat[0].header['WMAX'] #print('flatfield:', WMIN, WMAX) a0 = flat[0].data[-meta.LTV1:-meta.LTV1+meta.subarray_size, -meta.LTV2:-meta.LTV2+meta.subarray_size] a1 = flat[1].data[-meta.LTV1:-meta.LTV1+meta.subarray_size, -meta.LTV2:-meta.LTV2+meta.subarray_size] a2 = flat[2].data[-meta.LTV1:-meta.LTV1+meta.subarray_size, -meta.LTV2:-meta.LTV2+meta.subarray_size] flatfield = [] for i in range(meta.norbit*meta.nvisit): wave = meta.wave_grid[i, :] x = (wave - WMIN)/(WMAX-WMIN) flatfield.append(a0+a1*x+a2*x**2) flatfield[i][flatfield[i] < 0.5] = -1. #sets flatfield pixels below 0.5 to -1 so they can be masked return flatfield def peak_finder(array, i, ii, orbnum, meta): # determine the aperture cutout rowmedian = np.median(array, axis=1) # median of every row rowmedian_absder = abs( rowmedian[1:] - rowmedian[:-1]) # absolute derivative in order to determine where the spectrum is # we use scipy.signal.find_peaks to determine in which rows the spectrum starts and ends # TODO: Think about better values for height and distance # TODO: Finding the row with the highest change in flux (compared to row above and below) isnt robust against outliers! peaks, _ = find_peaks(rowmedian_absder, height=max(rowmedian_absder * 0.3), distance=2) # peaks = peaks[:2] # only take the two biggest peaks (there should be only 2) peaks = np.array([min(peaks[:2]), max(peaks[:2]) + 1]) if meta.save_utr_plot or meta.show_utr_plot: plots.utr(array, meta, i, ii, orbnum, rowmedian, rowmedian_absder, peaks) return peaks def median_abs_dev(vec): """ Used to determine the variance for the background count estimate """ med = ma.median(vec) return ma.median(abs(vec - med)) def read_refspec(meta): """ Reads in the reference spectrum """ refspec = np.loadtxt(meta.workdir + '/ancil/refspec/refspec.txt').T x_refspec, y_refspec = refspec[0]*1e10, refspec[1]/max(refspec[1]) return (x_refspec, y_refspec) def residuals2(params, x1, y1, x2, y2): """ calculate residuals for leastsq. """ a, b, c = params x1=np.array(x1) x2=np.array(x2) y1=np.array(y1) y2=np.array(y2) f = interp1d(x1, y1, kind='cubic') fit = f(a+b*x2)*c return fit - y2 def correct_wave_shift_fct_0(meta, orbnum, cmin, cmax, spec_opt, i): template_waves = meta.wave_grid[0, int(meta.refpix[orbnum, 1]) + meta.LTV1, cmin:cmax] g102mask = template_waves > 8200 # we dont use the spectrum below 8200 angstrom for the interpolation as the reference bandpass cuts out below this wavelength x_refspec, y_refspec = read_refspec(meta) # TODO: Try to make this look nicer x_refspec_new = np.concatenate((np.linspace(-5000, min(x_refspec)+1, 10, endpoint=True), x_refspec, np.linspace(max(x_refspec) + 350, 30000, 10, endpoint=False))) y_refspec_new = np.concatenate((np.zeros(10), y_refspec, np.zeros(10))) # TODO: will break if optimal extractions isnt used! #x_data & y_data is the spectrum if no wavelength correction would be performed x_data = template_waves[g102mask] y_data = (spec_opt / max(spec_opt))[g102mask] p0 = [0, 1, 1] # initial guess for least squares leastsq_res = leastsq(residuals2, p0, args=(x_refspec_new, y_refspec_new, x_data, y_data))[0] if meta.save_refspec_fit_plot or meta.show_refspec_fit_plot: plots.refspec_fit(x_refspec_new, y_refspec_new, p0, x_data, y_data, leastsq_res, meta, i) # for all other but first exposure in visit exposures x_data_firstexpvisit = leastsq_res[0] + template_waves * leastsq_res[1] y_data_firstexpvisit = np.copy(y_data) # np.savetxt('testing_exp0.txt', list(zip(x_data_firstexpvisit, y_data_firstexpvisit))) # np.savetxt('testing_firstexp.txt', list(zip(template_waves, spec_opt/max(spec_opt)))) return x_data_firstexpvisit, y_data_firstexpvisit, leastsq_res def correct_wave_shift_fct_00(meta, orbnum, cmin, cmax, spec_opt, i): template_waves = meta.wave_grid[0, int(meta.refpix[orbnum, 1]) + meta.LTV1, cmin:cmax] x_refspec, y_refspec = template_waves, spec_opt / max(spec_opt) # TODO: Try to make this look nicer x_refspec_new = np.concatenate((np.linspace(-5000, min(x_refspec)+1, 10, endpoint=True), x_refspec, np.linspace(max(x_refspec) + 350, 30000, 10, endpoint=False))) y_refspec_new = np.concatenate((np.zeros(10), y_refspec, np.zeros(10))) # TODO: will break if optimal extractions isnt used! #x_data & y_data is the spectrum if no wavelength correction would be performed x_data = template_waves y_data = (spec_opt / max(spec_opt)) p0 = [0, 1, 1] # initial guess for least squares leastsq_res = leastsq(residuals2, p0, args=(x_refspec_new, y_refspec_new, x_data, y_data))[0] if meta.save_refspec_fit_plot or meta.show_refspec_fit_plot: plots.refspec_fit(x_refspec_new, y_refspec_new, p0, x_data, y_data, leastsq_res, meta, i) # for all other but first exposure in visit exposures x_data_firstexpvisit = leastsq_res[0] + template_waves * leastsq_res[1] y_data_firstexpvisit = np.copy(y_data) # np.savetxt('testing_exp0.txt', list(zip(x_data_firstexpvisit, y_data_firstexpvisit))) # np.savetxt('testing_firstexp.txt', list(zip(template_waves, spec_opt/max(spec_opt)))) return x_data_firstexpvisit, y_data_firstexpvisit, leastsq_res def correct_wave_shift_fct_1(meta, orbnum, cmin, cmax, spec_opt, x_data_firstexpvisit, y_data_firstexpvisit, i): # TODO: So bad too x_model = np.concatenate((np.linspace(-5000, min(x_data_firstexpvisit)+1, 10, endpoint=True), x_data_firstexpvisit, np.linspace(max(x_data_firstexpvisit) + 350, 30000, 10, endpoint=False))) y_model = np.concatenate((np.zeros(10), y_data_firstexpvisit, np.zeros(10))) x_data = meta.wave_grid[0, int(meta.refpix[orbnum, 1]) + meta.LTV1, cmin:cmax] y_data = spec_opt / max(spec_opt) p0 = [0, 1, 1] leastsq_res = leastsq(residuals2, p0, args=(x_model, y_model, x_data, y_data))[0] if meta.save_refspec_fit_plot or meta.show_refspec_fit_plot: plots.refspec_fit(x_model, y_model, p0, x_data, y_data, leastsq_res, meta, i) wvls = leastsq_res[0] + x_data * leastsq_res[1] return wvls, leastsq_res #30 def read_fitfiles(meta): """ read in the files (white or spectroscopic) which will be fitted """ if meta.s30_fit_white: print('White light curve fit will be performed') files = [] if meta.s30_most_recent_s20: lst_dir = os.listdir(meta.workdir + "/extracted_lc/") lst_dir = sn(lst_dir) white_dir = lst_dir[-1] files.append(meta.workdir + "/extracted_lc/" + white_dir + "/lc_white.txt") print('using most recent s20 run: {0}'.format(white_dir)) else: files.append(meta.s30_white_file_path) print('using user set white file: '.format(meta.s30_white_file_path)) if meta.grism == 'G102': meta.wavelength_list = [1.0] elif meta.grism == 'G141': meta.wavelength_list = [1.4] elif meta.s30_fit_spec: print('Spectroscopic light curve fit(s) will be performed') if meta.s30_most_recent_s21: # find most recent bins directory lst_dir = np.array([f.path for f in os.scandir(meta.workdir + "/extracted_sp/") if f.is_dir()]) dirs_bool = np.array(['/bins' in i for i in lst_dir]) lst_dir = lst_dir[dirs_bool] dirs_times = [i[-19:] for i in lst_dir] # there are 19 digits in the typical '%Y-%m-%d_%H-%M-%S' format # sort the times times_sorted = sn(dirs_times) # most recent time recent_time = times_sorted[-1] idx = 0 for i in range(len(lst_dir)): if lst_dir[i][-19:] == recent_time: idx = i spec_dir_full = lst_dir[idx] #spec_dir_full = meta.workdir + "/extracted_sp/" + spec_dir files = glob.glob(os.path.join(spec_dir_full, "*.txt")) files = sn(files) print('using most recent s21 run: {0}'.format(spec_dir_full)) else: spec_dir_full = meta.s30_spec_dir_path files = glob.glob(os.path.join(spec_dir_full, "*.txt")) # files = sn(files) print('using user set spectroscopic directory: '.format(meta.s30_spec_dir_path)) spec_dir_wvl_file = spec_dir_full + '/wvl_table.dat' meta.wavelength_list = ascii.read(spec_dir_wvl_file)['wavelengths'] else: print('Neither s30_fit_white nor s30_fit_spec are True!') print('Identified file(s) for fitting:', files) return files, meta def format_params_for_Model(theta, params, meta, fit_par): nvisit = int(meta.nvisit) params_updated = [] fixed_array = np.array(fit_par['fixed']) tied_array = np.array(fit_par['tied']) free_array = [] for i in range(len(fixed_array)): if fixed_array[i].lower() == 'true' and tied_array[i] == -1: for ii in range(nvisit): free_array.append(False) if fixed_array[i].lower() == 'true' and not tied_array[i] == -1: free_array.append(False) if fixed_array[i].lower() == 'false' and tied_array[i] == -1: free_array.append(True) for ii in range(nvisit-1): free_array.append(False) if fixed_array[i].lower() == 'false' and not tied_array[i] == -1: free_array.append(True) free_array = np.array(free_array) # #TODO: Oida? # def repeated(array, index, n_times): # array_new = [] # index_index = 0 # for ii in range(len(array)): # if ii in index: # array_new.append([array[index[index_index]]] * n_times) # else: # array_new.append([array[ii]]) # index_index = index_index + 1 # array_new2 = np.array([item for sublist in array_new for item in sublist]) # return array_new2 theta_new = np.copy(theta) params_updated = np.copy(params) params_updated[free_array] = theta_new #print('free_array', free_array) #print('params_updated', params_updated) return np.array(params_updated) def computeRMS(data, maxnbins=None, binstep=1, isrmserr=False): """ COMPUTE ROOT-MEAN-SQUARE AND STANDARD ERROR OF DATA FOR VARIOUS BIN SIZES Taken from POET: https://github.com/kevin218/POET/blob/master/code/lib/correlated_noise.py """ # data = fit.normresiduals # maxnbin = maximum # of bins # binstep = Bin step size # bin data into multiple bin sizes npts = data.size if maxnbins is None: maxnbins = npts / 10. binsz = np.arange(1, maxnbins + binstep, step=binstep, dtype=int) nbins = np.zeros(binsz.size, dtype=int) rms = np.zeros(binsz.size) rmserr = np.zeros(binsz.size) for i in range(binsz.size): nbins[i] = int(np.floor(data.size / binsz[i])) bindata = np.zeros(nbins[i], dtype=float) # bin data # ADDED INTEGER CONVERSION, mh 01/21/12 for j in range(nbins[i]): bindata[j] = data[j * binsz[i]:(j + 1) * binsz[i]].mean() # get rms rms[i] = np.sqrt(np.mean(bindata ** 2)) rmserr[i] = rms[i] / np.sqrt(2. * nbins[i]) # expected for white noise (WINN 2008, PONT 2006) stderr = (data.std() / np.sqrt(binsz)) * np.sqrt(nbins / (nbins - 1.)) if isrmserr is True: return rms, stderr, binsz, rmserr else: return rms, stderr, binsz def format_params_for_sampling(params, meta, fit_par): #FIXME: make sure this works for cases when nvisit>1 nvisit = int(meta.nvisit) fixed_array = np.array(fit_par['fixed']) tied_array = np.array(fit_par['tied']) free_array = [] for i in range(len(fixed_array)): if fixed_array[i].lower() == 'true' and tied_array[i] == -1: for ii in range(nvisit): free_array.append(False) if fixed_array[i].lower() == 'true' and not tied_array[i] == -1: free_array.append(False) if fixed_array[i].lower() == 'false' and tied_array[i] == -1: free_array.append(True) for ii in range(nvisit-1): free_array.append(False) if fixed_array[i].lower() == 'false' and not tied_array[i] == -1: free_array.append(True) free_array = np.array(free_array) theta = params[free_array] return np.array(theta) def make_lsq_rprs_txt(vals, errs, idxs, meta): """ Saves the rprs vs wvl as a txt file as resulting from the lsq. """ if not os.path.isdir(meta.workdir + meta.fitdir + '/lsq_res'): os.makedirs(meta.workdir + meta.fitdir + '/lsq_res') f_lsq = open(meta.workdir + meta.fitdir + '/lsq_res' + "/lsq_rprs.txt", 'w') rp_idx = np.where(np.array(meta.labels) == 'rp')[0][0] rprs_vals_lsq = [vals[ii][idxs[0][rp_idx]] for ii in range(len(vals))] rprs_errs_lsq = [errs[ii][idxs[0][rp_idx]] for ii in range(len(errs))] file_header = ['wavelength (micron)', 'rprs', 'rprs_err', 'chi2red'] print("#{: <24} {: <25} {: <25} {: <25}".format(*file_header), file=f_lsq) for row in zip(meta.wavelength_list, rprs_vals_lsq, rprs_errs_lsq, meta.chi2red_list): print("{: <25} {: <25} {: <25} {: <25}".format(*row), file=f_lsq) f_lsq.close() def make_mcmc_rprs_txt(vals_mcmc, errs_lower_mcmc, errs_upper_mcmc, meta): """ Saves the rprs vs wvl as a txt file as resulting from the MCMC. """ rp_idx = np.where(np.array(meta.labels) == 'rp')[0][0] medians = np.array(vals_mcmc).T[rp_idx] errors_lower = np.array(errs_lower_mcmc).T[rp_idx] errors_upper = np.array(errs_upper_mcmc).T[rp_idx] if not os.path.isdir(meta.workdir + meta.fitdir + '/mcmc_res'): os.makedirs(meta.workdir + meta.fitdir + '/mcmc_res') f_mcmc = open(meta.workdir + meta.fitdir + '/mcmc_res' + "/mcmc_rprs.txt", 'w') file_header = ['wavelength (micron)', 'rprs', 'rprs_err_lower', 'rprs_err_upper'] print("#{: <24} {: <25} {: <25} {: <25}".format(*file_header), file=f_mcmc) for row in zip(meta.wavelength_list, medians, errors_lower, errors_upper): print("{: <25} {: <25} {: <25} {: <25}".format(*row), file=f_mcmc) f_mcmc.close() def make_nested_rprs_txt(vals_nested, errs_lower_nested, errs_upper_nested, meta): """ Saves the rprs vs wvl as a txt file as resulting from the MCMC. """ rp_idx = np.where(np.array(meta.labels) == 'rp')[0][0] medians = np.array(vals_nested).T[rp_idx] errors_lower = np.array(errs_lower_nested).T[rp_idx] errors_upper = np.array(errs_upper_nested).T[rp_idx] if not os.path.isdir(meta.workdir + meta.fitdir + '/nested_res'): os.makedirs(meta.workdir + meta.fitdir + '/nested_res') f_mcmc = open(meta.workdir + meta.fitdir + '/nested_res' + "/nested_rprs.txt", 'w') file_header = ['wavelength (micron)', 'rprs', 'rprs_err_lower', 'rprs_err_upper'] print("#{: <24} {: <25} {: <25} {: <25}".format(*file_header), file=f_mcmc) for row in zip(meta.wavelength_list, medians, errors_lower, errors_upper): print("{: <25} {: <25} {: <25} {: <25}".format(*row), file=f_mcmc) f_mcmc.close() def quantile(x, q): return np.percentile(x, [100. * qi for qi in q]) def weighted_mean(data, err): #calculates the weighted mean for data points data with std devs. err ind = err != 0.0 weights = 1.0/err[ind]**2 mu = np.sum(data[ind]*weights)/np.sum(weights) var = 1.0/np.sum(weights) return [mu, np.sqrt(var)] def residuals(params, template_waves, template, spectrum, error): shift, scale = params fit = scale*np.interp(template_waves, template_waves-shift, spectrum) x = (template-fit)/error return (template-fit)/error def interpolate_spectrum(spectrum, error, template, template_waves): p0 = [1., 1.0] #initial guess for parameters shift and scale plsq, success = leastsq(residuals, p0, args=(template_waves, template, spectrum, error)) shift, scale = plsq interp_spectrum = np.interp(template_waves, template_waves-shift, spectrum) interp_error = np.interp(template_waves, template_waves-shift, error) return [interp_spectrum, interp_error, shift] # def read_dict(filename): # #with open(filename,"r") as text: # # return dict(line.strip().split() for line in text) # dict = {} # with open(filename,"r") as text: # for line in text: # key, value = line.split() # value = str_to_num(value) # if value == 'True': value = True # if value == 'False': value = False # dict[key] = value # return dict #def getphase(t): # phase = (t - t0)/period # return phase - int(phase)
{ "alphanum_fraction": 0.6301002646, "author": null, "avg_line_length": 39.1869031378, "converted": null, "ext": "py", "file": null, "hexsha": "1d1071c4a9b2c4886fa373e74d9d471cc81f3097", "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-29T13:37:31.000Z", "max_forks_repo_forks_event_min_datetime": "2022-03-29T13:37:31.000Z", "max_forks_repo_head_hexsha": "2eb1e4b450c97dc28d5a05b3ebddd80706cfca79", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sebastian-zieba/PACMAN", "max_forks_repo_path": "src/pacman/lib/util.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "2eb1e4b450c97dc28d5a05b3ebddd80706cfca79", "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": "sebastian-zieba/PACMAN", "max_issues_repo_path": "src/pacman/lib/util.py", "max_line_length": 178, "max_stars_count": 1, "max_stars_repo_head_hexsha": "2eb1e4b450c97dc28d5a05b3ebddd80706cfca79", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sebastian-zieba/PACMAN", "max_stars_repo_path": "src/pacman/lib/util.py", "max_stars_repo_stars_event_max_datetime": "2022-03-23T10:26:33.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-23T10:26:33.000Z", "num_tokens": 8086, "path": null, "reason": "import numpy,from scipy,from astropy", "repo": null, "save_path": null, "sha": null, "size": 28724 }
import numpy.testing as npt import torch import espaloma as esp from espaloma.utils.geometry import ( _sample_four_particle_torsion_scan, _timemachine_signed_torsion_angle, ) def test_dihedral_vectors(): import espaloma as esp distribution = torch.distributions.normal.Normal( loc=torch.zeros(5, 3), scale=torch.ones(5, 3) ) left = distribution.sample() right = distribution.sample() npt.assert_almost_equal( esp.mm.geometry._angle(left, right).numpy(), esp.mm.geometry._dihedral(left, right).numpy(), decimal=3, ) def test_dihedral_points(): n_samples = 1000 # get geometries xyz_np = _sample_four_particle_torsion_scan(n_samples) # compute dihedrals using timemachine (numpy / JAX) ci, cj, ck, cl = ( xyz_np[:, 0, :], xyz_np[:, 1, :], xyz_np[:, 2, :], xyz_np[:, 3, :], ) theta_timemachine = _timemachine_signed_torsion_angle(ci, cj, ck, cl) # compute dihedrals using espaloma (PyTorch) xyz = torch.tensor(xyz_np) x0, x1, x2, x3 = xyz[:, 0, :], xyz[:, 1, :], xyz[:, 2, :], xyz[:, 3, :] theta_espaloma = esp.dihedral(x0, x1, x2, x3).numpy() npt.assert_almost_equal( theta_timemachine, theta_espaloma, decimal=3, )
{ "alphanum_fraction": 0.6313364055, "author": null, "avg_line_length": 24.5660377358, "converted": null, "ext": "py", "file": null, "hexsha": "444b35b04f16bac967c4be718d1ea887e7b2f884", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-19T20:49:08.000Z", "max_forks_repo_forks_event_min_datetime": "2020-11-13T19:24:09.000Z", "max_forks_repo_head_hexsha": "cae5664446d0c89025de5eb827f507d8af64e2d4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cschlick/espaloma", "max_forks_repo_path": "espaloma/mm/tests/test_dihedral.py", "max_issues_count": 72, "max_issues_repo_head_hexsha": "cae5664446d0c89025de5eb827f507d8af64e2d4", "max_issues_repo_issues_event_max_datetime": "2022-03-25T14:24:52.000Z", "max_issues_repo_issues_event_min_datetime": "2020-04-16T18:49:51.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "cschlick/espaloma", "max_issues_repo_path": "espaloma/mm/tests/test_dihedral.py", "max_line_length": 75, "max_stars_count": 60, "max_stars_repo_head_hexsha": "cae5664446d0c89025de5eb827f507d8af64e2d4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cschlick/espaloma", "max_stars_repo_path": "espaloma/mm/tests/test_dihedral.py", "max_stars_repo_stars_event_max_datetime": "2022-03-29T17:53:17.000Z", "max_stars_repo_stars_event_min_datetime": "2020-05-15T13:21:55.000Z", "num_tokens": 375, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1302 }
import random import numpy as np class Dataset: """ A mapping from column names to immutable arrays of equal length. """ def __init__(self, **data): self._data = {} self._length = None super().__init__() for column, data in data.items(): self[column] = data @property def columns(self): return sorted(self._data.keys()) def copy(self): data = {x: self[x].copy() for x in self.columns} return type(self)(**data) def sample(self, size): indices = random.sample(range(len(self)), size) return self[indices] def __len__(self): return self._length def __contains__(self, column): return column in self._data def __getattr__(self, column): if column in self: return self[column] raise AttributeError def __iter__(self): for index in range(len(self)): yield tuple(self[x][index] for x in self.columns) def __eq__(self, other): if not isinstance(other, type(self)): return NotImplemented if self.columns != other.columns: return False for column in self.columns: if not (self[column] == other[column]).all(): return False return True def __getitem__(self, key): if isinstance(key, slice): data = {x: self[x][key] for x in self.columns} return type(self)(**data) if isinstance(key, (tuple, list)) and isinstance(key[0], int): data = {x: self[x][key] for x in self.columns} return type(self)(**data) if isinstance(key, (tuple, list)) and isinstance(key[0], str): data = {x: self[x] for x in key} return type(self)(**data) return self._data[key].copy() def __setitem__(self, key, data): if isinstance(key, (tuple, list)) and isinstance(key[0], str): for column, data in zip(key, data): self[column] = data return if isinstance(key, (tuple, list)) and isinstance(key[0], int): raise NotImplementedError('column content is immutable') data = np.array(data) data.setflags(write=False) if not data.size: raise ValueError('must not be empty') if not self._length: self._length = len(data) if len(data) != self._length: raise ValueError('must have same length') self._data[key] = data def __delitem__(self, key): if isinstance(key, (tuple, list)): for column in key: del self._data[column] return del self._data[key] def __str__(self): message = '' for column in self.columns: message += '{} ({}):\n\n'.format(column, self[column].dtype) message += str(self[column]) + '\n\n' return message def __getstate__(self): return {'length': self._length, 'data': self._data} def __setstate__(self, state): self._length = state['length'] self._data = state['data']
{ "alphanum_fraction": 0.5430769231, "author": null, "avg_line_length": 31.5533980583, "converted": null, "ext": "py", "file": null, "hexsha": "b890ea8f1dfb10602452f7f081689d7b823747de", "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": "d77cc621d452c9ecf48d9ac80349b41aeb842412", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "FedericoMolinaChavez/tesis-research", "max_forks_repo_path": "sets-master/sets-master/sets/core/dataset.py", "max_issues_count": 4, "max_issues_repo_head_hexsha": "d77cc621d452c9ecf48d9ac80349b41aeb842412", "max_issues_repo_issues_event_max_datetime": "2022-02-18T12:56:32.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-09T20:33:57.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "FedericoMolinaChavez/tesis-research", "max_issues_repo_path": "sets-master/sets-master/sets/core/dataset.py", "max_line_length": 73, "max_stars_count": null, "max_stars_repo_head_hexsha": "d77cc621d452c9ecf48d9ac80349b41aeb842412", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "FedericoMolinaChavez/tesis-research", "max_stars_repo_path": "sets-master/sets-master/sets/core/dataset.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 719, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 3250 }
import os import numpy as np import pretty_midi import torch import dataprocess import matplotlib.pyplot as plt import dataprocess # Directory to load processed midi files processed_dir = 'processed_midi_files\\' # Directory to load processed event files processed_events_dir = 'processed_event_indices_files/' # Number of files in the data set max_files = 1281 big_max_files = 3845 # Twinkle twinkle example midi twinkle_notes = np.array([ # C major pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('C4'), start=0, end=1), pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('E4'), start=0, end=1), pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('G4'), start=0, end=1), # Twinkle, twinkle pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('C5'), start=0, end=0.25), pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('C5'), start=0.25, end=0.5), pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('G5'), start=0.5, end=0.75), pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('G5'), start=0.75, end=1), # F major pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('F4'), start=1, end=2), pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('G4'), start=1, end=2), pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('C5'), start=1, end=2), # Little pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('A5'), start=1, end=1.25), pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('A5'), start=1.25, end=1.5), # C major pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('C4'), start=1.5, end=2), pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('E4'), start=1.5, end=2), pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('G4'), start=1.5, end=2), # Star pretty_midi.Note(velocity=100, pitch=pretty_midi.note_name_to_number('G5'), start=1.5, end=2), ]) def device(tensor=None): """ Get the available computaiton device """ return 'cuda' if torch.cuda.is_available() else 'cpu' def use_cuda(): return torch.cuda.is_available() def here(file_name): """ Get the given file name relative to the working directory """ return os.path.abspath(os.path.join(os.path.dirname(__file__), file_name)) def pitches_to_midi(pitches, duration=0.25, velocity=100): """ Turn array of pitches into full midi data """ notes = [] time_acc = 0 for i in range(len(pitches)): notes.append(pretty_midi.Note(velocity, int(pitches[i]), time_acc, time_acc + duration)) time_acc += duration return np.array(notes) def pitchesvelocity_to_midi(data, duration=0.25, velocity=100): """ Turn array of pitches into full midi data """ notes = [] time_acc = 0 for i in range(len(data)): notes.append(pretty_midi.Note(int(data[i][0]), int(data[i][1]), time_acc, time_acc + duration)) time_acc += duration return np.array(notes) def array_to_midi(input): """ Convert array to the pretty_midi format """ notes = [] for note in input: notes.append(pretty_midi.Note(int(note[0]), int(note[1]), note[2], note[3])) return np.array(notes) def midi_to_array(midi_path): """ Read MIDI file into a 4D array where each element is [velocity, pitch, start, end] """ # Get MIDI data data = pretty_midi.PrettyMIDI(midi_path).instruments[0].notes # Init 4D array array = np.zeros((len(data),4)) # Add MIDI data to array for i in range(len(data)): array[i] = ([data[i].velocity, data[i].pitch, data[i].start, data[i].end]) # Return array return array def write_piano_midi(notes, write_path): """ Output an array of notes to the desired path as piano MIDI """ # Create the output structure output = pretty_midi.PrettyMIDI() # Create the instrument program and instrument piano_program = pretty_midi.instrument_name_to_program('Acoustic Grand Piano') piano = pretty_midi.Instrument(program=piano_program) # Set the piano notes to the list of notes piano.notes = notes # Give the output our instrument output.instruments.append(piano) # Write the output output.write(write_path) def write_processed_midi(dataset_path): """ Process all the midi into text data """ data = [] file_num = 0 curr_dir = os.path.dirname(__file__) # If the directory holding the processed files doesn't exist if(not os.path.exists(processed_dir)): os.mkdir(processed_dir) # Perform a walk in the dataset directory for root, dirs, files in os.walk(dataset_path): # For each file in the directory and subdirectories for file in files: # For all midi files if file.endswith(".midi"): print("Util: Saving midi_", file_num, "...") # Grab the midi and generate a file name temp = midi_to_array(os.path.join(root, file)) file_name = os.path.join(curr_dir, processed_dir + 'midi_'+str(file_num)) # Save the file np.save(file_name, temp) # Increment the file number file_num += 1 print("Util: Finished saving MIDI to array.", file_num + 1, "total files.") return data def read_processed_midi(file_num): """ Read a processed midi file given its file number """ if (file_num <= max_files and file_num >= 0): curr_dir = os.path.dirname(__file__) path = os.path.join(curr_dir, processed_dir + 'midi_'+str(file_num) + ".npy") return np.load(path) def load_all_predata(n=None): data = [] # Set the range if (n is None) or (n > max_files): n = max_files # Get the data for i in range(n): data.append(read_processed_midi(i)) data = np.array(data) data.view(np.float) return torch.from_numpy(data) def load_all_predata_event_indices(n=None): data = [] # Set the range if (n is None) or (n > max_files): n = max_files # Get the data for i in range(n+1): data = np.append(data, read_processed_event_index(i)) data = np.array(data) data.view(np.float) return data def load_all_predata_event_indices_augmented(n=None): """ Load all the preprocessed augmented data If n is specified, load only that number of files, otherwise load them all """ data = [] # Set the range if (n is None) or (n > big_max_files): n = big_max_files # Get the data for i in range(n+1): data = np.append(data, read_processed_event_index(i)) data = np.array(data) data.view(np.float) return data def load_all_predata_pitchonly(n=None): data = [] # Set the range if (n is None) or (n > max_files): n = max_files # Get the data for i in range(n): arr = read_processed_midi(i) for j in range(len(arr)): data.append(arr[j][1]) data = np.array(data) data.view(np.float) return torch.from_numpy(data) def load_all_predata_pitchvelocityonly(n=None): data = [] # Set the range if (n is None) or (n > max_files): n = max_files # Get the data for i in range(n): arr = read_processed_midi(i) for j in range(len(arr)): data.append([arr[j][0], arr[j][1]]) data = np.array(data) data.view(np.float) return torch.from_numpy(data) def save_model(model, path): """ Save the whole PyTorch model """ torch.save(model, here(path)) def load_model(path): """ Load the whole PyTorch model """ model = torch.load(here(path)) model.eval() return model # A variable to determine the directory to store the models in models_path = 'models/' def create_dir(dir_path): """ Creates a directory at the specified path """ if(not os.path.exists(dir_path)): os.mkdir(dir_path) def get_latest_model_num(): """ Gets the latest model number in the models directory """ if(not os.path.exists(models_path)): create_dir(models_path) model_num = 0 for root, dirs, files, in os.walk(models_path): for dir in dirs: if dir.startswith('model_'): temp_num = int(dir[len('model_'):]) if temp_num > model_num: model_num = temp_num return model_num def get_latest_gen_num(model_num=None): """ Gets the latest gen_num, if model_num is not given the latest model_num will be given """ if model_num==None: model_num = get_latest_model_num() gen_num = 0 for root, dirs, files, in os.walk(models_path+'model_'+str(model_num)+'/gens/'): for file in files: if file.endswith('.midi'): temp_num = int(file[len('gen_'):-len('.midi')]) if temp_num > gen_num: gen_num = temp_num return gen_num def save_on_train(model, losses, num_epochs, params, model_name=None): """ Creates a loss vs epoch plot, Creates a directory for the current model, then saves the model, plot, loss, and params for the model params - An array containing all the params in order losses - An array containing all the losses num_epoch - Number of epochs model_name must follow format trained_model_x.pt, where x is an integer """ create_dir(models_path) model_num = 0 if model_name==None: model_num = get_latest_model_num() if(os.path.exists(models_path+'model_'+str(model_num))): model_num += 1 model_name = 'trained_model_'+str(model_num)+'.pt' dir_path = models_path+'model_'+str(model_num)+'/' else: if model_name[-3:] != ".pt" or model_name[:len("trained_model_")] != "trained_model_" or not model_name.replace("trained_model_","")[:-3].isdigit(): print("Error: model_name is incorrect and does not follow the format \"trained_model_x.pt\" where x is an integer") return model_num = model_name.replace("trained_model_","")[:-len('.pt')] dir_path = models_path+'model_'+model_num+'/' create_dir(dir_path) create_dir(dir_path+'gens/') x_axis = np.arange(num_epochs-1) fig, (loss_plot) = plt.subplots(1,1) loss_plot.plot(x_axis, losses) loss_plot.set_xlabel('epochs') loss_plot.set_ylabel('loss') loss_plot.legend() fig.savefig(dir_path+'loss.png') np.savetxt(dir_path+'losses_'+str(model_num)+'.txt', losses) np.savetxt(dir_path+'params_'+str(model_num)+'.txt', params) torch.save(model, dir_path+model_name) def save_on_gen(input, midi_arr, model_num=None, gen_num=None): """ Saves the input and midi_file to a folder Will save to the latest model, and will create new gen file if no gen_num is specified Specified gen_num will overwrite a file Specified model_num will be saved into that model """ if model_num==None: model_num = get_latest_model_num() if gen_num==None: gen_num = get_latest_gen_num(model_num) if(os.path.exists(models_path+'model_'+str(model_num)+'/gens/gen_'+str(gen_num)+'_input.txt')): gen_num += 1 dir_path = models_path+'model_'+str(model_num)+'/gens/' np.savetxt(dir_path+'gen_'+str(gen_num)+'_input.txt', input) write_piano_midi(midi_arr, dir_path+'gen_'+str(gen_num)+'.midi') def load_param(model_num): """ Returns empty list if it does not exist Grabs the params of the specified model number """ param_path = models_path+'model_'+str(model_num)+'/params_'+str(model_num)+'.txt' if(os.path.exists(param_path)): return np.loadtxt(param_path) return [] def new_load_model(model_num=None): """ Returns empty list if it does not exist Grabs the model of the specified model number """ if model_num is None: model_num = get_latest_model_num() model_path = models_path+'model_'+str(model_num)+'/trained_model_'+str(model_num)+'.pt' if(os.path.exists(model_path)): return torch.load(model_path) return [] def write_all_processed_midi_to_event_indices(): """ Takes all processed midi, processes it into events, then indices and saves them into the processed_indices_dir """ create_dir(processed_events_dir) for i in range(max_files+1): midi_arr = read_processed_midi(i) event_arr = dataprocess.midi_array_to_event2(midi_arr) index_arr = dataprocess.events_to_indices(event_arr) np.save(processed_events_dir+'event_index_arr_'+str(i)+'.npy', index_arr) print("Saving file", i, "...") print("Complete!") def write_all_processed_midi_to_event_indices_augmented(n=None): """ Takes all processed midi, processes it into events, then indices and saves them into the processed_indices_dir """ create_dir(processed_events_dir) if (n is None) or (n > max_files): n = max_files fnum = 0 for i in range(n+1): midi_arr = read_processed_midi(i) event_arr = dataprocess.midi_array_to_event2(midi_arr) index_arr = dataprocess.events_to_indices(event_arr) # First augmentation midi_arr2 = midi_arr for j in midi_arr2: j[1] += 3 if j[1] > 127: j[1] = 127 event_arr2 = dataprocess.midi_array_to_event2(midi_arr2) index_arr2 = dataprocess.events_to_indices(event_arr2) # Second augmentation midi_arr3 = midi_arr for j in midi_arr3: j[1] -= 3 if j[1] < 0: j[1] = 0 event_arr3 = dataprocess.midi_array_to_event2(midi_arr3) index_arr3 = dataprocess.events_to_indices(event_arr3) # Save three versions, the original and two augmented np.save(processed_events_dir+'event_index_arr_'+str(fnum)+'.npy', index_arr) print("Saving file", fnum, "...") fnum += 1 np.save(processed_events_dir+'event_index_arr_'+str(fnum)+'.npy', index_arr2) print("Saving file", fnum, "...") fnum += 1 np.save(processed_events_dir+'event_index_arr_'+str(fnum)+'.npy', index_arr3) print("Saving file", fnum, "...") fnum += 1 print("Complete!") def read_processed_event_index(file_num): """ Read a processed event file given its file number """ return np.load(processed_events_dir+'event_index_arr_'+str(file_num)+'.npy')
{ "alphanum_fraction": 0.7249079017, "author": null, "avg_line_length": 31.896882494, "converted": null, "ext": "py", "file": null, "hexsha": "c2d3d5f7f007334c053da5ed55e457466e722d66", "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": "08329b49de6ee93456e3f394cc98954dded6ae3b", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cxcd/CPS803", "max_forks_repo_path": "util.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "08329b49de6ee93456e3f394cc98954dded6ae3b", "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": "cxcd/CPS803", "max_issues_repo_path": "util.py", "max_line_length": 150, "max_stars_count": null, "max_stars_repo_head_hexsha": "08329b49de6ee93456e3f394cc98954dded6ae3b", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cxcd/CPS803", "max_stars_repo_path": "util.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3712, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 13301 }
from pathlib import Path import warnings import cv2 import numpy as np from PIL import Image import torch from .colormap import voc_colormap class ToneLabel: def __init__(self, label: np.ndarray, ignore: set = {0}) -> None: assert label.dtype == np.uint8 self.data = label self.ignore = ignore @classmethod def load(cls, path: str, dtype=np.uint8): data = cv2.imread(path, cv2.IMREAD_GRAYSCALE) return cls(data.astype(dtype)) @property def shape(self) -> tuple: return self.data.shape def save(self, path: str): return cv2.imwrite(path, self.data) def get_tensor(self) -> torch.Tensor: return torch.from_numpy(self.data.astype(np.int32)) def visualize(self) -> Image.Image: colors = voc_colormap(range(200)).astype(np.uint8) return Image.fromarray(colors[self.data]) class ToneParameter: def __init__(self, tone_index: int, tone_type: str, mask, param: dict) -> None: self.tone_index = tone_index self.tone_type = tone_type self.mask = mask self.param = param def __repr__(self) -> str: return ( self.__class__.__name__ + "(tone_index={}, tone_type={}, param={})".format( self.tone_index, self.tone_type, self.param ) ) class ToneImageGenerator: def __init__(self, data_root: str = "./data/") -> None: self.tone_dataset = ToneDataset(data_root) def render(self, label: ToneLabel, line=None) -> np.ndarray: params = self.label_to_params(label) if line is None: # prepare a white image shape = params[0] img = np.ones(shape, dtype=np.uint8) * 255 else: img = line.copy() for tone_param in params[1:]: if tone_param.tone_type == "unlabeled": continue tone = self.generate(tone_param) img = np.minimum(tone, img) return img.astype(np.uint8) def label_index_to_param(self, lb: int) -> ToneParameter: tone_index = lb - 1 for tone_type in ToneDataset.tone_types: if 0 <= tone_index < len(self.tone_dataset.data[tone_type]): break tone_index -= len(self.tone_dataset.data[tone_type]) else: tone_type = "unlabeled" assert tone_index == 0 param = dict() if tone_type in {"gradation", "dark"}: pass elif tone_type == "effect": param["scale"] = 1.0 elif tone_type == "light": param["scale_inv"] = 1.0 param["angle"] = 0 param["value_scale"] = 1.0 tone_param = ToneParameter(tone_index, tone_type, None, param) return tone_param def label_to_params(self, label: ToneLabel) -> list: params = list() params.append(label.shape) # prepare label_set that renders label_set = set(np.unique(label.data)) label_set -= label.ignore for lb in label_set: mask = label.data == lb tone_param = self.label_index_to_param(lb) tone_param.mask = mask * 255.0 params.append(tone_param) return params def generate(self, tone_param: ToneParameter) -> np.ndarray: """generate screentones from tone_param modified from the code by Chengze Li. """ tile = self.tone_dataset.get(tone_param.tone_index, tone_param.tone_type) mask = tone_param.mask if tone_param.tone_type == "gradation": result = np.ones(mask.shape, np.float32) * 255.0 h_tile = tile.shape[0] mask_bin = mask == 255.0 xmin, xmax = np.where(np.any(mask_bin, axis=0))[0][[0, -1]] ymin, ymax = np.where(np.any(mask_bin, axis=1))[0][[0, -1]] h_box, w_box = ymax - ymin, xmax - xmin # NOTE: (h_box: height of a contour rectangular) + 1 <= (h_tile: height of a tone image) if h_tile >= h_box: crop = tile[0:h_box, 0:w_box] result[ymin:ymax, xmin:xmax] = crop else: warnings.warn( "Unexpected label. Unable to paste gradation.", RuntimeWarning ) elif tone_param.tone_type == "effect": # height, width for resize height_t, width_t = tile.shape height, width = mask.shape scaler = height / float(height_t) scalec = width / float(width_t) scale = (max(scaler, scalec) + 1) / 2 height_t = max(height, int(height_t * scale) + 1) width_t = max(width, int(width_t * scale) + 1) newtile = np.ones((height_t + 1, width_t + 1), np.float32) * 255.0 effect = cv2.resize(tile, (width_t, height_t), interpolation=cv2.INTER_AREA) newtile[0:height_t, 0:width_t] = effect # center crop rr = (0 + height_t - height + 1) // 2 rc = (0 + width_t - width + 1) // 2 result = newtile[rr : rr + height, rc : rc + width] elif tone_param.tone_type == "dark": height, width = mask.shape result = cv2.resize(tile, (width, height), interpolation=cv2.INTER_AREA) elif tone_param.tone_type == "light": scale_inv = tone_param.param["scale_inv"] angle = tone_param.param["angle"] height, width = mask.shape assert scale_inv == 1.0 and (not angle) rowtiles = height // tile.shape[0] + 1 coltiles = width // tile.shape[1] + 1 tile_dest = np.tile(tile, (rowtiles, coltiles)) result = tile_dest[:height, :width] else: raise NotImplementedError # edit value_scale = tone_param.param["value_scale"] tile = result * value_scale tile[tile > 255] = 255 # apply mask tile = mask * tile / 255.0 + (255 - mask) return tile class ToneDataset: tone_types = ("gradation", "effect", "light", "dark") def __init__(self, root: str, grayscale: bool = True) -> None: self.root = Path(root) data_root = { "light": "screenPatterns/light/", "effect": "secretsanta2011/effects/", "gradation": "secretsanta2011/gradations/", } self.data = dict() for tone_type in self.tone_types: if tone_type == "dark": self.data[tone_type] = [np.zeros((10, 10), dtype=np.uint8)] else: if tone_type in {"light", "effect"}: paths = sorted((self.root / data_root[tone_type]).glob("*")) else: paths = sorted((self.root / data_root[tone_type]).glob("*/*/*")) color = cv2.IMREAD_GRAYSCALE if grayscale else cv2.IMREAD_UNCHANGED self.data[tone_type] = [ cv2.imread(path.as_posix(), color) for path in paths ] def __len__(self) -> int: return sum(len(self.data[tone_type]) for tone_type in self.tone_types) def get(self, index: int, tone_type) -> np.ndarray: return self.data[tone_type][index]
{ "alphanum_fraction": 0.5605209047, "author": null, "avg_line_length": 32.7130044843, "converted": null, "ext": "py", "file": null, "hexsha": "e99aca3f19d3a0ffaa9c93ffee19207e481707c2", "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": "3eb51b2e0e11aa7f470f9b6a92bfde5ef1476062", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "kktsubota/manga-character-screentone", "max_forks_repo_path": "utils/screentone.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "3eb51b2e0e11aa7f470f9b6a92bfde5ef1476062", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "kktsubota/manga-character-screentone", "max_issues_repo_path": "utils/screentone.py", "max_line_length": 100, "max_stars_count": 2, "max_stars_repo_head_hexsha": "3eb51b2e0e11aa7f470f9b6a92bfde5ef1476062", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "kktsubota/manga-character-screentone", "max_stars_repo_path": "utils/screentone.py", "max_stars_repo_stars_event_max_datetime": "2021-11-20T03:03:20.000Z", "max_stars_repo_stars_event_min_datetime": "2021-11-17T13:56:36.000Z", "num_tokens": 1783, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 7295 }
import os import itertools import pytest import numpy as np from rbc.errors import UnsupportedError, HeavyDBServerError from rbc.tests import heavydb_fixture, assert_equal from rbc.typesystem import Type rbc_heavydb = pytest.importorskip('rbc.heavydb') available_version, reason = rbc_heavydb.is_available() # Throw an error on Travis CI if the server is not available if "TRAVIS" in os.environ and not available_version: pytest.exit(msg=reason, returncode=1) pytestmark = pytest.mark.skipif(not available_version, reason=reason) @pytest.mark.parametrize("heavydb_brand", ['omnisci', 'heavyai']) def test_get_client_config(tmpdir, heavydb_brand): d = tmpdir.mkdir(heavydb_brand) fh = d.join("client.conf") fh.write(f""" [user] name = foo password = secret [server] port: 1234 host: example.com dbname: {heavydb_brand} [rbc] debug: False use_host_target: False # server: Server [NOT IMPL] # target_info: TargetInfo """) conf_file = os.path.join(fh.dirname, fh.basename) client_conf_env = dict(heavyai='HEAVYDB_CLIENT_CONF', omnisci='OMNISCI_CLIENT_CONF')[heavydb_brand] old_conf = os.environ.get(client_conf_env) os.environ[client_conf_env] = conf_file try: conf = rbc_heavydb.get_client_config() assert conf['user'] == 'foo' assert conf['password'] == 'secret' assert conf['port'] == 1234 assert conf['host'] == 'example.com' assert conf['dbname'] == heavydb_brand assert conf['debug'] == bool(0) conf = rbc_heavydb.get_client_config(dbname='test') assert conf['dbname'] == 'test' finally: if old_conf is None: del os.environ[client_conf_env] else: os.environ[client_conf_env] = old_conf @pytest.fixture(scope='module') def nb_version(): from rbc.utils import get_version return get_version('numba') @pytest.fixture(scope='module') def heavydb(): for o in heavydb_fixture(globals()): yield o def test_direct_call(heavydb): heavydb.reset() @heavydb('double(double)') def farhenheit2celcius(f): return (f - 32) * 5 / 9 assert_equal(farhenheit2celcius(40).execute(), np.float32(40 / 9)) def test_local_caller(heavydb): heavydb.reset() def func(f): return f caller = heavydb('double(double)')(func) msg = "Cannot create a local `Caller`" with pytest.raises(UnsupportedError, match=msg): _ = caller.local def test_redefine(heavydb): heavydb.reset() @heavydb('i32(i32)') def incr(x): return x + 1 desrc, result = heavydb.sql_execute( f'select i4, incr(i4) from {heavydb.table_name}') for x, x1 in result: assert x1 == x + 1 # Re-defining triggers a warning message when in debug mode @heavydb('i32(i32)') # noqa: F811 def incr(x): # noqa: F811 return x + 2 desrc, result = heavydb.sql_execute( f'select i4, incr(i4) from {heavydb.table_name}') for x, x1 in result: assert x1 == x + 2 def test_single_argument_overloading(heavydb): heavydb.reset() @heavydb( 'f64(f64)', 'i64(i64)', 'i32(i32)', 'f32(f32)', # 'i32(f32)', ) def mydecr(x): return x - 1 desrc, result = heavydb.sql_execute( 'select f4, mydecr(f4) from {heavydb.table_name}'.format(**locals())) result = list(result) assert len(result) > 0 for x, x1 in result: assert x1 == x - 1 assert isinstance(x1, type(x)) desrc, result = heavydb.sql_execute( 'select f8, mydecr(f8) from {heavydb.table_name}'.format(**locals())) result = list(result) assert len(result) > 0 for x, x1 in result: assert x1 == x - 1 assert isinstance(x1, type(x)) desrc, result = heavydb.sql_execute( 'select i4, mydecr(i4) from {heavydb.table_name}'.format(**locals())) result = list(result) assert len(result) > 0 for x, x1 in result: assert x1 == x - 1 assert isinstance(x1, type(x)) def test_thrift_api_doc(heavydb): heavydb.reset() @heavydb('double(int, double)', 'float(int, float)', 'int(int, int)') def foo(i, v): return v * i + 55 descr, result = heavydb.sql_execute( 'select f8, foo(i4, f8) from {heavydb.table_name}'.format(**locals())) result = list(result) assert len(result) > 0 for i, (x, x1) in enumerate(result): assert x1 == x * i + 55 assert isinstance(x1, type(x)) def test_multiple_implementation(heavydb): heavydb.reset() @heavydb('int(f64)', 'int(i64)') # noqa: F811 def bits(x): return 64 @heavydb('int(f32)', 'int(i32)') # noqa: F811 def bits(x): # noqa: F811 return 32 @heavydb('int(i16)') # noqa: F811 def bits(x): # noqa: F811 return 16 @heavydb('int(i8)') # noqa: F811 def bits(x): # noqa: F811 return 8 descr, result = heavydb.sql_execute( 'select bits(i1), bits(i2), bits(i4), bits(f4), bits(i8), bits(f8)' ' from {heavydb.table_name} limit 1'.format(**locals())) result = list(result) assert len(result) == 1 assert result[0] == (8, 16, 32, 32, 64, 64) def test_loadtime_udf(heavydb): # This test requires that heavydb server is started with `--udf # sample_udf.cpp` option where the .cpp file defines `udf_diff` try: desrc, result = heavydb.sql_execute( 'select i4, udf_diff2(i4, i4) from {heavydb.table_name}' .format(**locals())) except Exception as msg: assert "Undefined function call 'udf_diff2'" in str(msg) return result = list(result) for i_, (i, d) in enumerate(result): assert i_ == i assert d == 0 def test_f32(heavydb): """If UDF name ends with an underscore, expect strange behaviour. For instance, defining @heavydb('f32(f32)', 'f32(f64)') def f32_(x): return x+4.5 the query `select f32_(0.0E0))` fails but not when defining @heavydb('f32(f64)', 'f32(f32)') def f32_(x): return x+4.5 (notice the order of signatures in heavydb decorator argument). """ @heavydb('f32(f32)', 'f32(f64)') # noqa: F811 def f_32(x): return x+4.5 descr, result = heavydb.sql_execute( 'select f_32(0.0E0) from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (4.5,) def test_castop(heavydb): @heavydb('i16(i16)') # noqa: F811 def i32(x): return x+2 # noqa: F811 @heavydb('i32(i32)') # noqa: F811 def i32(x): return x+4 # noqa: F811 descr, result = heavydb.sql_execute( 'select i32(cast(1 as int))' ' from {heavydb.table_name} limit 1'.format(**locals())) assert list(result)[0] == (5,) def test_binding(heavydb): heavydb.reset() full = os.environ.get('RBC_TESTS_FULL', 'FALSE').lower() in ['1', 'true', 'on'] if full: argument_types = ['i8', 'i16', 'i32', 'i64', 'f32', 'f64'] literals = ['0', '0.0', 'cast(0 as tinyint)', 'cast(0 as smallint)', 'cast(0 as int)', 'cast(0 as bigint)', 'cast(0 as float)', 'cast(0 as double)'] literals_types = ['i32', 'f32'] + argument_types column_vars = ['cast(i8 as tinyint)', 'cast(i8 as smallint)', 'cast(i8 as int)', 'cast(i8 as bigint)', 'cast(i8 as float)', 'cast(i8 as double)'] column_vars_types = argument_types else: # skip smallint and int argument_types = ['i8', 'i64', 'f32', 'f64'] literals = ['0', '0.0', 'cast(0 as tinyint)', 'cast(0 as bigint)', 'cast(0 as float)', 'cast(0 as double)'] literals_types = ['i32', 'f32'] + argument_types column_vars = ['cast(i8 as tinyint)', 'cast(i8 as bigint)', 'cast(i8 as float)', 'cast(i8 as double)'] column_vars_types = argument_types if available_version[:2] >= (5, 9): heavydb.require_version((5, 9), 'Requires heavydb-internal PR 6003') def get_result(overload_types, input_type, is_literal): overload_types_ = overload_types[::-1 if is_literal else 1] for overload_type in overload_types_: if input_type[0] == overload_type[0]: if int(input_type[1:]) <= int(overload_type[1:]): return overload_type if input_type[0] == 'i': for overload_type in reversed(overload_types): if overload_type[0] == 'f': return overload_type return 'NO BINDING FOUND' elif available_version[:2] == (5, 8): def get_result(overload_types, input_type, is_literal): overload_types_ = overload_types[::-1 if is_literal else 1] for overload_type in overload_types_: if input_type[0] == overload_type[0]: if int(input_type[1:]) <= int(overload_type[1:]): return overload_type if input_type[0] == 'i': for overload_type in overload_types_: if overload_type[0] == 'f' and int(input_type[1:]) <= int(overload_type[1:]): return overload_type return 'NO BINDING FOUND' else: # typeless literal expressions not support as arguments literals = literals[2:] literals_types = literals_types[2:] def get_result(overload_types, input_type, is_literal): for overload_type in overload_types: if input_type[0] == overload_type[0]: if int(input_type[1:]) <= int(overload_type[1:]): return overload_type elif overload_type == 'f64': return overload_type return 'NO BINDING FOUND' assert len(literals) == len(literals_types) assert len(column_vars) == len(column_vars_types) heavydb.reset() functions = [] for r in range(1, len(argument_types) + 1): if not full and r not in [1, 2, len(argument_types)]: continue for p in itertools.combinations(range(len(argument_types)), r=r): fname = 'rt_binding_' + '_'.join(map(argument_types.__getitem__, p)) for i in p: foo = eval(f'lambda x: {i}') foo.__name__ = fname heavydb(f'i8({argument_types[i]})')(foo) functions.append(fname) heavydb.register() for fname in functions: for input, input_type in zip(literals, literals_types): try: descr, result = heavydb.sql_execute(f'select {fname}({input})') result = list(result) result = argument_types[result[0][0]] except Exception: result = 'NO BINDING FOUND' expected = get_result(fname[len('rt_binding_'):].split('_'), input_type, True) assert result == expected, (fname, input, input_type, result, expected) for input, input_type in zip(column_vars, column_vars_types): try: descr, result = heavydb.sql_execute( f'select {fname}({input}) from {heavydb.table_name} limit 1') result = list(result) result = argument_types[result[0][0]] except Exception: result = 'NO BINDING FOUND' expected = get_result(fname[len('rt_binding_'):].split('_'), input_type, False) assert result == expected, (fname, input, input_type, result, expected) def test_casting(heavydb): """Define UDFs: i8(<tinyint>), i16(<smallint>), i32(<int>), i64(<bigint>) f32(<float>), f64(<double>) The following table defines the behavior of applying these UDFs to values with different types: OmnisciDB version 5.9+ ---------------------- | Functions applied to <itype value> itype | i8 | i16 | i32 | i64 | f32 | f64 | ---------+------+------+------+------+------+------+ tinyint | OK | OK | OK | OK | OK | OK | smallint | FAIL | OK | OK | OK | OK | OK | int | FAIL | FAIL | OK | OK | OK | OK | bigint | FAIL | FAIL | FAIL | OK | OK | OK | float | FAIL | FAIL | FAIL | FAIL | OK | OK | double | FAIL | FAIL | FAIL | FAIL | FAIL | OK | OmnisciDB version 5.8 ---------------------- | Functions applied to <itype value> itype | i8 | i16 | i32 | i64 | f32 | f64 | ---------+------+------+------+------+------+------+ tinyint | OK | OK | OK | OK | OK | OK | smallint | FAIL | OK | OK | OK | OK | OK | int | FAIL | FAIL | OK | OK | OK | OK | bigint | FAIL | FAIL | FAIL | OK | FAIL | OK | float | FAIL | FAIL | FAIL | FAIL | OK | OK | double | FAIL | FAIL | FAIL | FAIL | FAIL | OK | OmnisciDB version 5.7 and older ------------------------------- | Functions applied to <itype value> itype | i8 | i16 | i32 | i64 | f32 | f64 | ---------+------+------+------+------+------+------+ tinyint | OK | OK | OK | OK | FAIL | FAIL | smallint | FAIL | OK | OK | OK | FAIL | FAIL | int | FAIL | FAIL | OK | OK | FAIL | FAIL | bigint | FAIL | FAIL | FAIL | OK | FAIL | FAIL | float | FAIL | FAIL | FAIL | FAIL | OK | OK | double | FAIL | FAIL | FAIL | FAIL | FAIL | OK | test_binding is superior test with respect to successful UDF executions but it does not check exception messages. """ heavydb.reset() @heavydb('i8(i8)') # noqa: F811 def i8(x): return x+1 @heavydb('i16(i16)') # noqa: F811 def i16(x): return x+2 @heavydb('i32(i32)') # noqa: F811 def i32(x): return x+4 @heavydb('i64(i64)') # noqa: F811 def i64(x): return x+8 @heavydb('f32(f32)') # noqa: F811 def f32(x): return x+4.5 # cannot create a 8-bit and 16-bit int literals in sql, so, using # the following helper functions: @heavydb('i8(i8)', 'i8(i16)', 'i8(i32)') # noqa: F811 def i_8(x): return x+1 @heavydb('i16(i16)', 'i16(i32)') # noqa: F811 def i_16(x): return x+2 # cannot create a 32-bit float literal in sql, so, using a helper # function for that: @heavydb('f32(f32)', 'f32(f64)') # noqa: F811 def f_32(x): return x+4.5 @heavydb('f64(f64)') # noqa: F811 def f64(x): return x+8.5 @heavydb('i8(i8)') def ifoo(x): return x + 1 @heavydb('i16(i16)') # noqa: F811 def ifoo(x): return x + 2 # noqa: F811 @heavydb('i32(i32)') # noqa: F811 def ifoo(x): return x + 4 # noqa: F811 @heavydb('i64(i64)') # noqa: F811 def ifoo(x): return x + 8 # noqa: F811 @heavydb('f32(f32)') def ffoo(x): return x + 4.5 # noqa: F811 @heavydb('f64(f64)') # noqa: F811 def ffoo(x): return x + 8.5 # noqa: F811 rows = [] for itype, ivalue in [('tinyint', 'i_8(0)'), ('smallint', 'i_16(0)'), ('int', 'i32(0)'), ('bigint', 'i64(0)'), ('float', 'f_32(0.0)'), ('double', 'f64(0.0)')]: row = [f'{itype:8}'] cols = [f'{"itype":8}'] for atype, func in [('tinyint', 'i8'), ('smallint', 'i16'), ('int', 'i32'), ('bigint', 'i64'), ('float', 'f32'), ('double', 'f64')]: cols.append(f'{func:4}') try: descr, result = heavydb.sql_execute( f'select {func}({ivalue}) from {heavydb.table_name} limit 1') status = 'OK' except Exception: status = 'FAIL' row.append(f'{status:4}') if not rows: rows.append(' | '.join(cols)) rows.append('+'.join([f'{"":-^9}'] + [f'{"":-^6}'] * (len(cols)-1))) rows.append(' | '.join(row)) print('\n\nSUPPORTED CASTING RULES FOR SCALAR ARGUMENTS:\n') print('\n'.join(rows)) descr, result = heavydb.sql_execute( 'select i_8(0),i_16(0),i32(0),i64(0) from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (1, 2, 4, 8) descr, result = heavydb.sql_execute( 'select i_8(i1),i16(i2),i32(i4),i64(i8)' ' from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (1, 2, 4, 8) descr, result = heavydb.sql_execute( 'select ifoo(i_8(0)),ifoo(i_16(0)),ifoo(i32(0)),ifoo(i64(0))' ' from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (1+1, 2+2, 4+4, 8+8) descr, result = heavydb.sql_execute( 'select ifoo(i1),ifoo(i2),ifoo(i4),ifoo(i8)' ' from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (1, 2, 4, 8) descr, result = heavydb.sql_execute( 'select i64(i_8(0)), i64(i_16(0)),i64(i32(0)),i64(i64(0))' ' from {heavydb.table_name} limit 1'.format(**locals())) assert list(result)[0] == (9, 10, 12, 16) descr, result = heavydb.sql_execute( 'select i64(i1), i64(i2),i64(i4),i64(i8)' ' from {heavydb.table_name} limit 1'.format(**locals())) assert list(result)[0] == (8, 8, 8, 8) descr, result = heavydb.sql_execute( 'select i32(i_8(0)), i32(i_16(0)),i32(i32(0))' ' from {heavydb.table_name} limit 1'.format(**locals())) assert list(result)[0] == (5, 6, 8) descr, result = heavydb.sql_execute( 'select i32(i1), i32(i2),i32(i4)' ' from {heavydb.table_name} limit 1'.format(**locals())) assert list(result)[0] == (4, 4, 4) descr, result = heavydb.sql_execute( 'select i16(i_8(0)), i16(i_16(0)) from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (3, 4) descr, result = heavydb.sql_execute( 'select i16(i1), i16(i2) from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (2, 2) descr, result = heavydb.sql_execute( 'select i8(i_8(0)) from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (2,) descr, result = heavydb.sql_execute( 'select i8(i1) from {heavydb.table_name} limit 1'.format(**locals())) assert list(result)[0] == (1,) descr, result = heavydb.sql_execute( 'select f_32(0.0E0), f64(0.0E0) from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (4.5, 8.5) descr, result = heavydb.sql_execute( 'select f_32(f4), f64(f8) from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (4.5, 8.5) descr, result = heavydb.sql_execute( 'select f64(f_32(0.0E0)), f64(f64(0.0E0))' ' from {heavydb.table_name} limit 1'.format(**locals())) assert list(result)[0] == (13.0, 17.0) descr, result = heavydb.sql_execute( 'select f64(f4), f64(f8)' ' from {heavydb.table_name} limit 1'.format(**locals())) assert list(result)[0] == (8.5, 8.5) descr, result = heavydb.sql_execute( 'select f32(f_32(0.0E0)) from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (9.0,) descr, result = heavydb.sql_execute( 'select f32(f4) from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (4.5,) descr, result = heavydb.sql_execute( 'select ffoo(f_32(0.0E0)), ffoo(f64(0.0E0))' ' from {heavydb.table_name} limit 1'.format(**locals())) assert list(result)[0] == (9.0, 17.0) descr, result = heavydb.sql_execute( 'select ffoo(f4), ffoo(f8)' ' from {heavydb.table_name} limit 1'.format(**locals())) assert list(result)[0] == (4.5, 8.5) for v, f, t in [ ('i64(0)', r'i32', r'BIGINT'), ('i64(0)', r'i16', r'BIGINT'), ('i64(0)', r'i8', r'BIGINT'), ('i8', r'i32', r'BIGINT'), ('i8', r'i16', r'BIGINT'), ('i8', r'i8', r'BIGINT'), ('i32(0)', r'i16', r'INTEGER'), ('i32(0)', r'i8', r'INTEGER'), ('i4', r'i16', r'INTEGER'), ('i4', r'i8', r'INTEGER'), ('i_16(0)', r'i8', r'SMALLINT'), ('i2', r'i8', r'SMALLINT'), ('f64(0)', r'f32', r'DOUBLE'), ('f8', r'f32', r'DOUBLE'), ]: q = f'select {f}({v}) from {heavydb.table_name} limit 1' match = (r".*(Function "+f+r"\("+t+r"\) not supported" r"|Could not bind "+f+r"\("+t+r"\))") with pytest.raises(Exception, match=match): descr, result = heavydb.sql_execute(q) print('query: ', q) print('expected: ', match) for f in [r'f64', r'f32']: for at, av, r in [ (r'BIGINT', 'i64(0)', (16.5,)), (r'INTEGER', 'i32(0)', (12.5,)), (r'SMALLINT', 'i_16(0)', (10.5,)), (r'TINYINT', 'i_8(0)', (9.5,)), (r'BIGINT', 'i8', (8.5,)), (r'INTEGER', 'i4', (8.5,)), (r'SMALLINT', 'i2', (8.5,)), (r'TINYINT', 'i1', (8.5,)), ]: if available_version[:2] >= (5, 9): # heavydb-internal PR 6003 changed the casting table if f == r'f32': r = r[0] - 4, descr, result = heavydb.sql_execute( f'select {f}({av}) from {heavydb.table_name} limit 1') assert list(result)[0] == r, (f, at, av, r) elif available_version[:2] == (5, 8): # heavydb-internal PR 5814 changed the casting table if f == r'f32' and at == r'BIGINT': with pytest.raises( Exception, match=(r".*(Function "+f+r"\("+at+r"\) not supported" r"|Could not bind "+f+r"\("+at+r"\))")): descr, result = heavydb.sql_execute( f'select {f}({av}) from {heavydb.table_name} limit 1') else: if f == r'f32': r = r[0] - 4, descr, result = heavydb.sql_execute( f'select {f}({av}) from {heavydb.table_name} limit 1') assert list(result)[0] == r, (f, at, av, r) elif f == r'f64': # temporary: allow integers as double arguments descr, result = heavydb.sql_execute( f'select {f}({av}) from {heavydb.table_name} limit 1') assert list(result)[0] == r else: with pytest.raises( Exception, match=(r".*(Function "+f+r"\("+at+r"\) not supported" r"|Could not bind "+f+r"\("+at+r"\))")): descr, result = heavydb.sql_execute( 'select '+f+'('+av+f') from {heavydb.table_name} limit 1') for f in [r'i64', r'i32', r'i16', r'i8']: for at, av in [ (r'DOUBLE', 'f64(0E0)'), (r'FLOAT', 'f_32(0E0)'), (r'DOUBLE', 'f8'), (r'FLOAT', 'f4'), ]: with pytest.raises( Exception, match=(r".*(Function "+f+r"\("+at+r"\) not supported" r"|Could not bind "+f+r"\("+at+r"\))")): descr, result = heavydb.sql_execute( f'select {f}({av}) from {heavydb.table_name} limit 1') def test_truncate_issue(heavydb): heavydb.reset() @heavydb('int(f64)', 'int(i64)') # noqa: F811 def bits(x): # noqa: F811 return 64 @heavydb('int(f32)', 'int(i32)') # noqa: F811 def bits(x): # noqa: F811 return 32 @heavydb('int(i16)') # noqa: F811 def bits(x): # noqa: F811 return 16 @heavydb('int(i8)') # noqa: F811 def bits(x): # noqa: F811 return 8 descr, result = heavydb.sql_execute( 'select bits(truncate(2016, 1)) from {heavydb.table_name} limit 1' .format(**locals())) if available_version[:2] >= (5, 8): # heavydb-internal PR 5915 changes the casting table assert list(result)[0] in [(64,)] else: assert list(result)[0] in [(16,), (32,)] descr, result = heavydb.sql_execute( 'select bits(truncate(cast(2016.0 as smallint), 1))' ' from {heavydb.table_name} limit 1' .format(**locals())) if available_version[:2] >= (5, 8): assert list(result)[0] == (64,) else: assert list(result)[0] == (16,) descr, result = heavydb.sql_execute( 'select bits(truncate(cast(2016.0 as int), 1))' ' from {heavydb.table_name} limit 1' .format(**locals())) if available_version[:2] >= (5, 8): assert list(result)[0] == (64,) else: assert list(result)[0] == (32,) descr, result = heavydb.sql_execute( 'select bits(truncate(cast(2016.0 as bigint), 1))' ' from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (64,) descr, result = heavydb.sql_execute( 'select bits(truncate(cast(2016.0 as float), 1))' ' from {heavydb.table_name} limit 1' .format(**locals())) if available_version[:2] >= (5, 8): assert list(result)[0] == (64,) else: assert list(result)[0] == (32,) descr, result = heavydb.sql_execute( 'select bits(truncate(cast(2016.0 as double), 1))' ' from {heavydb.table_name} limit 1' .format(**locals())) assert list(result)[0] == (64,) def test_unregistering(heavydb): heavydb.reset() @heavydb('i32(i32)') def fahrenheit2celsius(f): return (f - 32) * 5 / 9 _, result = heavydb.sql_execute('select fahrenheit2celsius(40)') assert list(result)[0] == (4,) heavydb.unregister() msg = "Undefined function call" with pytest.raises(HeavyDBServerError, match=msg): heavydb.sql_execute('select fahrenheit2celsius(40)') def test_format_type(heavydb): def test(s, caller=False): with heavydb.targets['cpu']: with Type.alias(**heavydb.typesystem_aliases): typ = Type.fromobject(s) if caller: typ = heavydb.caller_signature(typ) return heavydb.format_type(typ) assert test('int32 x') == 'int32 x' assert test('Column<int32 x | name=y>') == 'Column<int32 x | name=y>' assert test('Column<int32 | name=y>') == 'Column<int32 y>' assert test('Column<int32 x>') == 'Column<int32 x>' assert test('Column<int32>') == 'Column<int32>' assert test('Column<int32> z') == 'Column<int32> z' assert test('Column<int32> | name=z') == 'Column<int32> z' assert test('Column<int32> x | name=z') == 'Column<int32> x | name=z' assert test('Column<TextEncodingNone>') == 'Column<TextEncodingNone>' assert test('Column<Array<int32>>') == 'Column<Array<int32>>' assert test('Column<Array<TextEncodingNone>>') == 'Column<Array<TextEncodingNone>>' assert test('OutputColumn<int32>') == 'OutputColumn<int32>' assert test('ColumnList<int32>') == 'ColumnList<int32>' assert test('UDTF(ColumnList<int32>)') == 'UDTF(ColumnList<int32>)' assert test('int32(ColumnList<int32>)') == 'UDTF(ColumnList<int32>)' assert (test('UDTF(int32 x, Column<float32> y, OutputColumn<int64> z)') == 'UDTF(int32 x, Column<float32> y, OutputColumn<int64> z)') assert test('UDTF(RowMultiplier)') == 'UDTF(RowMultiplier)' assert test('UDTF(RowMultiplier m)') == 'UDTF(RowMultiplier m)' assert test('UDTF(RowMultiplier | name=m)') == 'UDTF(RowMultiplier m)' assert test('UDTF(Constant m)') == 'UDTF(Constant m)' assert test('UDTF(ConstantParameter m)') == 'UDTF(ConstantParameter m)' assert test('UDTF(SpecifiedParameter m)') == 'UDTF(SpecifiedParameter m)' assert test('UDTF(PreFlight m)') == 'UDTF(PreFlight m)' assert test('UDTF(TableFunctionManager mgr)') == 'UDTF(TableFunctionManager mgr)' assert test('UDTF(Cursor<int32, float64>)') == 'UDTF(Cursor<Column<int32>, Column<float64>>)' assert test('UDTF(Cursor<int32 x>)') == 'UDTF(Cursor<Column<int32> x>)' assert test('UDTF(Cursor<int32 | name=x>)') == 'UDTF(Cursor<Column<int32> x>)' assert test('UDTF(Cursor<TextEncodingNone x>)') == 'UDTF(Cursor<Column<TextEncodingNone> x>)' assert test('int32(int32)') == '(int32) -> int32' assert test('int32(int32 x)') == '(int32 x) -> int32' assert test('int32(Array<int32>)') == '(Array<int32>) -> int32' assert test('int32(int32[])') == '(Array<int32>) -> int32' assert test('int32(Array<int32> x)') == '(Array<int32> x) -> int32' assert test('int32(TextEncodingNone)') == '(TextEncodingNone) -> int32' assert test('int32(TextEncodingNone x)') == '(TextEncodingNone x) -> int32' assert test('int32(TextEncodingDict)') == '(TextEncodingDict) -> int32' assert test('int32(TextEncodingDict x)') == '(TextEncodingDict x) -> int32' assert test('int32(Array<TextEncodingNone> x)') == '(Array<TextEncodingNone> x) -> int32' def test2(s): return test(s, caller=True) assert test2('UDTF(int32, OutputColumn<int32>)') == '(int32) -> (Column<int32>)' assert test2('UDTF(OutputColumn<int32>)') == '(void) -> (Column<int32>)' assert (test2('UDTF(int32 | sizer, OutputColumn<int32>)') == '(RowMultiplier) -> (Column<int32>)') assert (test2('UDTF(ConstantParameter, OutputColumn<int32>)') == '(ConstantParameter) -> (Column<int32>)') assert test2('UDTF(SpecifiedParameter, OutputColumn<int32>)') == '(void) -> (Column<int32>)' assert test2('UDTF(Constant, OutputColumn<int32>)') == '(void) -> (Column<int32>)' assert test2('UDTF(PreFlight, OutputColumn<int32>)') == '(void) -> (Column<int32>)' assert test2('UDTF(TableFunctionManager, OutputColumn<int32>)') == '(void) -> (Column<int32>)' assert (test2('UDTF(RowMultiplier, OutputColumn<Array<TextEncodingNone>>)') == '(RowMultiplier) -> (Column<Array<TextEncodingNone>>)') assert test2('UDTF(Cursor<int32>)') == '(Cursor<Column<int32>>) -> void' assert test2('UDTF(Cursor<int32 x>)') == '(Cursor<Column<int32> x>) -> void' def test_reconnect(heavydb): heavydb2 = heavydb.reconnect() assert heavydb.session_id != heavydb2.session_id assert heavydb2.host == heavydb.host assert heavydb2.port == heavydb.port def test_non_admin_user(heavydb): heavydb.require_version((5, 9), 'Requires omniscidb 5.9 or newer') user = 'rbc_test_non_admin_user' password = 'Xy2kq_3lM' dbname = 'rbc_test_non_admin_user_db' # create user and user's database: heavydb.sql_execute(f'DROP DATABASE IF EXISTS {dbname};') heavydb.sql_execute(f'DROP USER IF EXISTS "{user}";') heavydb.sql_execute( f"CREATE USER {user} (password = '{password}', is_super = 'false', can_login='true');") heavydb.sql_execute(f"CREATE DATABASE {dbname} (owner = '{user}');") heavydb.sql_execute(f"ALTER USER {user} (default_db = '{dbname}');") # test the ability to register and use UDFs as a non-admin user: userdb = heavydb.reconnect(user=user, password=password, dbname=dbname) assert userdb.user == user assert userdb.password == password assert userdb.dbname == dbname @userdb('int(int)') def rbc_test_non_admin_user_udf(x): return x + 1 assert rbc_test_non_admin_user_udf(1).execute() == 2 # clean up: heavydb.sql_execute(f'DROP DATABASE IF EXISTS {dbname};') heavydb.sql_execute(f'DROP USER IF EXISTS "{user}";')
{ "alphanum_fraction": 0.5541629086, "author": null, "avg_line_length": 36.8304696449, "converted": null, "ext": "py", "file": null, "hexsha": "a707f335af0b8a14ad84261224620361b31fc9ec", "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": "630805b6a32a1e53883dd8502e9a0679c9923b0b", "max_forks_repo_licenses": [ "BSD-3-Clause" ], "max_forks_repo_name": "tupui/rbc", "max_forks_repo_path": "rbc/tests/heavydb/test_heavydb.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "630805b6a32a1e53883dd8502e9a0679c9923b0b", "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": "tupui/rbc", "max_issues_repo_path": "rbc/tests/heavydb/test_heavydb.py", "max_line_length": 98, "max_stars_count": 1, "max_stars_repo_head_hexsha": "630805b6a32a1e53883dd8502e9a0679c9923b0b", "max_stars_repo_licenses": [ "BSD-3-Clause" ], "max_stars_repo_name": "tupui/rbc", "max_stars_repo_path": "rbc/tests/heavydb/test_heavydb.py", "max_stars_repo_stars_event_max_datetime": "2019-02-15T14:14:58.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-15T14:14:58.000Z", "num_tokens": 9371, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 32153 }
[STATEMENT] lemma fold_is_None: "x=None \<longleftrightarrow> is_None x" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (x = None) = is_None x [PROOF STEP] by (cases x) auto
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "Automatic_Refinement_Autoref_Bindings_HOL", "hexsha": null, "include": null, "lang": null, "length": 1, "llama_tokens": 76, "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 }
@safetestset "REM" begin using GlobalMatchingModels, Statistics, Test, Random using Distributions probe = [6,1,1,3]; memory = [0 2; 1 2; 0 1; 3 0]; model = REM(;memory, g=.40, c=.70) activations = compute_activations(model, probe) @test activations ≈ [10.5802,.18450] atol = 1e-4 prob = compute_prob(activations) @test prob ≈ .8433 atol = 1e-4 Random.seed!(58) model = REM(;memory=fill(0, 4, 4), g=.40, c=.70) stimuli = generate_stimuli(.3, 4, 4) encode!(model, stimuli) dims = size(model.memory) @test dims == (4,4) @test sum(model.memory .!= stimuli) > 0 Random.seed!(25) g = .30 c = .70 u = .80 n = 5000 stimuli = generate_stimuli(g, n, n) model = REM(;memory=fill(0, n, n), g, c, u) encode!(model, stimuli) est = mean(model.memory .== 0) @test est ≈ (1 - u) + u * g * c + u * (1 - c) * g atol = 1e-4 end
{ "alphanum_fraction": 0.5681570338, "author": null, "avg_line_length": 28.65625, "converted": null, "ext": "jl", "file": null, "hexsha": "31d3b1b3d2020452728334cb311e5475cb0aa8cf", "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": "b5785cccc58ecf3a98cdeeb95f02882028f08b3e", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "itsdfish/GlobalMatchingModels.jl", "max_forks_repo_path": "test/REM_tests.jl", "max_issues_count": 4, "max_issues_repo_head_hexsha": "b5785cccc58ecf3a98cdeeb95f02882028f08b3e", "max_issues_repo_issues_event_max_datetime": "2021-08-08T11:30:20.000Z", "max_issues_repo_issues_event_min_datetime": "2021-06-19T10:48:46.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "itsdfish/GlobalMatchingModels.jl", "max_issues_repo_path": "test/REM_tests.jl", "max_line_length": 66, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b5785cccc58ecf3a98cdeeb95f02882028f08b3e", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "itsdfish/GlobalMatchingModels.jl", "max_stars_repo_path": "test/REM_tests.jl", "max_stars_repo_stars_event_max_datetime": "2021-04-25T12:48:13.000Z", "max_stars_repo_stars_event_min_datetime": "2021-04-25T12:48:13.000Z", "num_tokens": 341, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 917 }
# -*- coding: utf-8 -*- """ Created on Mon Sep 19 13:31:01 2011 @author: - """ import DejaVu2 as DejaVu from DejaVu2.Spheres import GLUSpheres try : from DejaVu2 import hyperballs hyperballsFound = True except : hyperballsFound = False if hyperballsFound: from DejaVu2.hyperballs.AtomAndBondGLSL import AtomAndBondGLSL from DejaVu2.hyperballs.ballimproved_frag import ballimproved_frag from DejaVu2.hyperballs.ballimproved_vert import ballimproved_vert from DejaVu2.hyperballs.stickimproved_frag import stickimproved_frag from DejaVu2.hyperballs.stickimproved_vert import stickimproved_vert # from opengltk.OpenGL.GL import * # from opengltk.OpenGL.GLU import * # from OpenGL.GLUT import glutSwapBuffers # from OpenGL import GL # from OpenGL.GL import * import numpy TOO_BIG = 0 TOO_SMALL = 1 SIZE_OK = 2 class hyperBalls(GLUSpheres): keywords = list(GLUSpheres.keywords) for kw in ['quality', 'stacks', 'slices']: keywords.remove(kw) def makeTemplate(self): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() pass def __init__(self, name=None, check=1, **kw): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() self.r = 1 # default scaling factor for system self.pos = numpy.zeros(3) # center of bounding box # self.orien = quaternion([0,0,-1,0]) # orientation in space self.scaleFactor = 1 self.idx = None self.DirV = [] self.clipplane = numpy.array([0.,0.,0.,0,], numpy.float32) self.excl = numpy.array([], numpy.int32) self.sticks = True self.shaders = AtomAndBondGLSL() #print "ok shaders ", self.shaders self.shaders.setAtomFragmentShaderProgramSource(ballimproved_frag); self.shaders.setAtomVertexShaderProgramSource(ballimproved_vert); self.shaders.setBondFragmentShaderProgramSource(stickimproved_frag); self.shaders.setBondVertexShaderProgramSource(stickimproved_vert); self.immediateRendering = False self.width = kw.get( 'w') self.bufferAssigned = False self.atompos = None self.numbonds = 0 self.numatoms = 0 self.bonds = [] self.shrink = 0.01 self.bScale = 0.1 self.aScale = 1.0 self.draw_axes = False self.pmvProj = False self.pmvTransf = False self.lightDir = (0.,0.8,0.6) apply( GLUSpheres.__init__, (self, name, check), kw) self.dpyList=None # shrink, aScale, bScale self.options={"CPK":[0.01,0.2,0.3], "VDW":[0.01,3,0.01], "LIC":[0.01,0.26,0.26], "HBL":[0.3,0.4,0.4]} def setOption(self,name): self.shrink, self.aScale, self.bScale = self.options[name] self.initialise() #update ? def setAtoms(self,mol): self.pmvmol = mol self.atoms = mol.allAtoms for at in mol.allAtoms: at.colors["qutemol"] = tuple( [1.0,.0,.0] ) # def initialise(self,): # #se should trigger the wheel event zomm to change he overall cssscle # #recompute r # self.shaders.initGL() def initialise(self): #if not already initialized do it, otherwise update self.shaders.bshrinks = self.shrink self.shaders.aScales = self.aScale#/10.0 self.shaders.bScales = self.bScale#/10.0 if not self.bufferAssigned : self.shaders.setupBuffersAndTextures(self.numatoms,self.numbonds, self.atompos,self.bonds, self.colors,self.radii); self.shaders.initGL() self.bufferAssigned = True else : self.shaders.updateBuffersAndTextures(self.numatoms,self.numbonds, self.atompos,self.bonds, self.colors,self.radii); def Set(self, check=1, redo=0, updateOwnGui=False, **kw): """set data for this object check=1 : verify that all the keywords present can be handle by this func redo=1 : append self to viewer.objectsNeedingRedo updateOwnGui=True : allow to update owngui at the end this func """ if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() v = kw.get( 'centers') if v is None : v = kw.get('vertices') mat = kw.has_key('materials') rad = kw.get( 'radii') colors = kw.get( 'colors') bonds = kw.get( "bonds" ) shrink = kw.get('shrink') bScale = kw.get('bScale') aScale = kw.get('aScale') redoFlags = 0 if v: # self.redoDspLst=1 self.atompos = coords = numpy.array(v, numpy.float32) self.numatoms = len(coords) self.radii = numpy.ones(self.numatoms) self.shaders.nbAtoms = self.numatoms; self.shaders.positions = self.atompos #update vbo ? if bonds : self.bonds = numpy.array(kw["bonds"], int)#.tolist() self.numbonds = len(self.bonds) self.shaders.nbBonds = self.numbonds; self.shaders.links=numpy.array(self.bonds,numpy.uint32) if v or bonds : self.shaders.updateTextureSize() self.shaders.initVertTCoordIndice();#in case nbatoms changed ? if not self.bufferAssigned : self.shaders.initGL() self.bufferAssigned = True self.shaders.updateVBO() if v : self.shaders.updatePositions(self.atompos) if rad: self.radii = self.vdw_radii = numpy.array(rad, numpy.float32) if v or rad : self.shaders.updateSizes(self.radii) if shrink: self.shrink = shrink #update shrink self.shaders.updateShrinks(shrink) if bScale: self.bScale = bScale self.shaders.updateBondScales(bScale) #update bScale if aScale: self.aScale = aScale self.shaders.updateAtomScales(aScale) if colors:# colors : self.colors = numpy.array(colors, numpy.float32) elif mat : if len(kw["materials"]) == 1 : #uniq color self.colors = numpy.array(kw["materials"]*self.numatoms,numpy.float32) else : self.colors = numpy.array(kw["materials"], numpy.float32) if colors or mat : self.shaders.updateColors(self.colors) # if self.atompos is not None or 'colors' in kw: # self.initialise() redoFlags = apply( GLUSpheres.Set, (self, 0, 0), kw) redoFlags = 0 #print "okSET" # self.SetSpaceFill() return self.redoNow(redo, updateOwnGui, redoFlags) def updateColors(self,): self.colors = numpy.array(self.pmvmol.allAtoms.colors['hpballs'], numpy.float32) def doClip(self): if self.viewer is not None : if self.viewer.currentClip.visible : #recompute the plane ? self.clipplane = self.viewer.currentClip.eqn else : self.clipplane = numpy.array([0.,0.,0.,0,], numpy.float32) clip = self.viewer.currentClip.clipPlaneNames[self.viewer.currentClip.num] else : clip = GL_CLIP_PLANE0 return clip def makeTemplate(self): pass def DisplayFunction(self): # print "ok HP DisplayFunction" self.Draw() def vertexArrayCallback(self): # print "ok HP vertexArrayCallback" self.Draw() def Draw(self): if __debug__: if hasattr(DejaVu, 'functionName'): DejaVu.functionName() """Draw function of the geom return status 0 or 1 If you want fast rendering, you need to set self.templateDSPL using MakeTemplate. """ #print "ok HP Draw" self.shaders.useAllTextures() status = 1 self.shaders.drawAtoms_vbo() if self.sticks : self.shaders.drawBonds_vbo(); return status if __name__=="__main__": import numpy from DejaVu2.hpBalls import hyperBalls hsp = hyperBalls("hpBalls") print "ok",hsp v=numpy.random.random((100,3))*20.0 r=numpy.random.random(100)*5.0 c=numpy.random.random((100,4)) hsp.Set(vertices=v,radii=r.tolist(),materials=c)#no bons hsp.sticks=False vi = self.GUI.VIEWER vi.useMasterDpyList=0 vi.AddObject(hsp)
{ "alphanum_fraction": 0.5414300736, "author": null, "avg_line_length": 38.6585365854, "converted": null, "ext": "py", "file": null, "hexsha": "595c5070fd98cada08f686bd47fbe108612c2059", "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": "6900497629f601c4b6c0c37da26de58ffa221988", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "bio-hpc/metascreener", "max_forks_repo_path": "MetaScreener/external_sw/mgltools/MGLToolsPckgs/DejaVu2/hpBalls.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "6900497629f601c4b6c0c37da26de58ffa221988", "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": "bio-hpc/metascreener", "max_issues_repo_path": "MetaScreener/external_sw/mgltools/MGLToolsPckgs/DejaVu2/hpBalls.py", "max_line_length": 243, "max_stars_count": 8, "max_stars_repo_head_hexsha": "6900497629f601c4b6c0c37da26de58ffa221988", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "bio-hpc/metascreener", "max_stars_repo_path": "MetaScreener/external_sw/mgltools/MGLToolsPckgs/DejaVu2/hpBalls.py", "max_stars_repo_stars_event_max_datetime": "2022-02-14T11:30:03.000Z", "max_stars_repo_stars_event_min_datetime": "2021-12-14T21:30:01.000Z", "num_tokens": 2227, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 9510 }
[STATEMENT] lemma ospec_alt: "ospec m P = (case m of None \<Rightarrow> False | Some x \<Rightarrow> P x)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. ospec m P = (case m of None \<Rightarrow> False | Some x \<Rightarrow> P x) [PROOF STEP] by (auto split: option.splits)
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "ROBDD_Option_Helpers", "hexsha": null, "include": null, "lang": null, "length": 1, "llama_tokens": 101, "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 }
from __future__ import division import sys sys.path.append("GenAnalysis/tools/") import macroeco_distributions as md import macroecotools as mt import feasible_functions as ff import predRADs import mete import pln import cloud import numpy as np def getPredRADs(N, S, Nmax): PRED = [] # Predicted geometric series predRAD = predRADs.get_GeomSeries(N, S, False) # False mean no zeros allowed PRED.append(predRAD) # Predicted log-series logSeries = mete.get_mete_rad(S, N) predRAD = logSeries[0] PRED.append(predRAD) # Predicted PLN predRAD = pln.get_rad_from_obs(RAD, 'pln') PRED.append(predRAD) sample_size = 10 # Predicted from compositions (basically geometric series) predRAD = getPred(N, S, maxn, 'compositions', sample_size) PRED.append(predRAD) # Predicted from Fraction 1: Power Fraction predRAD = getPred(N, S, maxn, 'power fraction', sample_size) PRED.append(predRAD) # Predicted from Fraction 2: Random non-preemption predRAD = getPred(N, S, maxn, 'random fraction non-preemption', sample_size) PRED.append(predRAD) # Predicted from Fraction 3: Random preemption predRAD = getPred(N, S, maxn, 'random fraction', sample_size) PRED.append(predRAD) return PRED NScombos = [[10**10, 10**5], [10**20, 10**5], [10**30, 10**5], [10**40, 10**5], [10**10, 10**7], [10**20, 10**7], [10**30, 10**7], [10**40, 10**7], [10**10, 10**9], [10**20, 10**9], [10**30, 10**9], [10**40, 10**9]] NScombos = [[1000, 50]] models = ['geometric series', 'log series', 'log normal', 'compositions', 'random fraction preemption', 'random fraction'] # uncomment the following if wanting to overwrite exiting output file OUT1 = open('/Users/lisalocey/Desktop/global/NS_SimData.txt', 'w+') print>>OUT1, 'N', 'S', 'geometric series', 'log series', 'log normal', print>>OUT1, 'compositions', 'power fraction', print>>OUT1, 'random fraction preemption', 'random fraction' OUT1.close() for combo in NScombos: N, S = combo Nmax = int(1.00*N) #! GETTING READY TO RUN SOME CODE ! for model in models: print N, S, model # using PiCloud #job_id = cloud.call(getPredRADs, N, S, Nmax, _type='m1') # use picloud #PRED = cloud.result(job_id) # or using the native env PRED = getPredRADs(N, S, Nmax) # Each element of PRED is a list, i.e. PRED[0] is [predicted RAD, r2 of obs vs. pred] GS, LS, PLN, FS, COMPS, PowerFrac, RandFracPre, RandFrac = PRED OUT1 = open('NS_SimData.txt', 'a') for i, ab in enumerate(RAD): # each species in each site at each date # gets its own record of predicted abundances print>>OUT1, N, S, int(GS_rad[i]), LS_rad[i], PLN_rad[i], FS_rad[i] OUT1.close()
{ "alphanum_fraction": 0.5973220118, "author": null, "avg_line_length": 31.8958333333, "converted": null, "ext": "py", "file": null, "hexsha": "8b8f6068c2d5098b6dafdc835f7c47163bbd45cf", "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": "5bac4e039be75f4528ccfd8b7ba85500a5495b96", "max_forks_repo_licenses": [ "Unlicense", "MIT" ], "max_forks_repo_name": "klocey/MicroMETE", "max_forks_repo_path": "global/RADfits.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "5bac4e039be75f4528ccfd8b7ba85500a5495b96", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "Unlicense", "MIT" ], "max_issues_repo_name": "klocey/MicroMETE", "max_issues_repo_path": "global/RADfits.py", "max_line_length": 93, "max_stars_count": null, "max_stars_repo_head_hexsha": "5bac4e039be75f4528ccfd8b7ba85500a5495b96", "max_stars_repo_licenses": [ "Unlicense", "MIT" ], "max_stars_repo_name": "klocey/MicroMETE", "max_stars_repo_path": "global/RADfits.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 896, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 3062 }
""" Copyright (C) 2018-2021 Intel Corporation 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 collections import logging as log from copy import deepcopy from typing import List import networkx as nx import numpy as np from mo.graph.port import Port from mo.middle.passes.eliminate import mark_output_reachable_nodes, shape_inference, mark_undead_nodes, \ mark_const_producer_nodes, eliminate_dead_nodes, add_constant_operations from mo.utils.error import Error from mo.utils.utils import refer_to_faq_msg, deprecated_api, shrink_str_value def dict_to_ordered_dict(d: dict, func=lambda t: t): return collections.OrderedDict(sorted(d.items(), key=lambda t: func(t[0]))) class Node: def __init__(self, graph, node: str): assert node in graph, "Attempt to access node {} that not in graph".format(node) super(Node, self).__setattr__('graph', graph) super(Node, self).__setattr__('node', node) # obsolete super(Node, self).__setattr__('id', node) def __str__(self, max_length: int = 100): node_dict = self.graph.node[self.id] print_dict = {k: v if k != 'value' else shrink_str_value(v, max_symbols=max_length) for k, v in node_dict.items()} return str(print_dict) def __setattr__(self, k, v): # you can assign only existing attributes attrs = self.graph.node[self.node] if not k in attrs: raise AttributeError("Attribute {} missing in {} node".format(k, self.name)) if k == 'version' and attrs.get(k, v) != v: raise AttributeError("Attribute 'version' cannot be updated in {} node".format(self.name)) attrs[k] = v def __getattr__(self, k): return self.graph.node[self.node][k] def __getitem__(self, k): return self.graph.node[self.node][k] def __setitem__(self, k, v): if k == 'version' and self.graph.node[self.node].get(k, v) != v: raise AttributeError("Attribute 'version' cannot be updated in {} node".format(self.name)) self.graph.node[self.node][k] = v def __contains__(self, k): return self.has(k) def __eq__(self, other): return ( self.__class__ == other.__class__ and self.graph == other.graph and self.id == other.id ) def __hash__(self): return hash((self.graph, self.id)) def __delitem__(self, k): del self.graph.node[self.node][k] def add_input_port(self, idx, skip_if_exist=False, **kwargs): if not self.has_valid('_in_ports'): Node(self.graph, self.id)['_in_ports'] = {} control_flow = kwargs['control_flow'] if kwargs.get('control_flow') is not None else False if skip_if_exist is False and idx in self.in_ports(control_flow=control_flow): raise Error("Input port with {} index already exists for {} node.".format(idx, self.name)) self._in_ports.update({idx: kwargs}) def delete_input_ports(self, idx_set, skip_if_absent=False): if len(idx_set) == 0: return # there is nothing to delete for idx in idx_set: self.delete_input_port(idx, skip_if_absent) def delete_input_port(self, idx, skip_if_absent=False): if not self.has_valid('_in_ports'): raise Error( 'Cannot removed ports with indices {} from node {} because node doesn\'t ' 'have _in_ports attribute'.format(idx, self.soft_get('name'))) # no handling of control flow edges -- TODO control_flow = False if not skip_if_absent and idx not in self.in_ports(control_flow=control_flow): raise Error("Input port with index {} doesn't exist in node {}.".format(idx, self.soft_get('name'))) if not self.in_port(idx).disconnected(): self.in_port(idx).disconnect() del self._in_ports[idx] # update in_ports_count for consistency but it is unlikely have any effect somewhere in the code self['in_ports_count'] = len(self._in_ports) def delete_output_port(self, idx, skip_if_absent=False): if not self.has_valid('_out_ports'): raise Error( 'Cannot removed ports with indices {} from node {} because node doesn\'t ' 'have _out_ports attribute'.format(idx, self.soft_get('name'))) # no handling of control flow edges -- TODO control_flow = False if not skip_if_absent and idx not in self.out_ports(control_flow=control_flow): raise Error("Output port with index {} doesn't exist in node {}.".format(idx, self.soft_get('name'))) if not self.out_port(idx).disconnected(): self.out_port(idx).disconnect() del self._out_ports[idx] # update in_ports_count for consistency but it is unlikely have any effect somewhere in the code self['out_ports_count'] = len(self._out_ports) def add_output_port(self, idx, skip_if_exist=False, **kwargs): if not self.has_valid('_out_ports'): Node(self.graph, self.id)['_out_ports'] = {} control_flow = kwargs['control_flow'] if kwargs.get('control_flow') is not None else False if skip_if_exist is False and idx in self.out_ports(control_flow=control_flow): raise Error("Output port with {} index already exists for {} node.".format(idx, self.name)) self._out_ports.update({idx: kwargs}) def add_sequence_of_ports(self, type: str, rng): assert type in ['in', 'out'] for idx in rng: if type == 'in': self.add_input_port(idx, skip_if_exist=True) if type == 'out': self.add_output_port(idx, skip_if_exist=True) def in_port(self, idx=None, control_flow=False) -> Port: if not self.has_valid('_in_ports'): raise Error("Operation {} {} has no _in_ports attribute", self.op, self.name) if idx not in self._in_ports: raise Error("Input port with index {} is not in node {}".format(idx, self.name)) if not control_flow and 'control_flow' in self._in_ports[idx] and self._in_ports[idx]['control_flow']: raise Error("Attempt to access control flow port when it's prohibited for node {}".format(self.name)) return Port(node=self, idx=idx, type='in', **self._in_ports[idx]) def in_ports(self, control_flow=False): if not self.has_valid('_in_ports'): raise Error("Operation {} {} has no _in_ports attribute", self.op, self.name) ports = {} for idx in self._in_ports: if control_flow or 'control_flow' not in self._in_ports[idx] or not self._in_ports[idx]['control_flow']: ports.update({idx: self.in_port(idx, control_flow=control_flow)}) return dict_to_ordered_dict(ports, func=lambda t: str(t)) def out_port(self, idx=None, control_flow=False) -> Port: if not self.has_valid('_out_ports'): raise Error("Operation {} {} has no _out_ports attribute", self.op, self.name) if idx not in self._out_ports: raise Error("Output port with index {} is not in node {}".format(idx, self.name)) if not control_flow and 'control_flow' in self._out_ports[idx] and self._out_ports[idx]['control_flow']: raise Error("Attempt to access control flow port when it's prohibited for node {}".format(self.name)) return Port(node=self, idx=idx, type='out', **self._out_ports[idx]) def out_ports(self, control_flow=False): if not self.has_valid('_out_ports'): raise Error("Operation {} {} has no _out_ports attribute", self.op, self.name) ports = {} for idx in self._out_ports: if control_flow or 'control_flow' not in self._out_ports[idx] or not self._out_ports[idx]['control_flow']: ports.update({idx: self.out_port(idx, control_flow=control_flow)}) return dict_to_ordered_dict(ports, func=lambda t: str(t)) def has_port(self, port_type, idx, control_flow=False): assert port_type in ['in', 'out'], "Invalid usage of has_port method" if port_type == 'in': return self.has_valid('_in_ports') and idx in self.in_ports(control_flow=control_flow) else: return self.has_valid('_out_ports') and idx in self.out_ports(control_flow=control_flow) def is_in_port_connected(self, idx, control_flow=False): return self.has_port('in', idx, control_flow) and not self.in_port(idx, control_flow).disconnected() def is_out_port_connected(self, idx, control_flow=False): return self.has_port('out', idx, control_flow) and not self.out_port(idx, control_flow).disconnected() def attrs(self): return self.graph.node[self.node] def has(self, k): return k in self.graph.node[self.node] def has_valid(self, k): return self.has(k) and not self.graph.node[self.node][k] is None def has_and_set(self, k): return self.has_valid(k) and self[k] def in_nodes_edges(self, control_flow: bool = False): return dict_to_ordered_dict({x[1]['in']: (Node(self.graph, x[0]), x[1]) for x in self.get_inputs(control_flow=control_flow)}) def in_nodes(self, control_flow: bool = False): assert self.has('kind') # TODO: remove as it always exists assert self.kind in ['op', 'data'] # TODO: remove as it always exists if self.kind == 'op': return dict_to_ordered_dict({x[1]['in']: Node(self.graph, x[0]) for x in self.get_inputs(control_flow=control_flow)}) elif self.kind == 'data': return [Node(self.graph, n) for n, d in self.get_inputs(control_flow=control_flow)] def in_node(self, key=0, control_flow: bool = False): return self.in_nodes(control_flow=control_flow)[key] def in_edges(self, control_flow: bool = False): assert self.has('kind') assert self.kind in ['op', 'data'] if self.kind == 'op': return dict_to_ordered_dict({x[1]['in']: x[1] for x in self.get_inputs(control_flow=control_flow)}) elif self.kind == 'data': return [d for n, d in self.get_inputs(control_flow=control_flow)] def out_nodes_edges(self, control_flow: bool = False): return dict_to_ordered_dict({x[1]['out']: (Node(self.graph, x[0]), x[1]) for x in self.get_outputs(control_flow=control_flow)}) def out_nodes(self, control_flow: bool = False): assert self.has('kind') assert self.kind in ['op', 'data'] if self.kind == 'op': return dict_to_ordered_dict({x[1]['out']: Node(self.graph, x[0]) for x in self.get_outputs(control_flow=control_flow)}) elif self.kind == 'data': return [Node(self.graph, n) for n, d in self.get_outputs(control_flow=control_flow)] def out_edges(self, control_flow: bool = False): assert self.has('kind') assert self.kind in ['op', 'data'] if self.kind == 'op': return dict_to_ordered_dict({x[1]['out']: x[1] for x in self.get_outputs(control_flow=control_flow)}) elif self.kind == 'data': return [d for n, d in self.get_outputs(control_flow=control_flow)] def out_node(self, key=0, control_flow: bool = False): return self.out_nodes(control_flow=control_flow)[key] def in_edge(self, key=0, control_flow: bool = False): return self.in_edges(control_flow=control_flow)[key] def out_edge(self, key=0, control_flow: bool = False): return self.out_edges(control_flow=control_flow)[key] def get_attrs(self): return self.graph.node[self.node] def get_inputs(self, edge_attr: dict = None, control_flow: bool = False): if edge_attr is None: edge_attr = {} in_edges = self.graph.in_edges(self.id, data=True) if not control_flow: in_edges = [(u, v, d) for u, v, d in in_edges if 'control_flow_edge' not in d or not d['control_flow_edge']] return [(u, d) for u, v, d in in_edges if all([attr in d and d[attr] == edge_attr[attr] for attr in edge_attr])] def get_outputs(self, edge_attr: dict = None, control_flow: bool = False): if edge_attr is None: edge_attr = {} out_edges = self.graph.out_edges(self.id, data=True) if not control_flow: out_edges = [(u, v, d) for u, v, d in out_edges if 'control_flow_edge' not in d or not d['control_flow_edge']] return [(v, d) for u, v, d in out_edges if all([attr in d and d[attr] == edge_attr[attr] for attr in edge_attr])] def get_sorted_inputs(self, control_flow: bool = False): return sorted([x for x in self.get_inputs(control_flow=control_flow) if 'in' in x[1]], key=lambda x: x[1]['in']) def get_sorted_outputs(self, control_flow: bool = False): return sorted([x for x in self.get_outputs(control_flow=control_flow) if 'out' in x[1]], key=lambda x: x[1]['out']) def soft_get(self, k, default='<UNKNOWN>'): return self[k] if self.has_valid(k) else default def edges(self, attrs: dict = None): """ Get a single edge with specified set of attributes. If none or multiple edges satisfies this criteria, exception is raised Edge is represented as tuple (u, v, d), where u is source node, v is destination node and d is edge attributes. """ edges = list(self.graph.in_edges([self.id], data=True)) + list(self.graph.out_edges([self.id], data=True)) return [(u, v, d) for u, v, d in edges if dict_includes(d, attrs)] def edge(self, attrs: dict = None): """ Get a single edge with specified set of attributes. If none or multiple edges satisfies this criteria, exception is raised Edge is represented as tuple (u, v, d), where u is source node, v is destination node and d is edge attributes. """ edges = self.edges(attrs) assert len(edges) == 1, 'edges: {}, required attributes: {}'.format(edges, attrs) return edges[0] def copy_node(self, new_attrs: dict = None, dst_graph=None): ''' Copies node with all attributes (optionally updated) within the same graph or to different graph.''' if new_attrs is None: new_attrs = {} if dst_graph is None: dst_graph = self.graph attrs = deepcopy(self.attrs()) new_id = dst_graph.unique_id(attrs['name']) if 'name' in attrs else dst_graph.unique_id() attrs['name'] = new_id attrs.update(new_attrs) dst_graph.add_node(new_id, **attrs) return Node(dst_graph, new_id) def insert_node_with_data_before(self, inp, new_op_class: callable, op_before_params: dict = None, infer_current: bool = False, additional_inputs: list = None): """ Inserts operation node with op_before_params and data node before current operation :param inp: input data node of current node :param new_op_class: class of operation that will be inserted before current operation node :param op_before_params: parameters to be added to operation that will be inserted before current operation Before calling: [...] -> inp -> Cur_Op -> Cur_Data -> [...] After calling: [...] -> inp -> New_Op_bef -> New_Data_bef -> Cur_Op -> Cur_Data -> [...] [op_before_params] """ graph = self.graph node = Node(graph, self.node) cls_name = new_op_class.op op_before_params = {} if op_before_params is None else op_before_params # operating with input new_op_before = new_op_class(graph, op_before_params) edge_attrs = deepcopy(graph.get_edge_data(inp.id, node.id)[0]) graph.remove_edge(inp.id, node.id) # form a list of input nodes for a new op node combining new_out and additional_inputs inputs = [inp] + (additional_inputs if additional_inputs else []) new_inp = new_op_before.create_node_with_data(inputs, {'name': node.name + cls_name + '/Before'}) graph.add_edge(new_inp.id, node.id, **edge_attrs) if infer_current: node.infer(node) def insert_node_with_data_after(self, out, new_op_class: callable, op_after_params: dict = None, additional_inputs: list = None): """ Inserts operation node with op_after_params and data node after current operation :param out: output data node of current node :param new_op_class: class of operation that will be inserted after current operation node :param op_after_params: parameters to be added to operation that will be inserted after current operation :param additional_inputs: other parameters for a new operation node in addition to one that is created at the 'out' placed; new nodes are added after 0-th input TODO Allow indexing for input parameters as well as for 'out' data node to explicitly specify ports that are connected to. Before calling: [...] -> Cur_Op -> Cur_Data -> [...] After calling: [...] -> Cur_Op -> Cur_Data -> New_Op_aft -> New_Data_aft(==out) -> [...] [op_after_params] """ # we import it here because Op imports Node and unique_id from this file from mo.ops.op import Op graph = self.graph node = Node(graph, self.node) cls_name = new_op_class.op op_after_params = {} if op_after_params is None else op_after_params new_op_after = new_op_class(graph, op_after_params) graph.remove_edge(node.id, out.id) new_out = Op.create_data_node(graph, node) node.infer(node) # form a list of input nodes for a new op node combining new_out and additional_inputs inputs = [new_out] + (additional_inputs if additional_inputs else []) new_op_after.create_node_with_data(inputs, {'name': node.name + cls_name + '/After'}, data_nodes=out) def bracket_with_different_nodes_with_data(self, inp, out, new_op_class_before: callable, new_op_class_after: callable, op_before_params: dict = None, op_after_params: dict = None): """ Inserts one operation node with op_before_params and data node before current operation node and inserts one operation node with op_after_params and data node after current operation node :param inp: input data node of self.node node :param out: output data node of self.node node :param new_op_class_before: class of operation that will be inserted before current operation node :param new_op_class_after: class of operation that will be inserted after current operation node :param op_before_params: parameters to be added to operation that will be inserted before current operation :param op_after_params: parameters to be added to operation that will be inserted after current operation Before calling: [...] -> inp -> Cur_Op -> out -> [...] After calling: [...] -> inp -> New_Op_bef -> New_Data_bef -> Cur_Op -> Cur_Data -> New_Op_aft -> New_Data_aft(==out) -> [...] [op_before_params] [op_after_params] """ op_before_params = {} if op_before_params is None else op_before_params op_after_params = {} if op_after_params is None else op_after_params self.insert_node_with_data_before(inp, new_op_class_before, op_before_params) self.insert_node_with_data_after(out, new_op_class_after, op_after_params) def bracket_op_with_another_op(self, inp, out, new_op_class: callable, op_before_params: dict = None, op_after_params: dict = None): """ Covers current operation with two similar another ones of class new_op_class: :param inp: input data node of self.node node :param out: output data node of self.node node :param new_op_class: class of operation with which current operation will be covered :param op_before_params: parameters to be added to operation that will be inserted before current operation :param op_after_params: parameters to be added to operation that will be inserted after current operation Before calling: [...] -> inp -> Cur_Op -> out -> [...] After calling: [...] -> inp -> New_Op_bef -> New_Data_bef -> Cur_Op -> Cur_Data -> New_Op_aft -> New_Data_aft(==out) -> [...] [op_before_params] [op_after_params] """ self.bracket_with_different_nodes_with_data(inp=inp, out=out, new_op_class_before=new_op_class, new_op_class_after=new_op_class, op_before_params=op_before_params, op_after_params=op_after_params) def insert_node_after(self, new_node, node_out_port: int = 0): """ Insert node 'new_node' after output with index 'node_out_port' of the node 'node'. All consumers of node 'node' output with index 'node_out_port' will be changed to consume node 'new_node'. The function should be used when graph doesn't contain data nodes yet. :param node: node after which new node should be inserted. :param new_node: node to be inserted. :param node_out_port: the output index for the node 'node' to insert :return: None """ assert self.graph is new_node.graph assert (len([name for name in self.graph.nodes() if Node(self.graph, name).soft_get('kind') == 'data']) == 0) graph = self.graph old_edges = list(graph.out_edges(self.id, data=True, keys=True)) # create new edges first and then remove all old edges. This is needed for case when 'node' has several consumers # getting input from 'node_out_port'. # save tuple ("name of the destination edge", "edge key") to be removed node_name_and_edge_key = [] for _, dst_name, edge_key, edge_attrs in old_edges: if edge_attrs['out'] == node_out_port: log.debug('Create edge from "{}" to "{}"'.format(new_node.name, dst_name)) graph.create_edge(new_node, Node(graph, dst_name), 0, edge_attrs['in']) node_name_and_edge_key.append((dst_name, edge_key)) for dst_name, edge_key in node_name_and_edge_key: log.debug('Remove edge from "{}" to "{}"'.format(self.id, dst_name)) graph.remove_edge(self.id, dst_name, edge_key) graph.create_edge(self, new_node, node_out_port, 0, {}) def insert_op_on_input_port(self, in_port_idx: int, new_op_class: callable, new_op_attrs: dict, value: np.ndarray = None): """ Inserts new operation of new_op_class on in_port_index input port with new_op_attrs Connects Const operation with value to 1 input port of new node if value was passed Returns new operation node """ graph = self.graph name = self.soft_get('name', self.id) op_node = new_op_class(graph, new_op_attrs).create_node() assert self.has_port('in', in_port_idx), \ 'Node `{}` should have input port with idx `{}` but it does not'.format(name, in_port_idx) in_port_source = self.in_port(in_port_idx).get_source() self.in_port(in_port_idx).get_connection().set_source(op_node.out_port(0)) op_node.in_port(0).connect(in_port_source) if value is not None: from mo.ops.const import Const constant = Const(graph, {'value': value, 'name': op_node.name + '/value'}).create_node() op_node.in_port(1).connect(constant.out_port(0)) return op_node def replace_node(self, new_node, new_node_out_port: int = None): """ Replaces node 'old_node' with a node 'new_node' preserving edge attributes. :param old_node: node to be replaced. :param new_node: node to replace with. :return: None """ assert self.graph is new_node.graph assert self.id != new_node.id, "New node and replaceable node are the same" graph = self.graph # save output edges and reconnect them to new node for _, dst_node_name, edge_attrs in graph.out_edges(self.id, data=True): new_edge_attrs = deepcopy(edge_attrs) if new_node_out_port is not None: assert 'out' not in edge_attrs or edge_attrs['out'] == 0, \ 'replace_node function can replace old node with a single output port only if new_node_out_port is ' \ 'specified' new_edge_attrs.update({'out': new_node_out_port}) graph.add_edge(new_node.id, dst_node_name, **new_edge_attrs) # if the node for replace is output node then we propagate this attribute to a new node if len(self.out_nodes()) == 1 and self.out_node().has('op') and self.out_node().op == 'Result': graph.remove_node(self.out_node().id) add_opoutput(graph, new_node.id, 0, False) graph.remove_node(self.id) def input_ports_with(self, node): """ Returns a list of integers that specify input ports that connected to a given node. :param node: node in the graph that is expected to appear at input port for self node :return: a list of integers with port indices that are connected to self node """ return [i for i in range(len(self.in_nodes())) if self.in_node(i).id == node.id] def update_node(self): """ Update internal node attributes. Currently it just add input/output ports. :return: None """ in_ports_count = self.in_ports_count if self.has_valid('in_ports_count') else None out_ports_count = self.out_ports_count if self.has_valid('out_ports_count') else None if not self.has_valid('_in_ports'): Node(self.graph, self.id)['_in_ports'] = dict() if not self.has_valid('_out_ports'): Node(self.graph, self.id)['_out_ports'] = dict() if in_ports_count is not None: for idx in range(in_ports_count): if idx not in self._in_ports: self.add_input_port(idx=idx) if out_ports_count is not None: for idx in range(out_ports_count): if idx not in self._out_ports: self.add_output_port(idx=idx) def get_opset(self): """ Gets the operation set version where the operation was introduced. If the version is not defined then consider it an extension :return: the string with the opset name """ return self.soft_get('version', 'extension') class Graph(nx.MultiDiGraph): def __init__(self, data=None, **attr): self.stage = None self.strict_mode = True super().__init__(data, **attr) if not hasattr(self, 'node'): self.node = self.nodes unique_id_count = 0 # SAFE API DESCRIPTION # all provided methods below are designed to be more safe and convenient # be careful while using other methods from nx.MultiDiGraph def add_node(self, node_for_adding, **attrs): # TODO: check required attrs for node super().add_node(node_for_adding, **attrs) node = Node(self, node_for_adding) node.update_node() def add_edge(self, u_for_edge, v_for_edge, key=None, **attr): # TODO: turn on strict mode if self.strict_mode: unode = Node(self, u_for_edge) vnode = Node(self, v_for_edge) # Check that we connect Op->Op in front phase, and data->Op or Op->data in middle(back) phase # Also check that all necessary ports are exists message = "Attempt to connect {} to {}.".format(u_for_edge, v_for_edge) if self.stage == 'front': assert unode.kind == 'op' and vnode.kind == 'op', "{} Wrong add_adge usage! You can connect only two " \ "operations in front phase".format(message) assert 'in' in attr and 'out' in attr, "Missing necessary attribute in or out when adding edge " \ "between {} and {}".format(u_for_edge, v_for_edge) is_control_flow = 'control_flow_edge' in attr and attr['control_flow_edge'] is True in_port = 'control_flow_{}'.format(attr['in']) if is_control_flow else attr['in'] out_port = 'control_flow_{}'.format(attr['out']) if is_control_flow else attr['out'] assert unode.has_port('out', out_port, control_flow=is_control_flow), \ "{} Missing out port ({}) in {} node".format(message, out_port, unode.soft_get('name', unode.id)) assert vnode.has_port('in', in_port, control_flow=is_control_flow), \ "{} Missing in port ({}) in {} node".format(message, in_port, vnode.soft_get('name', vnode.id)) elif self.stage in ['middle', 'back']: assert (unode.kind == 'data' and vnode.kind == 'op') or (unode.kind == 'op' and vnode.kind == 'data') if unode.kind == 'data' and vnode.kind == 'op': assert 'in' in attr, "Attribute in is missing when adding edge to {}".format(v_for_edge) assert vnode.has_port('in', attr['in']), "{} Node {} has no in port ({})" \ "".format(message, vnode.name, attr['in']) if unode.kind == 'op' and vnode.kind == 'data': assert 'out' in attr, "Attribute out is missing when adding edge from {}".format(u_for_edge) assert unode.has_port('out', attr['out']), "{} Node {} has no out port ({})" \ "".format(message, unode.name, attr['out']) return super().add_edge(u_for_edge, v_for_edge, key=key, **attr) def add_edges_from(self, ebunch_to_add, **attr): for e in ebunch_to_add: ne = len(e) if ne == 4: u, v, key, dd = e elif ne == 3: u, v, dd = e key = None elif ne == 2: u, v = e dd = {} key = None else: raise Error("Edge tuple %s must be a 2-tuple, 3-tuple or 4-tuple." % (e,)) ddd = attr.copy() ddd.update(dd) self.add_edge(u, v, key=key, **ddd) def remove_edge(self, u, v, key=None): return super().remove_edge(u, v, key=key) def erase_node(self, node: Node): """ Erases node from the graph and reconnect edges from input node(s) to output node(s) Produces assertion error if the node being removed has multiple inputs or outputs. The function can be used in the front phase only (when there are no data nodes in the graph). :param node: Node to erase """ node_id = node.id inputs = list(self.in_edges(node_id, data=True)) outputs = list(self.out_edges(node_id, data=True)) assert node.kind == 'op' and (len(node.out_nodes()) == 0 or list(node.out_nodes().values())[0].kind != 'data'), \ "The function must be used before the partial infer when graph doesn't contain data nodes." assert len(node.out_nodes()) <= 1, "The node {} must produce just one output tensor".format( node.soft_get('name')) assert len(inputs) <= 1, "The node {} must have just one input".format(node.soft_get('name')) if len(outputs) == 0 and len(inputs) != 0: from mo.front.extractor import add_output_ops input_ids = {input_node_id: {'port': {'out': [attrs['out']]}} for input_node_id, _, attrs in inputs} if node.has('op') and node.op == 'Result': add_output_ops(self, input_ids) if len(outputs) == 0 or len(inputs) == 0: self.remove_node(node_id) return input_node_id = inputs[0][0] for src, dst, attrs in outputs: self.remove_edge(src, dst) # update the 'out' attribute of the edge from the node being removed attrs['out'] = inputs[0][2]['out'] self.add_edge(input_node_id, dst, **attrs) self.remove_node(node_id) def get_edge_data(self, u, v, key=None, default=None): return super().get_edge_data(u, v, key=key, default=default) def get_inputs_with_ports(self, match, pattern_edges, input_names_in_pattern): """ Front replacements of multi-input nodes should specify output port to add_node-like functions This function is a helper to get such information out of matched nodes :param graph: graph to operate on :param match: dictionary returned by matching function :param pattern_edges: edges that are specified in pattern :param input_names_in_pattern: names of matched nodes as they were specified in pattern that should be in resulting list :return: list of tuples of node and output port """ inputs = [] for name in input_names_in_pattern: assert name in match, "node named {} not in match {}".format(name, match) src = match[name] dst = [] for edge in pattern_edges: if edge[0] == name: assert edge[1] in match, "name from pattern_edges {} not in match {}".format(edge[1], match) dst.append(match[edge[1]]) if len(dst) != 1: raise Error('Multiple output ports detected for node {} as {} in pattern'.format(match[name].id, name)) dst = dst[0] out_port = self.get_edge_data(src.id, dst.id)[0]['out'] inputs.append((src, out_port)) return inputs def get_node_id_by_name(self, name: str): nodes = self.get_nodes_with_attributes(name=name) if len(nodes) == 0: raise Error('No node with name {}. ' + refer_to_faq_msg(51), name) elif len(nodes) > 1: raise Error('Multiple nodes with name {}'.format(name)) else: return nodes[0] def get_op_nodes(self, **attrs): nodes = self.get_nodes_with_attributes(**dict(kind='op', **attrs)) return [Node(self, node) for node in nodes] def get_data_nodes(self, has_value=None): """ Returns list of data nodes. If has_value = True, returns data nodes with value If has_value = False, returns data nodes without value """ data_nodes = [Node(self, node) for node in self.nodes() if Node(self, node).soft_get('kind') == 'data'] return [node for node in data_nodes if has_value is None or node.has_valid('value') == has_value] def get_nodes_with_attributes(self, **attrs: dict): node_attrs = self.nodes(data=True) return [n for n, d in node_attrs if all(a in d.items() for a in attrs.items())] def unique_id(self, prefix: str = ""): """ Generates a unique node id for a new node in a given graph. The optional string prefix can be specified. """ # TODO thread safety? self.unique_id_count = max(self.unique_id_count, self.number_of_nodes()) + 1 if prefix and not self.has_node(prefix): return str(prefix) while self.has_node(prefix + str(self.unique_id_count)): self.unique_id_count += 1 return prefix + str(self.unique_id_count) def check_empty_graph(self, description: str): if len(self.nodes()) <= 1: raise Error( "Graph contains {} node after executing {}. It considered as error because resulting IR will be " "empty which is not usual".format(len(self.nodes()), description)) def check_shapes_consistency(self): data_nodes = self.get_data_nodes() data_nodes_with_wrong_shapes = [] for data_node in data_nodes: if not data_node.has('shape'): data_nodes_with_wrong_shapes.append((data_node.name, "no shape attribute")) continue if data_node.shape is not None and not isinstance(data_node.shape, np.ndarray): data_nodes_with_wrong_shapes.append((data_node.name, type(data_node.shape))) if len(data_nodes_with_wrong_shapes) > 0: raise Error("Graph contains data nodes ({}) with inconsistent shapes: {}".format( len(data_nodes_with_wrong_shapes), data_nodes_with_wrong_shapes )) def check_nodes_ports_are_consecutive(self): # Check that all operation nodes has consecutive ports indexes op_nodes = self.get_op_nodes() for node in op_nodes: for idx in range(len(node.in_ports())): if idx not in node.in_ports(): raise Error("Node {} has not consecutive in ports indexes: {}".format(node.name, list(node.in_ports().keys()))) for idx in range(len(node.out_ports())): if idx not in node.out_ports(): raise Error("Node {} has not consecutive out ports indexes: {}".format(node.name, list( node.out_ports().keys()))) def dump_graph_for_graphviz(self, node_attrs: list = ['kind', 'op', 'shape', 'correct_data_layout', 'nchw_layout', 'internal_layer_id'], edge_attrs: list = ['in', 'out'], nodes_to_dump: list = None, save_to_svg=False, highlight_nodes: list = None): from extensions.ops.tensor_iterator import _get_internal_output_node_id, _get_internal_input_node_id fill_color = {'op': 'lightblue', 'data': 'whitesmoke', 'highlight': 'firebrick'} fill_color_by_type = {'Const': 'lightpink', 'Parameter': 'yellowgreen', 'TensorIterator': 'lemonchiffon'} style = {'op': 'filled,bold', 'data': 'filled,rounded'} subgraphs = {} if highlight_nodes is None: highlight_nodes = [] def _subgraph_label(node_id, node_attrs: dict, attrs_to_print: list): subgraphs[node_id] = "cluster_{}".format(node_id) label = 'subgraph "cluster_{}" '.format(node_id) + '{\n' label += 'label = "{}"; \n'.format(node_id) label += 'color={}; \nstyle="filled,rounded";\n'.format(fill_color_by_type[node_attrs['op']]) subgraph_name = node_attrs['sub_graphs'] assert len(subgraph_name) == 1 body = node_attrs[subgraph_name[0]].dump_graph_for_graphviz() body = body.split('\n')[2:-1] label += '\n'.join(body) label += '\n}\n' return label def _node_label(node_id, node_attrs: dict, attrs_to_print: list): label = str(node_id) + '\\n' + '\\n'.join([str(key) + '=' + str(node_attrs.get(key, 'None')) for key in attrs_to_print if key in node_attrs]) if node_attrs.get('type', '') == 'Const': if 'value' not in attrs_to_print and 'value' in node_attrs: if node_attrs['value'] is not None: label += '\\nvalue=\\"' + \ ','.join([str(val) for val in node_attrs['value'].flatten()])[:40] + '\\"' else: label += '\\nvalue=None' return label def _dump_nodes_attrs(): string = '' for node_id in nodes_to_dump: attrs = self.node[node_id] color = fill_color_by_type.get(attrs.get('type', ''), fill_color[attrs['kind']]) if node_id in highlight_nodes or 'highlight' in node_attrs and node_attrs['highlight']: color = fill_color['highlight'] if attrs.get('op') == 'TensorIterator': string += _subgraph_label(node_id, attrs, node_attrs) else: string += '"{}" [fillcolor={} style="{}" shape=box label="{}"];\n'.format( node_id, color, style[attrs['kind']], _node_label(node_id, attrs, node_attrs)) return string def _dump_edges_attrs(): string = '' for src_node_id, dst_node_id, attrs in self.edges(data=True): if src_node_id not in nodes_to_dump or dst_node_id not in nodes_to_dump: continue if src_node_id in subgraphs: edge_label = subgraphs[src_node_id] edge_label_name = 'ltail' src_node_id = _get_internal_output_node_id(self, src_node_id, attrs['external_port_id']) elif dst_node_id in subgraphs: edge_label = subgraphs[dst_node_id] edge_label_name = 'lhead' dst_node_id = _get_internal_input_node_id(self, dst_node_id, attrs['external_port_id']) else: edge_label = ' '.join( [str(key) + '=' + str(attrs.get(key, 'None')) for key in edge_attrs if key in attrs]) edge_label_name = 'label' string += '"{}" -> "{}" [{} = "{}"];\n'.format(src_node_id, dst_node_id, edge_label_name, edge_label) return string log.debug("---- GRAPHVIZ OUTPUT STARTS ----") if nodes_to_dump is None: nodes_to_dump = self.nodes() string = '\ndigraph {\n' string += _dump_nodes_attrs() string += _dump_edges_attrs() string += '}' log.debug("---- GRAPHVIZ OUTPUT ENDS ----") if save_to_svg: try: import graphviz import os file_name = "{}_{}.txt".format(self.name.replace('/', '_'), 0) id = 1 while os.path.exists(file_name): file_name = "{}_{}.txt".format(self.name.replace('/', '_'), id) id += 1 with open(file_name, "w") as f: f.write(string) graphviz.render('dot', 'svg', file_name) print('Graph was saved to {}.{}'.format(file_name, 'svg')) except ImportError: raise ImportError('Can\'t import graphviz') except Exception as e: raise Error('Can\'t save graph to svg') from e return string def print_graph_stat(self): log.debug('Number of nodes in graph: {}'.format(self.number_of_nodes())) log.debug('Number of edges in graph: {}'.format(len(list(self.edges())))) ops = collections.defaultdict(int) for _node in self.nodes(): node = Node(self, _node) kind = node.kind if node.has('kind') else '<UNDEFINED>' if node.has('op'): ops['op/' + node.op] += 1 else: ops[kind] += 1 if node.has('shape') and np.any(node.shape == 0): log.error("Found bad shape: '{}' for node '{}'".format(node.shape, node.node)) for k, v in ops.items(): log.debug(' {} : {}'.format(k, v)) def create_sub_graph_copy(self, nodes_to_extract: list): """ Create new graph which is a sub-graph of the 'graph' that contains just nodes from 'nodes_to_extract' list. The returned sub-graph is a deep copy of the provided graph nodes. :param graph: graph to create a sub-graph from. :param nodes_to_extract: list of node names to extract. :return: new graph. """ return self.subgraph(nodes_to_extract).copy() def create_edge(self, src_node: Node, dst_node: Node, out_port: int = 0, in_port: int = 0, edge_attrs: dict = None): """ Creates edge from node 'src_node' from output with index 'out_port' to node 'dst_node' with input index 'in_port'. :param src_node: node to create edge from. :param dst_node: node to create edge to. :param out_port: the index of output tensor of the 'src_node'. :param in_port: the input index of the node 'dst_node'. :param edge_attrs: dictionary with edge attrs. :return: None """ # edges must belong to the same graph assert src_node.graph is dst_node.graph graph = src_node.graph if edge_attrs is None: edge_attrs = dict() else: edge_attrs = edge_attrs.copy() edge_attrs.update( {'in': in_port, 'out': out_port, 'in_attrs': ['in', 'permutation'], 'out_attrs': ['out', 'permutation'], 'data_attrs': ['fw_tensor_debug_info']}) # TODO: in case if in_port do not exists, we should raise an Exception here graph.add_edges_from([(src_node.id, dst_node.id, edge_attrs)]) def dfs(self, node_name: str, visited: set): """ Implementation of the depth-first search algorithm starting from the specific node. :param graph: networkx graph to operate on. :param node_name: node name to start search from. :param visited: set of already visited nodes. :return: list of nodes in the DFS-visit order. """ order = [] stack = [node_name] while len(stack) != 0: node_name = stack[0] stack.pop(0) visited.add(node_name) has_child = False for _, out_node_name in self.out_edges(node_name): if out_node_name not in visited: stack.insert(0, node_name) stack.insert(0, out_node_name) has_child = True break if not has_child: order.append(node_name) return order def pseudo_topological_sort(self, reverse: bool = False): """ The function performs topological sort but doesn't check for cycle existence. So it may produce wrong nodes order for some applications. :param graph: graph to pseudo-topologically sort. :param reverse: flag indicating whether need to reverse nodes order. :return: nodes in the topological sort if cycle doesn't exist and in pseudo-topological sort if not. """ nodes_without_inputs = list() for node_name in self.nodes(): if len(self.in_edges(node_name)) == 0: nodes_without_inputs.append(node_name) order = list() visited = set() for node_name in nodes_without_inputs: if node_name not in visited: order.extend(self.dfs(node_name, visited)) order = [Node(self, node) for node in order] if reverse: return order else: return list(reversed(order)) def clean_up(self, undead_node_types: list = None): if undead_node_types is None: undead_node_types = [] if not getattr(self.graph['cmd_params'], 'static_shape', False): undead_node_types.extend(['ShapeOf', 'Shape', 'slice_like']) mark_output_reachable_nodes(self) shape_inference(self) mark_undead_nodes(self, undead_node_types) mark_const_producer_nodes(self) eliminate_dead_nodes(self) # Add Const op for constant data nodes add_constant_operations(self) def fill_graph_with_nodes(graph, src_nodes, get_id: callable, get_attrs: callable): """ Go over all nodes in src_nodes that should be enumerable and create new NX nodes using get_id and get_attrs functions to create node id and node attributes correspondingly. """ for node in src_nodes: graph.add_node(get_id(node), **get_attrs(node)) def dict_includes_compare_attrs(attr, attr_probe): if callable(attr_probe) and not isinstance(attr_probe, type): return attr_probe(attr) else: res = (attr == attr_probe) # check if the result of comparison is a numpy scalar value which occur when attr is python scalar and # attr_probe is a numpy scalar if hasattr(res, 'ndim') and res.ndim == 0: return res.item() return res if isinstance(res, bool) else all(res) def dict_includes(big: dict, sub_dict: dict, skip_attr_names=[]): """ Searches attributes from sub_dict in big and ensures that all values match. Entries in sub_dict can be of two types: callable or not callable. If callable is specified it is treated as probing function for attribute value from big dictionary by callable(attr) expression. If it is not callable, the values are compared with == operator. """ return all( dict_includes_compare_attrs(big.get(attr, None), sub_dict[attr]) for attr in sub_dict.keys() if attr not in skip_attr_names ) def add_opoutput(graph: Graph, node_name: str, port: int, cut: bool = True): """ Creates and connects Result node to node_name port. Cuts existing port if requested. :param graph: graph to operate with :param node_name: name of existing node in the graph that we want to add Result to :param port: output port of node to connect Result to :param cut: determines way of operating with edge specified by node_name and port """ # we import it here because Op imports add_attrs_props and update_ie_fields from this file from mo.ops.result import Result node = Node(graph, node_name) if cut and len(node.out_edges()) != 0: opoutput_node = Result(graph).create_node_on_port(node, port, {'name': node_name + '/sink_port_' + str(port)}) else: tensor_names = None if node.has_valid('op') and port in node.out_ports(): tensor_names = node.out_port(port).get_tensor_names() opoutput_node = Result(graph).create_node([(node, port)], {'name': node_name + '/sink_port_' + str(port)}) opoutput_node.in_edge()['data_attrs'] = ['fw_tensor_debug_info'] opoutput_node.in_edge()['fw_tensor_debug_info'] = [(node_name, port, tensor_names)] log.debug('Sink: {} for node {}'.format(opoutput_node.id, node_name)) log.debug(str(graph.node[opoutput_node.id])) log.debug("Add edge from {} to {}".format(node_name, opoutput_node.id)) return opoutput_node.id # TODO implement merging for keys with dictionary values? def merge_edge_props(attrs: dict, additional_attrs: dict): """ Update edge attributes without changing 'in' and 'out' keys. It is necessary to copy edge attributes during merging of nodes when result of one subgraph call is passed as input to another subgraph call """ result = attrs for (key, value) in additional_attrs.items(): if key not in ['in', 'out']: if type(additional_attrs[key]) is list: if key not in result: result[key] = [] result[key].extend(additional_attrs[key]) result[key] = list(set(result[key])) # silly solution to find unique elements else: result[key] = value return result def rename_node(node: Node, name): if not node.graph.get_nodes_with_attributes(name=name): node.name = name else: assert 'Node with name {} already exists'.format(name) def rename_nodes(nodes: List[tuple]): for node, name in nodes: rename_node(node, name) def get_edge_attribute_between_nodes(node1: Node, node2: Node, attr_name: str): """ Gets edge attribute value between two nodes. This method is introduced for implementation of manual replacing of nodes attributes with tensor debug information. It is needed after removing of fake outputs. Also there are cases when graph transformations lead to mismatch of tensor name and input node, so manual attribute change is needed. This method should only be used during the front phase. And it is applicable only for cases when there is just one edge between two given nodes. """ for edge_idx in node1.out_edges(): edge = node1.out_edge(edge_idx) out_port = edge['out'] out_node = node1.out_node(out_port) if out_node.id == node2.id: if attr_name in edge: return edge[attr_name] return None def set_edge_attribute_between_nodes(node1: Node, node2: Node, attr_name: str, new_value): """ Sets edge attribute value between two nodes. This method is introduced for implementation of manual replacing of nodes attributes with tensor debug information. It is needed after removing of fake outputs. Also there are cases when graph transformations lead to mismatch of tensor name and input node, so manual attribute change is needed. This method should only be used during the front phase. And it is applicable only for cases when there is just one edge between two given nodes. """ for edge_idx in node1.out_edges(): edge = node1.out_edge(edge_idx) out_port = edge['out'] out_node = node1.out_node(out_port) if out_node.id == node2.id: if attr_name in edge: edge[attr_name] = new_value # All functions below are deprecated and will be removed in next release # Please, use methods from Graph/Node classes instead @deprecated_api(Graph) def get_node_id_by_name(graph: Graph, name: str): return graph.get_node_id_by_name(name=name) @deprecated_api(Graph) def print_graph_stat(graph: Graph): return graph.print_graph_stat() @deprecated_api(Graph) def get_inputs_with_ports(graph: Graph, match, pattern_edges, input_names_in_pattern): """ Front replacements of multi-input nodes should specify output port to add_node-like functions This function is a helper to get such information out of matched nodes :param graph: graph to operate on :param match: dictionary returned by matching function :param pattern_edges: edges that are specified in pattern :param input_names_in_pattern: names of matched nodes as they were specified in pattern that should be in resulting list :return: list of tuples of node and output port """ return graph.get_inputs_with_ports(match=match, pattern_edges=pattern_edges, input_names_in_pattern=input_names_in_pattern) @deprecated_api(Graph) def dump_graph_for_graphviz(graph: Graph, node_attrs: list = ['kind', 'op', 'shape'], edge_attrs: list = ['in', 'out'], nodes_to_dump: list = None, save_to_svg=False): return graph.dump_graph_for_graphviz(node_attrs=node_attrs, edge_attrs=edge_attrs, nodes_to_dump=nodes_to_dump, save_to_svg=save_to_svg) @deprecated_api(Graph) def create_sub_graph_copy(graph: Graph, nodes_to_extract: list): """ Create new graph which is a sub-graph of the 'graph' that contains just nodes from 'nodes_to_extract' list. The returned sub-graph is a deep copy of the provided graph nodes. :param graph: graph to create a sub-graph from. :param nodes_to_extract: list of node names to extract. :return: new graph. """ return graph.create_sub_graph_copy(nodes_to_extract=nodes_to_extract) @deprecated_api(Graph) def get_graph_ops(graph: Graph): return graph.get_op_nodes() @deprecated_api(Graph) def check_empty_graph(graph: Graph, description: str): return graph.check_empty_graph(description=description) @deprecated_api(Graph) def create_edge(src_node: Node, dst_node: Node, out_port: int = 0, in_port: int = 0, edge_attrs: dict = None): """ Creates edge from node 'src_node' from output with index 'out_port' to node 'dst_node' with input index 'in_port'. :param src_node: node to create edge from. :param dst_node: node to create edge to. :param out_port: the index of output tensor of the 'src_node'. :param in_port: the input index of the node 'dst_node'. :param edge_attrs: dictionary with edge attrs. :return: None """ assert src_node.graph is dst_node.graph graph = src_node.graph return graph.create_edge(src_node=src_node, dst_node=dst_node, out_port=out_port, in_port=in_port, edge_attrs=edge_attrs) @deprecated_api(Graph) def erase_node(node: Node): """ Erases node from the graph and reconnect edges from input node(s) to output node(s) Produces assertion error if the node being removed has multiple inputs or outputs. The function can be used in the front phase only (when there are no data nodes in the graph). :param node: Node to erase """ graph = node.graph return graph.erase_node(node) @deprecated_api(Node) def get_sorted_inputs(node: Node, control_flow: bool = False): return node.get_sorted_inputs(control_flow=control_flow) @deprecated_api(Node) def get_sorted_outputs(node: Node, control_flow: bool = False): return node.get_sorted_outputs(control_flow=control_flow) @deprecated_api(Node) def insert_node_after(node: Node, new_node: Node, node_out_port: int = 0): """ Insert node 'new_node' after output with index 'node_out_port' of the node 'node'. All consumers of node 'node' output with index 'node_out_port' will be changed to consume node 'new_node'. The function should be used when graph doesn't contain data nodes yet. :param node: node after which new node should be inserted. :param new_node: node to be inserted. :param node_out_port: the output index for the node 'node' to insert :return: None """ return node.insert_node_after(new_node=new_node, node_out_port=node_out_port) @deprecated_api(Node) def replace_node(old_node: Node, new_node: Node, new_node_out_port: int = None): """ Replaces node 'old_node' with a node 'new_node' preserving edge attributes. :param old_node: node to be replaced. :param new_node: node to replace with. :return: None """ return old_node.replace_node(new_node=new_node, new_node_out_port=new_node_out_port) @deprecated_api(Node) def copy_node(src_node: Node, new_attrs: dict = None, dst_graph: nx.MultiDiGraph = None): """ Copies node with all attributes (optionally updated) within the same graph or to different graph.""" return src_node.copy_node(new_attrs=new_attrs, dst_graph=dst_graph) @deprecated_api(Node) def get_inputs(graph: Graph, node: str, edge_attr: dict = None, control_flow: bool = False): return Node(graph, node).get_inputs(edge_attr=edge_attr, control_flow=control_flow) @deprecated_api(Node) def get_outputs(graph: Graph, node: str, edge_attr: dict = None, control_flow: bool = False): return Node(graph, node).get_outputs(edge_attr=edge_attr, control_flow=control_flow)
{ "alphanum_fraction": 0.6228148442, "author": null, "avg_line_length": 47.1355140187, "converted": null, "ext": "py", "file": null, "hexsha": "dbfc556cea9df7ec556026cd15ea74a1c9e12bed", "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": "67a82a040faaf66f109035acf7de6e4b7568bc08", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "jayabs2020/openvino", "max_forks_repo_path": "model-optimizer/mo/graph/graph.py", "max_issues_count": 19, "max_issues_repo_head_hexsha": "5c5f41e66410ba4484099d912822b0217e13287a", "max_issues_repo_issues_event_max_datetime": "2022-02-21T13:06:26.000Z", "max_issues_repo_issues_event_min_datetime": "2021-03-26T08:11:00.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "juierror/openvino", "max_issues_repo_path": "model-optimizer/mo/graph/graph.py", "max_line_length": 122, "max_stars_count": null, "max_stars_repo_head_hexsha": "5c5f41e66410ba4484099d912822b0217e13287a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "juierror/openvino", "max_stars_repo_path": "model-optimizer/mo/graph/graph.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 13404, "path": null, "reason": "import numpy,import networkx", "repo": null, "save_path": null, "sha": null, "size": 60522 }
Subroutine chkout(l, t, tmin, nc) Implicit Double Precision (A-H, O-Z) Parameter (maxptn=400001) Common /prec2/gx(maxptn), gy(maxptn), gz(maxptn), ft(maxptn), px(maxptn), py(maxptn), pz(maxptn), e(maxptn), xmass(maxptn), ityp(maxptn) Save m1 = 11 m2 = 11 m3 = 11 Call chkcel(l, m1, m2, m3, t, tmin, nc) Do i = 1, 10 Do j = 1, 10 Do k = 1, 10 If (i==1 .Or. i==10 .Or. j==1 .Or. j==10 .Or. k==1 .Or. k==10) Call chkcel(l, i, j, k, t, tmin, nc) End Do End Do End Do Return End Subroutine chkout
{ "alphanum_fraction": 0.5680580762, "author": null, "avg_line_length": 29, "converted": null, "ext": "f90", "file": null, "hexsha": "8e8759233ff4d09fbcd1d5467ac34b05c40b6fb9", "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": "90c7a1ab4dc04a092e64af759d53e22f6fea5b02", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "xiaohaijin/AMPT", "max_forks_repo_path": "src/chkout.f90", "max_issues_count": null, "max_issues_repo_head_hexsha": "90c7a1ab4dc04a092e64af759d53e22f6fea5b02", "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": "xiaohaijin/AMPT", "max_issues_repo_path": "src/chkout.f90", "max_line_length": 138, "max_stars_count": 2, "max_stars_repo_head_hexsha": "90c7a1ab4dc04a092e64af759d53e22f6fea5b02", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "xiaohaijin/AMPT", "max_stars_repo_path": "src/chkout.f90", "max_stars_repo_stars_event_max_datetime": "2021-03-14T12:58:59.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-24T19:37:06.000Z", "num_tokens": 244, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 551 }
# Lint as: python3 # Copyright 2018 Google LLC # # 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 # # https://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. """General utilities.""" from __future__ import absolute_import from __future__ import division # Standard __future__ imports from __future__ import print_function import inspect import sys import traceback from typing import Any, Callable, Dict, List, Optional, Text, Union import numpy as np import six import tensorflow as tf from tensorflow_model_analysis import constants from tensorflow_model_analysis import types # Separator used when combining multiple layers of Extracts keys into a single # string. Normally we would like to use '.' or '/' as a separator, but the # output gets written to a table backed by a proto based schema which limits the # characters that can be used to [a-zA-Z_]. KEY_SEPARATOR = '__' # Suffix for keys representing the top k keys associated with a sparse item. KEYS_SUFFIX = 'keys' # Suffix for keys representing the top k values associated with a sparse item. VALUES_SUFFIX = 'values' def unique_key(key: Text, current_keys: List[Text], update_keys: Optional[bool] = False) -> Text: """Returns a unique key given a list of current keys. If the key exists in current_keys then a new key with _1, _2, ..., etc appended will be returned, otherwise the key will be returned as passed. Args: key: desired key name. current_keys: List of current key names. update_keys: True to append the new key to current_keys. """ index = 1 k = key while k in current_keys: k = '%s_%d' % (key, index) index += 1 if update_keys: current_keys.append(k) return k def compound_key(keys: List[Text], separator: Text = KEY_SEPARATOR) -> Text: """Returns a compound key based on a list of keys. Args: keys: Keys used to make up compound key. separator: Separator between keys. To ensure the keys can be parsed out of any compound key created, any use of a separator within a key will be replaced by two separators. """ return separator.join([key.replace(separator, separator * 2) for key in keys]) def create_keys_key(key: Text) -> Text: """Creates secondary key representing the sparse keys associated with key.""" return '_'.join([key, KEYS_SUFFIX]) def create_values_key(key: Text) -> Text: """Creates secondary key representing sparse values associated with key.""" return '_'.join([key, VALUES_SUFFIX]) def get_by_keys(data: Dict[Text, Any], keys: List[Any], default_value=None, optional: bool = False) -> Any: """Returns value with given key(s) in (possibly multi-level) dict. The keys represent multiple levels of indirection into the data. For example if 3 keys are passed then the data is expected to be a dict of dict of dict. For compatibily with data that uses prefixing to create separate the keys in a single dict, lookups will also be searched for under the keys separated by '/'. For example, the keys 'head1' and 'probabilities' could be stored in a a single dict as 'head1/probabilties'. Args: data: Dict to get value from. keys: Sequence of keys to lookup in data. None keys will be ignored. default_value: Default value if not found. optional: Whether the key is optional or not. If default value is None and optional is False then a ValueError will be raised if key not found. Raises: ValueError: If (non-optional) key is not found. """ if not keys: raise ValueError('no keys provided to get_by_keys: %d' % data) format_keys = lambda keys: '->'.join([str(k) for k in keys if k is not None]) value = data keys_matched = 0 for i, key in enumerate(keys): if key is None: keys_matched += 1 continue if not isinstance(value, dict): raise ValueError('expected dict for "%s" but found %s: %s' % (format_keys(keys[:i + 1]), type(value), data)) if key in value: value = value[key] keys_matched += 1 continue # If values have prefixes matching the key, return those values (stripped # of the prefix) instead. prefix_matches = {} for k, v in value.items(): if k.startswith(key + '/'): prefix_matches[k[len(key) + 1:]] = v if prefix_matches: value = prefix_matches keys_matched += 1 continue break if keys_matched < len(keys) or isinstance(value, dict) and not value: if default_value is not None: return default_value if optional: return None raise ValueError('"%s" key not found (or value is empty dict): %s' % (format_keys(keys[:keys_matched + 1]), data)) return value def reraise_augmented(exception: Exception, additional_message: Text) -> None: """Reraise a given exception with additional information. Based on _reraise_augmented in Apache Beam. Args: exception: Original exception. additional_message: Additional message to append to original exception's message. """ # To emulate exception chaining (not available in Python 2). original_traceback = sys.exc_info()[2] try: # Attempt to construct the same kind of exception # with an augmented message. # # pytype: disable=attribute-error # PyType doesn't know that Exception has the args attribute. new_exception = type(exception)( exception.args[0] + ' additional message: ' + additional_message, *exception.args[1:]) # pytype: enable=attribute-error except: # pylint: disable=bare-except # If anything goes wrong, construct a RuntimeError whose message # records the original exception's type and message. new_exception = RuntimeError( traceback.format_exception_only(type(exception), exception)[-1].strip() + ' additional message: ' + additional_message) six.reraise(type(new_exception), new_exception, original_traceback) def kwargs_only(fn): """Wraps function so that callers must call it using keyword-arguments only. Args: fn: fn to wrap. Returns: Wrapped function that may only be called using keyword-arguments. """ if hasattr(inspect, 'getfullargspec'): # For Python 3 args = inspect.getfullargspec(fn) varargs = args.varargs keywords = args.varkw else: # For Python 2 args = inspect.getargspec(fn) # pylint: disable=deprecated-method varargs = args.varargs keywords = args.keywords if varargs is not None: raise TypeError('function to wrap should not have *args parameter') if keywords is not None: raise TypeError('function to wrap should not have **kwargs parameter') arg_list = args.args has_default = [False] * len(arg_list) default_values = [None] * len(arg_list) has_self = arg_list[0] == 'self' if args.defaults: has_default[-len(args.defaults):] = [True] * len(args.defaults) default_values[-len(args.defaults):] = args.defaults def wrapped_fn(*args, **kwargs): """Wrapped function.""" if args: if not has_self or (has_self and len(args) != 1): raise TypeError('function %s must be called using keyword-arguments ' 'only.' % fn.__name__) if has_self: if len(args) != 1: raise TypeError('function %s has self argument but not called with ' 'exactly 1 positional argument' % fn.__name__) kwargs['self'] = args[0] kwargs_to_pass = {} for arg_name, arg_has_default, arg_default_value in zip( arg_list, has_default, default_values): if not arg_has_default and arg_name not in kwargs: raise TypeError('function %s must be called with %s specified' % (fn.__name__, arg_name)) kwargs_to_pass[arg_name] = kwargs.pop(arg_name, arg_default_value) if kwargs: raise TypeError('function %s called with extraneous kwargs: %s' % (fn.__name__, kwargs.keys())) return fn(**kwargs_to_pass) return wrapped_fn def get_features_from_extracts( element: types.Extracts ) -> Union[types.DictOfTensorValue, types.DictOfFetchedTensorValues]: """Fetch features from the extracts.""" features = None if constants.FEATURES_PREDICTIONS_LABELS_KEY in element: fpl = element[constants.FEATURES_PREDICTIONS_LABELS_KEY] if not isinstance(fpl, types.FeaturesPredictionsLabels): raise TypeError( 'Expected FPL to be instance of FeaturesPredictionsLabel. FPL was: ' '%s of type %s' % (str(fpl), type(fpl))) features = fpl.features elif constants.FEATURES_KEY in element: features = element[constants.FEATURES_KEY] else: raise RuntimeError('Features missing, Please ensure Predict() was called.') return features def merge_extracts(extracts: List[types.Extracts]) -> types.Extracts: """Merges list of extracts into single extract with multi-dimentional data.""" def merge_with_lists(target, key, value): if isinstance(value, dict): if key not in target: target[key] = {} target = target[key] for k, v in value.items(): merge_with_lists(target, k, v) else: if key not in target: target[key] = [] if isinstance(value, np.ndarray): value = value.tolist() target[key].append(value) def to_numpy(target): if isinstance(target, dict): return {k: to_numpy(v) for k, v in target.items()} elif target and isinstance(target[0], tf.compat.v1.SparseTensorValue): t = tf.sparse.concat(0, target) return tf.compat.v1.SparseTensorValue( indices=t.indices.numpy(), values=t.values.numpy(), dense_shape=t.dense_shape.numpy()) else: arr = np.array(target) # Flatten values that were originally single item lists into a single list # e.g. [[1], [2], [3]] -> [1, 2, 3] if len(arr.shape) == 2 and arr.shape[1] == 1: return arr.squeeze(axis=1) # Special case for empty slice arrays # e.g. [[()], [()], [()]] -> [(), (), ()] elif len(arr.shape) == 3 and arr.shape[1] == 1 and arr.shape[2] == 0: return arr.squeeze(axis=1) else: return arr result = {} for x in extracts: for k, v in x.items(): merge_with_lists(result, k, v) return to_numpy(result) # TODO(b/162743769): Account for pointer fanout in byte size estimation. class SizeEstimator(object): """Size estimator.""" def __init__(self, size_threshold: int, size_fn: Callable[[Any], int]): self._size_threshold = size_threshold self._curr_size = 0 self._size_fn = size_fn def __iadd__(self, other: 'SizeEstimator') -> 'SizeEstimator': self._curr_size += other.get_estimate() return self def update(self, value: Any): self._curr_size += self._size_fn(value) def should_flush(self) -> bool: return self._curr_size >= self._size_threshold def clear(self): self._curr_size = 0 def get_estimate(self) -> int: return self._curr_size
{ "alphanum_fraction": 0.6789973018, "author": null, "avg_line_length": 33.6920821114, "converted": null, "ext": "py", "file": null, "hexsha": "4afa039b32d67b7d992edb9e2604a5df58af757e", "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": "e803ea6778d8550ec77dcc92bc8172f1a3a90f38", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Mikehem/tfx", "max_forks_repo_path": "tensorflow_model_analysis/util.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "e803ea6778d8550ec77dcc92bc8172f1a3a90f38", "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": "Mikehem/tfx", "max_issues_repo_path": "tensorflow_model_analysis/util.py", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "e803ea6778d8550ec77dcc92bc8172f1a3a90f38", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Mikehem/tfx", "max_stars_repo_path": "tensorflow_model_analysis/util.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2779, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 11489 }
export plot_atom export plot_atom! export plot_graphene @recipe function f(g::Vector{T}) where T<:AbstractGPrimitive get_x.(g), get_y.(g) end function plot_atom!(plt, g::Vector{T}; kw...) where T<:AbstractGPrimitive atoms = filter(isatom, g) bonds = filter(isbond, g) polygons = filter(ispolygon, g) scatter!(plt, get_x.(atoms), get_y.(atoms); kw...) end plot_atom!(plt, g::T; kw...) where T<:AbstractGPrimitive = plot_atom!(plt, [g], kw...) function plot_atom!(g::Vector{T}; kw...) where T<:AbstractGPrimitive atoms = filter(isatom, g) bonds = filter(isbond, g) polygons = filter(ispolygon, g) scatter!(get_x.(atoms), get_y.(atoms); kw...) end plot_atom!(g::T; kw...) where T<:AbstractGPrimitive = plot_atom!([g], kw...) function plot_atom(g::Vector{T}; kw...) where T<:AbstractGPrimitive atoms = filter(isatom, g) bonds = filter(isbond, g) polygons = filter(ispolygon, g) scatter(get_x.(atoms), get_y.(atoms); kw...) end plot_atom(g::T; kw...) where T<:AbstractGPrimitive = plot_atom([g], kw...) function plot_graphene(graphene, g::Vector{T}; kw...) where T<:AbstractGPrimitive plt = plot([], aspect_ratio = 1, xlims=(0,256), ylims=(0,256), framestyle=:box, legend=false) g_palette = [ colorant"#6E6E6E", # 1 colorant"#DF0101", # 2 colorant"#FBD606", # 3 colorant"#BF2626", # 4 colorant"#FEE081", # 5 colorant"#B3BED2", # 6 colorant"#353D52", # 7 colorant"#0D621E", # 8 colorant"#934BB2", # 9 colorant"#3EAE7E", # 10 colorant"#EFBAA0", # 11 colorant"#602E56", # 12 colorant"#3f9778", # 13 colorant"#FF8000", # 14 colorant"#5FB404", # 15 colorant"#182854", # 16 colorant"#ACAEB5", # 17 colorant"#5A7460", # 18 colorant"#B93F01", # 19 colorant"#1897AB", # 20 colorant"#FFFFFF"] # >20 gatoms = filter(isatom, g) # gbonds = filter(isbond, g) gpolygons = sort(filter(ispolygon, g), rev=true) for n in gpolygons points = [[get_x(p), get_y(p)] for p in filter_relatives_by_type(graphene, n, "Atom")] hull = convex_hull(points) noa = get_noa(n) plot!(plt, VPolygon(hull), alpha=1, color=g_palette[min(noa,21)]) end if !isempty(gatoms) plot_atom!(plt, gatoms, color=g_palette[1]) end return plt end plot_graphene(graphene, g::T; kw...) where T<:AbstractGEntry = plot_polygon(graphene, [g]; kw...) function plot_graphene(graphene, g_vector::Vector{GDefect}; kw...) temp = AbstractGPrimitive[] for g in g_vector temp = [graphene[collect(get_members(g))]; temp] end plot_graphene(graphene, temp; kw...) end
{ "alphanum_fraction": 0.6314403911, "author": null, "avg_line_length": 32.4268292683, "converted": null, "ext": "jl", "file": null, "hexsha": "c5babb36b74d4f358664cd42589a7a3f26e00ac1", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2020-02-08T10:46:06.000Z", "max_forks_repo_forks_event_min_datetime": "2020-02-08T10:46:06.000Z", "max_forks_repo_head_hexsha": "ca7213b75561a48054c9f70ffc330448f09c2f54", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "chenspc/Graphene.jl", "max_forks_repo_path": "src/plotting.jl", "max_issues_count": 2, "max_issues_repo_head_hexsha": "ca7213b75561a48054c9f70ffc330448f09c2f54", "max_issues_repo_issues_event_max_datetime": "2020-02-08T15:51:40.000Z", "max_issues_repo_issues_event_min_datetime": "2019-12-30T15:50:33.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "chenspc/Graphene.jl", "max_issues_repo_path": "src/plotting.jl", "max_line_length": 97, "max_stars_count": null, "max_stars_repo_head_hexsha": "ca7213b75561a48054c9f70ffc330448f09c2f54", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "chenspc/Graphene.jl", "max_stars_repo_path": "src/plotting.jl", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 872, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2659 }
import numpy as np from learning import IRL_helper # get the Reinforcement learner from playing import play # get the RL Test agent, gives out feature expectations after 2000 frames from nn import neural_net # construct the nn and send to playing BEHAVIOR = 'bumping' # yellow/brown/red/bumping FRAMES = 100000 # number of RL training frames per iteration of IRL class RelEntIRL: def __init__(self, expert_demos, nonoptimal_demos, num_frames, behavior): self.expert_demos = expert_demos self.policy_features = nonoptimal_demos self.num_features = len(self.expert_demos[0]) self.weights = np.zeros((self.num_features,)) self.num_frames = num_frames self.behavior = behavior def calculate_objective(self): '''For the partition function Z($\theta$), we just sum over all the exponents of their rewards, similar to the equation above equation (6) in the original paper.''' objective = np.dot(self.expert_feature, self.weights) for i in range(self.policy_features.shape[0]): objective -= np.exp(np.dot(self.policy_features[i], self.weights)) return objective def calculate_expert_feature(self): self.expert_feature = np.zeros_like(self.weights) for i in range(len(self.expert_demos)): self.expert_feature += self.expert_demos[i] self.expert_feature /= len(self.expert_demos) return self.expert_feature def train(self, step_size=1e-4, num_iters=50000, print_every=5000): self.calculate_expert_feature() importance_sampling = np.zeros((len(self.policy_features),)) for i in range(num_iters): update = np.zeros_like(self.weights) for j in range(len(self.policy_features)): importance_sampling[j] = np.exp(np.dot(self.policy_features[j], self.weights)) importance_sampling /= np.sum(importance_sampling, axis=0) weighted_sum = np.sum(np.multiply(np.array([importance_sampling, ] * self.policy_features.shape[1]).T, \ self.policy_features), axis=0) self.weights += step_size * (self.expert_feature - weighted_sum) # One weird trick to ensure that the weights don't blow up. self.weights = self.weights / np.linalg.norm(self.weights, keepdims=True) if i % print_every == 0: print("Value of objective is: " + str(self.calculate_objective())) def getRLAgentFE(self, W, i, count=1): # get the feature expectations of a new policy using RL agent nn_param = [164, 150] params = { "batchSize": 100, "buffer": 50000, "nn": nn_param, "observe": 1000 } IRL_helper(W, self.behavior, self.num_frames, i, nn_param, params) # train the agent and save the model in a file used below saved_model = 'saved-models_'+self.behavior+'/evaluatedPolicies/'+str(i)+'-164-150-'+str(params["batchSize"])+'-'+str(params["buffer"])+"-"+str(self.num_frames)+'.h5' # use the saved model to get the FE model = neural_net(self.num_features, [164, 150], saved_model) if count > 1: feat = np.zeros((count, self.num_features)) for a in range(count): feat[a, :] = play(model, W) return feat return play(model, W) # return feature expectations by executing the learned policy def get_trajectory_policy(behavior='red', count=5): nn_param = [164, 150] params = { "batchSize": 100, "buffer": 50000, "nn": nn_param } n_feat = 8 n_frames = 100000 if behavior == 'red': i = 3 elif behavior == 'brown': i = 5 elif behavior == 'yellow': i = 100 saved_model = 'saved-models_' + behavior + '/evaluatedPolicies/' + str(i) + '-164-150-' + str( params["batchSize"]) + '-' + str(params["buffer"]) + "-" + str(n_frames) + '.h5' # use the saved model to get the FE model = neural_net(n_feat, [164, 150], saved_model) if behavior == 'red': W = [0.2816, -0.5547, -0.2297, 0.6824, -0.3025, 0.0004, 0.0525, -0.0075] elif behavior == 'brown': W = [-0.2627, 0.0363, 0.0931, 0.0046, -0.1829, 0.6987, -0.5922, -0.2201] elif behavior == 'yellow': W = [-0.0880, -0.0624, 0.0914, -0.0114, 0.6690, -0.0771, -0.6650, -0.2897] feat = np.zeros((count, n_feat)) for a in range(count): feat[a, :] = play(model, W) return feat def generate_non_optimal_trajectories(behavior='red', count=5): try: with open(behavior + '_init_policy.pkl', 'rb') as f: total = pickle.load(f) except FileNotFoundError: Red = get_trajectory_policy('red', count) Brown = get_trajectory_policy('brown', count) Yellow = get_trajectory_policy('yellow', count) with open("random_feat.pkl", "rb") as f: randomPolicyFE = pickle.load(f) randomPolicyFE = randomPolicyFE[0: count, :] if behavior == 'red': total = np.vstack((Brown, Yellow, randomPolicyFE)) elif behavior == 'yellow': total = np.vstack((Brown, Red, randomPolicyFE)) elif behavior == 'brown': total = np.vstack((Yellow, Red, randomPolicyFE)) with open(behavior + '_init_policy.pkl', 'wb') as f: pickle.dump(total, f) return total import pickle import time if __name__ == "__main__": expertPolicyYellowFE = [[7.5366e+00, 4.6350e+00, 7.4421e+00, 3.1817e-01, 8.3398e+00, 1.3710e-08, 1.3419e+00, 0.0000e+00]] # ^feature expectations for the "follow Yellow obstacles" behavior expertPolicyRedFE = [[7.9100e+00, 5.3745e-01, 5.2363e+00, 2.8652e+00, 3.3120e+00, 3.6478e-06, 3.82276074e+00, 1.0219e-17]] # ^feature expectations for the follow Red obstacles behavior expertPolicyBrownFE = [[5.2210e+00, 5.6980e+00, 7.7984e+00, 4.8440e-01, 2.0885e-04, 9.2215e+00, 2.9386e-01, 4.8498e-17]] # ^feature expectations for the "follow Brown obstacles" behavior expertPolicyBumpingFE = [[7.5313e+00, 8.2716e+00, 8.0021e+00, 2.5849e-03, 2.4300e+01, 9.5962e+01, 1.5814e+01, 1.5538e+03]] # ^feature expectations for the "nasty bumping" behavior randomPolicyFE = generate_non_optimal_trajectories(BEHAVIOR, count=1) if BEHAVIOR == 'red': expert_policy = expertPolicyRedFE elif BEHAVIOR == 'yellow': expert_policy = expertPolicyYellowFE elif BEHAVIOR == 'bumping': expert_policy = expertPolicyBumpingFE elif BEHAVIOR == 'brown': expert_policy = expertPolicyBrownFE rl_iter = 1 start = time.time() for i in range(0, rl_iter): relent = RelEntIRL(expert_policy, randomPolicyFE, FRAMES, BEHAVIOR) relent.train() print("weights: ", relent.weights) #learner_feature = relent.getRLAgentFE(relent.weights, 10000, count=2) # randomPolicyFE = learner_feature # randomPolicyFE = np.vstack((randomPolicyFE, learner_feature)) # print("Learner feature at iteration ", i, ": ", learner_feature) # end = time.time() # print("Time: ", (end - start) // 60, " min ", (end - start) % 60, " second") with open("saved_weights_" + BEHAVIOR + "/iter_" + str(i) + "_weights.pkl", "wb") as f: pickle.dump(relent.weights, f)
{ "alphanum_fraction": 0.6178115016, "author": null, "avg_line_length": 42.9257142857, "converted": null, "ext": "py", "file": null, "hexsha": "d9b4dbfc3a7d9cce0bebf747f1f15c915ce3368d", "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": "f84781bb19c2371783e306e9b17b7f3cc2267c3c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "mturja-vf-ic-bd/self-driving-car_Robotics-Project", "max_forks_repo_path": "maxEntIRL.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "f84781bb19c2371783e306e9b17b7f3cc2267c3c", "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": "mturja-vf-ic-bd/self-driving-car_Robotics-Project", "max_issues_repo_path": "maxEntIRL.py", "max_line_length": 211, "max_stars_count": null, "max_stars_repo_head_hexsha": "f84781bb19c2371783e306e9b17b7f3cc2267c3c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "mturja-vf-ic-bd/self-driving-car_Robotics-Project", "max_stars_repo_path": "maxEntIRL.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2092, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 7512 }
"""In this instantiation of the online AdWords problem, the #variables becomes n*m*(#slots)* """ import random import numpy as np import pulp as pl import configs from src.data_utils import create_data_vars from src.pulp_utils import optimize_lp # SLOTS = 3 # GAMMA = 0.99 np.random.seed(256) def calc_slot_discount(slot_num): return GAMMA ** slot_num def min_lp_solver(c, A_ub, b_ub, bounds): """ Args: b_ub: A_ub: c: Co-efficients for each variable. bounds: (min, max) bounds of each of the x_i. Set default to (0, 1.0) Returns: """ solver = pl.getSolver(configs.SOLVER_TYPE) obj_value, values = optimize_lp(c, A_ub, b_ub, objective=pl.LpMinimize, solver=solver, bounds=bounds) return obj_value, values def get_adword_dual(c, A, b): """ Args: c: A: b: Returns: c_new: (m+n, 1) A_new: (n*m, m+n) b_new: (n*m, 1) """ c_new = b # (m+n, 1) A_new = -A.T b_new = -c return c_new, A_new, b_new def fill_A(n, m, W, kw_nums): """ Args: n: #advertisers m: #keywords kw_nums: number of the keyword coming to the queries. """ A = np.zeros([m + n + m*n, m * n * SLOTS]) # First m rows for the ∑_i ∑_s x_ijs <= 1 constraints for i in range(m): start = i * SLOTS while start + SLOTS < len(A[i]): A[i, start:start + SLOTS] = 1 start += m * SLOTS # Next n rows will have ∑_j ∑_s w_ijs x_ijs d_ijs <= B_i for i in range(n): for j in range(m): kw_num = kw_nums[j] for s in range(SLOTS): A[m + i, i * m * SLOTS + j * SLOTS + s] = calc_slot_discount(s) * W[i][kw_num] # Don't allow for single advertiser purchasing multiple slots. for i in range(n): for j in range(m): for slot in range(SLOTS): # constr = np.zeros((1, n*m*SLOTS)) # constr[0, i*m*SLOTS: i*m*SLOTS + SLOTS] = 1 # A = np.concatenate([A, constr], axis=0) A[m + n + i*m + j, i*m*SLOTS + j*SLOTS + slot] = 1 # A has a total of m + n + mn rows and m*n*SLOTScolumns. return A def fill_b(n, m, B): print(f'B: {B}') b = np.zeros((m + n, 1)) b[:m] = 1 for i in range(n): b[m + i] = B[i] # For making sure that the same advertiser won't bid on the same query more than once. b[m+n:] = 1 return b def min_max_norm(arr): min_ = arr[0] max_ = arr[0] for i in range(len(arr)): if min_ > arr[i]: min_ = arr[i] if max_ < arr[i]: max_ = arr[i] new_arr = [(arr[i] - min_) / (max_ - min_ + 1e-9) for i in range(len(arr))] return new_arr def online_greedy_step(B, M, W, n, kw_num): """ Args: B: M: W: n: kw_num: keyword number. Returns: optimal_ad_num: which advertiser is mapped. optimal_bid: bid value of the matched advertiser """ optimal_ad_num = [-1] * SLOTS optimal_bid = [0] * SLOTS for slot in range(SLOTS): # slot_discount = 1 - slot*DISCOUNT_FACTOR slot_discount = calc_slot_discount(slot) for i in range(n): # 0 means no bid. if W[i][kw_num]==0: continue if slot_discount * W[i][kw_num] <= (B[i] - M[i]): if optimal_bid[slot] <= slot_discount * W[i][kw_num]: # Making sure an Ad doesn't come twice in a query. if i in optimal_ad_num: continue optimal_bid[slot] = slot_discount * W[i][kw_num] optimal_ad_num[slot] = i return optimal_ad_num, optimal_bid def online_greedy(B, W, n, r, m, kw_nums): """ Args: B: (n), budgets W: (n*r) i-th advertiser's bid for j-th keyword n: # advertisers r: # keywords kw_nums: (m) number of the keyword in each of the queries Returns: Q: (m) query assignment revenue: Revenue accrued """ M = [0] * n revenue = 0 Q = [[-1] * SLOTS] * m freqs = [0] * r for t in range(len(kw_nums)): kw_num = kw_nums[t] # Maintaining the keyword frequency. freqs[kw_num] += 1 ad_nums, bids = online_greedy_step(B, M, W, n, kw_num) for slot, (slot_ad_num, slot_bid) in enumerate(zip(ad_nums, bids)): if slot_ad_num == -1: continue M[slot_ad_num] += slot_bid revenue += slot_bid Q[t][slot] = slot_ad_num return M, Q, revenue, freqs def online_weighted_greedy_step_with_dynamic_slots(B, M, W, alphas, n, kw_num, kw_slots): # TODO(rajiv): Check the validity again. slots = kw_slots[kw_num] optimal_ad_nums = [-1] * slots optimal_bids = [0] * slots disc_bids = [-1] * slots for slot in range(slots): # slot_discount = max(0.1, (1 - DISCOUNT_FACTOR*slot)) slot_discount = calc_slot_discount(slot) for i in range(n): # 0 means no bid. if W[i][kw_num]==0: continue disc = (1 - alphas[i]) slot_discounted_bid = slot_discount * W[i][kw_num] if slot_discounted_bid <= (B[i] - M[i]): if disc_bids[slot] < disc * W[i][kw_num]: # Making sure an Ad won't be placed twice in a query. if i in optimal_ad_nums: continue disc_bids[slot] = disc * W[i][kw_num] optimal_bids[slot] = slot_discounted_bid optimal_ad_nums[slot] = i return optimal_ad_nums, optimal_bids def online_weighted_greedy_step(B, M, W, alphas, n, kw_num): optimal_ad_nums = [-1] * SLOTS optimal_bids = [0] * SLOTS disc_bids = [-1] * SLOTS for slot in range(SLOTS): slot_discount = calc_slot_discount(slot) for i in range(n): # 0 means no bid. if W[i][kw_num] == 0: continue disc = (1 - alphas[i]) slot_discounted_bid = slot_discount * W[i][kw_num] if slot_discounted_bid <= (B[i] - M[i]): if disc_bids[slot] < disc * W[i][kw_num]: if i in optimal_ad_nums: continue disc_bids[slot] = disc * W[i][kw_num] optimal_bids[slot] = slot_discounted_bid optimal_ad_nums[slot] = i return optimal_ad_nums, optimal_bids def expand_W_with_slots(W, kw_nums): """First executes np.take to get the n*r to n*m. Then expands the final dim to accommodate for the slot values. Args: W: kw_nums: Returns: """ W_new = np.take(W, indices=kw_nums, axis=1) W_slots = np.expand_dims(W_new, axis=2) # n*m*1 W_slots = np.repeat(W_slots, repeats=SLOTS, axis=2) # n*m*SLOTS # discounting = [(1 - s * DISCOUNT_FACTOR) for s in range(SLOTS)] discounting = [calc_slot_discount(s) for s in range(SLOTS)] W_slots = W_slots * discounting return W_slots def redistribute_slots(kw_probs, total_slots): softmax_probs = np.exp(kw_probs) / np.sum(np.exp(kw_probs)) softmax_probs = softmax_probs.tolist() slots = [int(total_slots * prob) for prob in softmax_probs] rem_slots = total_slots - sum(slots) for i in range(rem_slots): slots[i] += 1 return slots def online_dual_lp(B, W, n, r, m, kw_nums, kw_probs, eps): """ Args: B: W: n: r: m: kw_nums: eps: Returns: """ eps_m = int(eps * m) # Incorporating click probabilities. for i in range(len(W)): for j in range(len(W[0])): W[i][j] *= kw_probs[i] M, Q, revenue, freqs = online_greedy(B, W, n, r, eps_m, kw_nums[:eps_m]) c = np.array(expand_W_with_slots(W, kw_nums))[:, :eps_m, :].flatten() A = fill_A(n, eps_m, W, kw_nums[:eps_m]) b = fill_b(n, eps_m, B) c_du, A_du, b_du = get_adword_dual(c, A, b) c_du = np.concatenate([c_du[:eps_m], eps * c_du[eps_m:]], axis=0) bounds = [(0, 1e9)] * eps_m + [(0, 1)] * n obj_value, values = min_lp_solver(c_du, A_du, b_du, bounds) alphas = values[eps_m:] slots = redistribute_slots(kw_probs, SLOTS * m) print(f'sum slots: {sum(slots)}') for t in range(eps_m, m): Q.append([]) ad_nums, bids = online_weighted_greedy_step_with_dynamic_slots(B, M, W, alphas, n, kw_nums[t], slots) # ad_nums, bids = online_weighted_greedy_step(B, M, W, alphas, n, kw_nums[t]) for slot, (ad_num, bid) in enumerate(zip(ad_nums, bids)): if ad_num == -1: Q[t].append(ad_num) continue M[ad_num] += bid revenue += bid Q[t].append(ad_num) print(f't: {t} | revenue: {revenue}') msum = sum(M) return Q, msum # revenue also gives the same answer def get_results(data_alias='ds0'): """ This function makes it easy to get numbers of slides. This is a common function in all problem files. Args: data_alias: Returns: results: A dictionary with keys as query assignments `Q` and revenue `revenue`. """ data = create_data_vars(data_alias) n = data['n'] m = data['m'] W = data['W'] B = data['B'] kw_nums = data['kw_nums'] r = data['r'] for i in range(n): B[i] *= 5 kw_probs = [random.random() for i in range(r)] Q, revenue = online_dual_lp(B, W, n, r, m, kw_nums, kw_probs, eps=0.1) results = { 'Q': Q, 'revenue': revenue } return results if __name__=="__main__": slots = [2, 3, 4, 5] gammas = [0.99, 0.95, 0.9, 0.85, 0.8, 0.7] ''' for slots_i in slots: for gamma in gammas: SLOTS = slots_i GAMMA = gamma revenue = get_results('ds3')['revenue'] results.append((slots_i, gamma, revenue)) s = '' for item in results: gamma = item[1] s += str(item[2]) + ',' if gamma == 0.7: print(s) s = '' ''' ''' results = [] slots = [5] gammas = [0.7] for slot in slots: for gamma in gammas: avg = [] for t in range(10): SLOTS = slot GAMMA = gamma revenue = get_results('ds3')['revenue'] avg.append(revenue) revenue = sum(avg)/len(avg) results.append(revenue) for res in results: print(res) # for j in range(len(gammas)): # s += str(item[2]) + ',' # print(s) ''' slots = [3, 5] gammas = [0.9] results = [] for slot in slots: for gamma in gammas: SLOTS = slot GAMMA = gamma revenue = get_results('ds3')['revenue'] results.append(revenue)
{ "alphanum_fraction": 0.5365102374, "author": null, "avg_line_length": 27.664160401, "converted": null, "ext": "py", "file": null, "hexsha": "b048421f966b39da33771d135e80a49b90e9691a", "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": "4fa4628da06e3558b9f8c2917c0e87d9c5287690", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "rajiv256/cs531_proj_2", "max_forks_repo_path": "src/extensions/online_ad_platforms.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "4fa4628da06e3558b9f8c2917c0e87d9c5287690", "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": "rajiv256/cs531_proj_2", "max_issues_repo_path": "src/extensions/online_ad_platforms.py", "max_line_length": 109, "max_stars_count": null, "max_stars_repo_head_hexsha": "4fa4628da06e3558b9f8c2917c0e87d9c5287690", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "rajiv256/cs531_proj_2", "max_stars_repo_path": "src/extensions/online_ad_platforms.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3171, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 11038 }
#MIT License # This software has been heavily inspired from: JetsonHacks YouTube videos, examples and GitHub Code # Please refer to : https://github.com/jetsonhacks/gpuGraphTX # Modifications to include instant bar graphs and also CPU average usage history # by: Walther Carballo Hernandez # Please refer to: https://github.com/walcarher # Modifications Copyright (c) 2019-2021 Institut Pascal #Copyright (c) 2018 Jetsonhacks #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons to whom the Software is #furnished to do so, subject to the following conditions: #The above copyright notice and this permission notice shall be included in all #copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from collections import deque # This files are to be found in the L4T version of TX2 and on C10GX CHIMERA board, this may vary in the future cpuLoadFile = '/sys/devices/3160000.i2c/i2c-0/0-0041/iio_device/in_power1_input' # CPU power channel gpuLoadFile = '/sys/devices/3160000.i2c/i2c-0/0-0040/iio_device/in_power0_input' # GPU power channel fpgaLoadFile = '/sys/devices/3160000.i2c/i2c-0/0-0042/iio_device/in_power0_input' # FPGA core power channel fig = plt.figure(figsize=(7,3)) plt.subplots_adjust(top=0.85, bottom=0.30) fig.set_facecolor('#F2F1F0') fig.canvas.set_window_title('CPU-FPGA-GPU Power Monitor') # Subplot for the CPU-FPGA-GPU activity ax = plt.subplot2grid((1,1), (0,0), rowspan=2, colspan=1) # For the comparison cpuLine, = ax.plot([],[]) gpuLine, = ax.plot([],[]) fpgaLine, = ax.plot([],[]) # The line points in x,y list form cpuy_list = deque([0]*240) cpux_list = deque(np.linspace(60,0,num=240)) gpuy_list = deque([0]*240) gpux_list = deque(np.linspace(60,0,num=240)) fpgay_list = deque([0]*240) fpgax_list = deque(np.linspace(60,0,num=240)) cpu_fill_lines=0 gpu_fill_lines=0 fpga_fill_lines=0 def initGraph(): global ax global cpuLine global gpuLine global fpgaLine global cpu_fill_lines global gpu_fill_lines global fpga_fill_lines ax.set_xlim(60, 0) ax.set_ylim(-10, 10000) ax.set_title('CPU-FPGA-GPU Power Plot') ax.set_ylabel('Power (mW)') ax.set_xlabel('Samples'); ax.grid(color='gray', linestyle='dotted', linewidth=1) cpuLine.set_data([],[]) cpuLine.set_color('gray') cpuLine.set_label('CPU') cpu_fill_lines=ax.fill_between(cpuLine.get_xdata(),50,0) gpuLine.set_data([],[]) gpuLine.set_color('green') gpuLine.set_label('GPU') gpu_fill_lines=ax.fill_between(gpuLine.get_xdata(),50,0) fpgaLine.set_data([],[]) fpgaLine.set_color('blue') fpgaLine.set_label('FPGA') fpga_fill_lines=ax.fill_between(fpgaLine.get_xdata(),50,0) ax.legend(loc='upper left') return [cpuLine] + [cpu_fill_lines] + [fpgaLine] + [fpga_fill_lines] + [gpuLine] + [gpu_fill_lines] def updateGraph(frame): global cpu_fill_lines global cpuy_list global cpux_list global cpuLine global gpu_fill_lines global gpuy_list global gpux_list global gpuLine global fpga_fill_lines global fpgay_list global fpgax_list global fpgaLine global ax # Draw average CPU power consumption cpuy_list.popleft() try: with open(cpuLoadFile, 'r') as cpuFile: fileData = cpuFile.read() except IOError: fileData = '0' # The CPU power is in mW cpuy_list.append(int(fileData)) cpuLine.set_data(cpux_list,cpuy_list) cpu_fill_lines.remove() cpu_fill_lines=ax.fill_between(cpux_list,0,cpuy_list, facecolor='gray', alpha=0.25) # Draw average GPU power consumption gpuy_list.popleft() try: with open(gpuLoadFile, 'r') as gpuFile: fileData = gpuFile.read() except IOError: fileData = '0' # The GPU power is in mW gpuy_list.append(int(fileData)) gpuLine.set_data(gpux_list,gpuy_list) gpu_fill_lines.remove() gpu_fill_lines=ax.fill_between(gpux_list,0,gpuy_list, facecolor='green', alpha=0.25) # Draw average FPGA power consumption fpgay_list.popleft() try: with open(fpgaLoadFile, 'r') as fpgaFile: fileData = fpgaFile.read() except IOError: fileData = '0' # The FPGA power is in mW fpgay_list.append(int(fileData)) fpgaLine.set_data(fpgax_list,fpgay_list) fpga_fill_lines.remove() fpga_fill_lines=ax.fill_between(fpgax_list,0,fpgay_list, facecolor='blue', alpha=0.25) return [cpuLine] + [cpu_fill_lines] + [fpgaLine] + [fpga_fill_lines] + [gpuLine] + [gpu_fill_lines] # Keep a reference to the FuncAnimation, so it does not get garbage collected animation = FuncAnimation(fig, updateGraph, frames=200, init_func=initGraph, interval=100, blit=True) plt.show()
{ "alphanum_fraction": 0.7256097561, "author": null, "avg_line_length": 35.2911392405, "converted": null, "ext": "py", "file": null, "hexsha": "025c8982d9f018b5cc6261e612e9304b7a671ca7", "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": "8b78ebce08f589fff1a695693c4ebd86e9bdc730", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "walcarher/Demo1Achieve", "max_forks_repo_path": "CPU-FPGA-GPU_PowerMonitor.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "8b78ebce08f589fff1a695693c4ebd86e9bdc730", "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": "walcarher/Demo1Achieve", "max_issues_repo_path": "CPU-FPGA-GPU_PowerMonitor.py", "max_line_length": 110, "max_stars_count": 1, "max_stars_repo_head_hexsha": "62c206e1ccf05f83e20bb1ed3a6518460de5eb9a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "walcarher/Demo2Achieve", "max_stars_repo_path": "CPU-FPGA-GPU_PowerMonitor.py", "max_stars_repo_stars_event_max_datetime": "2019-09-25T14:25:13.000Z", "max_stars_repo_stars_event_min_datetime": "2019-09-25T14:25:13.000Z", "num_tokens": 1532, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 5576 }
using UnPack using ..Fields: sweep using ..Fields: pre_post_colons ##### ##### fft! ##### dct3D!(f, dir::Int) = dct3D!(f, Val(dir), Radix2Type()) function dct3D!(f, ::Val{dim}, fft_type::FFTType=Radix2Type()) where {dim} @unpack Ipre, Ipost = pre_post_colons(f, dim) for i in 1:size(f, dim) fv = @view f[Ipre..., i, Ipost...] dct2!(fv, fft_type) end end idct3D!(f, dir::Int) = idct3D!(f, Val(dir), Radix2Type()) function idct3D!(f, ::Val{dim}, fft_type::FFTType=Radix2Type()) where {dim} @unpack Ipre, Ipost = pre_post_colons(f, dim) for i in 1:size(f, dim) fv = @view f[Ipre..., i, Ipost...] idct2!(fv, fft_type) end end
{ "alphanum_fraction": 0.5867052023, "author": null, "avg_line_length": 22.3225806452, "converted": null, "ext": "jl", "file": null, "hexsha": "e41dc4db4228d35e2af0cb4675ba906747ecf2e8", "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": "a88311ce88b665289e9780a65dceef76529f2d94", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "charleskawczynski/MOONS.jl", "max_forks_repo_path": "src/FFTs/wrappers3D.jl", "max_issues_count": 18, "max_issues_repo_head_hexsha": "a88311ce88b665289e9780a65dceef76529f2d94", "max_issues_repo_issues_event_max_datetime": "2021-04-28T15:26:15.000Z", "max_issues_repo_issues_event_min_datetime": "2020-12-30T19:19:19.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "charleskawczynski/MOONS.jl", "max_issues_repo_path": "src/FFTs/wrappers3D.jl", "max_line_length": 75, "max_stars_count": 1, "max_stars_repo_head_hexsha": "a88311ce88b665289e9780a65dceef76529f2d94", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "charleskawczynski/MOONS.jl", "max_stars_repo_path": "src/FFTs/wrappers3D.jl", "max_stars_repo_stars_event_max_datetime": "2021-05-26T22:31:50.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-26T22:31:50.000Z", "num_tokens": 250, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 692 }
''' ***************************************************************************************** * * =============================================== * Nirikshak Bot (NB) Theme (eYRC 2020-21) * =============================================== * * This script is to implement Task 5 of Nirikshak Bot (NB) Theme (eYRC 2020-21). * * This software is made available on an "AS IS WHERE IS BASIS". * Licensee/end user indemnifies and will keep e-Yantra indemnified from * any and all claim(s) that emanate from the use of the Software or * breach of the terms of this agreement. * * e-Yantra - An MHRD (now MOE) project under National Mission on Education using ICT (NMEICT) * ***************************************************************************************** ''' # Team ID: [ Team-ID ] # Author List: [ Names of team members worked on this file separated by Comma: Name1, Name2, ... ] # Filename: task_5.py # Functions: # [ Comma separated list of functions in this file ] # Global variables: # [ List of global variables defined in this file ] # NOTE: Make sure you do NOT call sys.exit() in this code. ####################### IMPORT MODULES ####################### ## You are not allowed to make any changes in this section. ## ############################################################## import numpy as np import cv2 import os, sys import traceback import time import math import json ############################################################## start_coord_4 = (0, 5) start_coord_1, end_coord_1, end_coord_4, start_coord_2, end_coord_2, start_coord_3, end_coord_3 = (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 0) next_table = [False, False, False] gate = True client_id = 0 # Importing the sim module for Remote API connection with CoppeliaSim try: import sim except Exception: print('\n[ERROR] It seems the sim.py OR simConst.py files are not found!') print('\n[WARNING] Make sure to have following files in the directory:') print( 'sim.py, simConst.py and appropriate library - remoteApi.dll (if on Windows), remoteApi.so (if on Linux) or remoteApi.dylib (if on Mac).\n') # Import 'task_1b.py' file as module try: import task_1b except ImportError: print('\n[ERROR] task_1b.py file is not present in the current directory.') print('Your current directory is: ', os.getcwd()) print('Make sure task_1b.py is present in this current directory.\n') except Exception as e: print('Your task_1b.py throwed an Exception. Kindly debug your code!\n') traceback.print_exc(file=sys.stdout) # Import 'task_1a_part1.py' file as module try: import task_1a_part1 except ImportError: print('\n[ERROR] task_1a_part1.py file is not present in the current directory.') print('Your current directory is: ', os.getcwd()) print('Make sure task_1a_part1.py is present in this current directory.\n') except Exception as e: print('Your task_1a_part1.py throwed an Exception. Kindly debug your code!\n') traceback.print_exc(file=sys.stdout) # Import 'task_2a.py' file as module try: import task_2a except ImportError: print('\n[ERROR] task_2a.py file is not present in the current directory.') print('Your current directory is: ', os.getcwd()) print('Make sure task_2a.py is present in this current directory.\n') except Exception as e: print('Your task_2a.py throwed an Exception. Kindly debug your code!\n') traceback.print_exc(file=sys.stdout) # Import 'task_2b.py' file as module try: import task_2b except ImportError: print('\n[ERROR] task_2b.py file is not present in the current directory.') print('Your current directory is: ', os.getcwd()) print('Make sure task_2b.py is present in this current directory.\n') except Exception as e: print('Your task_2b.py throwed an Exception. Kindly debug your code!\n') traceback.print_exc(file=sys.stdout) # Import 'task_3.py' file as module try: import task_3 except ImportError: print('\n[ERROR] task_3.py file is not present in the current directory.') print('Your current directory is: ', os.getcwd()) print('Make sure task_3.py is present in this current directory.\n') except Exception as e: print('Your task_3.py throwed an Exception. Kindly debug your code!\n') traceback.print_exc(file=sys.stdout) # Import 'task_4a.py' file as module try: import task_4a except ImportError: print('\n[ERROR] task_4a.py file is not present in the current directory.') print('Your current directory is: ', os.getcwd()) print('Make sure task_4a.py is present in this current directory.\n') except Exception as e: print('Your task_4a.py throwed an Exception. Kindly debug your code!\n') traceback.print_exc(file=sys.stdout) ############################################################## # NOTE: YOU ARE NOT ALLOWED TO MAKE ANY CHANGE TO THIS FUNCTION # # Function Name: send_color_and_collection_box_identified # Inputs: ball_color and collection_box_name # Outputs: None # Purpose: 1. This function should only be called when the task is being evaluated using # test executable. # 2. The format to send the data is as follows: # 'color::collection_box_name' def send_color_and_collection_box_identified(ball_color, collection_box_name): global client_id color_and_cb = [ball_color + '::' + collection_box_name] inputBuffer = bytearray() return_code, retInts, retFloats, retStrings, retBuffer = sim.simxCallScriptFunction(client_id, 'evaluation_screen_respondable_1', sim.sim_scripttype_childscript, 'color_and_cb_identification', [], [], color_and_cb, inputBuffer, sim.simx_opmode_blocking) def invert_model_properties(object_handle): global client_id return_code, curr_model_prop = sim.simxGetModelProperty(client_id, object_handle, sim.simx_opmode_blocking) if curr_model_prop == 0: # Overrides the required model props as NOT measureable, NOT dynamic, NOT collidable, NOT # renderable, NOT detectable, NOT respondable and invisible to other model's bounding boxes. return_code = sim.simxSetModelProperty(client_id, object_handle, 1135, sim.simx_opmode_blocking) else: return_code = sim.simxSetModelProperty(client_id, object_handle, 0, sim.simx_opmode_blocking) ################# ADD UTILITY FUNCTIONS HERE ################# ## You can define any utility functions for your code. ## ## Please add proper comments to ensure that your code is ## ## readable and easy to understand. ## ############################################################## def get_start_end_coord(data, cl): global start_coord_1, end_coord_1, end_coord_4, \ start_coord_2, end_coord_2, start_coord_3, end_coord_3, \ next_table next_table[0] = next_table[1] = next_table[2] = False tmp = data[cl][0] del data[cl][0] if tmp == "T1_CB1": end_coord_4 = (5, 9) start_coord_1 = (5, 0) end_coord_1 = (0, 4) next_table[0] = True elif tmp == "T1_CB2": end_coord_4 = (5, 9) start_coord_1 = (5, 0) end_coord_1 = (4, 9) next_table[0] = True elif tmp == "T1_CB3": end_coord_4 = (5, 9) start_coord_1 = (5, 0) end_coord_1 = (9, 5) next_table[0] = True elif tmp == "T2_CB1": end_coord_4 = (9, 4) start_coord_2 = (0, 4) end_coord_2 = (4, 9) next_table[1] = True elif tmp == "T2_CB2": end_coord_4 = (9, 4) start_coord_2 = (0, 4) end_coord_2 = (9, 5) next_table[1] = True elif tmp == "T2_CB3": end_coord_4 = (9, 4) start_coord_2 = (0, 4) end_coord_2 = (5, 0) next_table[1] = True elif tmp == "T3_CB1": end_coord_4 = (4, 0) start_coord_3 = (4, 9) end_coord_3 = (9, 5) next_table[2] = True elif tmp == "T3_CB2": end_coord_4 = (4, 0) start_coord_3 = (4, 9) end_coord_3 = (5, 0) next_table[2] = True elif tmp == "T3_CB3": end_coord_4 = (4, 0) start_coord_3 = (4, 9) end_coord_3 = (0, 4) next_table[2] = True def draw_setpoint(client_id, coords, table): coppelia_coord = [] for element in coords: coppelia_coord.append(((10 * element) - 45) / 100) inputBuffer = bytearray() return_code, retInts, retFloats, retStrings, retBuffer = sim.simxCallScriptFunction(client_id, "top_plate_respondable_t" + str( table) + "_1", sim.sim_scripttype_customizationscript, "drawSetpoint", [], coppelia_coord, [], inputBuffer, sim.simx_opmode_blocking) def send_data_to_draw_path(client_id, path, n): coppelia_sim_coord_path = [] for coord in path: for element in coord: coppelia_sim_coord_path.append(((10 * element) - 45) / 100) inputBuffer = bytearray() return_code, retInts, retFloats, retStrings, retBuffer = sim.simxCallScriptFunction(client_id, "top_plate_respondable_t" + str( n) + "_1", sim.sim_scripttype_customizationscript, 'drawPath', [], coppelia_sim_coord_path, [], inputBuffer, sim.simx_opmode_blocking) def convert_path_to_pixels(path): pixel_path = [] for coord in path: pixel_path.append((coord[0] * 128 + 64, coord[1] * 128 + 64)) return pixel_path def convert_pixel_to_path(coord): coord = [(coord[0] - 64) / 128, (coord[1] - 64) / 128] return coord def traverse_path(pixel_path, table): global gate, client_id turns = [] prev_turn = pixel_path[0] n = len(pixel_path) signx, signy = 1, 1 res = 1280 tmp = 20 for i in range(0, len(pixel_path) - 1): signxt, signyt = 0, 0 signx1 = -1 * np.sign(pixel_path[i][0] - pixel_path[i - 1][0]) signy1 = -1 * np.sign(pixel_path[i][1] - pixel_path[i - 1][1]) signx2 = -1 * np.sign(pixel_path[i + 1][0] - pixel_path[i][0]) signy2 = -1 * np.sign(pixel_path[i + 1][1] - pixel_path[i][1]) if signx1 == 0 and signy2 == 0: if pixel_path[i + 1][0] > pixel_path[i][0]: signyt = -1 elif pixel_path[i + 1][0] < pixel_path[i][0]: signyt = 1 print("y turn:", signyt) if signy1 == 0 and signx2 == 0: if pixel_path[i + 1][1] > pixel_path[i][1]: signxt = -1 elif pixel_path[i + 1][1] < pixel_path[i][1]: signxt = 1 print("x turn:", signxt) if (pixel_path[i][0] == pixel_path[i - 1][0] and pixel_path[i][1] == pixel_path[i + 1][1]) or \ (pixel_path[i][1] == pixel_path[i - 1][1] and pixel_path[i][0] == pixel_path[i + 1][0]): turns.append([pixel_path[i][1] + signy1 * 40 + signxt * tmp, pixel_path[i][0] + signx1 * 40 + signyt * tmp]) prev_turn = pixel_path[i] elif abs(prev_turn[0] - pixel_path[i][0]) > 100 or abs(prev_turn[1] - pixel_path[i][1]) > 100: turns.append([pixel_path[i][1] + signy1 * 0, pixel_path[i][0] + signx1 * 0]) prev_turn = pixel_path[i] for i in range(0, len(turns)): if turns[i][0] < 70: turns[i][0] = turns[i][0] + 25 if turns[i][0] > 1200: turns[i][0] = turns[i][0] - 30 if turns[i][1] < 70: turns[i][1] = turns[i][1] + 25 if turns[i][1] > 1200: turns[i][1] = turns[i][1] - 30 turns.append([pixel_path[n - 1][1] - signy * 0, pixel_path[n - 1][0] - signx * 0]) gate = True t1, t2 = 0, 0 task_3.zero(client_id, table, 0, 0) print("\nTurns array generated!", turns) cnt = 0 for i in range(0, len(turns)): task_3.change_setpoint(turns[i]) cnt = 0 gate = True draw_setpoint(client_id, convert_pixel_to_path(turns[i]), table) flag = 0 while True: vision_sensor_image, image_resolution, return_code = task_2b.get_vision_sensor_image(client_id, task_3.getVisionSensorHandle(table)) transformed_image = task_2b.transform_vision_sensor_image(vision_sensor_image, image_resolution) warped_img = task_1b.applyPerspectiveTransform_vs(transformed_image) if warped_img is None: continue shapes = task_1a_part1.scan_image(warped_img, True) print(shapes) print("Current setpoint: ", turns[i]) print("\n") if len(shapes) == 0: continue center_x = shapes['Circle'][1] center_y = shapes['Circle'][2] return_code_signal, t1_string = sim.simxGetStringSignal(client_id, 'time', sim.simx_opmode_streaming) if return_code_signal == 0: t1 = float(t1_string) if turns[i][0] + 30 > center_x > turns[i][0] - 30 and turns[i][ 1] + 30 > center_y > turns[i][1] - 30: while turns[i][0] + 30 > center_x > turns[i][0] - 30 and turns[i][ 1] + 30 > center_y > turns[i][1] - 30: print("\nInside safe zone!\n") return_code_signal, t2_string = sim.simxGetStringSignal(client_id, 'time', sim.simx_opmode_buffer) if return_code_signal == 0: t2 = float(t2_string) vision_sensor_image, image_resolution, return_code = task_2b.get_vision_sensor_image(client_id, task_3.getVisionSensorHandle(table)) transformed_image = task_2b.transform_vision_sensor_image(vision_sensor_image, image_resolution) warped_img = task_1b.applyPerspectiveTransform_vs(transformed_image) if warped_img is None: continue shapes = task_1a_part1.scan_image(warped_img, True) if len(shapes) == 0: continue center_x = shapes['Circle'][1] center_y = shapes['Circle'][2] if t2 - t1 > 0.25: flag = 1 break else: print("Calling control logic 1!") if gate: print("Waiting") # time.sleep(2) gate = False previous_error_x = turns[i][0] - center_x previous_error_y = turns[i][1] - center_y angle_x, angle_y = task_3.control_logic(center_x, center_y, table, client_id, previous_error_x, previous_error_y) # task_3.zero(client_id,table,0,0) else: angle_x, angle_y = task_3.control_logic(center_x, center_y, table, client_id, 0, 0) # task_3.zero(client_id,table,0,0) # task_3.control_logic(center_x, center_y, table, client_id) else: print("Calling control logic 2!") if gate: print("Waiting") # time.sleep(2) gate = False previous_error_x = turns[i][0] - center_x previous_error_y = turns[i][1] - center_y angle_x, angle_y = task_3.control_logic(center_x, center_y, table, client_id, previous_error_x, previous_error_y) # task_3.zero(client_id,table,0,0) else: angle_x, angle_y = task_3.control_logic(center_x, center_y, table, client_id, 0, 0) # task_3.zero(client_id,table,0,0) # task_3.control_logic(center_x, center_y, table, client_id) if flag == 1: print(np.sign(angle_x), np.sign(angle_y)) task_3.zero(client_id, table, -angle_x, -angle_y) break if len(turns) - 1 == i and cnt == 20: break else: cnt = cnt + 1 def main(rec_client_id): global start_coord_1, end_coord_1, end_coord_4, start_coord_1, start_coord_2, end_coord_2, start_coord_3, end_coord_3, client_id, next_table client_id = rec_client_id maze_t4 = cv2.imread('maze_t4.jpg') maze_t1 = cv2.imread('maze_t1.jpg') maze_t2 = cv2.imread('maze_t2.jpg') maze_t3 = cv2.imread('maze_t3.jpg') print("Maze images read!\n") warped_img_t4 = task_1b.applyPerspectiveTransform(maze_t4) warped_img_t1 = task_1b.applyPerspectiveTransform(maze_t1) warped_img_t2 = task_1b.applyPerspectiveTransform(maze_t2) warped_img_t3 = task_1b.applyPerspectiveTransform(maze_t3) maze_array_t4 = task_1b.detectMaze(warped_img_t4) maze_array_t1 = task_1b.detectMaze(warped_img_t1) maze_array_t2 = task_1b.detectMaze(warped_img_t2) maze_array_t3 = task_1b.detectMaze(warped_img_t3) print("Maze array detected:") return_code = task_2b.send_data(rec_client_id, maze_array_t4, 'top_plate_respondable_t4_1') return_code = task_2b.send_data(rec_client_id, maze_array_t1, 'top_plate_respondable_t1_1') return_code = task_2b.send_data(rec_client_id, maze_array_t2, 'top_plate_respondable_t2_1') return_code = task_2b.send_data(rec_client_id, maze_array_t3, 'top_plate_respondable_t3_1') print("\nMaze generated!\n") with open("ball_details.json") as f: data = json.load(f) print(data) return_code = task_2a.start_simulation(rec_client_id) print("Simulation started!\n") task_3.init_setup(rec_client_id) for i in range(3): shapes = {} while shapes.get("Circle") is None: img_vs5, res, _ = task_2a.get_vision_sensor_image_c(rec_client_id, 5) img = task_2a.transform_vision_sensor_image_c(img_vs5, res) shapes = task_1a_part1.scan_image(img, False) cl = shapes["Circle"][0] print(cl) send_color_and_collection_box_identified(cl, data[cl][0]) get_start_end_coord(data, cl) path_t4 = task_4a.find_path(maze_array_t4, start_coord_4, end_coord_4) send_data_to_draw_path(rec_client_id, path_t4, 4) print("\nPath sent to CoppeliaSim\n") pixel_path_t4 = convert_path_to_pixels(path_t4) print("Entering traverse path\n") traverse_path(pixel_path_t4, 4) print("Ball traversed!") time.sleep(1) if next_table[0]: path_t1 = task_4a.find_path(maze_array_t1, start_coord_1, end_coord_1) send_data_to_draw_path(rec_client_id, path_t1, 1) pixel_path_t1 = convert_path_to_pixels(path_t1) print("Path sent to CoppeliaSim") print("Entering traverse path\n") traverse_path(pixel_path_t1, 1) print("Ball traversed!") if next_table[1]: path_t2 = task_4a.find_path(maze_array_t2, start_coord_2, end_coord_2) send_data_to_draw_path(rec_client_id, path_t2, 2) pixel_path_t2 = convert_path_to_pixels(path_t2) print("Path sent to CoppeliaSim") print("Entering traverse path\n") traverse_path(pixel_path_t2, 2) print("Ball traversed!") if next_table[2]: path_t3 = task_4a.find_path(maze_array_t3, start_coord_3, end_coord_3) send_data_to_draw_path(rec_client_id, path_t3, 3) pixel_path_t3 = convert_path_to_pixels(path_t3) print("Path sent to CoppeliaSim") print("Entering traverse path\n") traverse_path(pixel_path_t3, 3) print("Ball traversed!") time.sleep(2) return_code = task_2a.stop_simulation(rec_client_id) if __name__ == "__main__": main(client_id)
{ "alphanum_fraction": 0.5420124246, "author": null, "avg_line_length": 40.5386029412, "converted": null, "ext": "py", "file": null, "hexsha": "e192bb4145c390bfb354fa3ce61530df483b26b0", "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": "e3db8e9bde3108e659bda506c6adf393fb2da295", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Harshit-1104/Eyantra-2020", "max_forks_repo_path": "task_6.py", "max_issues_count": 5, "max_issues_repo_head_hexsha": "64d88675fc372aec4a9cc164fb354e1ed78633b8", "max_issues_repo_issues_event_max_datetime": "2021-10-07T19:44:41.000Z", "max_issues_repo_issues_event_min_datetime": "2021-10-07T18:46:58.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "CodeSlayer2001/Eyantra-2020", "max_issues_repo_path": "task_6.py", "max_line_length": 152, "max_stars_count": null, "max_stars_repo_head_hexsha": "64d88675fc372aec4a9cc164fb354e1ed78633b8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "CodeSlayer2001/Eyantra-2020", "max_stars_repo_path": "task_6.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5324, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 22053 }
# Copyright 2013 Novo Nordisk Foundation Center for Biosustainability, DTU. # # 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 __future__ import absolute_import, print_function import colorsys import inspect import itertools import logging import math import platform import re from collections import OrderedDict from datetime import datetime from functools import partial from itertools import islice from time import time from uuid import uuid1 import numpy import pandas import pkg_resources from cobra.util.context import HistoryManager from numpy.random import RandomState logger = logging.getLogger(__name__) _BIOMASS_RE_ = re.compile("biomass", re.IGNORECASE) class frozendict(dict): def __init__(self, iterable, **kwargs): super(frozendict, self).__init__(iterable, **kwargs) def popitem(self): raise AttributeError("'frozendict' object has no attribute 'popitem") def pop(self, k, d=None): raise AttributeError("'frozendict' object has no attribute 'pop") def __setitem__(self, key, value): raise AttributeError("'frozendict' object has no attribute '__setitem__") def setdefault(self, k, d=None): raise AttributeError("'frozendict' object has no attribute 'setdefault") def __delitem__(self, key): raise AttributeError("'frozendict' object has no attribute '__delitem__") def __hash__(self): return hash(tuple(sorted(self.items()))) def update(self, E=None, **F): raise AttributeError("'frozendict' object has no attribute 'update") def float_ceil(val, decimals=0): """ Like ceil but the number of decimals can be set. Equivalent of $$round(val + 1e^{-decimals}/2, decimals)$$ val: float, numpy.array The initial value. decimals: int The number of decimal places. Returns ------- float, numpy.array """ aux = math.pow(10, -decimals) / 2 return numpy.round(val + aux, decimals) def float_floor(val, decimals=0): """ Like floor but the number of decimals can be set. Equivalent of $$round(val - 1e^{-decimals}/2, decimals)$$ val: float, numpy.array The initial value. decimals: int The number of decimal places. Returns ------- float, numpy.array """ aux = math.pow(10, -decimals) / 2 return numpy.round(val - aux, decimals) class ProblemCache(object): """ Variable and constraint cache for models. To be used in complex methods that require many extra variables and constraints when one must run simulations with the same method many times. It allows rollback to the previous state in case one iteration fails to build the problem or generates an invalid state. """ def __init__(self, model): self.history_manager = None self._model = model self.variables = {} self.constraints = {} self.objective = None self.original_objective = model.solver.objective self._contexts = [HistoryManager()] self.transaction_id = None def begin_transaction(self): """ Creates a time point. If rollback is called, the variables and constrains will be reverted to this point. """ self._contexts.append(HistoryManager()) @property def model(self): return self._model def _append_constraint(self, constraint_id, create, *args, **kwargs): constraint = self.constraints[constraint_id] = create(self._model, constraint_id, *args, **kwargs) assert constraint_id in self.constraints self._model.solver.add(constraint) def _remove_constraint(self, constraint_id): constraint = self.constraints.pop(constraint_id) self._model.solver.remove(constraint) def _append_variable(self, variable_id, create, *args, **kwargs): variable = self.variables[variable_id] = create(self._model, variable_id, *args, **kwargs) assert variable_id in self.variables self._model.solver.add(variable) def _remove_variable(self, variable_id): variable = self.variables.pop(variable_id) self._model.solver.remove(variable) def _rebuild_variable(self, variable): (type, lb, ub, name) = variable.type, variable.lb, variable.ub, variable.name def rebuild(): self._model.solver.remove(variable) new_variable = self.model.solver.interface.Variable(name, lb=lb, ub=ub, type=type) self.variables[name] = variable self._model.solver.add(new_variable, sloppy=True) return rebuild def add_constraint(self, constraint_id, create, update, *args, **kwargs): """ Adds a new cached constraint. The create and update functions must have the following signatures: >>> create(model, constraint_id, *args) >>> update(model, constraint, *args) "args" in the first example must match args on the second example. Parameters ---------- constraint_id : str The identifier of the constraint create : function A function that creates an optlang.interface.Constraint update : function a function that updates an optlang.interface.Constraint """ context = self._contexts[-1] if constraint_id not in self.constraints: self._append_constraint(constraint_id, create, *args, **kwargs) context(partial(self._remove_constraint, constraint_id)) elif update is not None: update(self._model, self.constraints[constraint_id], *args, **kwargs) assert constraint_id in self.constraints def add_variable(self, variable_id, create, update, *args, **kwargs): """ Adds a new cached variable. The create and update functions must have the following signatures: >>> create(model, variable_id, *args) >>> update(model, variable, *args) "args" in the first example must match args on the second example. Parameters ---------- variable_id : str The identifier of the constraint create : function A function that creates an optlang.interface.Variable update : function a function that updates an optlang.interface.Variable """ context = self._contexts[-1] if variable_id not in self.variables: self._append_variable(variable_id, create, *args, **kwargs) context(partial(self._remove_variable, variable_id)) elif update is not None: # rebuild_function = self._rebuild_variable(self.variables[variable_id]) update(self._model, self.variables[variable_id], *args, **kwargs) # context(rebuild_function) assert variable_id in self.variables def add_objective(self, create, update, *args): context = self._contexts[-1] if self.objective is None: previous_objective = self._model.solver.objective self.model.solver.objective = self.objective = create(self._model, *args) context(partial(setattr, self._model.solver, 'objective', previous_objective)) elif update: previous_objective = self._model.solver.objective self.model.solver.objective = self.objective = update(self._model, *args) context(partial(setattr, self._model.solver, 'objective', previous_objective)) def reset(self): """ Removes all constraints and variables from the cache. """ variables = list(self.variables.keys()) constraints = list(self.constraints.keys()) while len(self._contexts) > 0: manager = self._contexts.pop() manager.reset() self._contexts.append(HistoryManager()) assert all(var_id not in self._model.solver.variables for var_id in variables) assert all(const_id not in self._model.solver.constraints for const_id in constraints) self.variables = {} self.constraints = {} self._model.objective = self.original_objective self.objective = None def rollback(self): """ Returns to the previous transaction start point. """ if len(self._contexts) < 2: raise RuntimeError("Start transaction must be called before rollback") self._contexts.pop().reset() def __enter__(self): """ Allows problem cache to be used with a _with_ statement. Examples -------- You want to run room/lmoma for every single knockout. >>> with ProblemCache(model) as cache: >>> for reaction in reactions: >>> reaction.knock_out() >>> result = lmoma(model, reference=reference, cache=cache) Returns ------- ProblemCache returns itself """ return self def __exit__(self, exc_type, exc_val, exc_tb): self.reset() class RandomGenerator(object): def __init__(self, seed=None): self._random = RandomState(seed=seed) def seed(self, seed): self._random = RandomState(seed=seed) def random(self): return self._random.rand() def randint(self, a, b=None): if b is None: b = a a = 0 r = self._random.randint(a, high=b, size=1) return r[0] def sample(self, population, k): if k == 0: return [] return list(self._random.choice(population, size=k, replace=False)) def __getattr__(self, attr): return getattr(self._random, attr) def __getstate__(self): return {'_random': self._random} def __setstate__(self, d): self._random = d['_random'] def uniform(self, low=0.0, high=1.0, size=None): return self._random.uniform(low, high, size) class Singleton(object): """ Singleton class to be extended """ _instance = None def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = super(Singleton, cls).__new__(cls) return cls._instance class AutoVivification(dict): """Implementation of perl's autovivification feature. Checkout http://stackoverflow.com/a/652284/280182""" def __getitem__(self, item): try: return dict.__getitem__(self, item) except KeyError: value = self[item] = type(self)() return value class TimeMachine(object): """Travel back and forth in time.""" def __init__(self): super(TimeMachine, self).__init__() self.history = OrderedDict() def __call__(self, do=None, undo=None, bookmark=None): output = do() current_time = time() if bookmark is None: entry_id = uuid1() else: entry_id = bookmark # make sure that entry is added to the end of history self.history.pop(entry_id, None) self.history[entry_id] = {'unix_epoch': current_time, 'undo': undo, 'redo': do} return entry_id, output def __str__(self): info = '\n' for item in self.history.items(): info += self._history_item_to_str(item) return info def __enter__(self): return self def __exit__(self, type, value, traceback): self.reset() @staticmethod def _history_item_to_str(item): info = '' uuid, entry = item info += datetime.fromtimestamp(entry['unix_epoch']).strftime('%Y-%m-%d %H:%M:%S') + '\n' undo_entry = entry['undo'] try: # partial (if .keywords is None print {} instead) elements = undo_entry.func, undo_entry.args, undo_entry.keywords or {} info += 'undo: ' + ' '.join([str(elem) for elem in elements]) + '\n' except AttributeError: # normal python function info += 'undo: ' + undo_entry.__name__ + '\n' redo_entry = entry['redo'] try: elements = redo_entry.func, redo_entry.args, redo_entry.keywords or {} # partial info += 'redo: ' + ' '.join([str(elem) for elem in elements]) + '\n' except AttributeError: info += 'redo: ' + redo_entry.__name__ + '\n' return info def undo(self, bookmark=None): if bookmark is None: try: (uuid, entry) = self.history.popitem() entry['undo']() except KeyError: # history is empty pass elif bookmark in list(self.history.keys()): uuid = False while uuid is not bookmark: (uuid, entry) = self.history.popitem() entry['undo']() else: raise Exception( 'Provided bookmark %s cannot be found in the time machine.') def redo(self): raise NotImplementedError def reset(self): if self.history: # history is not empty self.undo(bookmark=list(self.history.keys())[0]) class Timer(object): """Taken from http://stackoverflow.com/a/5849861/280182""" def __init__(self, name=None): self.name = name def __enter__(self): self.tstart = time() def __exit__(self, type, value, traceback): if self.name: print('[%s]' % self.name, end=' ') print('Elapsed: %s' % (time() - self.tstart)) class IntelliContainer(object): def __init__(self, **kwargs): self._dict = dict(**kwargs) def __getattr__(self, value): return self._dict.get(value) def __setitem__(self, key, value): self._dict[key] = value def __iter__(self): return iter(self._dict.values()) def __dir__(self): return list(self._dict.keys()) def inheritdocstring(name, bases, attrs): """Use as metaclass to inherit class and method docstrings from parent. Adapted from http://stackoverflow.com/questions/13937500/inherit-a-parent-class-docstring-as-doc-attribute""" temp = type('temporaryclass', bases, {}) if '__doc__' not in attrs or not attrs["__doc__"]: # create a temporary 'parent' to (greatly) simplify the MRO search for cls in inspect.getmro(temp): if cls.__doc__ is not None: attrs['__doc__'] = cls.__doc__ break for attr_name, attr in attrs.items(): if not attr.__doc__: for cls in inspect.getmro(temp): try: if getattr(cls, attr_name).__doc__ is not None: attr.__doc__ = getattr(cls, attr_name).__doc__ break except (AttributeError, TypeError): continue return type(name, bases, attrs) def partition_(lst, n): """Partition a list into n bite size chunks.""" division = len(lst) / float(n) return [lst[int(round(division * i)): int(round(division * (i + 1)))] for i in range(n)] def partition(ite, n): """Partition an iterable into n bite size chunks.""" try: length = len(ite) except TypeError: ite = list(ite) length = len(ite) division = length / float(n) iterator = iter(ite) return [list(islice(iterator, 0, round(division * (i + 1)) - round(division * i))) for i in range(n)] def flatten(l): return [item for sublist in l for item in sublist] def generate_colors(n): hsv_tuples = [(v * 1.0 / n, 0.5, 0.5) for v in range(n)] color_map = {} for i in range(n): rgb = colorsys.hsv_to_rgb(*hsv_tuples[i]) color = tuple(int(channel * 256) for channel in rgb) color_map[i] = '#%02x%02x%02x' % color return color_map def memoize(function, memo={}): def wrapper(*args): if args in memo: return memo[args] else: rv = function(*args) memo[args] = rv return rv return wrapper def get_system_info(): package_info = list() for dist in pkg_resources.working_set: req = str(dist.as_requirement()) package_info.append(req) return dict(package_info=package_info, platform=platform.platform(), machine=platform.machine(), system=platform.system()) def in_ipnb(): """ Check if it is running inside an IPython Notebook (updated for new notebooks) """ return pandas.io.formats.console.in_ipython_frontend() def str_to_valid_variable_name(s): """Adapted from http://stackoverflow.com/a/3303361/280182""" # Remove invalid characters s = re.sub('[^0-9a-zA-Z_]', '_', s) # Remove leading characters until we find a letter or underscore s = re.sub('^[^a-zA-Z_]+', '', s) return s def zip_repeat(long_iter, short_iter): """ Zips two iterable objects but repeats the second one if it is shorter than the first one. Parameters ---------- long_iter: iterable short_iter: iterable Returns ------- generator """ for i, j in zip(long_iter, itertools.cycle(short_iter)): yield i, j def pick_one(iterable): """ Helper function that returns an element of an iterable (it the iterable is ordered this will be the first element). """ it = iter(iterable) return next(it) def reduce_reaction_set(reaction_set, groups): """ Reduces a set of reactions according to a number of groups of reactions. The reduction will be performed so that the resulting set will contain no more than 1 reaction from each group. Reactions that are not in any of the groups will remain in the set. Parameters ---------- reaction_set: Set groups: Iterable of sets Returns ------- Set """ reaction_set = set(reaction_set) # Make a shallow copy result = [] for group in groups: intersection = group & reaction_set if intersection: # If any elements of group are in reaction_set, add one of these to result result.append(pick_one(intersection)) reaction_set = reaction_set - intersection result = set(result) | reaction_set # Add the remaining reactions to result return result def decompose_reaction_groups(reaction_groups, reactions): """ reaction_groups : list A list with dictionaries (element: relative_coefficient) reactions : list, set, tuple A collection of reactions. Returns ------- list A list of all possible group substitutions. """ to_keep = [] to_replace = {} for element in reactions: for g in reaction_groups: if element in g: to_replace[element] = g.keys() break if element not in to_replace: to_keep.append(element) return (list(combo) + to_keep for combo in itertools.product(*to_replace.values())) def current_solver_name(model): """Give a string representation for an optlang interface. Parameters ---------- model : cobra.Model A model Returns ------- string The name of the interface as a string """ interface = model.solver.interface.__name__ return re.sub(r"optlang.|.interface", "", interface)
{ "alphanum_fraction": 0.6245202989, "author": null, "avg_line_length": 30.4676923077, "converted": null, "ext": "py", "file": null, "hexsha": "71ac8422d992953bdaf989e663681e8c1c0ad1df", "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": "13571b93bdd195d6d39a9ec43180916a1ff4490a", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "ChiamYu/cameo", "max_forks_repo_path": "cameo/util.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "13571b93bdd195d6d39a9ec43180916a1ff4490a", "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": "ChiamYu/cameo", "max_issues_repo_path": "cameo/util.py", "max_line_length": 115, "max_stars_count": null, "max_stars_repo_head_hexsha": "13571b93bdd195d6d39a9ec43180916a1ff4490a", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "ChiamYu/cameo", "max_stars_repo_path": "cameo/util.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 4430, "path": null, "reason": "import numpy,from numpy", "repo": null, "save_path": null, "sha": null, "size": 19804 }
import os, sys import numpy as np import imageio import json import random import time import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm, trange import matplotlib.pyplot as plt from models.sampler import StratifiedSampler, ImportanceSampler from models.renderer import VolumetricRenderer from models.nerf_mlp import VolumeInterpolater from models.nerf_net import NeRFNet class VoxelNeRFNet(NeRFNet): def __init__(self, volume_size, N_samples=64, N_importance=64, ray_chunk=1024*32, pts_chuck=1024*64, perturb=1., raw_noise_std=0., white_bkgd=False): super().__init__(netdepth=1, netwidth=1, netdepth_fine=1, netwidth_fine=1, viewdirs=False, use_embed=False, multires=0, multires_views=0, conv_embed=False, N_samples=N_samples, N_importance=N_importance, ray_chunk=ray_chunk, pts_chuck=pts_chuck, perturb=perturb, raw_noise_std=raw_noise_std, white_bkgd=white_bkgd) del self.nerf del self.nerf_fine # create nerf mlps self.nerf = VolumeInterpolater(volume_size) self.nerf_fine = self.nerf def load_from_numpy(self, np_vol): self.nerf.load_from_numpy(np_vol)
{ "alphanum_fraction": 0.7480376766, "author": null, "avg_line_length": 32.6666666667, "converted": null, "ext": "py", "file": null, "hexsha": "e0b1028366c5e47a45602de67d777758b2c6922f", "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": "63f8d63c82c9975b6fb0d872ec92dbba121f9af3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "zjzcodecode/nerf-pytorch-1", "max_forks_repo_path": "models/voxel_nerf_net.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "63f8d63c82c9975b6fb0d872ec92dbba121f9af3", "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": "zjzcodecode/nerf-pytorch-1", "max_issues_repo_path": "models/voxel_nerf_net.py", "max_line_length": 104, "max_stars_count": 2, "max_stars_repo_head_hexsha": "63f8d63c82c9975b6fb0d872ec92dbba121f9af3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "zjzcodecode/nerf-pytorch-1", "max_stars_repo_path": "models/voxel_nerf_net.py", "max_stars_repo_stars_event_max_datetime": "2022-03-18T20:20:53.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-07T01:27:59.000Z", "num_tokens": 352, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1274 }
const FT = Float64 import SciMLBase: step! using OrdinaryDiffEq using OrdinaryDiffEq: ODEProblem, solve, SSPRK33, savevalues!, Euler using LinearAlgebra using ClimaCore # pending PR merge: # import Pkg; Pkg.add(url="https://github.com/CliMA/ClimaCore.jl",rev="sb/online-sphere-remap", subdir = "lib/ClimaCoreTempestRemap") # using old interface - before the new one is consolidated: import Pkg; Pkg.add(url = "https://github.com/CliMA/ClimaAtmos.jl", rev = "jh_ln/external_boundary_conditons"); using ClimaCoreTempestRemap import Test: @test import ClimaAtmos.BoundaryConditions: get_boundary_flux, AbstractBoundary export get_boundary_flux include("atmos.jl") include("slab.jl") include("coupled_bc.jl") include("conservation.jl") # initiate spatial and temporal info tspan = (0.0, 1300.0) # 172800.0) cpl_Δt = 5.0 # seconds atmos_dt, slab_dt = (5.0, 5.0) # seconds slab_sim = slab_init(FT, tspan, dt = atmos_dt, npolynomial = 3) atmos_sim = atmos_init(FT, tspan, dt = slab_dt, npolynomial = 3) # parameter exchange slab_sim.integrator.p.cp_d .= CLIMAParameters.Planet.cp_d(atmos_sim.model.parameters) # regridding init atmos_energy_bc = atmos_sim.model.boundary_conditions.ρe_tot.bottom atmos_momentum_bc = atmos_sim.model.boundary_conditions.uh.bottom F_a_space = axes(atmos_energy_bc.flux) F_s_space = axes(slab_sim.integrator.u.T_sfc) # weightfile = tempname() # R_atm2slab = ClimaCoreTempestRemap.generate_map( # bring back once CC #614 is resolved/ merged # F_s_space, #target # F_a_space, #source # weightfile = weightfile, # ) # R_slab2atm = ClimaCoreTempestRemap.generate_map(# bring back once CC #614 is resolved/ merged # F_a_space, #target # F_s_space, #source # weightfile = weightfile, # ) function dummmy_remap!(target, source) # delete when can use Tempest again parent(target) .= parent(source) end # init conservation info collector CS = ConservationCheck([], []) # coupling loop for t in (tspan[1]:cpl_Δt:tspan[end]) @show t ## Atmos # calculate surface fluxes for Atmos BCs coupler_atmos_boundary_flux(atmos_energy_bc, atmos_sim, slab_sim, F_a_space, F_s_space) coupler_atmos_boundary_flux(atmos_momentum_bc, atmos_sim, slab_sim, F_a_space, F_s_space) # run step!(atmos_sim.integrator, t - atmos_sim.integrator.t, true) # NOTE: use (t - integ_atm.t) here instead of Δt_cpl to avoid accumulating roundoff error in our timestepping. ## Slab # pre: get accumulated flux from atmos F_S = ClimaCore.Fields.zeros(F_s_space) # ClimaCoreTempestRemap.remap!(F_S, atmoatmos_energy_bcs_bc.flux, R_atm2slab) dummmy_remap!(F_S, atmos_energy_bc.flux) # save the accumulated flux slab_F_sfc = slab_sim.integrator.p.F_sfc slab_F_sfc .= F_S .* cpl_Δt # run step!(slab_sim.integrator, t - slab_sim.integrator.t, true) # conservation info check_conservation(CS, atmos_sim, slab_sim) end
{ "alphanum_fraction": 0.7479423868, "author": null, "avg_line_length": 32.4, "converted": null, "ext": "jl", "file": null, "hexsha": "44bdf6df8a3db3944ebb994a0f5460b17eb38993", "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": "d21349895a9bdaf9e192b534977deff9bb05385b", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "CliMA/ClimaCoupler.jl", "max_forks_repo_path": "experiments/ClimaCore/bc-wave-slab/run.jl", "max_issues_count": 8, "max_issues_repo_head_hexsha": "d21349895a9bdaf9e192b534977deff9bb05385b", "max_issues_repo_issues_event_max_datetime": "2022-03-28T23:53:13.000Z", "max_issues_repo_issues_event_min_datetime": "2021-12-08T22:24:17.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "CliMA/ClimaCoupler.jl", "max_issues_repo_path": "experiments/ClimaCore/bc-wave-slab/run.jl", "max_line_length": 176, "max_stars_count": 1, "max_stars_repo_head_hexsha": "b1848bb1fe39d391040424f2e3ae8321d86d9b29", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "CliMA/ClimaCoupler", "max_stars_repo_path": "experiments/ClimaCore/bc-wave-slab/run.jl", "max_stars_repo_stars_event_max_datetime": "2022-03-05T07:09:01.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-05T07:09:01.000Z", "num_tokens": 890, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2916 }
module Periodize using Cubature: hcubature using Cuba using JSON using Mea.Green II = [1.0 + 0.0im 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0 0.0 0.0 0.0 0.0 1.0] function buildmodelvec(finsE::String, finparams::String) params = JSON.parsefile(finparams) t = 1.0 tp = params["tp"][1] mu = params["mu"][1] (wvec, sEvec_c) = Green.readgreen_c(finsE) return ModelVector(t, tp, mu, wvec, sEvec_c) end type ModelVector t_::Float64 ; tp_::Float64 ; mu_::Float64 wvec_::Array{Float64, 1} ; sEvec_c_::Array{Complex{Float64}, 3} cumulants_::Array{Complex{Float64}, 3} function ModelVector(t::Float64, tp::Float64, mu::Float64, wvec::Array{Float64, 1}, sEvec_c::Array{Complex{Float64}, 3}) cumulants = build_cumulants(wvec, mu, sEvec_c) return new(t, tp, mu, wvec, sEvec_c, cumulants) end end function build_cumulants(wvec::Array{Float64, 1}, mu::Float64, sEvec_c::Array{Complex{Float64}, 3}) cumulants = zeros(Complex{Float64}, size(sEvec_c)) for (ii, ww) in enumerate(wvec) tmp = zeros(Complex{Float64}, (4, 4)) tmp[1, 1] = tmp[2, 2] = tmp[3, 3] = tmp[4, 4] = (ww + mu) tmp -= sEvec_c[ii, :, :] cumulants[ii, :, :] = inv(tmp) end return cumulants end type Model t_::Float64 ; tp_::Float64 ; mu_::Float64 w_::Float64 ; sE_::Array{Complex{Float64}, 2} cumulant_::Array{Complex{Float64}, 2} function Model(modelvec::ModelVector, ii::Integer) (t, tp, mu, w, sE_c, cumulant) = (modelvec.t_, modelvec.tp_, modelvec.mu_, modelvec.wvec_[ii], modelvec.sEvec_c_[ii, :, :], modelvec.cumulants_[ii, :, :]) return new(t, tp, mu, w, sE_c, cumulant) end end function t_value(model::Model, kx::Float64, ky::Float64) # This is t_ij(k_tilde) t = model.t_; tp = model.tp_ t_val = zeros(Complex{Float64}, (4, 4)) ex = exp(-2.0im*kx) ; emx = conj(ex) ey = exp(-2.0im*ky) ; emy = conj(ey) tloc = [0.0 -t -tp -t -t 0.0 -t 0.0 -tp -t 0.0 -t -t 0.0 -t 0.0] t_val += tloc t_val[1, 1] += 0.0; t_val[1, 2] += -t*ex; t_val[1, 3] += -tp*ex*ey; t_val[1, 4] += -t*ey t_val[2, 1] += -t*emx; t_val[2, 2] += 0.0; t_val[2, 3] += -t*ey; t_val[2, 4] += -tp*(emx + ey) t_val[3, 1] += -tp*emx*emy; t_val[3, 2] += -t*emy; t_val[3, 3] += 0.0; t_val[3, 4] += -t*emx t_val[4, 1] += -t*emy; t_val[4, 2] += -tp*(ex + emy); t_val[4, 3] += -t*ex; t_val[4, 4] += 0.0 return (t_val) end function exp_k(kx::Float64, ky::Float64) expk = zeros(Complex{Float64}, 4) # Here exp_k[i] is in fact e**(-j*dot(k, r_i)) where r_i is a site of the cluster expk[1] = 1.0 expk[2] = exp(1.0im*kx) expk[3] = exp(1.0im*(kx+ky)) expk[4] = exp(1.0im*ky) return expk end function eps_0(model::Model, kx::Float64, ky::Float64) return (-2.0*model.t_*(cos(kx) + cos(ky)) - 2.0*model.tp_*cos(kx + ky) ) end function hopping_test(model::Model, kx::Float64, ky::Float64) t = model.t_ ; tp = model.tp_ k = [kx, ky] N_c = 4 r_sites = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]] K_sites = pi*deepcopy(r_sites) t_array = zeros(Complex{Float64}, (N_c, N_c)) for i in 1:N_c for j in 1:N_c for K in K_sites t_array[i, j] += 1.0/N_c * exp(1.0im*dot(K + k, r_sites[i] - r_sites[j])) * eps_0(model, (K + k)...) end end end return t_array end function build_gf_ktilde(model::Model, kx::Float64, ky::Float64) return inv((model.w_ + model.mu_) * II - t_value(model, kx, ky) - model.sE_) end function build_gf_ktilde_inverse(model::Model, kx::Float64, ky::Float64) return( (model.w_ + model.mu_) * II - t_value(model, kx, ky) - model.sE_) end function periodize(arg::Array{Complex{Float64}, 2}, kx::Float64, ky::Float64) N_c = 4.0 expk = exp_k(kx, ky) return (1.0/N_c * dot(expk, (arg * expk)) ) end function make_akwgreen(model::Model) function akw(kk::Array{Float64, 1}) # periodize the imaginary part (Ak_w) #N_c = 4.0 gf_ktilde = build_gf_ktilde(model, kk[1], kk[2]) #expk = exp_k(kx, ky) #return imag(-2.0/N_c * dot(expk, (gf_ktilde * expk)) ) return imag(-2.0*periodize(gf_ktilde, kk[1], kk[2])) end return akw end function make_akwcum(model::Model) function akwcum(kk::Array{Float64, 1}) # periodize the imaginary part (Ak_w) cump = periodize(model.cumulant_, kk[1], kk[2]) return imag(-2.0*inv(inv(cump) - eps_0(model, kk[1], kk[2]))) end return akwcum end function make_akwtrace(model::Model) function akwtrace(kk::Array{Float64, 1}) # periodize the imaginary part (Ak_w) N_c = 4.0 return 1.0/N_c*trace(-2.0*imag(build_gf_ktilde(model, kk[1], kk[2]))) end return akwtrace end function make_akw2green(model::Model) akw = make_akwgreen(model) function akw2(kk::Array{Float64, 1}) return (akw(kk)^2.0) end return akw2 end function make_akw2cum(model::Model) akwcum = make_akwcum(model) function akw2cum(kk::Array{Float64, 1}) return (akwcum(kk)^2.0) end return akw2cum end function make_akw2trace(model::Model) function akw2trace(kk::Array{Float64, 1}) # periodize the imaginary part (Ak_w) N_c = 4.0 gfktilde = build_gf_ktilde(model, kk[1], kk[2]) return 1.0/N_c*trace(-2.0*imag(gfktilde)*-2.0*imag(gfktilde) ) end return akw2trace end function calcintegral(modelvector::ModelVector, fct; fout_name::String="out.dat", maxevals::Int64=100000, kwargs...) len_sEvec_c = size(modelvector.sEvec_c_)[1] result = zeros(Float64, len_sEvec_c) #println("in calcintegral, kwargs = ", kwargs...) #fct = getfield(Mea.Periodize, Symbol(fctname)) for n in 1:len_sEvec_c model = Model(modelvector, n) result[n] = (2.0*pi)^(-2.0)*hcubature(fct(model; kwargs...), (-pi, -pi), (pi, pi), reltol=1.49e-8, abstol=1.49e-8, maxevals=maxevals)[1] end result_out = hcat(modelvector.wvec_, result) writedlm(fout_name, result_out, " ") return result_out end function calcintegral_cuba(modelvector::ModelVector, fct; fout_name::String="out.dat", maxevals::Int64=100000, kwargs...) len_sEvec_c = size(modelvector.sEvec_c_)[1] result = zeros(Float64, len_sEvec_c) #fct = getfield(Mea.Periodize, Symbol(fctname)) for n in 1:len_sEvec_c model = Model(modelvector, n) result[n] = (2.0*pi)^(-2.0)*divonne(fct(model; kwargs...), 2, 1, reltol=1.49e-8, abstol=1.49e-8, maxevals=maxevals).integral[1] end result_out = hcat(modelvector.wvec_, result) writedlm(fout_name, result_out, " ") return result_out end function calcdos(modelvector::ModelVector; fout_name::String="dos.dat", maxevals::Int64=100000) dos_out = calcintegral(modelvector, make_akwgreen, fout_name=fout_name, maxevals=maxevals) return dos_out end function calcdos2(modelvector::ModelVector; fout_name::String="dos2.dat", maxevals::Int64=100000) dos2_out = calcintegral(modelvector, make_akw2green, fout_name=fout_name, maxevals=maxevals) return dos2_out end end
{ "alphanum_fraction": 0.6102437688, "author": null, "avg_line_length": 28.9761904762, "converted": null, "ext": "jl", "file": null, "hexsha": "8e204be75489e6739a64f60214bfc9d05fb9e5d6", "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": "453649a4ffedf9569023e248e23e1c4adddf1fbf", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ZGCDDoo/mea.jl", "max_forks_repo_path": "src/Periodize.jl", "max_issues_count": null, "max_issues_repo_head_hexsha": "453649a4ffedf9569023e248e23e1c4adddf1fbf", "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": "ZGCDDoo/mea.jl", "max_issues_repo_path": "src/Periodize.jl", "max_line_length": 162, "max_stars_count": null, "max_stars_repo_head_hexsha": "453649a4ffedf9569023e248e23e1c4adddf1fbf", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ZGCDDoo/mea.jl", "max_stars_repo_path": "src/Periodize.jl", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2743, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 7302 }
import pdb import torch import numpy as np import time from tools.utils import Progbar,AverageMeter from matplotlib import pyplot as plt from scipy.integrate import simps def predict_set(nets, dataloader, runtime_params): run_type = runtime_params['run_type'] #net = net.eval() progbar = Progbar(len(dataloader.dataset), stateful_metrics=['run-type']) batch_time = AverageMeter() names = [] pred_landmarks = np.array([]) gt_landmarks = np.array([]) with torch.no_grad(): for i, (landmarks, imgs, img_paths) in enumerate(dataloader): s_time = time.time() imgs = imgs.cuda() names.extend(img_paths) net = nets[0] if 'half' in runtime_params.values(): output = net(imgs.half()) else: output = net(imgs) output = output.cpu().numpy() pred_landmarks = np.concatenate((pred_landmarks,output),axis=0) gt_landmarks = np.concatenate((gt_landmarks,landmarks.data.numpy()),axis=0) progbar.add(imgs.size(0), values=[('run-type', run_type)]) # ,('batch_time', batch_time.val)]) batch_time.update(time.time() - s_time) if runtime_params['debug'] and i: break pred_landmarks = pred_landmarks.reshape((-1,28,2)) gt_landmarks = gt_landmarks.reshape((-1,28,2)) assert gt_landmarks.shape == pred_landmarks.shape return gt_landmarks, gt_landmarks, names def dist(gtLandmark, dist_type='centers', left_pt=0, right_pt=8, num_eye_pts=8): if dist_type=='centers': normDist = np.linalg.norm(np.mean(gtLandmark[left_pt:left_pt+num_eye_pts], axis=0) - np.mean(gtLandmark[right_pt:right_pt+num_eye_pts], axis=0)) elif dist_type=='corners': normDist = np.linalg.norm(gtLandmark[left_pt] - gtLandmark[right_pt+num_eye_pts/2]) elif dist_type=='diagonal': height, width = np.max(gtLandmark, axis=0) - np.min(gtLandmark, axis=0) normDist = np.sqrt(width**2 + height**2) return normDist def landmark_error(gtLandmarks, predict_Landmarks, dist_type='centers', show_results=False, verbose=False): norm_errors = [] errors = [] for i in range(len(gtLandmarks)): norm_dist = dist(gtLandmarks[i], dist_type=dist_type) error = np.mean(np.sqrt(np.sum((gtLandmarks[i] - predict_Landmarks[i])**2, axis=1))) norm_error = error/norm_dist errors.append(error) norm_errors.append(norm_error) if verbose: print('{0}: {1}'.format(i, error)) if verbose: print("Image idxs sorted by error") print(np.argsort(errors)) avg_error = np.mean(errors) avg_norm_error = np.mean(norm_errors) print("Average error: {0}".format(avg_error)) print("Average norm error: {0}".format(avg_norm_error)) return norm_errors, errors def auc_error(errors, failure_threshold=0.03, step=0.0001, save_path='', showCurve=True): nErrors = len(errors) xAxis = list(np.arange(0., failure_threshold+step, step)) ced = [float(np.count_nonzero([errors <= x])) / nErrors for x in xAxis] auc = simps(ced, x=xAxis) / failure_threshold failure_rate = 1. - ced[-1] print("AUC @ {0}: {1}".format(failure_threshold, auc)) print("Failure rate: {0}".format(failure_rate)) if showCurve: plt.plot(xAxis, ced) plt.savefig(save_path) return auc, failure_rate def evaluate(gt_landmarks, landmarks,th,save_path): gt_landmarks = gt_landmarks.permute((1,0,2)).cpu().numpy() landmarks = landmarks.permute((1, 0, 2)).cpu().numpy() norm_errors, errors = landmark_error(gt_landmarks,landmarks) auc, failure_rate = auc_error(errors,th,save_path=save_path) return {'auc':auc,'failure_rate':failure_rate,"errors":errors}
{ "alphanum_fraction": 0.6504424779, "author": null, "avg_line_length": 39.2040816327, "converted": null, "ext": "py", "file": null, "hexsha": "eb060b2473fdc3a2526e2579cb65771873a89c41", "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": "ac5d1e0436e9e0835a6939f8d125f1d36007bc62", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "dong03/DogNoseLandmarks", "max_forks_repo_path": "tools/eval.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "ac5d1e0436e9e0835a6939f8d125f1d36007bc62", "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": "dong03/DogNoseLandmarks", "max_issues_repo_path": "tools/eval.py", "max_line_length": 107, "max_stars_count": 1, "max_stars_repo_head_hexsha": "ac5d1e0436e9e0835a6939f8d125f1d36007bc62", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "dong03/DogNoseLandmarks", "max_stars_repo_path": "tools/eval.py", "max_stars_repo_stars_event_max_datetime": "2020-09-09T04:34:55.000Z", "max_stars_repo_stars_event_min_datetime": "2020-09-09T04:34:55.000Z", "num_tokens": 979, "path": null, "reason": "import numpy,from scipy", "repo": null, "save_path": null, "sha": null, "size": 3842 }
from typing import Dict, List, Tuple import torch from torch.utils.data.dataset import Dataset as torchDataset import numpy as np import copy def shuffle(experiences, orders=None): st_size = experiences.shape batch_size = st_size[0] nbr_distractors_po = st_size[1] perms = [] shuffled_experiences = [] output_order = [] for b in range(batch_size): if orders is None: perm = torch.randperm(nbr_distractors_po) else: perm = orders[b] #if experiences.is_cuda: perm = perm.cuda() output_order.append(perm) perms.append(perm.unsqueeze(0)) shuffled_experiences.append( experiences[b,perm,...].unsqueeze(0)) perms = torch.cat(perms, dim=0) shuffled_experiences = torch.cat(shuffled_experiences, dim=0) decision_target = (perms==0).max(dim=1)[1].long() return shuffled_experiences, decision_target, output_order class Dataset(torchDataset): def __init__(self, kwargs): ''' :attribute classes: List (or Dictionary) of Lists of (absolute) indices of experiences. ''' super(Dataset,self).__init__() self.kwargs = kwargs if "root_folder" in kwargs: self.root_folder = kwargs['root_folder'] self.nbr_distractors = self.kwargs['nbr_distractors'] self.nbr_stimulus = self.kwargs['nbr_stimulus'] self.classes = None def getNbrDistractors(self, mode='train'): return self.nbr_distractors[mode] def setNbrDistractors(self, nbr_distractors, mode='train'): assert(nbr_distractors > 0) self.nbr_distractors[mode] = nbr_distractors def __len__(self) -> int: raise NotImplementedError def getNbrClasses(self) -> int: raise NotImplementedError def sample(self, idx: int = None, from_class: List[int] = None, excepts: List[int] = None, excepts_class: List[int]=None, target_only: bool = False) -> Dict[str,object]: ''' Sample an experience from the dataset. Along with relevant distractor experiences. If :param from_class: is not None, the sampled experiences will belong to the specified class(es). If :param excepts: is not None, this function will make sure to not sample from the specified list of exceptions. :param from_class: None, or List of keys (Strings or Integers) that corresponds to entries in self.classes :param excepts: None, or List of indices (Integers) that are not considered for sampling. :param excepts_class: None, or List of keys (Strings or Integers) that corresponds to entries in self.classes. :param target_only: bool (default: `False`) defining whether to sample only the target or distractors too. :returns: - sample_d: Dict of: - `"experiences"`: Tensor of the sampled experiences. - `"indices"`: List[int] of the indices of the sampled experiences. - `"exp_labels"`: List[int] consisting of the indices of the label to which the experiences belong. - `"exp_latents"`: Tensor representatin the latent of the experience in one-hot-encoded vector form. - `"exp_latents_values"`: Tensor representatin the latent of the experience in value form. - some other keys provided by the dataset used... ''' raise NotImplementedError def __getitem__(self, idx: int) -> Dict[str, torch.Tensor]: ''' Samples target experience and distractor experiences according to the distractor sampling scheme. TODO: In object_centric/class_centric mode, if some distractors are sampled, then it is important to sample them from a list of indices that exclude the elements of the class the target belongs to. So far, object_centric mode is only used without distractors. :params idx: int, index of the experiences to use as a target. :returns: - `output_dict`: Dict of elements: - 'speaker_experiences': Tensor of shape `(1, A, nbr_stimulus, stimulus_shape)` where `A=nbr_distractors+1` if `self.kwargs['observability']=='full'` or `A=1` otherwise (`'partial'`). - some other relevant values aligned with the speaker experiences, the keys starts with "speaker_". - 'listener_experiences': Tensor of shape `(1, nbr_distractors+1, nbr_stimulus, stimulus_shape)`. - some other relevant values aligned with the listener experiences, the keys starts with "listener_". - 'target_decision_idx': Tensor of type Long and shape `(1,)` containing the index of the target experience among the 'listener_experiences'. ''' from_class = None if 'similarity' in self.kwargs['distractor_sampling']: similarity_ratio = float(self.kwargs['distractor_sampling'].split('-')[-1]) sampled_d = self.sample(idx=idx, target_only=True) exp_labels = sampled_d["exp_labels"] #_, _, exp_labels, _ = self.sample(idx=idx, target_only=True) from_class = None if torch.rand(size=(1,)).item() < similarity_ratio: from_class = exp_labels sample_d = self.sample(idx=idx, from_class=from_class) exp_labels = sample_d["exp_labels"] # Adding batch dimension: for k,v in sample_d.items(): if not(isinstance(v, torch.Tensor)): v = torch.Tensor(v) sample_d[k] = v.unsqueeze(0) ##-------------------------------------------------------------- ##-------------------------------------------------------------- # Creating listener's dictionnary: listener_sample_d = copy.deepcopy(sample_d) retain_target = True if self.kwargs["descriptive"]: retain_target = torch.rand(size=(1,)).item() < self.kwargs['descriptive_target_ratio'] # Target experience is excluded from the experiences yielded to the listener: if not retain_target: # Sample a new element for the listener to consider. # Different from the target element in itself, but also in its class: new_target_for_listener_sample_d = self.sample( idx=None, from_class=from_class, target_only=True, excepts=[idx], excepts_class=[exp_labels[0]] ) # Adding batch dimension: for k,v in new_target_for_listener_sample_d.items(): if not(isinstance(v, torch.Tensor)): v = torch.Tensor(v) listener_sample_d[k][:,0] = v.unsqueeze(0) # Object-Centric or Stimulus-Centric? if retain_target and self.kwargs['object_centric']: new_target_for_listener_sample_d = self.sample( idx=None, from_class=[exp_labels[0]], excepts=[idx], # Make sure to not sample the actual target! target_only=True ) # Adding batch dimension: for k,v in new_target_for_listener_sample_d.items(): if not(isinstance(v, torch.Tensor)): v = torch.Tensor(v) listener_sample_d[k][:,0] = v.unsqueeze(0) listener_sample_d["experiences"], target_decision_idx, orders = shuffle(listener_sample_d["experiences"]) if not retain_target: # The target_decision_idx is set to `nbr_experiences`: target_decision_idx = (self.nbr_distractors[self.mode]+1)*torch.ones(1).long() for k,v in listener_sample_d.items(): if k == "experiences": continue listener_sample_d[k], _, _ = shuffle(v, orders=orders) ##-------------------------------------------------------------- ##-------------------------------------------------------------- # Creating speaker's dictionnary: speaker_sample_d = copy.deepcopy(sample_d) if self.kwargs['observability'] == "partial": for k,v in speaker_sample_d.items(): speaker_sample_d[k] = v[:,0].unsqueeze(1) output_dict = {"target_decision_idx":target_decision_idx} for k,v in listener_sample_d.items(): output_dict[f"listener_{k}"] = v for k,v in speaker_sample_d.items(): output_dict[f"speaker_{k}"] = v return output_dict
{ "alphanum_fraction": 0.5893566322, "author": null, "avg_line_length": 46.6296296296, "converted": null, "ext": "py", "file": null, "hexsha": "06a8c1171b06a088d166de75775589964c991f62", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-01-06T08:42:24.000Z", "max_forks_repo_forks_event_min_datetime": "2020-12-20T23:00:23.000Z", "max_forks_repo_head_hexsha": "d1f9f14ed186292e22802781f4737e6747cd8c64", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Near32/SymbolicBehaviourBenchmark", "max_forks_repo_path": "symbolic_behaviour_benchmark/utils/dataset.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "d1f9f14ed186292e22802781f4737e6747cd8c64", "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": "Near32/SymbolicBehaviourBenchmark", "max_issues_repo_path": "symbolic_behaviour_benchmark/utils/dataset.py", "max_line_length": 124, "max_stars_count": 19, "max_stars_repo_head_hexsha": "d1f9f14ed186292e22802781f4737e6747cd8c64", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Near32/SymbolicBehaviourBenchmark", "max_stars_repo_path": "symbolic_behaviour_benchmark/utils/dataset.py", "max_stars_repo_stars_event_max_datetime": "2022-03-15T09:10:25.000Z", "max_stars_repo_stars_event_min_datetime": "2019-11-20T05:50:37.000Z", "num_tokens": 1836, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 8813 }
# -*- coding: utf-8 -*- r""" Checks for FES """ from . import CythonFeature, PythonModule TEST_CODE = """ # disutils: libraries=fes from libc.stdint cimport uint64_t cdef extern from "<fes_interface.h>": ctypedef int (*solution_callback_t)(void *, uint64_t) void exhaustive_search_wrapper(int n, int n_eqs, int degree, int ***coeffs, solution_callback_t callback, void* callback_state, int verbose) solutions = 0 class InternalState: verbose = False sols = [] max_sols = 0 cdef int report_solution(void *_state, uint64_t i): global solutions solutions += 1 return 0 sig_on() cdef int ***coeffs = <int ***> sig_calloc(1, sizeof(int **)) coeffs[0] = <int **> sig_calloc(3, sizeof(int *)) coeffs[0][0] = <int *> sig_calloc(1, sizeof(int)) coeffs[0][1] = <int *> sig_calloc(2, sizeof(int)) coeffs[0][2] = <int *> sig_calloc(1, sizeof(int)) coeffs[0][2][0] = 1 # x*y = 0 internal_state = InternalState() exhaustive_search_wrapper(2, 1, 2, coeffs, report_solution, <void *>internal_state, 0) sig_free(coeffs[0][2]) sig_free(coeffs[0][1]) sig_free(coeffs[0][0]) sig_free(coeffs[0]) sig_free(coeffs) sig_off() if solutions != 3: raise AssertionError("libFES did not find three solutions for x*y = 0") """ class LibFESLibrary(CythonFeature): r""" A :class:`Feature` which describes whether the FES library is present and functional. EXAMPLES:: sage: from sage.features.fes import LibFESLibrary sage: LibFESLibrary().require() # optional: fes """ def __init__(self): r""" TESTS:: sage: from sage.features.fes import LibFESLibrary sage: isinstance(LibFESLibrary(), LibFESLibrary) True """ CythonFeature.__init__(self, "LibFES", test_code=TEST_CODE, spkg="fes", url="http://www.lifl.fr/~bouillag/fes/") class LibFES(PythonModule): r""" A :class:`Feature` which describes whether the :mod:`sage.libs.fes` module has been enabled for this build of Sage and is functional. EXAMPLES:: sage: from sage.features.fes import LibFES sage: LibFES().require() # optional: fes """ def __init__(self): r""" TESTS:: sage: from sage.features.fes import LibFES sage: isinstance(LibFES(), LibFES) True """ PythonModule.__init__(self, "sage.libs.fes", spkg="fes", url="http://www.lifl.fr/~bouillag/fes/")
{ "alphanum_fraction": 0.6448979592, "author": null, "avg_line_length": 26.9230769231, "converted": null, "ext": "py", "file": null, "hexsha": "fe7c60df85b3b458338f3598e87b3690dde86e89", "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:22:38.000Z", "max_forks_repo_forks_event_min_datetime": "2020-07-23T10:22:38.000Z", "max_forks_repo_head_hexsha": "2d495be78e0bdc7a0a635454290b27bb4f5f70f0", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "bopopescu/sage", "max_forks_repo_path": "src/sage/features/fes.py", "max_issues_count": 2, "max_issues_repo_head_hexsha": "2d495be78e0bdc7a0a635454290b27bb4f5f70f0", "max_issues_repo_issues_event_max_datetime": "2020-07-23T12:13:30.000Z", "max_issues_repo_issues_event_min_datetime": "2018-10-30T13:40:20.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "bopopescu/sage", "max_issues_repo_path": "src/sage/features/fes.py", "max_line_length": 144, "max_stars_count": 3, "max_stars_repo_head_hexsha": "2d495be78e0bdc7a0a635454290b27bb4f5f70f0", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "bopopescu/sage", "max_stars_repo_path": "src/sage/features/fes.py", "max_stars_repo_stars_event_max_datetime": "2019-11-08T12:31:43.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-15T13:48:24.000Z", "num_tokens": 711, "path": null, "reason": "from sage", "repo": null, "save_path": null, "sha": null, "size": 2450 }
// Copyright 2017, 2018 Peter Dimov. // Distributed under the Boost Software License, Version 1.0. #include <boost/hash2/fnv1a.hpp> #include <boost/hash2/siphash.hpp> #include <boost/hash2/xxhash.hpp> #include <boost/hash2/spooky2.hpp> #include <boost/hash2/md5.hpp> #include <boost/hash2/sha1.hpp> #include <boost/hash2/murmur3.hpp> #include <boost/hash2/hash_append.hpp> #include <boost/hash2/get_integral_result.hpp> #include <boost/chrono.hpp> #include <boost/core/demangle.hpp> #include <typeinfo> #include <cstddef> #include <cstdio> #include <string> #include <limits> #include <cmath> template<class R, class H> void test_( int N ) { typedef boost::chrono::steady_clock clock_type; clock_type::time_point t1 = clock_type::now(); double r = 0; H h; for( int i = 0; i < N; ++i ) { using boost::hash2::get_integral_result; r += get_integral_result<R>( h.result() ); r += 0.5; } clock_type::time_point t2 = clock_type::now(); long long ms = boost::chrono::duration_cast<boost::chrono::milliseconds>( t2 - t1 ).count(); r /= N; // Standard deviation of Bates distribution double stddev = static_cast<double>( std::numeric_limits<R>::max() ) - static_cast<double>( std::numeric_limits<R>::min() ) / std::sqrt( 12.0 * N ); r /= stddev; printf( "%s: r=%e, %lld ms\n", boost::core::demangle( typeid(H).name() ).c_str(), r, ms ); } template<class R> void test( int N ) { printf( "Integral result type `%s`:\n\n", boost::core::demangle( typeid(R).name() ).c_str() ); test_<R, boost::hash2::fnv1a_32>( N ); test_<R, boost::hash2::fnv1a_64>( N ); test_<R, boost::hash2::murmur3_32>( N ); test_<R, boost::hash2::murmur3_128>( N ); test_<R, boost::hash2::xxhash_32>( N ); test_<R, boost::hash2::xxhash_64>( N ); test_<R, boost::hash2::spooky2_128>( N ); test_<R, boost::hash2::siphash_32>( N ); test_<R, boost::hash2::siphash_64>( N ); test_<R, boost::hash2::md5_128>( N ); test_<R, boost::hash2::sha1_160>( N ); test_<R, boost::hash2::hmac_md5_128>( N ); test_<R, boost::hash2::hmac_sha1_160>( N ); puts( "" ); } int main() { int const N = 64 * 1024 * 1024; test<signed char>( N ); test<short>( N ); test<int>( N ); test<long long>( N ); }
{ "alphanum_fraction": 0.6275951557, "author": null, "avg_line_length": 27.5238095238, "converted": null, "ext": "cpp", "file": null, "hexsha": "bd7a7d30b7e9e290c7b7bac1bd093db49ad1cb23", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-04-07T17:07:06.000Z", "max_forks_repo_forks_event_min_datetime": "2018-01-06T18:23:19.000Z", "max_forks_repo_head_hexsha": "9e3fc2a72c6aeb4e2de7daad7ca34a3aaeaa4217", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "pdimov/hash2", "max_forks_repo_path": "benchmark/average.cpp", "max_issues_count": 1, "max_issues_repo_head_hexsha": "9e3fc2a72c6aeb4e2de7daad7ca34a3aaeaa4217", "max_issues_repo_issues_event_max_datetime": "2018-05-27T13:11:12.000Z", "max_issues_repo_issues_event_min_datetime": "2018-04-27T10:46:35.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "pdimov/hash2", "max_issues_repo_path": "benchmark/average.cpp", "max_line_length": 152, "max_stars_count": 9, "max_stars_repo_head_hexsha": "9e3fc2a72c6aeb4e2de7daad7ca34a3aaeaa4217", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "pdimov/hash2", "max_stars_repo_path": "benchmark/average.cpp", "max_stars_repo_stars_event_max_datetime": "2021-02-03T12:30:22.000Z", "max_stars_repo_stars_event_min_datetime": "2018-01-06T18:23:15.000Z", "num_tokens": 728, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2312 }
#!/usr/bin/env # -*- coding: utf-8 -*- """ @author: ludvigolsen """ import pandas as pd import numpy as np import warnings from utipy.utils.convert_to_df import convert_to_df def polynomializer(data, degree=2, suffix='_poly', exclude=[], copy=True): """ Creates polymonial features. Adds suffix with information on which degree a column represents. Parameters ---------- data : pd.DataFrame The data to add polynomial features to. degree : int How many degrees to add. suffix: str Text between column name and degree number. Added to the new columns. exclude: list List of column names to exclude, e.g. non-numeric columns. Returns ------- pd.DataFrame with added polynomial features / columns. Examples -------- Uncomment code to run. # df = pd.DataFrame({'a': [1,2,3,4,5], # 'b': [2,3,4,5,6], # 'c': ['a','b','c','d','e']}) # polynomializer(df, degree = 3, exclude = ['c']) """ # Create copy of data if copy: data = data.copy() data, _ = convert_to_df(data) if exclude != []: cols_include = [c for c in data.columns if c not in exclude] data_include = data.filter(items=cols_include) else: data_include = data try: # Create dataframes with exponential columns polynomialized = [data_include ** deg for deg in range(degree + 1)[1:]] except: # This exception is most likely seen # because a column in data_include is NOT numeric. # So we exclude non-numeric columns, warn the user # and try again. numeric_data = data_include.select_dtypes(include=[np.number]) # Get excluded columns and add to exclude auto_excluded = [ i for i in data_include.columns if i not in numeric_data.columns ] exclude = np.concatenate([exclude, auto_excluded]) if len(auto_excluded) != 0: warnings.warn( "Excluded {} non-numeric columns.".format(len(auto_excluded))) try: # Create dataframes with exponential columns polynomialized = [numeric_data ** deg for deg in range(degree + 1)[1:]] except Exception as e: print("Something went wrong when creating polynomials.") raise e else: print("Something went wrong when creating polynomials.") raise # Function for adding suffix to column names def suffixicate(df, deg): if deg != 0: return df.add_suffix("{}{}".format(suffix, deg + 1)) return df # Add suffices to dataframes polynomialized = map( lambda df, deg: suffixicate(df, deg), polynomialized, range(degree) ) # Combine dataframes polynomialized = pd.concat(polynomialized, axis=1) # Combine processed data with excluded data data_all = pd.concat([data.filter(items=exclude), polynomialized], axis=1) # Reorder # First get all the new column names new_cols = [c for c in polynomialized.columns if c not in data.columns] # Append old and new column names all_columns_sorted = np.append(data.columns, new_cols) # Reorder dataframe data_ordered = data_all.filter(items=all_columns_sorted) return data_ordered
{ "alphanum_fraction": 0.5937948865, "author": null, "avg_line_length": 27.4094488189, "converted": null, "ext": "py", "file": null, "hexsha": "fac884fe9f941e6c6161b420de7d18734b5b9e60", "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": "c287f7eed15b3591118bba49ecdfc2b2605f59a0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LudvigOlsen/utipy", "max_forks_repo_path": "utipy/pandas/polynomializer.py", "max_issues_count": 1, "max_issues_repo_head_hexsha": "c287f7eed15b3591118bba49ecdfc2b2605f59a0", "max_issues_repo_issues_event_max_datetime": "2022-02-16T15:24:33.000Z", "max_issues_repo_issues_event_min_datetime": "2022-02-16T15:24:33.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "LudvigOlsen/utipy", "max_issues_repo_path": "utipy/pandas/polynomializer.py", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "c287f7eed15b3591118bba49ecdfc2b2605f59a0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LudvigOlsen/utipy", "max_stars_repo_path": "utipy/pandas/polynomializer.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 787, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 3481 }
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # import argparse import os import h5py import numpy as np import scipy import scipy.io.wavfile import librosa parser = argparse.ArgumentParser() # Input parser.add_argument('--input-wavs', default='wavs', type=str, help='Path to folder with wavs to process.') parser.add_argument('--input-features', default='features', type=str, help='Path to folder with mels to process.') # Settings parser.add_argument('--compute-features', action='store_true', default=False, help='Compute features.') parser.add_argument('--window', default=0.025, type=float, help='Window size (s).') parser.add_argument('--stride', default=0.01, type=float, help='Window stride (s).') parser.add_argument('--num-mels', default=64, type=int, help='Number of Mel coefficients.') parser.add_argument('--astype', default='float32', type=str, help='Data type for storage.') parser.add_argument('--pack-features', action='store_true', default=False, help='Pack features.') parser.add_argument('--compressed', action='store_true', default=False, help='Compress features.') # Output parser.add_argument('--output-features', default='features', type=str, help='Path to folder with processed features.') parser.add_argument('--output-file', default='features.hdf5', type=str, help='Path to file with processed features.') def compute_features(args): """ Compute MFSCs for all audio wav files in a given directory. """ print('Computing features...') if not os.path.isdir(args.output_features): os.makedirs(args.output_features) lst_wavs = os.listdir(args.input_wavs) lst_wavs = [e[:-4] for e in lst_wavs if e.endswith('.wav')] counter = 0 for i in lst_wavs: try: fs, audio = scipy.io.wavfile.read(os.path.join(args.input_wavs, i + '.wav')) mfsc = librosa.feature.melspectrogram(y=audio.astype(float), sr=fs, n_fft=int(fs * args.window), n_mels=args.num_mels, hop_length=int(fs * args.stride), power=1) mfsc = librosa.power_to_db(mfsc, ref=np.max).T.astype(args.astype) np.save(os.path.join(args.output_features, i), mfsc) except Exception: print('Error processing: ' + str(i)) counter += 1 if counter % 1000 == 0: print('Finished processing: ' + str(counter) + ' files.') def pack_features(args): """ Pack all npy MFSCs in a given directory into a single hdf file. """ print('Packing features...') lst_npys = os.listdir(args.input_features) lst_npys = [e[:-4] for e in lst_npys if e.endswith('.npy')] counter = 0 # Variables for Welford’s mean and variance n, mean, v = 0, np.zeros(args.num_mels), np.zeros(args.num_mels) kwargs = {'compression': 'gzip', 'compression_opts': 9} if args.compressed else {} with h5py.File(args.output_file, 'w') as f: for i in lst_npys: mfsc = np.load(os.path.join(args.output_features, i + '.npy')) f.create_dataset(i, data=mfsc, dtype=args.astype, **kwargs) for w in range(mfsc.shape[0]): n += 1 delta = mfsc[w] - mean mean += delta / n v += (mfsc[w] - mean) * delta counter += 1 if counter % 1000 == 0: print('Finished packing: ' + str(counter) + ' files.') var = v / (n - 1) stddev = np.sqrt(var) f.create_dataset('mean', data=mean.astype(args.astype), dtype=args.astype, **kwargs) f.create_dataset('variance', data=var.astype(args.astype), dtype=args.astype, **kwargs) f.create_dataset('stddev', data=stddev.astype(args.astype), dtype=args.astype, **kwargs) def main(args): if args.compute_features: compute_features(args) if args.pack_features: pack_features(args) if not args.compute_features and not args.pack_features: print('P.S. I didnt do anything. Both compute and pack features are false.') if __name__ == "__main__": args = parser.parse_args() main(args) print('Success!')
{ "alphanum_fraction": 0.5522655008, "author": null, "avg_line_length": 37, "converted": null, "ext": "py", "file": null, "hexsha": "7ec972e2d6ae3f3db6d5f7f27dd6ec1d9739a87d", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 11, "max_forks_repo_forks_event_max_datetime": "2021-11-06T16:19:53.000Z", "max_forks_repo_forks_event_min_datetime": "2020-01-04T19:37:24.000Z", "max_forks_repo_head_hexsha": "bf96ad3bffdd80834e94edffe796534e6290e533", "max_forks_repo_licenses": [ "CC-BY-4.0" ], "max_forks_repo_name": "facebookresearch/daqa", "max_forks_repo_path": "daqa-mod/compute_audio_features.py", "max_issues_count": 1, "max_issues_repo_head_hexsha": "bf96ad3bffdd80834e94edffe796534e6290e533", "max_issues_repo_issues_event_max_datetime": "2021-04-22T16:03:12.000Z", "max_issues_repo_issues_event_min_datetime": "2021-04-15T20:25:50.000Z", "max_issues_repo_licenses": [ "CC-BY-4.0" ], "max_issues_repo_name": "facebookresearch/daqa", "max_issues_repo_path": "daqa-mod/compute_audio_features.py", "max_line_length": 86, "max_stars_count": 19, "max_stars_repo_head_hexsha": "bf96ad3bffdd80834e94edffe796534e6290e533", "max_stars_repo_licenses": [ "CC-BY-4.0" ], "max_stars_repo_name": "facebookresearch/daqa", "max_stars_repo_path": "daqa-mod/compute_audio_features.py", "max_stars_repo_stars_event_max_datetime": "2022-03-31T09:21:05.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-30T19:00:48.000Z", "num_tokens": 1073, "path": null, "reason": "import numpy,import scipy", "repo": null, "save_path": null, "sha": null, "size": 5032 }
import numpy as np from binning import rebin from expandimage import expand_image def div_free_solution(mag, scale, mirror=0, no_ring=0): """Double precision version of the routine suggested by B. J. LaBonte. It calculates the solution a satisfying the gauge conditions of Chae (2001) by means of the fast Fourier transform Features -------- Pads the original image with a mirror image of the original if mirror is set Programmers ---------- B. J. LaBonte & M. K. Georgoulis (JHU/APL, 10/13/05) """ res = mag.shape id1 = res[0] id2 = res[1] mag_ref = mag # Pad the image with zeroes# put image in the middle if no_ring == 0: for m in range(1, 16): if 2.0 ** m <= id1 < 2.0 ** (m + 1): enx = int(np.fix(2.0 ** float(m + 1))) for m in range(1, 16): if 2.0 ** m <= id2 < 2.0 ** (m + 1): eny = int(np.fix(2.0 ** (m + 1))) if mirror != 0: mag, stx, sty = expand_image(mag_ref, enx - id1, eny - id2, mirror=mirror) else: mag, stx, sty = expand_image(mag_ref, enx - id1, eny - id2) else: stx = 0 sty = 0 # Get the basic transform nx = mag[:, 0].size ny = mag[0, :].size ftm = np.fft.fft2(mag, norm='forward') # Multiply by i ftr = ftm * complex(0, -1) # Generate wavenumber images kx = np.array(np.arange(nx)).repeat(ny).reshape(nx, ny) - np.float(nx - 2) / 2.0 kx = np.roll(kx, -int((nx - 2) / 2), axis=0) kx = -kx * 2. * np.pi / np.float(nx) ky = np.transpose(np.array(np.arange(ny)).repeat(nx).reshape(ny, nx)) - np.float(ny - 2) / 2. ky = np.roll(ky, -int((ny - 2) / 2), axis=1) ky = -ky * 2. * np.pi / np.float(ny) k2 = kx ** 2 + ky ** 2 k2[0, 0] = 1. # Get vector potential from inverse transform apx = (np.fft.ifft2((ky / k2) * ftr, norm='forward')).real apy = (np.fft.ifft2((-kx / k2) * ftr, norm='forward')).real a = np.zeros((nx, ny, 2)) a[:, :, 0] = apx a[:, :, 1] = apy a = a * scale if no_ring == 0: a = np.zeros((apx[int(stx):int(stx + id1), int(sty):int(sty + id2)].shape[0], apx[int(stx):int(stx + id1), int(sty):int(sty + id2)].shape[1], 2)) a[:, :, 0] = apx[int(stx):int(stx + id1), int(sty):int(sty + id2)] a[:, :, 1] = apy[int(stx):int(stx + id1), int(sty):int(sty + id2)] a = a * scale return a
{ "alphanum_fraction": 0.5273390036, "author": null, "avg_line_length": 30.8625, "converted": null, "ext": "py", "file": null, "hexsha": "6395fd209a695f6b18fcb7e6047ef1cfdf7d9b0d", "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": "9b6f4049c819d758bca6e524a80c6d7a09e7b179", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "LuisLinan/helicity_fluxes", "max_forks_repo_path": "divfree.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "9b6f4049c819d758bca6e524a80c6d7a09e7b179", "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": "LuisLinan/helicity_fluxes", "max_issues_repo_path": "divfree.py", "max_line_length": 101, "max_stars_count": null, "max_stars_repo_head_hexsha": "9b6f4049c819d758bca6e524a80c6d7a09e7b179", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "LuisLinan/helicity_fluxes", "max_stars_repo_path": "divfree.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 884, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 2469 }
# -*- coding: utf-8 -*- """TF2.0 ANN Regression Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1XDvj0pjF_Sc1SVSbAw6zv1RcnLlqOo2u """ # Commented out IPython magic to ensure Python compatibility. # Install TensorFlow from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np import tensorflow as tf print(tf.__version__) # Other imports # Make the dataset N = 1000 X = np.random.random((N, 2)) * 6 - 3 # uniformly distributed between (-3, +3) Y = np.cos(2*X[:, 0]) + np.cos(3*X[:, 1]) """This implements the function: $$ y = \cos(2x_1) + cos(3x_2) $$ """ # Plot it fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(X[:, 0], X[:, 1], Y) # plt.show() # Build the model model = tf.keras.models.Sequential([ tf.keras.layers.Dense(128, input_shape=(2,), activation='relu'), tf.keras.layers.Dense(1) ]) # Compile and fit opt = tf.keras.optimizers.Adam(0.01) model.compile(optimizer=opt, loss='mse') r = model.fit(X, Y, epochs=100) # Plot the loss plt.plot(r.history['loss'], label='loss') # Plot the prediction surface fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(X[:, 0], X[:, 1], Y) # surface plot line = np.linspace(-3, 3, 50) xx, yy = np.meshgrid(line, line) Xgrid = np.vstack((xx.flatten(), yy.flatten())).T Yhat = model.predict(Xgrid).flatten() ax.plot_trisurf(Xgrid[:, 0], Xgrid[:, 1], Yhat, linewidth=0.2, antialiased=True) plt.show() # Can it extrapolate? # Plot the prediction surface fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(X[:, 0], X[:, 1], Y) # surface plot line = np.linspace(-5, 5, 50) xx, yy = np.meshgrid(line, line) Xgrid = np.vstack((xx.flatten(), yy.flatten())).T Yhat = model.predict(Xgrid).flatten() ax.plot_trisurf(Xgrid[:, 0], Xgrid[:, 1], Yhat, linewidth=0.2, antialiased=True) plt.show()
{ "alphanum_fraction": 0.6804177546, "author": null, "avg_line_length": 24.8701298701, "converted": null, "ext": "py", "file": null, "hexsha": "07943181f72284d7cd1603dfec174adbf0b04af4", "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": "70c4f993c68ce5030e9df0edd15004bbb9fc71e7", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "talk2sunil83/UpgradLearning", "max_forks_repo_path": "zExtraLearning/MLPrep/tf2.0/NbExtracts/04tf2_0_ann_regression.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "70c4f993c68ce5030e9df0edd15004bbb9fc71e7", "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": "talk2sunil83/UpgradLearning", "max_issues_repo_path": "zExtraLearning/MLPrep/tf2.0/NbExtracts/04tf2_0_ann_regression.py", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "70c4f993c68ce5030e9df0edd15004bbb9fc71e7", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "talk2sunil83/UpgradLearning", "max_stars_repo_path": "zExtraLearning/MLPrep/tf2.0/NbExtracts/04tf2_0_ann_regression.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 599, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1915 }
[STATEMENT] lemma observable2_equiv_observable: "observable2 ob P = observable ob P" [PROOF STATE] proof (prove) goal (1 subgoal): 1. observable2 ob P = observable ob P [PROOF STEP] by (unfold observable_def observable2_def) (auto)
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "Key_Agreement_Strong_Adversaries_Refinement", "hexsha": null, "include": null, "lang": null, "length": 1, "llama_tokens": 81, "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 Test using GraphIO.EdgeList using GraphIO.EdgeList: IntEdgeListFormat @testset "EdgeList" begin for g in values(digraphs) readback_test(EdgeListFormat(), g) readback_test(IntEdgeListFormat(), g) end end
{ "alphanum_fraction": 0.7276595745, "author": null, "avg_line_length": 19.5833333333, "converted": null, "ext": "jl", "file": null, "hexsha": "d4fb0b80cfdc28917802af959cb1b8beb9c3cb29", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2022-02-08T22:43:02.000Z", "max_forks_repo_forks_event_min_datetime": "2017-04-20T23:22:58.000Z", "max_forks_repo_head_hexsha": "fbde6c328a08a7c5819dc3acc85ac3bf55707abe", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "sbromberger/GraphIO.jl", "max_forks_repo_path": "test/Edgelist/runtests.jl", "max_issues_count": 40, "max_issues_repo_head_hexsha": "fbde6c328a08a7c5819dc3acc85ac3bf55707abe", "max_issues_repo_issues_event_max_datetime": "2022-03-04T14:02:34.000Z", "max_issues_repo_issues_event_min_datetime": "2017-04-19T23:57:59.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "sbromberger/GraphIO.jl", "max_issues_repo_path": "test/Edgelist/runtests.jl", "max_line_length": 45, "max_stars_count": 49, "max_stars_repo_head_hexsha": "fbde6c328a08a7c5819dc3acc85ac3bf55707abe", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "sbromberger/GraphIO.jl", "max_stars_repo_path": "test/Edgelist/runtests.jl", "max_stars_repo_stars_event_max_datetime": "2022-03-10T12:53:23.000Z", "max_stars_repo_stars_event_min_datetime": "2017-04-20T00:04:56.000Z", "num_tokens": 66, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 235 }
# -*- coding: utf-8 -*- # ========================================================================== # # Copyright 2018-2019 Remi Cresson (IRSTEA) # Copyright 2020 Remi Cresson (INRAE) # # 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.txt # # 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 gdal import numpy as np import tensorflow.compat.v1 as tf from deprecated import deprecated tf.disable_v2_behavior() def read_image_as_np(filename, as_patches=False): """ Read an image as numpy array. @param filename File name of patches image @param as_patches True if the image must be read as patches @return 4D numpy array [batch, h, w, c] """ # Open a GDAL dataset ds = gdal.Open(filename) if ds is None: raise Exception("Unable to open file {}".format(filename)) # Raster infos n_bands = ds.RasterCount szx = ds.RasterXSize szy = ds.RasterYSize # Raster array myarray = ds.ReadAsArray() # Re-order bands (when there is > 1 band) if (len(myarray.shape) == 3): axes = (1, 2, 0) myarray = np.transpose(myarray, axes=axes) if (as_patches): n = int(szy / szx) return myarray.reshape((n, szx, szx, n_bands)) return myarray.reshape((1, szy, szx, n_bands)) def create_savedmodel(sess, inputs, outputs, directory): """ Create a SavedModel @param sess TF session @param inputs List of inputs names (e.g. ["x_cnn_1:0", "x_cnn_2:0"]) @param outputs List of outputs names (e.g. ["prediction:0", "features:0"]) @param directory Path for the generated SavedModel """ print("Create a SavedModel in " + directory) graph = tf.compat.v1.get_default_graph() inputs_names = {i: graph.get_tensor_by_name(i) for i in inputs} outputs_names = {o: graph.get_tensor_by_name(o) for o in outputs} tf.compat.v1.saved_model.simple_save(sess, directory, inputs=inputs_names, outputs=outputs_names) def ckpt_to_savedmodel(ckpt_path, inputs, outputs, savedmodel_path, clear_devices=False): """ Read a Checkpoint and build a SavedModel @param ckpt_path Path to the checkpoint file (without the ".meta" extension) @param inputs List of inputs names (e.g. ["x_cnn_1:0", "x_cnn_2:0"]) @param outputs List of outputs names (e.g. ["prediction:0", "features:0"]) @param savedmodel_path Path for the generated SavedModel @param clear_devices Clear TF devices positionning (True/False) """ tf.compat.v1.reset_default_graph() with tf.compat.v1.Session() as sess: # Restore variables from disk model_saver = tf.compat.v1.train.import_meta_graph(ckpt_path + ".meta", clear_devices=clear_devices) model_saver.restore(sess, ckpt_path) # Create a SavedModel create_savedmodel(sess, inputs=inputs, outputs=outputs, directory=savedmodel_path) @deprecated def read_samples(filename): """ Read a patches image. @param filename: raster file name """ return read_image_as_np(filename, as_patches=True) @deprecated def CreateSavedModel(sess, inputs, outputs, directory): """ Create a SavedModel @param sess TF session @param inputs List of inputs names (e.g. ["x_cnn_1:0", "x_cnn_2:0"]) @param outputs List of outputs names (e.g. ["prediction:0", "features:0"]) @param directory Path for the generated SavedModel """ create_savedmodel(sess, inputs, outputs, directory) @deprecated def CheckpointToSavedModel(ckpt_path, inputs, outputs, savedmodel_path, clear_devices=False): """ Read a Checkpoint and build a SavedModel @param ckpt_path Path to the checkpoint file (without the ".meta" extension) @param inputs List of inputs names (e.g. ["x_cnn_1:0", "x_cnn_2:0"]) @param outputs List of outputs names (e.g. ["prediction:0", "features:0"]) @param savedmodel_path Path for the generated SavedModel @param clear_devices Clear TF devices positionning (True/False) """ ckpt_to_savedmodel(ckpt_path, inputs, outputs, savedmodel_path, clear_devices)
{ "alphanum_fraction": 0.6649484536, "author": null, "avg_line_length": 37.8536585366, "converted": null, "ext": "py", "file": null, "hexsha": "fe4c5deaedb4095275f7161143a23ad968b10392", "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": "3b84497ab0df767569a32d6457997c8183867bcc", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "Doctor-Who/otbtf", "max_forks_repo_path": "python/tricks.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "3b84497ab0df767569a32d6457997c8183867bcc", "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": "Doctor-Who/otbtf", "max_issues_repo_path": "python/tricks.py", "max_line_length": 108, "max_stars_count": null, "max_stars_repo_head_hexsha": "3b84497ab0df767569a32d6457997c8183867bcc", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "Doctor-Who/otbtf", "max_stars_repo_path": "python/tricks.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1182, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 4656 }
from abc import ABC, abstractmethod import cv2 import numpy as np import pandas as pd from skimage.draw import line as raster_line from .suite import Suite, project_points, compute_pose_error # delete me import matplotlib.pyplot as plt def compute_3d_coordinates(oc, pts, model): if not len(pts): return np.empty((0, 3)) colors = oc[pts[:, 1], pts[:, 0]] if np.any(colors[:, -1] != 255): raise NotImplementedError("The object coordinate masks have issues") return colors[:, :3] * model.size / 255 + model.min def draw_lines(lines, img, color): paths = np.concatenate( [ np.stack( raster_line(line[0, 1], line[0, 0], line[1, 1], line[1, 0]), axis=-1 ) for line in lines ] ) out = img.copy() out[paths[:, 0], paths[:, 1]] = color return out def extract_sift_keypoints(rgb): gray = cv2.cvtColor(rgb[:, :, :3], cv2.COLOR_RGB2GRAY) sift = cv2.xfeatures2d.SIFT_create() detections = sift.detect(gray, None) # store unique keypoints keypoints = np.unique( np.array([kp.pt for kp in detections]).astype(np.uint32), axis=0 ) return keypoints def extract_line_segments(rgb): gray = cv2.cvtColor(rgb[:, :, :3], cv2.COLOR_RGB2GRAY) ld = cv2.line_descriptor.LSDDetector_createLSDDetector() keylines = ld.detect(gray, 1, 1) paths = [] idx = [] for i, keyline in enumerate(keylines): start = np.round(keyline.getStartPoint()).astype(int) end = np.round(keyline.getEndPoint()).astype(int) path = np.stack(raster_line(start[1], start[0], end[1], end[0]), axis=-1) paths.append(path) idx.append(np.full(len(path), i)) paths = np.concatenate(paths) idx = np.concatenate(idx) # ensure max bounds are not overstepped max_bound = np.array(rgb.shape[:2]) - 1 paths = np.minimum(paths, max_bound) return paths, idx def extract_point_correspondences(oid, frame, keypoints, model): # filter keypoints to object mask and object coordinate data pts_2d = keypoints[ np.logical_and( frame["mask"][keypoints[:, 1], keypoints[:, 0]] == oid, frame["oc"][keypoints[:, 1], keypoints[:, 0], -1] == 255, ) ] # objects get the corresponding object coordinates pts_3d = compute_3d_coordinates(frame["oc"], pts_2d, model) return pts_2d, pts_3d def extract_line_correspondences(oid, frame, lines, model): paths, idx = lines # prune line segments to masks. assume masks are convex mask = np.logical_and(frame["mask"] == oid, frame["oc"][:, :, -1] == 255) line_2d = [] for pid in range(idx[-1]): path = paths[idx == pid] if not np.any(mask[path[:, 0], path[:, 1]]): continue line = np.empty((2, 2), dtype=int) # clamp at start and at the end start, end = None, None for i, (r, c) in enumerate(path): if mask[r, c]: line[0] = (c, r) start = i break for i, (r, c) in enumerate(reversed(path)): if mask[r, c]: line[1] = (c, r) end = len(path) - i break # Reject very small segments if end - start < 5: continue line_2d.append(line) line_2d = np.array(line_2d) # array can cope with empty lists # # debug # img = draw_lines(line_2d, frame["rgb"], np.array([255, 255, 255], dtype=np.uint8)) # plt.imshow(img); plt.show() # # objects get the corresponding object coordinates line_3d = compute_3d_coordinates( frame["oc"], line_2d.reshape(-1, 2), model ).reshape(-1, 2, 3) return line_2d, line_3d class RealSuite(Suite, ABC): def __init__(self, methods, timed=True): super().__init__(methods, timed) self.data = None # dataset placeholder # Since each dataset has a different number of sequences, frames # objects per frames and even instance per objects, we need to # store everything in a flat array and store indexes for each # instance self.did = None # datasets self.sid = None # sequences self.fid = None # frames self.oid = None # objects def init_run(self, data): self.data = data self.results = { "angular": [], "translation": [], } if self.timed: self.results["time"] = [] # Initialize accumulators self.did = [] # datasets self.sid = [] # sequences self.fid = [] # frames self.oid = [] # objects @abstractmethod def extract_features(self, rgb): pass @abstractmethod def extract_correspondences(self, oid, frame, features, model): pass def run(self, data): self.init_run(data) # Can we print some progress statistics n_prog, i_prog = 0, 0 for ds in self.data: n_prog += len(ds) print("Progress: 0.00%", end="", flush=True) # Looping over datasets for did, ds in enumerate(self.data): # looping over sequences for sid, seq in enumerate(ds): # looping over frames for frame in seq: # extract features in each frame features = self.extract_features(frame["rgb"]) # Iterate through each object in frame for oid, pose in frame["poses"].items(): # plt.imsave(f'/tmp/images/{seq.name:02d}_{frame["id"]:04d}.m.png', frame["mask"]) # plt.imsave(f'/tmp/images/{seq.name:02d}_{frame["id"]:04d}.o.png', frame["oc"]) mmask = frame["mask"].astype(bool) moc = frame["oc"][:, :, -1] == 255 iou = np.sum(np.logical_and(mmask, moc)) / np.sum( np.logical_or(mmask, moc) ) # there are legit occlusion cases lower than 0.6 iou if iou < 0.5: error_msg = "IoU issues between mask and object coordinates" raise RuntimeError(error_msg) # extract correspondences correspondences = self.extract_correspondences( oid, frame, features, ds.models[str(oid)] ) # Pre allocate placeholders storing results nm = len(self.methods) ang_all = np.full(nm, np.nan) trans_all = np.full(nm, np.nan) time_all = np.full(nm, np.nan) groundtruth = (pose[:, :3], pose[:, -1]) for mid, method in enumerate(self.methods): # get a pose estimate (R, t), time_all[mid] = self.estimate_pose( method, groundtruth, ds.camera.K, **correspondences ) # Sanitize results if np.any(np.isnan(R)) or np.any(np.isnan(t)): continue # store error results in the object ang_all[mid], trans_all[mid] = compute_pose_error( groundtruth, (R, t) ) # let each method compute the pose compute pose self.did.append(did) self.sid.append(sid) self.fid.append(frame["id"]) self.oid.append(oid) self.results["angular"].append(ang_all) self.results["translation"].append(trans_all) if self.timed: self.results["time"].append(time_all) # progress only reported at frame level i_prog += 1 percent = i_prog * 100 / n_prog print(f"\rProgress: {percent:>6.2f}%", end="", flush=True) print("\rProgress: 100.00%", flush=True) # merge everything together self.did = np.array(self.did) self.sid = np.array(self.sid) self.fid = np.array(self.fid) self.oid = np.array(self.oid) self.results["angular"] = np.stack(self.results["angular"]) self.results["translation"] = np.stack(self.results["translation"]) if self.timed: self.results["time"] = np.stack(self.results["time"]) def _aggregate_results(self): # build tables for angular error, translation errors, timings and nan counts angular = [] translation = [] timings = [] nans = [] dids = [] sids = [] # filter out all nans good_mask = np.logical_not( np.logical_or.reduce(np.isnan(self.results["angular"]).T) ) # Looping over datasets for did, ds in enumerate(self.data): for sid, seq in enumerate(ds): dids.append(type(ds).__name__) # sids.append(str(seq.name)) sids.append(type(ds).seq_names[sid]) mask_with_nans = np.logical_and(self.did == did, self.sid == sid) mask = np.logical_and(mask_with_nans, good_mask) angular.append(np.nanmedian(self.results["angular"][mask], axis=0)) translation.append( np.nanmedian(self.results["translation"][mask], axis=0) ) nans.append( np.sum(np.isnan(self.results["angular"][mask_with_nans]), axis=0) ) if self.timed: timings.append(np.nanmean(self.results["time"][mask], axis=0)) # last row is over the entire data set angular.append(np.nanmedian(self.results["angular"][good_mask], axis=0)) translation.append(np.nanmedian(self.results["translation"][good_mask], axis=0)) nans.append(np.sum(np.isnan(self.results["angular"]), axis=0)) if self.timed: timings.append(np.nanmean(self.results["time"][good_mask], axis=0)) # dids.append("all") # sids.append("all") # Aggregate angular = np.stack(angular) translation = np.stack(translation) timings = np.stack(timings) nans = np.stack(nans) return angular, translation, timings, nans, dids, sids def print(self, mode=None): angular, translation, timings, nans, dids, sids = self._aggregate_results() # build pandas table for pretty rendering for data, name, scale in zip( [angular, translation, timings, nans], [ "Angular Error (°)", "Translation Error (%)", "Average Runtime (ms)", "NaN Counts", ], [1.0, 100.0, 1000.0, 1], ): print(name) df = pd.DataFrame( data * scale, index=[d + " " + s for d, s, in zip(dids, sids)] + ["All"], columns=[m.__name__ for m in self.methods], ) if mode is None or mode == "console": print(df, "\n") elif mode == "latex": print(df.to_latex(), "\n") else: raise RuntimeError("Unknown mode '" + str(mode) + "'") # Combined angle and translation print("Angular Error (°) / Translation Error (‰)") str_format = np.frompyfunc(lambda x: f"{np.round(x, 3):.3f}", 1, 1) data = str_format(np.stack([angular, translation], axis=-1) * (1.0, 1000.0)) if mode == "latex": # highlight the best bf_format = np.frompyfunc(lambda x: f"\\textbf{{{x}}}", 1, 1) best_angular = np.argmin(angular, axis=1) sidx = list(range(len(data))) data[sidx, best_angular, 0] = bf_format(data[sidx, best_angular, 0]) best_translation = np.argmin(translation, axis=1) # import pdb; pdb.set_trace() data[sidx, best_translation, 1] = bf_format(data[sidx, best_translation, 1]) data = data[:, :, 0] + " / " + data[:, :, 1] df = pd.DataFrame( data, index=[d[:4] + " " + s for d, s, in zip(dids, sids)] + ["All"], columns=[ m.__name__ + " \\textdegree/\\textperthousand" if mode == "latex" else " (° / ‰)" for m in self.methods ], ) if mode is None or mode == "console": print(df, "\n") elif mode == "latex": print(df.to_latex(escape=False), "\n") else: raise RuntimeError("Unknown mode '" + str(mode) + "'") class PnPReal(RealSuite): def extract_features(self, rgb): return extract_sift_keypoints(rgb) def extract_correspondences(self, oid, frame, keypoints, model): pts_2d, pts_3d = extract_point_correspondences(oid, frame, keypoints, model) return {"pts_2d": pts_2d, "pts_3d": pts_3d} class PnLReal(RealSuite): def extract_features(self, rgb): return extract_line_segments(rgb) def extract_correspondences(self, oid, frame, lines, model): line_2d, line_3d = extract_line_correspondences(oid, frame, lines, model) return {"line_2d": line_2d, "line_3d": line_3d} class PnPLReal(RealSuite): def extract_features(self, rgb): keypoints = extract_sift_keypoints(rgb) keylines = extract_line_segments(rgb) return keypoints, keylines def extract_correspondences(self, oid, frame, features, model): keypoints, keylines = features pts_2d, pts_3d = extract_point_correspondences(oid, frame, keypoints, model) line_2d, line_3d = extract_line_correspondences(oid, frame, keylines, model) return { "pts_2d": pts_2d, "pts_3d": pts_3d, "line_2d": line_2d, "line_3d": line_3d, }
{ "alphanum_fraction": 0.5314480741, "author": null, "avg_line_length": 34.1021377672, "converted": null, "ext": "py", "file": null, "hexsha": "7b772d5d721e31fea6c83206c3a9cd5fdde1ebcf", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 9, "max_forks_repo_forks_event_max_datetime": "2022-01-19T09:48:22.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-13T15:56:47.000Z", "max_forks_repo_head_hexsha": "eaa568594df0adcf0c70cc5288b24e5dc1fa9d2f", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "SergioRAgostinho/cvxpnpl", "max_forks_repo_path": "benchmarks/toolkit/suites/real.py", "max_issues_count": 6, "max_issues_repo_head_hexsha": "eaa568594df0adcf0c70cc5288b24e5dc1fa9d2f", "max_issues_repo_issues_event_max_datetime": "2021-06-29T13:56:22.000Z", "max_issues_repo_issues_event_min_datetime": "2019-05-08T17:03:54.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "SergioRAgostinho/cvxpnpl", "max_issues_repo_path": "benchmarks/toolkit/suites/real.py", "max_line_length": 106, "max_stars_count": 51, "max_stars_repo_head_hexsha": "eaa568594df0adcf0c70cc5288b24e5dc1fa9d2f", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "SergioRAgostinho/cvxpnpl", "max_stars_repo_path": "benchmarks/toolkit/suites/real.py", "max_stars_repo_stars_event_max_datetime": "2022-03-06T06:24:07.000Z", "max_stars_repo_stars_event_min_datetime": "2019-07-25T18:42:44.000Z", "num_tokens": 3394, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 14357 }
export Astrobee2D mutable struct Astrobee2D{T<:AbstractFloat} <: Robot mass::T J::T Jinv::T n_thrusters::Int s::T r::T hard_limit_vel::T hard_limit_accel::T hard_limit_ω::T hard_limit_α::T btCollisionObject xb::Vector{T} Jcollision end function Astrobee2D{T}() where T n_thrusters = 12 s = 0.5*0.305 # each side of cube is 30.5cm r = sqrt(2)*s # inflate to sphere # ground robot param: freeflyer/astrobee/config/worlds/granite.config mass = 14.4 hard_limit_vel = 0.20 hard_limit_accel = 0.02 hard_limit_ω = 10*π/180 hard_limit_α = 10*π/180 J = 0.1083 Jinv = inv(J) xb = [0.; 0.15; 0.] Jcollision = [] # btCollisionObject = BulletCollision.convex_hull_cylinder(SVector{3}(zeros(3)), SVector{3}(0.,0.,1.), r) btCollisionObjects = BulletCollision.BulletCollisionObjectPtr[] push!(btCollisionObjects, BulletCollision.convex_hull_cylinder(SVector{3}(zeros(3)), SVector{3}(0.,0.,1.), r)) push!(btCollisionObjects, BulletCollision.convex_hull_cylinder(SVector{3}(xb...), SVector{3}(0.,0.,1.), r)) btCollisionObject = BulletCollision.compound_collision_object(btCollisionObjects) # new astrobee instance return Astrobee2D{T}(mass, J, Jinv, n_thrusters, s, r, hard_limit_vel, hard_limit_accel, hard_limit_ω, hard_limit_α, btCollisionObject, xb, Jcollision) end Astrobee2D(::Type{T} = Float64; kwargs...) where {T} = Astrobee2D{T}(; kwargs...)
{ "alphanum_fraction": 0.7113620325, "author": null, "avg_line_length": 29.5208333333, "converted": null, "ext": "jl", "file": null, "hexsha": "5120fac29ea9a003423f9cc58ea4e953f8d08da5", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 18, "max_forks_repo_forks_event_max_datetime": "2022-03-09T10:17:09.000Z", "max_forks_repo_forks_event_min_datetime": "2019-05-07T21:08:47.000Z", "max_forks_repo_head_hexsha": "b5753959c2e232c4e91be3e73ec4a81470c703b1", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "schoelst/GuSTO.jl", "max_forks_repo_path": "src/robot/astrobee2D.jl", "max_issues_count": 6, "max_issues_repo_head_hexsha": "b5753959c2e232c4e91be3e73ec4a81470c703b1", "max_issues_repo_issues_event_max_datetime": "2019-09-27T23:30:56.000Z", "max_issues_repo_issues_event_min_datetime": "2019-07-13T01:04:23.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "schoelst/GuSTO.jl", "max_issues_repo_path": "src/robot/astrobee2D.jl", "max_line_length": 153, "max_stars_count": 39, "max_stars_repo_head_hexsha": "b5753959c2e232c4e91be3e73ec4a81470c703b1", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "schoelst/GuSTO.jl", "max_stars_repo_path": "src/robot/astrobee2D.jl", "max_stars_repo_stars_event_max_datetime": "2022-03-26T02:22:46.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-04T21:44:15.000Z", "num_tokens": 493, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 1417 }
[STATEMENT] lemma lzipWith_simps [simp]: "lzipWith\<cdot>f\<cdot>(x :@ xs)\<cdot>(y :@ ys) = f\<cdot>x\<cdot>y :@ lzipWith\<cdot>f\<cdot>xs\<cdot>ys" "lzipWith\<cdot>f\<cdot>(x :@ xs)\<cdot>lnil = lnil" "lzipWith\<cdot>f\<cdot>lnil\<cdot>(y :@ ys) = lnil" "lzipWith\<cdot>f\<cdot>lnil\<cdot>lnil = lnil" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (lzipWith\<cdot>f\<cdot>(x :@ xs)\<cdot>(y :@ ys) = f\<cdot>x\<cdot>y :@ lzipWith\<cdot>f\<cdot>xs\<cdot>ys &&& lzipWith\<cdot>f\<cdot>(x :@ xs)\<cdot>lnil = lnil) &&& lzipWith\<cdot>f\<cdot>lnil\<cdot>(y :@ ys) = lnil &&& lzipWith\<cdot>f\<cdot>lnil\<cdot>lnil = lnil [PROOF STEP] by fixrec_simp+
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "WorkerWrapper_LList", "hexsha": null, "include": null, "lang": null, "length": 1, "llama_tokens": 314, "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 }
#pragma once #include "iparam.h" #include "iparamlist.h" #include "iflag.h" #include "iarg.h" #include "iarglist.h" #include "icommand.h" #include "optioninfo.h" #include "format.h" #include <sfun/string_utils.h> #include <cmdlime/usageinfoformat.h> #include <gsl/gsl> #include <utility> #include <vector> #include <memory> #include <algorithm> #include <iomanip> namespace cmdlime::detail{ using namespace gsl; namespace str = sfun::string_utils; inline std::string adjustedToLineBreak(std::string line, std::string& text) { if (!text.empty() && !isspace(text.front())){ auto trimmedLine = str::trimFront(line); if (std::find_if(trimmedLine.begin(), trimmedLine.end(), [](auto ch){return std::isspace(ch);}) == trimmedLine.end()) return line; while(!isspace(line.back())){ text.insert(text.begin(), 1, line.back()); line.pop_back(); } } return line; } inline std::string popLine(std::string& text, std::size_t width, bool firstLine = false) { auto newLinePos = text.find('\n'); if (newLinePos != std::string::npos && newLinePos <= width){ auto line = text.substr(0, newLinePos); text.erase(text.begin(), text.begin() + static_cast<int>(newLinePos + 1)); if (!firstLine) line = str::trimFront(line); return line; } auto line = text.substr(0, width); if (text.size() < width) text.clear(); else text.erase(text.begin(), text.begin() + static_cast<int>(width)); if (!firstLine) line = str::trimFront(line); return adjustedToLineBreak(line, text); } template <typename T> inline std::vector<not_null<T*>> getParamsByOptionality(const std::vector<not_null<T*>>& params, bool isOptional) { auto result = std::vector<not_null<T*>>{}; std::copy_if(params.begin(), params.end(), std::back_inserter(result), [isOptional](auto param){return param->isOptional() == isOptional;}); return result; } template <typename T> const std::string& getName(T& option) { return option.info().name(); } template <typename T> const std::string& getType(T& option) { return option.info().type(); } template <typename T> const std::string& getDescription(T& option) { return option.info().description(); } template <FormatType formatType> class UsageInfoCreator{ public: UsageInfoCreator(std::string programName, UsageInfoFormat outputSettings, const std::vector<not_null<IParam*>>& params, const std::vector<not_null<IParamList*>>& paramLists, std::vector<not_null<IFlag*>> flags, std::vector<not_null<IArg*>> args, IArgList* argList, std::vector<not_null<ICommand*>> commands) : programName_(std::move(programName)) , params_(getParamsByOptionality(params, false)) , optionalParams_(getParamsByOptionality(params, true)) , paramLists_(getParamsByOptionality(paramLists, false)) , optionalParamLists_(getParamsByOptionality(paramLists, true)) , flags_(std::move(flags)) , args_(std::move(args)) , argList_(argList) , commands_(std::move(commands)) , outputSettings_(outputSettings) , maxOptionNameSize_(maxOptionNameLength() + outputSettings.columnsSpacing) { } std::string createDetailed() { return minimizedUsageInfo() + argsInfo() + paramsInfo() + paramListsInfo() + optionsInfo() + optionalParamListsInfo() + flagsInfo() + commandsInfo(); } std::string create() { return usageInfo(); } private: using OutputFormatter = typename Format<formatType>::outputFormatter; std::string usageInfo() { auto result = "Usage: " + programName_ + " "; if (!commands_.empty()) result += "[commands] "; for (auto arg : args_) result += OutputFormatter::argUsageName(*arg) + " "; for (auto param : params_) result += OutputFormatter::paramUsageName(*param) + " "; for (auto paramList : paramLists_) result += OutputFormatter::paramListUsageName(*paramList) + " "; for (auto param : optionalParams_) result += OutputFormatter::paramUsageName(*param) + " "; for (auto paramList : optionalParamLists_) result += OutputFormatter::paramListUsageName(*paramList) + " "; for (auto flag : flags_) result += OutputFormatter::flagUsageName(*flag) + " "; if (argList_) result += OutputFormatter::argListUsageName(*argList_); result += "\n"; return result; } std::string minimizedUsageInfo() { auto result = "Usage: " + programName_ + " "; if (!commands_.empty()) result += "[commands] "; for (auto arg : args_) result += OutputFormatter::argUsageName(*arg) + " "; for (auto param : params_) result += OutputFormatter::paramUsageName(*param) + " "; for (auto paramList : paramLists_) result += OutputFormatter::paramListUsageName(*paramList) + " "; if (!optionalParams_.empty() || !optionalParamLists_.empty()) result += "[params] "; if (!flags_.empty()) result += "[flags] "; if (argList_) result += OutputFormatter::argListUsageName(*argList_); result += "\n"; return result; } std::string paramsInfo() { auto result = std::string{"Parameters:\n"}; if (params_.empty()) return result; for (const auto& param : params_){ const auto name = OutputFormatter::paramDescriptionName(*param, outputSettings_.nameIndentation) + "\n"; result += makeConfigFieldInfo(name, getDescription(*param)); } return result; } std::string paramListsInfo() { auto result = std::string{}; if (paramLists_.empty()) return result; for (const auto paramList : paramLists_){ const auto name = OutputFormatter::paramListDescriptionName(*paramList, outputSettings_.nameIndentation) + "\n"; auto description = getDescription(*paramList); if (!description.empty()) description += "\n(multi-value)"; else description += "multi-value"; result += makeConfigFieldInfo(name, description); } return result; } std::string optionsInfo() { if (optionalParams_.empty()) return {}; auto result = std::string{}; for (const auto option : optionalParams_){ auto description = getDescription(*option); if (!description.empty()){ if (!option->defaultValue().empty()) description += "\n(optional, default: " + option->defaultValue() + ")"; else description += "\n(optional)"; } else{ if (!option->defaultValue().empty()) description += "optional, default: " + option->defaultValue(); else description += "optional"; } result += makeConfigFieldInfo(OutputFormatter::paramDescriptionName(*option, outputSettings_.nameIndentation) + "\n", description); } return result; } std::string optionalParamListsInfo() { if (optionalParamLists_.empty()) return {}; auto result = std::string{}; for (const auto option : optionalParamLists_){ auto description = getDescription(*option); if (!description.empty()){ description += "\n(multi-value, "; if (!option->defaultValue().empty()) description += "optional, default: " + option->defaultValue() + ")"; else description += "optional)"; } else{ description += "multi-value, "; if (!option->defaultValue().empty()) description += "optional, default: " + option->defaultValue(); else description += "optional"; } result += makeConfigFieldInfo(OutputFormatter::paramListDescriptionName(*option, outputSettings_.nameIndentation) + "\n", description); } return result; } std::string argsInfo() { if (args_.empty() && !argList_) return {}; auto result = std::string{"Arguments:\n"}; for (const auto arg : args_) result += makeConfigFieldInfo(OutputFormatter::argDescriptionName(*arg, outputSettings_.nameIndentation) + "\n", getDescription(*arg)); if (argList_){ auto description = getDescription(*argList_); if (!description.empty()){ description += "\n(multi-value"; if (argList_->isOptional()){ if (!argList_->defaultValue().empty()) description += ", optional, default: " + argList_->defaultValue() + ")"; else description += ", optional)"; } else description += ")"; } else{ description += "multi-value"; if (argList_->isOptional()){ if (!argList_->defaultValue().empty()) description += ", optional, default: " + argList_->defaultValue(); else description += ", optional"; } } result += makeConfigFieldInfo(OutputFormatter::argListDescriptionName(*argList_, outputSettings_.nameIndentation) + "\n", description); } return result; } std::string flagsInfo() { if (flags_.empty()) return {}; auto result = std::string{"Flags:\n"}; for (const auto flag : flags_) result += makeConfigFieldInfo(OutputFormatter::flagDescriptionName(*flag, outputSettings_.nameIndentation) + "\n", getDescription(*flag)); return result; } std::string commandsInfo() { if (commands_.empty()) return {}; auto result = std::string{"Commands:\n"}; for (const auto command : commands_){ auto nameStream = std::stringstream{}; if (outputSettings_.nameIndentation) nameStream << std::setw(outputSettings_.nameIndentation) << " "; nameStream << getName(*command) << " [options]"; result += makeConfigFieldInfo(nameStream.str(), getDescription(*command)); } return result; } int maxOptionNameLength() { auto length = 0; auto updateLength = [&length](std::string name) { auto firstLine = true; do { auto nameLine = popLine(name, 100, firstLine); length = std::max(length, static_cast<int>(nameLine.size())); firstLine = false; } while(!name.empty()); }; for (auto param : params_) updateLength(OutputFormatter::paramDescriptionName(*param, outputSettings_.nameIndentation)); for (auto option : optionalParams_) updateLength(OutputFormatter::paramDescriptionName(*option, outputSettings_.nameIndentation)); for (auto flag : flags_) updateLength(OutputFormatter::flagDescriptionName(*flag, outputSettings_.nameIndentation)); for (auto arg : args_) updateLength(OutputFormatter::argDescriptionName(*arg, outputSettings_.nameIndentation)); if (argList_) updateLength(OutputFormatter::argListDescriptionName(*argList_, outputSettings_.nameIndentation)); return length; } std::string makeConfigFieldInfo(std::string name, std::string description) { auto maxNameWidth = std::min(outputSettings_.maxNameColumnWidth, maxOptionNameSize_); const auto columnSeparatorWidth = 1; const auto leftColumnWidth = columnSeparatorWidth + maxNameWidth; const auto rightColumnWidth = static_cast<std::size_t>(outputSettings_.terminalWidth - leftColumnWidth); const auto descriptionWidth = rightColumnWidth - 2; auto stream = std::stringstream{}; auto firstLine = true; while (!name.empty()){ auto nameLine = popLine(name, static_cast<std::size_t>(maxNameWidth), firstLine); const auto descriptionLine = popLine(description, descriptionWidth, firstLine); if (firstLine) stream << std::setw(maxNameWidth) << std::left << nameLine << " " << descriptionLine << std::endl; else stream << std::setw(maxNameWidth) << std::left << nameLine << " " << descriptionLine << std::endl; firstLine = false; } while(!description.empty()){ auto descriptionLine = popLine(description, descriptionWidth); stream << std::setw(leftColumnWidth) << " " << " " << descriptionLine << std::endl; } return stream.str(); } private: std::string programName_; std::vector<not_null<IParam*>> params_; std::vector<not_null<IParam*>> optionalParams_; std::vector<not_null<IParamList*>> paramLists_; std::vector<not_null<IParamList*>> optionalParamLists_; std::vector<not_null<IFlag*>> flags_; std::vector<not_null<IArg*>> args_; IArgList* argList_; std::vector<not_null<ICommand*>> commands_; UsageInfoFormat outputSettings_; int maxOptionNameSize_; }; }
{ "alphanum_fraction": 0.5743567692, "author": null, "avg_line_length": 35.5038167939, "converted": null, "ext": "h", "file": null, "hexsha": "d9c6b6d0a0ef1923fa425eda5cbc14f36cffcb2f", "include": null, "lang": "C", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-22T00:36:08.000Z", "max_forks_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_forks_repo_licenses": [ "MS-PL" ], "max_forks_repo_name": "GerHobbelt/hypertextcpp", "max_forks_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/usageinfocreator.h", "max_issues_count": 6, "max_issues_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_issues_repo_issues_event_max_datetime": "2021-12-21T08:13:28.000Z", "max_issues_repo_issues_event_min_datetime": "2021-05-20T22:04:52.000Z", "max_issues_repo_licenses": [ "MS-PL" ], "max_issues_repo_name": "GerHobbelt/hypertextcpp", "max_issues_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/usageinfocreator.h", "max_line_length": 150, "max_stars_count": 77, "max_stars_repo_head_hexsha": "0058bffd31fd2a46374fd44c6730c2356bbaab43", "max_stars_repo_licenses": [ "MS-PL" ], "max_stars_repo_name": "GerHobbelt/hypertextcpp", "max_stars_repo_path": "thirdparty/cmdlime/include/cmdlime/detail/usageinfocreator.h", "max_stars_repo_stars_event_max_datetime": "2022-02-13T21:37:54.000Z", "max_stars_repo_stars_event_min_datetime": "2021-05-20T18:05:54.000Z", "num_tokens": 2969, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 13953 }
[STATEMENT] lemma inline1_in_sub_gpvs: assumes "Inr (out, callee', rpv') \<in> set_spmf (inline1 callee gpv s)" and "(x, s') \<in> results_gpv \<I>' (callee' input)" and "input \<in> responses_\<I> \<I>' out" and "\<I> \<turnstile>g gpv \<surd>" shows "rpv' x \<in> sub_gpvs \<I> gpv" [PROOF STATE] proof (prove) goal (1 subgoal): 1. rpv' x \<in> sub_gpvs \<I> gpv [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. rpv' x \<in> sub_gpvs \<I> gpv [PROOF STEP] from \<open>\<I> \<turnstile>g gpv \<surd>\<close> [PROOF STATE] proof (chain) picking this: \<I> \<turnstile>g gpv \<surd> [PROOF STEP] have "set_spmf (inline1 callee gpv s) \<subseteq> {Inr (out, callee', rpv') | out callee' rpv'. \<forall>input \<in> responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl" (is "?concl (inline1 callee) gpv s" is "_ \<subseteq> ?rhs gpv s") [PROOF STATE] proof (prove) using this: \<I> \<turnstile>g gpv \<surd> goal (1 subgoal): 1. set_spmf (inline1 callee gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] proof(induction arbitrary: gpv s rule: inline1_fixp_induct) [PROOF STATE] proof (state) goal (3 subgoals): 1. spmf.admissible (\<lambda>inline1'. \<forall>x. \<I> \<turnstile>g x \<surd> \<longrightarrow> (\<forall>xa. set_spmf (inline1' (x, xa)) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(xa, s')\<in>results_gpv \<I>' (callee' input). rpv' xa \<in> sub_gpvs \<I> x} \<union> range Inl)) 2. \<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (return_pmf None) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl 3. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] case adm [PROOF STATE] proof (state) this: goal (3 subgoals): 1. spmf.admissible (\<lambda>inline1'. \<forall>x. \<I> \<turnstile>g x \<surd> \<longrightarrow> (\<forall>xa. set_spmf (inline1' (x, xa)) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(xa, s')\<in>results_gpv \<I>' (callee' input). rpv' xa \<in> sub_gpvs \<I> x} \<union> range Inl)) 2. \<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (return_pmf None) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl 3. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] show ?case [PROOF STATE] proof (prove) goal (1 subgoal): 1. spmf.admissible (\<lambda>inline1'. \<forall>x. \<I> \<turnstile>g x \<surd> \<longrightarrow> (\<forall>xa. set_spmf (inline1' (x, xa)) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (xa, s') \<Rightarrow> rpv' xa \<in> sub_gpvs \<I> x} \<union> range Inl)) [PROOF STEP] by(intro cont_intro ccpo_class.admissible_leI) [PROOF STATE] proof (state) this: spmf.admissible (\<lambda>inline1'. \<forall>x. \<I> \<turnstile>g x \<surd> \<longrightarrow> (\<forall>xa. set_spmf (inline1' (x, xa)) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (xa, s') \<Rightarrow> rpv' xa \<in> sub_gpvs \<I> x} \<union> range Inl)) goal (2 subgoals): 1. \<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (return_pmf None) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl 2. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] case bottom [PROOF STATE] proof (state) this: \<I> \<turnstile>g gpv \<surd> goal (2 subgoals): 1. \<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (return_pmf None) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl 2. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] show ?case [PROOF STATE] proof (prove) goal (1 subgoal): 1. set_spmf (return_pmf None) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] by simp [PROOF STATE] proof (state) this: set_spmf (return_pmf None) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] next [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] case (step inline1') [PROOF STATE] proof (state) this: \<I> \<turnstile>g ?gpv \<surd> \<Longrightarrow> set_spmf (inline1' ?gpv ?s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> ?gpv} \<union> range Inl \<I> \<turnstile>g gpv \<surd> goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] { [PROOF STATE] proof (state) this: \<I> \<turnstile>g ?gpv \<surd> \<Longrightarrow> set_spmf (inline1' ?gpv ?s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> ?gpv} \<union> range Inl \<I> \<turnstile>g gpv \<surd> goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] fix out c [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] assume IO: "IO out c \<in> set_spmf (the_gpv gpv)" [PROOF STATE] proof (state) this: IO out c \<in> set_spmf (the_gpv gpv) goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] from step.prems IO [PROOF STATE] proof (chain) picking this: \<I> \<turnstile>g gpv \<surd> IO out c \<in> set_spmf (the_gpv gpv) [PROOF STEP] have out: "out \<in> outs_\<I> \<I>" [PROOF STATE] proof (prove) using this: \<I> \<turnstile>g gpv \<surd> IO out c \<in> set_spmf (the_gpv gpv) goal (1 subgoal): 1. out \<in> outs_\<I> \<I> [PROOF STEP] by(rule WT_gpvD) [PROOF STATE] proof (state) this: out \<in> outs_\<I> \<I> goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] { [PROOF STATE] proof (state) this: out \<in> outs_\<I> \<I> goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] fix x s' [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] assume Pure: "Pure (x, s') \<in> set_spmf (the_gpv (callee s out))" [PROOF STATE] proof (state) this: Pure (x, s') \<in> set_spmf (the_gpv (callee s out)) goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] then [PROOF STATE] proof (chain) picking this: Pure (x, s') \<in> set_spmf (the_gpv (callee s out)) [PROOF STEP] have "(x, s') \<in> results_gpv \<I>' (callee s out)" [PROOF STATE] proof (prove) using this: Pure (x, s') \<in> set_spmf (the_gpv (callee s out)) goal (1 subgoal): 1. (x, s') \<in> results_gpv \<I>' (callee s out) [PROOF STEP] by(rule results_gpv.Pure) [PROOF STATE] proof (state) this: (x, s') \<in> results_gpv \<I>' (callee s out) goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] with out [PROOF STATE] proof (chain) picking this: out \<in> outs_\<I> \<I> (x, s') \<in> results_gpv \<I>' (callee s out) [PROOF STEP] have "x \<in> responses_\<I> \<I> out" [PROOF STATE] proof (prove) using this: out \<in> outs_\<I> \<I> (x, s') \<in> results_gpv \<I>' (callee s out) goal (1 subgoal): 1. x \<in> responses_\<I> \<I> out [PROOF STEP] by(auto dest: results) [PROOF STATE] proof (state) this: x \<in> responses_\<I> \<I> out goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] with step.prems IO [PROOF STATE] proof (chain) picking this: \<I> \<turnstile>g gpv \<surd> IO out c \<in> set_spmf (the_gpv gpv) x \<in> responses_\<I> \<I> out [PROOF STEP] have "\<I> \<turnstile>g c x \<surd>" [PROOF STATE] proof (prove) using this: \<I> \<turnstile>g gpv \<surd> IO out c \<in> set_spmf (the_gpv gpv) x \<in> responses_\<I> \<I> out goal (1 subgoal): 1. \<I> \<turnstile>g c x \<surd> [PROOF STEP] by(rule WT_gpvD) [PROOF STATE] proof (state) this: \<I> \<turnstile>g c x \<surd> goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] hence "?concl inline1' (c x) s'" [PROOF STATE] proof (prove) using this: \<I> \<turnstile>g c x \<surd> goal (1 subgoal): 1. set_spmf (inline1' (c x) s') \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> (c x)} \<union> range Inl [PROOF STEP] by(rule step.IH) [PROOF STATE] proof (state) this: set_spmf (inline1' (c x) s') \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> (c x)} \<union> range Inl goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] also [PROOF STATE] proof (state) this: set_spmf (inline1' (c x) s') \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> (c x)} \<union> range Inl goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] have "\<dots> \<subseteq> ?rhs gpv s'" [PROOF STATE] proof (prove) goal (1 subgoal): 1. {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> (c x)} \<union> range Inl \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] using IO Pure [PROOF STATE] proof (prove) using this: IO out c \<in> set_spmf (the_gpv gpv) Pure (x, s') \<in> set_spmf (the_gpv (callee s out)) goal (1 subgoal): 1. {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> (c x)} \<union> range Inl \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] by(fastforce intro: sub_gpvs.cont dest: WT_gpv_OutD[OF step.prems] results[THEN subsetD, OF _ results_gpv.Pure]) [PROOF STATE] proof (state) this: {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> (c x)} \<union> range Inl \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] finally [PROOF STATE] proof (chain) picking this: set_spmf (inline1' (c x) s') \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] have "set_spmf (inline1' (c x) s') \<subseteq> \<dots>" [PROOF STATE] proof (prove) using this: set_spmf (inline1' (c x) s') \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl goal (1 subgoal): 1. set_spmf (inline1' (c x) s') \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] . [PROOF STATE] proof (state) this: set_spmf (inline1' (c x) s') \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] } [PROOF STATE] proof (state) this: Pure (?xa2, ?s'a2) \<in> set_spmf (the_gpv (callee s out)) \<Longrightarrow> set_spmf (inline1' (c ?xa2) ?s'a2) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] moreover [PROOF STATE] proof (state) this: Pure (?xa2, ?s'a2) \<in> set_spmf (the_gpv (callee s out)) \<Longrightarrow> set_spmf (inline1' (c ?xa2) ?s'a2) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] { [PROOF STATE] proof (state) this: Pure (?xa2, ?s'a2) \<in> set_spmf (the_gpv (callee s out)) \<Longrightarrow> set_spmf (inline1' (c ?xa2) ?s'a2) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] fix out' c' input x s' [PROOF STATE] proof (state) goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] assume "IO out' c' \<in> set_spmf (the_gpv (callee s out))" and "input \<in> responses_\<I> \<I>' out'" and "(x, s') \<in> results_gpv \<I>' (c' input)" [PROOF STATE] proof (state) this: IO out' c' \<in> set_spmf (the_gpv (callee s out)) input \<in> responses_\<I> \<I>' out' (x, s') \<in> results_gpv \<I>' (c' input) goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] then [PROOF STATE] proof (chain) picking this: IO out' c' \<in> set_spmf (the_gpv (callee s out)) input \<in> responses_\<I> \<I>' out' (x, s') \<in> results_gpv \<I>' (c' input) [PROOF STEP] have "c x \<in> sub_gpvs \<I> gpv" [PROOF STATE] proof (prove) using this: IO out' c' \<in> set_spmf (the_gpv (callee s out)) input \<in> responses_\<I> \<I>' out' (x, s') \<in> results_gpv \<I>' (c' input) goal (1 subgoal): 1. c x \<in> sub_gpvs \<I> gpv [PROOF STEP] using IO [PROOF STATE] proof (prove) using this: IO out' c' \<in> set_spmf (the_gpv (callee s out)) input \<in> responses_\<I> \<I>' out' (x, s') \<in> results_gpv \<I>' (c' input) IO out c \<in> set_spmf (the_gpv gpv) goal (1 subgoal): 1. c x \<in> sub_gpvs \<I> gpv [PROOF STEP] by(auto intro!: sub_gpvs.base dest: WT_gpv_OutD[OF step.prems] results[THEN subsetD, OF _ results_gpv.IO]) [PROOF STATE] proof (state) this: c x \<in> sub_gpvs \<I> gpv goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] } [PROOF STATE] proof (state) this: \<lbrakk>IO ?out'2 ?c'2 \<in> set_spmf (the_gpv (callee s out)); ?inputa2 \<in> responses_\<I> \<I>' ?out'2; (?xa2, ?s'a2) \<in> results_gpv \<I>' (?c'2 ?inputa2)\<rbrakk> \<Longrightarrow> c ?xa2 \<in> sub_gpvs \<I> gpv goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<lbrakk>IO ?out'2 ?c'2 \<in> set_spmf (the_gpv (callee s out)); ?inputa2 \<in> responses_\<I> \<I>' ?out'2; (?xa2, ?s'a2) \<in> results_gpv \<I>' (?c'2 ?inputa2)\<rbrakk> \<Longrightarrow> c ?xa2 \<in> sub_gpvs \<I> gpv goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] note calculation [PROOF STATE] proof (state) this: Pure (?xa2, ?s'a2) \<in> set_spmf (the_gpv (callee s out)) \<Longrightarrow> set_spmf (inline1' (c ?xa2) ?s'a2) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl \<lbrakk>IO ?out'2 ?c'2 \<in> set_spmf (the_gpv (callee s out)); ?inputa2 \<in> responses_\<I> \<I>' ?out'2; (?xa2, ?s'a2) \<in> results_gpv \<I>' (?c'2 ?inputa2)\<rbrakk> \<Longrightarrow> c ?xa2 \<in> sub_gpvs \<I> gpv goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] } [PROOF STATE] proof (state) this: \<lbrakk>IO ?outa5 ?c5 \<in> set_spmf (the_gpv gpv); Pure (?xa2, ?s'a2) \<in> set_spmf (the_gpv (callee s ?outa5))\<rbrakk> \<Longrightarrow> set_spmf (inline1' (?c5 ?xa2) ?s'a2) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl \<lbrakk>IO ?outa5 ?c5 \<in> set_spmf (the_gpv gpv); IO ?out'2 ?c'2 \<in> set_spmf (the_gpv (callee s ?outa5)); ?inputa2 \<in> responses_\<I> \<I>' ?out'2; (?xa2, ?s'a2) \<in> results_gpv \<I>' (?c'2 ?inputa2)\<rbrakk> \<Longrightarrow> ?c5 ?xa2 \<in> sub_gpvs \<I> gpv goal (1 subgoal): 1. \<And>inline1' gpv s. \<lbrakk>\<And>gpv s. \<I> \<turnstile>g gpv \<surd> \<Longrightarrow> set_spmf (inline1' gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl; \<I> \<turnstile>g gpv \<surd>\<rbrakk> \<Longrightarrow> set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<lbrakk>IO ?outa5 ?c5 \<in> set_spmf (the_gpv gpv); Pure (?xa2, ?s'a2) \<in> set_spmf (the_gpv (callee s ?outa5))\<rbrakk> \<Longrightarrow> set_spmf (inline1' (?c5 ?xa2) ?s'a2) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl \<lbrakk>IO ?outa5 ?c5 \<in> set_spmf (the_gpv gpv); IO ?out'2 ?c'2 \<in> set_spmf (the_gpv (callee s ?outa5)); ?inputa2 \<in> responses_\<I> \<I>' ?out'2; (?xa2, ?s'a2) \<in> results_gpv \<I>' (?c'2 ?inputa2)\<rbrakk> \<Longrightarrow> ?c5 ?xa2 \<in> sub_gpvs \<I> gpv [PROOF STEP] show ?case [PROOF STATE] proof (prove) using this: \<lbrakk>IO ?outa5 ?c5 \<in> set_spmf (the_gpv gpv); Pure (?xa2, ?s'a2) \<in> set_spmf (the_gpv (callee s ?outa5))\<rbrakk> \<Longrightarrow> set_spmf (inline1' (?c5 ?xa2) ?s'a2) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl \<lbrakk>IO ?outa5 ?c5 \<in> set_spmf (the_gpv gpv); IO ?out'2 ?c'2 \<in> set_spmf (the_gpv (callee s ?outa5)); ?inputa2 \<in> responses_\<I> \<I>' ?out'2; (?xa2, ?s'a2) \<in> results_gpv \<I>' (?c'2 ?inputa2)\<rbrakk> \<Longrightarrow> ?c5 ?xa2 \<in> sub_gpvs \<I> gpv goal (1 subgoal): 1. set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] by(auto simp add: bind_UNION intro!: UN_least split: generat.split del: subsetI) [PROOF STATE] proof (state) this: set_spmf (the_gpv gpv \<bind> case_generat (\<lambda>x. return_spmf (Inl (x, s))) (\<lambda>out rpv. the_gpv (callee s out) \<bind> case_generat (\<lambda>(x, y). inline1' (rpv x) y) (\<lambda>out rpv'. return_spmf (Inr (out, rpv', rpv))))) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>a\<in>results_gpv \<I>' (callee' input). case a of (x, s') \<Rightarrow> rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl goal: No subgoals! [PROOF STEP] qed [PROOF STATE] proof (state) this: set_spmf (inline1 callee gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl goal (1 subgoal): 1. rpv' x \<in> sub_gpvs \<I> gpv [PROOF STEP] with assms [PROOF STATE] proof (chain) picking this: Inr (out, callee', rpv') \<in> set_spmf (inline1 callee gpv s) (x, s') \<in> results_gpv \<I>' (callee' input) input \<in> responses_\<I> \<I>' out \<I> \<turnstile>g gpv \<surd> set_spmf (inline1 callee gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl [PROOF STEP] show ?thesis [PROOF STATE] proof (prove) using this: Inr (out, callee', rpv') \<in> set_spmf (inline1 callee gpv s) (x, s') \<in> results_gpv \<I>' (callee' input) input \<in> responses_\<I> \<I>' out \<I> \<turnstile>g gpv \<surd> set_spmf (inline1 callee gpv s) \<subseteq> {Inr (out, callee', rpv') |out callee' rpv'. \<forall>input\<in>responses_\<I> \<I>' out. \<forall>(x, s')\<in>results_gpv \<I>' (callee' input). rpv' x \<in> sub_gpvs \<I> gpv} \<union> range Inl goal (1 subgoal): 1. rpv' x \<in> sub_gpvs \<I> gpv [PROOF STEP] by fastforce [PROOF STATE] proof (state) this: rpv' x \<in> sub_gpvs \<I> gpv goal: No subgoals! [PROOF STEP] qed
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "CryptHOL_Generative_Probabilistic_Value", "hexsha": null, "include": null, "lang": null, "length": 60, "llama_tokens": 21765, "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 }
abstract type AbstractZXDiagram{T, P} end Graphs.nv(zxd::AbstractZXDiagram) = throw(MethodError(Graphs.nv, zxd)) Graphs.ne(zxd::AbstractZXDiagram) = throw(MethodError(Graphs.ne, zxd)) Graphs.degree(zxd::AbstractZXDiagram, v) = throw(MethodError(Graphs.degree, (zxd, v))) Graphs.indegree(zxd::AbstractZXDiagram, v) = throw(MethodError(Graphs.indegree, (zxd, v))) Graphs.outdegree(zxd::AbstractZXDiagram, v) = throw(MethodError(Graphs.outdegree, (zxd, v))) Graphs.neighbors(zxd::AbstractZXDiagram, v) = throw(MethodError(Graphs.neighbors, (zxd, v))) Graphs.outneighbors(zxd::AbstractZXDiagram, v) = throw(MethodError(Graphs.outneighbors, (zxd, v))) Graphs.inneighbors(zxd::AbstractZXDiagram, v) = throw(MethodError(Graphs.inneighbors, (zxd, v))) Graphs.rem_edge!(zxd::AbstractZXDiagram, args...) = throw(MethodError(Graphs.rem_edge!, (zxd, args...))) Graphs.add_edge!(zxd::AbstractZXDiagram, args...) = throw(MethodError(Graphs.add_edge!, (zxd, args...))) Graphs.has_edge(zxd::AbstractZXDiagram, args...) = throw(MethodError(Graphs.has_edge, (zxd, args...))) Base.show(io::IO, zxd::AbstractZXDiagram) = throw(MethodError(Base.show, io, zxd)) Base.copy(zxd::AbstractZXDiagram) = throw(MethodError(Base.copy, zxd)) nqubits(zxd::AbstractZXDiagram) = throw(MethodError(ZXCalculus.nqubits, zxd)) spiders(zxd::AbstractZXDiagram) = throw(MethodError(ZXCalculus.spiders, zxd)) tcount(zxd::AbstractZXDiagram) = throw(MethodError(ZXCalculus.tcount, zxd)) get_inputs(zxd::AbstractZXDiagram) = throw(MethodError(ZXCalculus.get_inputs, zxd)) get_outputs(zxd::AbstractZXDiagram) = throw(MethodError(ZXCalculus.get_outputs, zxd)) scalar(zxd::AbstractZXDiagram) = throw(MethodError(ZXCalculus.scalar, zxd)) spider_sequence(zxd::AbstractZXDiagram) = throw(MethodError(ZXCalculus.spider_sequence, zxd)) round_phases!(zxd::AbstractZXDiagram) = throw(MethodError(ZXCalculus.round_phases!, zxd)) spider_type(zxd::AbstractZXDiagram, v) = throw(MethodError(ZXCalculus.spider_type, (zxd, v))) phase(zxd::AbstractZXDiagram, v) = throw(MethodError(ZXCalculus.phase, (zxd, v))) rem_spider!(zxd::AbstractZXDiagram, v) = throw(MethodError(ZXCalculus.rem_spider!, (zxd, v))) rem_spiders!(zxd::AbstractZXDiagram, vs)= throw(MethodError(ZXCalculus.rem_spiders!, (zxd, vs))) qubit_loc(zxd::AbstractZXDiagram, v) = throw(MethodError(ZXCalculus.qubit_loc, (zxd, v))) column_loc(zxd::AbstractZXDiagram, v) = throw(MethodError(ZXCalculus.column_loc, (zxd, v))) add_global_phase!(zxd::AbstractZXDiagram, p) = throw(MethodError(ZXCalculus.add_global_phase!, (zxd, p))) add_power!(zxd::AbstractZXDiagram, n) = throw(MethodError(ZXCalculus.add_power!, (zxd, n))) generate_layout!(zxd::AbstractZXDiagram, seq) = throw(MethodError(ZXCalculus.generate_layout!, (zxd, seq))) set_phase!(zxd::AbstractZXDiagram, args...) = throw(MethodError(ZXCalculus.set_phase!, (zxd, args...))) push_gate!(zxd::AbstractZXDiagram, args...) = throw(MethodError(ZXCalculus.push_gate!, (zxd, args...))) pushfirst_gate!(zxd::AbstractZXDiagram, args...) = throw(MethodError(ZXCalculus.pushfirst_gate!, (zxd, args...))) add_spider!(zxd::AbstractZXDiagram, args...) = throw(MethodError(ZXCalculus.add_spider!, (zxd, args...))) insert_spider!(zxd::AbstractZXDiagram, args...) = throw(MethodError(ZXCalculus.insert_spider!, (zxd, args...)))
{ "alphanum_fraction": 0.7655867971, "author": null, "avg_line_length": 79.8048780488, "converted": null, "ext": "jl", "file": null, "hexsha": "90fa516ac2d097230cf486f2320004bf71c476e4", "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": "625c96ae707493703462306ff2e02240fb389074", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ChenZhao44/ZX.jl", "max_forks_repo_path": "src/abstract_zx_diagram.jl", "max_issues_count": 12, "max_issues_repo_head_hexsha": "bbc19ab5ec0f1eb0b09ffa7a6e2976f60b625fbc", "max_issues_repo_issues_event_max_datetime": "2020-05-23T03:50:48.000Z", "max_issues_repo_issues_event_min_datetime": "2020-05-12T09:40:23.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "QuantumBFS/ZX.jl", "max_issues_repo_path": "src/abstract_zx_diagram.jl", "max_line_length": 113, "max_stars_count": null, "max_stars_repo_head_hexsha": "bbc19ab5ec0f1eb0b09ffa7a6e2976f60b625fbc", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "QuantumBFS/ZX.jl", "max_stars_repo_path": "src/abstract_zx_diagram.jl", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 961, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 3272 }
[STATEMENT] lemma (*equal_union: *) "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] proof - [PROOF STATE] proof (state) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] have F1: "\<forall>(x\<^sub>2::'b set) x\<^sub>1::'b set. x\<^sub>1 \<subseteq> x\<^sub>1 \<union> x\<^sub>2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>x\<^sub>2 x\<^sub>1. x\<^sub>1 \<subseteq> x\<^sub>1 \<union> x\<^sub>2 [PROOF STEP] by (metis Un_commute Un_upper2) [PROOF STATE] proof (state) this: \<forall>x\<^sub>2 x\<^sub>1. x\<^sub>1 \<subseteq> x\<^sub>1 \<union> x\<^sub>2 goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] have F2a: "\<forall>(x\<^sub>2::'b set) x\<^sub>1::'b set. x\<^sub>1 \<subseteq> x\<^sub>2 \<longrightarrow> x\<^sub>2 = x\<^sub>2 \<union> x\<^sub>1" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>x\<^sub>2 x\<^sub>1. x\<^sub>1 \<subseteq> x\<^sub>2 \<longrightarrow> x\<^sub>2 = x\<^sub>2 \<union> x\<^sub>1 [PROOF STEP] by (metis Un_commute subset_Un_eq) [PROOF STATE] proof (state) this: \<forall>x\<^sub>2 x\<^sub>1. x\<^sub>1 \<subseteq> x\<^sub>2 \<longrightarrow> x\<^sub>2 = x\<^sub>2 \<union> x\<^sub>1 goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] have F2: "\<forall>(x\<^sub>2::'b set) x\<^sub>1::'b set. x\<^sub>1 \<subseteq> x\<^sub>2 \<and> x\<^sub>2 \<subseteq> x\<^sub>1 \<longrightarrow> x\<^sub>1 = x\<^sub>2" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<forall>x\<^sub>2 x\<^sub>1. x\<^sub>1 \<subseteq> x\<^sub>2 \<and> x\<^sub>2 \<subseteq> x\<^sub>1 \<longrightarrow> x\<^sub>1 = x\<^sub>2 [PROOF STEP] by (metis F2a subset_Un_eq) [PROOF STATE] proof (state) this: \<forall>x\<^sub>2 x\<^sub>1. x\<^sub>1 \<subseteq> x\<^sub>2 \<and> x\<^sub>2 \<subseteq> x\<^sub>1 \<longrightarrow> x\<^sub>1 = x\<^sub>2 goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: \<forall>x\<^sub>2 x\<^sub>1. x\<^sub>1 \<subseteq> x\<^sub>2 \<and> x\<^sub>2 \<subseteq> x\<^sub>1 \<longrightarrow> x\<^sub>1 = x\<^sub>2 goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume "\<not> Z \<subseteq> X" [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Z \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis Un_upper2) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume AA1: "Y \<union> Z \<noteq> X" [PROOF STATE] proof (state) this: Y \<union> Z \<noteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: Y \<union> Z \<noteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume "\<not> Y \<subseteq> X" [PROOF STATE] proof (state) this: \<not> Y \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Y \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis F1) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume AAA1: "Y \<subseteq> X \<and> Y \<union> Z \<noteq> X" [PROOF STATE] proof (state) this: Y \<subseteq> X \<and> Y \<union> Z \<noteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: Y \<subseteq> X \<and> Y \<union> Z \<noteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume "\<not> Z \<subseteq> X" [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Z \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis Un_upper2) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume "(Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X" [PROOF STATE] proof (state) this: (Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z" [PROOF STATE] proof (prove) using this: (Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X goal (1 subgoal): 1. Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z [PROOF STEP] by (metis Un_subset_iff) [PROOF STATE] proof (state) this: Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> Y \<union> Z" [PROOF STATE] proof (prove) using this: Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z goal (1 subgoal): 1. Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> Y \<union> Z [PROOF STEP] by (metis F2) [PROOF STATE] proof (state) this: Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> Y \<union> Z goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "\<exists>x\<^sub>1::'a set. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z" [PROOF STATE] proof (prove) using this: Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> Y \<union> Z goal (1 subgoal): 1. \<exists>x\<^sub>1. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z [PROOF STEP] by (metis F1) [PROOF STATE] proof (state) this: \<exists>x\<^sub>1. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<exists>x\<^sub>1. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis Un_upper2) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: (Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) (Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) (Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis AAA1) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: Y \<subseteq> X \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) Y \<subseteq> X \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) Y \<subseteq> X \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis AA1) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] moreover [PROOF STATE] proof (state) this: Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume "\<exists>x\<^sub>1::'a set. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1" [PROOF STATE] proof (state) this: \<exists>x\<^sub>1. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1 goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: \<exists>x\<^sub>1. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1 goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume "\<not> Y \<subseteq> X" [PROOF STATE] proof (state) this: \<not> Y \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Y \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis F1) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume AAA1: "Y \<subseteq> X \<and> Y \<union> Z \<noteq> X" [PROOF STATE] proof (state) this: Y \<subseteq> X \<and> Y \<union> Z \<noteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: Y \<subseteq> X \<and> Y \<union> Z \<noteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume "\<not> Z \<subseteq> X" [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Z \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis Un_upper2) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume "(Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X" [PROOF STATE] proof (state) this: (Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z" [PROOF STATE] proof (prove) using this: (Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X goal (1 subgoal): 1. Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z [PROOF STEP] by (metis Un_subset_iff) [PROOF STATE] proof (state) this: Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> Y \<union> Z" [PROOF STATE] proof (prove) using this: Y \<union> Z \<subseteq> X \<and> X \<noteq> Y \<union> Z goal (1 subgoal): 1. Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> Y \<union> Z [PROOF STEP] by (metis F2) [PROOF STATE] proof (state) this: Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> Y \<union> Z goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "\<exists>x\<^sub>1::'a set. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z" [PROOF STATE] proof (prove) using this: Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> Y \<union> Z goal (1 subgoal): 1. \<exists>x\<^sub>1. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z [PROOF STEP] by (metis F1) [PROOF STATE] proof (state) this: \<exists>x\<^sub>1. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<exists>x\<^sub>1. Y \<subseteq> x\<^sub>1 \<union> Z \<and> Y \<union> Z \<noteq> X \<and> \<not> X \<subseteq> x\<^sub>1 \<union> Z goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis Un_upper2) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: (Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) (Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) (Z \<subseteq> X \<and> Y \<subseteq> X) \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis AAA1) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: Y \<subseteq> X \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) Y \<subseteq> X \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] have "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) Y \<subseteq> X \<and> Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by blast [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: \<exists>x\<^sub>1. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1 \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] moreover [PROOF STATE] proof (state) this: \<exists>x\<^sub>1. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1 \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] { [PROOF STATE] proof (state) this: \<exists>x\<^sub>1. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1 \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] assume "\<not> Y \<subseteq> X" [PROOF STATE] proof (state) this: \<not> Y \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] hence "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Y \<subseteq> X goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by (metis F1) [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] } [PROOF STATE] proof (state) this: \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] ultimately [PROOF STATE] proof (chain) picking this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) \<exists>x\<^sub>1. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1 \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] show "(X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V::'a set. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V))" [PROOF STATE] proof (prove) using this: \<not> Z \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) Y \<union> Z \<noteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) \<exists>x\<^sub>1. (Z \<subseteq> x\<^sub>1 \<and> Y \<subseteq> x\<^sub>1) \<and> \<not> X \<subseteq> x\<^sub>1 \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) \<not> Y \<subseteq> X \<Longrightarrow> (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal (1 subgoal): 1. (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) [PROOF STEP] by metis [PROOF STATE] proof (state) this: (X = Y \<union> Z) = (Y \<subseteq> X \<and> Z \<subseteq> X \<and> (\<forall>V. Y \<subseteq> V \<and> Z \<subseteq> V \<longrightarrow> X \<subseteq> V)) goal: No subgoals! [PROOF STEP] qed
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": null, "hexsha": null, "include": null, "lang": null, "length": 94, "llama_tokens": 15158, "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 argparse import copy import ctgan import lightgbm as lgbm import logging import multiprocessing as mp import numpy as np import os import pandas as pd import pathlib import yaml from contextlib import redirect_stdout, redirect_stderr from dataclasses import dataclass, field from itertools import product from sklearn import ensemble from sklearn import preprocessing from sklearn import metrics from sklearn import utils from typing import Dict, Union SAMPLE_ROWS = 1000 TARGET_FPR = 0.05 N_RUNS = 1 CATEGORICAL_FEATURES = [ 'source', 'payment_type', 'device_os', 'housing_status', 'employment_status' ] BOOLEAN_FEATURES = [ 'email_is_free', 'fraud_bool', 'foreign_request', 'keep_alive_session', 'phone_home_valid', 'phone_mobile_valid', 'has_other_cards' ] @dataclass class RunConfig: model_id: int train_df: pd.DataFrame = field(repr=False) val_df: pd.DataFrame = field(repr=False) discrete_columns: list model_run_dir: str config: Dict dry_run: bool dev_run: bool seed: Union[bool, None] def parse_argv(): parser = argparse.ArgumentParser('CTGAN Hyperparameter search') parser.add_argument('run_dir', help='Directory where the outputs of the experiment will be stored') parser.add_argument('config_path', type=str, help='Configurations for the sweep') parser.add_argument('--n-procs', type=int, default=1, help='Number of simultaneous processes to spawn') parser.add_argument('--devices', type=str, nargs='+', default=['cpu'], help='Devices to use') parser.add_argument('--log-level', type=str, default='info', help='Specify logging level') parser.add_argument('--seed', default=None, help='Specify seed to pass to sampling methods') run_opts = parser.add_mutually_exclusive_group() run_opts.add_argument( '--dry-run', default=False, action='store_true', help='Activate dry run mode (models are not trained, only a sample of the data is used)' ) run_opts.add_argument( '--dev-run', default=False, action='store_true', help='Activate dev run mode (models are trained for one epoch)' ) return parser.parse_args() def configure_logging(log_arg): received_level = getattr(logging, log_arg.upper(), None) logging_level = received_level if received_level else logging.INFO logging.basicConfig( format='[ %(levelname)s ] %(asctime)s (%(process)s-%(processName)s) %(message)s', datefmt='%Y-%m-%d %H:%M:%S', level=logging_level ) if not received_level: logging.warning('Unknown logging level %s: Setting logging to INFO', log_arg.upper()) def create_run_dir(run_dir, dry_run): if run_dir.exists(): logging.error('Run Directory already exists: \'%s\'', run_dir) exit(1) if not dry_run: os.mkdir(run_dir) logging.info('Run results stored at: \'%s\'', run_dir) def read_configurations(config_path): logging.info('Reading configurations from %s', config_path) with open(config_path, 'r') as f: configs = yaml.safe_load(f) return configs['data'], configs['sweep_params'] def load_data(data_config, dry_run, dev_run): logging.info('Loading train dataset from \'%s\'', data_config['train']) logging.info('Loading validation dataset from \'%s\'', data_config['validation']) nrows = SAMPLE_ROWS if dry_run else None train_df = pd.read_csv(data_config['train'], index_col=0, nrows=nrows) val_df = pd.read_csv(data_config['validation'], index_col=0, nrows=nrows) if 'keep' in data_config: train_df = train_df[data_config['keep']] val_df = val_df[data_config['keep']] elif 'remove' in data_config: train_df = train_df.drop(columns=data_config['remove']) val_df = val_df.drop(columns=data_config['remove']) discrete_columns = [f for f in CATEGORICAL_FEATURES + BOOLEAN_FEATURES if f in train_df.columns] logging.info('Train Dataset: %s Features, %s Examples', len(train_df.columns), len(train_df)) logging.info('Validation Dataset: %s Features, %s Examples', len(val_df.columns), len(val_df)) logging.debug('Train Features: %s', list(train_df.columns)) logging.debug('Validation features: %s', list(val_df.columns)) logging.debug('Discrete columns: %s', discrete_columns) return train_df, val_df, discrete_columns def pad_int(model_id, zfill=3): return str(model_id).zfill(zfill) def model_run_dir(run_dir, model_id): return run_dir / pad_int(model_id) def results_path(run_dir): return run_dir / 'results.csv' def config_path(model_run_dir, model_id): return model_run_dir / f'config-{pad_int(model_id)}.yml' def model_path(model_run_dir, model_id): return model_run_dir / f'model-{pad_int(model_id)}.pkl' def train_dataset_path(model_run_dir, model_id): return model_run_dir / f'train-dataset-{pad_int(model_id)}.csv' def synthetic_dataset_path(model_run_dir, model_id): return model_run_dir / f'synthetic-dataset-{pad_int(model_id)}.csv' def model_evaluation_path(model_run_dir, model_id): return model_run_dir / f'evaluation-{pad_int(model_id)}.csv' def stdout_path(model_run_dir, model_id): return model_run_dir / f'stdout-{pad_int(model_id)}.log' def stderr_path(model_run_dir, model_id): return model_run_dir/ f'stderr-{pad_int(model_id)}.log' def build_run_configs(run_dir, datasets_config, data_sweep_params, model_sweep_params, devices, dry_run, dev_run, seed): def gen_param(name, vals): return ((name, x) for x in vals) def build_partial_configs(**params): def to_tuple(val): try: return tuple(val) except TypeError: # If val not iterable will raise an exception # and we create an unary tuple with the value return (val,) tuples = map(lambda p: (p[0], to_tuple(p[1])), params.items()) gens = map(lambda p: gen_param(p[0], p[1]), tuples) return [dict(c) for c in product(*gens)] def distribute_gpus(configs, *gpus): n_gpus = len(gpus) for i, c in enumerate(configs): c['cuda'] = gpus[i % n_gpus] data_configs = build_partial_configs(**data_sweep_params) model_configs = build_partial_configs(**model_sweep_params) distribute_gpus(model_configs, *devices) configs = [dict(x) for x in product( gen_param('data', data_configs), gen_param('model', model_configs) )] train_df, val_df, discrete_columns = load_data(datasets_config, dry_run, dev_run) return [ RunConfig( model_id=model_id, train_df=train_df, val_df=val_df, discrete_columns=discrete_columns, model_run_dir=model_run_dir(run_dir, model_id), config=config, dry_run=dry_run, dev_run=dev_run, seed=seed ) for model_id, config in enumerate(configs, start=1) ] def subsample_with_prevalence(df, prevalence, seed): fraud = df[df['fraud_bool'] == 1] non_fraud = df[df['fraud_bool'] == 0] fraud_proportion, non_fraud_proportion = prevalence non_fraud_instances = (len(fraud) * non_fraud_proportion) // fraud_proportion if non_fraud_instances >= len(non_fraud): logging.warning( 'Unable to subsample dataframe: Expected more than %s negative examples but got %s', non_fraud_instances, len(fraud) ) non_fraud_sample = non_fraud else: non_fraud_sample = non_fraud.sample(n=non_fraud_instances, random_state=seed) return utils.shuffle(pd.concat((fraud, non_fraud_sample)), random_state=seed) def apply_config_to_data(df, data_config, model_id, seed): if 'prevalence' in data_config: df = subsample_with_prevalence(df, data_config['prevalence'], seed) if logging.root.isEnabledFor(logging.DEBUG): logging.debug( 'Model %s: Dataset with %s Examples (%s fraud, %s non fraud)', pad_int(model_id), len(df), len(df[df['fraud_bool'] == 1]), len(df[df['fraud_bool'] == 0]) ) return df def preprocess_categorical(train_df, val_df, discrete_columns): categorical_columns = np.intersect1d(discrete_columns, CATEGORICAL_FEATURES) for column in categorical_columns: train_unique = train_df[column].unique() val_unique = val_df[column].unique() nans = np.setdiff1d(val_unique, train_unique) val_df.loc[val_df[column].isin(nans), [column]] = np.nan train_dummy = pd.get_dummies(train_df, columns=categorical_columns, dummy_na=True) val_dummy = pd.get_dummies(val_df, columns=categorical_columns, dummy_na=True) for unseen_column in np.setdiff1d(train_dummy.columns, val_dummy.columns): val_dummy[unseen_column] = 0 return train_dummy, val_dummy def split(train_df, val_df, target): train_x = train_df.drop(columns=[target]) train_y = train_df[target] val_x = val_df.drop(columns=[target]) val_y = val_df[target] return train_x, train_y, val_x, val_y def preprocess_and_split(train_df, val_df, discrete_columns, target): train_dummy_df, val_dummy_df = preprocess_categorical(train_df, val_df, discrete_columns) return split(train_dummy_df, val_dummy_df, target) def class_index(model, class_value): return np.argwhere(model.classes_ == class_value)[0] def prediction_probabilities(model, x): return model.predict_proba(x)[:, class_index(model, 1)] def train_rf(train_x, train_y, val_x, val_y): obtained_fprs = [] obtained_tprs = [] obtained_thresholds = [] for _ in range(N_RUNS): model = ensemble.RandomForestClassifier(max_depth=20, n_estimators=200, n_jobs=1) model.fit(train_x, train_y.values.ravel()) pred_prob = prediction_probabilities(model, val_x) fprs, tprs, thresholds = metrics.roc_curve(val_y, pred_prob) obtained_fprs.append(fprs) obtained_tprs.append(tprs) obtained_thresholds.append(thresholds) return obtained_fprs, obtained_tprs, obtained_thresholds def ordinal_encode(train_df, val_df, categorical_features): for f in categorical_features: enc = preprocessing.OrdinalEncoder() train_df[f] = enc.fit_transform(train_df[[f]]) val_df[f] = enc.fit_transform(val_df[[f]]) return train_df, val_df def train_lgbm(train_df, val_df, discrete_columns, seed): obtained_fprs = [] obtained_tprs = [] obtained_thresholds = [] categorical_features = list(np.intersect1d(discrete_columns, CATEGORICAL_FEATURES)) train_df, val_df = ordinal_encode(train_df.copy(), val_df.copy(), categorical_features) train_df = subsample_with_prevalence(train_df, (1, 19), seed) train_x, train_y, val_x, val_y = split(train_df, val_df, 'fraud_bool') feature_names = list(train_x.columns) for _ in range(N_RUNS): # Best model for original dataset found by hyperparameter optimization model = lgbm.LGBMClassifier(**{ "max_depth": 83, "num_leaves": 13, "n_estimators": 162, "boosting_type": "goss", "learning_rate": 0.032482538486073374, "min_child_samples": 16, "seed": seed, "n_jobs": 1 }) model.fit(train_x, train_y, feature_name=feature_names, categorical_feature=categorical_features) pred_prob = prediction_probabilities(model, val_x) fprs, tprs, thresholds = metrics.roc_curve(val_y, pred_prob) obtained_fprs.append(fprs) obtained_tprs.append(tprs) obtained_thresholds.append(thresholds) return obtained_fprs, obtained_tprs, obtained_thresholds def compile_results( real_fprs, real_tprs, real_thresholds, synthetic_train_fprs, synthetic_train_tprs, synthetic_train_thresholds, synthetic_val_fprs, synthetic_val_tprs, synthetic_val_thresholds, synthetic_both_fprs, synthetic_both_tprs, synthetic_both_thresholds): records = [] for i, results in enumerate(zip(real_fprs, real_tprs, real_thresholds), start=1): for fpr, tpr, threshold in zip(*results): records.append((i, fpr, tpr, threshold, 'real')) for j, results in enumerate(zip(synthetic_train_fprs, synthetic_train_tprs, synthetic_train_thresholds), start=i+1): for fpr, tpr, threshold in zip(*results): records.append((j, fpr, tpr, threshold, 'synthetic-train')) for k, results in enumerate(zip(synthetic_val_fprs, synthetic_val_tprs, synthetic_val_thresholds), start=j+1): for fpr, tpr, threshold in zip(*results): records.append((k, fpr, tpr, threshold, 'synthetic-val')) for n, results in enumerate(zip(synthetic_both_fprs, synthetic_both_tprs, synthetic_both_thresholds), start=k+1): for fpr, tpr, threshold in zip(*results): records.append((n, fpr, tpr, threshold, 'synthetic-both')) return pd.DataFrame.from_records(records, columns=['run_id', 'fpr', 'tpr', 'threshold', 'discrimination']) def summarize_results( real_fprs, real_tprs, real_thresholds, synthetic_train_fprs, synthetic_train_tprs, synthetic_train_thresholds, synthetic_val_fprs, synthetic_val_tprs, synthetic_val_thresholds, synthetic_both_fprs, synthetic_both_tprs, synthetic_both_thresholds): def compute_avg_tpr_and_threshold(fprs, tprs, thresholds): avg_tpr = 0 avg_threshold = 0 for run_fprs, run_tprs, run_thresholds in zip(fprs, tprs, thresholds): target_fpr_index = np.argwhere(run_fprs <= TARGET_FPR).ravel()[-1] avg_tpr += run_tprs[target_fpr_index] / N_RUNS avg_threshold += run_thresholds[target_fpr_index] / N_RUNS return avg_tpr, avg_threshold avg_real_tpr, avg_real_threshold = \ compute_avg_tpr_and_threshold(real_fprs, real_tprs, real_thresholds) avg_synthetic_train_tpr, avg_synthetic_train_threshold = \ compute_avg_tpr_and_threshold(synthetic_train_fprs, synthetic_train_tprs, synthetic_train_thresholds) avg_synthetic_val_tpr, avg_synthetic_val_threshold = \ compute_avg_tpr_and_threshold(synthetic_val_fprs, synthetic_val_tprs, synthetic_val_thresholds) avg_synthetic_both_tpr, avg_synthetic_both_threshold = \ compute_avg_tpr_and_threshold(synthetic_both_fprs, synthetic_both_tprs, synthetic_both_thresholds) return ( avg_real_tpr, avg_real_threshold, avg_synthetic_train_tpr, avg_synthetic_train_threshold, avg_synthetic_val_tpr, avg_synthetic_val_threshold, avg_synthetic_both_tpr, avg_synthetic_both_threshold ) def run_instance(run_config: RunConfig): model_id = run_config.model_id train_df = run_config.train_df val_df = run_config.val_df discrete_columns = run_config.discrete_columns model_run_dir = pathlib.Path(run_config.model_run_dir) config = run_config.config config_save_path = config_path(model_run_dir, model_id) model_save_path = model_path(model_run_dir, model_id) model_evaluation_save_path = model_evaluation_path(model_run_dir, model_id) train_data_save_path = train_dataset_path(model_run_dir, model_id) synthetic_data_save_path = synthetic_dataset_path(model_run_dir, model_id) run_stdout_path = stdout_path(model_run_dir, model_id) run_stderr_path = stderr_path(model_run_dir, model_id) dry_run = run_config.dry_run dev_run = run_config.dev_run seed = run_config.seed logging.info('Model %s: Training started', pad_int(model_id)) logging.debug('Model %s: Config %s', pad_int(model_id), config) logging.debug('Model %s: Saved config to \'%s\'', pad_int(model_id), config_save_path) logging.debug('Model %s: Stdout redirected to \'%s\'', pad_int(model_id), run_stdout_path) logging.debug('Model %s: Stderr redirected to \'%s\'', pad_int(model_id), run_stderr_path) data_config = config['data'] model_config = config['model'] train_df['val'] = 0 val_df['val'] = 1 df = pd.concat((train_df, val_df)) df = utils.shuffle(df) df = apply_config_to_data(df, data_config, model_id, seed) discrete_columns = copy.copy(discrete_columns) discrete_columns.append('val') if not dry_run: os.mkdir(model_run_dir) df.to_csv(train_data_save_path) logging.debug('Model %s: Training data saved to %s', pad_int(model_id), train_data_save_path) with open(config_save_path, 'w') as fd: yaml.safe_dump(config, stream=fd, default_flow_style=False) if dev_run: model_config['epochs'] = 1 model = ctgan.CTGANSynthesizer(**model_config) with open(run_stdout_path, 'w') as out_fd, open(run_stderr_path, 'w') as err_fd: with redirect_stdout(out_fd), redirect_stderr(err_fd): model.fit(df, discrete_columns) if not dry_run: model.save(model_save_path) logging.info('Model %s: Saved model to \'%s\'', pad_int(model_id), model_save_path) if not dry_run: synthetic_df = model.sample(len(df)) synthetic_df.to_csv(synthetic_data_save_path) logging.info('Model %s: Saved synthetic dataset to \'%s\'', pad_int(model_id), synthetic_data_save_path) if not dry_run: synthetic_train_df = synthetic_df[synthetic_df['val'] == 0] synthetic_val_df = synthetic_df[synthetic_df['val'] == 1] real_fprs, real_tprs, real_thresholds = \ train_lgbm(train_df, val_df, discrete_columns, seed) synthetic_train_fprs, synthetic_train_tprs, synthetic_train_thresholds = \ train_lgbm(synthetic_train_df, val_df, discrete_columns, seed) synthetic_val_fprs, synthetic_val_tprs, synthetic_val_thresholds = \ train_lgbm(train_df, synthetic_val_df, discrete_columns, seed) synthetic_both_fprs, synthetic_both_tprs, synthetic_both_thresholds = \ train_lgbm(synthetic_train_df, synthetic_val_df, discrete_columns, seed) evaluation_results = compile_results( real_fprs, real_tprs, real_thresholds, synthetic_train_fprs, synthetic_train_tprs, synthetic_train_thresholds, synthetic_val_fprs, synthetic_val_tprs, synthetic_val_thresholds, synthetic_both_fprs, synthetic_both_tprs, synthetic_both_thresholds, ) evaluation_results.to_csv(model_evaluation_save_path) logging.info('Model %s: Saved evaluation to \'%s\'', pad_int(model_id), model_evaluation_save_path) if not dry_run: results = summarize_results( real_fprs, real_tprs, real_thresholds, synthetic_train_fprs, synthetic_train_tprs, synthetic_train_thresholds, synthetic_val_fprs, synthetic_val_tprs, synthetic_val_thresholds, synthetic_both_fprs, synthetic_both_tprs, synthetic_both_thresholds, ) return (model_id, *results) def run_experiment(): args = parse_argv() run_dir = pathlib.Path(args.run_dir) config_path = args.config_path n_procs = args.n_procs devices = args.devices dry_run = args.dry_run dev_run = args.dev_run seed = args.seed configure_logging(args.log_level) if seed: seed = int(seed) logging.info('Using seed value: %s', seed) if dry_run: logging.info('Executing in dry run mode (models are not trained, only a sample of the data is used)') if dev_run: logging.info('Executing dev run (models are trained for one epoch, only a sample of the data is used)') create_run_dir(run_dir, dry_run) datasets_config, sweep_params = read_configurations(config_path) data_sweep_params = {k: eval(str(v)) for k, v in sweep_params['data'].items()} model_sweep_params = {k: eval(str(v)) for k, v in sweep_params['model'].items()} run_configs = build_run_configs( run_dir, datasets_config, data_sweep_params, model_sweep_params, devices, dry_run, dev_run, seed ) logging.info('Submitted %s configs', len(run_configs)) logging.info('Starting %s processes with devices %s', n_procs, devices) results = [] with mp.Pool(n_procs) as pool: for model_results in pool.imap_unordered(run_instance, run_configs): if not dry_run: results.append(model_results) results_save_path = results_path(run_dir) if not dry_run: results_df = pd.DataFrame.from_records( results, columns=[ 'model_id', 'real_tpr', 'real_threshold', 'synthetic_train_tpr', 'synthetic_train_threshold', 'synthetic_val_tpr', 'synthetic_val_threshold', 'synthetic_both_tpr', 'synthetic_both_threshold' ] ) results_df.to_csv(results_save_path) logging.info('Saved experience results to \'%s\'', results_save_path) logging.info('Finished Successfully') if __name__ == '__main__': run_experiment()
{ "alphanum_fraction": 0.6790624712, "author": null, "avg_line_length": 32.0147710487, "converted": null, "ext": "py", "file": null, "hexsha": "148768d65adfd791543059fb146f5ce7ad26ff2f", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-09-06T04:17:59.000Z", "max_forks_repo_forks_event_min_datetime": "2021-09-06T04:17:59.000Z", "max_forks_repo_head_hexsha": "49ac63bc0d1cf2240c1889f652a9a100241fecb9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "feedzai/fairbench", "max_forks_repo_path": "notebooks/data_generation/ctgan-hyperparameter-search.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "49ac63bc0d1cf2240c1889f652a9a100241fecb9", "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": "feedzai/fairbench", "max_issues_repo_path": "notebooks/data_generation/ctgan-hyperparameter-search.py", "max_line_length": 120, "max_stars_count": 4, "max_stars_repo_head_hexsha": "49ac63bc0d1cf2240c1889f652a9a100241fecb9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "feedzai/fairbench", "max_stars_repo_path": "notebooks/data_generation/ctgan-hyperparameter-search.py", "max_stars_repo_stars_event_max_datetime": "2021-11-08T08:38:46.000Z", "max_stars_repo_stars_event_min_datetime": "2021-09-05T11:20:52.000Z", "num_tokens": 5123, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 21674 }
import pandas as pd import numpy as np from vincenty import vincenty from datetime import date, timedelta, datetime import pytz import math from ortools.constraint_solver import routing_enums_pb2 from ortools.constraint_solver import pywrapcp import boto3 from io import StringIO def report_generator(aws_access_key, aws_secret_key, aws_bucket_name): search_parameters = pywrapcp.DefaultRoutingSearchParameters() search_parameters.local_search_metaheuristic = ( routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH) search_parameters.time_limit.seconds = 30 search_parameters.log_search = True s3_resource = boto3.resource("s3", aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key, region_name="us-east-1") bucket = s3_resource.Bucket(aws_bucket_name) fecha_hoy = (datetime.now(pytz.timezone('Chile/Continental')) + timedelta(days=0)).strftime('%Y-%m-%d') #parametros id_transportadora = '0581-3' capacity = 25 trucks_no = 2 lng_tienda = -70.6068642 lat_tienda = -33.5138181 prefix = "ecommops/capacity/rutas/" + fecha_hoy + "/" name = 'Etapa_1_' + id_transportadora + '.csv' file_name = prefix + name csv_file = bucket.Object(file_name) df2 = pd.read_csv(csv_file.get()["Body"]) df2['lat'] = df2['lat'].astype(float) df2['lng'] = df2['lng'].astype(float) print(f'Etapa 2. Ingresaron {len(df2)} ordenes a la etapa 2 desde la etapa 1.') ### DISTANCIAS ### def vincenty_algo(lon1, lat1, lon2, lat2): place1 = (float(lon1), float(lat1)) place2 = (float(lon2), float(lat2)) dist = vincenty(place1, place2) return dist def get_distance_matrix(data4matrix): dist_matrix = [] for row in range(len(data4matrix)): temp_list = [] for col in range(len(data4matrix)): dist = vincenty_algo(data4matrix.loc[row, 'lat'], data4matrix.loc[row, 'lng'], data4matrix.loc[col, 'lat'], data4matrix.loc[col, 'lng']) temp_list.append(dist) dist_matrix.append(temp_list) return np.array(dist_matrix) def create_data_model(): data = {} distance_mtrx = get_distance_matrix(data_4_matrix) data['distance_matrix'] = distance_mtrx demand = [1 for x in range(len(distance_mtrx))] demand[0] = 0 data['demands'] = demand data['vehicle_capacities'] = [TRUCK_CAPACITY for x in range(trucks_needed)] data['num_vehicles'] = trucks_needed data['depot'] = 0 return data def print_solution(data, manager, routing, solution): #print(f'Objective: {solution.ObjectiveValue()}') total_distance = 0 total_load = 0 lista_rutas = [] lista_carga = [] dista_list = [] for vehicle_id in range(data['num_vehicles']): stops_list = [] index = routing.Start(vehicle_id) plan_output = 'Route for vehicle {}:\n'.format(vehicle_id) route_distance = 0 route_load = 0 while not routing.IsEnd(index): node_index = manager.IndexToNode(index) route_load += data['demands'][node_index] plan_output += ' Cliente {0} -> '.format(node_index) stops_list.append(node_index) previous_index = index index = solution.Value(routing.NextVar(index)) route_distance += routing.GetArcCostForVehicle( previous_index, index, vehicle_id) dista_list.append(route_distance) lista_carga.append(route_load) plan_output += ' Cliente {0}\n'.format(manager.IndexToNode(index)) stops_list.append(manager.IndexToNode(index)) plan_output += 'Distance of the route: {}km\n'.format(route_distance) plan_output += 'Load of the route: {}\n'.format(route_load) #print(plan_output) lista_rutas.append(stops_list) total_distance += route_distance total_load += route_load #print('Total distance of all routes: {}km'.format(total_distance)) #print('Total load of all routes: {}'.format(total_load)) return lista_rutas, dista_list, lista_carga def main(): data = create_data_model() manager = pywrapcp.RoutingIndexManager(len(data['distance_matrix']), data['num_vehicles'], data['depot']) routing = pywrapcp.RoutingModel(manager) def distance_callback(from_index, to_index): from_node = manager.IndexToNode(from_index) to_node = manager.IndexToNode(to_index) return data['distance_matrix'][from_node][to_node] transit_callback_index = routing.RegisterTransitCallback(distance_callback) routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index) def demand_callback(from_index): from_node = manager.IndexToNode(from_index) return data['demands'][from_node] demand_callback_index = routing.RegisterUnaryTransitCallback( demand_callback) routing.AddDimensionWithVehicleCapacity( demand_callback_index, 0, # null capacity slack data['vehicle_capacities'], # vehicle maximum capacities True, # start cumul to zero 'Capacity') search_parameters = pywrapcp.DefaultRoutingSearchParameters() search_parameters.first_solution_strategy = ( routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC) search_parameters.local_search_metaheuristic = ( routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH) search_parameters.time_limit.FromSeconds(1) solution = routing.SolveWithParameters(search_parameters) if solution: lista_rutas, dista_list, lista_carga = print_solution(data, manager, routing, solution) return lista_rutas, dista_list, lista_carga df_resultado_transportadora = pd.DataFrame() try: for transp in list(df2['transportadora'].unique()): TRUCK_CAPACITY = capacity df2_transportadora = df2.loc[df2['transportadora'] == transp] df2_transportadora = df2_transportadora.reset_index().drop(columns=['index']) trucks_needed = trucks_no #int(math.ceil(df2_transportadora.shape[0] / TRUCK_CAPACITY)) # if trucks_needed > 2: # print('Etapa 2: Se ha excedido el numero maximo de camiones, por lo que se ha creado mas de 2 rutas') centro_distribucion = [] centro_distribucion.insert(0, {'Orden': 'Origen', 'lat': lat_tienda,'lng': lng_tienda}) data_4_matrix = pd.concat([pd.DataFrame(centro_distribucion), df2_transportadora], ignore_index=True) data_4_matrix.reset_index(inplace=True, drop=True) lista_rutas, dista_list, lista_carga = main() df_resultado_rutas = pd.DataFrame() for ruta in range(len(lista_rutas)): df_resultado_transportadora_parcial = data_4_matrix[(data_4_matrix.index.isin(lista_rutas[ruta]))] df_resultado_transportadora_parcial = df_resultado_transportadora_parcial.reindex(lista_rutas[ruta]) df_resultado_transportadora_parcial = df_resultado_transportadora_parcial.fillna('Mirador') df_resultado_transportadora_parcial['Ruta'] = 'Camion ' + str(ruta) df_resultado_rutas = pd.concat([df_resultado_rutas, df_resultado_transportadora_parcial]) df_resultado_transportadora = pd.concat([df_resultado_transportadora, df_resultado_rutas]) df_resultado_transportadora = df_resultado_transportadora[df_resultado_transportadora['Orden'] != 'Origen'] buffer = StringIO() df_resultado_transportadora.to_csv(buffer, header=True, index=True, encoding="utf-8") buffer.seek(0) name2 = 'Etapa_2_' + id_transportadora + '.csv' file_name2 = prefix+name2 s3_client = boto3.client("s3", aws_access_key_id=aws_access_key, aws_secret_access_key=aws_secret_key, region_name = "us-east-1") response = s3_client.put_object(Bucket=aws_bucket_name, Key=file_name2, Body=buffer.getvalue()) print(f'Etapa 2. El numero de ordenes procesadas fue de {len(df_resultado_transportadora)}') except Exception as e: print(f"Etapa 2 Error: Se excedio el numero maximo de camiones permitido.") return False if len(df_resultado_transportadora) != 0: print('Etapa 2. Se ha finalizado exitosamente la ejecucion de la segunda etapa.') else: print('Etapa 2. El dataframe no tiene registros, repetir operacion') return True
{ "alphanum_fraction": 0.6389282213, "author": null, "avg_line_length": 40.9866071429, "converted": null, "ext": "py", "file": null, "hexsha": "95614ae404aed647f78faafa9f8670db7b30365b", "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": "24c96206042f1e8dd351daf9e3a1cb25ce6cbeee", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "SMU-AD/Rutas", "max_forks_repo_path": "Etapa_2_Optimizador.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "24c96206042f1e8dd351daf9e3a1cb25ce6cbeee", "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": "SMU-AD/Rutas", "max_issues_repo_path": "Etapa_2_Optimizador.py", "max_line_length": 138, "max_stars_count": null, "max_stars_repo_head_hexsha": "24c96206042f1e8dd351daf9e3a1cb25ce6cbeee", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "SMU-AD/Rutas", "max_stars_repo_path": "Etapa_2_Optimizador.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2083, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 9181 }
/* * The MIT License (MIT) * * Copyright (c) 2018 Sylko Olzscher * */ #include "test-mbus-001.h" #include <iostream> #include <fstream> #include <boost/test/unit_test.hpp> #include <smf/mbus/defs.h> namespace node { bool test_mbus_001() { // 0x0442 BOOST_CHECK_EQUAL(sml::encode_id("ABB"), 0x0442); BOOST_CHECK_EQUAL(sml::encode_id("ABB"), sml::encode_id("abb")); return true; } }
{ "alphanum_fraction": 0.6641975309, "author": null, "avg_line_length": 16.2, "converted": null, "ext": "cpp", "file": null, "hexsha": "d2e17f6dd166b256e751c10b2276988369063385", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 2, "max_forks_repo_forks_event_max_datetime": "2020-03-03T12:40:30.000Z", "max_forks_repo_forks_event_min_datetime": "2019-11-09T09:14:48.000Z", "max_forks_repo_head_hexsha": "e35e127867a4f66129477b780cbd09c5231fc7da", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "solosTec/node", "max_forks_repo_path": "test/unit-test/src/test-mbus-001.cpp", "max_issues_count": 7, "max_issues_repo_head_hexsha": "e35e127867a4f66129477b780cbd09c5231fc7da", "max_issues_repo_issues_event_max_datetime": "2021-05-17T09:52:07.000Z", "max_issues_repo_issues_event_min_datetime": "2020-01-14T20:38:04.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "solosTec/node", "max_issues_repo_path": "test/unit-test/src/test-mbus-001.cpp", "max_line_length": 66, "max_stars_count": 2, "max_stars_repo_head_hexsha": "e35e127867a4f66129477b780cbd09c5231fc7da", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "solosTec/node", "max_stars_repo_path": "test/unit-test/src/test-mbus-001.cpp", "max_stars_repo_stars_event_max_datetime": "2021-05-06T06:20:19.000Z", "max_stars_repo_stars_event_min_datetime": "2020-03-03T12:40:29.000Z", "num_tokens": 131, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 405 }
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2012 - 2014 MetaScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_TOINTS_HPP_INCLUDED #define BOOST_SIMD_ARITHMETIC_FUNCTIONS_SIMD_COMMON_TOINTS_HPP_INCLUDED #include <boost/simd/arithmetic/functions/toints.hpp> #include <boost/simd/include/functions/simd/toint.hpp> #include <boost/simd/include/functions/simd/bitwise_cast.hpp> #include <boost/simd/include/functions/simd/saturate.hpp> #include <boost/simd/include/functions/simd/is_less_equal.hpp> #include <boost/simd/include/functions/simd/is_greater_equal.hpp> #include <boost/simd/include/functions/simd/splat.hpp> #include <boost/simd/include/functions/simd/if_else.hpp> #include <boost/simd/include/constants/valmin.hpp> #include <boost/simd/include/constants/valmax.hpp> #include <boost/simd/sdk/meta/scalar_of.hpp> #include <boost/simd/sdk/config.hpp> #include <boost/dispatch/meta/as_integer.hpp> #include <boost/dispatch/attributes.hpp> #ifndef BOOST_SIMD_NO_NANS #include <boost/simd/include/functions/simd/if_zero_else.hpp> #include <boost/simd/include/functions/simd/is_nan.hpp> #endif namespace boost { namespace simd { namespace ext { BOOST_DISPATCH_IMPLEMENT ( toints_, tag::cpu_ , (A0)(X) , ((simd_<uint_<A0>,X>)) ) { typedef typename dispatch::meta::as_integer<A0, signed>::type result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0) const { return bitwise_cast<result_type>(saturate<result_type>(a0)); } }; BOOST_DISPATCH_IMPLEMENT ( toints_, tag::cpu_ , (A0)(X) , ((simd_<int_<A0>,X>)) ) { typedef A0 result_type; BOOST_FORCEINLINE result_type operator()(A0 const& a0) const { return a0; } }; BOOST_DISPATCH_IMPLEMENT ( toints_, tag::cpu_ , (A0)(X) , ((simd_<floating_<A0>,X>)) ) { typedef typename dispatch::meta::as_integer<A0>::type result_type; BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(1) { typedef typename meta::scalar_of<result_type>::type sr_t; const A0 Vax = splat<A0>(boost::simd::Valmax<sr_t>()); const A0 Vix = splat<A0>(boost::simd::Valmin<sr_t>()); #ifndef BOOST_SIMD_NO_NANS A0 aa0 = if_zero_else(is_nan(a0), a0); return if_else(boost::simd::le(aa0, Vix), Valmin<result_type>(), if_else(boost::simd::ge(aa0, Vax), Valmax<result_type>(), toint(aa0) ) ); #else return if_else(boost::simd::le(a0, Vix), Valmin<result_type>(), if_else(boost::simd::ge(a0, Vax), Valmax<result_type>(), toint(a0) ) ); #endif } }; } } } #endif
{ "alphanum_fraction": 0.5672696439, "author": null, "avg_line_length": 39.3111111111, "converted": null, "ext": "hpp", "file": null, "hexsha": "dc626ef2c30516ed92bfa5f73034c241ea93534d", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 7, "max_forks_repo_forks_event_max_datetime": "2021-07-31T12:46:14.000Z", "max_forks_repo_forks_event_min_datetime": "2017-12-02T12:59:17.000Z", "max_forks_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "psiha/nt2", "max_forks_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/toints.hpp", "max_issues_count": null, "max_issues_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "psiha/nt2", "max_issues_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/toints.hpp", "max_line_length": 80, "max_stars_count": 34, "max_stars_repo_head_hexsha": "5e829807f6b57b339ca1be918a6b60a2507c54d0", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "psiha/nt2", "max_stars_repo_path": "modules/boost/simd/base/include/boost/simd/arithmetic/functions/simd/common/toints.hpp", "max_stars_repo_stars_event_max_datetime": "2022-01-04T02:18:13.000Z", "max_stars_repo_stars_event_min_datetime": "2017-05-19T18:10:17.000Z", "num_tokens": 811, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 3538 }
# coding=utf-8 # Copyright 2022 HyperBO Authors. # # 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. """Objective functions for training a GP.""" import functools import logging from hyperbo.basics import linalg from hyperbo.basics import params_utils from hyperbo.gp_utils import utils import jax.numpy as jnp retrieve_params = params_utils.retrieve_params def sample_mean_cov_regularizer(mean_func, cov_func, params, dataset, warp_func=None, distance=utils.kl_multivariate_normal, use_feat0=False): """Compute a regularizer on sample mean and sample covariance. The returned regularizer aims to minimize the distance between the multivariate normal specified by sample mean/covariance and the multivariate normal specified by the parameterized GP. We support KL divergence as distance or squared Euclidean distance. Args: mean_func: mean function handle that maps from (params, n x d input, warp_func) to an n dimensional mean vector. (see vector_map in mean.py for more details). cov_func: covariance function handle that maps from (params, n1 x d input1, n2 x d input2, wrap_func) to a n1 x n2 covariance matrix (see matrix_map in kernel.py for more details). params: parameters for covariance, mean, and noise variance. dataset: Dict[Union[int, str], SubDataset], a dictionary mapping from key to SubDataset. For aligned sub-dataset, this function should only be used if each aligned sub-dataset only has (?, m) for y shape, where m > 1. warp_func: optional dictionary that specifies the warping function for each parameter. distance: distance function; currently support utils.kl_multivariate_normal or utils.euclidean_multivariate_normal. use_feat0: set to True if feat0 needs to be set in the distance function. Returns: Weighted l2 regularizer on sample mean and sample covariance. """ def compute_regularizer_dataset_subset(sub_dataset): """Compute the regularizer on a subset of dataset keys.""" if sub_dataset.y.shape[0] == 0: return 0. mu_data = jnp.mean(sub_dataset.y, axis=1) cov_data = jnp.cov(sub_dataset.y, bias=True) mu_model = mean_func(params, sub_dataset.x, warp_func=warp_func).flatten() noise_variance, = retrieve_params( params, ['noise_variance'], warp_func=warp_func) cov_model = cov_func( params, sub_dataset.x, warp_func=warp_func) + jnp.eye(sub_dataset.x.shape[0]) * noise_variance return distance( mu0=mu_data, cov0=cov_data, mu1=mu_model, cov1=cov_model, feat0=sub_dataset.y - mu_data[:, None] if use_feat0 else None) return jnp.sum( jnp.array([ compute_regularizer_dataset_subset(sub_dataset) for sub_dataset in dataset.values() if sub_dataset.aligned is not None ])) sample_mean_cov_regularizer_euc = functools.partial( sample_mean_cov_regularizer, distance=utils.euclidean_multivariate_normal) def neg_log_marginal_likelihood(mean_func, cov_func, params, dataset, warp_func=None, exclude_aligned=True): """Compute the negative of marginal likelihood of a (multi-task) GP. Args: mean_func: mean function handle that maps from (params, n x d input, warp_func) to an n dimensional mean vector. (see vector_map in mean.py for more details). cov_func: covariance function handle that maps from (params, n1 x d input1, n2 x d input2, wrap_func) to a n1 x n2 covariance matrix (see matrix_map in kernel.py for more details). params: parameters for covariance, mean, and noise variance. dataset: Dict[Union[int, str], SubDataset], a dictionary mapping from key to SubDataset. warp_func: optional dictionary that specifies the warping function for each parameter. exclude_aligned: exclude sub-datasets that are aligned. Returns: Negative log marginal likelihood. """ def compute_nll_sub_dataset(vx, vy): """Compute negative log likelihood for one sub dataset.""" chol, kinvy, vy = linalg.solve_gp_linear_system( mean_func=mean_func, cov_func=cov_func, params=params, x=vx, y=vy, warp_func=warp_func) nll_val = jnp.sum(0.5 * jnp.dot(vy.T, kinvy) + jnp.sum(jnp.log(jnp.diag(chol))) + 0.5 * len(vx) * jnp.log(2 * jnp.pi)) return nll_val total_nll = 0. for s in dataset.values(): if exclude_aligned and s.aligned is not None: continue if s.x.shape[0] == 0: continue total_nll += compute_nll_sub_dataset(s.x, s.y) # We should really be including priors on the hyperparameters here. if 'priors' in params.config: for k in params.model: if k in params.config['priors']: log_prior_fn = params.config['priors'][k] val, = retrieve_params(params, [k], warp_func) log_prior_prob = log_prior_fn(val) logging.info(msg=f'log_prior_prob({k}={val}) = {log_prior_prob}') total_nll -= log_prior_prob else: logging.warning('No prior provided for param %s', k) return total_nll nll = neg_log_marginal_likelihood regkl = sample_mean_cov_regularizer regeuc = sample_mean_cov_regularizer_euc def add(*objectives): def added_objective(*args, **kwargs): return sum([obj(*args, **kwargs) for obj in objectives]) return added_objective def mul(c, obj): def multiplied_objective(*args, **kwargs): return c * obj(*args, **kwargs) return multiplied_objective nll_regkl = lambda c: add(nll, mul(c, regkl)) nll_regeuc = lambda c: add(nll, mul(c, regeuc)) nll_regkl1 = nll_regkl(1.) nll_regeuc1 = nll_regeuc(1.) nll_regkl01 = nll_regkl(.1) nll_regeuc01 = nll_regkl(.1) nll_regkl10 = nll_regkl(10.) nll_regeuc10 = nll_regkl(10.)
{ "alphanum_fraction": 0.6748909282, "author": null, "avg_line_length": 35.1693121693, "converted": null, "ext": "py", "file": null, "hexsha": "6e8156415acfdf49e7609e675c97a2de761d93e0", "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": "a8c848920fb7de41ed89ac0ff61c5c45fcaa90a0", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "google-research/hyperbo", "max_forks_repo_path": "hyperbo/gp_utils/objectives.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "a8c848920fb7de41ed89ac0ff61c5c45fcaa90a0", "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": "google-research/hyperbo", "max_issues_repo_path": "hyperbo/gp_utils/objectives.py", "max_line_length": 80, "max_stars_count": 3, "max_stars_repo_head_hexsha": "a8c848920fb7de41ed89ac0ff61c5c45fcaa90a0", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "google-research/hyperbo", "max_stars_repo_path": "hyperbo/gp_utils/objectives.py", "max_stars_repo_stars_event_max_datetime": "2022-03-24T16:10:21.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-23T20:54:34.000Z", "num_tokens": 1587, "path": null, "reason": "import jax", "repo": null, "save_path": null, "sha": null, "size": 6647 }
import collections import os import sys import random import matplotlib.pyplot as plt import numpy as np import scipy.io as sio import torch from PIL import Image, ImageMath from torch.utils import data from main import get_data_path from torchvision.transforms import Compose, Normalize, Resize, ToTensor sys.path.append('/home/wenlidai/msc-project/main/loader') from BaseLoader import Loader class SEMSEG_LOADER(Loader): def __init__(self, mode, n_classes, transform=None, target_transform=None, img_size=512, ignore_index=255, do_transform=False, portion=1): super(SEMSEG_LOADER, self).__init__( mode, n_classes, transform, target_transform, img_size, ignore_index, do_transform, portion=portion) def __getitem__(self, index): img = None mask = None img_path, mask_path = self.imgs[index] img = Image.open(img_path).convert('RGB') if mask_path.split('.')[-1] == 'mat': mask = sio.loadmat(mask_path)['GTcls']['Segmentation'][0][0] mask = Image.fromarray(mask.astype(np.uint8)).convert('P') else: mask = Image.open(mask_path).convert('P') if self.do_transform: img, mask = self.further_transform(img, mask) else: img, mask = self.crop(img, mask) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: mask = self.target_transform(mask) return img, mask def get_pascal_labels(self): ''' 21 classes: - Person: person - Animal: bird, cat, cow, dog, horse, sheep - Vehicle: aeroplane, bicycle, boat, bus, car, motorbike, train - Indoor: bottle, chair, dining table, potted plant, sofa, tv/monitor ''' return np.asarray([ [0,0,0], [128,0,0], [0,128,0], [128,128,0], [0,0,128], [128,0,128], [0,128,128], [128,128,128], [64,0,0], [192,0,0], [64,128,0], [192,128,0], [64,0,128], [192,0,128], [64,128,128], [192,128,128], [0,64,0], [128,64,0], [0,192,0], [128,192,0], [0,64,128] ]) def preprocess(self, mode): assert mode in ['train', 'val', 'test'] items = [] sbd_path = get_data_path('sbd') sbd_img_path = os.path.join(sbd_path, 'dataset', 'img') sbd_mask_path = os.path.join(sbd_path, 'dataset', 'cls') voc_path = get_data_path('pascal') voc_test_path = get_data_path('pascal_test') voc_img_path = os.path.join(voc_path, 'JPEGImages') voc_mask_path = os.path.join(voc_path, 'SegmentationClass') # Train data = VOC_train + SBD_train + SBD_val if mode == 'train': sbd_data_list = [l.strip('\n') for l in open(os.path.join( sbd_path, 'dataset', 'trainval.txt')).readlines()] # SBD dataset contains some of the voc_val samples, so we have to remove them voc_val_data_list = [l.strip('\n') for l in open(os.path.join( voc_path, 'ImageSets', 'Segmentation', 'val.txt')).readlines()] sbd_data_list = list(set(sbd_data_list) - set(voc_val_data_list)) for it in sbd_data_list: item = (os.path.join(sbd_img_path, it + '.jpg'), os.path.join(sbd_mask_path, it + '.mat')) items.append(item) voc_data_list = [l.strip('\n') for l in open(os.path.join( voc_path, 'ImageSets', 'Segmentation', 'train.txt')).readlines()] for it in voc_data_list: item = (os.path.join(voc_img_path, it + '.jpg'), os.path.join(voc_mask_path, it + '.png')) items.append(item) # Val data = VOC_val elif mode == 'val': data_list = [l.strip('\n') for l in open(os.path.join( voc_path, 'ImageSets', 'Segmentation', 'val.txt')).readlines()] for it in data_list: item = (os.path.join(voc_img_path, it + '.jpg'), os.path.join(voc_mask_path, it + '.png')) items.append(item) # Test data = VOC_test else: img_path = os.path.join(voc_test_path, 'JPEGImages') data_list = [l.strip('\n') for l in open(os.path.join( voc_path, 'ImageSets', 'Segmentation', 'test.txt')).readlines()] for it in data_list: items.append((img_path, it)) return items class PASCAL_PARTS_LOADER(Loader): def __init__(self, mode, n_classes, transform=None, target_transform=None, img_size=512, ignore_index=255, do_transform=False, portion=1): super(PASCAL_PARTS_LOADER, self).__init__( mode, n_classes, transform, target_transform, img_size, ignore_index, do_transform, portion=portion) def __getitem__(self, index): img_path, mask_path = self.imgs[index] img = Image.open(img_path).convert('RGB') mask = Image.open(mask_path).convert('P') if self.do_transform: img, mask = self.further_transform(img, mask) else: img, mask = self.crop(img, mask) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: mask = self.target_transform(mask) return img, mask def get_pascal_labels(self): # 7 classes (background, head, torso, upper/lower arms, upper/lower legs) return np.asarray([ [0,0,0], [128,0,0], [0,128,0], [128,128,0], [0,0,128], [128,0,128], [0,128,128] ]) def preprocess(self, mode): assert mode in ['train', 'val', 'test'] data_path = get_data_path('pascalparts') if mode == 'train': data_list = [l.strip('\n') for l in open(os.path.join( data_path, 'ImageSets', 'Person', 'train.txt')).readlines()] elif mode == 'val': data_list = [l.strip('\n') for l in open(os.path.join( data_path, 'ImageSets', 'Person', 'val.txt')).readlines()] items = [] img_path = os.path.join(data_path, 'JPEGImages') mask_path = os.path.join(data_path, 'ImageSets', 'Person', 'gt') for it in data_list: item = (os.path.join(img_path, it + '.jpg'), os.path.join(mask_path, it + '.png')) items.append(item) return items class LIP_LOADER(Loader): def __init__(self, mode, n_classes, transform=None, target_transform=None, img_size=256, ignore_index=255, do_transform=False, portion=1): super(LIP_LOADER, self).__init__( mode, n_classes, transform, target_transform, img_size, ignore_index, do_transform, portion=portion) def __getitem__(self, index): img_path, mask_path = self.imgs[index] img = Image.open(img_path).convert('RGB') mask = Image.open(mask_path).convert('P') if self.do_transform: img, mask = self.further_transform(img, mask) else: img, mask = self.crop(img, mask) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: mask = self.target_transform(mask) return img, mask def get_pascal_labels(self): # 20 classes return np.asarray([ [0,0,0], [128,0,0], [0,128,0], [128,128,0], [0,0,128], [128,0,128], [0,128,128], [128,128,128], [64,0,0], [192,0,0], [64,128,0], [192,128,0], [64,0,128], [192,0,128], [64,128,128], [192,128,128], [0,64,0], [128,64,0], [0,192,0], [128,192,0] ]) def preprocess(self, mode): assert mode in ['train', 'val', 'test'] items = [] data_path = get_data_path('lip') if mode == 'train': img_path = os.path.join(data_path, 'multi-person', 'Training', 'Images') mask_path = os.path.join(data_path, 'multi-person', 'Training', 'Category_ids') data_list = [l.strip('\n') for l in open(os.path.join( data_path, 'multi-person', 'Training', 'train_id.txt')).readlines()] for it in data_list: item = (os.path.join(img_path, it + '.jpg'), os.path.join(mask_path, it + '.png')) items.append(item) elif mode == 'val': img_path = os.path.join(data_path, 'multi-person', 'Validation', 'Images') mask_path = os.path.join(data_path, 'multi-person', 'Validation', 'Category_ids') data_list = [l.strip('\n') for l in open(os.path.join( data_path, 'multi-person', 'Validation', 'val_id.txt')).readlines()] for it in data_list: item = (os.path.join(img_path, it + '.jpg'), os.path.join(mask_path, it + '.png')) items.append(item) return items[0:11716] class PASCAL_HUMAN_SEMSEG_LOADER(Loader): def __init__(self, mode, n_classes, transform=None, target_transform=None, img_size=512, ignore_index=255, do_transform=False, portion=1): super(PASCAL_HUMAN_SEMSEG_LOADER, self).__init__( mode, n_classes, transform, target_transform, img_size, ignore_index, do_transform, portion=portion) def __getitem__(self, index): img_path, mask_path = self.imgs[index] img = Image.open(img_path).convert('RGB') if mask_path.split('.')[-1] == 'mat': mask = sio.loadmat(mask_path)['GTcls']['Segmentation'][0][0] mask = Image.fromarray(mask.astype(np.uint8)).convert('P') else: mask = Image.open(mask_path).convert('P') if self.do_transform: img, mask = self.further_transform(img, mask) else: img, mask = self.crop(img, mask) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: mask = self.target_transform(mask) return img, mask def get_pascal_labels(self): return np.asarray([ [0,0,0], [128,0,0], [0,128,0], [128,128,0], [0,0,128], [128,0,128], [0,128,128], [128,128,128], [64,0,0], [192,0,0], [64,128,0], [192,128,0], [64,0,128], [192,0,128], [64,128,128], [192,128,128], [0,64,0], [128,64,0], [0,192,0], [128,192,0], [0,64,128] ]) def preprocess(self, mode): assert mode in ['train', 'val', 'test'] pascal_data_path = get_data_path('pascal') sbd_data_path = get_data_path('sbd') items = [] if mode == 'train': p = open(os.path.join(pascal_data_path, 'ImageSets', 'Person', 'train.txt')).readlines() s = open(os.path.join(sbd_data_path, 'dataset', 'train.txt')).readlines() lines = list(set(p).intersection(s)) data_list = [l.strip('\n') for l in lines] elif mode == 'val': p = open(os.path.join(pascal_data_path, 'ImageSets', 'Person', 'val.txt')).readlines() s = open(os.path.join(sbd_data_path, 'dataset', 'val.txt')).readlines() lines = list(set(p).intersection(s)) data_list = [l.strip('\n') for l in lines] img_path = os.path.join(sbd_data_path, 'dataset', 'img') mask_path = os.path.join(sbd_data_path, 'dataset', 'cls') for it in data_list: item = (os.path.join(img_path, it + '.jpg'), os.path.join(mask_path, it + '.mat')) items.append(item) return items class PASCAL_HUMAN_PARTS_LOADER(Loader): def __init__(self, mode, n_classes, transform=None, target_transform=None, img_size=512, ignore_index=255, do_transform=False, portion=1): super(PASCAL_HUMAN_PARTS_LOADER, self).__init__( mode, n_classes, transform, target_transform, img_size, ignore_index, do_transform, portion=portion) def __getitem__(self, index): img_path, mask_path = self.imgs[index] img = Image.open(img_path).convert('RGB') if mask_path.split('.')[-1] == 'mat': mask = sio.loadmat(mask_path)['GTcls']['Segmentation'][0][0] mask = Image.fromarray(mask.astype(np.uint8)).convert('P') else: mask = Image.open(mask_path).convert('P') if self.do_transform: img, mask = self.further_transform(img, mask) else: img, mask = self.crop(img, mask) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: mask = self.target_transform(mask) return img, mask def get_pascal_labels(self): return np.asarray([ [0,0,0], [128,0,0], [0,128,0], [128,128,0], [0,0,128], [128,0,128], [0,128,128] ]) def preprocess(self, mode): assert mode in ['train', 'val', 'test'] pascal_data_path = get_data_path('pascal') sbd_data_path = get_data_path('sbd') items = [] if mode == 'train': p = open(os.path.join(pascal_data_path, 'ImageSets', 'Person', 'train.txt')).readlines() s = open(os.path.join(sbd_data_path, 'dataset', 'train.txt')).readlines() lines = list(set(p).intersection(s)) data_list = [l.strip('\n') for l in lines] elif mode == 'val': p = open(os.path.join(pascal_data_path, 'ImageSets', 'Person', 'val.txt')).readlines() s = open(os.path.join(sbd_data_path, 'dataset', 'val.txt')).readlines() lines = list(set(p).intersection(s)) data_list = [l.strip('\n') for l in lines] img_path = os.path.join(sbd_data_path, 'dataset', 'img') mask_path = os.path.join(pascal_data_path, 'ImageSets', 'Person', 'gt') for it in data_list: item = (os.path.join(img_path, it + '.jpg'), os.path.join(mask_path, it + '.png')) items.append(item) return items class PASCAL_HUMAN_LOADER(Loader): def __init__(self, mode, n_classes, transform=None, target_transform=None, img_size=512, ignore_index=255, do_transform=False, portion=1): super(PASCAL_HUMAN_LOADER, self).__init__( mode, n_classes, transform, target_transform, img_size, ignore_index, do_transform, portion=portion) def __getitem__(self, index): img_path, sbd_mask_path, lip_mask_path = self.imgs[index] img = Image.open(img_path).convert('RGB') if sbd_mask_path.split('.')[-1] == 'mat': sbd_mask = sio.loadmat(sbd_mask_path)['GTcls']['Segmentation'][0][0] sbd_mask = Image.fromarray(sbd_mask.astype(np.uint8)).convert('P') else: sbd_mask = Image.open(sbd_mask_path).convert('P') if lip_mask_path.split('.')[-1] == 'mat': lip_mask = sio.loadmat(lip_mask_path)['GTcls']['Segmentation'][0][0] lip_mask = Image.fromarray(lip_mask.astype(np.uint8)).convert('P') else: lip_mask = Image.open(lip_mask_path).convert('P') if self.do_transform: img_transformed, sbd_mask = self.further_transform(img, sbd_mask) _, lip_mask = self.further_transform(img, lip_mask) else: img_transformed, sbd_mask = self.crop(img, sbd_mask) _, lip_mask = self.crop(img, lip_mask) if self.transform is not None: img_transformed = self.transform(img_transformed) if self.target_transform is not None: sbd_mask = self.target_transform(sbd_mask) lip_mask = self.target_transform(lip_mask) return img_transformed, sbd_mask, lip_mask def get_pascal_labels(self): return np.asarray([ [0,0,0], [128,0,0], [0,128,0], [128,128,0], [0,0,128], [128,0,128], [0,128,128], [128,128,128], [64,0,0], [192,0,0], [64,128,0], [192,128,0], [64,0,128], [192,0,128], [64,128,128], [192,128,128], [0,64,0], [128,64,0], [0,192,0], [128,192,0], [0,64,128] ]) def decode_segmap(self, temp, plot=False, task=0): label_colours = self.get_pascal_labels() if task == 1: label_colours = label_colours[0:7] r = temp.copy() g = temp.copy() b = temp.copy() for l in range(0, self.n_classes[task]): r[temp == l] = label_colours[l, 0] g[temp == l] = label_colours[l, 1] b[temp == l] = label_colours[l, 2] rgb = np.zeros((temp.shape[0], temp.shape[1], 3)) rgb[:, :, 0] = r rgb[:, :, 1] = g rgb[:, :, 2] = b if plot: plt.imshow(rgb) plt.show() else: return rgb def preprocess(self, mode): assert mode in ['train', 'val', 'test'] pascal_data_path = get_data_path('pascal') sbd_data_path = get_data_path('sbd') items = [] if mode == 'train': p = open(os.path.join(pascal_data_path, 'ImageSets', 'Person', 'train.txt')).readlines() s = open(os.path.join(sbd_data_path, 'dataset', 'train.txt')).readlines() lines = list(set(p).intersection(s)) data_list = [l.strip('\n') for l in lines] elif mode == 'val': p = open(os.path.join(pascal_data_path, 'ImageSets', 'Person', 'val.txt')).readlines() s = open(os.path.join(sbd_data_path, 'dataset', 'val.txt')).readlines() lines = list(set(p).intersection(s)) data_list = [l.strip('\n') for l in lines] img_path = os.path.join(sbd_data_path, 'dataset', 'img') semseg_mask_path = os.path.join(sbd_data_path, 'dataset', 'cls') parts_mask_path = os.path.join(pascal_data_path, 'ImageSets', 'Person', 'gt') for it in data_list: item = ( os.path.join(img_path, it + '.jpg'), os.path.join(semseg_mask_path, it + '.mat'), os.path.join(parts_mask_path, it + '.png') ) items.append(item) return items class SBD_LIP_LOADER(Loader): def __init__(self, mode, n_classes, transform=None, target_transform=None, img_size=512, ignore_index=255, do_transform=False, portion=1): self.sbd_loader = SEMSEG_LOADER( mode, n_classes[0], transform, target_transform, img_size, ignore_index, do_transform, portion=portion) self.lip_loader = LIP_LOADER( mode, n_classes[1], transform, target_transform, img_size, ignore_index, do_transform, portion=portion) super(SBD_LIP_LOADER, self).__init__( mode, n_classes, transform, target_transform, img_size, ignore_index, do_transform, portion=1) def __getitem__(self, index): img_path, mask_path = self.imgs[index] img = Image.open(img_path).convert('RGB') if mask_path.split('.')[-1] == 'mat': mask = sio.loadmat(mask_path)['GTcls']['Segmentation'][0][0] mask = Image.fromarray(mask.astype(np.uint8)).convert('P') else: mask = Image.open(mask_path).convert('P') if self.do_transform: img, mask = self.further_transform(img, mask) else: img, mask = self.crop(img, mask) if self.transform is not None: img = self.transform(img) if self.target_transform is not None: mask = self.target_transform(mask) if 'person' in img_path: task = 1 else: task = 0 return img, mask, task def get_pascal_labels(self, task): if task == 0: return np.asarray([ [0,0,0], [128,0,0], [0,128,0], [128,128,0], [0,0,128], [128,0,128], [0,128,128], [128,128,128], [64,0,0], [192,0,0], [64,128,0], [192,128,0], [64,0,128], [192,0,128], [64,128,128], [192,128,128], [0,64,0], [128,64,0], [0,192,0], [128,192,0], [0,64,128] ]) else: return np.asarray([ [0,0,0], [128,0,0], [0,128,0], [128,128,0], [0,0,128], [128,0,128], [0,128,128], [128,128,128], [64,0,0], [192,0,0], [64,128,0], [192,128,0], [64,0,128], [192,0,128], [64,128,128], [192,128,128], [0,64,0], [128,64,0], [0,192,0], [128,192,0] ]) def decode_segmap(self, temp, task=0, plot=False): label_colours = self.get_pascal_labels(task) r = temp.copy() g = temp.copy() b = temp.copy() for l in range(0, self.n_classes[task]): r[temp == l] = label_colours[l, 0] g[temp == l] = label_colours[l, 1] b[temp == l] = label_colours[l, 2] rgb = np.zeros((temp.shape[0], temp.shape[1], 3)) rgb[:, :, 0] = r rgb[:, :, 1] = g rgb[:, :, 2] = b if plot: plt.imshow(rgb) plt.show() else: return rgb def preprocess(self, mode): sbd_items = self.sbd_loader.imgs lip_items = self.lip_loader.imgs lip_items = lip_items[0:len(sbd_items)] return sbd_items + lip_items # mask_obj = sio.loadmat(mask_path) # person_class_index = None # for i, class_name in enumerate(mask_obj['anno']['objects'][0,0]['class'][0]): # if class_name[0] == 'person': # person_class_index = i # for i, part in enumerate(mask_obj['anno']['objects'][0,0]['parts'][0, person_class_index][0]): # part_name = part[0][0] # part_index = self.get_part_index(part_name) # if i == 0: # mask = part[1] * part_index # else: # mask = mask + part[1] * part_index # mask = Image.fromarray(mask.astype(np.uint8)).convert('P') # def get_part_index(self, part_name): # ''' # coarse partition: # head = 1 # torso = 2 # arm = 3 # leg = 4 # (background = 0) # There are 24 finer parts in total # ''' # if part_name in ['head','leye','reye','lear','rear','lebrow','rebrow','nose','mouth','hair']: # return 1 # if part_name in ['torso','neck']: # return 2 # if part_name in ['llarm','luarm','lhand','rlarm','ruarm','rhand']: # return 3 # if part_name in ['llleg','luleg','lfoot','rlleg','ruleg','rfoot']: # return 4
{ "alphanum_fraction": 0.5517571746, "author": null, "avg_line_length": 39.3876500858, "converted": null, "ext": "py", "file": null, "hexsha": "a5da45ac0ce5fd4a11d776202e2904f232bf9986", "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": "d92efa80e8314aea153d498cce3c9c6e30c252bd", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "wenliangdai/sunets-reproduce", "max_forks_repo_path": "main/loader/loaders.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "d92efa80e8314aea153d498cce3c9c6e30c252bd", "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": "wenliangdai/sunets-reproduce", "max_issues_repo_path": "main/loader/loaders.py", "max_line_length": 142, "max_stars_count": 2, "max_stars_repo_head_hexsha": "d92efa80e8314aea153d498cce3c9c6e30c252bd", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "wenliangdai/sunets-reproduce", "max_stars_repo_path": "main/loader/loaders.py", "max_stars_repo_stars_event_max_datetime": "2018-07-02T16:03:07.000Z", "max_stars_repo_stars_event_min_datetime": "2018-07-02T16:03:07.000Z", "num_tokens": 6120, "path": null, "reason": "import numpy,import scipy", "repo": null, "save_path": null, "sha": null, "size": 22963 }
import numpy as np import cv2 import math from .pattern import bit_pattern_31 factorPI = (float)(np.pi/180.) class OrbExtractor(object): #ORB检测Oriented FAST关键点时选取的图像块边长, #即计算质心时选取的图像块区域边长 HALF_PATCH_SIZE = 15 PATCH_SIZE = 31 EDGE_THRESHOLD = 19 W = 30 #grid size, unit pixel def __init__(self): self.nfeatures = 1000 #total keypoints extracted self.nlevels = 5 #pyramid levels self.scaleFactor = 0.8 #[0,1] self.initThFAST = 20 #threshold for greyscale value between P and neighbors in FAST self.minThFast = 7 self.ScaleFactors = np.zeros((self.nlevels,)) self.LevelSigma = np.zeros((self.nlevels,)) self.ScaleFactors[0] = 1. self.LevelSigma[0] = 1. for i in range(1, self.nlevels): self.ScaleFactors[i] = self.ScaleFactors[i-1] * self.scaleFactor self.LevelSigma[i] = self.ScaleFactors[i] * self.ScaleFactors[i] self.InvScaleFactors = np.zeros((self.nlevels,)) self.InvLevelSigma = np.zeros((self.nlevels,)) for i in range(1, self.nlevels): self.InvScaleFactors[i] = 1. / self.ScaleFactors[i] self.InvLevelSigma[i] = 1. / self.LevelSigma[i] self.ImagePyramid = [] self.FeaturePerLevel = np.zeros((self.nlevels,)) #factor = 1. / self.scaleFactor factor = self.scaleFactor * self.scaleFactor DesiredFeaturePerScale = self.nfeatures*(1-factor)/(1-pow(factor, self.nlevels)) sum_features = 0 for i in range(self.nlevels - 1): self.FeaturePerLevel[i] = np.round(DesiredFeaturePerScale) sum_features += self.FeaturePerLevel[i] DesiredFeaturePerScale *= factor self.FeaturePerLevel[self.nlevels-1] = max(self.nfeatures-sum_features, 0) #用于后面计算描述子的随机采样点集合 #最后通过求 x 坐标对应在半径为 HALF_PATCH_SIZE(15, 使用灰度质心法计算特征点的方向信息时, # 图像块的半径)的圆上的 y 坐标,标出了一个圆形区域用来求特征点方向; npoints = 512 self.pattern = [] for i in range(npoints): self.pattern.append((bit_pattern_31[i*2], bit_pattern_31[i*2+1])) #This is for orientation #表示为1/4圆的弦上, v点对应的最大横坐标u #注意45度以下计算得到,45度以上按照对称得到 self.umax = np.zeros((self.HALF_PATCH_SIZE+1,),dtype=np.int32) vmax = int(np.floor(self.HALF_PATCH_SIZE * np.sqrt(2.) / 2 + 1)) vmin = int(np.ceil(self.HALF_PATCH_SIZE * np.sqrt(2.) / 2)) hp2 = self.HALF_PATCH_SIZE * self.HALF_PATCH_SIZE for v in range(vmax+1): self.umax[v] = np.round(np.sqrt(hp2 - v*v)) #使用了对称的方式计算上四分之一的圆周上的umax,目的也是为了保持严格的对称(如 #果按照常规的想法做,由于cvRound就会很容易出现不对称的情况,同时这些随机采样 #的特征点集也不能够满足旋转之后的采样不变性了) v0 = 0 for v in reversed(range(vmin, self.HALF_PATCH_SIZE+1)): while self.umax[v0]==self.umax[v0 + 1]: v0+=1 self.umax[v] = v0 v0+=1 def Extract(self, img): #compute orb features and descriptors on an image #orb are dispersed on the image using octree if img is None: return #get image for each pyramid level self._ComputePyramid(img) #提取FAST角点和利用OctTree allKeypoints = self._ComputeKeyPointsOctTree() #计算描述子 nKeypoints = 0 for level in range(self.nlevels): nKeypoints += int(len(allKeypoints[level])) print("total keypoints number:", nKeypoints) if nKeypoints==0: return #描述矩阵共有nkeypoints行,32列,元素数据类型为CV_8U #也就是说每个特征点由32个CV_8U的数字描述 #descriptors = np.zeros((nKeypoints, 32), dtype=np.uint8) offset = 0 output_kpts = [] output_desc = [] #按层数依次遍历特征点 for level in range(self.nlevels): keypoints = allKeypoints[level] nkeypointslevel = len(keypoints) if nkeypointslevel == 0: continue blurimg = np.copy(self.ImagePyramid[level]) #ORB BRIEF对噪音敏感,高斯模糊缓解噪声敏感问题 #第一个参数是输入,第二个参数是高斯卷积核大小 #第三、第四个参数是X、Y方向上的方差sigma #第五个参数是扩边方式 blurimg = cv2.GaussianBlur(blurimg, (7,7), 2, 2, cv2.BORDER_REFLECT_101) #计算特征点描述子 #desc = descriptors[offset:offset+nkeypointslevel, :] desc = self._ComputeDescriptors(blurimg, keypoints, self.pattern) #恢复尺度后输出特征点结果 levelscale = self.ScaleFactors[level] for i in range(nkeypointslevel): keypoints[i].pt = (keypoints[i].pt[0]/levelscale, keypoints[i].pt[1]/levelscale) output_kpts.append(keypoints[i]) output_desc.append(desc[i]) return output_kpts, output_desc def _ComputeDescriptors(self, blurimg, keypoints, pattern): #重新确认清零 desc = np.zeros((len(keypoints), 32), dtype=np.uint8) for i in range(len(keypoints)): desc[i,:] = self._ComputeOrbDescriptor(keypoints[i], blurimg, pattern) return desc def _ComputeOrbDescriptor(self, kpt, img, pattern): """ 利用FAST特征点检测时求取的主方向,旋转特征点邻域,但旋转整个Patch再提取 BRIEF特征描述子的计算代价较大,因此,ORB采用了一种更高效的方式,在每个特征 点邻域Patch内先选取256对(512个)随机点,将其进行旋转,然后做判决编码为二进制串 pattern: [512, 2] """ angle = float(kpt.angle) * factorPI #degree to rad a = float(math.cos(angle)) b = float(math.sin(angle)) center_x = int(kpt.pt[0]) center_y = int(kpt.pt[1]) def GetValue(idx): return img[center_y+int(pattern[idx][0]*b + pattern[idx][1]*a)]\ [center_x+int(pattern[idx][0]*a - pattern[idx][1]*b)] #一次迭代读取pattern的步长,在一次迭代中,一共会获取16个元素 #可以计算出一共要有32×16个点用于迭代,而在代码一开始的pattern中就是512个点 pattern_step = 16 desc = np.zeros((32,), dtype=np.uint8) for i in range(32): #即将16个点的对比信息压缩到一个uint里,其中每一位都代表一个点对的对比结果. #则每个特征点最后得到32个描述值 t0, t1 = GetValue(i * pattern_step + 0), GetValue(i * pattern_step + 1) val = np.uint8(t0<t1) t0, t1 = GetValue(i * pattern_step + 2), GetValue(i * pattern_step + 3) val |= ((t0<t1)<<1) t0, t1 = GetValue(i * pattern_step + 4), GetValue(i * pattern_step + 5) val |= ((t0 < t1) << 2) t0, t1 = GetValue(i * pattern_step + 6), GetValue(i * pattern_step + 7) val |= ((t0 < t1) << 3) t0, t1 = GetValue(i * pattern_step + 8), GetValue(i * pattern_step + 9) val |= ((t0 < t1) << 4) t0, t1 = GetValue(i * pattern_step + 10), GetValue(i * pattern_step + 11) val |= ((t0 < t1) << 5) t0, t1 = GetValue(i * pattern_step + 12), GetValue(i * pattern_step + 13) val |= ((t0 < t1) << 6) t0, t1 = GetValue(i * pattern_step + 14), GetValue(i * pattern_step + 15) val |= ((t0 < t1) << 7) desc[i] = val return desc def _ComputeKeyPointsOctTree(self): #将image分为W×W格子,在每个格子上单独做检测 allKeypoints = [] #extract features of each pyramid level for level in range(self.nlevels): feat_height, feat_width = self.ImagePyramid[level].shape minBorderX = self.EDGE_THRESHOLD - 3 minBorderY = minBorderX maxBorderX = feat_width - self.EDGE_THRESHOLD + 3 maxBorderY = feat_height - self.EDGE_THRESHOLD + 3 #大量数据进行处理的时候就要使用reserve主动分配内存以提升程序执行效率 #这里保留的是用户指定总特征个数的10倍的内存 vToDistributeKeysPerLevel = [] width = maxBorderX - minBorderX height = maxBorderY - minBorderY nCols = 1 if width<self.W else int(width / self.W) #格网列数 nRows = 1 if height<self.W else int(height / self.W) #格网行数 wCell = int(np.ceil(width/nCols)) #每个格网的宽度,向上取整 hCell = int(np.ceil(height/nRows)) #依照行列遍历每个格网进行处理 #这一部分其实可以考虑用GPU进行并行加速,因为每个格网提取FAST角点的过程是各自独立的 for i in range(nRows): iniY = minBorderY + i*hCell if iniY >= maxBorderY-3: continue maxY = iniY + hCell + 6 if maxY > maxBorderY: maxY = maxBorderY for j in range(nCols): iniX = minBorderX + j*wCell if iniX >= maxBorderX-6: continue maxX = iniX + wCell + 6 if maxX > maxBorderX: maxX = maxBorderX #每一个格网都会建一个临时的vector用于存放这个小格子里的特征点 fast_detector = cv2.FastFeatureDetector_create(threshold=self.initThFAST, nonmaxSuppression=True, type=cv2.FAST_FEATURE_DETECTOR_TYPE_9_16) vKeysCell = fast_detector.detect(self.ImagePyramid[level][iniY:maxY, iniX:maxX]) #print("==>Init FAST didn't detect keypoints, use min Fast instead.") if not vKeysCell: fast_detector = cv2.FastFeatureDetector_create(threshold=self.minThFast, nonmaxSuppression=True, type=cv2.FAST_FEATURE_DETECTOR_TYPE_9_16) vKeysCell = fast_detector.detect(self.ImagePyramid[level][iniY:maxY, iniX:maxX]) #对于每一小块grid,如果提取的特征点不为空进行后续处理 if vKeysCell: maxresponse = vKeysCell[0].response idx = 0 for k in range(1, len(vKeysCell)): if vKeysCell[k].response > maxresponse: maxresponse = vKeysCell[k].response idx = k keypnt = vKeysCell[idx] keypnt.pt = (keypnt.pt[0]+j*wCell, keypnt.pt[1]+i*hCell) if len(vToDistributeKeysPerLevel) < self.FeaturePerLevel[level]: vToDistributeKeysPerLevel.append(keypnt) #print("level:".format(level), len(vToDistributeKeysPerLevel)) #利用八叉树对每一层提取的特征点进行过滤,使其均匀分布 #提取keypoints时已经直接简单完成这一步,skip scaledPatchSize = self.PATCH_SIZE * self.ScaleFactors[level] for keypnt in vToDistributeKeysPerLevel: #其实就是相当于整体平移一下 keypnt.pt = (keypnt.pt[0]+minBorderX, keypnt.pt[1]+minBorderY) #octave是OpenCV的KeyPoint类的属性之一,int类型,说明这个特征点是位于金字塔的哪一层 keypnt.octave = level #size也是KeyPoint的属性之一,float类型,说明该特征点的有效范围(直径) #FAST本身并没有严格意义上的有效范围概念(硬要说也有,就是中心点与周围比较像素构成的圆的直径), #但ORB用的是Oriented FAST,在计算方向时有用到PATCH_SIZE,因此在这里就把计算方向的范围 #作为特征点的有效范围.根据上面的计算公式也知道,scaledPatchSize与PATCH_SIZE和不同层的缩放 #因子有关.在PATCH_SIZE一定的情况下(例如这里在代码一开始就设置为了30)只与缩放因子有关, #每一层的特征点有效范围都一样 keypnt.size = scaledPatchSize allKeypoints.append(vToDistributeKeysPerLevel) #计算角点的方向,也是特征点提取的倒数第二步(最后一步是计算描述子) for level in range(self.nlevels): self._ComputeOrientation(self.ImagePyramid[level], allKeypoints[level], self.umax) return allKeypoints def _ComputeOrientation(self, img, keypnts, umax): """ 计算每个keypnt的质心方向 img: image of this pyramid level keypnts: detected fast keypoints of this pyramid level umax: u坐标绝对值的最大值 """ for kpt in keypnts: kpt.angle = self._IC_Angle(img, kpt.pt, umax) def _IC_Angle(self, img, pt, umax): """ 灰度质心法:以几何中心和灰度质心的连线作为该特征点方向 img: image of this pyramid level pt: point (u,v) in pixel units umax: u坐标绝对值的最大值 """ m_01 = 0 m_10 = 1 center_x = int(pt[0]) center_y = int(pt[1]) #先单独算出中间v=0这一行 for u in range(-self.HALF_PATCH_SIZE, self.HALF_PATCH_SIZE+1): m_10 += u * img[center_y][center_x-u] #本来m_01应该是一列一列地计算的,但是由于对称以及坐标x,y正负的原因,可以一次计算两行 for v in range(1, self.HALF_PATCH_SIZE+1): v_sum = 0 w_max =self.umax[v] #某行像素横坐标的最大范围,注意这里的图像块是圆形的 #在坐标范围内挨个像素遍历,实际是一次遍历2个 #假设每次处理的两个点坐标,中心线上方为(x,y),中心线下方为(x,-y) #对于某次待处理的两个点:m_10 = Σ x*I(x,y) = x*I(x,y) + x*I(x,-y) = x*(I(x,y) + I(x,-y)) #对于某次待处理的两个点:m_01 = Σ y*I(x,y) = y*I(x,y) - y*I(x,-y) = y*(I(x,y) - I(x,-y)) for u in range(-w_max, w_max+1): val_plus = int(img[center_y+v][center_x+u]) val_minus = int(img[center_y-v][center_x+u]) v_sum += (val_plus - val_minus) m_10 += u * (val_minus + val_plus) m_01 += v*v_sum return cv2.fastAtan2(float(m_01), float(m_10)) def _ComputePyramid(self, img): for level in range(self.nlevels): scale = self.ScaleFactors[level] #根据尺寸因子计算长宽尺寸 feat_width = int(np.round(float(img.shape[1]) * scale)) feat_height = int(np.round(float(img.shape[0]) * scale)) #计算每层图像 if level != 0: temp = cv2.resize(self.ImagePyramid[level-1], (feat_width, feat_height), interpolation = cv2.INTER_LINEAR) temp = cv2.copyMakeBorder(temp, self.EDGE_THRESHOLD, self.EDGE_THRESHOLD, self.EDGE_THRESHOLD, self.EDGE_THRESHOLD, cv2.BORDER_REFLECT_101) else: temp = cv2.copyMakeBorder(img, self.EDGE_THRESHOLD, self.EDGE_THRESHOLD, self.EDGE_THRESHOLD, self.EDGE_THRESHOLD, cv2.BORDER_REFLECT_101) self.ImagePyramid.append(temp[int(self.EDGE_THRESHOLD) : int(self.EDGE_THRESHOLD+feat_height), int(self.EDGE_THRESHOLD) : int(self.EDGE_THRESHOLD+feat_width)]) def Match(cur_kps, last_kps, cur_des, last_des): bfmatcher = cv2.BFMatcher(cv2.NORM_HAMMING) matches = bfmatcher.knnMatch(cur_des, last_des, k=2) match_kps = [] for m,n in matches: #each keypoints return 2 best matches(lowest distance) #if first match cost smaller than second match cost, regrad as confident if m.distance < 0.75*n.distance: match_kps.append(m) #needs at least 8 points to solve essential matrix assert len(match_kps) >= 8,\ "==> matched {} point pairs.".format(len(match_kps)) return match_kps if __name__ == "__main__": img_name = '/home/zuyuan/Data/kitti_tracking/raw_data/training/image_2/0000/000003.png' img_raw = cv2.imread(img_name) img = cv2.cvtColor(img_raw, cv2.COLOR_BGR2GRAY) #to gray scale #open-cv build-in lib function: orb = cv2.ORB_create() pts = cv2.goodFeaturesToTrack(img, 3000, qualityLevel=0.01, minDistance=3) kpts = [cv2.KeyPoint(x=pt[0][0],y=pt[0][1], _size=20) for pt in pts] for kpt in kpts: cv2.circle(img_raw, (int(kpt.pt[0]),int(kpt.pt[1])), 2, (0,0,255), thickness=1, lineType=8, shift=0) #red #improved from orb-slam2: orb = OrbExtractor() kpts, desc = orb.Extract(img) for kpt in kpts: cv2.circle(img_raw, (int(kpt.pt[0]),int(kpt.pt[1])), 2, (0,255,0), thickness=1, lineType=8, shift=0) #blue kpts_np = np.array([(kp.pt[0], kp.pt[1]) for kp in kpts]) desc_np = np.array(desc) img2_name = '/home/zuyuan/Data/kitti_tracking/raw_data/training/image_2/0000/000004.png' img2_raw = cv2.imread(img2_name) img2 = cv2.cvtColor(img2_raw, cv2.COLOR_BGR2GRAY) #to gray scale kpts2, desc2 = orb.Extract(img2) kpts2_np = np.array([(kp.pt[0], kp.pt[1]) for kp in kpts2]) desc2_np = np.array(desc2) match = Match(kpts2_np, kpts_np, desc2_np, desc_np) print(match) match_imgs = cv2.drawMatches(img2_raw, kpts2, img_raw, kpts, match, outImg=None) cv2.imshow("Match Result", match_imgs) cv2.imshow('compare', img_raw) cv2.waitKey(0) cv2.destroyAllWindows()
{ "alphanum_fraction": 0.6357886146, "author": null, "avg_line_length": 37.0352644836, "converted": null, "ext": "py", "file": null, "hexsha": "9cb329efed7ffb83f2e234056e044cf8613ca68d", "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": "0f485fcb6bf53341898142021b6a1295a0ca87a3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "yangzuyuanhao/vin", "max_forks_repo_path": "vo/orb/orb_extractor.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "0f485fcb6bf53341898142021b6a1295a0ca87a3", "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": "yangzuyuanhao/vin", "max_issues_repo_path": "vo/orb/orb_extractor.py", "max_line_length": 110, "max_stars_count": 1, "max_stars_repo_head_hexsha": "0f485fcb6bf53341898142021b6a1295a0ca87a3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "yangzuyuanhao/vin", "max_stars_repo_path": "vo/orb/orb_extractor.py", "max_stars_repo_stars_event_max_datetime": "2022-03-23T01:13:57.000Z", "max_stars_repo_stars_event_min_datetime": "2022-03-23T01:13:57.000Z", "num_tokens": 5355, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 14703 }
[STATEMENT] lemma signed_take_bit_0 [simp]: \<open>signed_take_bit 0 a = - (a mod 2)\<close> [PROOF STATE] proof (prove) goal (1 subgoal): 1. signed_take_bit 0 a = - (a mod (2::'a)) [PROOF STEP] by (simp add: bit_0 signed_take_bit_def odd_iff_mod_2_eq_one)
{ "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": 119, "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 -*- from __future__ import absolute_import, print_function, division import unittest import numpy as np import bcolz import h5py import zarr import pytest from allel import GenotypeArray, HaplotypeArray, AlleleCountsArray, VariantTable, \ GenotypeVector, GenotypeAlleleCountsArray, GenotypeAlleleCountsVector from allel import GenotypeChunkedArray, HaplotypeChunkedArray, AlleleCountsChunkedArray, \ VariantChunkedTable, GenotypeAlleleCountsChunkedArray from allel.test.tools import assert_array_equal as aeq from allel.test.model.test_api import GenotypeArrayInterface, \ diploid_genotype_data, triploid_genotype_data, HaplotypeArrayInterface, \ haplotype_data, allele_counts_data, AlleleCountsArrayInterface, \ VariantTableInterface, variant_table_data, variant_table_dtype, \ variant_table_names, GenotypeAlleleCountsArrayInterface, \ diploid_genotype_ac_data, triploid_genotype_ac_data from allel import chunked from allel.chunked.storage_zarr import ZarrTable class GenotypeChunkedArrayTests(GenotypeArrayInterface, unittest.TestCase): _class = GenotypeChunkedArray def setUp(self): chunked.storage_registry['default'] = chunked.bcolzmem_storage def setup_instance(self, data, **kwargs): data = chunked.storage_registry['default'].array(data, chunklen=2, **kwargs) return GenotypeChunkedArray(data) def test_constructor(self): # missing data arg with pytest.raises(TypeError): # noinspection PyArgumentList GenotypeChunkedArray() # data has wrong dtype data = 'foo bar' with pytest.raises(TypeError): GenotypeChunkedArray(data) # data has wrong dtype data = np.array([4., 5., 3.7]) with pytest.raises(TypeError): GenotypeChunkedArray(data) # data has wrong dimensions data = np.array([1, 2, 3]) with pytest.raises(TypeError): GenotypeChunkedArray(data) # data has wrong dimensions data = np.array([[1, 2], [3, 4]]) # use HaplotypeChunkedArray instead with pytest.raises(TypeError): GenotypeChunkedArray(data) # diploid data (typed) g = self.setup_instance(np.array(diploid_genotype_data, dtype='i1')) aeq(diploid_genotype_data, g) assert np.int8 == g.dtype # polyploid data (typed) g = self.setup_instance(np.array(triploid_genotype_data, dtype='i1')) aeq(triploid_genotype_data, g) assert np.int8 == g.dtype def test_storage(self): g = self.setup_instance(np.array(diploid_genotype_data)) # default is bcolz mem assert isinstance(g.values, bcolz.carray) assert g.values.rootdir is None, g.values.rootdir def test_slice_types(self): g = self.setup_instance(np.array(diploid_genotype_data, dtype='i1')) # total slice s = g[:] self.assertIsInstance(s, GenotypeArray) # row slice s = g[1:] self.assertIsInstance(s, GenotypeArray) # col slice s = g[:, 1:] self.assertIsInstance(s, GenotypeArray) # row index s = g[0] self.assertIsInstance(s, GenotypeVector) # col index s = g[:, 0] self.assertIsInstance(s, GenotypeVector) # ploidy index s = g[:, :, 0] self.assertIsInstance(s, np.ndarray) # item s = g[0, 0, 0] self.assertIsInstance(s, np.int8) def test_take(self): g = self.setup_instance(diploid_genotype_data) # take variants not in original order # not supported for carrays indices = [2, 0] with pytest.raises(NotImplementedError): g.take(indices, axis=0) def test_to_n_ref_array_like(self): # see also https://github.com/cggh/scikit-allel/issues/66 gn = self.setup_instance(diploid_genotype_data).to_n_ref(fill=-1) t = np.array(gn) > 0 assert 4 == np.count_nonzero(t) expect = np.array([[1, 1, 0], [1, 0, 0], [1, 0, 0], [0, 0, 0], [0, 0, 0]], dtype='b1') aeq(expect, t) # numpy reductions trigger the issue expect = np.array([2, 1, 1, 0, 0]) actual = np.sum(t, axis=1) aeq(expect, actual) expect = np.array([0, 0, 0, 0, 0]) actual = np.min(t, axis=1) aeq(expect, actual) expect = np.array([1, 1, 1, 0, 0]) actual = np.max(t, axis=1) aeq(expect, actual) class GenotypeChunkedArrayTestsBColzTmpStorage(GenotypeChunkedArrayTests): def setUp(self): chunked.storage_registry['default'] = chunked.bcolztmp_storage def setup_instance(self, data, **kwargs): data = chunked.bcolztmp_storage.array(data, chunklen=2, **kwargs) return GenotypeChunkedArray(data) def test_storage(self): g = self.setup_instance(np.array(diploid_genotype_data)) assert isinstance(g.values, bcolz.carray) assert g.values.rootdir is not None class GenotypeChunkedArrayTestsBColzCustomStorage(GenotypeChunkedArrayTests): def setUp(self): chunked.storage_registry['default'] = chunked.BcolzMemStorage( cparams=bcolz.cparams(cname='zlib', clevel=1) ) def setup_instance(self, data, **kwargs): data = chunked.storage_registry['default'].array(data, chunklen=2, **kwargs) return GenotypeChunkedArray(data) def test_storage(self): g = self.setup_instance(np.array(diploid_genotype_data)) assert isinstance(g.values, bcolz.carray) assert 'zlib' == g.values.cparams.cname assert 1 == g.values.cparams.clevel class GenotypeChunkedArrayTestsHDF5MemStorage(GenotypeChunkedArrayTests): def setUp(self): chunked.storage_registry['default'] = chunked.hdf5mem_storage def setup_instance(self, data, **kwargs): data = chunked.hdf5mem_storage.array(data, **kwargs) return GenotypeChunkedArray(data) def test_storage(self): g = self.setup_instance(np.array(diploid_genotype_data)) assert isinstance(g.values, h5py.Dataset) class GenotypeChunkedArrayTestsZarrMemStorage(GenotypeChunkedArrayTests): def setUp(self): chunked.storage_registry['default'] = chunked.zarrmem_storage def setup_instance(self, data, **kwargs): data = chunked.zarrmem_storage.array(data, **kwargs) return GenotypeChunkedArray(data) def test_storage(self): g = self.setup_instance(np.array(diploid_genotype_data)) assert isinstance(g.values, zarr.core.Array) class GenotypeChunkedArrayTestsZarrTmpStorage(GenotypeChunkedArrayTests): def setUp(self): chunked.storage_registry['default'] = chunked.zarrtmp_storage def setup_instance(self, data, **kwargs): data = chunked.zarrtmp_storage.array(data, **kwargs) return GenotypeChunkedArray(data) def test_storage(self): g = self.setup_instance(np.array(diploid_genotype_data)) assert isinstance(g.values, zarr.Array) assert isinstance(g.values.store, zarr.DirectoryStore) class GenotypeChunkedArrayTestsHDF5TmpStorage(GenotypeChunkedArrayTests): def setUp(self): chunked.storage_registry['default'] = chunked.hdf5tmp_storage def setup_instance(self, data, dtype=None): data = chunked.hdf5tmp_storage.array(data, dtype=dtype) return GenotypeChunkedArray(data) def test_storage(self): g = self.setup_instance(np.array(diploid_genotype_data)) assert isinstance(g.values, h5py.Dataset) class GenotypeChunkedArrayTestsHDF5TmpLZFStorage(GenotypeChunkedArrayTests): def setUp(self): chunked.storage_registry['default'] = chunked.hdf5tmp_lzf_storage def setup_instance(self, data, dtype=None): data = chunked.hdf5tmp_lzf_storage.array(data, dtype=dtype) return GenotypeChunkedArray(data) def test_storage(self): g = self.setup_instance(np.array(diploid_genotype_data)) assert isinstance(g.values, h5py.Dataset) assert g.values.compression == 'lzf' # noinspection PyMethodMayBeStatic class HaplotypeChunkedArrayTests(HaplotypeArrayInterface, unittest.TestCase): _class = HaplotypeChunkedArray def setUp(self): chunked.storage_registry['default'] = chunked.bcolzmem_storage def setup_instance(self, data, dtype=None): data = chunked.storage_registry['default'].array(data, dtype=dtype, chunklen=2) return HaplotypeChunkedArray(data) def test_constructor(self): # missing data arg with pytest.raises(TypeError): # noinspection PyArgumentList HaplotypeChunkedArray() # data has wrong dtype data = 'foo bar' with pytest.raises(TypeError): HaplotypeChunkedArray(data) # data has wrong dtype data = np.array([4., 5., 3.7]) with pytest.raises(TypeError): HaplotypeChunkedArray(data) # data has wrong dimensions data = np.array([1, 2, 3]) with pytest.raises(TypeError): HaplotypeChunkedArray(data) # data has wrong dimensions data = np.array([[[1, 2], [3, 4]]]) # use GenotypeCArray instead with pytest.raises(TypeError): HaplotypeChunkedArray(data) # typed data (typed) h = HaplotypeChunkedArray(np.array(haplotype_data, dtype='i1')) aeq(haplotype_data, h) assert np.int8 == h.dtype def test_slice_types(self): h = self.setup_instance(np.array(haplotype_data, dtype='i1')) # row slice s = h[1:] self.assertNotIsInstance(s, HaplotypeChunkedArray) self.assertIsInstance(s, HaplotypeArray) # col slice s = h[:, 1:] self.assertNotIsInstance(s, HaplotypeChunkedArray) self.assertIsInstance(s, HaplotypeArray) # row index s = h[0] self.assertNotIsInstance(s, HaplotypeChunkedArray) self.assertNotIsInstance(s, HaplotypeArray) self.assertIsInstance(s, np.ndarray) # col index s = h[:, 0] self.assertNotIsInstance(s, HaplotypeChunkedArray) self.assertNotIsInstance(s, HaplotypeArray) self.assertIsInstance(s, np.ndarray) # item s = h[0, 0] self.assertNotIsInstance(s, HaplotypeChunkedArray) self.assertNotIsInstance(s, HaplotypeArray) self.assertIsInstance(s, np.int8) # noinspection PyMethodMayBeStatic class AlleleCountsChunkedArrayTests(AlleleCountsArrayInterface, unittest.TestCase): _class = AlleleCountsChunkedArray def setUp(self): chunked.storage_registry['default'] = chunked.bcolzmem_storage def setup_instance(self, data): data = chunked.storage_registry['default'].array(data, chunklen=2) return AlleleCountsChunkedArray(data) def test_constructor(self): # missing data arg with pytest.raises(TypeError): # noinspection PyArgumentList AlleleCountsChunkedArray() # data has wrong dtype data = 'foo bar' with pytest.raises(TypeError): AlleleCountsChunkedArray(data) # data has wrong dtype data = np.array([4., 5., 3.7]) with pytest.raises(TypeError): AlleleCountsChunkedArray(data) # data has wrong dimensions data = np.array([1, 2, 3]) with pytest.raises(TypeError): AlleleCountsChunkedArray(data) # data has wrong dimensions data = np.array([[[1, 2], [3, 4]]]) with pytest.raises(TypeError): AlleleCountsChunkedArray(data) # typed data (typed) ac = AlleleCountsChunkedArray(np.array(allele_counts_data, dtype='u1')) aeq(allele_counts_data, ac) assert np.uint8 == ac.dtype def test_slice_types(self): ac = self.setup_instance(np.array(allele_counts_data, dtype='u2')) # row slice s = ac[1:] self.assertNotIsInstance(s, AlleleCountsChunkedArray) self.assertIsInstance(s, AlleleCountsArray) # col slice s = ac[:, 1:] self.assertNotIsInstance(s, AlleleCountsChunkedArray) self.assertNotIsInstance(s, AlleleCountsArray) self.assertIsInstance(s, np.ndarray) # row index s = ac[0] self.assertNotIsInstance(s, AlleleCountsChunkedArray) self.assertNotIsInstance(s, AlleleCountsArray) self.assertIsInstance(s, np.ndarray) # col index s = ac[:, 0] self.assertNotIsInstance(s, AlleleCountsChunkedArray) self.assertNotIsInstance(s, AlleleCountsArray) self.assertIsInstance(s, np.ndarray) # item s = ac[0, 0] self.assertNotIsInstance(s, AlleleCountsChunkedArray) self.assertNotIsInstance(s, AlleleCountsArray) self.assertIsInstance(s, np.uint16) class AlleleCountsChunkedArrayTestsHDF5Mem(AlleleCountsChunkedArrayTests): def setUp(self): chunked.storage_registry['default'] = chunked.hdf5mem_storage def setup_instance(self, data): data = chunked.storage_registry['default'].array(data) return AlleleCountsChunkedArray(data) class GenotypeAlleleCountsChunkedArrayTests(GenotypeAlleleCountsArrayInterface, unittest.TestCase): _class = GenotypeAlleleCountsChunkedArray def setUp(self): chunked.storage_registry['default'] = chunked.bcolzmem_storage def setup_instance(self, data, **kwargs): data = chunked.storage_registry['default'].array(data, chunklen=2, **kwargs) return GenotypeAlleleCountsChunkedArray(data) def test_constructor(self): # missing data arg with pytest.raises(TypeError): # noinspection PyArgumentList GenotypeAlleleCountsChunkedArray() # data has wrong dtype data = 'foo bar' with pytest.raises(TypeError): GenotypeAlleleCountsChunkedArray(data) # data has wrong dtype data = np.array([4., 5., 3.7]) with pytest.raises(TypeError): GenotypeAlleleCountsChunkedArray(data) # data has wrong dimensions data = np.array([1, 2, 3]) with pytest.raises(TypeError): GenotypeAlleleCountsChunkedArray(data) # data has wrong dimensions data = np.array([[1, 2], [3, 4]]) # use HaplotypeChunkedArray instead with pytest.raises(TypeError): GenotypeAlleleCountsChunkedArray(data) # diploid data (typed) g = self.setup_instance(np.array(diploid_genotype_ac_data, dtype='i1')) aeq(diploid_genotype_ac_data, g) assert np.int8 == g.dtype # polyploid data (typed) g = self.setup_instance(np.array(triploid_genotype_ac_data, dtype='i1')) aeq(triploid_genotype_ac_data, g) assert np.int8 == g.dtype def test_storage(self): g = self.setup_instance(np.array(diploid_genotype_ac_data)) # default is bcolz mem assert isinstance(g.values, bcolz.carray) assert g.values.rootdir is None, g.values.rootdir def test_slice_types(self): g = self.setup_instance(np.array(diploid_genotype_ac_data, dtype='i1')) # total slice s = g[:] self.assertIsInstance(s, GenotypeAlleleCountsArray) # row slice s = g[1:] self.assertIsInstance(s, GenotypeAlleleCountsArray) # col slice s = g[:, 1:] self.assertIsInstance(s, GenotypeAlleleCountsArray) # row index s = g[0] self.assertIsInstance(s, GenotypeAlleleCountsVector) # col index s = g[:, 0] self.assertIsInstance(s, GenotypeAlleleCountsVector) # ploidy index s = g[:, :, 0] self.assertIsInstance(s, np.ndarray) # item s = g[0, 0, 0] self.assertIsInstance(s, np.int8) class VariantChunkedTableTests(VariantTableInterface, unittest.TestCase): _class = VariantChunkedTable def setUp(self): chunked.storage_registry['default'] = chunked.bcolzmem_storage def setup_instance(self, data, **kwargs): data = chunked.storage_registry['default'].table(data, chunklen=2) return VariantChunkedTable(data, **kwargs) def test_storage(self): a = np.rec.array(variant_table_data, dtype=variant_table_dtype) vt = self.setup_instance(a) assert isinstance(vt.values, bcolz.ctable) def test_constructor(self): # missing data arg with self.assertRaises(TypeError): # noinspection PyArgumentList VariantChunkedTable() # recarray ra = np.rec.array(variant_table_data, dtype=variant_table_dtype) vt = VariantChunkedTable(ra) assert 5 == len(vt) aeq(ra, vt) # dict d = {n: ra[n] for n in variant_table_names} vt = VariantChunkedTable(d, names=variant_table_names) assert 5 == len(vt) aeq(ra, vt) def test_slice_types(self): ra = np.rec.array(variant_table_data, dtype=variant_table_dtype) vt = VariantChunkedTable(ra) # row slice s = vt[1:] self.assertNotIsInstance(s, VariantChunkedTable) self.assertIsInstance(s, VariantTable) # row index s = vt[0] self.assertNotIsInstance(s, VariantChunkedTable) self.assertNotIsInstance(s, VariantTable) self.assertIsInstance(s, (np.record, np.void, tuple)) # col access s = vt['CHROM'] self.assertNotIsInstance(s, VariantChunkedTable) self.assertNotIsInstance(s, VariantTable) self.assertIsInstance(s, chunked.ChunkedArrayWrapper) # bad access with pytest.raises(IndexError): # noinspection PyStatementEffect vt[:, 0] def test_take(self): a = np.rec.array(variant_table_data, dtype=variant_table_dtype) vt = VariantChunkedTable(a) # take variants not in original order # not supported for carrays indices = [2, 0] with pytest.raises(NotImplementedError): vt.take(indices) def test_eval_vm(self): a = np.rec.array(variant_table_data, dtype=variant_table_dtype) vt = self.setup_instance(a) expr = '(DP > 30) & (QD < 4)' r = vt.eval(expr, vm='numexpr') aeq([False, False, True, False, True], r) r = vt.eval(expr, vm='python') aeq([False, False, True, False, True], r) class VariantChunkedTableTestsHDF5Storage(VariantChunkedTableTests): def setUp(self): chunked.storage_registry['default'] = chunked.hdf5mem_storage def setup_instance(self, data, **kwargs): data = chunked.storage_registry['default'].table(data) return VariantChunkedTable(data, **kwargs) def test_storage(self): a = np.rec.array(variant_table_data, dtype=variant_table_dtype) vt = self.setup_instance(a) assert isinstance(vt.values, h5py.Group) class VariantChunkedTableTestsZarrStorage(VariantChunkedTableTests): def setUp(self): chunked.storage_registry['default'] = chunked.zarrmem_storage def setup_instance(self, data, **kwargs): data = chunked.storage_registry['default'].table(data) return VariantChunkedTable(data, **kwargs) def test_storage(self): a = np.rec.array(variant_table_data, dtype=variant_table_dtype) vt = self.setup_instance(a) assert isinstance(vt.values, ZarrTable) # noinspection PyMethodMayBeStatic def test_zarr_group(self): z = zarr.group() z.create_dataset('chrom', data=['1', '2', '3']) z.create_dataset('pos', data=[2, 4, 6]) vt = VariantChunkedTable(z) assert isinstance(vt.values, zarr.Group) class AlleleCountsChunkedTableTests(unittest.TestCase): def setUp(self): chunked.storage_registry['default'] = chunked.zarrmem_storage # noinspection PyMethodMayBeStatic def test_count_alleles_subpops(self): data = chunked.storage_registry['default'].array(diploid_genotype_data, chunklen=2) g = GenotypeChunkedArray(data) subpops = {'foo': [0, 2], 'bar': [1]} ac_subpops = g.count_alleles_subpops(subpops) for p in subpops.keys(): ac = g.take(subpops[p], axis=1).count_alleles() aeq(ac, ac_subpops[p]) loc = np.array([True, False, True, False, True]) t = ac_subpops.compress(loc) assert 3 == len(t)
{ "alphanum_fraction": 0.6471825264, "author": null, "avg_line_length": 32.2388289676, "converted": null, "ext": "py", "file": null, "hexsha": "86ee77133371724678d7e634cf3218121c392e42", "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": "ee2362c6bd4c3e39d2bd5e7ed890a9e3116d5367", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "yakkoroma/scikit-allel", "max_forks_repo_path": "allel/test/model/test_chunked.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "ee2362c6bd4c3e39d2bd5e7ed890a9e3116d5367", "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": "yakkoroma/scikit-allel", "max_issues_repo_path": "allel/test/model/test_chunked.py", "max_line_length": 91, "max_stars_count": null, "max_stars_repo_head_hexsha": "ee2362c6bd4c3e39d2bd5e7ed890a9e3116d5367", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "yakkoroma/scikit-allel", "max_stars_repo_path": "allel/test/model/test_chunked.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 5060, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 20923 }
import tensorflow import argparse import requests import json import numpy as np parser = argparse.ArgumentParser() parser.add_argument( '--image_path', type=str, default='~/Downloads/pic_temp/555.jpg', help='path of image' ) parser.add_argument( '--label_file', type=str, default='/tmp/output_labels.txt', help='path of label file' ) args = vars(parser.parse_args()) # Loading and pre-processing our input image image_path = args['image_path'] img = tensorflow.keras.preprocessing.image.img_to_array(tensorflow.keras.preprocessing.image.load_img(image_path, target_size=(128, 128))) / 255. img = np.expand_dims(img, axis=0) # sending post request to TensorFlow Serving server payload = {"instances": img.tolist()} json_response = requests.post('http://localhost:8501/v1/models/saved_models:predict', json=payload) pred = json.loads(json_response.content.decode('utf-8')) # print(pred) # create a list containing the class labels class_labels = [] label_file = args['label_file'] proto_as_ascii_lines = tensorflow.gfile.GFile(label_file).readlines() for l in proto_as_ascii_lines: class_labels.append(l.rstrip()) # get top k predictions top_k = np.array(pred['predictions'])[0].argsort()[-5:][::-1] print(top_k) for k in top_k: print(k, '-', class_labels[k]) # find the index of the class with maximum score, and print the label of the class with maximum score # pred = np.argmax(np.array(pred['predictions']), axis=-1) # print(pred[0], '-', class_labels[pred[0]])
{ "alphanum_fraction": 0.7324503311, "author": null, "avg_line_length": 29.0384615385, "converted": null, "ext": "py", "file": null, "hexsha": "6d3e8af5fa9219373097430bb9a63ead7fad27fd", "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": "df3f3d7443d35435d07d45309001254787d64ea6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "colddew/mix-script", "max_forks_repo_path": "shell/tensorflow/image_recognition_rest.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "df3f3d7443d35435d07d45309001254787d64ea6", "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": "colddew/mix-script", "max_issues_repo_path": "shell/tensorflow/image_recognition_rest.py", "max_line_length": 145, "max_stars_count": 1, "max_stars_repo_head_hexsha": "df3f3d7443d35435d07d45309001254787d64ea6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "colddew/mix-script", "max_stars_repo_path": "shell/tensorflow/image_recognition_rest.py", "max_stars_repo_stars_event_max_datetime": "2018-09-19T02:56:06.000Z", "max_stars_repo_stars_event_min_datetime": "2018-09-19T02:56:06.000Z", "num_tokens": 359, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1510 }
[STATEMENT] lemma Nonce_notin_initState [iff]: "Nonce N \<notin> parts (initState B)" [PROOF STATE] proof (prove) goal (1 subgoal): 1. Nonce N \<notin> parts (initState B) [PROOF STEP] by (induct_tac "B", auto)
{ "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": 85, "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 }
//---------------------------------------------------------------------------// // Copyright (c) 2018-2021 Mikhail Komarov <nemo@nil.foundation> // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //---------------------------------------------------------------------------// #pragma once #include <boost/range/adaptor/filtered.hpp> #include <nil/actor/core/scheduling.hh> #include <nil/actor/core/map_reduce.hh> #include <array> #include <vector> namespace nil { namespace actor { namespace detail { struct scheduling_group_specific_thread_local_data { struct per_scheduling_group { bool queue_is_initialized = false; /** * This array holds pointers to the scheduling group specific * data. The pointer is not use as is but is cast to a reference * to the appropriate type that is actually pointed to. */ std::vector<void *> specific_vals; }; std::array<per_scheduling_group, max_scheduling_groups()> per_scheduling_group_data; std::vector<scheduling_group_key_config> scheduling_group_key_configs; }; inline scheduling_group_specific_thread_local_data ** get_scheduling_group_specific_thread_local_data_ptr() noexcept { static thread_local scheduling_group_specific_thread_local_data *data; return &data; } inline scheduling_group_specific_thread_local_data & get_scheduling_group_specific_thread_local_data() noexcept { return **get_scheduling_group_specific_thread_local_data_ptr(); } [[noreturn]] void no_such_scheduling_group(scheduling_group sg); /** * Returns a pointer to the given scheduling group specific data. * @param sg - The scheduling group which it's data needs to be accessed * @param key - The scheduling group key that for the data to access * @return A pointer of type T* to the data, if sg is valid initialized. * * @note The parameter T has to be given since there is no way to deduce it. */ template<typename T> T *scheduling_group_get_specific_ptr(scheduling_group sg, scheduling_group_key key) noexcept { auto &data = detail::get_scheduling_group_specific_thread_local_data(); #ifdef ACTOR_DEBUG assert(std::type_index(typeid(T)) == data.scheduling_group_key_configs[key.id()].type_index); #endif auto sg_id = detail::scheduling_group_index(sg); if (__builtin_expect(sg_id < data.per_scheduling_group_data.size() && data.per_scheduling_group_data[sg_id].queue_is_initialized, true)) { return reinterpret_cast<T *>(data.per_scheduling_group_data[sg_id].specific_vals[key.id()]); } return nullptr; } } // namespace detail /** * Returns a reference to the given scheduling group specific data. * @param sg - The scheduling group which it's data needs to be accessed * @param key - The scheduling group key that for the data to access * @return A reference of type T& to the data. * * @note The parameter T has to be given since there is no way to deduce it. * May throw std::invalid_argument if sg does not exist or is uninitialized. */ template<typename T> T &scheduling_group_get_specific(scheduling_group sg, scheduling_group_key key) { T *p = detail::scheduling_group_get_specific_ptr<T>(sg, std::move(key)); if (!p) { detail::no_such_scheduling_group(sg); } return *p; } /** * Returns a reference to the current specific data. * @param key - The scheduling group key that for the data to access * @return A reference of type T& to the data. * * @note The parameter T has to be given since there is no way to deduce it. */ template<typename T> T &scheduling_group_get_specific(scheduling_group_key key) noexcept { // Unlike detail::scheduling_group_get_specific_ptr, this can // return a reference to an element whose queue_is_initialized is // false. auto &data = detail::get_scheduling_group_specific_thread_local_data(); assert(std::type_index(typeid(T)) == data.scheduling_group_key_configs[key.id()].type_index); auto sg_id = detail::scheduling_group_index(current_scheduling_group()); return *reinterpret_cast<T *>(data.per_scheduling_group_data[sg_id].specific_vals[key.id()]); } /** * A map reduce over all values of a specific scheduling group data. * @param mapper - A functor SomeType(SpecificValType&) or SomeType(SpecificValType) that maps * the specific data to a value of any type. * @param reducer - A functor of of type ConvetibleToInitial(Initial, MapperReurnType) that reduces * a value of type Initial and of the mapper return type to a value of type convertible to Initial. * @param initial_val - the initial value to pass in the first call to the reducer. * @param key - the key to the specific data that the mapper should act upon. * @return A future that resolves when the result of the map reduce is ready. * @note The type of SpecificValType must be given because there is no way to deduce it in a *consistent* * manner. * @note Theoretically the parameter type of Mapper can be deduced to be the type * (function_traits<Mapper>::arg<0>) but then there is a danger when the Mapper accepts a parameter type T where * SpecificValType is convertible to SpecificValType. */ template<typename SpecificValType, typename Mapper, typename Reducer, typename Initial> #ifdef BOOST_HAS_CONCEPTS requires requires(SpecificValType specific_val, Mapper mapper, Reducer reducer, Initial initial) { { reducer(initial, mapper(specific_val)) } -> std::convertible_to<Initial>; } #endif future<typename function_traits<Reducer>::return_type> map_reduce_scheduling_group_specific(Mapper mapper, Reducer reducer, Initial initial_val, scheduling_group_key key) { using per_scheduling_group = detail::scheduling_group_specific_thread_local_data::per_scheduling_group; auto &data = detail::get_scheduling_group_specific_thread_local_data(); auto wrapped_mapper = [key, mapper](per_scheduling_group &psg) { auto id = detail::scheduling_group_key_id(key); return make_ready_future<typename function_traits<Mapper>::return_type>( mapper(*reinterpret_cast<SpecificValType *>(psg.specific_vals[id]))); }; return map_reduce(data.per_scheduling_group_data | boost::adaptors::filtered(std::mem_fn(&per_scheduling_group::queue_is_initialized)), wrapped_mapper, std::move(initial_val), reducer); } /** * A reduce over all values of a specific scheduling group data. * @param reducer - A functor of of type ConvetibleToInitial(Initial, SpecificValType) that reduces * a value of type Initial and of the sg specific data type to a value of type convertible to Initial. * @param initial_val - the initial value to pass in the first call to the reducer. * @param key - the key to the specific data that the mapper should act upon. * @return A future that resolves when the result of the reduce is ready. * * @note The type of SpecificValType must be given because there is no way to deduce it in a *consistent* * manner. * @note Theoretically the parameter type of Reducer can be deduced to be the type * (function_traits<Reducer>::arg<0>) but then there is a danger when the Reducer accepts a parameter type T * where SpecificValType is convertible to SpecificValType. */ template<typename SpecificValType, typename Reducer, typename Initial> #ifdef BOOST_HAS_CONCEPTS requires requires(SpecificValType specific_val, Reducer reducer, Initial initial) { { reducer(initial, specific_val) } -> std::convertible_to<Initial>; } #endif future<typename function_traits<Reducer>::return_type> reduce_scheduling_group_specific(Reducer reducer, Initial initial_val, scheduling_group_key key) { using per_scheduling_group = detail::scheduling_group_specific_thread_local_data::per_scheduling_group; auto &data = detail::get_scheduling_group_specific_thread_local_data(); auto mapper = [key](per_scheduling_group &psg) { auto id = detail::scheduling_group_key_id(key); return make_ready_future<SpecificValType>(*reinterpret_cast<SpecificValType *>(psg.specific_vals[id])); }; return map_reduce(data.per_scheduling_group_data | boost::adaptors::filtered(std::mem_fn(&per_scheduling_group::queue_is_initialized)), mapper, std::move(initial_val), reducer); } } // namespace actor } // namespace nil
{ "alphanum_fraction": 0.6440473986, "author": null, "avg_line_length": 54.5555555556, "converted": null, "ext": "hh", "file": null, "hexsha": "cde81ef9baf64d5aeec07ae7aa9da215e454753c", "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": "b8dcff07cfa126998f096d077cc9b42190d2d742", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "NilFoundation/actor-core", "max_forks_repo_path": "include/nil/actor/core/scheduling_specific.hh", "max_issues_count": 2, "max_issues_repo_head_hexsha": "b8dcff07cfa126998f096d077cc9b42190d2d742", "max_issues_repo_issues_event_max_datetime": "2020-08-30T17:54:40.000Z", "max_issues_repo_issues_event_min_datetime": "2020-04-17T17:00:03.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "NilFoundation/actor-core", "max_issues_repo_path": "include/nil/actor/core/scheduling_specific.hh", "max_line_length": 120, "max_stars_count": null, "max_stars_repo_head_hexsha": "b8dcff07cfa126998f096d077cc9b42190d2d742", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "NilFoundation/actor-core", "max_stars_repo_path": "include/nil/actor/core/scheduling_specific.hh", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2128, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 10802 }
Require Import Braun.common.braun Braun.common.util Braun.common.same_structure. Require Import Braun.common.log Braun.common.sequence Braun.common.list_util. Require Import Braun.monad.monad. Require Import Program List. Require Import Omega. Section foldr. Variables A B : Set. Variable P : B -> (list A) -> nat -> Prop. Definition f_type := forall (x:A) (acc:B), {! acc' !:! B !<! c !>! forall xs accC, P acc xs accC -> P acc' (x :: xs) (c + accC + 10) !}. Definition base_type := {bv : B | (P bv nil 4)}. Definition foldr_result (f : f_type) (pr : base_type) l (res:B) (c : nat) := P res l c. Load "fold_gen.v". Next Obligation. unfold base_type in base. unfold foldr_result. destruct base. apply p. Qed. Next Obligation. unfold foldr_result. replace (an0 + (an + 10)) with (an + an0 + 10); try omega. auto. Defined. End foldr. Hint Unfold foldr_result. Arguments foldr [A] [B] P f base l. Program Definition sum (l:list nat) : {! n !:! nat !<! c !>! (forall x, In x l -> x <= n) /\ c = 13 * length l + 4 !} := n <- (foldr (fun b al n => (forall x, In x al -> x <= b) /\ n = 13 * length al + 4) (fun x y => += 3; <== plus x y) 0 l) ; <== n. Next Obligation. rename H0 into CR. split; [| omega]. intros x0 OR. inversion OR as [EQ|IN]. omega. remember (CR x0 IN). omega. Qed. Next Obligation. tauto. Qed. Next Obligation. unfold foldr_result in *. split. tauto. omega. Qed. (* example use of foldr *) Program Definition list_id (A : Set) (l : list A) : {! l' !:! list A !<! c !>! l' = l !} := foldr (fun xs ys n => xs = ys) (fun x ys => <== (cons x ys)) nil l.
{ "alphanum_fraction": null, "author": "rfindler", "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/rfindler-395-2013/395-2013-afaeb6f4076a1330bbdeb4537417906bbfab5119/fold/fold.v", "reason": null, "repo": "395-2013", "save_path": "github-repos/coq/rfindler-395-2013", "sha": "afaeb6f4076a1330bbdeb4537417906bbfab5119", "size": null }
[STATEMENT] lemma member_le_L2_set: "\<lbrakk>finite A; i \<in> A\<rbrakk> \<Longrightarrow> f i \<le> L2_set f A" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>finite A; i \<in> A\<rbrakk> \<Longrightarrow> f i \<le> L2_set f A [PROOF STEP] unfolding L2_set_def [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<lbrakk>finite A; i \<in> A\<rbrakk> \<Longrightarrow> f i \<le> sqrt (\<Sum>i\<in>A. (f i)\<^sup>2) [PROOF STEP] by (auto intro!: member_le_sum real_le_rsqrt)
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": null, "hexsha": null, "include": null, "lang": null, "length": 2, "llama_tokens": 221, "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 }
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2007-2013 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #include <boost/intrusive/list.hpp> #include <boost/intrusive/slist.hpp> #include <boost/intrusive/set.hpp> #include <boost/intrusive/unordered_set.hpp> #include <vector> using namespace boost::intrusive; struct VirtualBase { virtual ~VirtualBase(){} }; struct VirtualBase2 { virtual ~VirtualBase2(){} }; struct VirtualBase3 { }; class NonVirtualBase : public virtual VirtualBase , public virtual VirtualBase2 { public: int dummy[10]; }; class MyClass : public NonVirtualBase , public virtual VirtualBase3 { int int_; public: list_member_hook<> list_hook_; MyClass(int i = 0) : int_(i) {} }; //Define a list that will store MyClass using the public base hook typedef member_hook< MyClass, list_member_hook<>, &MyClass::list_hook_ > MemberHook; typedef list<MyClass, MemberHook> List; int main() { #ifndef _MSC_VER typedef std::vector<MyClass>::iterator VectIt; typedef std::vector<MyClass>::reverse_iterator VectRit; //Create several MyClass objects, each one with a different value std::vector<MyClass> values; for(int i = 0; i < 100; ++i) values.push_back(MyClass(i)); List my_list; //Now insert them in the reverse order //in the base hook intrusive list for(VectIt it(values.begin()), itend(values.end()); it != itend; ++it) my_list.push_front(*it); //Now test lists { List::const_iterator list_it(my_list.cbegin()); VectRit vect_it(values.rbegin()), vect_itend(values.rend()); //Test the objects inserted in the base hook list for(; vect_it != vect_itend; ++vect_it, ++list_it) if(&*list_it != &*vect_it) return 1; } #endif return 0; }
{ "alphanum_fraction": 0.6037651277, "author": null, "avg_line_length": 25.3522727273, "converted": null, "ext": "cpp", "file": null, "hexsha": "ba65ca9a0c6c0676a894eedd048a9d7bb941bbc4", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 27, "max_forks_repo_forks_event_max_datetime": "2021-08-12T05:04:39.000Z", "max_forks_repo_forks_event_min_datetime": "2015-01-28T16:33:30.000Z", "max_forks_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "flingone/frameworks_base_cmds_remoted", "max_forks_repo_path": "libs/boost/libs/intrusive/test/virtual_base_test.cpp", "max_issues_count": 9, "max_issues_repo_head_hexsha": "4509d9f0468137ed7fd8d100179160d167e7d943", "max_issues_repo_issues_event_max_datetime": "2020-04-12T23:03:28.000Z", "max_issues_repo_issues_event_min_datetime": "2015-01-28T16:33:19.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "flingone/frameworks_base_cmds_remoted", "max_issues_repo_path": "libs/boost/libs/intrusive/test/virtual_base_test.cpp", "max_line_length": 85, "max_stars_count": 85, "max_stars_repo_head_hexsha": "eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo", "max_stars_repo_path": "REDSI_1160929_1161573/boost_1_67_0/libs/intrusive/test/virtual_base_test.cpp", "max_stars_repo_stars_event_max_datetime": "2021-11-14T20:38:31.000Z", "max_stars_repo_stars_event_min_datetime": "2015-02-08T20:36:17.000Z", "num_tokens": 538, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2231 }
// // Copyright (w) 2016-2017 Vinnie Falco (vinnie dot falco at gmail dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // Official repository: https://github.com/boostorg/beast // #ifndef BOOST_BEAST_TEST_WEBSOCKET_HPP #define BOOST_BEAST_TEST_WEBSOCKET_HPP #include <boost/beast/core/multi_buffer.hpp> #include <boost/beast/websocket/stream.hpp> #include <boost/beast/experimental/test/stream.hpp> #include <boost/asio/executor_work_guard.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/spawn.hpp> #include <cstdlib> #include <memory> #include <ostream> #include <thread> namespace boost { namespace beast { namespace test { class ws_echo_server { std::ostream& log_; boost::asio::io_context ioc_; boost::asio::executor_work_guard< boost::asio::io_context::executor_type> work_; multi_buffer buffer_; test::stream ts_; std::thread t_; websocket::stream<test::stream&> ws_; bool close_ = false; public: enum class kind { sync, async, async_client }; explicit ws_echo_server( std::ostream& log, kind k = kind::sync) : log_(log) , work_(ioc_.get_executor()) , ts_(ioc_) , ws_(ts_) { beast::websocket::permessage_deflate pmd; pmd.server_enable = true; pmd.server_max_window_bits = 9; pmd.compLevel = 1; ws_.set_option(pmd); switch(k) { case kind::sync: t_ = std::thread{[&]{ do_sync(); }}; break; case kind::async: t_ = std::thread{[&]{ ioc_.run(); }}; do_accept(); break; case kind::async_client: t_ = std::thread{[&]{ ioc_.run(); }}; break; } } ~ws_echo_server() { work_.reset(); t_.join(); } test::stream& stream() { return ts_; } void async_handshake() { ws_.async_handshake("localhost", "/", std::bind( &ws_echo_server::on_handshake, this, std::placeholders::_1)); } void async_close() { boost::asio::post(ioc_, [&] { if(ws_.is_open()) { ws_.async_close({}, std::bind( &ws_echo_server::on_close, this, std::placeholders::_1)); } else { close_ = true; } }); } private: void do_sync() { try { ws_.accept(); for(;;) { ws_.read(buffer_); ws_.text(ws_.got_text()); ws_.write(buffer_.data()); buffer_.consume(buffer_.size()); } } catch(system_error const& se) { boost::ignore_unused(se); #if 0 if( se.code() != error::closed && se.code() != error::failed && se.code() != boost::asio::error::eof) log_ << "ws_echo_server: " << se.code().message() << std::endl; #endif } catch(std::exception const& e) { log_ << "ws_echo_server: " << e.what() << std::endl; } } void do_accept() { ws_.async_accept(std::bind( &ws_echo_server::on_accept, this, std::placeholders::_1)); } void on_handshake(error_code ec) { if(ec) return fail(ec); do_read(); } void on_accept(error_code ec) { if(ec) return fail(ec); if(close_) { return ws_.async_close({}, std::bind( &ws_echo_server::on_close, this, std::placeholders::_1)); } do_read(); } void do_read() { ws_.async_read(buffer_, std::bind( &ws_echo_server::on_read, this, std::placeholders::_1)); } void on_read(error_code ec) { if(ec) return fail(ec); ws_.text(ws_.got_text()); ws_.async_write(buffer_.data(), std::bind( &ws_echo_server::on_write, this, std::placeholders::_1)); } void on_write(error_code ec) { if(ec) return fail(ec); buffer_.consume(buffer_.size()); do_read(); } void on_close(error_code ec) { if(ec) return fail(ec); } void fail(error_code ec) { boost::ignore_unused(ec); #if 0 if( ec != error::closed && ec != error::failed && ec != boost::asio::error::eof) log_ << "echo_server_async: " << ec.message() << std::endl; #endif } }; } // test } // beast } // boost #endif
{ "alphanum_fraction": 0.454795022, "author": null, "avg_line_length": 21.856, "converted": null, "ext": "hpp", "file": null, "hexsha": "6dcf05852e022f576da4a4655f65e14ba2e4a64c", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 5, "max_forks_repo_forks_event_max_datetime": "2022-03-01T18:23:49.000Z", "max_forks_repo_forks_event_min_datetime": "2019-08-20T13:45:04.000Z", "max_forks_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_forks_repo_licenses": [ "BSL-1.0" ], "max_forks_repo_name": "avplayer/cxxrpc", "max_forks_repo_path": "third_party/boost/libs/beast/test/extras/include/boost/beast/test/websocket.hpp", "max_issues_count": 1, "max_issues_repo_head_hexsha": "7049b4079fac78b3828e68f787d04d699ce52f6d", "max_issues_repo_issues_event_max_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_issues_event_min_datetime": "2019-04-04T18:00:00.000Z", "max_issues_repo_licenses": [ "BSL-1.0" ], "max_issues_repo_name": "avplayer/cxxrpc", "max_issues_repo_path": "third_party/boost/libs/beast/test/extras/include/boost/beast/test/websocket.hpp", "max_line_length": 80, "max_stars_count": 32, "max_stars_repo_head_hexsha": "ffe074de008f6e8c46ae1f431399cf932164287f", "max_stars_repo_licenses": [ "BSL-1.0" ], "max_stars_repo_name": "Talustus/boost_src", "max_stars_repo_path": "libs/beast/test/extras/include/boost/beast/test/websocket.hpp", "max_stars_repo_stars_event_max_datetime": "2021-08-29T10:56:19.000Z", "max_stars_repo_stars_event_min_datetime": "2019-02-27T06:57:07.000Z", "num_tokens": 1225, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 5464 }
import glob import imageio import matplotlib.pyplot as plt from matplotlib.image import imread import numpy as np import os import PIL from tensorflow.keras import layers import time from IPython import display from PIL import Image, ImageOps import glob import numpy as np IMG_DIR = './data/eyes/' image_list = [] image_gray_list = [] save_images = True # Grab all of our images imcount = 0; for filename in glob.glob(IMG_DIR + "*.jpg"): if imcount == 16: break imcount+=1 im=Image.open(filename) print(f"Loading {filename}") resize_image = im.resize((64, 64)) #ImageOps.invert(resize_image) gray_image = resize_image.convert("RGB") image_list.append(gray_image) image_gray_list.append(np.array(gray_image)) print("Loaded " + str(len(image_list)) + " images") np_image_list = np.asarray(image_gray_list) result = Image.new("RGB", (256, 256)) i = 0 for y in range(0, 4): for x in range(0, 4): img = (np_image_list[i]) result.paste(Image.fromarray(img), (y * 64, x * 64)) i += 1 result.save("___test.png")
{ "alphanum_fraction": 0.7122370937, "author": null, "avg_line_length": 22.7391304348, "converted": null, "ext": "py", "file": null, "hexsha": "560323e25617c3820a1c61573c4f5d6af087df18", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2021-10-06T14:25:05.000Z", "max_forks_repo_forks_event_min_datetime": "2021-10-06T14:25:05.000Z", "max_forks_repo_head_hexsha": "0cecf2b3de6d97a91fc9c27d55c6b47320b538c5", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "aaaa-trsh/Eye-DCGAN", "max_forks_repo_path": "PyScraper/module1.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "0cecf2b3de6d97a91fc9c27d55c6b47320b538c5", "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": "aaaa-trsh/Eye-DCGAN", "max_issues_repo_path": "PyScraper/module1.py", "max_line_length": 56, "max_stars_count": null, "max_stars_repo_head_hexsha": "0cecf2b3de6d97a91fc9c27d55c6b47320b538c5", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "aaaa-trsh/Eye-DCGAN", "max_stars_repo_path": "PyScraper/module1.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 294, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1046 }
## Extraction Process # This data represents 15 minute extracts from https://data.nashville.gov ### Extaction Script # The script below uses an app_token per https://dev.socrata.com/consumers/getting-started.html. However, # you can make a certain number of requests without an application token. import pandas as pd import numpy as np import requests import json from datetime import datetime from pytz import timezone import sqlite3 def main(): lime = {'company':'lime','endpoint':'https://data.nashville.gov/resource/ntar-zcjt.json?','color':'lime','timezone':'UTC'} bird = {'company': 'bird','endpoint':'https://data.nashville.gov/resource/nar3-8j89.json?','color': 'black','timezone':'UTC'} uber = {'company':'uber','endpoint':'https://data.nashville.gov/resource/jwwr-v4rf.json?','color': 'red','timezone':'UTC'} lyft = {'company':'lyft','endpoint':'https://data.nashville.gov/resource/bmb2-fucd.json?', 'color': 'pink','timezone':'UTC'} gotcha = {'company': 'gotcha','endpoint':'https://data.nashville.gov/resource/anqi-zsnc.json?','color': 'aqua','timezone':'UTC'} spin = {'company':'spin','endpoint':'https://data.nashville.gov/resource/2gne-qgxz.json?','color': 'orange','timezone':'UTC'} bolt = {'company':'bolt','endpoint':'https://data.nashville.gov/resource/rxpd-ez2h.json?','color': 'yellow','timezone':'UTC'} # bolt data lat and long is inaccurate scooter_companies = [lime, bird, uber, lyft, gotcha, spin, bolt] utc = timezone('UTC') central = timezone('US/Central') extract_date = datetime.strftime(datetime.now(),'%Y-%m-%d') extract_time = datetime.strftime(datetime.now(),'%H:%M:%S') cst_extract_date_time = datetime.strptime(extract_date + ' ' + extract_time, '%Y-%m-%d %H:%M:%S') cst_extract_date_time = cst_extract_date_time.astimezone(central) cst_extract_date = str(datetime.strftime(cst_extract_date_time,'%Y-%m-%d')) cst_extract_time = str(datetime.strftime(cst_extract_date_time,'%H:%M:%S')) utc_extract_date_time = datetime.strptime(extract_date + ' ' + extract_time, '%Y-%m-%d %H:%M:%S') utc_extract_date_time = utc_extract_date_time.astimezone(utc) utc_extract_date = str(datetime.strftime(utc_extract_date_time,'%Y-%m-%d')) utc_extract_time = str(datetime.strftime(utc_extract_date_time,'%H:%M:%S')) conn = sqlite3.connect("scooters.db") all_data = [] for scooter in scooter_companies: company = scooter['company'] endpoint = scooter['endpoint'] color = scooter['color'] # app_token = '.json?' #add $$app_token=APPTOKEN url = endpoint # + app_token response = requests.get(url) data = json.loads(response.text) df = pd.DataFrame(data) df['gps_longitude'] = df['gps_longitude'].astype('float') df['gps_latitude'] = df['gps_latitude'].astype('float') df['company_name'] = company # converting date time to central - TODO: create a function df['date_time'] = df['availability_start_date'] + ' ' + df['availability_start_time'] df['date_time'] = df.apply(lambda x: datetime.strptime(x['date_time'], '%Y-%m-%d %H:%M:%S'),axis=1) df['utc_time'] = df.apply(lambda x: utc.localize(x['date_time']),axis=1) df['central_time'] = df.apply(lambda x: x['utc_time'].astimezone(central),axis=1) df['availability_start_date_cst'] = df.apply(lambda x: str(datetime.strftime(x['central_time'],'%Y-%m-%d')),axis=1) df['availability_start_time_cst'] = df.apply(lambda x: str(datetime.strftime(x['central_time'],'%H:%M:%S')),axis=1) df['extract_date_cst'] = cst_extract_date df['extract_time_cst'] = cst_extract_time df['extract_date_utc'] = utc_extract_date df['extract_time_utc'] = utc_extract_time extract_datetime = datetime.strptime(cst_extract_date + ' ' + cst_extract_time, '%Y-%m-%d %H:%M:%S') df['availability_duration_seconds'] = df.apply(lambda x: (central.localize(extract_datetime) - x['central_time']).total_seconds(),axis=1) # remove the conversion columns - we don't need them df_cleansed = df[['availability_duration', 'availability_start_date', 'availability_start_time', 'company_name','company_phone', 'company_website', 'gps_latitude', 'gps_longitude', 'real_time_fare', 'sumd_group', 'sumd_id', 'sumd_type', 'availability_start_date_cst', 'availability_start_time_cst','availability_duration_seconds', 'extract_date_cst','extract_time_cst','extract_date_utc','extract_time_utc']] all_data.append(df_cleansed) full_data_set = pd.concat(all_data) full_data_set.to_sql('scooters',conn,if_exists='append',index=False) conn.commit() conn.close() if __name__=='__main__': main()
{ "alphanum_fraction": 0.6752278376, "author": null, "avg_line_length": 45.1214953271, "converted": null, "ext": "py", "file": null, "hexsha": "ff025796a445d794835ed92300fe11b53291c5a6", "include": true, "lang": "Python", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 3, "max_forks_repo_forks_event_max_datetime": "2019-09-07T21:09:48.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-24T11:59:36.000Z", "max_forks_repo_head_hexsha": "eaaafddf3654c0fce0a6bdf7e42afe632451def8", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "krysmathis/open-data-portal", "max_forks_repo_path": "nashville/scooter-data/script/extract.py", "max_issues_count": 8, "max_issues_repo_head_hexsha": "eaaafddf3654c0fce0a6bdf7e42afe632451def8", "max_issues_repo_issues_event_max_datetime": "2021-04-16T14:56:26.000Z", "max_issues_repo_issues_event_min_datetime": "2019-07-27T14:00:24.000Z", "max_issues_repo_licenses": [ "Apache-2.0" ], "max_issues_repo_name": "krysmathis/open-data-portal", "max_issues_repo_path": "nashville/scooter-data/script/extract.py", "max_line_length": 145, "max_stars_count": 1, "max_stars_repo_head_hexsha": "e50411dc4cec38102a45c1a0ac76905141595f1b", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "kazshak/open-data-portal", "max_stars_repo_path": "nashville/scooter-data/script/extract.py", "max_stars_repo_stars_event_max_datetime": "2019-12-15T20:06:27.000Z", "max_stars_repo_stars_event_min_datetime": "2019-12-15T20:06:27.000Z", "num_tokens": 1234, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 4828 }
from .._lingspam import fetch_lingspam from .._lingspam import create_pipelines_lingspam from sklearn.model_selection import RandomizedSearchCV from sklearn.model_selection import cross_val_score import numpy as np def test_fetch(): """Test fetching the LingSpam dataset. """ try: df = fetch_lingspam() except Exception as e: print(e) assert((2893, 2) == df.values.shape) def test_basemodel(): """Test the sample pipelines for LingSpam. """ df = fetch_lingspam() # add somthng like ".sample(100)" for testing with less data. pipelines = create_pipelines_lingspam() X = df['text'].values y = df['spam?'].values.astype('int') for p in pipelines: scores = cross_val_score(p, X, y, cv=10) # Reduce cv folds for quicker testing. print(scores, np.mean(scores))
{ "alphanum_fraction": 0.6756756757, "author": null, "avg_line_length": 31.5185185185, "converted": null, "ext": "py", "file": null, "hexsha": "b8e9d367c8d9bbdd61324708b49c6f8bc4036b1e", "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": "cf5055bc8e8a11c9b44b5f01bf36efe3f0279606", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "in2ai/resources-spam-filtering", "max_forks_repo_path": "in2ai/play/spam/tests/test_lingspam.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "cf5055bc8e8a11c9b44b5f01bf36efe3f0279606", "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": "in2ai/resources-spam-filtering", "max_issues_repo_path": "in2ai/play/spam/tests/test_lingspam.py", "max_line_length": 90, "max_stars_count": null, "max_stars_repo_head_hexsha": "cf5055bc8e8a11c9b44b5f01bf36efe3f0279606", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "in2ai/resources-spam-filtering", "max_stars_repo_path": "in2ai/play/spam/tests/test_lingspam.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": 851 }
#%% import numpy as np print("Numpy Version is ", np.__version__) #%% # Creating 1 dimensional numpy array with Python list (int type) one_d_list = [1, 2, 3, 4, 5] array_one_dim_list = np.array(one_d_list) print("NumPy array: ", array_one_dim_list) print("Shape: ", array_one_dim_list.shape) print("Data Type: ", array_one_dim_list.dtype.name) #%% # Creating 2 dimensional numpy array with Python list (float type) two_d_list = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]] array_two_d_py_list = np.array(two_d_list) print("NumPy array: \n", array_two_d_py_list) print("Shape: ", array_two_d_py_list.shape) print("Data Type: ", array_two_d_py_list.dtype.name) #%% # Creating 3 dimensional numpy array with Python 3d list (String) three_d_list = [ [["aa", "bb", "cc"], ["dd", "ee", "ff"], ["gg", "hh", "kk"]], [["ll", "mm", "nn"], ["oo", "pp", "qq"], ["rr", "ss", "tt"]], ] three_d_array = np.array(three_d_list) print("NumPy array: \n", three_d_array) print("Shape: ", three_d_array.shape) print("Data Type: ", three_d_array.dtype.name) #%% # Creating 3 dimensional numpy array with Python 3d list (String) three_d_list = [ [["aa", "bb", "cc"], ["dd", "ee", "ff"], ["gg", "hh", "kk"]], [["ll", "mm", "nn"], ["oo", "pp", "qq"], ["rr", "ss", "tt"]], ] three_d_array = np.array(three_d_list) print("NumPy array: \n", three_d_array) print("Shape: ", three_d_array.shape) print("Data Type: ", three_d_array.dtype.name) #%% # Creating NumPy array with Python list with mix data type elements mix_data_type_list = [1.0, 2, 3.5, 4.75, 5.0] mix_data_type_array = np.array(mix_data_type_list) print("NumPy array: \n", mix_data_type_array) print("Shape: ", mix_data_type_array.shape) print("Data Type: ", mix_data_type_array.dtype.name) #%% # Creating NumPy array with Pythong list and specifying data type fix_data_type_array = np.array(mix_data_type_list, np.int) print("NumPy array: \n", fix_data_type_array) print("Shape: ", fix_data_type_array.shape) print("Data Type: ", fix_data_type_array.dtype.name) #%% # Creating NumPy array with mix of List and Tuples upgraded a_list = [1, 2.5, 3] a_tuple = (1.5, 2.3, 3) two_d_list_tuple_array = np.array([a_list, a_tuple]) print("NumPy array: \n", two_d_list_tuple_array) print("Shape: ", two_d_list_tuple_array.shape) print("Data Type: ", two_d_list_tuple_array.dtype.name) #%% # Creating NumPy array with jagged 2 d Python list jagged_two_d_list = [[1, 2, 3], [4, 5, 6], [7, 8]] jagged_two_d_array = np.array(jagged_two_d_list) print("NumPy array: \n", jagged_two_d_array) print("Shape: ", jagged_two_d_array.shape) print("Data Type: ", jagged_two_d_array.dtype.name) #%% # Create NumPy array with Python List and enforce minimum dimension # We are using an already create one dimensional array one_d_list array_enforced_three_dim_list = np.array(object=two_d_list, ndmin=3) print("NumPy array: ", array_enforced_three_dim_list) print("Shape: ", array_enforced_three_dim_list.shape) print("Data Type: ", array_enforced_three_dim_list.dtype.name) #%% # Use asarray to create NumPy array one_dim_list = [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]] one_dim_array_use_asarray = np.asarray(one_dim_list) print("NumPy array: \n", one_dim_array_use_asarray) print("Shape: ", one_dim_array_use_asarray.shape) print("Data Type: ", one_dim_array_use_asarray.dtype.name) # For above operation NumPy copy as object used to create array is Python list #%% # array method by default make copy and hence change applied to copy np.array(one_dim_array_use_asarray)[1]=1 print("NumPy array: \n", one_dim_array_use_asarray) # asarray method don't make copy and hence change applied to one_dim_array_use_asarray np.asarray(one_dim_array_use_asarray)[1]=1 print("NumPy array: \n", one_dim_array_use_asarray)
{ "alphanum_fraction": 0.7166755178, "author": null, "avg_line_length": 32.747826087, "converted": null, "ext": "py", "file": null, "hexsha": "2ac3f2b1b63f623e2edd2a08e1b7c84d03dd7a62", "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": "3f7f744ca6b1d093acf3b03578f5c9ed3dba5dd9", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "geekmj/python-tutorials", "max_forks_repo_path": "numpy-basics/create-array-with-python-structures.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "3f7f744ca6b1d093acf3b03578f5c9ed3dba5dd9", "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": "geekmj/python-tutorials", "max_issues_repo_path": "numpy-basics/create-array-with-python-structures.py", "max_line_length": 86, "max_stars_count": null, "max_stars_repo_head_hexsha": "3f7f744ca6b1d093acf3b03578f5c9ed3dba5dd9", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "geekmj/python-tutorials", "max_stars_repo_path": "numpy-basics/create-array-with-python-structures.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1145, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 3766 }
[STATEMENT] lemma rk_ext: assumes "rk X \<le> 3" shows "\<exists>P. rk(X \<union> {P}) = rk X + 1" [PROOF STATE] proof (prove) goal (1 subgoal): 1. \<exists>P. rk (X \<union> {P}) = rk X + 1 [PROOF STEP] proof- [PROOF STATE] proof (state) goal (1 subgoal): 1. \<exists>P. rk (X \<union> {P}) = rk X + 1 [PROOF STEP] obtain A B C D where "rk {A,B,C,D} \<ge> 4" [PROOF STATE] proof (prove) goal (1 subgoal): 1. (\<And>A B C D. 4 \<le> rk {A, B, C, D} \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] using rk_ax_dim [PROOF STATE] proof (prove) using this: \<exists>A B C D. 4 \<le> rk {A, B, C, D} goal (1 subgoal): 1. (\<And>A B C D. 4 \<le> rk {A, B, C, D} \<Longrightarrow> thesis) \<Longrightarrow> thesis [PROOF STEP] by auto [PROOF STATE] proof (state) this: 4 \<le> rk {A, B, C, D} goal (1 subgoal): 1. \<exists>P. rk (X \<union> {P}) = rk X + 1 [PROOF STEP] have f1:"rk (X \<union> {A, B, C, D}) \<ge> 4" [PROOF STATE] proof (prove) goal (1 subgoal): 1. 4 \<le> rk (X \<union> {A, B, C, D}) [PROOF STEP] by (metis Un_upper2 \<open>4 \<le> rk {A, B, C, D}\<close> matroid_ax_2 sup.coboundedI2 sup.orderE) [PROOF STATE] proof (state) this: 4 \<le> rk (X \<union> {A, B, C, D}) goal (1 subgoal): 1. \<exists>P. rk (X \<union> {P}) = rk X + 1 [PROOF STEP] have "rk (X \<union> {A, B, C, D}) = rk X" if "rk(X \<union> {A}) = rk(X \<union> {B})" and "rk(X \<union> {B}) = rk(X \<union> {C})" and "rk(X \<union> {C}) = rk(X \<union> {D})" and "rk(X \<union> {D}) = rk X" [PROOF STATE] proof (prove) goal (1 subgoal): 1. rk (X \<union> {A, B, C, D}) = rk X [PROOF STEP] using matroid_ax_3_alt' that(1) that(2) that(3) that(4) [PROOF STATE] proof (prove) using this: rk (?X \<union> {?y}) = rk (?X \<union> {?z}) \<longrightarrow> rk (?X \<union> {?z}) = rk ?X \<longrightarrow> rk ?X = rk (?X \<union> {?y, ?z}) rk (X \<union> {A}) = rk (X \<union> {B}) rk (X \<union> {B}) = rk (X \<union> {C}) rk (X \<union> {C}) = rk (X \<union> {D}) rk (X \<union> {D}) = rk X goal (1 subgoal): 1. rk (X \<union> {A, B, C, D}) = rk X [PROOF STEP] by auto [PROOF STATE] proof (state) this: \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> rk (X \<union> {A, B, C, D}) = rk X goal (1 subgoal): 1. \<exists>P. rk (X \<union> {P}) = rk X + 1 [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> rk (X \<union> {A, B, C, D}) = rk X [PROOF STEP] have f2:"rk (X \<union> {A, B, C, D}) \<le> 3" if "rk(X \<union> {A}) = rk(X \<union> {B})" and "rk(X \<union> {B}) = rk(X \<union> {C})" and "rk(X \<union> {C}) = rk(X \<union> {D})" and "rk(X \<union> {D}) = rk X" [PROOF STATE] proof (prove) using this: \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> rk (X \<union> {A, B, C, D}) = rk X goal (1 subgoal): 1. rk (X \<union> {A, B, C, D}) \<le> 3 [PROOF STEP] using assms that(1) that(2) that(3) that(4) [PROOF STATE] proof (prove) using this: \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> rk (X \<union> {A, B, C, D}) = rk X rk X \<le> 3 rk (X \<union> {A}) = rk (X \<union> {B}) rk (X \<union> {B}) = rk (X \<union> {C}) rk (X \<union> {C}) = rk (X \<union> {D}) rk (X \<union> {D}) = rk X goal (1 subgoal): 1. rk (X \<union> {A, B, C, D}) \<le> 3 [PROOF STEP] by linarith [PROOF STATE] proof (state) this: \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> rk (X \<union> {A, B, C, D}) \<le> 3 goal (1 subgoal): 1. \<exists>P. rk (X \<union> {P}) = rk X + 1 [PROOF STEP] from f1 and f2 [PROOF STATE] proof (chain) picking this: 4 \<le> rk (X \<union> {A, B, C, D}) \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> rk (X \<union> {A, B, C, D}) \<le> 3 [PROOF STEP] have "False" if "rk(X \<union> {A}) = rk(X \<union> {B})" and "rk(X \<union> {B}) = rk(X \<union> {C})" and "rk(X \<union> {C}) = rk(X \<union> {D})" and "rk(X \<union> {D}) = rk X" [PROOF STATE] proof (prove) using this: 4 \<le> rk (X \<union> {A, B, C, D}) \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> rk (X \<union> {A, B, C, D}) \<le> 3 goal (1 subgoal): 1. False [PROOF STEP] using that(1) that(2) that(3) that(4) [PROOF STATE] proof (prove) using this: 4 \<le> rk (X \<union> {A, B, C, D}) \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> rk (X \<union> {A, B, C, D}) \<le> 3 rk (X \<union> {A}) = rk (X \<union> {B}) rk (X \<union> {B}) = rk (X \<union> {C}) rk (X \<union> {C}) = rk (X \<union> {D}) rk (X \<union> {D}) = rk X goal (1 subgoal): 1. False [PROOF STEP] by linarith [PROOF STATE] proof (state) this: \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> False goal (1 subgoal): 1. \<exists>P. rk (X \<union> {P}) = rk X + 1 [PROOF STEP] then [PROOF STATE] proof (chain) picking this: \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> False [PROOF STEP] have "rk (X \<union> {A}) = rk X + 1 \<or> rk (X \<union> {B}) = rk X + 1 \<or> rk (X \<union> {C}) = rk X + 1 \<or> rk (X \<union> {D}) = rk X + 1" [PROOF STATE] proof (prove) using this: \<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> False goal (1 subgoal): 1. rk (X \<union> {A}) = rk X + 1 \<or> rk (X \<union> {B}) = rk X + 1 \<or> rk (X \<union> {C}) = rk X + 1 \<or> rk (X \<union> {D}) = rk X + 1 [PROOF STEP] by (smt One_nat_def Suc_le_eq Suc_numeral Un_upper2 \<open>4 \<le> rk {A, B, C, D}\<close> \<open>\<lbrakk>rk (X \<union> {A}) = rk (X \<union> {B}); rk (X \<union> {B}) = rk (X \<union> {C}); rk (X \<union> {C}) = rk (X \<union> {D}); rk (X \<union> {D}) = rk X\<rbrakk> \<Longrightarrow> rk (X \<union> {A, B, C, D}) = rk X\<close> add.right_neutral add_Suc_right assms antisym_conv1 matroid_ax_2 matroid_ax_2_alt not_less semiring_norm(2) semiring_norm(8) sup.coboundedI2 sup.orderE) [PROOF STATE] proof (state) this: rk (X \<union> {A}) = rk X + 1 \<or> rk (X \<union> {B}) = rk X + 1 \<or> rk (X \<union> {C}) = rk X + 1 \<or> rk (X \<union> {D}) = rk X + 1 goal (1 subgoal): 1. \<exists>P. rk (X \<union> {P}) = rk X + 1 [PROOF STEP] thus "\<exists>P . rk (X \<union> {P}) = rk X + 1" [PROOF STATE] proof (prove) using this: rk (X \<union> {A}) = rk X + 1 \<or> rk (X \<union> {B}) = rk X + 1 \<or> rk (X \<union> {C}) = rk X + 1 \<or> rk (X \<union> {D}) = rk X + 1 goal (1 subgoal): 1. \<exists>P. rk (X \<union> {P}) = rk X + 1 [PROOF STEP] by blast [PROOF STATE] proof (state) this: \<exists>P. rk (X \<union> {P}) = rk X + 1 goal: No subgoals! [PROOF STEP] qed
{ "alphanum_fraction": null, "author": null, "avg_line_length": null, "converted": null, "ext": null, "file": "Projective_Geometry_Matroid_Rank_Properties", "hexsha": null, "include": null, "lang": null, "length": 23, "llama_tokens": 3946, "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 sys import os import itertools from collections import defaultdict, Counter import re import numpy as np import cvxpy as cp NUMBERS = '123456789tjqk' # Allowed alternate inputs: a->1, 0->t, 10->t, emoji SUITS = 'scdh' CARDS = [ n+s for n, s in itertools.product(NUMBERS, SUITS) ] class Solver: def __init__(self, quiet=False, pretty=True, color=True, emoji=True): self.quiet = quiet self.pretty = pretty self.color = color self.emoji = emoji def solve(self, cards, optional_cards=()): # Count cards cards = list(cards) card_codes = cards_to_codes(cards) optional_cards = list(optional_cards) assert min((Counter(cards)-Counter(optional_cards)).values(), default=0) >= 0, ( 'optional_cards must be a subset of cards') card_counts = Counter(cards) optional_counts = Counter(optional_cards) # Make grid of cards to find sets and sequences seq_arr = np.zeros((len(SUITS), len(NUMBERS+NUMBERS[0:1])), dtype=int) for i, j in card_codes: seq_arr[i, j] += 1 seq_arr[:, -1] = seq_arr[:, 0] seq_nonzero = (seq_arr > 0).astype(int) # Extract sets, sequences, and find disconnected cards find_seq = np.concatenate([ seq_nonzero[:, 0:1] + seq_nonzero[:, 1:2], seq_nonzero[:, :-2] + seq_nonzero[:, 1:-1] + seq_nonzero[:, 2:], ], axis=1) alone = find_seq * seq_nonzero[:, :-1] == 1 alone[:, 0] &= seq_nonzero[:, -2] == 0 find_set = np.sum(seq_nonzero, axis=0)[:-1] alone[:, find_set >= 3] = False # Build a list of all possible sequences using the current cards seq_list = [] # Only the max length sequences, no overlap seq_list_full = [] for i in range(len(SUITS)): j = 0 while j < len(NUMBERS): if find_seq[i, j] >= 3: jj = j+1 while jj < len(NUMBERS) and find_seq[i, jj] >= 3: jj += 1 seq = (np.array([np.full(jj-j+2, i), range(j-1, jj+1)]).T % len(NUMBERS)) seq_list.append(seq[:13]) seq_list_full.append(seq[:13]) for l in reversed(range(3, min(13, len(seq)))): for ll in range(len(seq)-l+1): seq_list_full.append(seq[ll:l+ll]) j = jj - 1 j += 1 # Build a list of all possible sets using the current cards set_list = [] # Only the max length sets, no overlap set_list_full = [] arange4 = np.arange(4) for j in range(len(NUMBERS)): if find_set[j] < 3: continue group = np.array([ arange4[seq_nonzero[:, j] > 0], np.full(find_set[j], j) ]).T set_list.append(group) set_list_full.append(group) if len(group) == 4: set_list_full.append([group[0], group[1], group[2]]) set_list_full.append([group[1], group[2], group[3]]) set_list_full.append([group[0], group[2], group[3]]) set_list_full.append([group[0], group[1], group[3]]) # Map each card to the list of groups it could participate in card_options = defaultdict(list) for seq in itertools.chain(set_list_full, seq_list_full): for i, j in seq: card_options[i, j].append(frozenset((i, j) for i, j in seq)) def clean_solution(sol): '''Make pretty strings to display a solution''' if sol is None: return 'no solution', '' selected = sorted(( name for name, cnt in sol.items() for _ in range(cnt) ), key=sort_key ) remaining_cnt = ( Counter(cards) - Counter(c for name, cnt in sol.items() for name2 in [name] * cnt for c in name.replace('_', '').split(',')) ) hand = ','.join(sorted_cards(remaining_cnt.elements())) using_cnt = Counter(optional_cards) - remaining_cnt hand_use = ','.join(sorted_cards(using_cnt.elements())) out = f"({') ('.join(selected)})" for card in using_cnt.keys(): if using_cnt[card] <= 1: i = out.find(card) if i >= 0: out = f'{out[:i]}[ {card} ]{out[i+2:]}' else: out = out.replace(card, f'[ {card} ]') if not sol: out = 'no cards' else: out = self.pretty_cards(out) if not hand: hand = 'WIN' else: hand = self.pretty_cards(hand) if hand_use: hand = f'{hand} -- use: {self.pretty_cards(hand_use)}' return out, hand def solution_size(sol): '''The number of cards used by the solution.''' if sol is None: return 0 return sum( len(name.split(',')) * cnt for name, cnt in sol.items() ) def print_sol(sol): '''Print the solution.''' extra = len(card_codes)-solution_size(sol) table, hand = clean_solution(sol) if optional_cards: msg = f'--- {extra} left ---' if self.color: import termcolor if extra >= len(optional_cards): self.print(termcolor.colored(msg, 'yellow')) elif extra > 0: self.print(termcolor.colored(msg, 'green')) else: self.print(termcolor.colored(msg, 'green', attrs=['reverse'])) else: self.print(msg) self.print(f'hand: {hand}') self.print(f'table: {table}') # Check for an empty solution (otherwise causes the solver to fail) if len(seq_list_full) + len(set_list_full) == 0: # No solutions if cards == optional_cards: # Set comparison sol = {} else: sol = None print_sol(sol) return sol # Encode as an integer program possible_groups = [ codes_to_cards(group) for group in itertools.chain(set_list_full, seq_list_full) ] card_idx = {card: i for i, card in enumerate(card_counts)} card_mat = np.zeros((len(possible_groups), len(card_counts)), dtype=bool) for i, group in enumerate(possible_groups): for card in group: card_mat[i, card_idx[card]] = True card_min = np.zeros(len(card_counts), dtype=int) card_max = np.zeros(len(card_counts), dtype=int) for card in card_counts.keys(): max_count = card_counts[card] min_count = max_count - optional_counts[card] card_min[card_idx[card]] = min_count card_max[card_idx[card]] = max_count group_max = np.array([ 1 + all(card_counts[card] >= 2 for card in group) for group in possible_groups ]) # Setup CVXPY x = cp.Variable(len(possible_groups), integer=True) constraints = [ card_mat.T @ x >= card_min, card_mat.T @ x <= card_max, x <= group_max, x >= 0 ] obj = cp.Maximize(sum(card_mat.T @ x) - sum(x) / 1024) problem = cp.Problem(obj, constraints) # Solve cost = problem_solve_suppress_stdout(problem, verbose=False) if isinstance(cost, str) or x.value is None: self.print_err(f'solver failed: {problem.status} ({cost})', RuntimeError) if x.value is None: sol = None print_sol(sol) return sol else: sol = { cards_to_str(group): round(val) for group, val in zip(possible_groups, x.value) if round(val) > 0 } # Verify valid solution sol_card_counts = sum(( Counter(group_str.split(',')) for group_str, cnt in sol.items() for _ in range(cnt) ), start=Counter() ) remaining_counts = Counter(card_counts) remaining_counts.subtract(sol_card_counts) used_hand_counts = Counter(optional_counts) used_hand_counts.subtract(remaining_counts) if (any(val < 0 for val in remaining_counts.values()) or any(val < 0 for val in used_hand_counts.values())): # Invalid solution sol = None # Print and return in a sorted, easy-to-use form print_sol(sol) selected = [ name.split(',') for name in sorted(( name for name, cnt in sol.items() for _ in range(cnt) ), key=sort_key ) ] return selected def play_hand(self, table, hand=''): '''Convenience method to parse and check inputs and check the table state is solvable before solving table+hand.''' if isinstance(table, str): table = parse_cards(table) if isinstance(hand, str): hand = parse_cards(hand) if isinstance(table, Counter): table = list(table.elements()) if isinstance(hand, Counter): hand = list(hand.elements()) if max(Counter(table+hand).values(), default=0) > 2: for c, n in Counter(table+hand).most_common(1): self.print_err(f'more than two of card: {c} (x{n})', ValueError) for c in table+hand: if c not in CARDS: raise ValueError(f'invalid card: {c}') self.print() if hand: self.print('### Before your play ###') self.solve(table) self.print() self.print('### Solve ###') return self.solve(table+hand, hand) def print(self, *args, **kwargs): if not self.quiet: print(*args, **kwargs) def print_err(self, msg, err_type): if self.quiet: raise err_type(msg) else: if self.color: import termcolor print(termcolor.colored(f'Error: {msg}', 'red'), file=sys.stderr) else: print(f'Error: {msg}', file=sys.stderr) def pretty_cards(self, cards_str): if self.emoji: cards_str = cards_str.replace('s', '♠️ ').replace('c', '♣️ ') cards_str = cards_str.replace('d', '♦️ ').replace('h', '♥️ ') if self.pretty: cards_str = cards_str.replace('1', 'A').replace('t', '10') cards_str = cards_str.replace(',', ' ').upper() if self.emoji: if self.color: import termcolor end_marks = termcolor.colored('____', 'white', attrs=['reverse'] ).split('____') def mark(match): return ( end_marks[-1] + termcolor.colored(match[1], 'green', attrs=['reverse']) + end_marks[0] ) cards_str = re.sub(r'\[ ([^\]]*) \]', mark, cards_str) cards_str = termcolor.colored(cards_str, 'white', attrs=['reverse']) elif self.color: import termcolor def mark(match): return termcolor.colored(match[1], 'green', attrs=['underline']) cards_str = re.sub(r'\[ ([^[\]]*) \]', mark, cards_str) return cards_str def problem_solve_suppress_stdout(problem, **kwargs): '''Suppress diagnostic messages printed by CVXPY C-libraries.''' dup_success = False stdout_cp = None devnull = None try: stdout_cp = os.dup(1) devnull = open(os.devnull, 'w') os.dup2(devnull.fileno(), 1) dup_success = True return problem.solve(**kwargs) except: if dup_success: raise else: # Give up and run without stdout suppression return problem.solve(**kwargs) finally: if devnull is not None: devnull.close() if stdout_cp is not None: os.dup2(stdout_cp, 1) os.close(stdout_cp) def sort_key(s): s = s.lower() s = s.replace('a', '1').replace('q', 'i') s = s.replace('j', 'h').replace('s', 'b').replace('t', 'b') # Sort sequences after sets if ',' in s and not all(ss[:1] == s[:1] for ss in s.split(',')): s = 'z_' + s return s def sort_key_k(s): return sort_key(s).replace('1', 'l') def sorted_cards(cards): '''Returns the cards sorted nicely.''' cards = list(cards) if (any('k' in card for card in cards) and not any('2' in card for card in cards)): cards.sort(key=sort_key_k) else: cards.sort(key=sort_key) return cards def cards_to_codes(cards): '''Converts a list of card names to (suit_index, rank_index) tuples.''' return np.array([ (SUITS.index(s), NUMBERS.index(n)) for n, s in cards ]) def codes_to_cards(codes): '''Converts a list of (suit_index, rank_index) tuples to card names.''' return [ f'{NUMBERS[j]}{SUITS[i]}' for i, j in codes ] def codes_to_str(codes): '''Converts a list of card codes (index tuples) to a sorted, comma-separated, printable string.''' return cards_to_str(codes_to_cards(codes)) def cards_to_str(cards): '''Converts a list of card names to a sorted, comma-separated, printable string.''' return ','.join(sorted_cards(cards)) class ParseError(RuntimeError): pass def parse_cards(cards_str): '''Parse a comma-separated list of cards. Converts common variants of card names such as 10s->ts, ah->1h, 0d->td K♥️ ->kh. ''' # Normalize cards_nrm = cards_str.lower() cards_nrm = cards_nrm.replace('10', 't').replace('a', '1').replace('0', 't') cards_nrm = cards_nrm.replace('♠️', 's').replace('♣️', 'c') cards_nrm = cards_nrm.replace('♦️', 'd').replace('♥️', 'h') # Parse cards = [s.strip() for s in cards_nrm.split(',')] # Verify no invalid cards for i, card in enumerate(cards): if card and card not in CARDS: raise ParseError(f'''Invalid card "{cards_str.split(',')[i]}"''') cards = [card for card in cards if card] return cards def input_cards(input_msg, shortcuts=None): '''Prompts for input of a list of cards and returns the parsed list. If the input is invalid, prints an error and prompts again. If 'x' is entered, raises a KeyboardInterrupt. If a shortcuts dictionary is given and `user_input in shortcuts` shortcuts[user_input] will be parsed instead (ensuring user_input is lowercase). ''' while True: try: cards_str = input(input_msg) cards_str = cards_str.strip().lower() if cards_str == 'x': raise KeyboardInterrupt() if shortcuts and cards_str in shortcuts: cards_str = shortcuts[cards_str] return parse_cards(cards_str) except ParseError as e: print(str(e), file=sys.stderr)
{ "alphanum_fraction": 0.5135774788, "author": null, "avg_line_length": 36.2437923251, "converted": null, "ext": "py", "file": null, "hexsha": "b0e702afcc9e716808c44b671d9d37f2558f79d7", "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": "e5dd4cf05819d4cb9b8637c09b8a41df3d9c54d6", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "cduck/machiavelli", "max_forks_repo_path": "machiavelli/solver.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "e5dd4cf05819d4cb9b8637c09b8a41df3d9c54d6", "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": "cduck/machiavelli", "max_issues_repo_path": "machiavelli/solver.py", "max_line_length": 80, "max_stars_count": null, "max_stars_repo_head_hexsha": "e5dd4cf05819d4cb9b8637c09b8a41df3d9c54d6", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "cduck/machiavelli", "max_stars_repo_path": "machiavelli/solver.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3634, "path": null, "reason": "import numpy,import cvxpy", "repo": null, "save_path": null, "sha": null, "size": 16056 }
#ifndef BOOST_DETAIL_SP_TYPEINFO_HPP_INCLUDED #define BOOST_DETAIL_SP_TYPEINFO_HPP_INCLUDED // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif // detail/sp_typeinfo.hpp // // Copyright 2007 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/config.hpp> #if defined( BOOST_NO_TYPEID ) #include <boost/current_function.hpp> #include <functional> namespace boost { namespace detail { class sp_typeinfo { private: sp_typeinfo( sp_typeinfo const& ); sp_typeinfo& operator=( sp_typeinfo const& ); char const * name_; public: explicit sp_typeinfo( char const * name ): name_( name ) { } bool operator==( sp_typeinfo const& rhs ) const { return this == &rhs; } bool operator!=( sp_typeinfo const& rhs ) const { return this != &rhs; } bool before( sp_typeinfo const& rhs ) const { return std::less< sp_typeinfo const* >()( this, &rhs ); } char const* name() const { return name_; } }; template<class T> struct sp_typeid_ { static sp_typeinfo ti_; static char const * name() { return BOOST_CURRENT_FUNCTION; } }; template<class T> sp_typeinfo sp_typeid_< T >::ti_ = sp_typeid_< T >::name(); template<class T> struct sp_typeid_< T & >: sp_typeid_< T > { }; template<class T> struct sp_typeid_< T const >: sp_typeid_< T > { }; template<class T> struct sp_typeid_< T volatile >: sp_typeid_< T > { }; template<class T> struct sp_typeid_< T const volatile >: sp_typeid_< T > { }; } // namespace detail } // namespace boost #define BOOST_SP_TYPEID(T) (boost::detail::sp_typeid_<T>::ti_) #else #include <typeinfo> namespace boost { namespace detail { #if defined( BOOST_NO_STD_TYPEINFO ) typedef ::type_info sp_typeinfo; #else typedef std::type_info sp_typeinfo; #endif } // namespace detail } // namespace boost #define BOOST_SP_TYPEID(T) typeid(T) #endif #endif // #ifndef BOOST_DETAIL_SP_TYPEINFO_HPP_INCLUDED
{ "alphanum_fraction": 0.6408020924, "author": null, "avg_line_length": 17.6461538462, "converted": null, "ext": "hpp", "file": null, "hexsha": "c8db66d14c4ae49a10ba7d811397214c0d8b5f3e", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 6, "max_forks_repo_forks_event_max_datetime": "2022-01-27T12:19:58.000Z", "max_forks_repo_forks_event_min_datetime": "2015-05-07T14:41:53.000Z", "max_forks_repo_head_hexsha": "e1d09a3b979b54c7b49883d48c05650476f366ae", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "MIPT-ILab/mdsp", "max_forks_repo_path": "boost/boost/detail/sp_typeinfo.hpp", "max_issues_count": 3, "max_issues_repo_head_hexsha": "e1d09a3b979b54c7b49883d48c05650476f366ae", "max_issues_repo_issues_event_max_datetime": "2021-01-08T14:08:52.000Z", "max_issues_repo_issues_event_min_datetime": "2015-04-15T17:11:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "MIPT-ILab/mdsp", "max_issues_repo_path": "boost/boost/detail/sp_typeinfo.hpp", "max_line_length": 78, "max_stars_count": 33, "max_stars_repo_head_hexsha": "e1d09a3b979b54c7b49883d48c05650476f366ae", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "MIPT-ILab/mdsp", "max_stars_repo_path": "boost/boost/detail/sp_typeinfo.hpp", "max_stars_repo_stars_event_max_datetime": "2021-06-06T13:58:14.000Z", "max_stars_repo_stars_event_min_datetime": "2015-04-15T16:58:00.000Z", "num_tokens": 558, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2294 }
"""Per-channel plotting in the 2D processes-boxes space.""" import matplotlib.pyplot as plt import numpy as np from ..util import basic_kwargs_check, get_expected_matrix, get_experiment_tag def _my_format(val): """Enforce a format style with 5 digits maximum including the decimal dot.""" if val < 1e2: return f"{val:.2f}" if val < 1e3: return f"{val:.1f}" if val < 1e6: v_new, suffix = val / 1e3, "k" elif val < 1e9: v_new, suffix = val / 1e6, "M" elif val < 1e12: v_new, suffix = val / 1e9, "B" else: raise NotImplementedError(f"Value is larger than forseen: {val}.") if v_new < 10: return f"{v_new:.2f}{suffix}" elif v_new < 100: return f"{v_new:.1f}{suffix}" else: return f"{v_new:.0f}{suffix}" def _plot_matrix( matrix, ax, experiment_tag=None, omit_zero=True, allow_unused_kwargs=False, **kwargs ): """DataFrame with floats -> 2D heatmap on `ax`.""" if allow_unused_kwargs: basic_kwargs_check(**kwargs) elif kwargs: raise TypeError(f"{', '.join(kwargs)} is an invalid keyword argument.") if experiment_tag: get_experiment_tag(experiment_tag)(ax) def set_labels(ax): ax.set_yticks(np.arange(matrix.shape[0])) ax.set_xticks(np.arange(matrix.shape[1])) ax.set_ylabel("class", fontsize=14) try: ax.set_yticklabels(matrix.index, fontsize=12) except AttributeError: pass ax.set_xlabel("BR", fontsize=14) try: ax.set_xticklabels(matrix.columns, rotation=90, fontsize=12) except AttributeError: pass def set_numbers(ax): np_matrix = np.array(matrix) # To make it work also for pd.DataFrame. for text_y, row in enumerate(np_matrix): for text_x, val in enumerate(row): if omit_zero and val == 0: continue if val > 0.3 * np_matrix.max(): color = "black" else: color = "white" ax.text( text_x, text_y, _my_format(val), ha="center", va="center", color=color, ) ax.imshow(matrix) set_labels(ax) set_numbers(ax) return ax def expected_counts_matrix( channel, ax=None, no_bkg=False, combine_bkg=False, experiment_tag=None, allow_unused_kwargs=False, **kwargs, ): """A 2D matrix showing the expected counts per process and box. Args: channel: an alldecays.DataChannel ax: matplotlib axis that the plot is drawn onto. By default, create a new axis object. no_bkg: If True, exclude the background processes from the plot. combine_bkg: If True, combine all background processes into one. experiment_tag: Add a watermark to the axis. allow_unused_kwargs: This can be nice to have for `all_plots`like calls. """ if allow_unused_kwargs: basic_kwargs_check(**kwargs) elif kwargs: raise TypeError(f"{', '.join(kwargs)} is an invalid keyword argument.") if ax is None: fig, ax = plt.subplots(figsize=(8, 10)) expected_matrix = get_expected_matrix(channel) n_signal = expected_matrix[channel.decay_names].sum().sum() if no_bkg: expected_matrix = expected_matrix[channel.decay_names] elif combine_bkg: expected_matrix["bkg"] = expected_matrix[channel.bkg_names].sum(axis=1) expected_matrix = expected_matrix[channel.decay_names + ["bkg"]] _plot_matrix(expected_matrix, ax, experiment_tag, **kwargs) ax.set_title( ( f"Distribution of the {n_signal:_.0f} signal events\n" "in the channel as expected for SM BRs" ), fontsize=14, ) return ax def probability_matrix( channel, ax=None, no_bkg=False, combine_bkg=False, experiment_tag=None, allow_unused_kwargs=False, **kwargs, ): """A 2D matrix showing the box probabilities per process. Column entries do not necessarily add up to 100%. The missing probability accounts for the selection efficiency of the data channel. Args: channel: an alldecays.DataChannel ax: matplotlib axis that the plot is drawn onto. By default, create a new axis object. no_bkg: If True, exclude the background processes from the plot. combine_bkg: If True, combine all background processes into one. experiment_tag: Add a watermark to the axis. allow_unused_kwargs: This can be nice to have for `all_plots`like calls. """ if allow_unused_kwargs: basic_kwargs_check(**kwargs) elif kwargs: raise TypeError(f"{', '.join(kwargs)} is an invalid keyword argument.") if ax is None: fig, ax = plt.subplots(figsize=(8, 10)) percent_matrix = 100 * channel.mc_matrix if no_bkg: percent_matrix = percent_matrix[channel.decay_names] elif combine_bkg: weight = channel.bkg_cs_default / channel.bkg_cs_default.sum() percent_matrix["bkg"] = percent_matrix[channel.bkg_names].dot(weight) percent_matrix = percent_matrix[channel.decay_names + ["bkg"]] _plot_matrix(percent_matrix, ax, experiment_tag, **kwargs) ax.set_title("Matrix entries P(Class|BR) [%]", fontsize=14) return ax
{ "alphanum_fraction": 0.6202830189, "author": null, "avg_line_length": 31.8612716763, "converted": null, "ext": "py", "file": null, "hexsha": "1388d02d85924d75f9f4de2466b7b3e36988fbd9", "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": "08e51e99385ae7ca96edefddafd715e1d8cac3d3", "max_forks_repo_licenses": [ "Apache-2.0" ], "max_forks_repo_name": "LLR-ILD/alldecays", "max_forks_repo_path": "src/alldecays/plotting/channel/matrix_plots.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "08e51e99385ae7ca96edefddafd715e1d8cac3d3", "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": "LLR-ILD/alldecays", "max_issues_repo_path": "src/alldecays/plotting/channel/matrix_plots.py", "max_line_length": 88, "max_stars_count": null, "max_stars_repo_head_hexsha": "08e51e99385ae7ca96edefddafd715e1d8cac3d3", "max_stars_repo_licenses": [ "Apache-2.0" ], "max_stars_repo_name": "LLR-ILD/alldecays", "max_stars_repo_path": "src/alldecays/plotting/channel/matrix_plots.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1291, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 5512 }
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following * disclaimer. * * (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other materials provided with the distribution. * * (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * 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, THE UNITED STATES GOVERNMENT, OR ANY 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. **********************************************************************************************************************/ #ifndef SHAREDGUICOMPONENTS_BUTTONS_HPP #define SHAREDGUICOMPONENTS_BUTTONS_HPP #include <QPushButton> #include <boost/smart_ptr.hpp> class QPaintEvent; class QPixmap; class QTimer; namespace openstudio { class ZoomOutButton : public QPushButton { Q_OBJECT public: ZoomOutButton(QWidget * parent = nullptr); virtual ~ZoomOutButton() {} }; class OrangeButton : public QPushButton { Q_OBJECT public: OrangeButton(QWidget * parent = nullptr); virtual ~OrangeButton() {} }; class GrayButton : public QPushButton { Q_OBJECT public: GrayButton(QWidget * parent = nullptr); virtual ~GrayButton() {} }; class BlueButton : public QPushButton { Q_OBJECT public: BlueButton(QWidget * parent = nullptr); virtual ~BlueButton() {} }; class AddButton : public QPushButton { Q_OBJECT public: AddButton(QWidget * parent = nullptr); virtual ~AddButton() {} }; class SofterAddButton : public QPushButton { Q_OBJECT public: SofterAddButton(QWidget * parent = nullptr); virtual ~SofterAddButton() {} }; class RemoveButton : public QPushButton { Q_OBJECT public: RemoveButton(QWidget * parent = nullptr); virtual ~RemoveButton() {} }; class SofterRemoveButton : public QPushButton { Q_OBJECT public: SofterRemoveButton(QWidget * parent = nullptr); virtual ~SofterRemoveButton() {} }; class AddScriptButton : public QPushButton { Q_OBJECT public: AddScriptButton(QWidget * parent = nullptr); virtual ~AddScriptButton() {} }; class DuplicateButton : public QPushButton { Q_OBJECT public: DuplicateButton(QWidget * parent = nullptr); virtual ~DuplicateButton() {} }; class SofterDuplicateButton : public QPushButton { Q_OBJECT public: SofterDuplicateButton(QWidget * parent = nullptr); virtual ~SofterDuplicateButton() {} }; class UpButton : public QPushButton { Q_OBJECT public: UpButton(QWidget * parent = nullptr); virtual ~UpButton() {} }; class DownButton : public QPushButton { Q_OBJECT public: DownButton(QWidget * parent = nullptr); virtual ~DownButton() {} }; class MyMeasuresFolderButton : public QPushButton { Q_OBJECT public: MyMeasuresFolderButton(QWidget * parent = nullptr); virtual ~MyMeasuresFolderButton() {} }; class OpenDirectoryButton : public QPushButton { Q_OBJECT public: OpenDirectoryButton(QWidget * parent = nullptr); virtual ~OpenDirectoryButton() {} }; class CreateOneWithSelectedMeasuresButton : public GrayButton { Q_OBJECT public: CreateOneWithSelectedMeasuresButton(); virtual ~CreateOneWithSelectedMeasuresButton() {} }; class CreateOneForEachSelectedMeasureButton : public GrayButton { Q_OBJECT public: CreateOneForEachSelectedMeasureButton(); virtual ~CreateOneForEachSelectedMeasureButton() {} }; class CreateFromFileButton : public GrayButton { Q_OBJECT public: CreateFromFileButton(); virtual ~CreateFromFileButton() {} }; class CloudLostConnectionButton : public QPushButton { Q_OBJECT public: CloudLostConnectionButton(QWidget * parent = nullptr); virtual ~CloudLostConnectionButton() {} }; class CloudOffButton : public QPushButton { Q_OBJECT public: CloudOffButton(QWidget * parent = nullptr); virtual ~CloudOffButton() {} }; class CloudOnButton : public QPushButton { Q_OBJECT public: CloudOnButton(QWidget * parent = nullptr); virtual ~CloudOnButton() {} }; class CloudStartingButton : public QPushButton { Q_OBJECT public: CloudStartingButton(QWidget * parent = nullptr); virtual ~CloudStartingButton() {} public slots: void rotate(); protected: void paintEvent ( QPaintEvent * event ) override; private: QPixmap * m_background; QPixmap * m_arrow; float m_rotation; QTimer * m_timer; }; class CloudStoppingButton : public QPushButton { Q_OBJECT public: CloudStoppingButton(QWidget * parent = nullptr); virtual ~CloudStoppingButton() {} public slots: void rotate(); protected: void paintEvent ( QPaintEvent * event ) override; private: QPixmap * m_background; QPixmap * m_arrow; float m_rotation; QTimer * m_timer; }; class PlayButton : public QPushButton { Q_OBJECT public: enum Status { IDLE, IDLEDISABLED, STARTING, RUNNING, STOPPING, ERROR }; PlayButton(QWidget * parent = nullptr); virtual ~PlayButton() {} Status status() const; void setStatus(const Status & status); private: Status m_status; }; } // openstudio #endif // SHAREDGUICOMPONENTS_BUTTONS_HPP
{ "alphanum_fraction": 0.7119347665, "author": null, "avg_line_length": 20.1343283582, "converted": null, "ext": "hpp", "file": null, "hexsha": "6139d2488741688d9f49c4e2512d8ca8d52df513", "include": null, "lang": "C++", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 1, "max_forks_repo_forks_event_max_datetime": "2019-07-18T06:52:29.000Z", "max_forks_repo_forks_event_min_datetime": "2019-07-18T06:52:29.000Z", "max_forks_repo_head_hexsha": "6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "hongyuanjia/OpenStudio", "max_forks_repo_path": "openstudiocore/src/shared_gui_components/Buttons.hpp", "max_issues_count": null, "max_issues_repo_head_hexsha": "6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0", "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": "hongyuanjia/OpenStudio", "max_issues_repo_path": "openstudiocore/src/shared_gui_components/Buttons.hpp", "max_line_length": 120, "max_stars_count": 1, "max_stars_repo_head_hexsha": "6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "hongyuanjia/OpenStudio", "max_stars_repo_path": "openstudiocore/src/shared_gui_components/Buttons.hpp", "max_stars_repo_stars_event_max_datetime": "2019-04-21T15:38:54.000Z", "max_stars_repo_stars_event_min_datetime": "2019-04-21T15:38:54.000Z", "num_tokens": 1468, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 6745 }
```python # General import import numpy as np import scipy.sparse as sparse from scipy.integrate import ode import time import matplotlib.pyplot as plt ``` ```python # pyMPC and kalman import from pyMPC.mpc import MPCController from pyMPC.kalman import kalman_design_simple, LinearStateEstimator ``` ## System dynamics ## The system to be controlled is an inverted pendulum on a cart (see next Figure). The system is governed by the following differential equations: \begin{equation} \begin{aligned} (M+m)\ddot p + ml\ddot\phi \cos\phi - ml \dot \phi ^2 \sin \phi + b\dot p &= F \\ l \ddot \phi + \ddot p \cos \phi - g \sin\phi &= -f_\phi\dot \phi \end{aligned} \end{equation} Introducing the state vector $x=[p\; \dot p\; \phi\; \dot \phi]$ and the input $u=F$, the system dynamics are described in state-space by a set of an nonlinear ordinary differential equations: $\dot x = f(x,u)$ with \begin{equation} \begin{split} f(x,u) &= \begin{bmatrix} x_2\\ \frac{-mg \sin x_3\cos x_3 + mlx_4^3\sin x_3 + f_\phi m x_4 \cos x_3 - bx_2 + u }{M+(1-\cos^2 x_3)m}\\ x_3\\ \frac{(M+m)(g \sin x_3 - f_\phi x_4) - (lm x_4^2 \sin x_3 - bx_2 + u)\cos x_3}{l(M+(1-\cos^2 x_3)m)} \end{bmatrix}\\ \end{split} \end{equation} For MPC control design, the system is linearized about the upright (unstable) equilibrium point, i.e., about the point $x_{eq} = [0, \; 0\;, 0,\; 0]^\top$. The linearized system has form $\dot x = A_c x + B_c u$ with \begin{equation} A = \begin{bmatrix} 0& 1& 0& 0\\ 0& -\frac{b}{M}& -g\frac{m}{M}& f_\theta\frac{m}{M}\\ 0&0&0&1\\ 0&\frac{b}{Ml}& \frac{g(M+m)}{Ml}&-\frac{(M+m)f_\theta}{M l} \end{bmatrix},\qquad B= \begin{bmatrix} 0\\ \frac{1}{M}\\ 0\\ -\frac{1}{Ml}& \end{bmatrix} \end{equation} Next, the system is discretized with sampling time $T_s = 10\;\text{ms}$. Here we just use a Forward Euler dsicretization scheme for the sake of simplicity. ```python # Constants # M = 0.5 m = 0.2 b = 0.1 ftheta = 0.1 l = 0.3 g = 9.81 Ts = 10e-3 ``` ```python # System dynamics: \dot x = f_ODE(t,x,u) def f_ODE(t,x,u): F = u v = x[1] theta = x[2] omega = x[3] der = np.zeros(4) der[0] = v der[1] = (m * l * np.sin(theta) * omega ** 2 - m * g * np.sin(theta) * np.cos(theta) + m * ftheta * np.cos(theta) * omega + F - b * v) / (M + m * (1 - np.cos(theta) ** 2)) der[2] = omega der[3] = ((M + m) * (g * np.sin(theta) - ftheta * omega) - m * l * omega ** 2 * np.sin(theta) * np.cos(theta) - (F - b * v) * np.cos(theta)) / (l * (M + m * (1 - np.cos(theta) ** 2))) return der ``` ```python # Linearized System Matrices Ac =np.array([[0, 1, 0, 0], [0, -b / M, -(g * m) / M, (ftheta * m) / M], [0, 0, 0, 1], [0, b / (M * l), (M * g + g * m) / (M * l), -(M * ftheta + ftheta * m) / (M * l)]]) Bc = np.array([ [0.0], [1.0 / M], [0.0], [-1 / (M * l)] ]) Cc = np.array([[1., 0., 0., 0.], [0., 0., 1., 0.]]) Dc = np.zeros((2, 1)) [nx, nu] = Bc.shape # number of states and number or inputs ny = np.shape(Cc)[0] ``` ```python # Simple forward euler discretization Ad = np.eye(nx) + Ac * Ts Bd = Bc * Ts Cd = Cc Dd = Dc ``` ```python # Standard deviation of the measurement noise on position and angle std_npos = 0.005 std_nphi = 0.005 ``` ```python # Reference input and states xref = np.array([0.3, 0.0, 0.0, 0.0]) # reference state uref = np.array([0.0]) # reference input uminus1 = np.array([0.0]) # input at time step negative one - used to penalize the first delta u at time instant 0. Could be the same as uref. ``` ```python # Constraints xmin = np.array([-10.0, -10.0, -100, -100]) xmax = np.array([10.0, 10.0, 100, 100]) umin = np.array([-20]) umax = np.array([20]) Dumin = np.array([-5]) Dumax = np.array([5]) ``` ```python # Objective function weights Qx = sparse.diags([1.0, 0, 5.0, 0]) # Quadratic cost for states x0, x1, ..., x_N-1 QxN = sparse.diags([1.0, 0, 5.0, 0]) # Quadratic cost for xN Qu = 0.0 * sparse.eye(1) # Quadratic cost for u0, u1, ...., u_N-1 QDu = 0.1 * sparse.eye(1) # Quadratic cost for Du0, Du1, ...., Du_N-1 ``` ```python # Initialize simulation system phi0 = 15*2*np.pi/360 x0 = np.array([0, 0, phi0, 0]) # initial state t0 = 0 system_dyn = ode(f_ODE).set_integrator('vode', method='bdf') system_dyn.set_initial_value(x0, t0) _ = system_dyn.set_f_params(0.0) ``` ```python # Prediction horizon Np = 150 Nc = 75 ``` ```python # Instantiate and initialize MPC controller K = MPCController(Ad, Bd, Np=Np, Nc=Nc, x0=x0, xref=xref, uminus1=uminus1, Qx=Qx, QxN=QxN, Qu=Qu, QDu=QDu, xmin=xmin, xmax=xmax, umin=umin, umax=umax, Dumin=Dumin, Dumax=Dumax) K.setup() ``` ```python # Basic Kalman filter design Q_kal = np.diag([0.1, 10, 0.1, 10]) R_kal = np.eye(ny) L,P,W = kalman_design_simple(Ad, Bd, Cd, Dd, Q_kal, R_kal, type='filter') x0_est = x0 KF = LinearStateEstimator(x0_est, Ad, Bd, Cd, Dd,L) ``` ```python # Simulate in closed loop [nx, nu] = Bd.shape # number of states and number or inputs len_sim = 10 # simulation length (s) nsim = int(len_sim / Ts) # simulation length(timesteps) x_vec = np.zeros((nsim, nx)) y_vec = np.zeros((nsim, ny)) y_meas_vec = np.zeros((nsim, ny)) y_est_vec = np.zeros((nsim, ny)) x_est_vec = np.zeros((nsim, nx)) x_ref_vec = np.zeros((nsim, nx)) u_vec = np.zeros((nsim, nu)) t_MPC_CPU = np.zeros((nsim,1)) t_vec = np.arange(0, nsim) * Ts time_start = time.time() x_step = x0 x_step_est = x0 t_step = t0 uMPC = uminus1 for i in range(nsim): # Output for step i # System y_step = Cd.dot(system_dyn.y) # y[i] from the system ymeas_step = y_step ymeas_step[0] += std_npos * np.random.randn() ymeas_step[1] += std_nphi * np.random.randn() # Estimator # MPC uMPC = K.output() # u[i] = k(\hat x[i]) possibly computed at time instant -1 # Save output for step i y_vec[i, :] = y_step # y[i] y_meas_vec[i, :] = ymeas_step # y_meas[i] x_vec[i, :] = system_dyn.y # x[i] y_est_vec[i, :] = KF.y # \hat y[i|i-1] x_est_vec[i, :] = KF.x # \hat x[i|i-1] x_ref_vec[i, :] = xref #xref_fun(t_step) u_vec[i, :] = uMPC # u[i] # Update to i+1 # System system_dyn.set_f_params(uMPC) # set current input value to uMPC system_dyn.integrate(system_dyn.t + Ts) # integrate system dynamics for a time step # Kalman filter: update and predict KF.update(ymeas_step) # \hat x[i|i] KF.predict(uMPC) # \hat x[i+1|i] # MPC update for step i+1 time_MPC_start = time.time() K.update(KF.x, uMPC) # update with measurement (and possibly pre-compute u[i+1]) t_MPC_CPU[i] = time.time() - time_MPC_start # Time update t_step += Ts time_sim = time.time() - time_start ``` ```python # Plot results fig, axes = plt.subplots(3, 1, figsize=(10, 10), sharex=True) axes[0].plot(t_vec, x_est_vec[:, 0], "b", label="p_est") axes[0].plot(t_vec, x_vec[:, 0], "k", label='p') axes[0].plot(t_vec, x_ref_vec[:,0], "r--", linewidth=4, label="p_ref") axes[0].set_ylabel("Position (m)") axes[1].plot(t_vec, x_est_vec[:, 2] * 360 / 2 / np.pi, "b", label="phi_est") axes[1].plot(t_vec, x_vec[:, 2] * 360 / 2 / np.pi, label="phi") axes[1].plot(t_vec, x_ref_vec[:,2] * 360 / 2 / np.pi, "r--", linewidth=4, label="phi_ref") axes[1].set_ylabel("Angle (deg)") axes[2].plot(t_vec, u_vec[:, 0], label="u") axes[2].plot(t_vec, uref * np.ones(np.shape(t_vec)), "r--", linewidth=4, label="u_ref") axes[2].set_ylabel("Force (N)") for ax in axes: ax.grid(True) ax.legend() ``` ```python # Histogram of the MPC CPU time fig,ax = plt.subplots(1,1, figsize=(5,5)) ax.hist(t_MPC_CPU*1000, bins=100) ax.grid(True) _ = ax.set_xlabel('MPC computation CPU time (ms)') ```
{ "alphanum_fraction": 0.8836688743, "author": null, "avg_line_length": 172.6068181818, "converted": true, "ext": "ipynb", "file": null, "hexsha": "aedf2a233ebf9530189d0c12a9dfe3b0fa522d7b", "include": null, "lang": "Jupyter Notebook", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 20, "max_forks_repo_forks_event_max_datetime": "2022-03-31T08:38:25.000Z", "max_forks_repo_forks_event_min_datetime": "2019-10-13T13:50:16.000Z", "max_forks_repo_head_hexsha": "4b004ba707dab49cd36d96a3575b8593c870a904", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "passion4energy/pyMPC", "max_forks_repo_path": "examples/example_inverted_pendulum_kalman.ipynb", "max_issues_count": 2, "max_issues_repo_head_hexsha": "4b004ba707dab49cd36d96a3575b8593c870a904", "max_issues_repo_issues_event_max_datetime": "2021-01-30T11:35:58.000Z", "max_issues_repo_issues_event_min_datetime": "2020-04-17T00:03:27.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "passion4energy/pyMPC", "max_issues_repo_path": "examples/example_inverted_pendulum_kalman.ipynb", "max_line_length": 55396, "max_stars_count": 84, "max_stars_repo_head_hexsha": "291db149554767a035fcb01df3fed7a6b3fe60e4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "forgi86/pyMPC", "max_stars_repo_path": "examples/example_inverted_pendulum_kalman.ipynb", "max_stars_repo_stars_event_max_datetime": "2022-03-31T08:38:23.000Z", "max_stars_repo_stars_event_min_datetime": "2019-05-28T09:27:37.000Z", "num_tokens": 2925, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 75947 }
module DB using ...DBUtils using ..Entrez using SQLite using MySQL using DataStreams, DataFrames using NullableArrays export init_pubmed_db_mysql, init_pubmed_db_sqlite, get_value, all_pmids, get_article_mesh, db_insert! get_value{T}(val::Nullable{T}) = get(val) get_value(val)= val get_value{T}(val_array::Array{T}) = val_array get_value{T}(val_array::NullableArray{T, 1}) = val_array.values function init_pubmed_db_mysql(config) println("Initializing MySQL Database") #intput dictionary must have the following keys if haskey(config, :host) && haskey(config, :dbname) && haskey(config, :username) && haskey(config, :pswd) && haskey(config, :overwrite) mysql_code=nothing try filename = Pkg.dir() * "/BioMedQuery/src/Entrez/create_pubmed_db.sql" println(filename) f = open(filename, "r") mysql_code = readall(f) close(f) catch error("Could not read create_entrez_db.sql") end db = DBUtils.init_mysql_database(host = config[:host], dbname =config[:dbname], username = config[:username], pswd= config[:pswd], overwrite = config[:overwrite], mysql_code = mysql_code) return db end end function init_pubmed_db_sqlite(config) println("Initializing SQLite Database") if haskey(config, :db_path) && haskey(config, :overwrite) db = init_pubmed_db_sqlite(config[:db_path], config[:overwrite]) return db else println("Error with following configuration:") println(config) println("Must contain: db_path") error("Improper configuration for entrez_sqlite:init_database") end end # Creates a database with all necessary tables to store # Entrez related searches. All tables are empty at this point # If a database existis at the given path - an error is ruturned an the user # is asked whether he intended to clean the existing file function init_pubmed_db_sqlite(path::ASCIIString, overwrite=false) if isfile(path) if overwrite rm(path) else println("Database found. Returning existing database.") return SQLite.DB(path) end end #Create database file db = SQLite.DB(path) #Create tables to store SQLite.query(db, "CREATE TABLE article(pmid INTEGER NOT NULL PRIMARY KEY, title TEXT, pubYear INTEGER)") SQLite.query(db, "CREATE TABLE author(id INTEGER PRIMARY KEY AUTOINCREMENT, forename TEXT, lastname TEXT NOT NULL, CONSTRAINT unq UNIQUE(forename, lastname) )") SQLite.query(db, "CREATE TABLE author2article(aid INTEGER, pmid INTEGER, FOREIGN KEY(aid) REFERENCES author(id), FOREIGN KEY(pmid) REFERENCES article(pmid), PRIMARY KEY(aid, pmid) )") #-------------------------- # MeshHeading Tables #-------------------------- #Descriptor #The id corresponds to the DUI of mesh library #Adding a "D" at the beginning of the id, allows for #lookup in the mesh browerser # https://www.nlm.nih.gov/mesh/MBrowser.html SQLite.query(db, "CREATE TABLE mesh_descriptor(id INTEGER NOT NULL PRIMARY KEY , name TEXT UNIQUE )") #Qualifier SQLite.query(db, "CREATE TABLE mesh_qualifier(id INTEGER NOT NULL PRIMARY KEY , name TEXT UNIQUE )") #Heading SQLite.query(db, "CREATE TABLE mesh_heading(id INTEGER PRIMARY KEY AUTOINCREMENT, pmid INTEGER, did INTEGER, qid INTEGER, dmjr TEXT, qmjr TEXT, FOREIGN KEY(pmid) REFERENCES article(pmid), FOREIGN KEY(did) REFERENCES mesh_descriptor(id), FOREIGN KEY(qid) REFERENCES mesh_qualifier(id), CONSTRAINT unq UNIQUE(pmid, did, qid) )") return db end """ all_pmids(db) Return all PMIDs stored in the *article* table of the input database """ function all_pmids(db) query = db_query(db, "SELECT pmid FROM article;") return get_value(query[1]) end """ all_mesh(db) Return all PMIDs stored in the *article* table of the input database """ function all_mesh(db) query = db_query(db, "SELECT name FROM mesh_descriptor;") return get_value(query[1]) end """ get_article_mesh(db, pmid) Get the all mesh-descriptors associated with a give article """ function get_article_mesh(db, pmid::Integer) query_string = "SELECT md.name FROM mesh_heading as mh, mesh_descriptor as md WHERE mh.did = md.id AND mh.pmid = $pmid" query = db_query(db, query_string) #return data array return get_value(query.columns[1]) end function db_insert!(db, article::PubMedArticle, verbose=false) #------- PMID - TITLE - YEAR isnull(article.pmid) && error("NULL PMID") # Save article data insert_row!(db, "article", Dict(:pmid =>article.pmid.value, :title=>get(article.title, ""), :pubYear=>get(article.year, 0)), verbose) #------- AUTHORS for au in article.authors if isnull(au[:LastName]) println("Skipping author, null field: ", au) continue end author_id = insert_row!(db, "author", Dict(:id => nothing, :forename => get(au[:ForeName], "Unknown"), :lastname => get(au[:LastName], nothing)), verbose) if author_id < 0 sel = db_select(db, ["id"], "author", Dict(:forename => get(au[:ForeName], "Unknown"), :lastname => au[:LastName].value)) if length(sel[1]) > 0 author_id = get_value(sel[1][1]) if verbose println("Author already in db: ", au) end insert_row!(db, "author2article", Dict(:aid =>author_id, :pmid => article.pmid.value), verbose) else error("Can't save nor find Author: ", au) end end end end function db_insert!(db, pmid::Int64, mesh_heading_list::MeshHeadingList, verbose=false) for heading in mesh_heading_list did_int = heading.descriptor_id.value descriptor_name = heading.descriptor_name.value dmjr = get(heading.descriptor_mjr, nothing) #Save Descriptor insert_row!(db, "mesh_descriptor", Dict(:id=>did_int, :name=>descriptor_name), verbose) if isempty(heading.qualifier_id) #Save Headings insert_row!(db, "mesh_heading", Dict(:id=>nothing, :pmid=> pmid, :did=>did_int, :qid=>nothing, :dmjr=>nothing, :qmjr=>nothing), verbose ) else for i=1:length(heading.qualifier_id) qid_int = get(heading.qualifier_id[i], -1) qualifier_name = get(heading.qualifier_name[i], nothing) qmjr = get(heading.qualifier_mjr[i], nothing) #Save Qualifiers` insert_row!(db, "mesh_qualifier", Dict(:id=>qid_int, :name=>qualifier_name), verbose ) #Save Headings insert_row!(db, "mesh_heading", Dict(:id=>nothing, :pmid=> pmid, :did=>did_int, :qid=>qid_int, :dmjr=>dmjr, :qmjr=>qmjr), verbose ) end end end end end #module
{ "alphanum_fraction": 0.5884500065, "author": null, "avg_line_length": 29.6177606178, "converted": null, "ext": "jl", "file": null, "hexsha": "1f40e29772a7659204726702210b4073d820c5d5", "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": "a59fad12ef3be0d6fa9352133199cc991357aef4", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "JuliaPackageMirrors/BioMedQuery.jl", "max_forks_repo_path": "src/Entrez/entrez_db.jl", "max_issues_count": null, "max_issues_repo_head_hexsha": "a59fad12ef3be0d6fa9352133199cc991357aef4", "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": "JuliaPackageMirrors/BioMedQuery.jl", "max_issues_repo_path": "src/Entrez/entrez_db.jl", "max_line_length": 87, "max_stars_count": null, "max_stars_repo_head_hexsha": "a59fad12ef3be0d6fa9352133199cc991357aef4", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "JuliaPackageMirrors/BioMedQuery.jl", "max_stars_repo_path": "src/Entrez/entrez_db.jl", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 1762, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 7671 }
import numpy as np from numpy.linalg import lstsq from scipy.optimize import lsq_linear from . import moduleFrame class FitSignals(moduleFrame.Strategy): def __call__(self, signalVars, knownSpectra): # rows are additions, columns are contributors knownMask = ~np.isnan(knownSpectra[:, 0]) knownSignals = signalVars[:, knownMask] unknownSignals = signalVars[:, ~knownMask] knownSpectrum = knownSignals @ knownSpectra[knownMask, :] unknownSpectrum = self.titration.processedData - knownSpectrum fittedSignals, residuals, _, _ = lstsq( unknownSignals, unknownSpectrum, rcond=None ) fittedCurves = unknownSignals @ fittedSignals + knownSpectrum allSignals = knownSpectra.copy() allSignals[~knownMask, :] = fittedSignals return allSignals, residuals, fittedCurves class FitSignalsNonnegative(moduleFrame.Strategy): # TODO: account for known spectra def __call__(self, signalVars, knownSpectra): fittedSignals = np.empty((0, signalVars.shape[1])) residuals = np.empty((1, 0)) for signal in self.titration.processedData.T: result = lsq_linear(signalVars, signal, (0, np.inf), method="bvls") fittedSignals = np.vstack((fittedSignals, result.x)) residuals = np.append(residuals, result.cost) fittedSignals = fittedSignals.T fittedCurves = signalVars @ fittedSignals return fittedSignals, residuals, fittedCurves class ModuleFrame(moduleFrame.ModuleFrame): frameLabel = "Fit signals" dropdownLabelText = "Fit signals to curve using:" # TODO: add least squares with linear constraints dropdownOptions = { "Ordinary least squares": FitSignals, "Nonnegative least squares": FitSignalsNonnegative, } attributeName = "fitSignals"
{ "alphanum_fraction": 0.6898768077, "author": null, "avg_line_length": 38.1020408163, "converted": null, "ext": "py", "file": null, "hexsha": "24ba97b99cd37843fd8b359e53696bd9e75b0abb", "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-10T11:57:22.000Z", "max_forks_repo_forks_event_min_datetime": "2021-05-07T12:29:02.000Z", "max_forks_repo_head_hexsha": "bd67b2e7f4e1827c96d10bbf278c781ce22681f3", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "TChis/Musketeer", "max_forks_repo_path": "musketeer/fitSignals.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "bd67b2e7f4e1827c96d10bbf278c781ce22681f3", "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": "TChis/Musketeer", "max_issues_repo_path": "musketeer/fitSignals.py", "max_line_length": 79, "max_stars_count": null, "max_stars_repo_head_hexsha": "bd67b2e7f4e1827c96d10bbf278c781ce22681f3", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "TChis/Musketeer", "max_stars_repo_path": "musketeer/fitSignals.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 430, "path": null, "reason": "import numpy,from numpy,from scipy", "repo": null, "save_path": null, "sha": null, "size": 1867 }
""" NCalculus Numerical Differentiation and Integration Module. """ module NCalculus const GaussianRoots = [0.5773502692,-0.5773502692, 0.7745966692,0.0,-0.7745966692, 0.8611363116,0.3399810436,-0.3399810436,-0.8611363116, 0.9061798459,0.5384693101,0.0,-0.5384693101,-0.9061798459] const GaussianCoef = [1.0,1.0, 0.5555555556,0.8888888889,0.5555555556, 0.3478548451,0.6521451549,0.6521451549,0.3478548451, 0.2369268850,0.4786286705,0.5688888889,0.4786286705,0.2369268850] """ ThreePoint(f::Function, x₀::Real, h::Real; method::String="Endpoint") input a function `f`, x₀ and h.Args is method (default: "Endpoint", if you set method is't "Endpoint", it will return MidPoint ans.) """ @inline function ThreePoint(f::Function, x₀::Real, h::Real; method::String="Endpoint") if method == "Endpoint" return 1/h*(-3/2*f(x₀) + 2*f(x₀+h)- 1/2*f(x₀+2*h)) else return 1/(2*h) * (f(x₀+h) - f(x₀- h)) end end """ FivePoint(f::Function, x₀::Real, h::Real; method::String="Endpoint") input a function `f`, x₀ and h.Args is method (default: "Endpoint", if you set method is't "Endpoint", it will return MidPoint ans.) """ @inline function FivePoint(f::Function, x₀::Real, h::Real; method::String="Endpoint") if method == "Endpoint" return 1/(12*h)*(-25*f(x₀)+48f(x₀ +h)-36f(x₀+2h)+16f(x₀+3h)-3f(x₀+4h)) else return 1/(12*h) * (f(x₀ - 2h) - 8f(x₀ -h)+8f(x₀+h)-f(x₀ + 2h)) end end """ Trapezoidal(f::function, a::Real, b::Real) input a function `f`, and ``x in [a, b]`` calculate ∫f(x)dx. """ @inline function Trapezoidal(f::Function, a::Real, b::Real) return (b-a)/2 * (f(a) + f(b)) end """ Simpson(f::Function, a::Real, b::Real) input a function `f`, and ``x in [a, b]`` calculate ∫f(x)dx. """ @inline function Simpson(f::Function, a::Real, b::Real) return (b-a)/6 * (f(a) + 4*f(a+(b-a)/2) + f(b)) end """ Newton_Cotes(f::Function, a::Real, b::Real; n::Int=0, method::String="Midpoint") input a function `f`, and ``x in [a, b]``` calculate ``int_a^b f(x)dx``. args ``n∈[1,4]`` """ @inline function Newton_cotes(f::Function, a::Real, b::Real; n::Int=0, method::String="Midpoint") if method == "Open" o1 = (b-a)/2 * (f(a) + f(b)) o2 = (b-a)/6 * (f(a) + 4*f(a+(b-a)/2) + f(b)) o3 = 3*(b-a)/24 * (f(a) + 3*f(a+(b-a)/3) + 3*f(a+2*(b-a)/3) + f(b)) o4 = 2*(b-a)/180 * (7*f(a) + 32*f(a+(b-a)/4) + 12*f(a+(b-a)/2) + 32*f(a + 3*(b-a)/4) + 7*f(b)) o = [o1, o2, o3, o4] if 0<n≤4 return o[n] else return o end else c1 = 2 * (b-a)/2 * f((b+a)/2) c2 = 3/2 * (b-a)/3 * (f((b-a)/3) + f(2*(b-a)/3)) c3 = 4/3 * (b-a)/4 * (2*f((b-a)/4) - f((b-a)/2) + 2*f(3*(b-a)/4)) c4 = 5/24 * (b-a)/5 * (11*f((b-a)/5)+f(2*(b-a)/5)+f(3*(b-a)/5)+11f(4*(b-a)/5)) c = [c1, c2, c3, c4] if 0<n≤4 return c[n] else return c end end end """ Romberg(f::Function, a::Real, b::Real, n::Int; seq_tab::Bool=false) input a function `f`, and ``x in [a, b]``, set `n`.if Args `seq_tab=true`, will return a table, else return a value. """ @inline function Romberg(f::Function, a::Real, b::Real, n::Int; seq_tab::Bool=false) h = (b-a) result = zeros(n,n) result[1,1] = (f(a)+f(b))*h/2 for i = 2:n w = f(a)+f(b) for j = 1:(2^(i-1)-1) w = w + 2*f(a+j*(h/2^(i-1))) end result[i,1] = w*(h/2^i) end for i = 2:n for j = i:n result[j,i] = result[j,i-1]+(1/(4^(i-1)-1))*(result[j,i-1]-result[j-1,i-1]) end end if seq_tab return result else return result[n,n] end end """ Gaussian_Quad(f::Function; n::Int=3, a::Real=-1, b::Real=1) Gaussian Quadrature must set `n<6`,default calculate `int f(x)dx` in `[-1,1]`. you can set interval `[a, b]` to change default interval. """ @inline function Gaussian_Quad(f::Function;n::Int=3,a::Real=-1, b::Real=1) #Gaussian Args #Root = [0.5773502692,-0.5773502692, # 0.7745966692,0.0,-0.7745966692, # 0.8611363116,0.3399810436,-0.3399810436,-0.8611363116, # 0.9061798459,0.5384693101,0.0,-0.5384693101,-0.9061798459] #Coef = [1.0,1.0, # 0.5555555556,0.8888888889,0.5555555556, # 0.3478548451,0.6521451549,0.6521451549,0.3478548451, # 0.2369268850,0.4786286705,0.5688888889,0.4786286705,0.2369268850] if a == -1 && b == 1 return GaussianCoef[sum(1:n-1):sum(1:n-1)+n-1]' * f.(GaussianRoots[sum(1:n-1):sum(1:n-1)+n-1]) else return GaussianCoef[sum(1:n-1):sum(1:n-1)+n-1]' * (b-a)/2 * f.((b-a)/2 .* GaussianRoots[sum(1:n-1):sum(1:n-1)+n-1] .+ (b+a)/2) end end """ MutipleIntegralSimple(f::Function, interval_x::Tuple, interval_y::Tuple) It will apply the **Composite Trapezoidal rule** to approximate the integral. """ @inline function MutipleIntegralSimple(f::Function, interval_x::Tuple, interval_y::Tuple) a, b = interval_x c, d = interval_y return (b-a)*(d-c)/16 * (f(a,c) + f(a,d) +f(b,c) + f(b,d) + 2*(f((a+b)/2,c) + f((a+b)/2, d) + f(a, (c+d)/2) + f(b, (c+d)/2)) + 4*f((a+b)/2, (c+d)/2)) end """ SimpsonDoubleIntegral(f::Function, interval_x::Tuple, y_up::Function, y_down::Function; n::Int =6, m::Int=6) ``f = f(x, y), x ∈ interval_x, y = yup(x) - ydown(x)``, Args m and n is Separation distance. """ @inline function SimpsonDoubleIntegral(f::Function, interval_x::Tuple, y_up::Function, y_down::Function; n::Int =6, m::Int=6) a, b = interval_x h = (b - a) / n J₁, J₂, J₃ = zeros(3) for i = 0:n x = a + i * h HX = (y_up(x) - y_down(x)) / m K₁ = f(x, y_down(x)) + f(x, y_up(x)) K₂, K₃ = 0, 0 for j = 1:m-1 y = y_down(x) + j*HX Q = f(x, y) if iseven(j) K₂+= Q else K₃+= Q end end L = (K₁ + 2*K₂ + 4*K₃)*HX/3 if i == 0 || i == n J₁ = J₁ + L elseif iseven(i) J₂+= L else J₃+= L end end return h*(J₁+2J₂+4J₃)/3 end """ GaussianDoubleIntegral(f::Function, interval_x::Tuple, y_up::Function, y_down::Function, m::Int=5, n::Int=5) ``f = f(x, y), x ∈ interval_x, y = yup(x) - ydown(x)``, Args m and n is Separation distance. """ @inline function GaussianDoubleIntegral(f::Function, interval_x::Tuple, y_up::Function, y_down::Function; m::Int=5, n::Int=5) m, n = min(5, m), min(5, n) a, b = interval_x h₁ = (b - a) / 2 h₂ = (b + a) / 2 J = 0 for i in 1:m JX = 0 x = h₁ * GaussianRoots[sum(1:m-1)+i-1] + h₂ d₁ = y_up(x) c₁ = y_down(x) k₁ = (d₁ - c₁)/2 k₂ = (d₁ + c₁)/2 for j = 1:n y = k₁ * GaussianRoots[sum(1:n-1)+j-1] + k₂ Q = f(x, y) JX += GaussianCoef[sum(1:n-1)+j-1] * Q end J += GaussianCoef[sum(1:m-1)+i-1] * k₁ * JX end return h₁*J end end
{ "alphanum_fraction": 0.5332202431, "author": null, "avg_line_length": 31.0263157895, "converted": null, "ext": "jl", "file": null, "hexsha": "5b90b892bf4204bad7ffee546d68cec06e8aaa6d", "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": "1e4926d6968fa72cc6ba102ad04052a77044351a", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "ZhouZhuofei/NumericalAnalysis.jl", "max_forks_repo_path": "src/NCalculus.jl", "max_issues_count": 11, "max_issues_repo_head_hexsha": "1e4926d6968fa72cc6ba102ad04052a77044351a", "max_issues_repo_issues_event_max_datetime": "2020-12-11T00:37:24.000Z", "max_issues_repo_issues_event_min_datetime": "2020-09-24T17:58:58.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "ZhouZhuofei/NumericalAnalysis.jl", "max_issues_repo_path": "src/NCalculus.jl", "max_line_length": 136, "max_stars_count": null, "max_stars_repo_head_hexsha": "1e4926d6968fa72cc6ba102ad04052a77044351a", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "ZhouZhuofei/NumericalAnalysis.jl", "max_stars_repo_path": "src/NCalculus.jl", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 2839, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 7074 }
""" Scenario reduction algorithm for two-stage stochastic programmings The fast forward selection algorithm is used. References: [1]https://edoc.hu-berlin.de/bitstream/handle/18452/3285/8.pdf?sequence=1 [2]http://ftp.gamsworld.org/presentations/present_IEEE03.pdf Considering the second stage optimization problem is linear programming, the distance function is refined to c(ξ, ˜ξ) := max{1, kξkp−1, k˜ξkp−1}kξ − ˜ξk (p = 2, which is sufficient for right hand side uncertainties) """ from numpy import array, zeros, argmin, random, arange, linalg, ones, inf, delete, where, append class ScenarioReduction(): def __init__(self): self.name = "Scenario reduction" def run(self, scenario, weight, n_reduced, power): """ :param scenario: A fan scenario tree, when more stage are considered, some merge operation can be implemented :param weight: Weight of each scenario :param n_reduced: Number of scenarios needs to be reduced :param power: The power in the distance calculation :return: """ n_scenario = scenario.shape[0] # number of original scenarios c = zeros((n_scenario, n_scenario)) # Calculate the c matrix for i in range(n_scenario): for j in range(i+1): c[i, j] = linalg.norm((scenario[i, :] - scenario[j, :]), 2) c[i, j] = max([1, linalg.norm(scenario[i, :], power - 1), linalg.norm(scenario[j, :], power - 1)]) * \ c[i, j] c += c.transpose() J = arange(n_scenario) # The original index range J_reduced = array([]) # Implement the iteration for n in range(n_reduced): # find the minimal distance c_n = inf * ones(n_scenario) c_n[J] = 0 for u in J: # Delete the i-th distance J_temp = delete(J, where(J == u)) for k in J_temp: c_k_j = delete(c[int(k)], J_temp) c_n[int(u)] += weight[int(k)] * min(c_k_j) u_i = argmin(c_n) J_reduced = append(J_reduced, u_i) J = delete(J, where(J == u_i)) # Optimal redistribution p_s = weight.copy() p_s[J_reduced.astype(int)] = 0 for i in J_reduced: c_temp = c[int(i), :] c_temp[J_reduced.astype(int)] = inf index = argmin(c_temp) p_s[index] += weight[int(i)] scenario_reduced = scenario[J.astype(int), :] weight_reduced = p_s[J.astype(int)] return scenario_reduced, weight_reduced if __name__ == "__main__": n_scenario = 200 scenario = random.random((n_scenario, 10)) weight = ones(n_scenario) / n_scenario n_reduced = int(n_scenario / 2) power = 2 scenario_reduction = ScenarioReduction() (scenario_reduced, weight_reduced) = scenario_reduction.run(scenario=scenario, weight=weight, n_reduced=n_reduced, power=power) print(scenario_reduced)
{ "alphanum_fraction": 0.5913071683, "author": null, "avg_line_length": 37.5975609756, "converted": null, "ext": "py", "file": null, "hexsha": "0002bfa6f14c133e57f485c1d1e2a95f355a3f54", "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": "1ea824941fe87528622ec7aa8148024752a3947c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "Matrixeigs/EnergyManagementSourceCodes", "max_forks_repo_path": "solvers/scenario_reduction.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "1ea824941fe87528622ec7aa8148024752a3947c", "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": "Matrixeigs/EnergyManagementSourceCodes", "max_issues_repo_path": "solvers/scenario_reduction.py", "max_line_length": 118, "max_stars_count": 3, "max_stars_repo_head_hexsha": "1ea824941fe87528622ec7aa8148024752a3947c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "Matrixeigs/EnergyManagementSourceCodes", "max_stars_repo_path": "solvers/scenario_reduction.py", "max_stars_repo_stars_event_max_datetime": "2022-02-17T11:30:52.000Z", "max_stars_repo_stars_event_min_datetime": "2021-10-21T07:28:38.000Z", "num_tokens": 777, "path": null, "reason": "from numpy", "repo": null, "save_path": null, "sha": null, "size": 3083 }
import os from utils import read_pickle import numpy as np import pandas as pd from library.feature_engineering import encode_source_labels, clean_text_label, create_position_feature, make_c100_features from utils import duplicates_in_list from library.make_estimated_conc import (maximum_match_probability, conc_flood_fill_com, conc_from_decision_boundary, conc_flood_fill_max_prob) # Switches model_version = 'model_2022-03-21_w3107_s4114_l4' feature_meta_version = 'feature_meta_2022-03-21_w3107' target_label_file = 'MEX_labels_259' decision_boundary = 0.85 print('Predicting ' + target_label_file + ' HSCPC matches') # Constants n_root = 6357 # Paths work_dir = os.environ['work_dir'] + '/' model_dir = work_dir + 'model/' prediction_dir = work_dir + 'predictions/' label_dir = work_dir + 'input_labels/' # Extract target labels df = pd.read_excel(label_dir + target_label_file + '.xlsx', header=None) source_labels = df[0].values.tolist() x_labels = [] for i, r in enumerate(source_labels): row_label = clean_text_label(r) x_labels.append(row_label) print('Extracted ' + str(len(x_labels)) + ' source labels') assert not duplicates_in_list(x_labels) # Load HSCPC labels df = pd.read_excel(work_dir + 'hscpc/hscpc_labels.xlsx', header=0) target_labels = df['Labels'].values assert not duplicates_in_list(x_labels) # Load feature meta feature_meta_fname = work_dir + 'model/' + feature_meta_version + '.pkl' feature_meta = read_pickle(feature_meta_fname) tokenizer = feature_meta['tokenizer'] max_words = feature_meta['max_words'] # One-hot-encode x labels x_features_encoded = encode_source_labels(tokenizer, x_labels, max_words) # Add label position feature if feature_meta['add_position_features']: position_feature = create_position_feature(x_labels) x_features_encoded = np.hstack((x_features_encoded, np.array(position_feature).reshape(-1, 1))) # C100 features if feature_meta['add_isic_100_features']: c100_labels = pd.read_excel(work_dir + 'hscpc/c100_labels.xlsx')['sector'].to_list() new_features = make_c100_features(x_labels, c100_labels) x_features_encoded = np.hstack((x_features_encoded, new_features)) # Load predictive model model_fname = model_dir + model_version + '.pkl' model = read_pickle(model_fname) # Make prediction source_name = target_label_file.replace('_labels', '') preds = model.predict(x_features_encoded) print('Saving concordance predictions') fname_prefix = prediction_dir + 'challenger_deep_predict_' + source_name # Save raw estimates conc_raw_estimates = pd.DataFrame(preds, index=x_labels, columns=target_labels) conc_raw_estimates.to_excel(fname_prefix + '_raw' + '.xlsx') # Save estimates, filtered by decision boundary conc_filtered = conc_from_decision_boundary(conc_raw_estimates.copy(), decision_boundary=decision_boundary) conc_filtered.to_excel(fname_prefix + '_conc_thresholded_' + str(decision_boundary) + '.xlsx') # Center of mass conc_com = conc_flood_fill_com(conc_raw_estimates.copy()) conc_com.to_excel(fname_prefix + '_conc_flood_fill_com' + '.xlsx') # Set binary values based on the maximum probability in each row conc_max_prob = maximum_match_probability(conc_raw_estimates.copy()) conc_max_prob.to_excel(fname_prefix + '_conc_max_prob' + '.xlsx') # Center of mass conc_com = conc_flood_fill_max_prob(conc_raw_estimates.copy()) conc_com.to_excel(fname_prefix + '_conc_flood_fill_max_prob' + '.xlsx') print('Finished writing predictons to ' + prediction_dir)
{ "alphanum_fraction": 0.7845759818, "author": null, "avg_line_length": 35.4949494949, "converted": null, "ext": "py", "file": null, "hexsha": "b6c13de481d74048e542fa9c39cafa09d6f2bfb0", "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": "96fcc1b88c041554917ebbad4a4062055131c33c", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "spottedquoll/challenger_deep", "max_forks_repo_path": "predict_hscpc_labels.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "96fcc1b88c041554917ebbad4a4062055131c33c", "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": "spottedquoll/challenger_deep", "max_issues_repo_path": "predict_hscpc_labels.py", "max_line_length": 123, "max_stars_count": null, "max_stars_repo_head_hexsha": "96fcc1b88c041554917ebbad4a4062055131c33c", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "spottedquoll/challenger_deep", "max_stars_repo_path": "predict_hscpc_labels.py", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 833, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 3514 }
# This file was generated by the Julia Swagger Code Generator # Do not modify this file directly. Modify the swagger specification instead. @doc raw"""CustomResourceSubresourceStatus defines how to serve the status subresource for CustomResources. Status is represented by the &#x60;.status&#x60; JSON path inside of a CustomResource. When set, * exposes a /status subresource for the custom resource * PUT requests to the /status subresource take a custom resource object, and ignore changes to anything except the status stanza * PUT/POST/PATCH requests to the custom resource ignore changes to the status stanza IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus(; ) """ mutable struct IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus <: SwaggerModel function IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus(;) o = new() o end end # type IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus const _property_map_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus = Dict{Symbol,Symbol}() const _property_types_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus = Dict{Symbol,String}() Base.propertynames(::Type{ IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus }) = collect(keys(_property_map_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus)) Swagger.property_type(::Type{ IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus }, name::Symbol) = Union{Nothing,eval(Base.Meta.parse(_property_types_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus[name]))} Swagger.field_name(::Type{ IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus }, property_name::Symbol) = _property_map_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus[property_name] function check_required(o::IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus) true end function validate_property(::Type{ IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus }, name::Symbol, val) end
{ "alphanum_fraction": 0.8720637584, "author": null, "avg_line_length": 76.9032258065, "converted": null, "ext": "jl", "file": null, "hexsha": "e67d63db29058ff9c611af4d0bf71abee90170dd", "include": null, "lang": "Julia", "length": null, "llama_tokens": null, "mathlib_filename": null, "max_forks_count": 10, "max_forks_repo_forks_event_max_datetime": "2022-03-12T17:43:32.000Z", "max_forks_repo_forks_event_min_datetime": "2019-12-19T12:02:37.000Z", "max_forks_repo_head_hexsha": "0834cab05d2b5733cb365594000be16f54345ddb", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "memetics19/Kuber.jl", "max_forks_repo_path": "src/ApiImpl/api/model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus.jl", "max_issues_count": 15, "max_issues_repo_head_hexsha": "0834cab05d2b5733cb365594000be16f54345ddb", "max_issues_repo_issues_event_max_datetime": "2022-03-23T11:15:26.000Z", "max_issues_repo_issues_event_min_datetime": "2019-03-14T03:51:01.000Z", "max_issues_repo_licenses": [ "MIT" ], "max_issues_repo_name": "memetics19/Kuber.jl", "max_issues_repo_path": "src/ApiImpl/api/model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus.jl", "max_line_length": 474, "max_stars_count": 47, "max_stars_repo_head_hexsha": "0834cab05d2b5733cb365594000be16f54345ddb", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "memetics19/Kuber.jl", "max_stars_repo_path": "src/ApiImpl/api/model_IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceSubresourceStatus.jl", "max_stars_repo_stars_event_max_datetime": "2022-02-16T20:19:11.000Z", "max_stars_repo_stars_event_min_datetime": "2018-12-13T13:17:40.000Z", "num_tokens": 576, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 2384 }
#' Create an SQL tbl (abstract) #' #' Generally, you should no longer need to provide a custom `tbl()` #' method you you can default `tbl.DBIConnect` method. #' #' @keywords internal #' @export #' @param subclass name of subclass #' @param ... needed for agreement with generic. Not otherwise used. #' @param vars DEPRECATED tbl_sql <- function(subclass, src, from, ..., vars = NULL) { # If not literal sql, must be a table identifier from <- as.sql(from) if (!missing(vars)) { warning("`vars` argument is deprecated as it is no longer needed", call. = FALSE) } vars <- vars %||% db_query_fields(src$con, from) ops <- op_base_remote(from, vars) make_tbl(c(subclass, "sql", "lazy"), src = src, ops = ops) } #' @export same_src.tbl_sql <- function(x, y) { if (!inherits(y, "tbl_sql")) return(FALSE) same_src(x$src, y$src) } # Grouping methods ------------------------------------------------------------- #' @export group_size.tbl_sql <- function(x) { df <- x %>% summarise(n = n()) %>% collect() df$n } #' @export n_groups.tbl_sql <- function(x) { if (length(groups(x)) == 0) return(1L) df <- x %>% summarise() %>% ungroup() %>% summarise(n = n()) %>% collect() df$n } # Standard data frame methods -------------------------------------------------- #' @export as.data.frame.tbl_sql <- function(x, row.names = NULL, optional = NULL, ..., n = Inf) { as.data.frame(collect(x, n = n)) } #' @export tbl_sum.tbl_sql <- function(x) { grps <- op_grps(x$ops) sort <- op_sort(x$ops) c( "Source" = tbl_desc(x), "Database" = db_desc(x$src$con), if (length(grps) > 0) c("Groups" = commas(grps)), if (length(sort) > 0) c("Ordered by" = commas(deparse_all(sort))) ) } #' @export pull.tbl_sql <- function(.data, var = -1) { expr <- enquo(var) var <- dplyr:::find_var(expr, tbl_vars(.data)) .data <- ungroup(.data) .data <- select(.data, !! sym(var)) .data <- collect(.data) .data[[1]] } #' @export dimnames.tbl_sql <- function(x) { list(NULL, op_vars(x$ops)) } #' @export dim.tbl_sql <- function(x) { c(NA, length(op_vars(x$ops))) } #' @export tail.tbl_sql <- function(x, n = 6L, ...) { stop("tail() is not supported by sql sources", call. = FALSE) } # Joins ------------------------------------------------------------------------ #' Join sql tbls. #' #' See [join] for a description of the general purpose of the #' functions. #' #' @section Implementation notes: #' #' Semi-joins are implemented using `WHERE EXISTS`, and anti-joins with #' `WHERE NOT EXISTS`. Support for semi-joins is somewhat partial: you #' can only create semi joins where the `x` and `y` columns are #' compared with `=` not with more general operators. #' #' @inheritParams dplyr::join #' @param copy If `x` and `y` are not from the same data source, #' and `copy` is `TRUE`, then `y` will be copied into a #' temporary table in same database as `x`. `*_join()` will automatically #' run `ANALYZE` on the created table in the hope that this will make #' you queries as efficient as possible by giving more data to the query #' planner. #' #' This allows you to join tables across srcs, but it's potentially expensive #' operation so you must opt into it. #' @param auto_index if `copy` is `TRUE`, automatically create #' indices for the variables in `by`. This may speed up the join if #' there are matching indexes in `x`. #' @examples #' \dontrun{ #' library(dplyr) #' if (has_lahman("sqlite")) { #' #' # Left joins ---------------------------------------------------------------- #' lahman_s <- lahman_sqlite() #' batting <- tbl(lahman_s, "Batting") #' team_info <- select(tbl(lahman_s, "Teams"), yearID, lgID, teamID, G, R:H) #' #' # Combine player and whole team statistics #' first_stint <- select(filter(batting, stint == 1), playerID:H) #' both <- left_join(first_stint, team_info, type = "inner", by = c("yearID", "teamID", "lgID")) #' head(both) #' explain(both) #' #' # Join with a local data frame #' grid <- expand.grid( #' teamID = c("WAS", "ATL", "PHI", "NYA"), #' yearID = 2010:2012) #' top4a <- left_join(batting, grid, copy = TRUE) #' explain(top4a) #' #' # Indices don't really help here because there's no matching index on #' # batting #' top4b <- left_join(batting, grid, copy = TRUE, auto_index = TRUE) #' explain(top4b) #' #' # Semi-joins ---------------------------------------------------------------- #' #' people <- tbl(lahman_s, "Master") #' #' # All people in half of fame #' hof <- tbl(lahman_s, "HallOfFame") #' semi_join(people, hof) #' #' # All people not in the hall of fame #' anti_join(people, hof) #' #' # Find all managers #' manager <- tbl(lahman_s, "Managers") #' semi_join(people, manager) #' #' # Find all managers in hall of fame #' famous_manager <- semi_join(semi_join(people, manager), hof) #' famous_manager #' explain(famous_manager) #' #' # Anti-joins ---------------------------------------------------------------- #' #' # batters without person covariates #' anti_join(batting, people) #' } #' } #' @name join.tbl_sql NULL #' @rdname join.tbl_sql #' @export inner_join.tbl_lazy <- function(x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), auto_index = FALSE, ...) { add_op_join( x, y, "inner", by = by, copy = copy, suffix = suffix, auto_index = auto_index, ... ) } #' @rdname join.tbl_sql #' @export left_join.tbl_lazy <- function(x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), auto_index = FALSE, ...) { add_op_join( x, y, "left", by = by, copy = copy, suffix = suffix, auto_index = auto_index, ... ) } #' @rdname join.tbl_sql #' @export right_join.tbl_lazy <- function(x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), auto_index = FALSE, ...) { add_op_join( x, y, "right", by = by, copy = copy, suffix = suffix, auto_index = auto_index, ... ) } #' @rdname join.tbl_sql #' @export full_join.tbl_lazy <- function(x, y, by = NULL, copy = FALSE, suffix = c(".x", ".y"), auto_index = FALSE, ...) { add_op_join( x, y, "full", by = by, copy = copy, suffix = suffix, auto_index = auto_index, ... ) } #' @rdname join.tbl_sql #' @export semi_join.tbl_lazy <- function(x, y, by = NULL, copy = FALSE, auto_index = FALSE, ...) { add_op_semi_join( x, y, anti = FALSE, by = by, copy = copy, auto_index = auto_index, ... ) } #' @rdname join.tbl_sql #' @export anti_join.tbl_lazy <- function(x, y, by = NULL, copy = FALSE, auto_index = FALSE, ...) { add_op_semi_join( x, y, anti = TRUE, by = by, copy = copy, auto_index = auto_index, ... ) } # Set operations --------------------------------------------------------------- # registered onLoad intersect.tbl_lazy <- function(x, y, copy = FALSE, ...) { add_op_set_op(x, y, "INTERSECT", copy = copy, ...) } # registered onLoad union.tbl_lazy <- function(x, y, copy = FALSE, ...) { add_op_set_op(x, y, "UNION", copy = copy, ...) } #' @export union_all.tbl_lazy <- function(x, y, copy = FALSE, ...) { add_op_set_op(x, y, "UNION ALL", copy = copy, ...) } # registered onLoad setdiff.tbl_lazy <- function(x, y, copy = FALSE, ...) { add_op_set_op(x, y, "EXCEPT", copy = copy, ...) } # Copying ---------------------------------------------------------------------- #' @export auto_copy.tbl_sql <- function(x, y, copy = FALSE, ...) { copy_to(x$src, as.data.frame(y), random_table_name(), ...) } #' Copy a local data frame to a DBI backend. #' #' This [copy_to()] method works for all DBI sources. It is useful for #' copying small amounts of data to a database for examples, experiments, #' and joins. By default, it creates temporary tables which are typically #' only visible to the current connection to the database. #' #' @export #' @param df A local data frame, a `tbl_sql` from same source, or a `tbl_sql` #' from another source. If from another source, all data must transition #' through R in one pass, so it is only suitable for transferring small #' amounts of data. #' @param types a character vector giving variable types to use for the columns. #' See \url{http://www.sqlite.org/datatype3.html} for available types. #' @param temporary if `TRUE`, will create a temporary table that is #' local to this connection and will be automatically deleted when the #' connection expires #' @param unique_indexes a list of character vectors. Each element of the list #' will create a new unique index over the specified column(s). Duplicate rows #' will result in failure. #' @param indexes a list of character vectors. Each element of the list #' will create a new index. #' @param analyze if `TRUE` (the default), will automatically ANALYZE the #' new table so that the query optimiser has useful information. #' @inheritParams dplyr::copy_to #' @return A [tbl()] object (invisibly). #' @examples #' library(dplyr) #' set.seed(1014) #' #' mtcars$model <- rownames(mtcars) #' mtcars2 <- src_memdb() %>% #' copy_to(mtcars, indexes = list("model"), overwrite = TRUE) #' mtcars2 %>% filter(model == "Hornet 4 Drive") #' #' cyl8 <- mtcars2 %>% filter(cyl == 8) #' cyl8_cached <- copy_to(src_memdb(), cyl8) #' #' # copy_to is called automatically if you set copy = TRUE #' # in the join functions #' df <- tibble(cyl = c(6, 8)) #' mtcars2 %>% semi_join(df, copy = TRUE) copy_to.src_sql <- function(dest, df, name = deparse(substitute(df)), overwrite = FALSE, types = NULL, temporary = TRUE, unique_indexes = NULL, indexes = NULL, analyze = TRUE, ...) { assert_that(is_string(name), is.flag(temporary)) if (!is.data.frame(df) && !inherits(df, "tbl_sql")) { stop("`df` must be a local dataframe or a remote tbl_sql", call. = FALSE) } if (inherits(df, "tbl_sql") && same_src(df$src, dest)) { out <- compute(df, name = name, temporary = temporary, unique_indexes = unique_indexes, indexes = indexes, analyze = analyze, ... ) } else { df <- collect(df) class(df) <- "data.frame" # avoid S4 dispatch problem in dbSendPreparedQuery name <- db_copy_to(dest$con, name, df, overwrite = overwrite, types = types, temporary = temporary, unique_indexes = unique_indexes, indexes = indexes, analyze = analyze, ... ) out <- tbl(dest, name) } invisible(out) } #' @export collapse.tbl_sql <- function(x, vars = NULL, ...) { sql <- db_sql_render(x$src$con, x) tbl(x$src, sql) %>% group_by(!!! syms(op_grps(x))) %>% add_op_order(op_sort(x)) } #' @export compute.tbl_sql <- function(x, name = random_table_name(), temporary = TRUE, unique_indexes = list(), indexes = list(), analyze = TRUE, ...) { vars <- op_vars(x) assert_that(all(unlist(indexes) %in% vars)) assert_that(all(unlist(unique_indexes) %in% vars)) x_aliased <- select(x, !!! syms(vars)) # avoids problems with SQLite quoting (#1754) sql <- db_sql_render(x$src$con, x_aliased$ops) name <- db_compute(x$src$con, name, sql, temporary = temporary, unique_indexes = unique_indexes, indexes = indexes, analyze = analyze, ... ) tbl(x$src, name) %>% group_by(!!! syms(op_grps(x))) %>% add_op_order(op_sort(x)) } #' @export collect.tbl_sql <- function(x, ..., n = Inf, warn_incomplete = TRUE) { assert_that(length(n) == 1, n > 0L) if (n == Inf) { n <- -1 } else { # Gives the query planner information that it might be able to take # advantage of x <- head(x, n) } sql <- db_sql_render(x$src$con, x) out <- db_collect(x$src$con, sql, n = n, warn_incomplete = warn_incomplete) grouped_df(out, intersect(op_grps(x), names(out))) }
{ "alphanum_fraction": 0.5793397231, "author": null, "avg_line_length": 28.1267281106, "converted": null, "ext": "r", "file": null, "hexsha": "b659933c5fc789264f2ac6dda0507e57912fee47", "include": null, "lang": "R", "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": "ce9273eac8cdd451605efbadd2aedbca93ba04e0", "max_forks_repo_licenses": [ "MIT" ], "max_forks_repo_name": "tdsmith/dbplyr", "max_forks_repo_path": "R/tbl-sql.r", "max_issues_count": null, "max_issues_repo_head_hexsha": "ce9273eac8cdd451605efbadd2aedbca93ba04e0", "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": "tdsmith/dbplyr", "max_issues_repo_path": "R/tbl-sql.r", "max_line_length": 96, "max_stars_count": null, "max_stars_repo_head_hexsha": "ce9273eac8cdd451605efbadd2aedbca93ba04e0", "max_stars_repo_licenses": [ "MIT" ], "max_stars_repo_name": "tdsmith/dbplyr", "max_stars_repo_path": "R/tbl-sql.r", "max_stars_repo_stars_event_max_datetime": null, "max_stars_repo_stars_event_min_datetime": null, "num_tokens": 3282, "path": null, "reason": null, "repo": null, "save_path": null, "sha": null, "size": 12207 }
import numpy as np from .base import LightningModuleBase class LightningModuleSpecMixUp(LightningModuleBase): def training_step(self, batch, batch_nb): x, y = batch["x"], batch["y"] aux_x = {k: v for k, v in batch.items() if (k != "x") and (k[0] == "x")} aux_y = {k: v for k, v in batch.items() if (k != "y") and (k[0] == "y")} if self.transform is not None: x = self.transform(x) if ( (self.strong_transform is not None) and (self.max_epochs is not None) and ( self.current_epoch <= self.max_epochs - self.disable_strong_transform_in_last_epochs ) and (np.random.rand() < self.storong_transform_p) ): _, y_a, y_b, lam, idx = self.strong_transform(x, y) y_hat = self.forward(x, mixup_lambda=lam, mixup_index=idx, **aux_x) loss = lam * self.hooks.loss_fn(y_hat, y_a, **aux_y) + ( 1 - lam ) * self.hooks.loss_fn(y_hat, y_b, **aux_y) else: y_hat = self.forward(x, **aux_x) loss = self.hooks.loss_fn(y_hat, y, **aux_y) return {"loss": loss}
{ "alphanum_fraction": 0.5386533666, "author": null, "avg_line_length": 35.3823529412, "converted": null, "ext": "py", "file": null, "hexsha": "77e996c05a432a276f21abeb1663245a4a622de5", "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": "d7cf7b39e3164a75547ee50cc9a29bd5ed4c29bd", "max_forks_repo_licenses": [ "BSD-2-Clause" ], "max_forks_repo_name": "Ynakatsuka/birdclef-2021", "max_forks_repo_path": "src/kvt/lightning_modules/spec.py", "max_issues_count": null, "max_issues_repo_head_hexsha": "d7cf7b39e3164a75547ee50cc9a29bd5ed4c29bd", "max_issues_repo_issues_event_max_datetime": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_licenses": [ "BSD-2-Clause" ], "max_issues_repo_name": "Ynakatsuka/birdclef-2021", "max_issues_repo_path": "src/kvt/lightning_modules/spec.py", "max_line_length": 81, "max_stars_count": 6, "max_stars_repo_head_hexsha": "d7cf7b39e3164a75547ee50cc9a29bd5ed4c29bd", "max_stars_repo_licenses": [ "BSD-2-Clause" ], "max_stars_repo_name": "Ynakatsuka/birdclef-2021", "max_stars_repo_path": "src/kvt/lightning_modules/spec.py", "max_stars_repo_stars_event_max_datetime": "2022-03-04T05:00:52.000Z", "max_stars_repo_stars_event_min_datetime": "2021-06-02T01:40:27.000Z", "num_tokens": 325, "path": null, "reason": "import numpy", "repo": null, "save_path": null, "sha": null, "size": 1203 }