text stringlengths 0 27.1M | meta dict |
|---|---|
(*
Autor(s):
Andrej Dudenhefner (1)
Affiliation(s):
(1) Saarland University, Saarbrücken, Germany
*)
(*
Reduction from:
Diophantine Constraint Solvability (H10C_SAT)
to:
Square Diophantine Constraint Solvability (H10SQC_SAT)
*)
Require Import List Lia.
Require Cantor.
Import ListNotations.
Require Import Undecidability.DiophantineConstraints.H10C.
Require Import ssreflect ssrbool ssrfun.
Set Default Proof Using "Type".
Set Default Goal Selector "!".
Module Argument.
Notation encode := Cantor.to_nat.
Notation decode := Cantor.of_nat.
Opaque Cantor.to_nat Cantor.of_nat.
Section Reduction.
(* given instance of Diophantine constraint solvability *)
Context (cs: list h10c).
(* variable renaming *)
Definition ζ (x: nat) := encode (x, 0).
(*
fresh variables
θ x y 0 ~ x^2
θ x y 1 ~ y^2
θ x y 2 ~ x^2 + y^2
θ x y 3 ~ x + y
θ x y 4 ~ (x + y)^2
θ x y 5 ~ 2xy
*)
Definition θ (x y t: nat) := encode (x, 1 + encode (y, t)).
(* x * y = z <-> x^2 + 2z + y^2 = (x + y)^2 *)
Definition h10c_to_h10sqcs (c : h10c) : list h10sqc :=
match c with
| h10c_one x => [h10sqc_one (ζ x)]
| h10c_plus x y z => [h10sqc_plus (ζ x) (ζ y) (ζ z)]
| h10c_mult x y z => [
h10sqc_sq (ζ x) (θ x y 0); h10sqc_sq (ζ y) (θ x y 1); h10sqc_plus (θ x y 0) (θ x y 1) (θ x y 2);
h10sqc_plus (ζ x) (ζ y) (θ x y 3); h10sqc_sq (θ x y 3) (θ x y 4);
h10sqc_plus (ζ z) (ζ z) (θ x y 5); h10sqc_plus (θ x y 2) (θ x y 5) (θ x y 4)]
end.
(* constructed instance of square Diophantine constraint solvability *)
Definition sqcs := flat_map h10c_to_h10sqcs cs.
Section Transport.
(* solution of the given instance cs *)
Context (φ : nat -> nat) (Hφ: forall c, In c cs -> h10c_sem c φ).
(* solution of the constructed instance sqcs *)
Definition φ' (n: nat) :=
match decode n with
| (x, 0) => φ x
| (x, S m) =>
match decode m with
| (y, 0) => (φ x) * (φ x)
| (y, 1) => (φ y) * (φ y)
| (y, 2) => (φ x) * (φ x) + (φ y) * (φ y)
| (y, 3) => (φ x) + (φ y)
| (y, 4) => ((φ x) + (φ y)) * ((φ x) + (φ y))
| (y, 5) => (φ x) * (φ y) + (φ x) * (φ y)
| (_, _) => 0
end
end.
Lemma h10c_to_h10sqcs_spec {c} : h10c_sem c φ -> Forall (h10sqc_sem φ') (h10c_to_h10sqcs c).
Proof.
case: c => /=.
- move=> x ?. constructor; last done.
by rewrite /= /ζ /φ' Cantor.cancel_of_to.
- move=> x y z ?. constructor; last done.
by rewrite /= /ζ /φ' ?Cantor.cancel_of_to.
- move=> x y z ?. (do ? constructor);
rewrite /= /ζ /φ' ?Cantor.cancel_of_to /= ?Cantor.cancel_of_to; by nia.
Qed.
End Transport.
Lemma transport : H10C_SAT cs -> H10SQC_SAT sqcs.
Proof.
move=> [φ Hφ]. exists (φ' φ).
move: Hφ. rewrite -?Forall_forall /sqcs Forall_flat_map.
apply: Forall_impl => ?. by move /h10c_to_h10sqcs_spec.
Qed.
Section InverseTransport.
(* solution of the constructed instance sqcs *)
Context (φ' : nat -> nat) (Hφ': forall c, In c sqcs -> h10sqc_sem φ' c).
(* solution of the given instance cs *)
Definition φ (x: nat) := φ' (ζ x).
Lemma h10c_of_h10sqcs_spec {c} : Forall (h10sqc_sem φ') (h10c_to_h10sqcs c) -> h10c_sem c φ.
Proof.
case: c => /=.
- by move=> x /Forall_cons_iff [].
- by move=> x y z /Forall_cons_iff [].
- move=> x y z. do 7 (move=> /Forall_cons_iff /and_comm []).
rewrite /= /φ. by nia.
Qed.
End InverseTransport.
Lemma inverse_transport : H10SQC_SAT sqcs -> H10C_SAT cs.
Proof.
move=> [φ' Hφ']. exists (φ φ').
move: Hφ'. rewrite -?Forall_forall /sqcs Forall_flat_map.
apply: Forall_impl => ?. by move=> /h10c_of_h10sqcs_spec.
Qed.
End Reduction.
End Argument.
Require Import Undecidability.Synthetic.Definitions.
(* Diophantine Constraint Solvability many-one reduces to Square Diophantine Constraint Solvability *)
Theorem reduction : H10C_SAT ⪯ H10SQC_SAT.
Proof.
exists (fun cs => Argument.sqcs cs) => cs. constructor.
- exact: Argument.transport.
- exact: Argument.inverse_transport.
Qed.
| {
"alphanum_fraction": null,
"author": "uds-psl",
"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/uds-psl-coq-synthetic-incompleteness/coq-synthetic-incompleteness-cd7d8490f8542bfe85658c465bcb26b2ed163f53/theories/DiophantineConstraints/Reductions/H10C_SAT_to_H10SQC_SAT.v",
"reason": null,
"repo": "coq-synthetic-incompleteness",
"save_path": "github-repos/coq/uds-psl-coq-synthetic-incompleteness",
"sha": "cd7d8490f8542bfe85658c465bcb26b2ed163f53",
"size": null
} |
#include <boost/log/utility/strictest_lock.hpp>
| {
"alphanum_fraction": 0.8125,
"author": null,
"avg_line_length": 24,
"converted": null,
"ext": "hpp",
"file": null,
"hexsha": "0cee71c14a011e5e6150ffccbd7c31e805dd0e9b",
"include": null,
"lang": "C++",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-07-06T03:06:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-05-28T21:06:37.000Z",
"max_forks_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "miathedev/BoostForArduino",
"max_forks_repo_path": "src/boost_log_utility_strictest_lock.hpp",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e",
"max_issues_repo_issues_event_max_datetime": "2021-05-20T23:55:08.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-26T15:17:35.000Z",
"max_issues_repo_licenses": [
"BSL-1.0"
],
"max_issues_repo_name": "miathedev/BoostForArduino",
"max_issues_repo_path": "src/boost_log_utility_strictest_lock.hpp",
"max_line_length": 47,
"max_stars_count": 10,
"max_stars_repo_head_hexsha": "919621dcd0c157094bed4df752b583ba6ea6409e",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "miathedev/BoostForArduino",
"max_stars_repo_path": "src/boost_log_utility_strictest_lock.hpp",
"max_stars_repo_stars_event_max_datetime": "2021-07-06T02:48:49.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-17T00:58:42.000Z",
"num_tokens": 11,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 48
} |
import numpy as np
import time
arr = np.random.randn(100, 100)
arr = arr * 1000000000000000000 ##########################
arr.dtype = 'float64' ##########################
print(arr.dtype)
time_start = time.time()
for i in range(500):
for j in range(500):
arr * arr
print(i)
time_end = time.time()
time_mul = time_end - time_start
print('time cost', time_end - time_start, 's')
# arr = np.random.randn(100, 100)
# arr = arr * 32767
# arr.dtype = 'int16'
print(arr.dtype)
time_start = time.time()
for i in range(500):
for j in range(500):
arr + arr
print(i)
time_end = time.time()
time_pls = time_end - time_start
print('time cost', time_end - time_start, 's')
print('乘法时间:', time_mul)
print('加法时间:', time_pls)
| {
"alphanum_fraction": 0.6069057105,
"author": null,
"avg_line_length": 23.53125,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "3b87046b8d6bb71bb81cf86e824f9789c2e1955d",
"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": "cfde95efb73aaf07e942ede9987561de57ebfbfd",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Jager771/AdderNet",
"max_forks_repo_path": "runtime.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cfde95efb73aaf07e942ede9987561de57ebfbfd",
"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": "Jager771/AdderNet",
"max_issues_repo_path": "runtime.py",
"max_line_length": 61,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cfde95efb73aaf07e942ede9987561de57ebfbfd",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Jager771/AdderNet",
"max_stars_repo_path": "runtime.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 222,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 753
} |
# Copyright 2019 The OpenRadar Authors. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import numpy as np
from matplotlib import pyplot as plt
from numpy import pi
from numpy.fft import fft, fftfreq, fftshift
from scipy import signal
import logging
import sys
class ZoomFFT:
"""This class is an implementation of the Zoom Fast Fourier Transform (ZoomFFT).
The zoom FFT (Fast Fourier Transform) is a signal processing technique used to
analyse a portion of a spectrum at high resolution. The steps to apply the zoom
FFT to this region are as follows:
1. Frequency translate to shift the frequency range of interest down to near
0 Hz (DC)
2. Low pass filter to prevent aliasing when subsequently sampled at a lower
sample rate
3. Re-sample at a lower rate
4. FFT the re-sampled data (Multiple blocks of data are needed to have an FFT of
the same length)
The resulting spectrum will now have a much smaller resolution bandwidth, compared
to an FFT of non-translated data.
"""
def __init__(self, low_freq, high_freq, fs, signal=None):
"""Initialize the ZoomFFT class.
Args:
low_freq (int): Lower frequency limit
high_freq (int): Upper frequency limit
fs (int): sampling Frequency
signal (np.ndarray): Signal to perform the ZoomFFT on
"""
self.low_freq = low_freq
self.high_freq = high_freq
self.fs = fs
if (low_freq < 0) or (high_freq > fs) or ((high_freq - low_freq) > fs):
raise Exception("invalid inputs. Program Terminated! ")
if signal:
self.signal = signal
self.length = len(signal)
else:
# the default now is a sine signal, for demo purpose
pass
def set_signal(self, signal):
"""Sets given signal as a member variable of the class.
e.g. ZoomFFT.create_signal(generate_sinewave(a, b, c) + generate_sinewave(d, e, f))
Args:
signal (np.ndarray): Signal to perform the ZoomFFT on
"""
self.signal = signal
def sinewave(self, f, length, amplitude=1):
"""Generates a sine wave which could be used as a part of the signal.
Args:
f (int): Frequency of the sine wave
length (int): Number of data points in the sine wave
amplitude (int): Amplitude of the sine wave
Returns:
x (np.ndarray): Generated sine wave with the given parameters.
"""
self.length = length
x = amplitude * np.sin(2 * pi * f / self.fs * np.arange(length))
return x
def compute_fft(self):
"""Computes the Fast Fourier Transform (FFT) of the signal.
Returns:
X (np.ndarray): A frequency-shifted, unscaled, FFT of the signal.
"""
try:
X = fft(self.signal)
X = np.abs(fftshift(X)) # unscaled
return X
except NameError:
print("signal not defined. Program terminated!")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
def plot_fft(self, d=None):
"""Plots the Fast Fourier Transform (FFT) of the signal.
Args:
d (int): Sample spacing (inverse of the sampling rate)
"""
try:
d = 1 / self.fs if d is None else d
X = self.compute_fft()
freq = fftfreq(self.length, d)
self.original_sample_range = 1 / (self.length * d)
fig1, ax1 = plt.subplots()
ax1.stem(fftshift(freq), X / self.length)
ax1.set_xlabel('Frequency (Hz)', fontsize=12)
ax1.set_ylabel('Magnitude', fontsize=12)
ax1.set_title('FFT Two-sided spectrum', fontsize=12)
ax1.grid()
plt.show()
except:
print("Unexpected error:", sys.exc_info()[0])
raise
def compute_zoomfft(self, resample_number=None):
"""Computes the Zoom Fast Fourier Transform (ZoomFFT) of the signal.
Args:
resample_number (int): The number of samples in the resampled signal.
Returns:
Xd (np.ndarray): A frequency-shifted, unscaled, ZoomFFT of the signal.
bw_factor (int): Bandwidth factor
fftlen (int): Length of the ZoomFFT output
Ld (int): for internal use
F (int): for internal use
"""
try:
bw_of_interest = self.high_freq - self.low_freq
if self.length % bw_of_interest != 0:
logging.warning("length of signal should be divisible by bw_of_interest. Zoom FFT Spectrum may distort!")
input("Press Enter to continue...")
fc = (self.low_freq + self.high_freq) / 2
bw_factor = np.floor(self.fs / bw_of_interest).astype(np.uint8)
# mix the signal down to DC, and filter it through the FIR decimator
ind_vect = np.arange(self.length)
y = self.signal * np.exp(-1j * 2 * pi * ind_vect * fc / self.fs)
resample_number = bw_of_interest / self.original_sample_range if resample_number is None else resample_number
resample_range = bw_of_interest / resample_number
if resample_range != self.original_sample_range:
logging.warning("resample resolution != original sample resolution. Zoom FFT Spectrum may distort!")
input("Press Enter to continue...")
xd = signal.resample(y, np.int(resample_number))
fftlen = len(xd)
Xd = fft(xd)
Xd = np.abs(fftshift(Xd)) # unscaled
Ld = self.length / bw_factor
fsd = self.fs / bw_factor
F = fc + fsd / fftlen * np.arange(fftlen) - fsd / 2
return Xd, bw_factor, fftlen, Ld, F
except NameError:
print("signal not defined. Program terminated!")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
def plot_zoomfft(self, resample_number=None):
"""Plots the Zoom Fast Fourier Transform (ZoomFFT) of the signal.
Args:
resample_number (int): The number of samples in the resampled signal.
"""
try:
bw_of_interest = self.high_freq - self.low_freq
resample_number = bw_of_interest / self.original_sample_range if resample_number is None else resample_number
Xd, bw_factor, fftlen, Ld, F = self.compute_zoomfft(resample_number)
fig1, ax1 = plt.subplots()
ax1.stem(F, Xd / Ld, linefmt='C1-.', markerfmt='C1s')
ax1.grid()
ax1.set_xlabel('Frequency (Hz)', fontsize=12)
ax1.set_ylabel('Magnitude', fontsize=12)
ax1.set_title('Zoom FFT Spectrum. Mixer Approach.', fontsize=12)
fig1.subplots_adjust(hspace=0.35)
plt.show()
except:
print("Unexpected error:", sys.exc_info()[0])
raise
| {
"alphanum_fraction": 0.6002605863,
"author": null,
"avg_line_length": 36.7224880383,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "946a31bff87ddc7bb342aeb49f6db9f242a50178",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 119,
"max_forks_repo_forks_event_max_datetime": "2022-03-28T01:13:55.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-10-23T12:54:08.000Z",
"max_forks_repo_head_hexsha": "cab1b60ebc69be635860e474b2b6564a25befb5c",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "gimac/OpenRadar",
"max_forks_repo_path": "mmwave/dsp/ZoomFFT.py",
"max_issues_count": 36,
"max_issues_repo_head_hexsha": "cab1b60ebc69be635860e474b2b6564a25befb5c",
"max_issues_repo_issues_event_max_datetime": "2022-03-16T02:00:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-12-19T23:52:22.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "gimac/OpenRadar",
"max_issues_repo_path": "mmwave/dsp/ZoomFFT.py",
"max_line_length": 121,
"max_stars_count": 275,
"max_stars_repo_head_hexsha": "cab1b60ebc69be635860e474b2b6564a25befb5c",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "gimac/OpenRadar",
"max_stars_repo_path": "mmwave/dsp/ZoomFFT.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-29T08:29:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-21T18:33:05.000Z",
"num_tokens": 1726,
"path": null,
"reason": "import numpy,from numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 7675
} |
from __future__ import print_function
import os
from argparse import ArgumentParser
import numpy as np
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
if __name__ == '__main__':
parser = ArgumentParser("")
parser.add_argument("feats", help="Path to the npy features.")
parser.add_argument("out_dir", help="Path where to save the processed files.")
parser.add_argument("prefix", help="Files prefix, name of the dataset.")
parser.add_argument("pca_variance", help="Ratio of the variance to keep with the pca.")
args = parser.parse_args()
feats_path = args.feats
out_dir = args.out_dir
file_prefix = args.prefix
pca_variance = float(args.pca_variance)
feats = np.load(feats_path)
# perform standardization
feats = StandardScaler().fit_transform(feats)
pca = PCA(n_components=pca_variance, svd_solver="full")
feats_pc = pca.fit_transform(feats)
print(feats_pc.shape)
# Create output directory if not present
if not os.path.exists(out_dir):
try:
os.makedirs(out_dir)
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
raise
np.save(os.path.join(out_dir, file_prefix + '-feats.npy'), feats_pc)
| {
"alphanum_fraction": 0.7028483449,
"author": null,
"avg_line_length": 33.3076923077,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "b844e3f1daf05c31ab6d47c5b357a7c583f02cf8",
"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": "0cdda29dbc075fb8f3441c15638d1b06de992a57",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "enricovian/GraphSAGE",
"max_forks_repo_path": "preprocessing/pca.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0cdda29dbc075fb8f3441c15638d1b06de992a57",
"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": "enricovian/GraphSAGE",
"max_issues_repo_path": "preprocessing/pca.py",
"max_line_length": 91,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0cdda29dbc075fb8f3441c15638d1b06de992a57",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "enricovian/GraphSAGE",
"max_stars_repo_path": "preprocessing/pca.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": 1299
} |
// Copyright Vladimir Prus 2004.
// Copyright Hartmut Kaiser 2005.
// 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)
#ifndef BOOST_PP_IS_ITERATING
#ifndef BOOST_PLUGIN_FACTORY_IMPL_HK_2005_11_07
#define BOOST_PLUGIN_FACTORY_IMPL_HK_2005_11_07
#include <boost/mpl/list.hpp>
#include <boost/preprocessor/iterate.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/plugin/config.hpp>
#define BOOST_PP_ITERATION_PARAMS_1 \
(3, (3, PLUGIN_ARGUMENT_LIMIT, \
"boost/plugin/detail/plugin_factory_impl.hpp"))
#include BOOST_PP_ITERATE()
#endif // BOOST_PLUGIN_FACTORY_IMPL_HK_2005_11_07
///////////////////////////////////////////////////////////////////////////////
//
// Preprocessor vertical repetition code
//
///////////////////////////////////////////////////////////////////////////////
#else // defined(BOOST_PP_IS_ITERATING)
#define N BOOST_PP_ITERATION()
///////////////////////////////////////////////////////////////////////////////
namespace detail {
///////////////////////////////////////////////////////////////////////////
template<
typename BasePlugin, typename Base,
BOOST_PP_ENUM_PARAMS(N, typename A)
>
struct plugin_factory_item<
BasePlugin, Base,
boost::mpl::list<BOOST_PP_ENUM_PARAMS(N, A)>
>
: public Base
{
using Base::create;
BasePlugin* create(std::string const& name, BOOST_PP_ENUM_BINARY_PARAMS(N, A, a))
{
std::pair<abstract_factory<BasePlugin> *, dll_handle> r =
get_abstract_factory<BasePlugin>(this->m_dll, name);
return r.first->create(r.second, BOOST_PP_ENUM_PARAMS(N, a));
}
};
///////////////////////////////////////////////////////////////////////////
template<
typename BasePlugin, typename Base,
BOOST_PP_ENUM_PARAMS(N, typename A)
>
struct static_plugin_factory_item<
BasePlugin, Base,
boost::mpl::list<BOOST_PP_ENUM_PARAMS(N, A)>
>
: public Base
{
using Base::create;
BasePlugin* create(std::string const& name, BOOST_PP_ENUM_BINARY_PARAMS(N, A, a))
{
std::pair<abstract_factory<BasePlugin> *, dll_handle> r =
get_abstract_factory_static<BasePlugin>(
this->f, &empty_deleter, name);
return r.first->create(r.second, BOOST_PP_ENUM_PARAMS(N, a));
}
};
///////////////////////////////////////////////////////////////////////////////
} // namespace boost::plugin::detail
#undef N
#endif // defined(BOOST_PP_IS_ITERATING)
| {
"alphanum_fraction": 0.5374784111,
"author": null,
"avg_line_length": 34.0588235294,
"converted": null,
"ext": "hpp",
"file": null,
"hexsha": "0b954cd897cef840521407acdb2cc4a8d4ff89fb",
"include": null,
"lang": "C++",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-04-10T17:23:52.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-11-17T04:38:38.000Z",
"max_forks_repo_head_hexsha": "7376c0de0529e7d7b80cf08b94ec484c2e56d38e",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "saga-project/saga-cpp",
"max_forks_repo_path": "external/boost/plugin/boost/plugin/detail/plugin_factory_impl.hpp",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "7376c0de0529e7d7b80cf08b94ec484c2e56d38e",
"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": "saga-project/saga-cpp",
"max_issues_repo_path": "external/boost/plugin/boost/plugin/detail/plugin_factory_impl.hpp",
"max_line_length": 89,
"max_stars_count": 5,
"max_stars_repo_head_hexsha": "7376c0de0529e7d7b80cf08b94ec484c2e56d38e",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "saga-project/saga-cpp",
"max_stars_repo_path": "external/boost/plugin/boost/plugin/detail/plugin_factory_impl.hpp",
"max_stars_repo_stars_event_max_datetime": "2021-08-12T11:05:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-09-15T16:24:14.000Z",
"num_tokens": 568,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 2895
} |
# Copyright (c) Microsoft Corporation and contributors.
# Licensed under the MIT License.
import logging
import math
import time
from typing import Any, List, Optional, Tuple, Union
import networkx as nx
import numpy as np
from ..utils import remap_node_ids
def node2vec_embed(
graph: Union[nx.Graph, nx.DiGraph],
num_walks: int = 10,
walk_length: int = 80,
return_hyperparameter: float = 1.0,
inout_hyperparameter: float = 1.0,
dimensions: int = 128,
window_size: int = 10,
workers: int = 8,
iterations: int = 1,
interpolate_walk_lengths_by_node_degree: bool = True,
random_seed: Optional[int] = None,
) -> Tuple[np.array, List[Any]]:
"""
Generates a node2vec embedding from a given graph. Will follow the word2vec algorithm to create the embedding.
Parameters
----------
graph: Union[nx.Graph, nx.DiGraph]
A networkx graph or digraph. A multigraph should be turned into a non-multigraph so that the calling user
properly handles the multi-edges (i.e. aggregate weights or take last edge weight).
If the graph is unweighted, the weight of each edge will default to 1.
num_walks : int
Number of walks per source. Default is 10.
walk_length: int
Length of walk per source. Default is 80.
return_hyperparameter : float
Return hyperparameter (p). Default is 1.0
inout_hyperparameter : float
Inout hyperparameter (q). Default is 1.0
dimensions : int
Dimensionality of the word vectors. Default is 128.
window_size : int
Maximum distance between the current and predicted word within a sentence. Default is 10.
workers : int
Use these many worker threads to train the model. Default is 8.
iterations : int
Number of epochs in stochastic gradient descent (SGD)
interpolate_walk_lengths_by_node_degree : bool
Use a dynamic walk length that corresponds to each nodes
degree. If the node is in the bottom 20 percentile, default to a walk length of 1. If it is in the top 10
percentile, use ``walk_length``. If it is in the 20-80 percentiles, linearly interpolate between 1 and ``walk_length``.
This will reduce lower degree nodes from biasing your resulting embedding. If a low degree node has the same
number of walks as a high degree node (which it will if this setting is not on), then the lower degree nodes
will take a smaller breadth of random walks when compared to the high degree nodes. This will result in your
lower degree walks dominating your higher degree nodes.
random_seed : int
Seed to be used for reproducible results. Default is None and will produce a random output. Note that for a fully
deterministically-reproducible run, you must also limit to a single worker thread (`workers=1`), to eliminate
ordering jitter from OS thread scheduling. In addition the environment variable ``PYTHONHASHSEED`` must be set
to control hash randomization.
Returns
-------
Tuple[np.array, List[Any]]
A tuple containing a matrix, with each row index corresponding to the embedding for each node. The tuple
also contains a vector containing the corresponding vertex labels for each row in the matrix.
The matrix and vector are positionally correlated.
Notes
-----
The original reference implementation of node2vec comes from Aditya Grover from
https://github.com/aditya-grover/node2vec/.
Further details on the Alias Method used in this functionality can be found at
https://lips.cs.princeton.edu/the-alias-method-efficient-sampling-with-many-discrete-outcomes/
References
----------
.. [1] Aditya Grover and Jure Leskovec "node2vec: Scalable Feature Learning for Networks."
Knowledge Discovery and Data Mining, 2016.
"""
_preconditions(
graph,
num_walks,
walk_length,
return_hyperparameter,
inout_hyperparameter,
dimensions,
window_size,
workers,
iterations,
interpolate_walk_lengths_by_node_degree,
)
random_state = np.random.RandomState(seed=random_seed)
node2vec_graph = _Node2VecGraph(
graph, return_hyperparameter, inout_hyperparameter, random_state
)
logging.info(
f"Starting preprocessing of transition probabilities on graph with {str(len(graph.nodes()))} nodes and "
f"{str(len(graph.edges()))} edges"
)
start = time.time()
logging.info(f"Starting at time {str(start)}")
node2vec_graph._preprocess_transition_probabilities()
logging.info(f"Simulating walks on graph at time {str(time.time())}")
walks = node2vec_graph._simulate_walks(
num_walks, walk_length, interpolate_walk_lengths_by_node_degree
)
logging.info(f"Learning embeddings at time {str(time.time())}")
model = _learn_embeddings(
walks, dimensions, window_size, workers, iterations, random_seed
)
end = time.time()
logging.info(
f"Completed. Ending time is {str(end)} Elapsed time is {str(start - end)}"
)
labels = node2vec_graph.original_graph.nodes()
remapped_labels = node2vec_graph.label_map_to_string
return (
np.array([model.wv.get_vector(remapped_labels[node]) for node in labels]),
labels,
)
def _assert_is_positive_int(name: str, value: int):
if not isinstance(value, int):
raise TypeError(f"{name} must be an int")
if value <= 0:
raise ValueError(f"{name} must be > 0")
def _assert_is_nonnegative_float(name: str, value: float):
if not isinstance(value, float):
raise TypeError(f"{name} must be a float")
if value < 0.0:
raise ValueError(f"{name} must be >= 0.0")
def _preconditions(
graph: Union[nx.Graph, nx.DiGraph],
num_walks: int,
walk_length: int,
return_hyperparameter: float,
inout_hyperparameter: float,
dimensions: int,
window_size: int,
workers: int,
iterations: int,
interpolate_walk_lengths_by_node_degree: bool,
):
if not isinstance(graph, nx.Graph):
raise TypeError("graph must be a networkx Graph or DiGraph")
if graph.is_multigraph():
raise ValueError(
"This function does not work on multigraphs - because there are two reasonable ways to treat a "
"multigraph with different behaviors, we insist that the caller create an appropriate Graph or "
"DiGraph that represents the manner in which they'd like the multigraph to be treated for the "
"purposes of this embedding"
)
_assert_is_positive_int("num_walks", num_walks)
_assert_is_positive_int("walk_length", walk_length)
_assert_is_nonnegative_float("return_hyperparameter", return_hyperparameter)
_assert_is_nonnegative_float("inout_hyperparameter", inout_hyperparameter)
_assert_is_positive_int("dimensions", dimensions)
_assert_is_positive_int("window_size", window_size)
_assert_is_positive_int("workers", workers)
_assert_is_positive_int("iterations", iterations)
if not isinstance(interpolate_walk_lengths_by_node_degree, bool):
raise TypeError("interpolate_walk_lengths_by_node_degree must be a bool")
def _learn_embeddings(
walks: List[Any],
dimensions: int,
window_size: int,
workers: int,
iterations: int,
random_seed: Optional[int],
):
"""
Learn embeddings by optimizing the skip-gram objective using SGD.
"""
from gensim.models import Word2Vec
walks = [list(map(str, walk)) for walk in walks]
# Documentation - https://radimrehurek.com/gensim/models/word2vec.html
model = Word2Vec(
walks,
size=dimensions,
window=window_size,
min_count=0,
sg=1, # Training algorithm: 1 for skip-gram; otherwise CBOW
workers=workers,
iter=iterations,
seed=random_seed,
)
return model
class _Node2VecGraph:
"""
Temporary inner state object for constructing the random walks
Parameters
----------
graph: nx.Graph
A networkx graph
return_hyperparameter : float
Return hyperparameter
inout_hyperparameter : float
Inout hyperparameter
random_state : np.random.RandomState
Random State for reproducible results. Default is None and will produce random
results
"""
def __init__(
self,
graph: nx.Graph,
return_hyperparameter: float,
inout_hyperparameter: float,
random_state: Optional[np.random.RandomState] = None,
):
self.original_graph: nx.Graph = graph
graph_with_new_ids, new_id_map = remap_node_ids(graph=graph)
self.graph = graph_with_new_ids
self.label_map_to_string = new_id_map
self.is_directed = self.graph.is_directed()
self.p = return_hyperparameter
self.q = inout_hyperparameter
self.random_state = random_state
def node2vec_walk(
self,
walk_length: int,
start_node: Any,
degree_percentiles: Optional[np.ndarray],
):
"""
Simulate a random walk starting from start node.
"""
graph = self.graph
alias_nodes = self.alias_nodes
alias_edges = self.alias_edges
walk = [start_node]
# Percentiles will be provided if we are using the 'interpolate_walk_lengths_by_node_degree' feature.
# the intent of the code is to default the bottom 20% of to a minimal walk length, default the top 10% to a
# maximum walk length, and interpolate the inner 70% linearly from min to max.
# This is to avoid having your random walks be dominated by low degree nodes. If the low degree nodes have the
# same number of walks as the high degree nodes, the low degree nodes will take a smaller breadth of paths
# (due to their being less nodes to choose from) and will bias your resulting Word2Vec embedding
if degree_percentiles is not None:
degree = nx.degree(graph, start_node)
walk_length = self._get_walk_length_interpolated(
degree, degree_percentiles, walk_length
)
while len(walk) < walk_length:
current = walk[-1]
current_neighbors = sorted(graph.neighbors(current))
if len(current_neighbors) > 0:
if len(walk) == 1:
walk.append(
current_neighbors[
_alias_draw(
alias_nodes[current][0],
alias_nodes[current][1],
self.random_state,
)
]
)
else:
prev = walk[-2]
next = current_neighbors[
_alias_draw(
alias_edges[(prev, current)][0],
alias_edges[(prev, current)][1],
self.random_state,
)
]
walk.append(next)
else:
break
return walk
@staticmethod
def _get_walk_length_interpolated(
degree: int, percentiles: list, max_walk_length: int
):
"""
Given a node's degree, determine the length of a walk that should be used. If the degree is less than the
first element of the percentiles list, default the walk length to 1. Otherwise, if the degree is greater
than the last element of the list, default it to the max_walk_length. If it falls in the middle, do a linear
interpolation to decide the length of the walk.
"""
new_walk_length = None
for i, percentile in enumerate(percentiles):
# if we are below the first percentile in the list, default to a walk length of 1
if i == 0 and degree < percentile:
return 1
# otherwise, find which bucket we are going to be in.
if degree <= percentile:
new_walk_length = max_walk_length * ((i * 0.1) + 0.2)
break
# the degree is above the last percentile
if not new_walk_length:
new_walk_length = max_walk_length
# a walk length of 0 is invalid but can happen depending on the percentiles used
if new_walk_length < 1:
new_walk_length = 1
return math.floor(new_walk_length)
def _simulate_walks(
self,
num_walks: int,
walk_length: int,
interpolate_walk_lengths_by_node_degree: bool = False,
):
"""
Repeatedly simulate random walks from each node.
"""
graph = self.graph
walks = []
nodes = list(graph.nodes())
degree_percentiles: Optional[np.ndarray] = None
if interpolate_walk_lengths_by_node_degree:
degree_percentiles = np.percentile(
[degree for _, degree in graph.degree()], [x for x in range(20, 90, 10)]
)
for walk_iteration in range(num_walks):
logging.info(
"Walk iteration: " + str(walk_iteration + 1) + "/" + str(num_walks)
)
self.random_state.shuffle(nodes)
for node in nodes:
walks.append(
self.node2vec_walk(
walk_length=walk_length,
start_node=node,
degree_percentiles=degree_percentiles,
)
)
return walks
def _get_alias_edge(self, source: Any, destination: Any):
"""
Get the alias edge setup lists for a given edge.
"""
graph = self.graph
p = self.p
q = self.q
unnormalized_probs = []
for destination_neighbor in sorted(graph.neighbors(destination)):
if destination_neighbor == source:
unnormalized_probs.append(
graph[destination][destination_neighbor].get("weight", 1) / p
)
elif graph.has_edge(destination_neighbor, source):
unnormalized_probs.append(
graph[destination][destination_neighbor].get("weight", 1)
)
else:
unnormalized_probs.append(
graph[destination][destination_neighbor].get("weight", 1) / q
)
norm_const = sum(unnormalized_probs)
normalized_probs = [float(u_prob) / norm_const for u_prob in unnormalized_probs]
return _alias_setup(normalized_probs)
def _preprocess_transition_probabilities(self, weight_default: float = 1.0):
"""
Preprocessing of transition probabilities for guiding the random walks.
"""
graph = self.graph
is_directed = self.is_directed
alias_nodes = {}
total_nodes = len(graph.nodes())
bucket = 0
current_node = 0
quotient = int(total_nodes / 10)
logging.info(
f"Beginning preprocessing of transition probabilities for {total_nodes} vertices"
)
for node in graph.nodes():
current_node += 1
if current_node > bucket * quotient:
bucket += 1
logging.info(f"Completed {current_node} / {total_nodes} vertices")
unnormalized_probs = [
graph[node][nbr].get("weight", weight_default)
for nbr in sorted(graph.neighbors(node))
]
norm_const = sum(unnormalized_probs)
normalized_probs = [
float(u_prob) / norm_const for u_prob in unnormalized_probs
]
alias_nodes[node] = _alias_setup(normalized_probs)
logging.info(
f"Completed preprocessing of transition probabilities for vertices"
)
alias_edges = {}
total_edges = len(graph.edges())
bucket = 0
current_edge = 0
quotient = int(total_edges / 10)
logging.info(
f"Beginning preprocessing of transition probabilities for {total_edges} edges"
)
if is_directed:
for edge in graph.edges():
current_edge += 1
if current_edge > bucket * quotient:
bucket += 1
logging.info(f"Completed {current_edge} / {total_edges} edges")
alias_edges[edge] = self._get_alias_edge(edge[0], edge[1])
else:
for edge in graph.edges():
current_edge += 1
if current_edge > bucket * quotient:
bucket += 1
logging.info(f"Completed {current_edge} / {total_edges} edges")
alias_edges[edge] = self._get_alias_edge(edge[0], edge[1])
alias_edges[(edge[1], edge[0])] = self._get_alias_edge(edge[1], edge[0])
logging.info(f"Completed preprocessing of transition probabilities for edges")
self.alias_nodes = alias_nodes
self.alias_edges = alias_edges
return
def _alias_setup(probabilities: List[float]):
"""
Compute utility lists for non-uniform sampling from discrete distributions.
Refer to
https://lips.cs.princeton.edu/the-alias-method-efficient-sampling-with-many-discrete-outcomes/
for details
"""
number_of_outcomes = len(probabilities)
alias = np.zeros(number_of_outcomes)
sampled_probabilities = np.zeros(number_of_outcomes, dtype=int)
smaller = []
larger = []
for i, prob in enumerate(probabilities):
alias[i] = number_of_outcomes * prob
if alias[i] < 1.0:
smaller.append(i)
else:
larger.append(i)
while len(smaller) > 0 and len(larger) > 0:
small = smaller.pop()
large = larger.pop()
sampled_probabilities[small] = large
alias[large] = alias[large] + alias[small] - 1.0
if alias[large] < 1.0:
smaller.append(large)
else:
larger.append(large)
return sampled_probabilities, alias
def _alias_draw(
probabilities: List[float], alias: List[float], random_state: np.random.RandomState
):
"""
Draw sample from a non-uniform discrete distribution using alias sampling.
"""
number_of_outcomes = len(probabilities)
random_index = int(np.floor(random_state.rand() * number_of_outcomes))
if random_state.rand() < alias[random_index]:
return random_index
else:
return probabilities[random_index]
| {
"alphanum_fraction": 0.6270518013,
"author": null,
"avg_line_length": 35.5378787879,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "16386e8f49ac83e2f9c436adbc056266858401ad",
"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": "8ea9a47cabe35ad28ec9d381e525358c2027f619",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "dtborders/graspologic",
"max_forks_repo_path": "graspologic/embed/n2v.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8ea9a47cabe35ad28ec9d381e525358c2027f619",
"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": "dtborders/graspologic",
"max_issues_repo_path": "graspologic/embed/n2v.py",
"max_line_length": 127,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8ea9a47cabe35ad28ec9d381e525358c2027f619",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "dtborders/graspologic",
"max_stars_repo_path": "graspologic/embed/n2v.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4025,
"path": null,
"reason": "import numpy,import networkx",
"repo": null,
"save_path": null,
"sha": null,
"size": 18764
} |
@testset "ess.jl" begin
@testset "copy and split" begin
# check a matrix with even number of rows
x = rand(50, 20)
# check incompatible sizes
@test_throws DimensionMismatch MCMCDiagnosticTools.copyto_split!(
similar(x, 25, 20), x
)
@test_throws DimensionMismatch MCMCDiagnosticTools.copyto_split!(
similar(x, 50, 40), x
)
y = similar(x, 25, 40)
MCMCDiagnosticTools.copyto_split!(y, x)
@test reshape(y, size(x)) == x
# check a matrix with odd number of rows
x = rand(51, 20)
# check incompatible sizes
@test_throws DimensionMismatch MCMCDiagnosticTools.copyto_split!(
similar(x, 25, 20), x
)
@test_throws DimensionMismatch MCMCDiagnosticTools.copyto_split!(
similar(x, 51, 40), x
)
MCMCDiagnosticTools.copyto_split!(y, x)
@test reshape(y, 50, 20) == x[vcat(1:25, 27:51), :]
end
@testset "ESS and R̂ (IID samples)" begin
rawx = randn(10_000, 40, 10)
# Repeat tests with different scales
for scale in (1, 50, 100)
x = scale * rawx
ess_standard, rhat_standard = ess_rhat(x)
ess_standard2, rhat_standard2 = ess_rhat(x; method=ESSMethod())
ess_fft, rhat_fft = ess_rhat(x; method=FFTESSMethod())
ess_bda, rhat_bda = ess_rhat(x; method=BDAESSMethod())
# check that we get (roughly) the same results
@test ess_standard == ess_standard2
@test ess_standard ≈ ess_fft
@test rhat_standard == rhat_standard2 == rhat_fft == rhat_bda
# check that the estimates are reasonable
@test all(x -> isapprox(x, 100_000; rtol=0.1), ess_standard)
@test all(x -> isapprox(x, 100_000; rtol=0.1), ess_bda)
@test all(x -> isapprox(x, 1; rtol=0.1), rhat_standard)
# BDA method fluctuates more
@test var(ess_standard) < var(ess_bda)
end
end
@testset "ESS and R̂ (identical samples)" begin
x = ones(10_000, 40, 10)
ess_standard, rhat_standard = ess_rhat(x)
ess_standard2, rhat_standard2 = ess_rhat(x; method=ESSMethod())
ess_fft, rhat_fft = ess_rhat(x; method=FFTESSMethod())
ess_bda, rhat_bda = ess_rhat(x; method=BDAESSMethod())
# check that the estimates are all NaN
for ess in (ess_standard, ess_standard2, ess_fft, ess_bda)
@test all(isnan, ess)
end
for rhat in (rhat_standard, rhat_standard2, rhat_fft, rhat_bda)
@test all(isnan, rhat)
end
end
@testset "ESS and R̂ (single sample)" begin # check that issue #137 is fixed
x = rand(1, 5, 3)
for method in (ESSMethod(), FFTESSMethod(), BDAESSMethod())
# analyze array
ess_array, rhat_array = ess_rhat(x; method=method)
@test length(ess_array) == size(x, 2)
@test all(ismissing, ess_array) # since min(maxlag, niter - 1) = 0
@test length(rhat_array) == size(x, 2)
@test all(ismissing, rhat_array)
end
end
end
| {
"alphanum_fraction": 0.5882721856,
"author": null,
"avg_line_length": 35.043956044,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "4528c735d0445f6e90ae5879ff964f39384b882c",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2021-07-04T18:49:03.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-06-21T19:26:25.000Z",
"max_forks_repo_head_hexsha": "13ae88c7ff481d9831b3b09cbe0052658caf4a60",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "rikhuijzer/InferenceDiagnostics.jl",
"max_forks_repo_path": "test/ess.jl",
"max_issues_count": 16,
"max_issues_repo_head_hexsha": "13ae88c7ff481d9831b3b09cbe0052658caf4a60",
"max_issues_repo_issues_event_max_datetime": "2021-07-07T01:07:04.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-05-18T12:31:50.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "rikhuijzer/InferenceDiagnostics.jl",
"max_issues_repo_path": "test/ess.jl",
"max_line_length": 80,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "13ae88c7ff481d9831b3b09cbe0052658caf4a60",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "rikhuijzer/InferenceDiagnostics.jl",
"max_stars_repo_path": "test/ess.jl",
"max_stars_repo_stars_event_max_datetime": "2021-07-04T21:10:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-05-18T09:19:49.000Z",
"num_tokens": 926,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 3189
} |
#!/usr/bin/env python
# import
from __future__ import print_function
## batteries
import os
import sys
import uuid
import pytest
import subprocess
## 3rd party
import numpy as np
import pandas as pd
## package
from MGSIM import Utils
from MGSIM import SimHtReads
from MGSIM.Commands import HtReads as HtReads_CMD
# data dir
test_dir = os.path.join(os.path.dirname(__file__))
data_dir = os.path.join(test_dir, 'data')
tmp_dir = os.path.join(test_dir, 'tmp')
out_dir = os.path.join(test_dir, 'output')
def validate_fastq(base_dir):
# validating fastq
## Read1
output_R = os.path.join(base_dir, '1', 'R1.fq')
if not os.path.isfile(output_R):
raise IOError('Cannot find file: {}'.format(output_R))
ret = subprocess.run(['fqtools', 'validate', output_R])
assert ret.returncode == 0
## Read2
output_R = os.path.join(base_dir, '1', 'R2.fq')
if not os.path.isfile(output_R):
raise IOError('Cannot find file: {}'.format(output_R))
ret = subprocess.run(['fqtools', 'validate', output_R])
assert ret.returncode == 0
# tests
def test_barcode_gen():
"""
Testing the generation of barcodes
"""
n_barcodes = 1000
barcodes = SimHtReads.barcodes(n_barcodes)
assert len(barcodes) == n_barcodes
assert type(barcodes) is np.ndarray
def test_help(script_runner):
ret = script_runner.run('MGSIM', 'ht_reads', '-h')
assert ret.success
def test_main(script_runner, tmp_path):
genome_table = os.path.join(data_dir, 'genome_list.txt')
abund_table = os.path.join(data_dir, 'comm_wAbund.txt')
temp_dir = os.path.join(str(tmp_path), str(uuid.uuid4()))
output_prefix = os.path.join(str(tmp_path), 'TEST-main')
ret = script_runner.run('MGSIM', 'ht_reads', '--art-paired',
'--tmp-dir', temp_dir,
'--barcode-total', '20',
'--barcode-chunks', '2',
'--seq-depth', '1e3',
'--rndSeed', '8294',
genome_table, abund_table, output_prefix)
assert ret.success
validate_fastq(output_prefix)
def test_main_multi(script_runner, tmp_path):
genome_table = os.path.join(data_dir, 'genome_list.txt')
abund_table = os.path.join(data_dir, 'comm_wAbund.txt')
temp_dir = os.path.join(str(tmp_path), str(uuid.uuid4()))
output_prefix = os.path.join(str(tmp_path), 'TEST-main-multi')
ret = script_runner.run('MGSIM', 'ht_reads',
'--art-paired', '-n', '2',
'--tmp-dir', temp_dir,
'--seq-depth', '1e4',
'--rndSeed', '8294',
genome_table, abund_table, output_prefix)
assert ret.success
validate_fastq(output_prefix)
def test_main_zeros(script_runner, tmp_path):
genome_table = os.path.join(data_dir, 'genome_list.txt')
abund_table = os.path.join(data_dir, 'comm_wAbund_zeros.txt')
temp_dir = os.path.join(str(tmp_path), str(uuid.uuid4()))
output_prefix = os.path.join(str(tmp_path), 'TEST-main-zeros')
ret = script_runner.run('MGSIM', 'ht_reads', '--art-paired',
'--tmp-dir', temp_dir,
'--barcode-total', '20',
'--barcode-chunks', '2',
'--seq-depth', '1e3',
'--rndSeed', '8294',
genome_table, abund_table, output_prefix)
assert ret.success
validate_fastq(output_prefix)
def test_main_prefix(script_runner, tmp_path):
genome_table = os.path.join(data_dir, 'genome_list.txt')
abund_table = os.path.join(data_dir, 'comm_wAbund.txt')
temp_dir = os.path.join(str(tmp_path), str(uuid.uuid4()))
output_prefix = os.path.join(str(tmp_path), 'TEST-main-prefix')
ret = script_runner.run('MGSIM', 'ht_reads', '--art-paired',
'--tmp-dir', temp_dir,
'--barcode-total', '20',
'--barcode-chunks', '2',
'--seq-depth', '1e3',
'--read-name', '{readID}_BX:Z:{barcodeID}',
'--rndSeed', '8294',
genome_table, abund_table, output_prefix)
assert ret.success
validate_fastq(output_prefix)
def test_main_large_frag_sd(script_runner, tmp_path):
genome_table = os.path.join(data_dir, 'genome_list.txt')
abund_table = os.path.join(data_dir, 'comm_wAbund.txt')
temp_dir = os.path.join(str(tmp_path), str(uuid.uuid4()))
output_prefix = os.path.join(str(tmp_path), 'TEST-main-largeFragSize')
ret = script_runner.run('MGSIM', 'ht_reads', '--art-paired',
'--tmp-dir', temp_dir,
'--frag-size-mean', '10000',
'--frag-size-sd', '9000',
'--barcode-total', '20',
'--barcode-chunks', '2',
'--seq-depth', '5e3',
genome_table, abund_table, output_prefix)
assert ret.success
validate_fastq(output_prefix)
| {
"alphanum_fraction": 0.5725714286,
"author": null,
"avg_line_length": 39.4736842105,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "682dbbf6c1181e9b68cd73716d0576e6507b3bfb",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-13T12:40:39.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-13T12:40:39.000Z",
"max_forks_repo_head_hexsha": "9edae3c170cf5100b3408a853a87e1205e70dd1b",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nick-youngblut/MGSIM",
"max_forks_repo_path": "tests/test_HtReads.py",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "9edae3c170cf5100b3408a853a87e1205e70dd1b",
"max_issues_repo_issues_event_max_datetime": "2022-02-03T14:58:13.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-11-13T13:04:47.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "nick-youngblut/MGSIM",
"max_issues_repo_path": "tests/test_HtReads.py",
"max_line_length": 74,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "9edae3c170cf5100b3408a853a87e1205e70dd1b",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nick-youngblut/MGSIM",
"max_stars_repo_path": "tests/test_HtReads.py",
"max_stars_repo_stars_event_max_datetime": "2021-12-13T15:59:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-09-02T11:03:40.000Z",
"num_tokens": 1225,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 5250
} |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# cell_markers: region,endregion
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.4.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # <center>Data Mining Project 2 Spring semester 2019-2020</center>
# ## <center>Παναγιώτης Ευαγγελίου   1115201500039</center>
# ## <center>Γεώργιος Μαραγκοζάκης   1115201500089</center>
# ___
# ### Do all the necessary imports for this notebook
# region
# data processing
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold, GridSearchCV
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
from nltk.corpus import stopwords as nltkStopwords
from string import punctuation, digits
import re
from nltk import word_tokenize
from nltk.stem import PorterStemmer
# visualization
from wordcloud import WordCloud
from IPython.display import Image
from IPython.display import display
from itertools import cycle
import matplotlib.patches as mpatches
# classification
from sklearn.model_selection import KFold, cross_validate
from sklearn import svm, preprocessing
from sklearn.metrics import classification_report, make_scorer, accuracy_score, \
precision_score, recall_score, f1_score, roc_curve, auc,\
roc_auc_score, plot_roc_curve
from sklearn.ensemble import RandomForestClassifier
from sklearn.naive_bayes import GaussianNB
import matplotlib.pyplot as plt
from sklearn.multiclass import OneVsRestClassifier
from sklearn.preprocessing import label_binarize
import scipy
from collections import Counter
import gensim
import random
from operator import add
# vectorization
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
# clustering
from nltk.cluster import KMeansClusterer, cosine_distance
from sklearn.decomposition import PCA
from sklearn.decomposition import TruncatedSVD
# for data exploration
import os
import numpy as np
# endregion
# ## __Dataset Preprocessing__
# - ### *Make tsv files from all the txt files*
# region
myCategoriesFolder = ['business','entertainment','politics', 'sport', 'tech']
dataPathDir = './fulltext/data/'
myDataSetDf = pd.DataFrame(columns=['ID', 'TITLE', 'CONTENT', 'CATEGORY'])
id_count = 0
for category in myCategoriesFolder:
specificPath = dataPathDir + category + '/'
# find the column's names of each csv
for fileName in os.listdir(specificPath):
# we need to check only .txt files
if fileName.endswith(".txt"):
thisTxt = open(os.path.join(specificPath, fileName),"r")
thisTxtTitle = thisTxt.readline()
# get rid of '\n' on the end of title line
thisTxtTitle = thisTxtTitle.replace('\n', '')
thisTxtContent = thisTxt.readlines()
# get rid of empty lines '\n'
thisTxtContent = list(filter(lambda a: a != '\n', thisTxtContent))
# get rid of '\n' on the end of each line
thisTxtContent = [period.replace('\n', '') for period in thisTxtContent]
# convert list of lines into a single string line
thisTxtContent = ' '.join(thisTxtContent)
myDataSetDf = myDataSetDf.append({'ID': id_count, 'TITLE': thisTxtTitle, 'CONTENT': thisTxtContent, 'CATEGORY': category.upper()}, ignore_index=True)
thisTxt.close()
id_count += 1
display(myDataSetDf)
# endregion
# ## __Make wordcloud for each category__
def makeWordCloud(myText, saveLocationPath, myMaxWords=100, myMask=None, myStopWords=None):
'''Default function for generating wordcloud'''
wc = WordCloud(background_color="white", mask=myMask, max_words=myMaxWords,
stopwords=myStopWords, contour_width=3, contour_color='steelblue',
width=600, height=600)
# generate word cloud
wc.generate(myText)
# store to file
wc.to_file(saveLocationPath)
return saveLocationPath
def columnToText(myDfColumn):
wholeColumnText = ''
for text in myDfColumn:
wholeColumnText = wholeColumnText + ' ' + text
return wholeColumnText
stopWords = ENGLISH_STOP_WORDS
myAdditionalStopWords = ['say','said', 'new', 'need', 'year']
stopWords = (stopWords.union(myAdditionalStopWords))
# - ### *Business Wordcloud*
# region
makeWordCloud(saveLocationPath="businessWordCloud.png", myText=columnToText(myDataSetDf[myDataSetDf['CATEGORY'] == "BUSINESS"]['CONTENT']), myStopWords=stopWords)
Image('businessWordCloud.png')
# endregion
# - ### *Entertainment Wordcloud*
# region
makeWordCloud(saveLocationPath="entertainmentWordCloud.png", myText=columnToText(myDataSetDf[myDataSetDf['CATEGORY'] == "ENTERTAINMENT"]['CONTENT']), myStopWords=stopWords)
Image('entertainmentWordCloud.png')
# endregion
# - ### *Politics Wordcloud*
# region
makeWordCloud(saveLocationPath="politicsWordCloud.png", myText=columnToText(myDataSetDf[myDataSetDf['CATEGORY'] == "POLITICS"]['CONTENT']), myStopWords=stopWords)
Image('politicsWordCloud.png')
# endregion
# - ### *Sport Wordcloud*
# region
makeWordCloud(saveLocationPath="sportWordCloud.png", myText=columnToText(myDataSetDf[myDataSetDf['CATEGORY'] == "SPORT"]['CONTENT']), myStopWords=stopWords)
Image('sportWordCloud.png')
# endregion
# - ### *Tech Wordcloud*
# region
makeWordCloud(saveLocationPath="techWordCloud.png", myText=columnToText(myDataSetDf[myDataSetDf['CATEGORY'] == "TECH"]['CONTENT']), myStopWords=stopWords)
Image('techWordCloud.png')
# endregion
# ## __Classification__
def scoresReportCv(clf, trainX, trainY):
"""
Printing scores using cross_val_score
"""
print('----Report for 10-fold Cross Validation----')
scoring = {'Accuracy' : make_scorer(accuracy_score),
'Precision' : make_scorer(precision_score, average='weighted'),
'Recall' : make_scorer(recall_score, average='weighted'),
'F1' : make_scorer(f1_score, average='weighted')}
scores = cross_validate(clf, trainX, trainY, cv=10, scoring=scoring)
print ('Precision \t %0.2f' % (scores['test_Precision'].mean()))
print ('Recalls \t %0.2f' % (scores['test_Recall'].mean()))
print ('F-Measure \t %0.2f' % (scores['test_F1'].mean()))
print("Accuracy: \t %0.2f (+/- %0.2f)" % (scores['test_Accuracy'].mean(), scores['test_Accuracy'].std() * 2))
def makeRocPlot(labelTest, predictions, labelEncoder, mySubplots = None):
# Binarize the output
labelsAsNumber = [i for i in range(0,len(labelEncoder.classes_))]
labelTest = label_binarize(labelTest, classes=labelsAsNumber)
n_classes = labelTest.shape[1]
# Compute ROC curve and ROC area for each class
fpr = dict()
tpr = dict()
roc_auc = dict()
for i in range(n_classes):
fpr[i], tpr[i], _ = roc_curve(labelTest[:, i], predictions[:, i])
roc_auc[i] = auc(fpr[i], tpr[i])
# Compute micro-average ROC curve and ROC area
fpr["micro"], tpr["micro"], _ = roc_curve(labelTest.ravel(), predictions.ravel())
roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])
# First aggregate all false positive rates
all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_classes)]))
# Then interpolate all ROC curves at this points
mean_tpr = np.zeros_like(all_fpr)
for i in range(n_classes):
mean_tpr += np.interp(all_fpr, fpr[i], tpr[i])
# Finally average it and compute AUC
mean_tpr /= n_classes
fpr["macro"] = all_fpr
tpr["macro"] = mean_tpr
roc_auc["macro"] = auc(fpr["macro"], tpr["macro"])
lw = 2
if mySubplots is not None: # subplots for 10-CV
# Plot all ROC curves
mySubplots.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]),
color='deeppink', linestyle=':', linewidth=4)
mySubplots.plot(fpr["macro"], tpr["macro"],
label='macro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["macro"]),
color='navy', linestyle=':', linewidth=4)
colors = cycle(['aqua', 'darkorange', 'cornflowerblue', 'forestgreen', 'maroon'])
for i, color in zip(range(n_classes), colors):
mySubplots.plot(fpr[i], tpr[i], color=color, lw=lw,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(labelEncoder.classes_[i], roc_auc[i]))
mySubplots.plot([0, 1], [0, 1], 'k--', lw=lw)
mySubplots.axis(xmin=0.0,xmax=1.0, ymin=0.0, ymax=1.05)
mySubplots.set_xlabel('False Positive Rate')
mySubplots.set_ylabel('True Positive Rate')
mySubplots.legend(loc="lower right")
else:
# Plot all ROC curves
plt.figure(figsize=(12, 12))
plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]),
color='deeppink', linestyle=':', linewidth=4)
plt.plot(fpr["macro"], tpr["macro"],
label='macro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["macro"]),
color='navy', linestyle=':', linewidth=4)
colors = cycle(['aqua', 'darkorange', 'cornflowerblue', 'forestgreen', 'maroon'])
for i, color in zip(range(n_classes), colors):
plt.plot(fpr[i], tpr[i], color=color, lw=lw,
label='ROC curve of class {0} (area = {1:0.2f})'
''.format(labelEncoder.classes_[i], roc_auc[i]))
plt.plot([0, 1], [0, 1], 'k--', lw=lw)
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('ROC plot of all classes')
plt.legend(loc="lower right")
def makeRocPlotsCV (clf, trainX, trainY, labelEncoder):
# make rocPlots for each fold in 10 CV
f, axs = plt.subplots(5, 2)
f.set_figheight(30)
f.set_figwidth(30)
# Run classifier with cross-validation and plot ROC curves
cv = StratifiedKFold(n_splits=10)
i = 0
z = 0
k = 1
for train, test in cv.split(trainX, trainY):
y_score = clf.fit(trainX[train], trainY[train]).predict_proba(trainX[test])
makeRocPlot(trainY[test], y_score, labelEncoder, axs[i, z])
axs[i, z].set_title('Roc Plot for fold - {0}'.format(k))
k += 1
if z == 1:
i += 1
z = 0
else:
z = 1
plt.show()
# - #### Classification using SVM classifier
def SvmClassification(trainX, trainY, testX, testY, labelEncoder):
"""
Classify the text using the SVM classifier of scikit-learn
"""
clf = svm.SVC(kernel='linear', C=1, probability=True)
# use 10-fold Cross Validation
scoresReportCv(clf, trainX, trainY)
print('----Roc Plots for 10-fold Cross Validation----')
makeRocPlotsCV (clf, trainX, trainY, labelEncoder)
# fit train set
clf.fit(trainX, trainY)
# Predict test set
predY = clf.predict(testX)
# Classification_report
print('\n----Report for predictions on test dataset----')
print(classification_report(testY, predY, target_names=list(labelEncoder.classes_)))
print('\n----ROC plot for predictions on test dataset----')
y_score = clf.predict_proba(testX)
makeRocPlot(testY, y_score, labelEncoder)
plt.show()
return accuracy_score(testY, predY)
# we will use gridSearchCV with svm only one time for demonstration as it is slow
def SvmClassificationGridSearchCVDemo(trainX, trainY, testX, testY, labelEncoder):
"""
Classify the text using the SVM classifier of scikit-learn with gridSearchCV
"""
parameters = {'kernel':('linear', 'rbf'), 'C':[0.1, 1, 10], 'gamma':('scale', 'auto')}
svc = svm.SVC(probability=True)
clf = GridSearchCV(svc, parameters, n_jobs = -1)
# fit train set
clf.fit(trainX, trainY)
# Predict test set
predY = clf.predict(testX)
# Classification_report
print('\n----Report for predictions on test dataset with GridSearchCV----')
print(classification_report(testY, predY, target_names=list(labelEncoder.classes_)))
print('\n----ROC plot for predictions on test dataset with GridSearchCV----')
y_score = clf.predict_proba(testX)
makeRocPlot(testY, y_score, labelEncoder)
plt.show()
# - #### Classification using Random Forests classifier
def RandomForestClassification(trainX, trainY, testX, testY, labelEncoder):
"""
Classify the text using the Random Forest classifier of scikit-learn
"""
clf = RandomForestClassifier()
# use 10-fold Cross Validation
scoresReportCv(clf, trainX, trainY)
print('----Roc Plots for 10-fold Cross Validation----')
makeRocPlotsCV (clf, trainX, trainY, labelEncoder)
# fit train set
clf.fit(trainX, trainY)
# Predict test set
predY = clf.predict(testX)
# Classification_report
print('\n----Report for predictions on test dataset----')
print(classification_report(testY, predY, target_names=list(labelEncoder.classes_)))
print('\n----ROC plot for predictions on test dataset----')
y_score = clf.predict_proba(testX)
makeRocPlot(testY, y_score, labelEncoder)
plt.show()
return accuracy_score(testY, predY)
# - #### Classification using Naive Bayes classifier
def NaiveBayesClassification(trainX, trainY, testX, testY, labelEncoder):
"""
Classify the text using the Naive Bayes classifier of scikit-learn
"""
clf = GaussianNB()
trainX = trainX.toarray()
# use 10-fold Cross Validation
scoresReportCv(clf, trainX, trainY)
print('----Roc Plots for 10-fold Cross Validation----')
makeRocPlotsCV (clf, trainX, trainY, labelEncoder)
# fit train set
clf.fit(trainX, trainY)
# Predict test set
testX = testX.toarray()
predY = clf.predict(testX)
# Classification_report
print('\n----Report for predictions on test dataset----')
print(classification_report(testY, predY, target_names=list(labelEncoder.classes_)))
print('\n----ROC plot for predictions on test dataset----')
y_score = clf.predict_proba(testX)
makeRocPlot(testY, y_score, labelEncoder)
plt.show()
return accuracy_score(testY, predY)
# - #### Classification using K-Nearest Neighbor classifier
# Our implemantion is based on this link https://towardsdatascience.com/k-nearest-neighbor-classifier-from-scratch-in-python-698e3de97063
# and this link https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/
# region
# calculate the Euclidean distance between two 1d-arrays
def distance(instance1, instance2):
return scipy.spatial.distance.euclidean(instance1, instance2)
def get_neighbors(training_set,
labels,
test_instance,
k,
distance=distance):
"""
get_neighors calculates a list of the k nearest neighbors
of an instance 'test_instance'.
The list neighbors contains 3-tuples with
(index, dist, label)
where
index is the index from the training_set,
dist is the distance between the test_instance and the
instance training_set[index]
distance is a reference to a function used to calculate the
distances
"""
distances = []
for index in range(len(training_set)):
dist = distance(test_instance, training_set[index])
distances.append((training_set[index], dist, labels[index]))
distances.sort(key=lambda x: x[1])
neighbors = distances[:k]
return neighbors
# The function 'vote' returns the most common class. (Majority Voting)
def vote(neighbors):
class_counter = Counter()
for neighbor in neighbors:
class_counter[neighbor[2]] += 1
return class_counter.most_common(1)[0][0]
# ‘vote_prob’ is a function like ‘vote’ but returns the probability for all classes (like clf.predict_proba())
def vote_prob(neighbors):
class_counter = Counter()
for neighbor in neighbors:
class_counter[neighbor[2]] += 1
labels, votes = zip(*class_counter.most_common())
probabilityArray = votesToProbability(class_counter.most_common(), sum(votes))
return probabilityArray
def votesToProbability(tuplesList, totalVotes):
# tuplesList is of form [(num1,num2), (num1,num2), ...] where num1 is the label and num2 is the number of votes for this label
labelVotesDict = dict(tuplesList)
numOfClasses = 5
probabilityArray = []
for i in range(0,numOfClasses):
if i in labelVotesDict: # calculate probability
probabilityArray.append(labelVotesDict[i] / totalVotes)
else: # this label doesn't exist in the dictionary so its probability is 0
probabilityArray.append(0)
return np.asarray(probabilityArray)
# Make a prediction with neighbors
def predict_classification(training_set, labels, test_instance, k, distance=distance):
neighbors = get_neighbors(training_set, labels, test_instance, k, distance=distance)
prediction = vote(neighbors)
return prediction
# Make a prediction probability with neighbors
def predict_proba_classification(training_set, labels, test_instance, k, distance=distance):
neighbors = get_neighbors(training_set, labels, test_instance, k, distance=distance)
prediction_proba = vote_prob(neighbors)
return prediction_proba
# kNN Algorithm
def k_nearest_neighbors(trainX, trainY, testX, num_neighbors):
predictions = list()
for row in testX:
output = predict_classification(trainX, trainY, row, num_neighbors, distance=distance )
predictions.append(output)
return(predictions)
# kNN Algorithm probability predictions
def k_nearest_neighbors_proba(trainX, trainY, testX, num_neighbors):
predictions_proba = list()
for row in testX:
output = predict_proba_classification(trainX, trainY, row, num_neighbors, distance=distance )
predictions_proba.append(output)
return(predictions_proba)
# Evaluate an algorithm using a cross validation split
# Specific evaluation for our knn algorithm
def evaluate_algorithm(trainX, trainY, n_folds, labelEncoder):
# make rocPlots for each fold in 10 CV
f, axs = plt.subplots(5, 2)
f.set_figheight(30)
f.set_figwidth(30)
scoresAccuracy = list()
scoresPrecision = list()
scoresRecall = list()
scoresF1 = list()
cv = StratifiedKFold(n_splits=10)
i = 0
z = 0
k = 1
for train, test in cv.split(trainX, trainY):
predictions = k_nearest_neighbors(trainX[train], trainY[train], trainX[test], 100)
predY = np.asarray(predictions)
scoresAccuracy.append(accuracy_score(trainY[test], predY))
scoresPrecision.append(precision_score(trainY[test], predY, average='weighted'))
scoresRecall.append(recall_score(trainY[test], predY, average='weighted'))
scoresF1.append(f1_score(trainY[test], predY, average='weighted'))
# make roc plot for this fold
predictions_proba = k_nearest_neighbors_proba(trainX[train], trainY[train], trainX[test], 100)
predY_proba = np.asarray(predictions_proba)
makeRocPlot(trainY[test], predY_proba, labelEncoder, axs[i, z])
axs[i, z].set_title('Roc Plot for fold - {0}'.format(k))
k += 1
if z == 1:
i += 1
z = 0
else:
z = 1
plt.show()
scores = {'Accuracy':scoresAccuracy, 'Precision':scoresPrecision, 'Recall':scoresRecall, 'F1':scoresF1}
return scores
def KnnClassification(trainX, trainY, testX, testY, labelEncoder):
"""
Classify the text using the KNN classifier we implemented
"""
trainXarray = trainX.toarray()
testXarray = testX.toarray()
print('\n----10 Fold Cross Validation Evaluation----')
# evaluate algorithm
n_folds = 10
scores = evaluate_algorithm(trainXarray, trainY, n_folds, labelEncoder)
print ('Precision \t %0.2f' % (sum(scores['Precision'])/float(len(scores['Precision']))))
print ('Recalls \t %0.2f' % (sum(scores['Recall'])/float(len(scores['Recall']))))
print ('F-Measure \t %0.2f' % (sum(scores['F1'])/float(len(scores['F1']))))
print('Accuracy: \t %0.2f' % (sum(scores['Accuracy'])/float(len(scores['Accuracy']))))
# Classification_report
predictions = k_nearest_neighbors(trainXarray, trainY, testXarray, 100)
predY = np.asarray(predictions)
print('\n----Report for predictions on test dataset----')
print(classification_report(testY, predY, target_names=list(labelEncoder.classes_)))
predictions_proba = k_nearest_neighbors_proba(trainXarray, trainY, testXarray, 100)
predY_proba = np.asarray(predictions_proba)
print('\n----ROC plot for predictions on test dataset----')
makeRocPlot(testY, predY_proba, labelEncoder)
plt.show()
return accuracy_score(testY, predY)
# endregion
# - ### *Split DataSet into TrainData and TestData*
# region
trainDataSet, testDataSet = train_test_split(myDataSetDf, test_size=0.2, stratify=myDataSetDf['CATEGORY'])
# reset index
trainDataSet.reset_index(drop=True, inplace=True)
testDataSet.reset_index(drop=True, inplace=True)
# save to tsv files
trainDataSet.to_csv('train_set.tsv', sep = '\t')
# save test_set categories
testDataSetCategories = testDataSet[['CATEGORY']].copy()
testDataSetCategories.to_csv('test_set_categories.tsv', sep = '\t')
testDataSet = testDataSet.drop('CATEGORY', axis=1)
testDataSet.to_csv('test_set.tsv', sep = '\t')
# endregion
# Prepare train and test data that we will need below
# region
# build label encoder for categories
le = preprocessing.LabelEncoder()
le.fit(trainDataSet["CATEGORY"])
# transform categories into numbers
trainY = le.transform(trainDataSet["CATEGORY"])
testY = le.transform(testDataSetCategories["CATEGORY"])
accuracyDict = dict()
# endregion
# ## __Vectorization__
# Let's do classification using 2 different ways of vectorization
# region language="javascript"
# IPython.OutputArea.prototype._should_scroll = function(lines) {
# return false;
# }
# endregion
# - #### Bag-of-words vectorization
# region
bowVectorizer = CountVectorizer(max_features=1000)
trainX = bowVectorizer.fit_transform(trainDataSet['CONTENT'])
testX = bowVectorizer.transform(testDataSet['CONTENT'])
print('-------------SVM Classification with BOW Vectorization-------------')
accuracyDict["BOW-SVM"] = SvmClassification(trainX, trainY, testX, testY, le)
print('-------------SVM Classification with BOW Vectorization and GridSearchCV for demonstration-------------')
SvmClassificationGridSearchCVDemo(trainX, trainY, testX, testY, le)
print('\n-------------Random Forests Classification with BOW Vectorization-------------')
accuracyDict["BOW-RandomForests"] = RandomForestClassification(trainX, trainY, testX, testY, le)
print('\n-------------Naive Bayes Classification with BOW Vectorization-------------')
accuracyDict["BOW-NB"] = NaiveBayesClassification(trainX, trainY, testX, testY, le)
print('\n-------------K Nearest Neighbor Classification with BOW Vectorization-------------')
accuracyDict["BOW-knn"] = KnnClassification(trainX, trainY, testX, testY, le)
# endregion
# - #### Tf-idf vectorization
# region
tfIdfVectorizer = TfidfVectorizer(max_features=1000)
trainX = tfIdfVectorizer.fit_transform(trainDataSet['CONTENT'])
testX = tfIdfVectorizer.transform(testDataSet['CONTENT'])
print('-------------SVM Classification with TfIdf Vectorization-------------')
accuracyDict["TfIdf-SVM"] = SvmClassification(trainX, trainY, testX, testY, le)
print('\n-------------Random Forests Classification with TfIdf Vectorization-------------')
accuracyDict["TfIdf-RandomForests"] = RandomForestClassification(trainX, trainY, testX, testY, le)
print('\n-------------Naive Bayes Classification with TfIdf Vectorization-------------')
accuracyDict["TfIdf-NB"] = NaiveBayesClassification(trainX, trainY, testX, testY, le)
print('\n-------------K Nearest Neighbor Classification with TfIdf Vectorization-------------')
accuracyDict["TfIdf-knn"] = KnnClassification(trainX, trainY, testX, testY, le)
# endregion
# #### Results Summary
# region
resultsData = {r'Vectorizer \ Classifier': ['BOW', 'Tfidf'],
'SVM': [accuracyDict["BOW-SVM"], accuracyDict["TfIdf-SVM"]],
'Random Forest': [accuracyDict["BOW-RandomForests"], accuracyDict["TfIdf-RandomForests"]],
'Naive Bayes': [accuracyDict["BOW-NB"], accuracyDict["TfIdf-NB"]],
'K Nearest Neighbor': [accuracyDict["BOW-knn"], accuracyDict["TfIdf-knn"]]}
resultsDataFrame = pd.DataFrame(data=resultsData)
resultsDataFrame
# endregion
# ## __Beat the Benchmark (bonus)__
# region
def preprocessText(initText):
"""Preprocess the text"""
# Make everything to lower case
processedText = initText.lower()
# Remove urls
processedText = re.sub(r'(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-z0-9]+([\-\.]{1}[a-z0-9]+)'
r'*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?', ' ', processedText)
# Remove any punctuation from the text
for c in punctuation:
processedText = processedText.replace(c, ' ')
# Remove digits
processedText = re.sub(r'\d+', '', processedText)
# Remove consecutive spaces
processedText = re.sub(r" {2,}", ' ', processedText)
# Split to words
tokens = word_tokenize(processedText)
# Remove sropwords
stopWords = ENGLISH_STOP_WORDS
stopWords = (stopWords.union(nltkStopwords.words('english')))
filtered = [w for w in tokens if w not in stopWords]
# Concat the remaining words in a single string again
if not filtered: # list is empty
processedText = ''
else:
processedText = filtered[0]
for word in filtered[1:]:
processedText = processedText + ' ' + word
return processedText
def stemmingPreprocess(initText):
# Split to words
tokens = word_tokenize(initText)
# Do the stemming
stemmer = PorterStemmer()
stems = [stemmer.stem(token) for token in tokens]
# Concat the remaining words in a single string again
if not stems: # list is empty
processedText = ''
else:
processedText = stems[0]
for stem in stems[1:]:
processedText = processedText + ' ' + stem
return processedText
# endregion
# Let's do some preprocessing for train and test data
# region
trainDataPreprocessed = trainDataSet.copy()
testDataPreprocessed = testDataSet.copy()
# preprocess train data
for index, row in trainDataPreprocessed.iterrows():
initialText = row["CONTENT"]
trainDataPreprocessed.iloc[index]["CONTENT"] = preprocessText(initialText)
# preprocess test data
for index, row in testDataPreprocessed.iterrows():
initialText = row["CONTENT"]
testDataPreprocessed.iloc[index]["CONTENT"] = preprocessText(initialText)
# endregion
# Let's do stemming
# region
for index, row in trainDataPreprocessed.iterrows():
initialText = row["CONTENT"]
trainDataPreprocessed.iloc[index]["CONTENT"] = stemmingPreprocess(initialText)
for index, row in testDataPreprocessed.iterrows():
initialText = row["CONTENT"]
testDataPreprocessed.iloc[index]["CONTENT"] = stemmingPreprocess(initialText)
# endregion
# We will check only the SVM classifier with Tf-idf vectorization
# region
tfIdfVectorizer = TfidfVectorizer(max_features=1000)
trainX = tfIdfVectorizer.fit_transform(trainDataPreprocessed['CONTENT'])
testX = tfIdfVectorizer.transform(testDataPreprocessed['CONTENT'])
print('\n-------------SVM Classification with TfIdf Vectorization in processed text-------------')
accuracyDict["TfIdf-SVM-processed"] = SvmClassification(trainX, trainY, testX, testY, le)
# endregion
# Let's compare scores
# region
resultsDataCompare = {'SVM without preprocessing': [accuracyDict["TfIdf-SVM"]],
'SVM with preprocessing': [accuracyDict["TfIdf-SVM-processed"]]}
resultsCompareDataFrame = pd.DataFrame(data=resultsDataCompare)
resultsCompareDataFrame
# endregion
# As we see there is no big difference between scores for max_features=1000 in TfidfVectorizer.
# Let's check what happens for max_features=100
tfIdfVectorizer = TfidfVectorizer(max_features=100)
# region
trainX = tfIdfVectorizer.fit_transform(trainDataSet['CONTENT'])
testX = tfIdfVectorizer.transform(testDataSet['CONTENT'])
print('-------------SVM Classification with TfIdf Vectorization for max_features=100-------------')
accuracyDict["TfIdf-SVM-100"] = SvmClassification(trainX, trainY, testX, testY, le)
# endregion
# region
trainX = tfIdfVectorizer.fit_transform(trainDataPreprocessed['CONTENT'])
testX = tfIdfVectorizer.transform(testDataPreprocessed['CONTENT'])
print('\n-------------SVM Classification with TfIdf Vectorization in processed text for max_features=100-------------')
accuracyDict["TfIdf-SVM-processed-100"] = SvmClassification(trainX, trainY, testX, testY, le)
# endregion
# Let's compare scores one more time
# region
resultsDataCompare = {'SVM without preprocessing for max_features=100': [accuracyDict["TfIdf-SVM-100"]],
'SVM with preprocessing for max_features=100': [accuracyDict["TfIdf-SVM-processed-100"]]}
resultsCompareDataFrame = pd.DataFrame(data=resultsDataCompare)
resultsCompareDataFrame
# endregion
# Here we can see a significant difference.
# ## __Clustering__
def KmeansClustering(trainX, numberOfClusters, numberOfRepeats):
# init cluster with trainX
# example taken from https://www.nltk.org/_modules/nltk/cluster/kmeans.html#demo
clusterer = KMeansClusterer(numberOfClusters, cosine_distance, initial_means=None, repeats=numberOfRepeats)
assigned_clusters = clusterer.cluster(trainX, assign_clusters=True)
return clusterer, assigned_clusters
# - #### Compression using PCA method
def principalComponentAnalysis(nComponents, trainX, labels, clusters):
# reduce the features to 2D
random_state = 0
pca = PCA(n_components=nComponents, random_state=random_state)
#reduced_features = pca.fit_transform(trainX.toarray())
reduced_features = pca.fit_transform(trainX)
# reduce the cluster centers to 2D
reduced_cluster_centers = pca.transform(labels._means)
# assign specific marker shape for each true category
markers = ["o" , "v" , "P" , "s", "*"]
colors = ["tab:blue" , "tab:orange" , "tab:green" , "tab:red", "tab:purple"]
specificMarkers = list()
specificColors = list()
for i in range(0,trainX.shape[0]):
specificMarkers.append(markers[trainY[i]])
specificColors.append(colors[clusters[i]])
plt.figure(figsize=(12, 12))
xArray = reduced_features[:,0]
yArray = reduced_features[:,1]
for i in range(0,len(clusters)):
plt.scatter(xArray[i], yArray[i], marker=specificMarkers[i], c=specificColors[i])
plt.scatter(reduced_cluster_centers[:, 0], reduced_cluster_centers[:,1], marker='x', s=150, c='b')
patchList = []
for i in range(0,len(markers)):
patchList.append(plt.plot([],[], color='black', marker=markers[i], label=le.classes_[i], ls="")[0])
plt.legend(handles=patchList)
plt.show()
# - #### Compression using SVD method
def singularValueDecomposition(nComponents, trainX, labels, clusters):
# reduce the features to 2D
random_state = 0
svd = TruncatedSVD(n_components=nComponents, random_state=random_state)
#reduced_features = svd.fit_transform(trainX.toarray())
reduced_features = svd.fit_transform(trainX)
# reduce the cluster centers to 2D
reduced_cluster_centers = svd.transform(labels._means)
# assign specific marker shape for each true category
markers = ["o" , "v" , "P" , "s", "*"]
colors = ["tab:blue" , "tab:orange" , "tab:green" , "tab:red", "tab:purple"]
specificMarkers = list()
specificColors = list()
for i in range(0,trainX.shape[0]):
specificMarkers.append(markers[trainY[i]])
specificColors.append(colors[clusters[i]])
plt.figure(figsize=(12, 12))
xArray = reduced_features[:,0]
yArray = reduced_features[:,1]
for i in range(0,len(clusters)):
plt.scatter(xArray[i], yArray[i], marker=specificMarkers[i], c=specificColors[i])
plt.scatter(reduced_cluster_centers[:, 0], reduced_cluster_centers[:,1], marker='x', s=150, c='b')
patchList = []
for i in range(0,len(markers)):
patchList.append(plt.plot([],[], color='black', marker=markers[i], label=le.classes_[i], ls="")[0])
plt.legend(handles=patchList)
plt.show()
# - #### Bag-of-words vectorization
# region
bowVectorizer = CountVectorizer(max_features=1000)
trainX = bowVectorizer.fit_transform(trainDataSet['CONTENT'])
# convert trainX into list of arrays
vectorsTrainX = [np.array(f) for f in trainX.toarray()]
labels, clusters = KmeansClustering(vectorsTrainX, 5, 20)
print('\n-------------Kmeans Clustering with Bag-of-words Vectorization compressing using PCA method-------------')
principalComponentAnalysis(2, trainX.toarray(), labels, clusters)
print('\n-------------Kmeans Clustering with Bag-of-words Vectorization compressing using SVD method-------------')
singularValueDecomposition(2, trainX.toarray(), labels, clusters)
# endregion
# - #### Tf-idf vectorization
# region
tfIdfVectorizer = TfidfVectorizer(max_features=1000)
trainX = tfIdfVectorizer.fit_transform(trainDataSet['CONTENT'])
# convert trainX into list of arrays
vectorsTrainX = [np.array(f) for f in trainX.toarray()]
labels, clusters = KmeansClustering(vectorsTrainX, 5, 40)
print('\n-------------Kmeans Clustering with TfIdf Vectorization compressing using PCA method-------------')
principalComponentAnalysis(2, trainX.toarray(), labels, clusters)
print('\n-------------Kmeans Clustering with TfIdf Vectorization compressing using SVD method-------------')
singularValueDecomposition(2, trainX.toarray(), labels, clusters)
# endregion
# - #### Word embeddings vectorization
# Read pre-trained Word Embeddings
# Load Google's pre-trained Word2Vec model.
model_w2v = gensim.models.KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin', binary=True)
vec_size = 300
# region
def sample_floats(low=-1.0, high=1.0, k=1):
"""
Return a k-length list of unique random floats in the range of low <= x <= high
"""
result = []
seen = set()
for i in range(k):
x = random.uniform(low, high)
while x in seen:
x = random.uniform(low, high)
seen.add(x)
result.append(x)
return result
def wordEmbeddingsVectorizer(data):
"""
Vectorize the data based on the model we loaded.
"""
text_vec = []
for index, row in data.iterrows():
text = row['CONTENT']
text_len = len(text)
if text_len == 0:
article_vec = sample_floats(-5.0, 5.0, vec_size)
text_vec.append(article_vec)
continue
tokens = word_tokenize(text)
if tokens[0] in model_w2v.vocab:
article_vec = model_w2v[tokens[0]]
else:
article_vec = sample_floats(-5.0, 5.0, vec_size)
for token in tokens[1:]:
if token in model_w2v.vocab:
article_vec = list(map(add, article_vec, model_w2v[token]))
else:
article_vec = list(map(add, article_vec, sample_floats(-5.0, 5.0, vec_size)))
final_article_vec = [i / text_len for i in article_vec]
text_vec.append(final_article_vec)
return np.array(text_vec)
# endregion
# region
trainX = wordEmbeddingsVectorizer(trainDataSet)
# convert trainX, testX into list of arrays
vectorsTrainX = [np.array(f) for f in trainX]
labels, clusters = KmeansClustering(vectorsTrainX, 5, 40)
print('\n-------------Kmeans Clustering with Word embeddings Vectorization compressing using PCA method-------------')
principalComponentAnalysis(2, trainX, labels, clusters)
print('\n-------------Kmeans Clustering with Word embeddings Vectorization compressing using SVD method-------------')
singularValueDecomposition(2, trainX, labels, clusters)
# endregion
# **Σχόλια και παρατηρήσεις**
# - Έχουν υλοποιηθεί όλα τα ζητούμενα της εκφώνησης εκτός από το ICA στο bonus των μεθόδων συμπίεσης. Υλοποιήθηκε
# η PCA και η SVD.
# - Το beat the benchmark bonus έχει υλοποιηθεί.
# - Όσον αφορά το παραπάνω, το score για max_features=1000 στους Vectorizers είναι ήδη πολύ υψηλό, οπότε δεν υπάρχουν
# πολλά περιθώρια βελτίωσης και επομένως δεν βλέπουμε μεγάλη διαφορά. Για το λόγο αυτό γίνεται σύγκριση και για
# max_features=100 όπου εκεί η διαφορά είναι πιο φανερή.
# - Όσον αφορά την χρήση της GridSearchCV για την εύρεση των καλύτερων παραμέτρων στον αλγόριθμο SVM, την χρησιμοποιούμε
# μια φορά για demonstration διότι η χρήση του καθυστερεί τον χρόνο εκτέλεσης του προγράμματος μια και η λογική πίσω
# από αυτό είναι ο brute force συνδυασμός των διάφορων παραμέτρων.
# - Στο 10 fold cross validation παρουσιάζεται το roc plot για κάθε fold.
# - Η υλοποίηση του αλγορίθμου KNN έγινε με βάση τα link που αναφέρονται
# (https://towardsdatascience.com/k-nearest-neighbor-classifier-from-scratch-in-python-698e3de97063
# και https://machinelearningmastery.com/tutorial-to-implement-k-nearest-neighbors-in-python-from-scratch/).
# Παρόλα αυτά χρειάστηκαν να γίνουν πάρα πολλές αλλαγές/επεμβάσεις καθώς και γράψιμο νέου κώδικα.
# - Ιδιαίτερα αξίζει να σημειωθεί η υλοποίηση της συνάρτησης που υπολογίζει τις πιθανότητες (k_nearest_neighbors_proba())
# καθώς και της συνάρτησεις με το 10 fold cross validation evaluation οι οποίες δεν υπάρχουν αυτούσιες στα προαναφερθέντα links.
# - Όσον αφορά την εμφάνιση των πραγματικών κλάσεων των κειμένων στο clustering χρησιμοποιήθηκαν σχήματα. Η αντιστοίχηση των
# σχημάτων βρίσκεται στο πάνω δεξί μέρος του διαγράμματος.
| {
"alphanum_fraction": 0.6848394519,
"author": null,
"avg_line_length": 35.1507352941,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "046dd7cb1607b4f834c9f87ca88fa9cfa0ac983a",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-08-31T15:34:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-08-31T15:34:04.000Z",
"max_forks_repo_head_hexsha": "c2d52d59131cb1180e94fa8e7c90fb74f0632c98",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "PanosEvange/DataMiningProj2_2020",
"max_forks_repo_path": "sdi1500039.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c2d52d59131cb1180e94fa8e7c90fb74f0632c98",
"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": "PanosEvange/DataMiningProj2_2020",
"max_issues_repo_path": "sdi1500039.py",
"max_line_length": 172,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c2d52d59131cb1180e94fa8e7c90fb74f0632c98",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "PanosEvange/DataMiningProj2_2020",
"max_stars_repo_path": "sdi1500039.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 10360,
"path": null,
"reason": "import numpy,import scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 38244
} |
#' Complement codes the data for use with an ART network.
#'
#' This function complement codes the given data where the complement of x is 1-x.
#' @title ART_Complement_Code
#' @param data Matrix of size NumFeatures-by-NumSamples that holds the data to be complement coded.
#' @return Data that has been complement coded. It is a matrix of size 2*NumFeatures-by-NumSamples.
#' @export
ART_Complement_Code = function(data)
{
# Determine the size of the data.
numFeatures=ncol(data);
numSamples=nrow(data);
# Create the return variable.
complementCodedData = matrix(1,numSamples,2*numFeatures);
# Do the complement coding for each sample.
for (j in 1:numSamples)
{
count = 1;
for (i in seq(1,(2*numFeatures),2))
{
complementCodedData[j,i] = data[j,count];
complementCodedData[j,i + 1] = 1 - data[j,count];
count = count + 1;
}
}
return (complementCodedData);
} | {
"alphanum_fraction": 0.6919739696,
"author": null,
"avg_line_length": 30.7333333333,
"converted": null,
"ext": "r",
"file": null,
"hexsha": "2c38fe57bdecdce4d861537f240bcb9795737675",
"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": "dc5378a742673f5279d054e7cc3bd92d601235cc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gbaquer/fuzzyARTMAP",
"max_forks_repo_path": "R/ART_Complement_Code.r",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc",
"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": "gbaquer/fuzzyARTMAP",
"max_issues_repo_path": "R/ART_Complement_Code.r",
"max_line_length": 99,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gbaquer/fuzzyARTMAP",
"max_stars_repo_path": "R/ART_Complement_Code.r",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 251,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 922
} |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 20 16:16:14 2018
@author: landrieuloic
""""""
Large-scale Point Cloud Semantic Segmentation with Superpoint Graphs
http://arxiv.org/abs/1711.09869
2017 Loic Landrieu, Martin Simonovsky
Template file for processing custome datasets
"""
from __future__ import division
from __future__ import print_function
from builtins import range
import random
import numpy as np
import os
import functools
import torch
import torchnet as tnt
import h5py
import spg
def get_datasets(args, test_seed_offset=0):
"""build training and testing set"""
all_directories = ["Lille1_1/","Lille1_2/","Paris/", "Lille2/"]
VAL_RATIO = args.val_split
# Load superpoints graphs
testlist, trainlist, validlist = [], [], []
for n in all_directories:
nameFiles = os.listdir(args.PARISLILLE3D_PATH + '/superpoint_graphs/' + n )
N_parts = len(nameFiles)
k_val = int(VAL_RATIO*N_parts)
starting_point = np.random.randint(0,N_parts-k_val-1)
k_vals = [nameFiles[i] for i in range(starting_point, starting_point+k_val)]
for k in nameFiles:
if k in k_vals:
validlist.append(spg.spg_reader(args, args.PARISLILLE3D_PATH + '/superpoint_graphs/' + n + os.path.splitext(k)[0]+'.h5', True))
testlist.append(spg.spg_reader(args, args.PARISLILLE3D_PATH + '/superpoint_graphs/' + n + os.path.splitext(k)[0]+'.h5', True))
else :
trainlist.append(spg.spg_reader(args, args.PARISLILLE3D_PATH + '/superpoint_graphs/' + n + os.path.splitext(k)[0]+ '.h5', True))
# Normalize edge features
if args.spg_attribs01:
trainlist, testlist, validlist, scaler = spg.scaler01(trainlist, testlist, validlist=validlist)
return tnt.dataset.ListDataset([spg.spg_to_igraph(*tlist) for tlist in trainlist],
functools.partial(spg.loader, train=True, args=args, db_path=args.PARISLILLE3D_PATH)), \
tnt.dataset.ListDataset([spg.spg_to_igraph(*tlist) for tlist in testlist],
functools.partial(spg.loader, train=False, args=args, db_path=args.PARISLILLE3D_PATH, test_seed_offset=test_seed_offset)) ,\
tnt.dataset.ListDataset([spg.spg_to_igraph(*tlist) for tlist in validlist],
functools.partial(spg.loader, train=False, args=args, db_path=args.PARISLILLE3D_PATH, test_seed_offset=test_seed_offset)),\
scaler
def get_datasets_inference(args, test_seed_offset=0):
"""build training and testing set"""
all_directories = ["ajaccio_2/","ajaccio_57/", "dijon_9/"]
VAL_RATIO = args.val_split
# Load superpoints graphs
inferList = []
for n in all_directories:
nameFiles = os.listdir(args.PARISLILLE3D_PATH + '/superpoint_graphs/' + n )
for k in nameFiles:
inferList.append(spg.spg_reader(args, args.PARISLILLE3D_PATH + '/superpoint_graphs/' + n + os.path.splitext(k)[0]+ '.h5', True))
# Normalize edge features
if args.spg_attribs01:
inferList, _, _, scaler = spg.scaler01(inferList, inferList)
return tnt.dataset.ListDataset([spg.spg_to_igraph(*tlist) for tlist in inferList],
functools.partial(spg.loader, train=False, args=args, db_path=args.PARISLILLE3D_PATH)), \
scaler
def get_info(args):
edge_feats = 0
for attrib in args.edge_attribs.split(','):
a = attrib.split('/')[0]
if a in ['delta_avg', 'delta_std', 'xyz']:
edge_feats += 3
else:
edge_feats += 1
if args.loss_weights == 'none':
weights = np.ones((10,),dtype='f4')
else:
weights = h5py.File(args.PARISLILLE3D_PATH + "/parsed/class_count.h5")["class_count"][:].astype('f4')
weights = weights.mean()/(weights+1e-6)
if args.loss_weights == 'sqrt':
weights = np.sqrt(weights)
weights = torch.from_numpy(weights).cuda() if args.cuda else torch.from_numpy(weights)
return {
'node_feats': 11 if args.pc_attribs=='' else len(args.pc_attribs),
'edge_feats': edge_feats,
'class_weights' : weights,
'classes': 10,
'inv_class_map': {0 :"unclassified",
1 :"ground",
2 :"building",
3 :"pole - road sign - traffic light",
4 :"bollard - small pole",
5 :"trash can",
6 :"barrier",
7 :"pedestrian",
8 :"car",
9 :"natural - vegetation"}
}
def preprocess_pointclouds(PARISLILLE3D_PATH):
""" Preprocesses data by splitting them by components and normalizing."""
class_count = np.zeros((10,),dtype='int')
for n in ["ajaccio_2/","Lille1_1/","Lille1_2/","Lille2/","Paris/","ajaccio_57/", "dijon_9/"]:
pathP = '{}/parsed/{}'.format(PARISLILLE3D_PATH, n)
pathD = '{}/features/{}'.format(PARISLILLE3D_PATH, n)
pathC = '{}/superpoint_graphs/{}'.format(PARISLILLE3D_PATH, n)
if not os.path.exists(pathP):
os.makedirs(pathP)
random.seed(0)
for file in os.listdir(pathC):
if file.endswith(".h5"):
f = h5py.File(pathD + file, 'r')
if n in ["Lille1_1/","Lille1_2/","Lille2/","Paris/"]:
labels = f['labels'][:]
hard_labels = np.argmax(labels[:,1:],1)
label_count = np.bincount(hard_labels, minlength=9)
class_count[1:] = class_count[1:] + label_count
xyz = f['xyz'][:]
#rgb = f['rgb'][:].astype(np.float)
rgb = np.empty_like(xyz)
# elpsv = np.stack([ f['xyz'][:,2][:], f['geof'][:,0][:], f['geof'][:,1][:], f['geof'][:,2][:], f['geof'][:,3][:] ], axis=1)
elpsv = np.append(f['xyz'][:,[2]][:], f['geof'][:], axis=1)
# rescale to [-0.5,0.5]; keep xyz
#warning - to use the trained model, make sure the elevation is comparable
#to the set they were trained on
#i.e. ~0 for roads and ~0.2-0.3 for builings for sema3d
# and -0.5 for floor and 0.5 for ceiling for s3dis
elpsv[:,0] /= 100 # (rough guess) #adapt
elpsv[:,1:] -= 0.5
#rgb = rgb/255.0 - 0.5
P = np.concatenate([xyz, rgb, elpsv], axis=1)
f = h5py.File(pathC + file, 'r')
numc = len(f['components'].keys())
with h5py.File(pathP + file, 'w') as hf:
for c in range(numc):
idx = f['components/{:d}'.format(c)][:].flatten()
if idx.size > 10000: # trim extra large segments, just for speed-up of loading time
ii = random.sample(range(idx.size), k=10000)
idx = idx[ii]
hf.create_dataset(name='{:d}'.format(c), data=P[idx,...])
path = '{}/parsed/'.format(PARISLILLE3D_PATH)
data_file = h5py.File(path+'class_count.h5', 'w')
data_file.create_dataset('class_count', data=class_count, dtype='int')
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Large-scale Point Cloud Semantic Segmentation with Superpoint Graphs')
parser.add_argument('--PARISLILLE3D_PATH', default='datasets/ParisLille-3D')
args = parser.parse_args()
preprocess_pointclouds(args.PARISLILLE3D_PATH)
| {
"alphanum_fraction": 0.5825293351,
"author": null,
"avg_line_length": 45.1176470588,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "96ce9e2cdcf6c8a2b22eb1c19fc91e1819f0b56a",
"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": "37424a8392dc96e6bdb4dba07383af651b9f8df9",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JulesSanchez/superpoint_graph",
"max_forks_repo_path": "learning/ParisLille3D_dataset.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "37424a8392dc96e6bdb4dba07383af651b9f8df9",
"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": "JulesSanchez/superpoint_graph",
"max_issues_repo_path": "learning/ParisLille3D_dataset.py",
"max_line_length": 160,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "37424a8392dc96e6bdb4dba07383af651b9f8df9",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JulesSanchez/superpoint_graph",
"max_stars_repo_path": "learning/ParisLille3D_dataset.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2048,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 7670
} |
#=
export IdentityOperation
export apply_operation
export domaintype
export isidentity, istranslation, ispoint
"""
IdentityOperation{S<:Real} <: AbstractSpaceSymmetryOperation{S}
Represents identity (space symmetry) operation
# Fields
* `dimension::Int`: dimension of the space on which the identity operation acts
"""
struct IdentityOperation{S<:Real} <: AbstractSpaceSymmetryOperation{S}
dimension::Int
@doc """
IdentityOperation{S}(dim::Integer) where {S<:Real}
Construct an identity operation of dimension `dim`, on coordinates of type `S`.
* 2020-08-10: Haven't figured out how to make this appear in the documentation.
"""
function IdentityOperation{S}(dim::Integer) where {S<:Real}
return new{S}(dim)
end
@doc """
IdentityOperation(S, dim::Integer)
Construct an identity operation of dimension `dim`, on coordinates of type `S`.
"""
function IdentityOperation(::Type{S}, dim::Integer) where {S<:Real}
return new{S}(dim)
end
end
## properties
"""
isidentity(arg::IdentityOperation)
Check whether the argument is an identity. Always `true`.
"""
isidentity(arg::IdentityOperation) = true
"""
istranslation(arg::IdentityOperation)
Check whether the argument is a translation operation. Always `true`.
"""
istranslation(arg::IdentityOperation) = true
"""
ispoint(arg::IdentityOperation)
Check whether the argument is a point operation. Always `true`.
"""
ispoint(arg::IdentityOperation) = true
"""
dimension(arg::IdentityOperation)
Return the spatial dimension of the identity operation.
"""
dimension(arg::IdentityOperation) = arg.dimension
function Base.hash(arg::IdentityOperation{S}, h::UInt) where S
return hash(IdentityOperation{S}, hash(arg.dimension, h))
end
## operators
function Base.:(==)(lhs::IdentityOperation{S}, rhs::IdentityOperation{S}) where S
return lhs.dimension == rhs.dimension
end
function Base.:(*)(lhs::IdentityOperation{S}, rhs::IdentityOperation{S}) where S
if dimension(lhs) != dimension(rhs)
throw(DimensionMismatch("dimensions mismatch"))
end
return lhs
end
function Base.:(*)(lhs::AbstractSpaceSymmetryOperation{S}, rhs::IdentityOperation{S}) where S
if dimension(lhs) != dimension(rhs)
throw(DimensionMismatch("dimensions mismatch"))
end
return lhs
end
function Base.:(*)(lhs::IdentityOperation{S}, rhs::AbstractSpaceSymmetryOperation{S}) where S
if dimension(lhs) != dimension(rhs)
throw(DimensionMismatch("dimensions mismatch"))
end
return rhs
end
Base.:(^)(lhs::IdentityOperation, rhs::Integer) = lhs
Base.inv(arg::IdentityOperation) = arg
## apply
"""
apply_operation(identity{S}, coordinate::AbstractArray{S}) where {S<:Real}
Do nothing.
"""
function apply_operation(symop::IdentityOperation{S}, arg::AbstractArray{S}) where {S<:Real}
if dimension(symop) != size(arg, 1)
throw(DimensionMismatch("dimension mismatch"))
end
return arg
end
function (symop::IdentityOperation{S})(arg::AbstractArray{S}) where {S<:Real}
if dimension(symop) != size(arg, 1)
throw(DimensionMismatch("dimension mismatch"))
end
return arg
end
=# | {
"alphanum_fraction": 0.7046163444,
"author": null,
"avg_line_length": 24.4732824427,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "a3d94015d09d07f44a3ce2eb6b66863da3168332",
"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": "9880b9b2eb55f853ee667bdde70e911487eb724f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "kyungminlee/LatticeTools.jl",
"max_forks_repo_path": "src/SymmetryOperation/identityoperation.jl",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "9880b9b2eb55f853ee667bdde70e911487eb724f",
"max_issues_repo_issues_event_max_datetime": "2021-11-28T05:04:26.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-11-28T05:04:26.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "kyungminlee/LatticeTools.jl",
"max_issues_repo_path": "src/SymmetryOperation/identityoperation.jl",
"max_line_length": 93,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "9880b9b2eb55f853ee667bdde70e911487eb724f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "kyungminlee/LatticeTools.jl",
"max_stars_repo_path": "src/SymmetryOperation/identityoperation.jl",
"max_stars_repo_stars_event_max_datetime": "2021-11-09T22:33:37.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-08-01T01:01:23.000Z",
"num_tokens": 779,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 3206
} |
"""Everything needed for defining phases within an optimal control problem.
Classes:
Phase
"""
import copy
import itertools
from typing import (Optional, Tuple)
import sympy as sym
from .bounds import PhaseBounds
from .guess import PhaseGuess
from .mesh import PhaseMesh
from .scaling import PhaseScaling
from .typing import (OptionalExprsType, OptionalSymsType, TupleSymsType)
from .utils import (check_sym_name_clash, format_as_named_tuple)
__all__ = ["Phase"]
class Phase:
"""A single continuous time phase as part of an optimal control problem.
Attributes:
name: The name associated with a problem. Should be something short
like 'A'.
optimal_control_problem: The :obj:`OptimalControlProblem` with which
this phase is to be associated.
state_variables: The continuous time state variables in this phase.
control_variables: The continuous time control variables in this phase.
state_equations: The dynamical state equations associated with this
state variables in this phase.
integrand_functions: The integrand functions corresponding to the
integral variables in this phase.
path_constraints: The continuous time path constraints associated with
this phase.
bounds: The phase bounds on this phase. See :obj:PhaseBounds for more
details.
scaling: The phase scaling on this phase. See :obj:PhaseScaling for
more details.
guess: The initial guess at which this phase is to be solved.
mesh: This initial mesh on which this phase is to be solved.
_name: Protected version of :attr:`name`.
_ocp: Protected version of :attr:`optimal_control_problem`.
_phase_number: Protected integer number associated with this phase. If
not associated with any optimal control problem then defaults to
None until one is associated. These are ordered sequentially
starting at '0' in the order with which phases are added to an
optimal control problem.
_phase_suffix: Protected str which is used in the naming of auto-
generated Pycollo variables such as the endpoint state variables.
_y_var_user: Protected version of :attr:`state_variables`.
_u_var_user: Protected version of :attr:`control_variables`.
_q_var_user: Protected version of :attr:`integral_variables`.
_t_var_user: Protected version of :attr:`time_variables`.
_y_eqn_user: Protected version of :attr:`state_equations`.
_c_con_user: Protected version of :attr:`path_constraints`.
_q_fnc_user: Protected version of :attr:`integrand_functions`.
_t0_USER: Protected version of :attr:`initial_time_variable`.
_tF_USER: Protected version of :attr:`final_time_variable`.
_t0: Internal Pycollo symbol for phase initial time.
_tF: Internal Pycollo symbol for phase final time.
_STRETCH: Convenience expression for phase time scaling stretch.
_SHIFT: Convenience expression for phase time scaling shift.
"""
def __init__(self,
name: str,
*,
optimal_control_problem: Optional["OptimalControlProblem"] = None,
state_variables: OptionalSymsType = None,
control_variables: OptionalSymsType = None,
state_equations: OptionalExprsType = None,
integrand_functions: OptionalExprsType = None,
path_constraints: OptionalExprsType = None,
bounds: Optional[PhaseBounds] = None,
scaling: Optional[PhaseScaling] = None,
guess: Optional[PhaseGuess] = None,
mesh: Optional[PhaseMesh] = None,
):
"""Initialise the Phase object with minimum a name.
Args:
name: The name associated with a problem. Should be something short
like 'A'.
optimal_control_problem: The :obj:`OptimalControlProblem` with
which this phase is to be associated. Default value is None in
which case the phase remain uninitialised to an optimal control
problem.
state_variables: The continuous time state variables in this phase.
Default value is None in which case the phase has no associated
state variables and no phase-specific endpoint time or state
variables are created.
control_variables: The continuous time control variables in this
phase. Default value is None in which case the phase has no
associated control variables.
state_equations: The dynamical state equations associated with this
state variables in this phase. Default value is None in which
case no dynamical equations have been added to the phase yet.
integrand_functions: The integrand functions corresponding to the
integral variables in this phase. Default value is None in
which case the phase has no integrand functions associated with
it and no phase-specific integral variables are created.
path_constraints: The continuous time path constraints associated
with this phase. Default value is None in which case the phase
has no path constraints associated with it.
bounds: The phase bounds on this phase. See :obj:PhaseBounds for
more details. Default value is None in which case an empty
:obj:`PhaseBounds` object is instantiated and associated with
the phase.
scaling: The phase scaling on this phase. See :obj:PhaseScaling for
more details. Default value is None in which case an empty
:obj:`PhaseScaling` object is instantiated and associated with
the phase.
guess: The initial guess at which this phase is to be solved.
Default value is None in which case an empty :obj:`PhaseGuess`
object is instantiated and associated with the phase.
mesh: This initial mesh on which this phase is to be solved.
Default value is None in which case an empty :obj:`PhaseMesh`
object is instantiated and associated with the phase.
"""
self._name = str(name)
self._ocp = None
self._phase_number = None
self._phase_suffix = "X"
self._y_var_user = ()
self._u_var_user = ()
self._q_var_user = ()
self._t_var_user = ()
self._y_eqn_user = ()
self._c_con_user = ()
self._q_fnc_user = ()
if optimal_control_problem is not None:
self.optimal_control_problem = optimal_control_problem
self.state_variables = state_variables
self.control_variables = control_variables
self.state_equations = state_equations
self.integrand_functions = integrand_functions
self.path_constraints = path_constraints
self.bounds = bounds
self.scaling = scaling
self.guess = guess
self.mesh = mesh
self.auxiliary_data = {}
def create_new_copy(self,
name: str,
*,
copy_state_variables: bool = True,
copy_control_variables: bool = True,
copy_state_equations: bool = True,
copy_path_constraints: bool = True,
copy_integrand_functions: bool = True,
copy_state_endpoint_constraints: bool = False,
copy_bounds: bool = True,
copy_mesh: bool = True,
copy_scaling: bool = True,
copy_guess: bool = True,
):
self._check_variables_and_equations()
new_phase = Phase(name,
optimal_control_problem=self.optimal_control_problem)
if copy_state_variables:
new_phase.state_variables = copy.deepcopy(self.state_variables)
if copy_bounds:
new_phase.bounds.state_variables = copy.deepcopy(self.bounds.state_variables)
if copy_guess:
new_phase.guess.state_variables = copy.deepcopy(self.guess.state_variables)
if copy_scaling:
new_phase.scaling.state_variables = copy.deepcopy(self.scaling.state_variables)
if copy_control_variables:
new_phase.control_variables = copy.deepcopy(self.control_variables)
if copy_bounds:
new_phase.bounds.control_variables = copy.deepcopy(self.bounds.control_variables)
if copy_guess:
new_phase.guess.control_variables = copy.deepcopy(self.guess.control_variables)
if copy_scaling:
new_phase.scaling.control_variables = copy.deepcopy(self.scaling.control_variables)
if copy_state_equations:
new_phase.state_equations = copy.deepcopy(self.state_equations)
if copy_path_constraints:
new_phase.path_constraints = copy.deepcopy(self.path_constraints)
if copy_bounds:
new_phase.bounds.path_constraints = copy.deepcopy(self.bounds.path_constraints)
if copy_integrand_functions:
new_phase.integrand_functions = copy.deepcopy(self.integrand_functions)
if copy_bounds:
new_phase.bounds.integral_variables = copy.deepcopy(self.bounds.integral_variables)
if copy_state_endpoint_constraints and copy_bounds:
new_phase.bounds.state_endpoint_constraints = copy.deepcopy(self.bounds.state_endpoint_constraints)
if copy_mesh:
new_phase.mesh = copy.deepcopy(self.mesh)
return new_phase
@staticmethod
def create_new_copy_like(phase_for_copying: "Phase", name: str, **kwargs):
"""Constructor class to copy a phase."""
return phase_for_copying.create_new_copy(name, **kwargs)
@property
def name(self):
"""Name of the phase."""
return self._name
@property
def optimal_control_problem(self) -> Optional["OptimalControlProblem"]:
"""The optimal control problem with which this phase is associated.
There are two allowable scenarios. In the first scenario a phase may be
instantiated without being associated with an optimal control problem.
If this is the case then the default values of `None` for the phase
number and 'X' for the phase suffix remain.
In the second scenario a phase is instantiated with an associated
optimal control problem or is associated with an optimal control
problem after the first type of instantiation. In this case the phase
is appended to the protected `_phases` attribute of the
:obj:`OptimalControlProblem`, the phase number is set according to its
position in the order of addition to the optimal controls problem's
phases, and its phase suffix is set as a string version of the phase
number. Finally a replacement of any symbols that may have been used in
supplementary information about the phase that contained the placeholder
'X' phase suffix are renamed and substituted.
No checking is done to see whether the phase is already associated with
the optimal control problem in question or any other optimal control
problem. The reason being that if the setter method for this property is
accessed after having already been set then an `AttributeError` is
raised (see below). The reason this class works like that is to avoid
having to allow phases to be disassociated from an
:obj:`OptimalControlProblem` and thus having to handled the complexities
that would come with the phase renumbering and substitution of any
phase-related information that has already been given to the optimal
control problem.
Raises:
AttributeError: If an :obj:`OptimalControlProblem` has already been
associated with `self`. If a argument of any type other than
:obj:`OptimalControlProblem` is passed to the
`optimal_control_problem` property setter.
"""
return self._ocp
@optimal_control_problem.setter
def optimal_control_problem(self, ocp):
if self._ocp is not None:
msg = ('Optimal control problem is already set for this phase and '
'cannot be reset.')
raise AttributeError(msg)
try:
previous_phase_names = ocp._phases._fields
except AttributeError:
previous_phase_names = ()
phase_names = (*previous_phase_names, self.name)
ocp._phases = format_as_named_tuple([*ocp._phases, self],
named_keys=phase_names, sympify=False)
self._ocp = ocp
self._phase_number = self._ocp.number_phases - 1
self._phase_suffix = str(self.phase_number)
self.state_variables = self.state_variables
self.integrand_functions = self.integrand_functions
@property
def phase_number(self) -> Optional[int]:
"""The integer numerical identifier for the phase.
If this phase has not yet been associated with an optimal control
problem then None is returned.
Corresponds to the chronological order in which it was associated with
the optimal control problem in question.
"""
return self._phase_number
@property
def initial_time_variable(self) -> sym.Symbol:
"""Symbol for the time at which this phase begins."""
try:
return self._t0_USER
except AttributeError:
msg = ("Can't access initial time until associated with an optimal "
"control problem.")
raise AttributeError(msg)
@property
def final_time_variable(self) -> sym.Symbol:
"""Symbol for the time at which this phase begins."""
try:
return self._tF_USER
except AttributeError:
msg = ("Can't access final time until associated with an optimal "
"control problem.")
raise AttributeError(msg)
@property
def initial_state_variables(self) -> TupleSymsType:
"""Symbols for this phase's state variables at the initial time.
Raises:
AttributeError: If `optimal_control_problem` property has not yet
been set to a not None value. See docstring for
`state_variables` for details about why.
"""
try:
return self._y_t0_user
except AttributeError:
msg = ("Can't access initial state until associated with an optimal "
"control problem.")
raise AttributeError(msg)
@property
def final_state_variables(self) -> TupleSymsType:
"""Symbols for this phase's state variables at the final time.
Raises:
AttributeError: If `optimal_control_problem` property has not yet
been set to a not None value. See docstring for
`state_variables` for details about why.
"""
try:
return self._y_tF_user
except AttributeError:
msg = ("Can't access initial state until associated with an optimal "
"control problem.")
raise AttributeError(msg)
@property
def state_variables(self) -> TupleSymsType:
"""Symbols for this phase's state variables in order added by user.
The user may supply either a single symbol or an iterable of symbols.
The supplied argument is handled by the `format_as_tuple` method from
the `utils` module. Additional protected attributes `_y_t0_user` and
`_y_tF_user` are set by post-appending either '_PX(t0)' or '_PX(tF)' to
the user supplied symbols where the X is replaced by the phase suffix.
As such if this phase has not yet been associated with an optimal
control problem yet then `self` will not have attributes `_y_t0_user`
and `_y_tF_user` and accessing either the `initial_state` or
`final_state` property will raise an AttributeError.
"""
return self._y_var_user
@state_variables.setter
def state_variables(self, y_vars: OptionalSymsType):
self._y_var_user = format_as_named_tuple(y_vars)
check_sym_name_clash(self._y_var_user)
# Generate the state endpoint variable symbols only if phase has number
if self.optimal_control_problem is not None:
self._t0_USER = sym.Symbol(f't0_P{self._phase_suffix}')
self._tF_USER = sym.Symbol(f'tF_P{self._phase_suffix}')
self._t0 = sym.Symbol(f'_t0_P{self._phase_suffix}')
self._tF = sym.Symbol(f'_tF_P{self._phase_suffix}')
self._STRETCH = 0.5 * (self._tF - self._t0)
self._SHIFT = 0.5 * (self._t0 + self._tF)
self._t_var_user = (self._t0_USER, self._tF_USER)
try:
named_keys = self._y_var_user._fields
except AttributeError:
named_keys = ()
self._y_t0_user = format_as_named_tuple(
(sym.Symbol(f'{y}_P{self._phase_suffix}(t0)')
for y in self._y_var_user),
named_keys=named_keys)
self._y_tF_user = format_as_named_tuple(
(sym.Symbol(f'{y}_P{self._phase_suffix}(tF)')
for y in self._y_var_user),
named_keys=named_keys)
@property
def number_state_variables(self) -> int:
"""Integer number of state variables in the phase."""
return len(self._y_var_user)
@property
def control_variables(self) -> TupleSymsType:
"""Symbols for this phase's control variables in order added by user.
The user may supply either a single symbol or an iterable of symbols.
The supplied argument is handled by the `format_as_tuple` method from
the `utils` module.
"""
return self._u_var_user
@control_variables.setter
def control_variables(self, u_vars: OptionalSymsType):
self._u_var_user = format_as_named_tuple(u_vars)
check_sym_name_clash(self._u_var_user)
@property
def number_control_variables(self) -> int:
"""Integer number of control variables in the phase."""
return len(self._u_var_user)
@property
def integral_variables(self) -> TupleSymsType:
"""Symbols for this phase's integral variables.
These symbols are auto generated as required by the user-supplied
integrand functions.
"""
return self._q_var_user
@property
def time_variables(self) -> TupleSymsType:
"""The initial and final time symbols as a pair."""
return (self.initial_time_variable, self.final_time_variable)
@property
def number_integral_variables(self) -> int:
"""Integer number of integral variables in the phase."""
return len(self._q_var_user)
@property
def state_equations(self) -> Tuple[sym.Expr, ...]:
"""User-supplied dynamical equations in the phase.
These equations are the dynamical equations associated with each of the
state variables in the phase. There should therefore be exactly one
state equation for each dynamics symbol.
State equations can be supplied in a compact form by the user defining additional auxiliary symbols and
"""
return self._y_eqn_user
@state_equations.setter
def state_equations(self, y_eqns: OptionalExprsType):
try:
named_keys = self._y_var_user._fields
except AttributeError:
named_keys = ()
self._y_eqn_user = format_as_named_tuple(y_eqns, use_named=True,
named_keys=named_keys)
@property
def number_state_equations(self) -> int:
"""Integer number of state equations in the phase.
Should be the same as the number of state variables, i.e. there should
be a direct mapping between the two.
"""
return len(self._y_eqn_user)
@property
def path_constraints(self):
return self._c_con_user
@path_constraints.setter
def path_constraints(self, c_cons):
self._c_con_user = format_as_named_tuple(c_cons, use_named=False)
@property
def number_path_constraints(self):
return len(self._c_con_user)
@property
def integrand_functions(self):
return self._q_fnc_user
@integrand_functions.setter
def integrand_functions(self, integrands):
self._q_fnc_user = format_as_named_tuple(integrands, use_named=False)
self._q_var_user = tuple(sym.Symbol(f'q{i_q}_P{self._phase_suffix}')
for i_q, _ in enumerate(self._q_fnc_user))
@property
def number_integrand_functions(self):
return len(self._q_fnc_user)
@property
def bounds(self):
return self._bounds
@bounds.setter
def bounds(self, bounds):
if bounds is None:
self._bounds = PhaseBounds(phase=self)
else:
self._bounds = bounds
@property
def scaling(self):
return self._scaling
@scaling.setter
def scaling(self, scaling):
if scaling is None:
self._scaling = PhaseScaling(phase=self)
else:
self._scaling = scaling
@property
def mesh(self):
return self._mesh
@mesh.setter
def mesh(self, mesh):
if mesh is None:
self._mesh = PhaseMesh(phase=self)
else:
self._mesh = mesh
@property
def guess(self):
return self._guess
@guess.setter
def guess(self, guess):
if guess is None:
self._guess = PhaseGuess(phase=self)
else:
self._guess = guess
def _check_variables_and_equations(self):
"""Check the user-supplied variables and equations for this OCP phase.
Steps involved are:
* Ensure that the same number of state variables and state
equations are supplied.
* Ensure that the symbols related to the state equations are the
same set as the set of state variables.
* If the two sets are not the same then issue an informative
warning to the user describing what is wrong about the supplied
state variables and state equations.
Raises
------
ValueError
If the state variables and symbols associated with the state
equations are not the same.
"""
try:
set_state_variables_keys = set(self.state_variables._fields)
except AttributeError:
set_state_variables_keys = set()
try:
set_state_equations_keys = set(self.state_equations._fields)
except AttributeError:
set_state_equations_keys = set()
if set_state_variables_keys != set_state_equations_keys:
intersection = set_state_variables_keys.intersection(
set_state_equations_keys)
spacer = "', '"
msg_other = []
if len(set_state_variables_keys) != len(set_state_equations_keys):
if len(set_state_variables_keys) == 1:
msg_vars_len = (f"{len(set_state_variables_keys)} state "
f"variable is")
else:
msg_vars_len = (f"{len(set_state_variables_keys)} state "
f"variables are")
if len(set_state_equations_keys) == 1:
msg_eqns_len = (f"{len(set_state_equations_keys)} state "
f"equation is")
else:
msg_eqns_len = (f"{len(set_state_equations_keys)} state "
f"equations are")
msg_len = (f"{msg_vars_len} defined while {msg_eqns_len} "
f"supplied")
msg_other.append(msg_len)
only_in_variables = set_state_variables_keys.difference(
intersection)
if only_in_variables:
immutable_only_in_variables = list(only_in_variables)
if len(only_in_variables) == 1:
msg_vars = (f"the state variable "
f"'{immutable_only_in_variables[0]}' is defined "
f"without a state equation")
else:
msg_vars = (f"the state variables "
f"'{spacer.join(immutable_only_in_variables[:-1])}' "
f"and '{immutable_only_in_variables[-1]}' are defined "
f"without state equations")
msg_other.append(msg_vars)
only_in_equations = set_state_equations_keys.difference(
intersection)
if only_in_equations:
if len(only_in_equations) == 1:
immutable_only_in_equations = list(only_in_equations)
msg_eqns = (f"a state derivative is supplied for "
f"'{immutable_only_in_equations[0]}' which is not a "
f"state variable")
else:
msg_eqns = (f"state derivatives are supplied for "
f"'{spacer.join(immutable_only_in_equations[:-1])}' "
f"and '{immutable_only_in_equations[-1]}' which are "
f"not defined as state variables")
msg_other.append(msg_eqns)
msg = ("A state equation must be supplied for each state variable "
f"in each phase. Currently in phase '{self.name}'")
if len(msg_other) == 1:
full_msg = (f"{msg}, {msg_other[0]}.")
else:
full_msg = (f"{msg}: {'; '.join(msg_other[:-1])}; and "
f"{msg_other[-1]}.")
raise ValueError(full_msg)
def __str__(self):
string = (f"Phase {self.phase_number} of {self.optimal_control_problem}")
return string
def __repr__(self):
string = (f"Phase({repr(self.optimal_control_problem)}, "
f"phase_number={self.phase_number})")
return string
| {
"alphanum_fraction": 0.6108186604,
"author": null,
"avg_line_length": 42.9719188768,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "2514663eade4f1969524defc4b4a6a3d192b8d3d",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2022-02-12T06:05:31.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-10-02T23:19:21.000Z",
"max_forks_repo_head_hexsha": "5c5c425788acb9decdbcb70253aeb5a482b31c55",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "NoNotCar/pycollo",
"max_forks_repo_path": "pycollo/phase.py",
"max_issues_count": 6,
"max_issues_repo_head_hexsha": "5c5c425788acb9decdbcb70253aeb5a482b31c55",
"max_issues_repo_issues_event_max_datetime": "2022-02-14T17:03:21.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-06-16T20:18:38.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "NoNotCar/pycollo",
"max_issues_repo_path": "pycollo/phase.py",
"max_line_length": 112,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "5c5c425788acb9decdbcb70253aeb5a482b31c55",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "NoNotCar/pycollo",
"max_stars_repo_path": "pycollo/phase.py",
"max_stars_repo_stars_event_max_datetime": "2022-02-11T12:28:30.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-07T13:55:27.000Z",
"num_tokens": 5381,
"path": null,
"reason": "import sympy",
"repo": null,
"save_path": null,
"sha": null,
"size": 27545
} |
module NFFT
using Base.Cartesian
using FFTW
using Distributed
using SparseArrays
using LinearAlgebra
export NFFTPlan, nfft, nfft_adjoint, ndft, ndft_adjoint
include("windowFunctions.jl")
include("precomputation.jl")
#=
Some internal documentation (especially for people familiar with the nfft)
- The window is precomputed during construction of the NFFT plan
When performing the nfft convolution, the LUT of the window is used to
perform linear interpolation. This approach is reasonable fast and does not
require too much memory. There are, however alternatives known that are either
faster or require no extra memory at all.
The non-exported functions apodization and convolve are implemented
using Cartesian macros, that may not be very readable.
This is a conscious decision where performance has outweighed readability.
More readable versions can be (and have been) written using the CartesianRange approach,
but at the time of writing this approach require *a lot* of memory.
=#
#=
D is the number of dimensions of the array to be transformed.
DIM is the dimension along which the array is transformed.
DIM == 0 is the ordinary NFFT, i.e., where all dimensions are transformed.
DIM is a type parameter since it allows the @generated macro to
compile more efficient methods.
=#
mutable struct NFFTPlan{D,DIM,T}
N::NTuple{D,Int64}
M::Int64
x::Matrix{T}
m::Int64
sigma::T
n::NTuple{D,Int64}
K::Int64
windowLUT::Vector{Vector{T}}
windowHatInvLUT::Vector{Vector{T}}
forwardFFT::FFTW.cFFTWPlan{Complex{T},-1,true,D}
backwardFFT::FFTW.cFFTWPlan{Complex{T},1,true,D}
tmpVec::Array{Complex{T},D}
B::SparseMatrixCSC{T,Int64}
end
@inline dim(::NFFTPlan{D,DIM}) where {D, DIM} = DIM
"""
NFFTPlan(x, N, ...) -> plan
Compute `D` dimensional NFFT plan for sampling locations `x` (a vector or a `D`-by-`M` matrix) that can be applied on arrays of size `N` (a tuple of length `D`).
The optional arguments control the accuracy.
It takes as optional keywords all the keywords supported by `plan_fft` function (like
`flags` and `timelimit`). See documentation of `plan_fft` for reference.
"""
NFFTPlan
@enum PrecomputeFlags begin
LUT = 1
FULL = 2
end
function NFFTPlan(x::Matrix{T}, N::NTuple{D,Int}, m=4, sigma=2.0,
window=:kaiser_bessel, K=2000;
precompute::PrecomputeFlags=LUT, kwargs...) where {D,T}
if D != size(x,1)
throw(ArgumentError())
end
n = ntuple(d->round(Int,sigma*N[d]), D)
tmpVec = zeros(Complex{T}, n)
M = size(x,2)
FP = plan_fft!(tmpVec; kwargs...)
BP = plan_bfft!(tmpVec; kwargs...)
# Create lookup table
win, win_hat = getWindow(window)
windowLUT = Vector{Vector{T}}(undef,D)
windowHatInvLUT = Vector{Vector{T}}(undef,D)
for d=1:D
windowHatInvLUT[d] = zeros(T, N[d])
for k=1:N[d]
windowHatInvLUT[d][k] = 1. / win_hat(k-1-N[d]/2, n[d], m, sigma)
end
end
if precompute == LUT
Z = round(Int,3*K/2)
for d=1:D
windowLUT[d] = zeros(T, Z)
for l=1:Z
y = ((l-1) / (K-1)) * m/n[d]
windowLUT[d][l] = win(y, n[d], m, sigma)
end
end
B = sparse([],[],Float64[])
else
U1 = ntuple(d-> (d==1) ? 1 : (2*m+1)^(d-1), D)
U2 = ntuple(d-> (d==1) ? 1 : prod(n[1:(d-1)]), D)
B = precomputeB(win, x, n, m, M, sigma, T, U1, U2)
end
NFFTPlan{D,0,T}(N, M, x, m, sigma, n, K, windowLUT, windowHatInvLUT,
FP, BP, tmpVec, B )
end
NFFTPlan(x::AbstractMatrix{T}, N::NTuple{D,Int}, rest...; kwargs...) where {D,T} =
NFFTPlan(collect(x), N, rest...; kwargs...)
NFFTPlan(x::AbstractVector, N::Integer, rest...; kwargs...) =
NFFTPlan(reshape(x,1,length(x)), (N,), rest...; kwargs...)
# Directional NFFT
"""
NFFTPlan(x, d, N, ...) -> plan
Compute *directional* NFFT plan:
A 1D plan that is applied along dimension `d` of a `D` dimensional array of size `N` with sampling locations `x` (a vector).
It takes as optional keywords all the keywords supported by `plan_fft` function (like
`flags` and `timelimit`). See documentation of `plan_fft` for reference.
"""
function NFFTPlan(x::AbstractVector{T}, dim::Integer, N::NTuple{D,Int64}, m=4,
sigma=2.0, window=:kaiser_bessel, K=2000; kwargs...) where {D,T}
n = ntuple(d->round(Int, sigma*N[d]), D)
sz = [N...]
sz[dim] = n[dim]
tmpVec = Array{Complex{T}}(undef,sz...)
M = length(x)
FP = plan_fft!(tmpVec, dim; kwargs...)
BP = plan_bfft!(tmpVec, dim; kwargs...)
# Create lookup table
win, win_hat = getWindow(window)
windowLUT = Vector{Vector{T}}(undef,1)
Z = round(Int, 3*K/2)
windowLUT[1] = zeros(T, Z)
for l = 1:Z
y = ((l-1) / (K-1)) * m/n[dim]
windowLUT[1][l] = win(y, n[dim], m, sigma)
end
windowHatInvLUT = Vector{Vector{T}}(undef,1)
windowHatInvLUT[1] = zeros(T, N[dim])
for k = 1:N[dim]
windowHatInvLUT[1][k] = 1. / win_hat(k-1-N[dim]/2, n[dim], m, sigma)
end
B = sparse([],[],Float64[])
NFFTPlan{D,dim,T}(N, M, reshape(x,1,M), m, sigma, n, K, windowLUT,
windowHatInvLUT, FP, BP, tmpVec, B)
end
function NFFTPlan(x::Matrix{T}, dim::Integer, N::NTuple{D,Int}, m=4, sigma=2.0,
window=:kaiser_bessel, K=2000; kwargs...) where {D,T}
if size(x,1) != 1 && size(x,2) != 1
throw(DimensionMismatch())
end
NFFTPlan(vec(x), dim, N, m, sigma, window, K; kwargs...)
end
function Base.show(io::IO, p::NFFTPlan{D,0}) where D
print(io, "NFFTPlan with ", p.M, " sampling points for ", p.N, " array")
end
function Base.show(io::IO, p::NFFTPlan{D,DIM}) where {D,DIM}
print(io, "NFFTPlan with ", p.M, " sampling points for ", p.N, " array along dimension ", DIM)
end
@generated function consistencyCheck(p::NFFTPlan{D,DIM,T}, f::AbstractArray{U,D},
fHat::AbstractArray{Y}) where {D,DIM,T,U,Y}
quote
if $DIM == 0
fHat_test = (p.M == length(fHat))
elseif $DIM > 0
fHat_test = @nall $D d -> ( d == $DIM ? size(fHat,d) == p.M : size(fHat,d) == p.N[d] )
end
if p.N != size(f) || !fHat_test
throw(DimensionMismatch("Data is not consistent with NFFTPlan"))
end
end
end
### nfft functions ###
"""
nfft!(p, f, fHat) -> fHat
Calculate the NFFT of `f` with plan `p` and store the result in `fHat`.
Both `f` and `fHat` must be complex arrays.
"""
function nfft!(p::NFFTPlan{D,DIM,T}, f::AbstractArray, fHat::StridedArray, verbose=false) where {D,DIM,T}
consistencyCheck(p, f, fHat)
fill!(p.tmpVec, zero(Complex{T}))
t1 = @elapsed @inbounds apodization!(p, f, p.tmpVec)
if nprocs() == 1
t2 = @elapsed p.forwardFFT * p.tmpVec # fft!(p.tmpVec) or fft!(p.tmpVec, dim)
else
t2 = @elapsed dim(p) == 0 ? fft!(p.tmpVec) : fft!(p.tmpVec, dim(p))
end
t3 = @elapsed @inbounds convolve!(p, p.tmpVec, fHat)
if verbose
@info "Timing: apod=$t1 fft=$t2 conv=$t3"
end
return fHat
end
"""
nfft(p, f) -> fHat
For a **non**-directional `D` dimensional plan `p` this calculates the NFFT of a `D` dimensional array `f` of size `N`.
`fHat` is a vector of length `M`.
(`M` and `N` are defined in the plan creation)
For a **directional** `D` dimensional plan `p` both `f` and `fHat` are `D`
dimensional arrays, and the dimension specified in the plan creation is
affected.
"""
function nfft(p::NFFTPlan{D,0,T}, f::AbstractArray{U,D}, args...) where {D,T,U}
fHat = zeros(Complex{T}, p.M)
nfft!(p, f, fHat, args...)
return fHat
end
function nfft(x, f::AbstractArray{T,D}, rest...; kwargs...) where {D,T}
p = NFFTPlan(x, size(f), rest...; kwargs...)
return nfft(p, f)
end
function nfft(p::NFFTPlan{D,DIM,T}, f::AbstractArray{U,D}, args...) where {D,DIM,T,U}
sz = [p.N...]
sz[DIM] = p.M
fHat = Array{Complex{T}}(undef,sz...)
nfft!(p, f, fHat, args...)
return fHat
end
"""
nfft_adjoint!(p, fHat, f) -> f
Calculate the adjoint NFFT of `fHat` and store the result in `f`.
Both `f` and `fHat` must be complex arrays.
"""
function nfft_adjoint!(p::NFFTPlan, fHat::AbstractArray, f::StridedArray, verbose=false)
consistencyCheck(p, f, fHat)
t1 = @elapsed @inbounds convolve_adjoint!(p, fHat, p.tmpVec)
if nprocs() == 1
t2 = @elapsed p.backwardFFT * p.tmpVec # bfft!(p.tmpVec) or bfft!(p.tmpVec, dim)
else
t2 = @elapsed dim(p) == 0 ? bfft!(p.tmpVec) : bfft!(p.tmpVec, dim(p))
end
t3 = @elapsed @inbounds apodization_adjoint!(p, p.tmpVec, f)
if verbose
@info "Timing: conv=$t1 fft=$t2 apod=$t3"
end
return f
end
"""
nfft_adjoint(p, f) -> fHat
For a **non**-directional `D` dimensional plan `p` this calculates the adjoint NFFT of a length `M` vector `fHat`
`f` is a `D` dimensional array of size `N`.
(`M` and `N` are defined in the plan creation)
For a **directional** `D` dimensional plan `p` both `f` and `fHat` are `D`
dimensional arrays, and the dimension specified in the plan creation is
affected.
"""
function nfft_adjoint(p::NFFTPlan{D,DIM,T}, fHat::AbstractArray{U}, args...) where {D,DIM,T,U}
f = Array{Complex{T}}(undef,p.N)
nfft_adjoint!(p, fHat, f, args...)
return f
end
function nfft_adjoint(x, N, fHat::AbstractVector{T}, rest...; kwargs...) where T
p = NFFTPlan(x, N, rest...; kwargs...)
return nfft_adjoint(p, fHat)
end
include("directional.jl")
include("multidimensional.jl")
include("samplingDensity.jl")
include("NDFT.jl")
end
| {
"alphanum_fraction": 0.6199834506,
"author": null,
"avg_line_length": 30.4025157233,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "f8b9d2d0ab93c0a9645a7f50ed22cc5556a598a2",
"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": "4cb177f5b3790c928a1539effae2d450927f29b4",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "UnofficialJuliaMirror/NFFT.jl-efe261a4-0d2b-5849-be55-fc731d526b0d",
"max_forks_repo_path": "src/NFFT.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "4cb177f5b3790c928a1539effae2d450927f29b4",
"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": "UnofficialJuliaMirror/NFFT.jl-efe261a4-0d2b-5849-be55-fc731d526b0d",
"max_issues_repo_path": "src/NFFT.jl",
"max_line_length": 161,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "4cb177f5b3790c928a1539effae2d450927f29b4",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "UnofficialJuliaMirror/NFFT.jl-efe261a4-0d2b-5849-be55-fc731d526b0d",
"max_stars_repo_path": "src/NFFT.jl",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3081,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 9668
} |
import numpy as np
import torch
from cnns.nnlib.utils.shift_DC_component import shift_DC
from cnns.nnlib.pytorch_layers.pytorch_utils import compress_2D_index_forward
torch.manual_seed(31)
# x = torch.randint(10, (6, 6))
x = torch.tensor([[6., 5., 0., 2., 4., 1.],
[4., 2., 8., 5., 6., 8.],
[0., 0., 4., 2., 0., 2.],
[2., 9., 9., 9., 1., 6.],
[3., 0., 9., 4., 6., 6.],
[7., 3., 4., 7., 9., 0.]])
x = x.to(torch.float)
print("sum of x: ", x.sum().item())
print("x: ", x)
xfft = torch.rfft(x, onesided=False, signal_ndim=2, normalized=False)
print("xfft: ", xfft)
# xfft: tensor([[[153.0000, 0.0000],
# [-16.0000, -3.4641],
# [ 0.0000, 10.3923],
# [ 11.0000, 0.0000],
# [ 0.0000, -10.3923],
# [-16.0000, 3.4641]],
#
# [[ -4.5000, 14.7224],
# [ 7.5000, 7.7942],
# [ 18.0000, -12.1244],
# [ 16.5000, 12.9904],
# [ -1.5000, 23.3827],
# [ 12.0000, -15.5885]],
#
# [[ 4.5000, -19.9186],
# [ 14.0000, -12.1244],
# [ 16.5000, 0.8660],
# [-20.5000, -0.8660],
# [-12.0000, 19.0526],
# [ 3.5000, 12.9904]],
#
# [[-45.0000, 0.0000],
# [ 9.0000, 5.1962],
# [ -3.0000, 1.7321],
# [ 9.0000, 0.0000],
# [ -3.0000, -1.7321],
# [ 9.0000, -5.1962]],
#
# [[ 4.5000, 19.9186],
# [ 3.5000, -12.9904],
# [-12.0000, -19.0526],
# [-20.5000, 0.8660],
# [ 16.5000, -0.8660],
# [ 14.0000, 12.1244]],
#
# [[ -4.5000, -14.7224],
# [ 12.0000, 15.5885],
# [ -1.5000, -23.3827],
# [ 16.5000, -12.9904],
# [ 18.0000, 12.1244],
# [ 7.5000, -7.7942]]])
xfft_dc = shift_DC(xfft, onesided=False)
print("xfft_dc: ", xfft_dc)
xfft = torch.rfft(x, onesided=True, signal_ndim=2, normalized=False)
print("xfft onesided: ", xfft)
xfft_dc = shift_DC(xfft, onesided=True)
print("xfft dc onesided: ", xfft_dc)
xfft_compress1 = compress_2D_index_forward(xfft, index_forward=3)
xfft_compress1_dc = shift_DC(xfft_compress1, onesided=True)
print("xfft compress1: ", xfft_compress1_dc)
xfft_compress2 = compress_2D_index_forward(xfft, index_forward=2)
xfft_compress2_dc = shift_DC(xfft_compress2, onesided=True)
print("xfft compress2: ", xfft_compress2_dc)
#
# input
# full
# xfft(both
# sided:
# [[[16.5000, -0.8660][14.0000, 12.1244][4.5000, 19.9186][3.5000, -12.9904][
# -12.0000, -19.0526][-20.5000, 0.8660]]
# [[18.0000, 12.1244][7.5000, -7.7942][-4.5000, -14.7224][12.0000, 15.5885][
# -1.5000, -23.3827][16.5000, -12.9904]]
# [[0.0000, -10.3923][-16.0000, 3.4641][153.0000, 0.0000][-16.0000, -3.4641][
# 0.0000, 10.3923][11.0000, 0.0000]]
# [[-1.5000, 23.3827][12.0000, -15.5885][-4.5000, 14.7224][7.5000, 7.7942][
# 18.0000, -12.1244][16.5000, 12.9904]]
# [[-12.0000, 19.0526][3.5000, 12.9904][4.5000, -19.9186][14.0000, -12.1244][
# 16.5000, 0.8660][-20.5000, -0.8660]]
# [[-3.0000, -1.7321][9.0000, -5.1962][-45.0000, 0.0000][9.0000, 5.1962][
# -3.0000, 1.7321][9.0000, 0.0000]]])
#
# xfft
# onesided:
# [[[153.0000, 0.0000][-16.0000, -3.4641][0.0000, 10.3923][11.0000, 0.0000]]
# [[-4.5000, 14.7224][7.5000, 7.7942][18.0000, -12.1244][16.5000, 12.9904]]
# [[4.5000, -19.9186][14.0000, -12.1244][16.5000, 0.8660][-20.5000, -0.8660]]
# [[-45.0000, 0.0000][9.0000, 5.1962][-3.0000, 1.7321][9.0000, 0.0000]]
# [[4.5000, 19.9186][3.5000, -12.9904][-12.0000, -19.0526][-20.5000, 0.8660]]
# [[-4.5000, -14.7224][12.0000, 15.5885][-1.5000, -23.3827][16.5000, -12.9904]]]
#
# xfft
# dc
# onesided:
# [[[4.5000, 19.9186][3.5000, -12.9904][-12.0000, -19.0526][-20.5000, 0.8660]]
# [[-4.5000, -14.7224][12.0000, 15.5885][-1.5000, -23.3827][16.5000, -12.9904]]
# [[153.0000, 0.0000][-16.0000, -3.4641][0.0000, 10.3923][11.0000, 0.0000]]
# [[-4.5000, 14.7224][7.5000, 7.7942][18.0000, -12.1244][16.5000, 12.9904]]
# [[4.5000, -19.9186][14.0000, -12.1244][16.5000, 0.8660][-20.5000, -0.8660]]
# [[-45.0000, 0.0000][9.0000, 5.1962][-3.0000, 1.7321][9.0000, 0.0000]]])
#
# xfft
# compress
# 1:
# [[[4.5000, 19.9186][3.5000, -12.9904][-12.0000, -19.0526]]
# [[-4.5000, -14.7224][12.0000, 15.5885][-1.5000, -23.3827]]
# [[153.0000, 0.0000][-16.0000, -3.4641][0.0000, 10.3923]]
# [[-4.5000, 14.7224][7.5000, 7.7942][18.0000, -12.1244]]
# [[4.5000, -19.9186][14.0000, -12.1244][16.5000, 0.8660]]]
#
# xfft
# compress
# 2:
# [[-4.5000, -14.7224][12.0000, 15.5885]]
# [[153.0000, 0.0000][-16.0000, -3.4641]]
# [[-4.5000, 14.7224][7.5000, 7.7942]]
#
#
| {
"alphanum_fraction": 0.5235256547,
"author": null,
"avg_line_length": 35.3157894737,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "f4e0282c9049d7696aa0d1718e760012ed3e5bf3",
"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": "81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "adam-dziedzic/time-series-ml",
"max_forks_repo_path": "cnns/graphs/fft_visualize/technique_pytorch.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a",
"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": "adam-dziedzic/time-series-ml",
"max_issues_repo_path": "cnns/graphs/fft_visualize/technique_pytorch.py",
"max_line_length": 81,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "81aaa27f1dd9ea3d7d62b661dac40cac6c1ef77a",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "adam-dziedzic/time-series-ml",
"max_stars_repo_path": "cnns/graphs/fft_visualize/technique_pytorch.py",
"max_stars_repo_stars_event_max_datetime": "2018-03-25T13:19:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-03-25T13:19:46.000Z",
"num_tokens": 2328,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 4697
} |
[STATEMENT]
lemma approx_add: "a \<approx> b \<Longrightarrow> c \<approx> d \<Longrightarrow> a + c \<approx> b + d"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>a \<approx> b; c \<approx> d\<rbrakk> \<Longrightarrow> a + c \<approx> b + d
[PROOF STEP]
proof (unfold approx_def)
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<lbrakk>a - b \<in> Infinitesimal; c - d \<in> Infinitesimal\<rbrakk> \<Longrightarrow> a + c - (b + d) \<in> Infinitesimal
[PROOF STEP]
assume inf: "a - b \<in> Infinitesimal" "c - d \<in> Infinitesimal"
[PROOF STATE]
proof (state)
this:
a - b \<in> Infinitesimal
c - d \<in> Infinitesimal
goal (1 subgoal):
1. \<lbrakk>a - b \<in> Infinitesimal; c - d \<in> Infinitesimal\<rbrakk> \<Longrightarrow> a + c - (b + d) \<in> Infinitesimal
[PROOF STEP]
have "a + c - (b + d) = (a - b) + (c - d)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. a + c - (b + d) = a - b + (c - d)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
a + c - (b + d) = a - b + (c - d)
goal (1 subgoal):
1. \<lbrakk>a - b \<in> Infinitesimal; c - d \<in> Infinitesimal\<rbrakk> \<Longrightarrow> a + c - (b + d) \<in> Infinitesimal
[PROOF STEP]
also
[PROOF STATE]
proof (state)
this:
a + c - (b + d) = a - b + (c - d)
goal (1 subgoal):
1. \<lbrakk>a - b \<in> Infinitesimal; c - d \<in> Infinitesimal\<rbrakk> \<Longrightarrow> a + c - (b + d) \<in> Infinitesimal
[PROOF STEP]
have "... \<in> Infinitesimal"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. a - b + (c - d) \<in> Infinitesimal
[PROOF STEP]
using inf
[PROOF STATE]
proof (prove)
using this:
a - b \<in> Infinitesimal
c - d \<in> Infinitesimal
goal (1 subgoal):
1. a - b + (c - d) \<in> Infinitesimal
[PROOF STEP]
by (rule Infinitesimal_add)
[PROOF STATE]
proof (state)
this:
a - b + (c - d) \<in> Infinitesimal
goal (1 subgoal):
1. \<lbrakk>a - b \<in> Infinitesimal; c - d \<in> Infinitesimal\<rbrakk> \<Longrightarrow> a + c - (b + d) \<in> Infinitesimal
[PROOF STEP]
finally
[PROOF STATE]
proof (chain)
picking this:
a + c - (b + d) \<in> Infinitesimal
[PROOF STEP]
show "a + c - (b + d) \<in> Infinitesimal"
[PROOF STATE]
proof (prove)
using this:
a + c - (b + d) \<in> Infinitesimal
goal (1 subgoal):
1. a + c - (b + d) \<in> Infinitesimal
[PROOF STEP]
.
[PROOF STATE]
proof (state)
this:
a + c - (b + d) \<in> Infinitesimal
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": 12,
"llama_tokens": 1060,
"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 _*_
"""
Pytorch(笔记9)--读取自定义数据
https://blog.csdn.net/haiqiang1995/article/details/90348966
Pytorch源码(一)—— 简析torchvision的ImageFolder
https://www.jianshu.com/p/5bb684c4c9fc
Pytorch-ImageFolder/自定义类 读取图片数据
https://jianzhuwang.blog.csdn.net/article/details/103776245
"""
from torch.utils.data import Dataset
def imageLoader(path, type='pil'):
# 自定义图片图片读取方式,可以自行增加resize、数据增强等操作
if path is None:
return
if type == 'pil':
from PIL import Image
# print(path)
return Image.open(path).convert('RGB')
elif type == 'cv2':
import cv2
import numpy as np
return cv2.imdecode(np.fromfile(path, dtype=np.uint8), 1)
# class readTxt(Dataset):
# # 构造函数设置默认参数
# def __init__(self, txt_path, dir_type=None, read_type='pil'):
# with open(txt_path, 'r') as f:
# imgs = []
# for line in f:
# line = line.strip('\n') # 移除字符串首尾的换行符
# line = line.rstrip() # 删除末尾空
# words = line.split() # 以空格为分隔符 将字符串分成
# imgs.append((words[0], int(words[1]))) # imgs中包含有图像路径和标签
# self.imgs = imgs
# self.transform = trans_gen.genTrans
# self.mode = dir_type
# self.type = read_type
# self.loader = imageLoader
#
# def __getitem__(self, index):
# img, label = self.imgs[index]
# # 调用定义的loader方法
# image = self.loader(img, self.type)
# if self.mode is not None:
# image = self.transform(self.mode)(image)
#
# return image, label
#
# def __len__(self):
# return len(self.imgs)
# IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif']
IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif', '.tiff', '.webp')
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
extensions (tuple of strings): extensions to consider (lowercase)
Returns:
bool: True if the filename ends with one of given extensions
"""
return filename.lower().endswith(extensions)
def is_image_file(filename):
"""Checks if a file is an allowed image extension.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known image extension
"""
return has_file_allowed_extension(filename, IMG_EXTENSIONS)
# def pil_loader(path):
# # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)
# with open(path, 'rb') as f:
# img = Image.open(f)
# return img.convert('RGB')
#
#
# def accimage_loader(path):
# import accimage
# # https://github.com/pytorch/accimage
# try:
# return accimage.Image(path)
# except IOError:
# # Potentially a decoding problem, fall back to PIL.Image
# return pil_loader(path)
#
#
# def default_loader(path):
# from torchvision import get_image_backend
# if get_image_backend() == 'accimage':
# return accimage_loader(path)
# else:
# return pil_loader(path)
#
# def find_classes(dir):
# # 得到指定目录下的所有文件,并将其名字和指定目录的路径合并
# # 以数组的形式存在classes中
# classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
# # 使用sort()进行简单的排序
# classes.sort()
# # 将其保存的路径排序后简单地映射到 0 ~ [ len(classes)-1] 的数字上
# class_to_idx = {classes[i]: i for i in range(len(classes))}
# # 返回存放路径的数组和存放其映射后的序号的数组
# return classes, class_to_idx
#
# def has_file_allowed_extension(filename, extensions):
# """Checks if a file is an allowed extension.
#
# Args:
# filename (string): path to a file
#
# Returns:
# bool: True if the filename ends with a known image extension
# """
# # 将文件的名变成小写
# filename_lower = filename.lower()
#
# # endswith() 方法用于判断字符串是否以指定后缀结尾
# # 如果以指定后缀结尾返回True,否则返回False
# return any(filename_lower.endswith(ext) for ext in extensions)
#
# def make_dataset(dir, class_to_idx, extensions):
# images = []
# # expanduser把path中包含的"~"和"~user"转换成用户目录
# # 主要还是在Linux之类的系统中使用,在不包含"~"和"~user"时
# # dir不变
# dir = os.path.expanduser(dir)
# # 排序后按顺序通过for循环dir路径下的所有文件名
# for target in sorted(os.listdir(dir)):
# # 将路径拼合
# d = os.path.join(dir, target)
# # 如果拼接后不是文件目录,则跳出这次循环
# if not os.path.isdir(d):
# continue
# # os.walk(d) 返回的fnames是当前d目录下所有的文件名
# # 注意:第一个for其实就只循环一次,返回的fnames 是一个数组
# for root, _, fnames in sorted(os.walk(d)):
# # 循环每一个文件名
# for fname in sorted(fnames):
# # 文件的后缀名是否符合给定
# if has_file_allowed_extension(fname, extensions):
# # 组合路径
# path = os.path.join(root, fname)
# # 将组合后的路径和该文件位于哪一个序号的文件夹下的序号
# # 组成元祖
# item = (path, class_to_idx[target])
# # 将其存入数组中
# images.append(item)
#
# return images
def make_dataset(dir, lines, class_to_idx, extensions=None, is_valid_file=None):
import os
images = []
# dir = os.path.expanduser(dir)
# if not ((extensions is None) ^ (is_valid_file is None)):
# raise ValueError("Both extensions and is_valid_file cannot be None or not None at the same time")
# if extensions is not None:
# def is_valid_file(x):
# return has_file_allowed_extension(x, extensions)
# for target in sorted(class_to_idx.keys()):
# d = os.path.join(dir, target)
# if not os.path.isdir(d):
# continue
# for root, _, fnames in sorted(os.walk(d)):
# for fname in sorted(fnames):
# path = os.path.join(root, fname)
# if is_valid_file(path):
# item = (path, class_to_idx[target])
# images.append(item)
for line in lines:
# print(line)
name = line.strip('\n').rstrip().split()[0]
target = line.strip('\n').rstrip().split()[-1]
path = os.path.join(dir, target, name)
if is_image_file(path):
item = (path, class_to_idx[target])
images.append(item)
return images
class ImageTxt(Dataset):
def __init__(self, txt, root='', data_type=None, read_type='pil',
loader=imageLoader, transform=None, target_transform=None,
extensions=None, is_valid_file=None):
super(ImageTxt, self).__init__()
from viclassifier.utils import trans_gen
with open(txt) as f:
lines = f.readlines()
labels = [line.strip('\n').rstrip().split()[-1] for line in lines]
classes, class_to_idx = self._find_classes(labels)
if root == '':
samples = [(line.strip('\n').rstrip().split()[0],
class_to_idx(line.strip('\n').rstrip().split()[-1])) for line in lines if is_image_file(line)]
else:
samples = make_dataset(root, lines, class_to_idx)
if len(samples) == 0:
raise (RuntimeError("Found 0 files!\n"))
self.data_type = data_type
self.read_type = read_type
# self.transform = transform
self.transform = trans_gen.genTrans
self.target_transform = target_transform
self.loader = loader
# self.extensions = extensions
self.classes = classes
self.class_to_idx = class_to_idx
self.samples = samples
self.targets = [s[1] for s in samples]
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (sample, target) where target is class_index of the target class.
"""
path, target = self.samples[index]
sample = self.loader(path, self.read_type)
if self.transform is not None:
# sample = self.transform(sample)
try:
sample = self.transform(self.data_type)(sample)
except:
print("error in transform")
if self.target_transform is not None:
target = self.target_transform(target)
return sample, target
def __len__(self):
return len(self.samples)
def _find_classes(self, labels):
"""
Finds the class folders in a dataset.
Args:
dir (string): Root directory path.
Returns:
tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary.
Ensures:
No class is a subdirectory of another.
"""
# import sys
# if sys.version_info >= (3, 5):
# # Faster and available in Python 3.5 and above
# classes = [d.name for d in os.scandir(dir) if d.is_dir()]
# else:
# classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))]
classes = list(set(labels))
classes.sort()
class_to_idx = {classes[i]: i for i in range(len(classes))}
return classes, class_to_idx
if __name__ == '__main__':
import os, sys
viclassifier_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print(viclassifier_dir)
sys.path.append(viclassifier_dir)
from torch.utils.data import DataLoader
root_dir = r'C:\Users\xxx\cls\full'
train_txt = r'C:\Users\xxx\cls\full\full_train.txt'
test_txt = r'C:\Users\xxx\cls\full\full_test.txt'
train_data = ImageTxt(train_txt, root_dir, 'train')
test_data = ImageTxt(test_txt, root_dir, 'test')
# train_data 和test_data包含多有的训练与测试数据,调用DataLoader批量加载
train_loader = DataLoader(dataset=train_data, batch_size=64, shuffle=True)
test_loader = DataLoader(dataset=test_data, batch_size=64)
if train_data.class_to_idx is not None:
print(train_data.class_to_idx)
if test_data.class_to_idx is not None:
print(test_data.class_to_idx)
if train_loader is not None:
for inputs, labels in train_loader:
print(inputs, labels)
break
if test_loader is not None:
for inputs, labels in test_loader:
print(inputs, labels)
break
| {
"alphanum_fraction": 0.5970812796,
"author": null,
"avg_line_length": 32.2336448598,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "2513c3a7356cfdc0d6f4ec38f7e2ef4af038dbaa",
"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": "fd6c4730e880f35a9429277a6025219315e067cc",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "vic9527/viclassifier",
"max_forks_repo_path": "utils/txt_reader.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "fd6c4730e880f35a9429277a6025219315e067cc",
"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": "vic9527/viclassifier",
"max_issues_repo_path": "utils/txt_reader.py",
"max_line_length": 118,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "fd6c4730e880f35a9429277a6025219315e067cc",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "vic9527/ViClassifier",
"max_stars_repo_path": "utils/txt_reader.py",
"max_stars_repo_stars_event_max_datetime": "2021-11-03T05:05:34.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-03T05:05:34.000Z",
"num_tokens": 2799,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 10347
} |
#!/usr/bin/env python
'''Trains a temporal difference (TD) agent in the tabular pegs on disks domain.'''
# python
import sys
from time import time
# scipy
from scipy.io import loadmat, savemat
from numpy.random import seed
# self
from rl_environment import RlEnvironment
from rl_agent_td import RlAgentTd
def Main():
'''Entrypoint to the program.'''
# PARAMETERS =====================================================================================
params = loadmat("parameters.mat", squeeze_me=True)
randomSeed = params["randomSeed"]
tMax = params["tMax"]
nEpisodes = params["nEpisodes"]
saveFileName = params["saveFileName"]
# INITIALIZATION =================================================================================
# set random seeds
seed(randomSeed)
# initialize agent
agent = RlAgentTd(params)
# RUN TEST =======================================================================================
episodeReturn = []; episodeTime = []
for episode in xrange(nEpisodes):
startTime = time()
episodeReturn.append(0)
env = RlEnvironment(params)
s = env.GetState()
a = agent.GetAction(s)
for t in xrange(tMax):
r = env.Transition(a)
ss = env.GetState()
aa = agent.GetAction(ss)
agent.UpdateQFunction(s, a, r, ss, aa)
s = ss; a = aa
episodeReturn[-1] += r
print("Episode {}.{} had return {}.".format(realization, episode, episodeReturn[-1]))
episodeTime.append(time()-startTime)
print("Agent learned {} values.".format(agent.GetQTableSize()))
saveData = {"episodeReturn":episodeReturn, "episodeTime":episodeTime,
"nValuesLearned":agent.GetQTableSize()}
saveData.update(params)
savemat(saveFileName, saveData)
if __name__ == "__main__":
if len(sys.argv) < 2 or type(sys.argv[1]) != type(""):
print("Usage: trainFile paramsFile")
exit()
realization = 0 if len(sys.argv) < 3 else int(sys.argv[2])
exec("from " + sys.argv[1] + " import Parameters")
Parameters(realization)
Main()
| {
"alphanum_fraction": 0.5840274375,
"author": null,
"avg_line_length": 27.2133333333,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "53c0a3bbd2b163bd8234b357569eee8a353cc100",
"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": "706d0802bda43195d41b953a02380f3d0d731718",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "mgualti/Seq6DofManip",
"max_forks_repo_path": "PegsOnDisksTabular/python/train_td.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "706d0802bda43195d41b953a02380f3d0d731718",
"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": "mgualti/Seq6DofManip",
"max_issues_repo_path": "PegsOnDisksTabular/python/train_td.py",
"max_line_length": 100,
"max_stars_count": 4,
"max_stars_repo_head_hexsha": "706d0802bda43195d41b953a02380f3d0d731718",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "mgualti/Seq6DofManip",
"max_stars_repo_path": "PegsOnDisksTabular/python/train_td.py",
"max_stars_repo_stars_event_max_datetime": "2021-04-08T14:44:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-04-08T03:58:31.000Z",
"num_tokens": 485,
"path": null,
"reason": "from numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2041
} |
from torch import nn
import numpy as np
def optional_repeat(value, times):
""" helper function, to repeat a parameter's value many times
:param value: an single basic python type (int, float, boolean, string), or a list with length equals to times
:param times: int, how many times to repeat
:return: a list with length equal to times
"""
if type(value) is not list:
value = [value]
if len(value) != 1 and len(value) != times:
raise ValueError('The value should be a singleton, or be a list with times length.')
if len(value) == times:
return value # do nothing
return np.array(value).repeat(times).tolist()
class MLP(nn.Module):
""" Multi-near perceptron. That is a k-layer deep network where each layer is a fully-connected layer, with
(optionally) batch-norm, a non-linearity and dropout. The last layer (output) is always a 'pure' linear function.
"""
def __init__(self, in_feat_dims, out_channels, b_norm=True, dropout_rate=0,
non_linearity=nn.ReLU(inplace=True), closure=None):
"""Constructor
:param in_feat_dims: input feature dimensions
:param out_channels: list of ints describing each the number hidden/final neurons. The
:param b_norm: True/False, or list of booleans
:param dropout_rate: int, or list of int values
:param non_linearity: nn.Module
:param closure: optional nn.Module to use at the end of the MLP
"""
super(MLP, self).__init__()
n_layers = len(out_channels)
dropout_rate = optional_repeat(dropout_rate, n_layers-1)
b_norm = optional_repeat(b_norm, n_layers-1)
previous_feat_dim = in_feat_dims
all_ops = []
for depth in range(len(out_channels)):
out_dim = out_channels[depth]
affine_op = nn.Linear(previous_feat_dim, out_dim, bias=True)
all_ops.append(affine_op)
if depth < len(out_channels) - 1:
if b_norm[depth]:
all_ops.append(nn.BatchNorm1d(out_dim))
if non_linearity is not None:
all_ops.append(non_linearity)
if dropout_rate[depth] > 0:
all_ops.append(nn.Dropout(p=dropout_rate[depth]))
previous_feat_dim = out_dim
if closure is not None:
all_ops.append(closure)
self.net = nn.Sequential(*all_ops)
def __call__(self, x):
return self.net(x) | {
"alphanum_fraction": 0.6352753392,
"author": null,
"avg_line_length": 37.4029850746,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "439c52f20b2ba9d013e5ccde8ebfcf7319dc97df",
"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": "191e2664dd1f0d79b176a2a6adbd5898dda04872",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "fjhzhixi/3D-SPS",
"max_forks_repo_path": "models/mlp.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "191e2664dd1f0d79b176a2a6adbd5898dda04872",
"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": "fjhzhixi/3D-SPS",
"max_issues_repo_path": "models/mlp.py",
"max_line_length": 117,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "191e2664dd1f0d79b176a2a6adbd5898dda04872",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "fjhzhixi/3D-SPS",
"max_stars_repo_path": "models/mlp.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T13:42:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-16T07:50:10.000Z",
"num_tokens": 577,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2506
} |
Produce is a book of short fiction and poetry by accomplished UC Davis Undergraduates undergraduate and graduate students. A reinvention of the UCD undergraduate literary magazine known as Seele (pronounced zayluh), Produce was grown in association with the UC Davis English Club.
To purchase, contact the above email or one of the editors. The cost is $10.
2007
Released June 2007
Contents: 148 pages; 19 undergraduate poems, 17 undergraduate pieces of fiction, 14 graduate poems and pieces of fiction
Editors: Crystal Cheney, Tyler Fyotek, Users/BrianAng Brian Ang, Vanessa Uhlig, Users/EliseKane Elise Kane, Jacob Israel Chilton, Users/BoHeeKim Bo Hee Kim, Carmen Lau, Preston Hatfield, Users/JacobRoche J. Richard Roche, Monica Storss
Contributors:
Undergraduate Poetry: Michelle TangJackson, Users/BrianAng Brian Ang, Naushad Ulhaq, Vanessa Uhlig, Nathan Test, Susan Calvillo, Users/JacobRoche Jacob Roche, Users/EliseKane Elise Kane, Arnold Kemp, Alicia Raby, Jacob Israel Chilton, Henry 7 Reneau Jr., Kristen Judd, Collin Brennan, Tyler Fyotek, Toni Chisamore
Undergraduate Fiction: Carmen Lau, Michelle TangJackson, Rachel Slotnick, Ryan Willingham, Preston Hatfield, Long Lim, James Xiao, Users/BoHeeKim Bo Hee Kim, Jessica Ng, Kira McManus, Dahlia GrossmanHeinze, Sam Bivins, Users/JacobRoche J. Richard Roche, Hailey Yeager
Graduate: Monica Storss, Gabrielle Myers, Patricia Killelea, Jeanine Peters, Crystal Anderson, Emily Norwood, Masin Persina, Crystal Cheney
2006
The book was created with no departmental or university funding, released independently through Moonstreet Press and printed in Massachusetts. Prior to its official release, three of the eight editors, (Kaelan Smith, Elise Kane, and Crystal Cheney), were guests on Dr. Andy Jones Dr. Andy Joness esteemed KDVS 90.3 fm radio showDr. Andys Poetry and Technology Hourwhere they explained the book editing process and financial challenges of publishing. They also read some of their own work from the book as a sample for listeners. Produce debuted May 18, 2006 at a release party held in the Art Building lobby. Sacramento band Johanna provided entertainment.
Contents: 31 poems, 20 pieces of fiction
Editors: Kaelan Smith, Tristen Chang, Crystal Cheney, Emily Connors, Elise Kane, James Xiao, Marie Burcham, Sam Spieller
Contributors:
Poetry: S.A. Spieller, Michelle Jackson, Tristen Chang, Patricia Anne Killelea, Elise Kane, Arjuna Neuman, Marie Burcham, Alycia Raby, Arnold Kemp, James Xiao, Nathan Smith, Kaelan Smith, and Michael Giardina.
Fiction: Kaelan Smith, Crystal Cheney, Emily Connor, Tristen Chang, Kate James, Luke Maulding, Melissa Chordas, Marie Burcham, Michael Giardina, Diana Chan, S. A. Spieller, James Xiao.
| {
"alphanum_fraction": 0.7997076023,
"author": null,
"avg_line_length": 109.44,
"converted": null,
"ext": "f",
"file": null,
"hexsha": "b4ad1250f0d4d29c2dcf397b3b6261faaac9f455",
"include": null,
"lang": "FORTRAN",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "voflo/Search",
"max_forks_repo_path": "lab/davisWiki/Produce_%28Book%29.f",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "voflo/Search",
"max_issues_repo_path": "lab/davisWiki/Produce_%28Book%29.f",
"max_line_length": 656,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "voflo/Search",
"max_stars_repo_path": "lab/davisWiki/Produce_%28Book%29.f",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 695,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 2736
} |
import numpy as np
import yields
from scipy import integrate
class SNIa(object):
"""
Class holding the SNIa delay time distribution and yields.
"""
def __init__(self, dtd_name, yield_name, lifetimes_obj, imf_obj,
**kwargs):
"""
Initialize the SN Ia model.
:param dtd_name: Name of the delay time distribution. Currently can be
either "old art" for the old prescription or
"new art power law" for the new one.
:type dtd_name: str
:param yield_name: Name of the yield set being used.
:type yield_name: str
:param lifetimes_obj: Already created Lifetimes object to be used by
the delay time distribution
:type lifetimes_obj: tabulation.Lifetime
:param imf_obj: Already created IMF object to be used to calibrate the
number of SN (for the old ART prescription)
:type imf_obj: tabulation.IMF
:param kwargs: Additional parameters to be passed to the SN Ia DTD
function. For "old art" we need "min_mass", "max_mass",
and "exploding_fraction" (the fraction of stars between
min_mass and max_mass that explode as SN Ia. For
"art power law" we only need the overall number of SNIa
that explode in a unit mass SSP: "number_sn_ia"
"""
# parse the DTD
if dtd_name.lower() == "old art":
self.sn_dtd = np.vectorize(self.old_art_dtd, otypes=[float])
elif dtd_name.lower() == "art power law":
self.sn_dtd = np.vectorize(self.art_power_law_dtd, otypes=[float])
else:
raise ValueError("SN Ia DTD not supported.")
# store the lifetime objects
self.lifetimes = lifetimes_obj
self.imf = imf_obj
# parse the yields
if yield_name.lower() == "nomoto_18":
self.model = yields.Yields("nomoto_18_Ia_W7")
self.metallicities = [0.002, 0.02]
else:
raise ValueError("SN Ia model set not recognized")
# set the number of SN Ia per unit mass SSP. For old art we need to
# calculate it.
if dtd_name.lower() == "old art":
num_in_range = integrate.quad(self.imf.normalized_dn_dm,
kwargs["min_mass"],
kwargs["max_mass"])[0]
self.number_sn_Ia = num_in_range * kwargs["exploding_fraction"]
elif dtd_name.lower() == "art power law":
self.number_sn_Ia = kwargs["number_sn_ia"]
def old_art_dtd(self, age):
"""
SN Ia rate previously coded in ART. This is normalized to produce
the desired number of SN Ia (as specified by min_mass, max_mass, and
exploding_fraction) at infinity.
:param age: Age (in years) at which to get the SN rate.
:return: SN Ia rate, in units of SN per year per unit stellar mass.
"""
return self.number_sn_Ia * self.old_art_phi_per_dt(age)
@staticmethod
def old_art_phi_per_dt(age):
"""
SN rate as previously coded in ART. Is normalized to 1 at infinity.
This function returns phi / dt.
:param age: Age (in years) at which to get the SN Ia rate.
:return: rate, normalized to 1.
"""
t_eject = 2E8 # years
# no SN Ia early on
if age < 0.1 * t_eject:
return 0
# make the heart of the DTD. The last term is to make it normalized.
def sub_func(x):
return np.exp(-x ** 2) * np.sqrt(x ** 3) / 1.812804954
normalized_age = t_eject / age
return sub_func(normalized_age) / t_eject
def art_power_law_dtd(self, age, z):
"""
SN rate going in the new ART prescription.
This is a power law with index -1.13, normalized to produce the desired
number of supernovae after one Hubble time.
See http://nbviewer.jupyter.org/github/gillenbrown/Tabulation/blob/master/notebooks/sn_Ia.ipynb
for more info.
:param age: Age (in years) at which to get the SN Ia rates.
:param z: Metallicity of the progenitor. This is used to determine the
lifetime at which SN Ia start.
:return: SN Ia rate in supernovae per year per unit stellar mass.
"""
new_art_s = 1.13
min_age = self.lifetimes.lifetime(8.0, z)
if age < min_age:
return 0
else:
return self.number_sn_Ia * 2.3480851917 * age ** (-new_art_s)
def ejected_mass(self, element, metallicity):
"""
Get the ejected mass of a given element in a SN Ia explosion.
:param element: element to get the ejected mass of
:param metallicity: Metallicity of the progenitor
:return: Ejected mass of that element in solar masses
"""
if metallicity not in self.metallicities:
raise ValueError("Can only get values at the exact metallicities.")
# this is basically a convenience function to just get the model.
self.model.set_metallicity(metallicity)
if element == "total_metals":
return self.model.ejecta_sum(metal_only=True)
else:
try:
return self.model.abundances[element]
except KeyError: # element not present
return 0
| {
"alphanum_fraction": 0.5940163191,
"author": null,
"avg_line_length": 39.9637681159,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "f82784fdcbcae9e4b7ab0348fbde5e82be285e98",
"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": "a894d530ca8efe270c42da385150debaaf132fc5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gillenbrown/Tabulation",
"max_forks_repo_path": "tabulation/sn_Ia.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a894d530ca8efe270c42da385150debaaf132fc5",
"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": "gillenbrown/Tabulation",
"max_issues_repo_path": "tabulation/sn_Ia.py",
"max_line_length": 103,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "a894d530ca8efe270c42da385150debaaf132fc5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gillenbrown/Tabulation",
"max_stars_repo_path": "tabulation/sn_Ia.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1313,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 5515
} |
### A Pluto.jl notebook ###
# v0.12.20
using Markdown
using InteractiveUtils
# ╔═╡ 88071c54-619d-11eb-3007-7db2c4a86215
begin
using MLJ
using LeastSquaresSVM
using MLJModels
using DataFrames
using StatsPlots
using BenchmarkTools
end
# ╔═╡ ae6803ac-619f-11eb-0d67-cb1be3400e9c
@load SVC pkg = LIBSVM;
# ╔═╡ b1598d44-619d-11eb-1efa-eb785775d940
gr();
# ╔═╡ cb3ab102-619d-11eb-1339-81cf03974fee
X, y = MLJ.make_moons(250; noise=0.3);
# ╔═╡ d7e2967c-619d-11eb-0d7f-9f0e79b48902
dfCircles = DataFrame(X);
# ╔═╡ e37d9ae0-619d-11eb-2ff0-3394d6447c9f
dfCircles.y = y;
# ╔═╡ 15c33f64-619e-11eb-0745-8fe5b6cf13a9
first(dfCircles, 3)
# ╔═╡ d0318284-619e-11eb-3fa1-59fb348e5d06
d = MLJ.int(y; type=Int);
# ╔═╡ 6db3e5d8-619f-11eb-1512-4d23ffd7adb3
dfCircles.c = d;
# ╔═╡ e7202e7e-619d-11eb-1b4a-e77c27e2d200
@df dfCircles scatter(:x1, :x2, colour=:c)
# ╔═╡ 3ca54cf6-619e-11eb-1a89-d7e83e9de721
function train_lssvm_hp(X, y, train)
model = LSSVClassifier()
r1 = range(model, :σ, lower=1e-2, upper=10.0)
r2 = range(model, :γ, lower=1, upper=200.0)
self_tuning_model = TunedModel(
model=model,
tuning=RandomSearch(),
resampling=CV(nfolds=5),
range=[r1, r2],
measure=accuracy,
n=1000
)
mach = machine(self_tuning_model, X, y)
fit!(mach, rows=train)
return mach
end;
# ╔═╡ a17664ba-619f-11eb-317c-79e5a717faca
function train_svm_hp(X, y, train)
model = SVC()
r1 = range(model, :cost, lower=1, upper=1000.0)
r2 = range(model, :gamma, lower=1e-2, upper=10.0)
self_tuning_model = TunedModel(
model=model,
tuning=RandomSearch(),
resampling=CV(nfolds=5),
range=[r1, r2],
measure=accuracy,
n=1000
)
mach = machine(self_tuning_model, X, y)
fit!(mach, rows=train)
return mach
end;
# ╔═╡ a6aa28f2-619f-11eb-0f6a-9167af8e877a
Xstd = MLJ.transform(MLJ.fit!(MLJ.machine(Standardizer(), X)), X);
# ╔═╡ e03600a0-619f-11eb-15a2-3f4677c2f723
train, test = MLJ.partition(eachindex(y), 0.8, shuffle=true);
# ╔═╡ 67d60f1a-61a4-11eb-3d38-35c2ccbd2744
@benchmark train_lssvm_hp($Xstd, $y, $train)
# ╔═╡ 70b7286c-61a4-11eb-28d0-4fbb79a7f373
@benchmark train_svm_hp($Xstd, $y, $train)
# ╔═╡ c1e62e68-619f-11eb-32b0-a744377d1b3c
mach1 = train_lssvm_hp(Xstd, y, train);
# ╔═╡ 2792dda8-619e-11eb-0da5-9712e7cb14de
mach2 = train_svm_hp(Xstd, y, train);
# ╔═╡ c4f54008-61a4-11eb-3b9e-994353e3ff5b
function predict_model(y, test, mach)
results = MLJ.predict(mach, rows=test)
acc = MLJ.accuracy(results, y[test])
return acc
end;
# ╔═╡ 3689b474-61a5-11eb-0c60-a5c7c2a8e51e
acc1 = predict_model(y, test, mach1)
# ╔═╡ 4d1edf3c-61a5-11eb-30a9-3dc0a13fcba0
acc2 = predict_model(y, test, mach2)
# ╔═╡ 53c88e0c-61a5-11eb-3581-852491d59ffb
# ╔═╡ f9e794a6-61a3-11eb-316c-21c05947feaa
# ╔═╡ f6c26bfc-61a3-11eb-240c-97f3e8e48d63
# ╔═╡ e1dfbd84-61a3-11eb-2f44-f7146ce3045e
# ╔═╡ dbaacbf2-61a3-11eb-25b6-d33f4d04a74d
# ╔═╡ d449e050-61a3-11eb-1087-29a8e7b2b7dc
# ╔═╡ 03119e10-619e-11eb-28c6-ef029e684719
# ╔═╡ fcdf5636-619d-11eb-3019-953155bd46d3
# ╔═╡ b55b6cc8-619d-11eb-2829-7dbc5071a4e4
# ╔═╡ b544cca2-619d-11eb-30a5-c95dcb2294ea
# ╔═╡ b52c910a-619d-11eb-28af-b52571b41a82
# ╔═╡ b5135dd4-619d-11eb-226b-ad3792f806d6
# ╔═╡ b4fbe730-619d-11eb-294b-d100ca550814
# ╔═╡ b4e0b232-619d-11eb-3807-898664a71425
# ╔═╡ b4c5fc4c-619d-11eb-1567-650d59a0de08
# ╔═╡ b4abcbec-619d-11eb-3a17-b9064e2eedbc
# ╔═╡ b491fa8c-619d-11eb-3863-3ddd7fc0aa54
# ╔═╡ b4768d88-619d-11eb-0500-d3d24f8dbc5e
# ╔═╡ b45e3d8c-619d-11eb-081c-b9b953986714
# ╔═╡ b442d9b4-619d-11eb-36b5-81efc98e22cd
# ╔═╡ b42a464e-619d-11eb-11cb-870135a4f5a9
# ╔═╡ b40e3044-619d-11eb-0f41-8b657055d962
# ╔═╡ b3f4735c-619d-11eb-1610-057c920d8c69
# ╔═╡ b3a6646e-619d-11eb-1f5e-17020f493ab5
# ╔═╡ Cell order:
# ╠═88071c54-619d-11eb-3007-7db2c4a86215
# ╠═ae6803ac-619f-11eb-0d67-cb1be3400e9c
# ╠═b1598d44-619d-11eb-1efa-eb785775d940
# ╠═cb3ab102-619d-11eb-1339-81cf03974fee
# ╠═d7e2967c-619d-11eb-0d7f-9f0e79b48902
# ╠═e37d9ae0-619d-11eb-2ff0-3394d6447c9f
# ╠═15c33f64-619e-11eb-0745-8fe5b6cf13a9
# ╠═d0318284-619e-11eb-3fa1-59fb348e5d06
# ╠═6db3e5d8-619f-11eb-1512-4d23ffd7adb3
# ╠═e7202e7e-619d-11eb-1b4a-e77c27e2d200
# ╠═3ca54cf6-619e-11eb-1a89-d7e83e9de721
# ╠═a17664ba-619f-11eb-317c-79e5a717faca
# ╠═a6aa28f2-619f-11eb-0f6a-9167af8e877a
# ╠═e03600a0-619f-11eb-15a2-3f4677c2f723
# ╠═67d60f1a-61a4-11eb-3d38-35c2ccbd2744
# ╠═70b7286c-61a4-11eb-28d0-4fbb79a7f373
# ╠═c1e62e68-619f-11eb-32b0-a744377d1b3c
# ╠═2792dda8-619e-11eb-0da5-9712e7cb14de
# ╠═c4f54008-61a4-11eb-3b9e-994353e3ff5b
# ╠═3689b474-61a5-11eb-0c60-a5c7c2a8e51e
# ╠═4d1edf3c-61a5-11eb-30a9-3dc0a13fcba0
# ╠═53c88e0c-61a5-11eb-3581-852491d59ffb
# ╠═f9e794a6-61a3-11eb-316c-21c05947feaa
# ╠═f6c26bfc-61a3-11eb-240c-97f3e8e48d63
# ╠═e1dfbd84-61a3-11eb-2f44-f7146ce3045e
# ╠═dbaacbf2-61a3-11eb-25b6-d33f4d04a74d
# ╠═d449e050-61a3-11eb-1087-29a8e7b2b7dc
# ╠═03119e10-619e-11eb-28c6-ef029e684719
# ╠═fcdf5636-619d-11eb-3019-953155bd46d3
# ╠═b55b6cc8-619d-11eb-2829-7dbc5071a4e4
# ╠═b544cca2-619d-11eb-30a5-c95dcb2294ea
# ╠═b52c910a-619d-11eb-28af-b52571b41a82
# ╠═b5135dd4-619d-11eb-226b-ad3792f806d6
# ╠═b4fbe730-619d-11eb-294b-d100ca550814
# ╠═b4e0b232-619d-11eb-3807-898664a71425
# ╠═b4c5fc4c-619d-11eb-1567-650d59a0de08
# ╠═b4abcbec-619d-11eb-3a17-b9064e2eedbc
# ╠═b491fa8c-619d-11eb-3863-3ddd7fc0aa54
# ╠═b4768d88-619d-11eb-0500-d3d24f8dbc5e
# ╠═b45e3d8c-619d-11eb-081c-b9b953986714
# ╠═b442d9b4-619d-11eb-36b5-81efc98e22cd
# ╠═b42a464e-619d-11eb-11cb-870135a4f5a9
# ╠═b40e3044-619d-11eb-0f41-8b657055d962
# ╠═b3f4735c-619d-11eb-1610-057c920d8c69
# ╠═b3a6646e-619d-11eb-1f5e-17020f493ab5
| {
"alphanum_fraction": 0.729468599,
"author": null,
"avg_line_length": 23.4831932773,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "62d7d92bb5d316eab0d669db9c3b83c969b9632b",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-27T13:58:11.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-27T13:58:11.000Z",
"max_forks_repo_head_hexsha": "749f4782d369aacbbeb3b759220b59ece43e602f",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "edwinb-ai/LSSVM-benchmarks",
"max_forks_repo_path": "src/binary_generic.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "749f4782d369aacbbeb3b759220b59ece43e602f",
"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": "edwinb-ai/LSSVM-benchmarks",
"max_issues_repo_path": "src/binary_generic.jl",
"max_line_length": 66,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "749f4782d369aacbbeb3b759220b59ece43e602f",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "edwinb-ai/LSSVM-benchmarks",
"max_stars_repo_path": "src/binary_generic.jl",
"max_stars_repo_stars_event_max_datetime": "2021-01-27T13:57:56.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-27T13:57:56.000Z",
"num_tokens": 3210,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 5589
} |
import cv2
import mxnet as mx
import numpy as np
import scipy as sc
from utils.math import Distances
from dataProcessor.tiffReader import GEOMAP
from validation.osmClasses import OSMClasses
from utils.labelProcessor import LabelProcessor
from validation.clcClasses import CLCClasses
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import mean_squared_log_error, normalized_mutual_info_score
from lib.mapar.mapar import Mapar
from sklearn.neighbors import BallTree
from sklearn.neighbors import DistanceMetric
class MultiClassValidation():
'''
Each tile is represented by the proportion taken by each class in the image.
A simple regressor trained supervised on the real proportion of labels. The quality of embeddings
is measured by the quality of the regressor.
MAP@R and gSil determine the score without a additional regressor.
'''
def __init__(self, size, classifiers={'knn': KNeighborsClassifier()}, distance=Distances.L2_Dist, validation_map=GEOMAP.OSM):
self.distance = distance
self.classifiers = classifiers
self.labelProcessor = LabelProcessor(size, validation_map)
if validation_map == GEOMAP.OSM:
self.colorToLabel = OSMClasses.getLabel
self.nb_labels = 13
elif validation_map == GEOMAP.CLC:
self.colorToLabel = CLCClasses.getLabel
self.nb_labels = 45
def train(self, embeddings, class_imgs):
data, labels = self.getTrainData(embeddings, class_imgs)
for key, classifier in self.classifiers.items():
classifier.fit(data, labels)
return self
def predict(self, embeddings, class_imgs):
data, labels = self.getTrainData(embeddings, class_imgs)
for key, classifier in self.classifiers.items():
pred_labels = classifier.predict(data)
for clabel in range(0, len(labels)):
print(labels[clabel], pred_labels[clabel])
def silhouette(X, y):
y = y+1e-8
weights = y.sum(axis=1)
y = y/np.expand_dims(y.sum(axis=1), axis=1)
out = 0
x_tree = BallTree(
X, leaf_size=2, metric=DistanceMetric.get_metric("l2"))
xdist, xind = x_tree.query(X, k=X.shape[0], sort_results=True)
a_dists = []
b_dists = []
for cluster in range(0, y.shape[1]):
intra = np.min([np.repeat(y[xind[:, :1]][:, :, cluster],
xind[:,1:].shape[1], axis=1), y[xind[:, 1:]][:, :, cluster]], axis=0)
# print(intra.shape)
a_dist = 1.0/intra.sum(axis=1) * \
np.sum(xdist[:, 1:] * intra, axis=1)
a_dists.append(a_dist)
for compcluster in range(0, y.shape[1]):
if cluster != compcluster:
inter1 = np.repeat(
y[xind[:, :1]][:, :, cluster], xind[:, 1:].shape[1], axis=1)
inter2 = y[xind[:, 1:]][:, :, compcluster]
inter12 = np.min([inter1, inter2], axis=0)
inter3 = np.repeat(
y[xind[:, :1]][:, :, compcluster], xind[:, 1:].shape[1], axis=1)
inter4 = y[xind[:, 1:]][:, :, cluster]
inter34 = np.min([inter3, inter4], axis=0)
inter = np.max([inter12, inter34], axis=0)
b_dist = 1.0/inter.sum(axis=1) * \
np.sum(xdist[:, 1:] * inter, axis=1)
b_dists.append(b_dist)
a_dist = np.min(a_dists, axis=0)
b_dist = np.min(b_dists, axis=0)
out = ((b_dist-a_dist)/np.max([b_dist, a_dist], axis=(0)))
return (out*weights).sum()/weights.sum()
def scores(self, embeddings, class_imgs):
tsum_error = {}
nmi = {}
silhouette_scores = {}
ccc = {}
mapar1 = {}
mapar5 = {}
mapar10 = {}
data, labels = self.getTrainData(embeddings, class_imgs)
for key, classifier in self.classifiers.items():
pred_labels = classifier.predict(data)
pred_labels = pred_labels / \
np.expand_dims(pred_labels.sum(axis=1), axis=1)
pred_labels = np.clip(pred_labels, 0, 1)
#err = mean_squared_log_error(pred_labels, labels)
sum_error = 0
for batch in range(0, len(labels)):
sum_error += np.sum(np.abs(pred_labels[batch] - labels[batch]))
sum_error = sum_error / len(labels)
tsum_error[key] = sum_error
mean_nmi_score = 0
for batch in range(0, len(pred_labels)):
score = normalized_mutual_info_score(pred_labels[batch].astype(
int), labels[batch].astype(int), average_method='arithmetic')
mean_nmi_score += score
nmi[key] = mean_nmi_score/len(pred_labels)
silhouette_scores[key] = MultiClassValidation.silhouette(
data, labels)
dendro = sc.cluster.hierarchy.linkage(labels, 'single')
dists = sc.spatial.distance.pdist(data)
cophe_dists = sc.cluster.hierarchy.cophenet(dendro)
ccc[key] = np.corrcoef(dists, cophe_dists)[0, 1]
mapar1[key] = Mapar.score(data, labels, k=1)
mapar5[key] = Mapar.score(data, labels, k=5)
mapar10[key] = Mapar.score(data, labels, k=10)
return tsum_error, nmi, silhouette_scores, ccc, mapar1, mapar5, mapar10
def getTrainData(self, embeddings, class_imgs):
data = None
labels = None
np_class_imgs = class_imgs
np_embeddings = embeddings
for np_class_img in range(0, len(np_class_imgs)):
label = self.labelProcessor.getLabels(
np_class_imgs[np_class_img], processed=True)
# print(idx)
if label.sum() > 0:
if data is None:
data = np.expand_dims(np_embeddings[np_class_img], axis=0)
labels = np.expand_dims(label, axis=0)
else:
data = np.concatenate((data, np.expand_dims(
np_embeddings[np_class_img], axis=0)), axis=0)
labels = np.concatenate(
(labels, np.expand_dims(label, axis=0)), axis=0)
labels = labels/np.expand_dims(labels.sum(axis=1), axis=1)
return data, labels
def unitTest():
def mean(img):
return img.mean(axis=(0, 1), exclude=True)
images, coords, px_coords, valid = batchSampler.unitTest(32, 64)
emb_pred, emb_pos, emb_neg = images
class_pred, class_pos, class_neg = valid
embs = nd.concat(mean(emb_pred), mean(emb_pos), dim=0)
class_imgs = nd.concat(class_pred, class_pos, dim=0)
embs = nd.concat(embs, mean(emb_neg), dim=0)
class_imgs = nd.concat(class_imgs, class_neg, dim=0)
validator = Validation(embs[:int(len(embs)/2)],
class_imgs[:int(len(embs)/2)])
validator.train()
acc = validator.accurancy(
embs[int(len(embs)/2):], class_imgs[int(len(embs)/2):])
print(acc)
| {
"alphanum_fraction": 0.5867895545,
"author": null,
"avg_line_length": 38.9184782609,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "303de942c76947c2b07d7f5caa9f36b662f7f6a5",
"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": "c77169b06100fc4bcc5d8967474836221ce551d2",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "fisch92/Metric-embeddings-for-satellite-image-classification",
"max_forks_repo_path": "validation/multi_class_validation.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c77169b06100fc4bcc5d8967474836221ce551d2",
"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": "fisch92/Metric-embeddings-for-satellite-image-classification",
"max_issues_repo_path": "validation/multi_class_validation.py",
"max_line_length": 129,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "c77169b06100fc4bcc5d8967474836221ce551d2",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "fisch92/Metric-embeddings-for-satellite-image-classification",
"max_stars_repo_path": "validation/multi_class_validation.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-24T04:29:21.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-03-24T04:29:21.000Z",
"num_tokens": 1745,
"path": null,
"reason": "import numpy,import scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 7161
} |
[STATEMENT]
lemma list_dtree_subset:
assumes "xs |\<subseteq>| ys" and "list_dtree (Node r ys)"
shows "list_dtree (Node r xs)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. list_dtree (Node r xs)
[PROOF STEP]
using wf_dlverts_sub[OF assms(1)] wf_darcs_sub[OF assms(1)] assms(2)
[PROOF STATE]
proof (prove)
using this:
wf_dlverts (Node ?r ys) \<Longrightarrow> wf_dlverts (Node ?r xs)
wf_darcs (Node ?r' ys) \<Longrightarrow> wf_darcs (Node ?r xs)
list_dtree (Node r ys)
goal (1 subgoal):
1. list_dtree (Node r xs)
[PROOF STEP]
by (unfold_locales) (fast dest: list_dtree.wf_lverts list_dtree.wf_arcs)+ | {
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": "Query_Optimization_List_Dtree",
"hexsha": null,
"include": null,
"lang": null,
"length": 2,
"llama_tokens": 277,
"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
import fenics as fa
class PoissonRobot:
def __init__(self, args):
self.args = args
self.name = 'robot'
self._build_mesh()
self._build_function_space()
self._set_detailed_boundary_flags()
def _build_mesh(self):
self.width = 0.5
mesh = fa.RectangleMesh(fa.Point(0, 0), fa.Point(self.width, 10), 2, 20, 'crossed')
self.mesh = mesh
def _build_function_space(self):
self.V = fa.VectorFunctionSpace(self.mesh, 'P', 1)
self.W = fa.FunctionSpace(self.mesh, 'DG', 0)
self.num_dofs = self.V.dim()
self.coo_dof = self.V.tabulate_dof_coordinates()
def _set_detailed_boundary_flags(self):
x1 = self.coo_dof[:, 0]
x2 = self.coo_dof[:, 1]
# [bottom, left_x, left_y, right_x, right_y]
boundary_flags_list = [np.zeros(self.num_dofs) for i in range(5)]
counter_left = 0
counter_right = 0
for i in range(self.num_dofs):
if x2[i] < 1e-10:
boundary_flags_list[0][i] = 1
else:
if x1[i] < 1e-10:
if counter_left % 2 == 0:
boundary_flags_list[1][i] = 1
else:
boundary_flags_list[2][i] = 1
counter_left += 1
if x1[i] > self.width - 1e-10:
if counter_right % 2 == 0:
boundary_flags_list[3][i] = 1
else:
boundary_flags_list[4][i] = 1
counter_right += 1
self.boundary_flags_list = boundary_flags_list
def compute_areas(self):
w = fa.Function(self.W)
area = np.zeros(self.W.dim())
for i in range(self.W.dim()):
w.vector()[:] = 0
w.vector()[i] = 1
area[i] = fa.assemble(w * fa.dx)
return area
| {
"alphanum_fraction": 0.5153246753,
"author": null,
"avg_line_length": 33.1896551724,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "1ef00aa22d9b7249192d1fe0be8c160963bc972d",
"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": "4cf184457c9d7add88d27ce4a3f72ca5f886c2b1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "xingyuansun/amorsyn",
"max_forks_repo_path": "soft_robot/transformer.py",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "4cf184457c9d7add88d27ce4a3f72ca5f886c2b1",
"max_issues_repo_issues_event_max_datetime": "2021-11-25T16:45:00.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-11-25T11:10:26.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "xingyuansun/amorsyn",
"max_issues_repo_path": "soft_robot/transformer.py",
"max_line_length": 91,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "4cf184457c9d7add88d27ce4a3f72ca5f886c2b1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "xingyuansun/amorsyn",
"max_stars_repo_path": "soft_robot/transformer.py",
"max_stars_repo_stars_event_max_datetime": "2021-12-01T15:16:17.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-12-01T03:48:05.000Z",
"num_tokens": 509,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1925
} |
"""
Functions defined in the Pico Technology SDK v10.6.10.24
"""
from ctypes import (c_int8, c_int16, c_uint16, c_int32, c_uint32, c_int64,
c_uint64, c_float, c_double, c_void_p, POINTER)
from numpy.ctypeslib import ndpointer
from ...picotech import c_enum
from ..errors import PICO_STATUS, PICO_INFO
from .callbacks import (
GetOverviewBuffersMaxMin,
BlockReady,
ps2000aDataReady,
ps2000aStreamingReady,
PS3000_CALLBACK_FUNC,
ps3000aDataReady,
ps3000aStreamingReady,
ps4000DataReady,
ps4000StreamingReady,
ps4000aDataReady,
ps4000aStreamingReady,
ps5000DataReady,
ps5000StreamingReady,
ps5000aDataReady,
ps5000aStreamingReady,
ps6000DataReady,
ps6000StreamingReady,
)
from .structs import (
PS2000ADigitalChannelDirections,
PS2000APwqConditions,
PS2000ATriggerChannelProperties,
PS2000ATriggerConditions,
PS2000PwqConditions,
PS2000TriggerChannelProperties,
PS2000TriggerConditions,
PS3000ADigitalChannelDirections,
PS3000APwqConditions,
PS3000APwqConditionsV2,
PS3000ATriggerChannelProperties,
PS3000ATriggerConditions,
PS3000ATriggerConditionsV2,
PS3000ATriggerInfo,
PS3000PwqConditions,
PS3000TriggerChannelProperties,
PS3000TriggerConditions,
PS4000AChannelLedSetting,
PS4000ACondition,
PS4000AConnectDetect,
PS4000ADirection,
PS4000ATriggerChannelProperties,
PS4000PwqConditions,
PS4000TriggerChannelProperties,
PS4000TriggerConditions,
PS5000APwqConditions,
PS5000ATriggerChannelProperties,
PS5000ATriggerConditions,
PS5000ATriggerInfo,
PS5000PwqConditions,
PS5000TriggerChannelProperties,
PS5000TriggerConditions,
PS6000PwqConditions,
PS6000TriggerChannelProperties,
PS6000TriggerConditions
)
# The structure for each item in a *_funcptrs list is:
#
# (SDK_function_name, an_alias_for_the_function_name, return_data_type, errcheck_callable,
# (ctype, SDK_type, SDK_argument_name),
# ************************ SDK functions for ps2000 ************************
ps2000_funcptrs = [
('ps2000PingUnit', 'PingUnit', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle')]
),
('ps2000SetAdvTriggerChannelConditions', 'SetAdvTriggerChannelConditions', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS2000TriggerConditions), 'PS2000_TRIGGER_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions')]
),
('ps2000SetAdvTriggerChannelDirections', 'SetAdvTriggerChannelDirections', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS2000_THRESHOLD_DIRECTION', 'channelA'),
(c_enum, 'PS2000_THRESHOLD_DIRECTION', 'channelB'),
(c_enum, 'PS2000_THRESHOLD_DIRECTION', 'channelC'),
(c_enum, 'PS2000_THRESHOLD_DIRECTION', 'channelD'),
(c_enum, 'PS2000_THRESHOLD_DIRECTION', 'ext')]
),
('ps2000SetAdvTriggerChannelProperties', 'SetAdvTriggerChannelProperties', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS2000TriggerChannelProperties), 'PS2000_TRIGGER_CHANNEL_PROPERTIES*', 'channelProperties'),
(c_int16, 'int16_t', 'nChannelProperties'),
(c_int32, 'int32_t', 'autoTriggerMilliseconds')]
),
('ps2000SetAdvTriggerDelay', 'SetAdvTriggerDelay', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'delay'),
(c_float, 'float', 'preTriggerDelay')]
),
('ps2000SetPulseWidthQualifier', 'SetPulseWidthQualifier', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS2000PwqConditions), 'PS2000_PWQ_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'PS2000_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'lower'),
(c_uint32, 'uint32_t', 'upper'),
(c_enum, 'PS2000_PULSE_WIDTH_TYPE', 'type')]
),
('ps2000_close_unit', 'CloseUnit', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle')]
),
('ps2000_flash_led', 'FlashLed', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle')]
),
('ps2000_get_streaming_last_values', 'GetStreamingLastValues', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(GetOverviewBuffersMaxMin, 'GetOverviewBuffersMaxMin', 'lpGetOverviewBuffersMaxMin')]
),
('ps2000_get_streaming_values', 'GetStreamingValues', c_uint32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_double), 'double*', 'start_time'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_a_max'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_a_min'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_b_max'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_b_min'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_c_max'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_c_min'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_d_max'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_d_min'),
(POINTER(c_int16), 'int16_t*', 'overflow'),
(POINTER(c_uint32), 'uint32_t*', 'triggerAt'),
(POINTER(c_int16), 'int16_t*', 'triggered'),
(c_uint32, 'uint32_t', 'no_of_values'),
(c_uint32, 'uint32_t', 'noOfSamplesPerAggregate')]
),
('ps2000_get_streaming_values_no_aggregation', 'GetStreamingValuesNoAggregation', c_uint32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_double), 'double*', 'start_time'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_a'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_b'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_c'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_d'),
(POINTER(c_int16), 'int16_t*', 'overflow'),
(POINTER(c_uint32), 'uint32_t*', 'triggerAt'),
(POINTER(c_int16), 'int16_t*', 'trigger'),
(c_uint32, 'uint32_t', 'no_of_values')]
),
('ps2000_get_timebase', 'GetTimebase', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'timebase'),
(c_int32, 'int32_t', 'no_of_samples'),
(POINTER(c_int32), 'int32_t*', 'time_interval'),
(POINTER(c_int16), 'int16_t*', 'time_units'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'max_samples')]
),
('ps2000_get_times_and_values', 'GetTimesAndValues', c_int32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int32), 'int32_t*', 'times'),
(POINTER(c_int16), 'int16_t*', 'buffer_a'),
(POINTER(c_int16), 'int16_t*', 'buffer_b'),
(POINTER(c_int16), 'int16_t*', 'buffer_c'),
(POINTER(c_int16), 'int16_t*', 'buffer_d'),
(POINTER(c_int16), 'int16_t*', 'overflow'),
(c_int16, 'int16_t', 'time_units'),
(c_int32, 'int32_t', 'no_of_values')]
),
('ps2000_get_unit_info', 'GetUnitInfo', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int8), 'int8_t*', 'string'),
(c_int16, 'int16_t', 'string_length'),
(c_int16, 'int16_t', 'line')]
),
('ps2000_get_values', 'GetValues', c_int32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'buffer_a'),
(POINTER(c_int16), 'int16_t*', 'buffer_b'),
(POINTER(c_int16), 'int16_t*', 'buffer_c'),
(POINTER(c_int16), 'int16_t*', 'buffer_d'),
(POINTER(c_int16), 'int16_t*', 'overflow'),
(c_int32, 'int32_t', 'no_of_values')]
),
('ps2000_last_button_press', 'LastButtonPress', c_int16, None,
[(c_int16, 'int16_t', 'handle')]
),
('ps2000_open_unit', 'OpenUnit', c_int16, None,
[]
),
('ps2000_open_unit_async', 'OpenUnitAsync', c_int16, None,
[]
),
('ps2000_open_unit_progress', 'OpenUnitProgress', c_int16, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int16), 'int16_t*', 'progress_percent')]
),
('ps2000_overview_buffer_status', 'OverviewBufferStatus', c_int16, 'errcheck_one',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'previous_buffer_overrun')]
),
('ps2000_ready', 'Ready', c_int16, 'errcheck_negative_one',
[(c_int16, 'int16_t', 'handle')]
),
('ps2000_run_block', 'RunBlock', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'no_of_values'),
(c_int16, 'int16_t', 'timebase'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'time_indisposed_ms')]
),
('ps2000_run_streaming', 'RunStreaming', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'sample_interval_ms'),
(c_int32, 'int32_t', 'max_samples'),
(c_int16, 'int16_t', 'windowed')]
),
('ps2000_run_streaming_ns', 'RunStreamingNs', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'sample_interval'),
(c_enum, 'PS2000_TIME_UNITS', 'time_units'),
(c_uint32, 'uint32_t', 'max_samples'),
(c_int16, 'int16_t', 'auto_stop'),
(c_uint32, 'uint32_t', 'noOfSamplesPerAggregate'),
(c_uint32, 'uint32_t', 'overview_buffer_size')]
),
('ps2000_set_channel', 'SetChannel', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_int16, 'int16_t', 'dc'),
(c_int16, 'int16_t', 'range')]
),
('ps2000_set_ets', 'SetEts', c_int32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'mode'),
(c_int16, 'int16_t', 'ets_cycles'),
(c_int16, 'int16_t', 'ets_interleave')]
),
('ps2000_set_led', 'SetLed', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'state')]
),
('ps2000_set_light', 'SetLight', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'state')]
),
('ps2000_set_sig_gen_arbitrary', 'SetSigGenArbitrary', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(ndpointer(dtype=c_int8, ndim=1, flags='C_CONTIGUOUS'), 'uint8_t*', 'arbitraryWaveform'),
(c_int32, 'int32_t', 'arbitraryWaveformSize'),
(c_enum, 'PS2000_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'sweeps')]
),
('ps2000_set_sig_gen_built_in', 'SetSigGenBuiltIn', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_enum, 'PS2000_WAVE_TYPE', 'waveType'),
(c_float, 'float', 'startFrequency'),
(c_float, 'float', 'stopFrequency'),
(c_float, 'float', 'increment'),
(c_float, 'float', 'dwellTime'),
(c_enum, 'PS2000_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'sweeps')]
),
('ps2000_set_trigger', 'SetTrigger', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_int16, 'int16_t', 'direction'),
(c_int16, 'int16_t', 'delay'),
(c_int16, 'int16_t', 'auto_trigger_ms')]
),
('ps2000_set_trigger2', 'SetTrigger2', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_int16, 'int16_t', 'direction'),
(c_float, 'float', 'delay'),
(c_int16, 'int16_t', 'auto_trigger_ms')]
),
('ps2000_stop', 'Stop', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle')]
),
]
# ************************ SDK functions for ps2000aApi ************************
ps2000aApi_funcptrs = [
('ps2000aCloseUnit', 'CloseUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps2000aEnumerateUnits', 'EnumerateUnits', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'count'),
(POINTER(c_int8), 'int8_t*', 'serials'),
(POINTER(c_int16), 'int16_t*', 'serialLth')]
),
('ps2000aFlashLed', 'FlashLed', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'start')]
),
('ps2000aGetAnalogueOffset', 'GetAnalogueOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS2000A_RANGE', 'range'),
(c_enum, 'PS2000A_COUPLING', 'coupling'),
(POINTER(c_float), 'float*', 'maximumVoltage'),
(POINTER(c_float), 'float*', 'minimumVoltage')]
),
('ps2000aGetChannelInformation', 'GetChannelInformation', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS2000A_CHANNEL_INFO', 'info'),
(c_int32, 'int32_t', 'probe'),
(POINTER(c_int32), 'int32_t*', 'ranges'),
(POINTER(c_int32), 'int32_t*', 'length'),
(c_int32, 'int32_t', 'channels')]
),
('ps2000aGetMaxDownSampleRatio', 'GetMaxDownSampleRatio', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'noOfUnaggreatedSamples'),
(POINTER(c_uint32), 'uint32_t*', 'maxDownSampleRatio'),
(c_enum, 'PS2000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps2000aGetMaxSegments', 'GetMaxSegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint16), 'uint16_t*', 'maxSegments')]
),
('ps2000aGetNoOfCaptures', 'GetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'nCaptures')]
),
('ps2000aGetNoOfProcessedCaptures', 'GetNoOfProcessedCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'nProcessedCaptures')]
),
('ps2000aGetStreamingLatestValues', 'GetStreamingLatestValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(ps2000aStreamingReady, 'ps2000aStreamingReady', 'lpPs'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps2000aGetTimebase', 'GetTimebase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_int32), 'int32_t*', 'timeIntervalNanoseconds'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps2000aGetTimebase2', 'GetTimebase2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_float), 'float*', 'timeIntervalNanoseconds'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps2000aGetTriggerTimeOffset', 'GetTriggerTimeOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(POINTER(c_enum), 'PS2000A_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps2000aGetTriggerTimeOffset64', 'GetTriggerTimeOffset64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'time'),
(POINTER(c_enum), 'PS2000A_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps2000aGetUnitInfo', 'GetUnitInfo', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int8), 'int8_t*', 'string'),
(c_int16, 'int16_t', 'stringLength'),
(POINTER(c_int16), 'int16_t*', 'requiredSize'),
(PICO_INFO, 'PICO_INFO', 'info')]
),
('ps2000aGetValues', 'GetValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS2000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps2000aGetValuesAsync', 'GetValuesAsync', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(c_uint32, 'uint32_t', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_int16, 'int16_t', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(ps2000aDataReady, 'void*', 'lpDataReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps2000aGetValuesBulk', 'GetValuesBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS2000A_RATIO_MODE', 'downSampleRatioMode'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps2000aGetValuesOverlapped', 'GetValuesOverlapped', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS2000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps2000aGetValuesOverlappedBulk', 'GetValuesOverlappedBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS2000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps2000aGetValuesTriggerTimeOffsetBulk', 'GetValuesTriggerTimeOffsetBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timesUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timesLower'),
(POINTER(c_enum), 'PS2000A_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex')]
),
('ps2000aGetValuesTriggerTimeOffsetBulk64', 'GetValuesTriggerTimeOffsetBulk64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'times'),
(POINTER(c_enum), 'PS2000A_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex')]
),
('ps2000aHoldOff', 'HoldOff', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint64, 'uint64_t', 'holdoff'),
(c_enum, 'PS2000A_HOLDOFF_TYPE', 'type')]
),
('ps2000aIsReady', 'IsReady', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'ready')]
),
('ps2000aIsTriggerOrPulseWidthQualifierEnabled', 'IsTriggerOrPulseWidthQualifierEnabled', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'triggerEnabled'),
(POINTER(c_int16), 'int16_t*', 'pulseWidthQualifierEnabled')]
),
('ps2000aMaximumValue', 'MaximumValue', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'value')]
),
('ps2000aMemorySegments', 'MemorySegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint16, 'uint16_t', 'nSegments'),
(POINTER(c_int32), 'int32_t*', 'nMaxSamples')]
),
('ps2000aMinimumValue', 'MinimumValue', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'value')]
),
('ps2000aNoOfStreamingValues', 'NoOfStreamingValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfValues')]
),
('ps2000aOpenUnit', 'OpenUnit', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int8), 'int8_t*', 'serial')]
),
('ps2000aOpenUnitAsync', 'OpenUnitAsync', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'status'),
(POINTER(c_int8), 'int8_t*', 'serial')]
),
('ps2000aOpenUnitProgress', 'OpenUnitProgress', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int16), 'int16_t*', 'progressPercent'),
(POINTER(c_int16), 'int16_t*', 'complete')]
),
('ps2000aPingUnit', 'PingUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps2000aRunBlock', 'RunBlock', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'noOfPreTriggerSamples'),
(c_int32, 'int32_t', 'noOfPostTriggerSamples'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'timeIndisposedMs'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(BlockReady, 'ps2000aBlockReady', 'lpReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps2000aRunStreaming', 'RunStreaming', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'sampleInterval'),
(c_enum, 'PS2000A_TIME_UNITS', 'sampleIntervalTimeUnits'),
(c_uint32, 'uint32_t', 'maxPreTriggerSamples'),
(c_uint32, 'uint32_t', 'maxPostPreTriggerSamples'),
(c_int16, 'int16_t', 'autoStop'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS2000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'overviewBufferSize')]
),
('ps2000aSetChannel', 'SetChannel', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS2000A_CHANNEL', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_enum, 'PS2000A_COUPLING', 'type'),
(c_enum, 'PS2000A_RANGE', 'range'),
(c_float, 'float', 'analogOffset')]
),
('ps2000aSetDataBuffer', 'SetDataBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'channelOrPort'),
(POINTER(c_int16), 'int16_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(c_enum, 'PS2000A_RATIO_MODE', 'mode')]
),
('ps2000aSetDataBuffers', 'SetDataBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'channelOrPort'),
(POINTER(c_int16), 'int16_t*', 'bufferMax'),
(POINTER(c_int16), 'int16_t*', 'bufferMin'),
(c_int32, 'int32_t', 'bufferLth'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(c_enum, 'PS2000A_RATIO_MODE', 'mode')]
),
('ps2000aSetDigitalAnalogTriggerOperand', 'SetDigitalAnalogTriggerOperand', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS2000A_TRIGGER_OPERAND', 'operand')]
),
('ps2000aSetDigitalPort', 'SetDigitalPort', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS2000A_DIGITAL_PORT', 'port'),
(c_int16, 'int16_t', 'enabled'),
(c_int16, 'int16_t', 'logicLevel')]
),
('ps2000aSetEts', 'SetEts', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS2000A_ETS_MODE', 'mode'),
(c_int16, 'int16_t', 'etsCycles'),
(c_int16, 'int16_t', 'etsInterleave'),
(POINTER(c_int32), 'int32_t*', 'sampleTimePicoseconds')]
),
('ps2000aSetEtsTimeBuffer', 'SetEtsTimeBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps2000aSetEtsTimeBuffers', 'SetEtsTimeBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps2000aSetNoOfCaptures', 'SetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint16, 'uint16_t', 'nCaptures')]
),
('ps2000aSetPulseWidthQualifier', 'SetPulseWidthQualifier', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS2000APwqConditions), 'PS2000A_PWQ_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'PS2000A_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'lower'),
(c_uint32, 'uint32_t', 'upper'),
(c_enum, 'PS2000A_PULSE_WIDTH_TYPE', 'type')]
),
('ps2000aSetSigGenArbitrary', 'SetSigGenArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(ndpointer(dtype=c_int16, ndim=1, flags='C_CONTIGUOUS'), 'int16_t*', 'arbitraryWaveform'),
(c_int32, 'int32_t', 'arbitraryWaveformSize'),
(c_enum, 'PS2000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS2000A_EXTRA_OPERATIONS', 'operation'),
(c_enum, 'PS2000A_INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS2000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS2000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps2000aSetSigGenBuiltIn', 'SetSigGenBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_int16, 'int16_t', 'waveType'),
(c_float, 'float', 'startFrequency'),
(c_float, 'float', 'stopFrequency'),
(c_float, 'float', 'increment'),
(c_float, 'float', 'dwellTime'),
(c_enum, 'PS2000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS2000A_EXTRA_OPERATIONS', 'operation'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS2000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS2000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps2000aSetSigGenBuiltInV2', 'SetSigGenBuiltInV2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_int16, 'int16_t', 'waveType'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'PS2000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS2000A_EXTRA_OPERATIONS', 'operation'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS2000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS2000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps2000aSetSigGenPropertiesArbitrary', 'SetSigGenPropertiesArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(c_enum, 'PS2000A_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS2000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS2000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps2000aSetSigGenPropertiesBuiltIn', 'SetSigGenPropertiesBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'PS2000A_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS2000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS2000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps2000aSetSimpleTrigger', 'SetSimpleTrigger', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'enable'),
(c_enum, 'PS2000A_CHANNEL', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_enum, 'PS2000A_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'delay'),
(c_int16, 'int16_t', 'autoTrigger_ms')]
),
('ps2000aSetTriggerChannelConditions', 'SetTriggerChannelConditions', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS2000ATriggerConditions), 'PS2000A_TRIGGER_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions')]
),
('ps2000aSetTriggerChannelDirections', 'SetTriggerChannelDirections', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS2000A_THRESHOLD_DIRECTION', 'channelA'),
(c_enum, 'PS2000A_THRESHOLD_DIRECTION', 'channelB'),
(c_enum, 'PS2000A_THRESHOLD_DIRECTION', 'channelC'),
(c_enum, 'PS2000A_THRESHOLD_DIRECTION', 'channelD'),
(c_enum, 'PS2000A_THRESHOLD_DIRECTION', 'ext'),
(c_enum, 'PS2000A_THRESHOLD_DIRECTION', 'aux')]
),
('ps2000aSetTriggerChannelProperties', 'SetTriggerChannelProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS2000ATriggerChannelProperties), 'PS2000A_TRIGGER_CHANNEL_PROPERTIES*', 'channelProperties'),
(c_int16, 'int16_t', 'nChannelProperties'),
(c_int16, 'int16_t', 'auxOutputEnable'),
(c_int32, 'int32_t', 'autoTriggerMilliseconds')]
),
('ps2000aSetTriggerDelay', 'SetTriggerDelay', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'delay')]
),
('ps2000aSetTriggerDigitalPortProperties', 'SetTriggerDigitalPortProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS2000ADigitalChannelDirections), 'PS2000A_DIGITAL_CHANNEL_DIRECTIONS*', 'directions'),
(c_int16, 'int16_t', 'nDirections')]
),
('ps2000aSigGenArbitraryMinMaxValues', 'SigGenArbitraryMinMaxValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'minArbitraryWaveformValue'),
(POINTER(c_int16), 'int16_t*', 'maxArbitraryWaveformValue'),
(POINTER(c_uint32), 'uint32_t*', 'minArbitraryWaveformSize'),
(POINTER(c_uint32), 'uint32_t*', 'maxArbitraryWaveformSize')]
),
('ps2000aSigGenFrequencyToPhase', 'SigGenFrequencyToPhase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'frequency'),
(c_enum, 'PS2000A_INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'bufferLength'),
(POINTER(c_uint32), 'uint32_t*', 'phase')]
),
('ps2000aSigGenSoftwareControl', 'SigGenSoftwareControl', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'state')]
),
('ps2000aStop', 'Stop', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
]
# ************************ SDK functions for ps3000 ************************
ps3000_funcptrs = [
('ps3000PingUnit', 'PingUnit', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle')]
),
('ps3000SetAdvTriggerChannelConditions', 'SetAdvTriggerChannelConditions', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000TriggerConditions), 'TRIGGER_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions')]
),
('ps3000SetAdvTriggerChannelDirections', 'SetAdvTriggerChannelDirections', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelA'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelB'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelC'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelD'),
(c_enum, 'THRESHOLD_DIRECTION', 'ext')]
),
('ps3000SetAdvTriggerChannelProperties', 'SetAdvTriggerChannelProperties', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000TriggerChannelProperties), 'TRIGGER_CHANNEL_PROPERTIES*', 'channelProperties'),
(c_int16, 'int16_t', 'nChannelProperties'),
(c_int32, 'int32_t', 'autoTriggerMilliseconds')]
),
('ps3000SetAdvTriggerDelay', 'SetAdvTriggerDelay', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'delay'),
(c_float, 'float', 'preTriggerDelay')]
),
('ps3000SetPulseWidthQualifier', 'SetPulseWidthQualifier', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000PwqConditions), 'PWQ_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'lower'),
(c_uint32, 'uint32_t', 'upper'),
(c_enum, 'PULSE_WIDTH_TYPE', 'type')]
),
('ps3000_close_unit', 'CloseUnit', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle')]
),
('ps3000_flash_led', 'FlashLed', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle')]
),
('ps3000_get_streaming_last_values', 'GetStreamingLastValues', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(GetOverviewBuffersMaxMin, 'GetOverviewBuffersMaxMin', 'lpGetOverviewBuffersMaxMin')]
),
('ps3000_get_streaming_values', 'GetStreamingValues', c_uint32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_double), 'double*', 'start_time'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_a_max'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_a_min'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_b_max'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_b_min'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_c_max'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_c_min'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_d_max'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_d_min'),
(POINTER(c_int16), 'int16_t*', 'overflow'),
(POINTER(c_uint32), 'uint32_t*', 'triggerAt'),
(POINTER(c_int16), 'int16_t*', 'triggered'),
(c_uint32, 'uint32_t', 'no_of_values'),
(c_uint32, 'uint32_t', 'noOfSamplesPerAggregate')]
),
('ps3000_get_streaming_values_no_aggregation', 'GetStreamingValuesNoAggregation', c_uint32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_double), 'double*', 'start_time'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_a'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_b'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_c'),
(POINTER(c_int16), 'int16_t*', 'pbuffer_d'),
(POINTER(c_int16), 'int16_t*', 'overflow'),
(POINTER(c_uint32), 'uint32_t*', 'triggerAt'),
(POINTER(c_int16), 'int16_t*', 'trigger'),
(c_uint32, 'uint32_t', 'no_of_values')]
),
('ps3000_get_timebase', 'GetTimebase', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'timebase'),
(c_int32, 'int32_t', 'no_of_samples'),
(POINTER(c_int32), 'int32_t*', 'time_interval'),
(POINTER(c_int16), 'int16_t*', 'time_units'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'max_samples')]
),
('ps3000_get_times_and_values', 'GetTimesAndValues', c_int32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int32), 'int32_t*', 'times'),
(POINTER(c_int16), 'int16_t*', 'buffer_a'),
(POINTER(c_int16), 'int16_t*', 'buffer_b'),
(POINTER(c_int16), 'int16_t*', 'buffer_c'),
(POINTER(c_int16), 'int16_t*', 'buffer_d'),
(POINTER(c_int16), 'int16_t*', 'overflow'),
(c_int16, 'int16_t', 'time_units'),
(c_int32, 'int32_t', 'no_of_values')]
),
('ps3000_get_unit_info', 'GetUnitInfo', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int8), 'int8_t*', 'string'),
(c_int16, 'int16_t', 'string_length'),
(c_int16, 'int16_t', 'line')]
),
('ps3000_get_values', 'GetValues', c_int32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'buffer_a'),
(POINTER(c_int16), 'int16_t*', 'buffer_b'),
(POINTER(c_int16), 'int16_t*', 'buffer_c'),
(POINTER(c_int16), 'int16_t*', 'buffer_d'),
(POINTER(c_int16), 'int16_t*', 'overflow'),
(c_int32, 'int32_t', 'no_of_values')]
),
('ps3000_open_unit', 'OpenUnit', c_int16, None,
[]
),
('ps3000_open_unit_async', 'OpenUnitAsync', c_int16, None,
[]
),
('ps3000_open_unit_progress', 'OpenUnitProgress', c_int16, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int16), 'int16_t*', 'progress_percent')]
),
('ps3000_overview_buffer_status', 'OverviewBufferStatus', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'previous_buffer_overrun')]
),
('ps3000_ready', 'Ready', c_int16, 'errcheck_negative_one',
[(c_int16, 'int16_t', 'handle')]
),
('ps3000_release_stream_buffer', 'ReleaseStreamBuffer', c_void_p, None,
[(c_int16, 'int16_t', 'handle')]
),
('ps3000_run_block', 'RunBlock', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'no_of_values'),
(c_int16, 'int16_t', 'timebase'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'time_indisposed_ms')]
),
('ps3000_run_streaming', 'RunStreaming', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'sample_interval_ms'),
(c_int32, 'int32_t', 'max_samples'),
(c_int16, 'int16_t', 'windowed')]
),
('ps3000_run_streaming_ns', 'RunStreamingNs', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'sample_interval'),
(c_enum, 'PS3000_TIME_UNITS', 'time_units'),
(c_uint32, 'uint32_t', 'max_samples'),
(c_int16, 'int16_t', 'auto_stop'),
(c_uint32, 'uint32_t', 'noOfSamplesPerAggregate'),
(c_uint32, 'uint32_t', 'overview_buffer_size')]
),
('ps3000_save_streaming_data', 'SaveStreamingData', c_int16, None,
[(c_int16, 'int16_t', 'handle'),
(PS3000_CALLBACK_FUNC, 'PS3000_CALLBACK_FUNC', 'lpCallbackFunc'),
(POINTER(c_int16), 'int16_t*', 'dataBuffers'),
(c_int16, 'int16_t', 'dataBufferSize')]
),
('ps3000_set_channel', 'SetChannel', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_int16, 'int16_t', 'dc'),
(c_int16, 'int16_t', 'range')]
),
('ps3000_set_ets', 'SetEts', c_int32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'mode'),
(c_int16, 'int16_t', 'ets_cycles'),
(c_int16, 'int16_t', 'ets_interleave')]
),
('ps3000_set_siggen', 'SetSiggen', c_int32, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'wave_type'),
(c_int32, 'int32_t', 'start_frequency'),
(c_int32, 'int32_t', 'stop_frequency'),
(c_float, 'float', 'increment'),
(c_int16, 'int16_t', 'dwell_time'),
(c_int16, 'int16_t', 'repeat'),
(c_int16, 'int16_t', 'dual_slope')]
),
('ps3000_set_trigger', 'SetTrigger', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_int16, 'int16_t', 'direction'),
(c_int16, 'int16_t', 'delay'),
(c_int16, 'int16_t', 'auto_trigger_ms')]
),
('ps3000_set_trigger2', 'SetTrigger2', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_int16, 'int16_t', 'direction'),
(c_float, 'float', 'delay'),
(c_int16, 'int16_t', 'auto_trigger_ms')]
),
('ps3000_stop', 'Stop', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle')]
),
('ps3000_streaming_ns_get_interval_stateless', 'StreamingNsGetIntervalStateless', c_int16, 'errcheck_zero',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'nChannels'),
(POINTER(c_uint32), 'uint32_t*', 'sample_interval')]
),
]
# ************************ SDK functions for ps3000aApi ************************
ps3000aApi_funcptrs = [
('ps3000aChangePowerSource', 'ChangePowerSource', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(PICO_STATUS, 'PICO_STATUS', 'powerState')]
),
('ps3000aCloseUnit', 'CloseUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps3000aCurrentPowerSource', 'CurrentPowerSource', PICO_STATUS, None,
[(c_int16, 'int16_t', 'handle')]
),
('ps3000aEnumerateUnits', 'EnumerateUnits', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'count'),
(POINTER(c_int8), 'int8_t*', 'serials'),
(POINTER(c_int16), 'int16_t*', 'serialLth')]
),
('ps3000aFlashLed', 'FlashLed', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'start')]
),
('ps3000aGetAnalogueOffset', 'GetAnalogueOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS3000A_RANGE', 'range'),
(c_enum, 'PS3000A_COUPLING', 'coupling'),
(POINTER(c_float), 'float*', 'maximumVoltage'),
(POINTER(c_float), 'float*', 'minimumVoltage')]
),
('ps3000aGetChannelInformation', 'GetChannelInformation', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS3000A_CHANNEL_INFO', 'info'),
(c_int32, 'int32_t', 'probe'),
(POINTER(c_int32), 'int32_t*', 'ranges'),
(POINTER(c_int32), 'int32_t*', 'length'),
(c_int32, 'int32_t', 'channels')]
),
('ps3000aGetMaxDownSampleRatio', 'GetMaxDownSampleRatio', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'noOfUnaggreatedSamples'),
(POINTER(c_uint32), 'uint32_t*', 'maxDownSampleRatio'),
(c_enum, 'PS3000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps3000aGetMaxEtsValues', 'GetMaxEtsValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'etsCycles'),
(POINTER(c_int16), 'int16_t*', 'etsInterleave')]
),
('ps3000aGetMaxSegments', 'GetMaxSegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'maxSegments')]
),
('ps3000aGetNoOfCaptures', 'GetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'nCaptures')]
),
('ps3000aGetNoOfProcessedCaptures', 'GetNoOfProcessedCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'nProcessedCaptures')]
),
('ps3000aGetStreamingLatestValues', 'GetStreamingLatestValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(ps3000aStreamingReady, 'ps3000aStreamingReady', 'lpPs'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps3000aGetTimebase', 'GetTimebase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_int32), 'int32_t*', 'timeIntervalNanoseconds'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps3000aGetTimebase2', 'GetTimebase2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_float), 'float*', 'timeIntervalNanoseconds'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps3000aGetTriggerInfoBulk', 'GetTriggerInfoBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000ATriggerInfo), 'PS3000A_TRIGGER_INFO*', 'triggerInfo'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex')]
),
('ps3000aGetTriggerTimeOffset', 'GetTriggerTimeOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(POINTER(c_enum), 'PS3000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps3000aGetTriggerTimeOffset64', 'GetTriggerTimeOffset64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'time'),
(POINTER(c_enum), 'PS3000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps3000aGetUnitInfo', 'GetUnitInfo', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int8), 'int8_t*', 'string'),
(c_int16, 'int16_t', 'stringLength'),
(POINTER(c_int16), 'int16_t*', 'requiredSize'),
(PICO_INFO, 'PICO_INFO', 'info')]
),
('ps3000aGetValues', 'GetValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS3000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps3000aGetValuesAsync', 'GetValuesAsync', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(c_uint32, 'uint32_t', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_int16, 'int16_t', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(ps3000aDataReady, 'void*', 'lpDataReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps3000aGetValuesBulk', 'GetValuesBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS3000A_RATIO_MODE', 'downSampleRatioMode'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps3000aGetValuesOverlapped', 'GetValuesOverlapped', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS3000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps3000aGetValuesOverlappedBulk', 'GetValuesOverlappedBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS3000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps3000aGetValuesTriggerTimeOffsetBulk', 'GetValuesTriggerTimeOffsetBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timesUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timesLower'),
(POINTER(c_enum), 'PS3000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex')]
),
('ps3000aGetValuesTriggerTimeOffsetBulk64', 'GetValuesTriggerTimeOffsetBulk64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'times'),
(POINTER(c_enum), 'PS3000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex')]
),
('ps3000aHoldOff', 'HoldOff', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint64, 'uint64_t', 'holdoff'),
(c_enum, 'PS3000A_HOLDOFF_TYPE', 'type')]
),
('ps3000aIsReady', 'IsReady', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'ready')]
),
('ps3000aIsTriggerOrPulseWidthQualifierEnabled', 'IsTriggerOrPulseWidthQualifierEnabled', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'triggerEnabled'),
(POINTER(c_int16), 'int16_t*', 'pulseWidthQualifierEnabled')]
),
('ps3000aMaximumValue', 'MaximumValue', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'value')]
),
('ps3000aMemorySegments', 'MemorySegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'nSegments'),
(POINTER(c_int32), 'int32_t*', 'nMaxSamples')]
),
('ps3000aMinimumValue', 'MinimumValue', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'value')]
),
('ps3000aNoOfStreamingValues', 'NoOfStreamingValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfValues')]
),
('ps3000aOpenUnit', 'OpenUnit', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int8), 'int8_t*', 'serial')]
),
('ps3000aOpenUnitAsync', 'OpenUnitAsync', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'status'),
(POINTER(c_int8), 'int8_t*', 'serial')]
),
('ps3000aOpenUnitProgress', 'OpenUnitProgress', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int16), 'int16_t*', 'progressPercent'),
(POINTER(c_int16), 'int16_t*', 'complete')]
),
('ps3000aPingUnit', 'PingUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps3000aRunBlock', 'RunBlock', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'noOfPreTriggerSamples'),
(c_int32, 'int32_t', 'noOfPostTriggerSamples'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'timeIndisposedMs'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(BlockReady, 'ps3000aBlockReady', 'lpReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps3000aRunStreaming', 'RunStreaming', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'sampleInterval'),
(c_enum, 'PS3000A_TIME_UNITS', 'sampleIntervalTimeUnits'),
(c_uint32, 'uint32_t', 'maxPreTriggerSamples'),
(c_uint32, 'uint32_t', 'maxPostPreTriggerSamples'),
(c_int16, 'int16_t', 'autoStop'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS3000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'overviewBufferSize')]
),
('ps3000aSetBandwidthFilter', 'SetBandwidthFilter', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS3000A_CHANNEL', 'channel'),
(c_enum, 'PS3000A_BANDWIDTH_LIMITER', 'bandwidth')]
),
('ps3000aSetChannel', 'SetChannel', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS3000A_CHANNEL', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_enum, 'PS3000A_COUPLING', 'type'),
(c_enum, 'PS3000A_RANGE', 'range'),
(c_float, 'float', 'analogOffset')]
),
('ps3000aSetDataBuffer', 'SetDataBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS3000A_CHANNEL', 'channelOrPort'),
(POINTER(c_int16), 'int16_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(c_enum, 'PS3000A_RATIO_MODE', 'mode')]
),
('ps3000aSetDataBuffers', 'SetDataBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS3000A_CHANNEL', 'channelOrPort'),
(POINTER(c_int16), 'int16_t*', 'bufferMax'),
(POINTER(c_int16), 'int16_t*', 'bufferMin'),
(c_int32, 'int32_t', 'bufferLth'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(c_enum, 'PS3000A_RATIO_MODE', 'mode')]
),
('ps3000aSetDigitalPort', 'SetDigitalPort', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS3000A_DIGITAL_PORT', 'port'),
(c_int16, 'int16_t', 'enabled'),
(c_int16, 'int16_t', 'logicLevel')]
),
('ps3000aSetEts', 'SetEts', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS3000A_ETS_MODE', 'mode'),
(c_int16, 'int16_t', 'etsCycles'),
(c_int16, 'int16_t', 'etsInterleave'),
(POINTER(c_int32), 'int32_t*', 'sampleTimePicoseconds')]
),
('ps3000aSetEtsTimeBuffer', 'SetEtsTimeBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps3000aSetEtsTimeBuffers', 'SetEtsTimeBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps3000aSetNoOfCaptures', 'SetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'nCaptures')]
),
('ps3000aSetPulseWidthDigitalPortProperties', 'SetPulseWidthDigitalPortProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000ADigitalChannelDirections), 'PS3000A_DIGITAL_CHANNEL_DIRECTIONS*', 'directions'),
(c_int16, 'int16_t', 'nDirections')]
),
('ps3000aSetPulseWidthQualifier', 'SetPulseWidthQualifier', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000APwqConditions), 'PS3000A_PWQ_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'PS3000A_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'lower'),
(c_uint32, 'uint32_t', 'upper'),
(c_enum, 'PS3000A_PULSE_WIDTH_TYPE', 'type')]
),
('ps3000aSetPulseWidthQualifierV2', 'SetPulseWidthQualifierV2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000APwqConditionsV2), 'PS3000A_PWQ_CONDITIONS_V2*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'PS3000A_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'lower'),
(c_uint32, 'uint32_t', 'upper'),
(c_enum, 'PS3000A_PULSE_WIDTH_TYPE', 'type')]
),
('ps3000aSetSigGenArbitrary', 'SetSigGenArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(ndpointer(dtype=c_int16, ndim=1, flags='C_CONTIGUOUS'), 'int16_t*', 'arbitraryWaveform'),
(c_int32, 'int32_t', 'arbitraryWaveformSize'),
(c_enum, 'PS3000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS3000A_EXTRA_OPERATIONS', 'operation'),
(c_enum, 'PS3000A_INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS3000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS3000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps3000aSetSigGenBuiltIn', 'SetSigGenBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_int16, 'int16_t', 'waveType'),
(c_float, 'float', 'startFrequency'),
(c_float, 'float', 'stopFrequency'),
(c_float, 'float', 'increment'),
(c_float, 'float', 'dwellTime'),
(c_enum, 'PS3000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS3000A_EXTRA_OPERATIONS', 'operation'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS3000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS3000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps3000aSetSigGenBuiltInV2', 'SetSigGenBuiltInV2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_int16, 'int16_t', 'waveType'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'PS3000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS3000A_EXTRA_OPERATIONS', 'operation'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS3000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS3000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps3000aSetSigGenPropertiesArbitrary', 'SetSigGenPropertiesArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(c_enum, 'PS3000A_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS3000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS3000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps3000aSetSigGenPropertiesBuiltIn', 'SetSigGenPropertiesBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'PS3000A_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS3000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS3000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps3000aSetSimpleTrigger', 'SetSimpleTrigger', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'enable'),
(c_enum, 'PS3000A_CHANNEL', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_enum, 'PS3000A_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'delay'),
(c_int16, 'int16_t', 'autoTrigger_ms')]
),
('ps3000aSetTriggerChannelConditions', 'SetTriggerChannelConditions', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000ATriggerConditions), 'PS3000A_TRIGGER_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions')]
),
('ps3000aSetTriggerChannelConditionsV2', 'SetTriggerChannelConditionsV2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000ATriggerConditionsV2), 'PS3000A_TRIGGER_CONDITIONS_V2*', 'conditions'),
(c_int16, 'int16_t', 'nConditions')]
),
('ps3000aSetTriggerChannelDirections', 'SetTriggerChannelDirections', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS3000A_THRESHOLD_DIRECTION', 'channelA'),
(c_enum, 'PS3000A_THRESHOLD_DIRECTION', 'channelB'),
(c_enum, 'PS3000A_THRESHOLD_DIRECTION', 'channelC'),
(c_enum, 'PS3000A_THRESHOLD_DIRECTION', 'channelD'),
(c_enum, 'PS3000A_THRESHOLD_DIRECTION', 'ext'),
(c_enum, 'PS3000A_THRESHOLD_DIRECTION', 'aux')]
),
('ps3000aSetTriggerChannelProperties', 'SetTriggerChannelProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000ATriggerChannelProperties), 'PS3000A_TRIGGER_CHANNEL_PROPERTIES*', 'channelProperties'),
(c_int16, 'int16_t', 'nChannelProperties'),
(c_int16, 'int16_t', 'auxOutputEnable'),
(c_int32, 'int32_t', 'autoTriggerMilliseconds')]
),
('ps3000aSetTriggerDelay', 'SetTriggerDelay', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'delay')]
),
('ps3000aSetTriggerDigitalPortProperties', 'SetTriggerDigitalPortProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS3000ADigitalChannelDirections), 'PS3000A_DIGITAL_CHANNEL_DIRECTIONS*', 'directions'),
(c_int16, 'int16_t', 'nDirections')]
),
('ps3000aSigGenArbitraryMinMaxValues', 'SigGenArbitraryMinMaxValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'minArbitraryWaveformValue'),
(POINTER(c_int16), 'int16_t*', 'maxArbitraryWaveformValue'),
(POINTER(c_uint32), 'uint32_t*', 'minArbitraryWaveformSize'),
(POINTER(c_uint32), 'uint32_t*', 'maxArbitraryWaveformSize')]
),
('ps3000aSigGenFrequencyToPhase', 'SigGenFrequencyToPhase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'frequency'),
(c_enum, 'PS3000A_INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'bufferLength'),
(POINTER(c_uint32), 'uint32_t*', 'phase')]
),
('ps3000aSigGenSoftwareControl', 'SigGenSoftwareControl', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'state')]
),
('ps3000aStop', 'Stop', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
]
# ************************ SDK functions for ps4000Api ************************
ps4000Api_funcptrs = [
('ps4000CloseUnit', 'CloseUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps4000EnumerateUnits', 'EnumerateUnits', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'count'),
(POINTER(c_int8), 'int8_t*', 'serials'),
(POINTER(c_int16), 'int16_t*', 'serialLth')]
),
('ps4000FlashLed', 'FlashLed', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'start')]
),
('ps4000GetChannelInformation', 'GetChannelInformation', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_CHANNEL_INFO', 'info'),
(c_int32, 'int32_t', 'probe'),
(POINTER(c_int32), 'int32_t*', 'ranges'),
(POINTER(c_int32), 'int32_t*', 'length'),
(c_int32, 'int32_t', 'channels')]
),
('ps4000GetMaxDownSampleRatio', 'GetMaxDownSampleRatio', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'noOfUnaggreatedSamples'),
(POINTER(c_uint32), 'uint32_t*', 'maxDownSampleRatio'),
(c_int16, 'int16_t', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps4000GetNoOfCaptures', 'GetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint16), 'uint16_t*', 'nCaptures')]
),
('ps4000GetProbe', 'GetProbe', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_enum), 'PS4000_PROBE*', 'probe')]
),
('ps4000GetStreamingLatestValues', 'GetStreamingLatestValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(ps4000StreamingReady, 'ps4000StreamingReady', 'lpPs'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps4000GetTimebase', 'GetTimebase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_int32), 'int32_t*', 'timeIntervalNanoseconds'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps4000GetTimebase2', 'GetTimebase2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_float), 'float*', 'timeIntervalNanoseconds'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps4000GetTriggerChannelTimeOffset', 'GetTriggerChannelTimeOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(POINTER(c_enum), 'PS4000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(c_enum, 'PS4000_CHANNEL', 'channel')]
),
('ps4000GetTriggerChannelTimeOffset64', 'GetTriggerChannelTimeOffset64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'time'),
(POINTER(c_enum), 'PS4000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(c_enum, 'PS4000_CHANNEL', 'channel')]
),
('ps4000GetTriggerTimeOffset', 'GetTriggerTimeOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(POINTER(c_enum), 'PS4000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps4000GetTriggerTimeOffset64', 'GetTriggerTimeOffset64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'time'),
(POINTER(c_enum), 'PS4000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps4000GetUnitInfo', 'GetUnitInfo', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int8), 'int8_t*', 'string'),
(c_int16, 'int16_t', 'stringLength'),
(POINTER(c_int16), 'int16_t*', 'requiredSize'),
(PICO_INFO, 'PICO_INFO', 'info')]
),
('ps4000GetValues', 'GetValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_int16, 'int16_t', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps4000GetValuesAsync', 'GetValuesAsync', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(c_uint32, 'uint32_t', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_int16, 'int16_t', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(ps4000DataReady, 'void*', 'lpDataReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps4000GetValuesBulk', 'GetValuesBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps4000GetValuesTriggerChannelTimeOffsetBulk', 'GetValuesTriggerChannelTimeOffsetBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timesUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timesLower'),
(POINTER(c_enum), 'PS4000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex'),
(c_enum, 'PS4000_CHANNEL', 'channel')]
),
('ps4000GetValuesTriggerChannelTimeOffsetBulk64', 'GetValuesTriggerChannelTimeOffsetBulk64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'times'),
(POINTER(c_enum), 'PS4000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex'),
(c_enum, 'PS4000_CHANNEL', 'channel')]
),
('ps4000GetValuesTriggerTimeOffsetBulk', 'GetValuesTriggerTimeOffsetBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timesUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timesLower'),
(POINTER(c_enum), 'PS4000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex')]
),
('ps4000GetValuesTriggerTimeOffsetBulk64', 'GetValuesTriggerTimeOffsetBulk64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'times'),
(POINTER(c_enum), 'PS4000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex')]
),
('ps4000HoldOff', 'HoldOff', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint64, 'uint64_t', 'holdoff'),
(c_enum, 'PS4000_HOLDOFF_TYPE', 'type')]
),
('ps4000IsLedFlashing', 'IsLedFlashing', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'status')]
),
('ps4000IsReady', 'IsReady', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'ready')]
),
('ps4000IsTriggerOrPulseWidthQualifierEnabled', 'IsTriggerOrPulseWidthQualifierEnabled', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'triggerEnabled'),
(POINTER(c_int16), 'int16_t*', 'pulseWidthQualifierEnabled')]
),
('ps4000MemorySegments', 'MemorySegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint16, 'uint16_t', 'nSegments'),
(POINTER(c_int32), 'int32_t*', 'nMaxSamples')]
),
('ps4000NoOfStreamingValues', 'NoOfStreamingValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfValues')]
),
('ps4000OpenUnit', 'OpenUnit', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle')]
),
('ps4000OpenUnitAsync', 'OpenUnitAsync', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'status')]
),
('ps4000OpenUnitAsyncEx', 'OpenUnitAsyncEx', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'status'),
(POINTER(c_int8), 'int8_t*', 'serial')]
),
('ps4000OpenUnitEx', 'OpenUnitEx', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int8), 'int8_t*', 'serial')]
),
('ps4000OpenUnitProgress', 'OpenUnitProgress', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int16), 'int16_t*', 'progressPercent'),
(POINTER(c_int16), 'int16_t*', 'complete')]
),
('ps4000PingUnit', 'PingUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps4000RunBlock', 'RunBlock', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'noOfPreTriggerSamples'),
(c_int32, 'int32_t', 'noOfPostTriggerSamples'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'timeIndisposedMs'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(BlockReady, 'ps4000BlockReady', 'lpReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps4000RunStreaming', 'RunStreaming', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'sampleInterval'),
(c_enum, 'PS4000_TIME_UNITS', 'sampleIntervalTimeUnits'),
(c_uint32, 'uint32_t', 'maxPreTriggerSamples'),
(c_uint32, 'uint32_t', 'maxPostPreTriggerSamples'),
(c_int16, 'int16_t', 'autoStop'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_uint32, 'uint32_t', 'overviewBufferSize')]
),
('ps4000RunStreamingEx', 'RunStreamingEx', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'sampleInterval'),
(c_enum, 'PS4000_TIME_UNITS', 'sampleIntervalTimeUnits'),
(c_uint32, 'uint32_t', 'maxPreTriggerSamples'),
(c_uint32, 'uint32_t', 'maxPostPreTriggerSamples'),
(c_int16, 'int16_t', 'autoStop'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_int16, 'int16_t', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'overviewBufferSize')]
),
('ps4000SetBwFilter', 'SetBwFilter', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_CHANNEL', 'channel'),
(c_int16, 'int16_t', 'enable')]
),
('ps4000SetChannel', 'SetChannel', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_CHANNEL', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_int16, 'int16_t', 'dc'),
(c_enum, 'PS4000_RANGE', 'range')]
),
('ps4000SetDataBuffer', 'SetDataBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps4000SetDataBufferBulk', 'SetDataBufferBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth'),
(c_uint16, 'uint16_t', 'waveform')]
),
('ps4000SetDataBufferWithMode', 'SetDataBufferWithMode', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth'),
(c_enum, 'RATIO_MODE', 'mode')]
),
('ps4000SetDataBuffers', 'SetDataBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'bufferMax'),
(POINTER(c_int16), 'int16_t*', 'bufferMin'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps4000SetDataBuffersWithMode', 'SetDataBuffersWithMode', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'bufferMax'),
(POINTER(c_int16), 'int16_t*', 'bufferMin'),
(c_int32, 'int32_t', 'bufferLth'),
(c_enum, 'RATIO_MODE', 'mode')]
),
('ps4000SetEts', 'SetEts', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_ETS_MODE', 'mode'),
(c_int16, 'int16_t', 'etsCycles'),
(c_int16, 'int16_t', 'etsInterleave'),
(POINTER(c_int32), 'int32_t*', 'sampleTimePicoseconds')]
),
('ps4000SetEtsTimeBuffer', 'SetEtsTimeBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps4000SetEtsTimeBuffers', 'SetEtsTimeBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps4000SetExtTriggerRange', 'SetExtTriggerRange', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_RANGE', 'extRange')]
),
('ps4000SetFrequencyCounter', 'SetFrequencyCounter', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_CHANNEL', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_enum, 'PS4000_FREQUENCY_COUNTER_RANGE', 'range'),
(c_int16, 'int16_t', 'thresholdMajor'),
(c_int16, 'int16_t', 'thresholdMinor')]
),
('ps4000SetNoOfCaptures', 'SetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint16, 'uint16_t', 'nCaptures')]
),
('ps4000SetProbe', 'SetProbe', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000_PROBE', 'probe'),
(c_enum, 'PS4000_RANGE', 'range')]
),
('ps4000SetPulseWidthQualifier', 'SetPulseWidthQualifier', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS4000PwqConditions), 'PWQ_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'lower'),
(c_uint32, 'uint32_t', 'upper'),
(c_enum, 'PULSE_WIDTH_TYPE', 'type')]
),
('ps4000SetSigGenArbitrary', 'SetSigGenArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(ndpointer(dtype=c_int16, ndim=1, flags='C_CONTIGUOUS'), 'int16_t*', 'arbitraryWaveform'),
(c_int32, 'int32_t', 'arbitraryWaveformSize'),
(c_enum, 'SWEEP_TYPE', 'sweepType'),
(c_int16, 'int16_t', 'operationType'),
(c_enum, 'INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps4000SetSigGenBuiltIn', 'SetSigGenBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_int16, 'int16_t', 'waveType'),
(c_float, 'float', 'startFrequency'),
(c_float, 'float', 'stopFrequency'),
(c_float, 'float', 'increment'),
(c_float, 'float', 'dwellTime'),
(c_enum, 'SWEEP_TYPE', 'sweepType'),
(c_int16, 'int16_t', 'operationType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps4000SetSimpleTrigger', 'SetSimpleTrigger', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'enable'),
(c_enum, 'PS4000_CHANNEL', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_enum, 'THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'delay'),
(c_int16, 'int16_t', 'autoTrigger_ms')]
),
('ps4000SetTriggerChannelConditions', 'SetTriggerChannelConditions', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS4000TriggerConditions), 'TRIGGER_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions')]
),
('ps4000SetTriggerChannelDirections', 'SetTriggerChannelDirections', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelA'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelB'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelC'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelD'),
(c_enum, 'THRESHOLD_DIRECTION', 'ext'),
(c_enum, 'THRESHOLD_DIRECTION', 'aux')]
),
('ps4000SetTriggerChannelProperties', 'SetTriggerChannelProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS4000TriggerChannelProperties), 'TRIGGER_CHANNEL_PROPERTIES*', 'channelProperties'),
(c_int16, 'int16_t', 'nChannelProperties'),
(c_int16, 'int16_t', 'auxOutputEnable'),
(c_int32, 'int32_t', 'autoTriggerMilliseconds')]
),
('ps4000SetTriggerDelay', 'SetTriggerDelay', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'delay')]
),
('ps4000SigGenArbitraryMinMaxValues', 'SigGenArbitraryMinMaxValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'minArbitraryWaveformValue'),
(POINTER(c_int16), 'int16_t*', 'maxArbitraryWaveformValue'),
(POINTER(c_uint32), 'uint32_t*', 'minArbitraryWaveformSize'),
(POINTER(c_uint32), 'uint32_t*', 'maxArbitraryWaveformSize')]
),
('ps4000SigGenFrequencyToPhase', 'SigGenFrequencyToPhase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'frequency'),
(c_enum, 'INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'bufferLength'),
(POINTER(c_uint32), 'uint32_t*', 'phase')]
),
('ps4000SigGenOff', 'SigGenOff', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps4000SigGenSoftwareControl', 'SigGenSoftwareControl', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'state')]
),
('ps4000Stop', 'Stop', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps4000TriggerWithinPreTriggerSamples', 'TriggerWithinPreTriggerSamples', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'state')]
),
]
# ************************ SDK functions for ps4000aApi ************************
ps4000aApi_funcptrs = [
('ps4000aApplyResistanceScaling', 'ApplyResistanceScaling', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000A_CHANNEL', 'channel'),
(c_enum, 'PS4000A_RANGE', 'range'),
(POINTER(c_int16), 'int16_t*', 'bufferMax'),
(POINTER(c_int16), 'int16_t*', 'bufferMin'),
(c_uint32, 'uint32_t', 'buffertLth'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps4000aChangePowerSource', 'ChangePowerSource', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(PICO_STATUS, 'PICO_STATUS', 'powerState')]
),
('ps4000aCloseUnit', 'CloseUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps4000aConnectDetect', 'ConnectDetect', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS4000AConnectDetect), 'PS4000A_CONNECT_DETECT*', 'sensor'),
(c_int16, 'int16_t', 'nSensors')]
),
('ps4000aCurrentPowerSource', 'CurrentPowerSource', PICO_STATUS, None,
[(c_int16, 'int16_t', 'handle')]
),
('ps4000aDeviceMetaData', 'DeviceMetaData', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int8), 'int8_t*', 'settings'),
(POINTER(c_int32), 'int32_t*', 'nSettingsLength'),
(c_enum, 'PS4000A_META_TYPE', 'type'),
(c_enum, 'PS4000A_META_OPERATION', 'operation'),
(c_enum, 'PS4000A_META_FORMAT', 'format')]
),
('ps4000aEnumerateUnits', 'EnumerateUnits', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'count'),
(POINTER(c_int8), 'int8_t*', 'serials'),
(POINTER(c_int16), 'int16_t*', 'serialLth')]
),
('ps4000aFlashLed', 'FlashLed', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'start')]
),
('ps4000aGetAnalogueOffset', 'GetAnalogueOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000A_RANGE', 'range'),
(c_enum, 'PS4000A_COUPLING', 'coupling'),
(POINTER(c_float), 'float*', 'maximumVoltage'),
(POINTER(c_float), 'float*', 'minimumVoltage')]
),
('ps4000aGetChannelInformation', 'GetChannelInformation', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000A_CHANNEL_INFO', 'info'),
(c_int32, 'int32_t', 'probe'),
(POINTER(c_int32), 'int32_t*', 'ranges'),
(POINTER(c_int32), 'int32_t*', 'length'),
(c_int32, 'int32_t', 'channels')]
),
('ps4000aGetCommonModeOverflow', 'GetCommonModeOverflow', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint16), 'uint16_t*', 'overflow')]
),
('ps4000aGetMaxDownSampleRatio', 'GetMaxDownSampleRatio', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'noOfUnaggreatedSamples'),
(POINTER(c_uint32), 'uint32_t*', 'maxDownSampleRatio'),
(c_enum, 'PS4000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps4000aGetMaxSegments', 'GetMaxSegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'maxSegments')]
),
('ps4000aGetNoOfCaptures', 'GetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'nCaptures')]
),
('ps4000aGetNoOfProcessedCaptures', 'GetNoOfProcessedCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'nProcessedCaptures')]
),
('ps4000aGetStreamingLatestValues', 'GetStreamingLatestValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(ps4000aStreamingReady, 'ps4000aStreamingReady', 'lpPs'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps4000aGetString', 'GetString', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PICO_STRING_VALUE', 'stringValue'),
(POINTER(c_int8), 'int8_t*', 'string'),
(POINTER(c_int32), 'int32_t*', 'stringLength')]
),
('ps4000aGetTimebase', 'GetTimebase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_int32), 'int32_t*', 'timeIntervalNanoseconds'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps4000aGetTimebase2', 'GetTimebase2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_float), 'float*', 'timeIntervalNanoseconds'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps4000aGetTriggerTimeOffset', 'GetTriggerTimeOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(POINTER(c_enum), 'PS4000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps4000aGetTriggerTimeOffset64', 'GetTriggerTimeOffset64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'time'),
(POINTER(c_enum), 'PS4000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps4000aGetUnitInfo', 'GetUnitInfo', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int8), 'int8_t*', 'string'),
(c_int16, 'int16_t', 'stringLength'),
(POINTER(c_int16), 'int16_t*', 'requiredSize'),
(PICO_INFO, 'PICO_INFO', 'info')]
),
('ps4000aGetValues', 'GetValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS4000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps4000aGetValuesAsync', 'GetValuesAsync', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(c_uint32, 'uint32_t', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS4000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(ps4000aDataReady, 'void*', 'lpDataReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps4000aGetValuesBulk', 'GetValuesBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS4000A_RATIO_MODE', 'downSampleRatioMode'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps4000aGetValuesOverlapped', 'GetValuesOverlapped', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS4000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps4000aGetValuesOverlappedBulk', 'GetValuesOverlappedBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS4000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps4000aGetValuesTriggerTimeOffsetBulk', 'GetValuesTriggerTimeOffsetBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timesUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timesLower'),
(POINTER(c_enum), 'PS4000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex')]
),
('ps4000aGetValuesTriggerTimeOffsetBulk64', 'GetValuesTriggerTimeOffsetBulk64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'times'),
(POINTER(c_enum), 'PS4000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex')]
),
('ps4000aIsLedFlashing', 'IsLedFlashing', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'status')]
),
('ps4000aIsReady', 'IsReady', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'ready')]
),
('ps4000aIsTriggerOrPulseWidthQualifierEnabled', 'IsTriggerOrPulseWidthQualifierEnabled', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'triggerEnabled'),
(POINTER(c_int16), 'int16_t*', 'pulseWidthQualifierEnabled')]
),
('ps4000aMaximumValue', 'MaximumValue', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'value')]
),
('ps4000aMemorySegments', 'MemorySegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'nSegments'),
(POINTER(c_int32), 'int32_t*', 'nMaxSamples')]
),
('ps4000aMinimumValue', 'MinimumValue', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'value')]
),
('ps4000aNoOfStreamingValues', 'NoOfStreamingValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfValues')]
),
('ps4000aOpenUnit', 'OpenUnit', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int8), 'int8_t*', 'serial')]
),
('ps4000aOpenUnitAsync', 'OpenUnitAsync', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'status'),
(POINTER(c_int8), 'int8_t*', 'serial')]
),
('ps4000aOpenUnitProgress', 'OpenUnitProgress', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int16), 'int16_t*', 'progressPercent'),
(POINTER(c_int16), 'int16_t*', 'complete')]
),
('ps4000aPingUnit', 'PingUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps4000aRunBlock', 'RunBlock', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'noOfPreTriggerSamples'),
(c_int32, 'int32_t', 'noOfPostTriggerSamples'),
(c_uint32, 'uint32_t', 'timebase'),
(POINTER(c_int32), 'int32_t*', 'timeIndisposedMs'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(BlockReady, 'ps4000aBlockReady', 'lpReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps4000aRunStreaming', 'RunStreaming', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'sampleInterval'),
(c_enum, 'PS4000A_TIME_UNITS', 'sampleIntervalTimeUnits'),
(c_uint32, 'uint32_t', 'maxPreTriggerSamples'),
(c_uint32, 'uint32_t', 'maxPostTriggerSamples'),
(c_int16, 'int16_t', 'autoStop'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS4000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'overviewBufferSize')]
),
('ps4000aSetBandwidthFilter', 'SetBandwidthFilter', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000A_CHANNEL', 'channel'),
(c_enum, 'PS4000A_BANDWIDTH_LIMITER', 'bandwidth')]
),
('ps4000aSetChannel', 'SetChannel', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000A_CHANNEL', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_enum, 'PS4000A_COUPLING', 'type'),
(c_enum, 'PS4000A_RANGE', 'range'),
(c_float, 'float', 'analogOffset')]
),
('ps4000aSetChannelLed', 'SetChannelLed', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS4000AChannelLedSetting), 'PS4000A_CHANNEL_LED_SETTING*', 'ledStates'),
(c_uint16, 'uint16_t', 'nLedStates')]
),
('ps4000aSetDataBuffer', 'SetDataBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000A_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(c_enum, 'PS4000A_RATIO_MODE', 'mode')]
),
('ps4000aSetDataBuffers', 'SetDataBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000A_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'bufferMax'),
(POINTER(c_int16), 'int16_t*', 'bufferMin'),
(c_int32, 'int32_t', 'bufferLth'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(c_enum, 'PS4000A_RATIO_MODE', 'mode')]
),
('ps4000aSetEts', 'SetEts', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000A_ETS_MODE', 'mode'),
(c_int16, 'int16_t', 'etsCycles'),
(c_int16, 'int16_t', 'etsInterleave'),
(POINTER(c_int32), 'int32_t*', 'sampleTimePicoseconds')]
),
('ps4000aSetEtsTimeBuffer', 'SetEtsTimeBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps4000aSetEtsTimeBuffers', 'SetEtsTimeBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps4000aSetFrequencyCounter', 'SetFrequencyCounter', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000A_CHANNEL', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_enum, 'PS4000A_FREQUENCY_COUNTER_RANGE', 'range'),
(c_int16, 'int16_t', 'thresholdMajor'),
(c_int16, 'int16_t', 'thresholdMinor')]
),
('ps4000aSetNoOfCaptures', 'SetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'nCaptures')]
),
('ps4000aSetPulseWidthQualifierConditions', 'SetPulseWidthQualifierConditions', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS4000ACondition), 'PS4000A_CONDITION*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'PS4000A_CONDITIONS_INFO', 'info')]
),
('ps4000aSetPulseWidthQualifierProperties', 'SetPulseWidthQualifierProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS4000A_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'lower'),
(c_uint32, 'uint32_t', 'upper'),
(c_enum, 'PS4000A_PULSE_WIDTH_TYPE', 'type')]
),
('ps4000aSetSigGenArbitrary', 'SetSigGenArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(ndpointer(dtype=c_int16, ndim=1, flags='C_CONTIGUOUS'), 'int16_t*', 'arbitraryWaveform'),
(c_int32, 'int32_t', 'arbitraryWaveformSize'),
(c_enum, 'PS4000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS4000A_EXTRA_OPERATIONS', 'operation'),
(c_enum, 'PS4000A_INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS4000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS4000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps4000aSetSigGenBuiltIn', 'SetSigGenBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_enum, 'PS4000A_WAVE_TYPE', 'waveType'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'PS4000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS4000A_EXTRA_OPERATIONS', 'operation'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS4000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS4000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps4000aSetSigGenPropertiesArbitrary', 'SetSigGenPropertiesArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(c_enum, 'PS4000A_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS4000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS4000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps4000aSetSigGenPropertiesBuiltIn', 'SetSigGenPropertiesBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'PS4000A_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS4000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS4000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps4000aSetSimpleTrigger', 'SetSimpleTrigger', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'enable'),
(c_enum, 'PS4000A_CHANNEL', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_enum, 'PS4000A_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'delay'),
(c_int16, 'int16_t', 'autoTrigger_ms')]
),
('ps4000aSetTriggerChannelConditions', 'SetTriggerChannelConditions', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS4000ACondition), 'PS4000A_CONDITION*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'PS4000A_CONDITIONS_INFO', 'info')]
),
('ps4000aSetTriggerChannelDirections', 'SetTriggerChannelDirections', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS4000ADirection), 'PS4000A_DIRECTION*', 'directions'),
(c_int16, 'int16_t', 'nDirections')]
),
('ps4000aSetTriggerChannelProperties', 'SetTriggerChannelProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS4000ATriggerChannelProperties), 'PS4000A_TRIGGER_CHANNEL_PROPERTIES*', 'channelProperties'),
(c_int16, 'int16_t', 'nChannelProperties'),
(c_int16, 'int16_t', 'auxOutputEnable'),
(c_int32, 'int32_t', 'autoTriggerMilliseconds')]
),
('ps4000aSetTriggerDelay', 'SetTriggerDelay', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'delay')]
),
('ps4000aSigGenArbitraryMinMaxValues', 'SigGenArbitraryMinMaxValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'minArbitraryWaveformValue'),
(POINTER(c_int16), 'int16_t*', 'maxArbitraryWaveformValue'),
(POINTER(c_uint32), 'uint32_t*', 'minArbitraryWaveformSize'),
(POINTER(c_uint32), 'uint32_t*', 'maxArbitraryWaveformSize')]
),
('ps4000aSigGenFrequencyToPhase', 'SigGenFrequencyToPhase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'frequency'),
(c_enum, 'PS4000A_INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'bufferLength'),
(POINTER(c_uint32), 'uint32_t*', 'phase')]
),
('ps4000aSigGenSoftwareControl', 'SigGenSoftwareControl', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'state')]
),
('ps4000aStop', 'Stop', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
]
# ************************ SDK functions for ps5000Api ************************
ps5000Api_funcptrs = [
('ps5000CloseUnit', 'CloseUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps5000FlashLed', 'FlashLed', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'start')]
),
('ps5000GetMaxDownSampleRatio', 'GetMaxDownSampleRatio', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'noOfUnaggreatedSamples'),
(POINTER(c_uint32), 'uint32_t*', 'maxDownSampleRatio'),
(c_int16, 'int16_t', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps5000GetStreamingLatestValues', 'GetStreamingLatestValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(ps5000StreamingReady, 'ps5000StreamingReady', 'lpPs'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps5000GetTimebase', 'GetTimebase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_int32), 'int32_t*', 'timeIntervalNanoseconds'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps5000GetTimebase2', 'GetTimebase2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_float), 'float*', 'timeIntervalNanoseconds'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps5000GetTriggerTimeOffset', 'GetTriggerTimeOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(POINTER(c_enum), 'PS5000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps5000GetTriggerTimeOffset64', 'GetTriggerTimeOffset64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'time'),
(POINTER(c_enum), 'PS5000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'segmentIndex')]
),
('ps5000GetUnitInfo', 'GetUnitInfo', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int8), 'int8_t*', 'string'),
(c_int16, 'int16_t', 'stringLength'),
(POINTER(c_int16), 'int16_t*', 'requiredSize'),
(PICO_INFO, 'PICO_INFO', 'info')]
),
('ps5000GetValues', 'GetValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_int16, 'int16_t', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps5000GetValuesAsync', 'GetValuesAsync', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(c_uint32, 'uint32_t', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_int16, 'int16_t', 'downSampleRatioMode'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(ps5000DataReady, 'void*', 'lpDataReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps5000GetValuesBulk', 'GetValuesBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps5000GetValuesTriggerTimeOffsetBulk', 'GetValuesTriggerTimeOffsetBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timesUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timesLower'),
(POINTER(c_enum), 'PS5000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex')]
),
('ps5000GetValuesTriggerTimeOffsetBulk64', 'GetValuesTriggerTimeOffsetBulk64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'times'),
(POINTER(c_enum), 'PS5000_TIME_UNITS*', 'timeUnits'),
(c_uint16, 'uint16_t', 'fromSegmentIndex'),
(c_uint16, 'uint16_t', 'toSegmentIndex')]
),
('ps5000IsLedFlashing', 'IsLedFlashing', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'status')]
),
('ps5000IsReady', 'IsReady', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'ready')]
),
('ps5000IsTriggerOrPulseWidthQualifierEnabled', 'IsTriggerOrPulseWidthQualifierEnabled', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'triggerEnabled'),
(POINTER(c_int16), 'int16_t*', 'pulseWidthQualifierEnabled')]
),
('ps5000MemorySegments', 'MemorySegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint16, 'uint16_t', 'nSegments'),
(POINTER(c_int32), 'int32_t*', 'nMaxSamples')]
),
('ps5000NoOfStreamingValues', 'NoOfStreamingValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfValues')]
),
('ps5000OpenUnit', 'OpenUnit', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle')]
),
('ps5000OpenUnitAsync', 'OpenUnitAsync', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'status')]
),
('ps5000OpenUnitProgress', 'OpenUnitProgress', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int16), 'int16_t*', 'progressPercent'),
(POINTER(c_int16), 'int16_t*', 'complete')]
),
('ps5000PingUnit', 'PingUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps5000RunBlock', 'RunBlock', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'noOfPreTriggerSamples'),
(c_int32, 'int32_t', 'noOfPostTriggerSamples'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'timeIndisposedMs'),
(c_uint16, 'uint16_t', 'segmentIndex'),
(BlockReady, 'ps5000BlockReady', 'lpReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps5000RunStreaming', 'RunStreaming', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'sampleInterval'),
(c_enum, 'PS5000_TIME_UNITS', 'sampleIntervalTimeUnits'),
(c_uint32, 'uint32_t', 'maxPreTriggerSamples'),
(c_uint32, 'uint32_t', 'maxPostPreTriggerSamples'),
(c_int16, 'int16_t', 'autoStop'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_uint32, 'uint32_t', 'overviewBufferSize')]
),
('ps5000SetChannel', 'SetChannel', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000_CHANNEL', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_int16, 'int16_t', 'dc'),
(c_enum, 'PS5000_RANGE', 'range')]
),
('ps5000SetDataBuffer', 'SetDataBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps5000SetDataBufferBulk', 'SetDataBufferBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth'),
(c_uint16, 'uint16_t', 'waveform')]
),
('ps5000SetDataBuffers', 'SetDataBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'bufferMax'),
(POINTER(c_int16), 'int16_t*', 'bufferMin'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps5000SetEts', 'SetEts', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000_ETS_MODE', 'mode'),
(c_int16, 'int16_t', 'etsCycles'),
(c_int16, 'int16_t', 'etsInterleave'),
(POINTER(c_int32), 'int32_t*', 'sampleTimePicoseconds')]
),
('ps5000SetEtsTimeBuffer', 'SetEtsTimeBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps5000SetEtsTimeBuffers', 'SetEtsTimeBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps5000SetNoOfCaptures', 'SetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint16, 'uint16_t', 'nCaptures')]
),
('ps5000SetPulseWidthQualifier', 'SetPulseWidthQualifier', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS5000PwqConditions), 'PWQ_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'lower'),
(c_uint32, 'uint32_t', 'upper'),
(c_enum, 'PULSE_WIDTH_TYPE', 'type')]
),
('ps5000SetSigGenArbitrary', 'SetSigGenArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(ndpointer(dtype=c_int16, ndim=1, flags='C_CONTIGUOUS'), 'int16_t*', 'arbitraryWaveform'),
(c_int32, 'int32_t', 'arbitraryWaveformSize'),
(c_enum, 'SWEEP_TYPE', 'sweepType'),
(c_int16, 'int16_t', 'whiteNoise'),
(c_enum, 'INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps5000SetSigGenBuiltIn', 'SetSigGenBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_int16, 'int16_t', 'waveType'),
(c_float, 'float', 'startFrequency'),
(c_float, 'float', 'stopFrequency'),
(c_float, 'float', 'increment'),
(c_float, 'float', 'dwellTime'),
(c_enum, 'SWEEP_TYPE', 'sweepType'),
(c_int16, 'int16_t', 'whiteNoise'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps5000SetSigGenBuiltInV2', 'SetSigGenBuiltInV2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_int16, 'int16_t', 'waveType'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'SWEEP_TYPE', 'sweepType'),
(c_int16, 'int16_t', 'whiteNoise'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps5000SetSimpleTrigger', 'SetSimpleTrigger', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'enable'),
(c_enum, 'PS5000_CHANNEL', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_enum, 'THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'delay'),
(c_int16, 'int16_t', 'autoTrigger_ms')]
),
('ps5000SetTriggerChannelConditions', 'SetTriggerChannelConditions', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS5000TriggerConditions), 'TRIGGER_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions')]
),
('ps5000SetTriggerChannelDirections', 'SetTriggerChannelDirections', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelA'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelB'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelC'),
(c_enum, 'THRESHOLD_DIRECTION', 'channelD'),
(c_enum, 'THRESHOLD_DIRECTION', 'ext'),
(c_enum, 'THRESHOLD_DIRECTION', 'aux')]
),
('ps5000SetTriggerChannelProperties', 'SetTriggerChannelProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS5000TriggerChannelProperties), 'TRIGGER_CHANNEL_PROPERTIES*', 'channelProperties'),
(c_int16, 'int16_t', 'nChannelProperties'),
(c_int16, 'int16_t', 'auxOutputEnable'),
(c_int32, 'int32_t', 'autoTriggerMilliseconds')]
),
('ps5000SetTriggerDelay', 'SetTriggerDelay', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'delay')]
),
('ps5000SigGenArbitraryMinMaxValues', 'SigGenArbitraryMinMaxValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'minArbitraryWaveformValue'),
(POINTER(c_int16), 'int16_t*', 'maxArbitraryWaveformValue'),
(POINTER(c_uint32), 'uint32_t*', 'minArbitraryWaveformSize'),
(POINTER(c_uint32), 'uint32_t*', 'maxArbitraryWaveformSize')]
),
('ps5000SigGenFrequencyToPhase', 'SigGenFrequencyToPhase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'frequency'),
(c_enum, 'INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'bufferLength'),
(POINTER(c_uint32), 'uint32_t*', 'phase')]
),
('ps5000SigGenSoftwareControl', 'SigGenSoftwareControl', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'state')]
),
('ps5000Stop', 'Stop', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
]
# ************************ SDK functions for ps5000aApi ************************
ps5000aApi_funcptrs = [
('ps5000aChangePowerSource', 'ChangePowerSource', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(PICO_STATUS, 'PICO_STATUS', 'powerState')]
),
('ps5000aCloseUnit', 'CloseUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps5000aCurrentPowerSource', 'CurrentPowerSource', PICO_STATUS, None,
[(c_int16, 'int16_t', 'handle')]
),
('ps5000aEnumerateUnits', 'EnumerateUnits', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'count'),
(POINTER(c_int8), 'int8_t*', 'serials'),
(POINTER(c_int16), 'int16_t*', 'serialLth')]
),
('ps5000aFlashLed', 'FlashLed', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'start')]
),
('ps5000aGetAnalogueOffset', 'GetAnalogueOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000A_RANGE', 'range'),
(c_enum, 'PS5000A_COUPLING', 'coupling'),
(POINTER(c_float), 'float*', 'maximumVoltage'),
(POINTER(c_float), 'float*', 'minimumVoltage')]
),
('ps5000aGetChannelInformation', 'GetChannelInformation', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000A_CHANNEL_INFO', 'info'),
(c_int32, 'int32_t', 'probe'),
(POINTER(c_int32), 'int32_t*', 'ranges'),
(POINTER(c_int32), 'int32_t*', 'length'),
(c_int32, 'int32_t', 'channels')]
),
('ps5000aGetDeviceResolution', 'GetDeviceResolution', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_enum), 'PS5000A_DEVICE_RESOLUTION*', 'resolution')]
),
('ps5000aGetMaxDownSampleRatio', 'GetMaxDownSampleRatio', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'noOfUnaggreatedSamples'),
(POINTER(c_uint32), 'uint32_t*', 'maxDownSampleRatio'),
(c_enum, 'PS5000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps5000aGetMaxSegments', 'GetMaxSegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'maxSegments')]
),
('ps5000aGetNoOfCaptures', 'GetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'nCaptures')]
),
('ps5000aGetNoOfProcessedCaptures', 'GetNoOfProcessedCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'nProcessedCaptures')]
),
('ps5000aGetStreamingLatestValues', 'GetStreamingLatestValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(ps5000aStreamingReady, 'ps5000aStreamingReady', 'lpPs'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps5000aGetTimebase', 'GetTimebase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_int32), 'int32_t*', 'timeIntervalNanoseconds'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps5000aGetTimebase2', 'GetTimebase2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int32, 'int32_t', 'noSamples'),
(POINTER(c_float), 'float*', 'timeIntervalNanoseconds'),
(POINTER(c_int32), 'int32_t*', 'maxSamples'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps5000aGetTriggerInfoBulk', 'GetTriggerInfoBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS5000ATriggerInfo), 'PS5000A_TRIGGER_INFO*', 'triggerInfo'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex')]
),
('ps5000aGetTriggerTimeOffset', 'GetTriggerTimeOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(POINTER(c_enum), 'PS5000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps5000aGetTriggerTimeOffset64', 'GetTriggerTimeOffset64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'time'),
(POINTER(c_enum), 'PS5000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps5000aGetUnitInfo', 'GetUnitInfo', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int8), 'int8_t*', 'string'),
(c_int16, 'int16_t', 'stringLength'),
(POINTER(c_int16), 'int16_t*', 'requiredSize'),
(PICO_INFO, 'PICO_INFO', 'info')]
),
('ps5000aGetValues', 'GetValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS5000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps5000aGetValuesAsync', 'GetValuesAsync', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(c_uint32, 'uint32_t', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS5000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(ps5000aDataReady, 'void*', 'lpDataReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps5000aGetValuesBulk', 'GetValuesBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS5000A_RATIO_MODE', 'downSampleRatioMode'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps5000aGetValuesOverlapped', 'GetValuesOverlapped', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS5000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps5000aGetValuesOverlappedBulk', 'GetValuesOverlappedBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS5000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps5000aGetValuesTriggerTimeOffsetBulk', 'GetValuesTriggerTimeOffsetBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timesUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timesLower'),
(POINTER(c_enum), 'PS5000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex')]
),
('ps5000aGetValuesTriggerTimeOffsetBulk64', 'GetValuesTriggerTimeOffsetBulk64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'times'),
(POINTER(c_enum), 'PS5000A_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex')]
),
('ps5000aIsLedFlashing', 'IsLedFlashing', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'status')]
),
('ps5000aIsReady', 'IsReady', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'ready')]
),
('ps5000aIsTriggerOrPulseWidthQualifierEnabled', 'IsTriggerOrPulseWidthQualifierEnabled', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'triggerEnabled'),
(POINTER(c_int16), 'int16_t*', 'pulseWidthQualifierEnabled')]
),
('ps5000aMaximumValue', 'MaximumValue', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'value')]
),
('ps5000aMemorySegments', 'MemorySegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'nSegments'),
(POINTER(c_int32), 'int32_t*', 'nMaxSamples')]
),
('ps5000aMinimumValue', 'MinimumValue', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'value')]
),
('ps5000aNoOfStreamingValues', 'NoOfStreamingValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfValues')]
),
('ps5000aOpenUnit', 'OpenUnit', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int8), 'int8_t*', 'serial'),
(c_enum, 'PS5000A_DEVICE_RESOLUTION', 'resolution')]
),
('ps5000aOpenUnitAsync', 'OpenUnitAsync', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'status'),
(POINTER(c_int8), 'int8_t*', 'serial'),
(c_enum, 'PS5000A_DEVICE_RESOLUTION', 'resolution')]
),
('ps5000aOpenUnitProgress', 'OpenUnitProgress', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int16), 'int16_t*', 'progressPercent'),
(POINTER(c_int16), 'int16_t*', 'complete')]
),
('ps5000aPingUnit', 'PingUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps5000aRunBlock', 'RunBlock', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'noOfPreTriggerSamples'),
(c_int32, 'int32_t', 'noOfPostTriggerSamples'),
(c_uint32, 'uint32_t', 'timebase'),
(POINTER(c_int32), 'int32_t*', 'timeIndisposedMs'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(BlockReady, 'ps5000aBlockReady', 'lpReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps5000aRunStreaming', 'RunStreaming', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'sampleInterval'),
(c_enum, 'PS5000A_TIME_UNITS', 'sampleIntervalTimeUnits'),
(c_uint32, 'uint32_t', 'maxPreTriggerSamples'),
(c_uint32, 'uint32_t', 'maxPostTriggerSamples'),
(c_int16, 'int16_t', 'autoStop'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS5000A_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'overviewBufferSize')]
),
('ps5000aSetBandwidthFilter', 'SetBandwidthFilter', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000A_CHANNEL', 'channel'),
(c_enum, 'PS5000A_BANDWIDTH_LIMITER', 'bandwidth')]
),
('ps5000aSetChannel', 'SetChannel', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000A_CHANNEL', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_enum, 'PS5000A_COUPLING', 'type'),
(c_enum, 'PS5000A_RANGE', 'range'),
(c_float, 'float', 'analogOffset')]
),
('ps5000aSetDataBuffer', 'SetDataBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000A_CHANNEL', 'channel'),
(ndpointer(dtype=c_int16, flags='C_CONTIGUOUS'), 'int16_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(c_enum, 'PS5000A_RATIO_MODE', 'mode')]
),
('ps5000aSetDataBuffers', 'SetDataBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000A_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'bufferMax'),
(POINTER(c_int16), 'int16_t*', 'bufferMin'),
(c_int32, 'int32_t', 'bufferLth'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(c_enum, 'PS5000A_RATIO_MODE', 'mode')]
),
('ps5000aSetDeviceResolution', 'SetDeviceResolution', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000A_DEVICE_RESOLUTION', 'resolution')]
),
('ps5000aSetEts', 'SetEts', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000A_ETS_MODE', 'mode'),
(c_int16, 'int16_t', 'etsCycles'),
(c_int16, 'int16_t', 'etsInterleave'),
(POINTER(c_int32), 'int32_t*', 'sampleTimePicoseconds')]
),
('ps5000aSetEtsTimeBuffer', 'SetEtsTimeBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'buffer'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps5000aSetEtsTimeBuffers', 'SetEtsTimeBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(c_int32, 'int32_t', 'bufferLth')]
),
('ps5000aSetNoOfCaptures', 'SetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'nCaptures')]
),
('ps5000aSetPulseWidthQualifier', 'SetPulseWidthQualifier', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS5000APwqConditions), 'PS5000A_PWQ_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'PS5000A_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'lower'),
(c_uint32, 'uint32_t', 'upper'),
(c_enum, 'PS5000A_PULSE_WIDTH_TYPE', 'type')]
),
('ps5000aSetSigGenArbitrary', 'SetSigGenArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(ndpointer(dtype=c_int16, ndim=1, flags='C_CONTIGUOUS'), 'int16_t*', 'arbitraryWaveform'),
(c_int32, 'int32_t', 'arbitraryWaveformSize'),
(c_enum, 'PS5000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS5000A_EXTRA_OPERATIONS', 'operation'),
(c_enum, 'PS5000A_INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS5000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS5000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps5000aSetSigGenBuiltIn', 'SetSigGenBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_enum, 'PS5000A_WAVE_TYPE', 'waveType'),
(c_float, 'float', 'startFrequency'),
(c_float, 'float', 'stopFrequency'),
(c_float, 'float', 'increment'),
(c_float, 'float', 'dwellTime'),
(c_enum, 'PS5000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS5000A_EXTRA_OPERATIONS', 'operation'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS5000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS5000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps5000aSetSigGenBuiltInV2', 'SetSigGenBuiltInV2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_enum, 'PS5000A_WAVE_TYPE', 'waveType'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'PS5000A_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS5000A_EXTRA_OPERATIONS', 'operation'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS5000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS5000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps5000aSetSigGenPropertiesArbitrary', 'SetSigGenPropertiesArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(c_enum, 'PS5000A_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS5000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS5000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps5000aSetSigGenPropertiesBuiltIn', 'SetSigGenPropertiesBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'PS5000A_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS5000A_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS5000A_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps5000aSetSimpleTrigger', 'SetSimpleTrigger', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'enable'),
(c_enum, 'PS5000A_CHANNEL', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_enum, 'PS5000A_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'delay'),
(c_int16, 'int16_t', 'autoTrigger_ms')]
),
('ps5000aSetTriggerChannelConditions', 'SetTriggerChannelConditions', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS5000ATriggerConditions), 'PS5000A_TRIGGER_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions')]
),
('ps5000aSetTriggerChannelDirections', 'SetTriggerChannelDirections', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000A_THRESHOLD_DIRECTION', 'channelA'),
(c_enum, 'PS5000A_THRESHOLD_DIRECTION', 'channelB'),
(c_enum, 'PS5000A_THRESHOLD_DIRECTION', 'channelC'),
(c_enum, 'PS5000A_THRESHOLD_DIRECTION', 'channelD'),
(c_enum, 'PS5000A_THRESHOLD_DIRECTION', 'ext'),
(c_enum, 'PS5000A_THRESHOLD_DIRECTION', 'aux')]
),
('ps5000aSetTriggerChannelProperties', 'SetTriggerChannelProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS5000ATriggerChannelProperties), 'PS5000A_TRIGGER_CHANNEL_PROPERTIES*', 'channelProperties'),
(c_int16, 'int16_t', 'nChannelProperties'),
(c_int16, 'int16_t', 'auxOutputEnable'),
(c_int32, 'int32_t', 'autoTriggerMilliseconds')]
),
('ps5000aSetTriggerDelay', 'SetTriggerDelay', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'delay')]
),
('ps5000aSigGenArbitraryMinMaxValues', 'SigGenArbitraryMinMaxValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'minArbitraryWaveformValue'),
(POINTER(c_int16), 'int16_t*', 'maxArbitraryWaveformValue'),
(POINTER(c_uint32), 'uint32_t*', 'minArbitraryWaveformSize'),
(POINTER(c_uint32), 'uint32_t*', 'maxArbitraryWaveformSize')]
),
('ps5000aSigGenFrequencyToPhase', 'SigGenFrequencyToPhase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'frequency'),
(c_enum, 'PS5000A_INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'bufferLength'),
(POINTER(c_uint32), 'uint32_t*', 'phase')]
),
('ps5000aSigGenSoftwareControl', 'SigGenSoftwareControl', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'state')]
),
('ps5000aStop', 'Stop', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps5000aTriggerWithinPreTriggerSamples', 'TriggerWithinPreTriggerSamples', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS5000A_TRIGGER_WITHIN_PRE_TRIGGER', 'state')]
),
]
# ************************ SDK functions for ps6000Api ************************
ps6000Api_funcptrs = [
('ps6000CloseUnit', 'CloseUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps6000EnumerateUnits', 'EnumerateUnits', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'count'),
(POINTER(c_int8), 'int8_t*', 'serials'),
(POINTER(c_int16), 'int16_t*', 'serialLth')]
),
('ps6000FlashLed', 'FlashLed', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'start')]
),
('ps6000GetAnalogueOffset', 'GetAnalogueOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS6000_RANGE', 'range'),
(c_enum, 'PS6000_COUPLING', 'coupling'),
(POINTER(c_float), 'float*', 'maximumVoltage'),
(POINTER(c_float), 'float*', 'minimumVoltage')]
),
('ps6000GetMaxDownSampleRatio', 'GetMaxDownSampleRatio', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'noOfUnaggreatedSamples'),
(POINTER(c_uint32), 'uint32_t*', 'maxDownSampleRatio'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps6000GetNoOfCaptures', 'GetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'nCaptures')]
),
('ps6000GetNoOfProcessedCaptures', 'GetNoOfProcessedCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'nProcessedCaptures')]
),
('ps6000GetStreamingLatestValues', 'GetStreamingLatestValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(ps6000StreamingReady, 'ps6000StreamingReady', 'lpPs'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps6000GetTimebase', 'GetTimebase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_uint32, 'uint32_t', 'noSamples'),
(POINTER(c_int32), 'int32_t*', 'timeIntervalNanoseconds'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_uint32), 'uint32_t*', 'maxSamples'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps6000GetTimebase2', 'GetTimebase2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'timebase'),
(c_uint32, 'uint32_t', 'noSamples'),
(POINTER(c_float), 'float*', 'timeIntervalNanoseconds'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_uint32), 'uint32_t*', 'maxSamples'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps6000GetTriggerTimeOffset', 'GetTriggerTimeOffset', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(POINTER(c_enum), 'PS6000_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps6000GetTriggerTimeOffset64', 'GetTriggerTimeOffset64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'time'),
(POINTER(c_enum), 'PS6000_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'segmentIndex')]
),
('ps6000GetUnitInfo', 'GetUnitInfo', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int8), 'int8_t*', 'string'),
(c_int16, 'int16_t', 'stringLength'),
(POINTER(c_int16), 'int16_t*', 'requiredSize'),
(PICO_INFO, 'PICO_INFO', 'info')]
),
('ps6000GetValues', 'GetValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps6000GetValuesAsync', 'GetValuesAsync', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(c_uint32, 'uint32_t', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(ps6000DataReady, 'void*', 'lpDataReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps6000GetValuesBulk', 'GetValuesBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps6000GetValuesBulkAsyc', 'GetValuesBulkAsyc', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps6000GetValuesOverlapped', 'GetValuesOverlapped', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps6000GetValuesOverlappedBulk', 'GetValuesOverlappedBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'startIndex'),
(POINTER(c_uint32), 'uint32_t*', 'noOfSamples'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex'),
(POINTER(c_int16), 'int16_t*', 'overflow')]
),
('ps6000GetValuesTriggerTimeOffsetBulk', 'GetValuesTriggerTimeOffsetBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timesUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timesLower'),
(POINTER(c_enum), 'PS6000_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex')]
),
('ps6000GetValuesTriggerTimeOffsetBulk64', 'GetValuesTriggerTimeOffsetBulk64', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'times'),
(POINTER(c_enum), 'PS6000_TIME_UNITS*', 'timeUnits'),
(c_uint32, 'uint32_t', 'fromSegmentIndex'),
(c_uint32, 'uint32_t', 'toSegmentIndex')]
),
('ps6000IsReady', 'IsReady', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'ready')]
),
('ps6000IsTriggerOrPulseWidthQualifierEnabled', 'IsTriggerOrPulseWidthQualifierEnabled', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'triggerEnabled'),
(POINTER(c_int16), 'int16_t*', 'pulseWidthQualifierEnabled')]
),
('ps6000MemorySegments', 'MemorySegments', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'nSegments'),
(POINTER(c_uint32), 'uint32_t*', 'nMaxSamples')]
),
('ps6000NoOfStreamingValues', 'NoOfStreamingValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'noOfValues')]
),
('ps6000OpenUnit', 'OpenUnit', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int8), 'int8_t*', 'serial')]
),
('ps6000OpenUnitAsync', 'OpenUnitAsync', PICO_STATUS, 'errcheck_api',
[(POINTER(c_int16), 'int16_t*', 'status'),
(POINTER(c_int8), 'int8_t*', 'serial')]
),
('ps6000OpenUnitProgress', 'OpenUnitProgress', PICO_STATUS, None,
[(POINTER(c_int16), 'int16_t*', 'handle'),
(POINTER(c_int16), 'int16_t*', 'progressPercent'),
(POINTER(c_int16), 'int16_t*', 'complete')]
),
('ps6000PingUnit', 'PingUnit', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
('ps6000RunBlock', 'RunBlock', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'noOfPreTriggerSamples'),
(c_uint32, 'uint32_t', 'noOfPostTriggerSamples'),
(c_uint32, 'uint32_t', 'timebase'),
(c_int16, 'int16_t', 'oversample'),
(POINTER(c_int32), 'int32_t*', 'timeIndisposedMs'),
(c_uint32, 'uint32_t', 'segmentIndex'),
(BlockReady, 'ps6000BlockReady', 'lpReady'),
(POINTER(c_void_p), 'void*', 'pParameter')]
),
('ps6000RunStreaming', 'RunStreaming', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'sampleInterval'),
(c_enum, 'PS6000_TIME_UNITS', 'sampleIntervalTimeUnits'),
(c_uint32, 'uint32_t', 'maxPreTriggerSamples'),
(c_uint32, 'uint32_t', 'maxPostPreTriggerSamples'),
(c_int16, 'int16_t', 'autoStop'),
(c_uint32, 'uint32_t', 'downSampleRatio'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode'),
(c_uint32, 'uint32_t', 'overviewBufferSize')]
),
('ps6000SetChannel', 'SetChannel', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS6000_CHANNEL', 'channel'),
(c_int16, 'int16_t', 'enabled'),
(c_enum, 'PS6000_COUPLING', 'type'),
(c_enum, 'PS6000_RANGE', 'range'),
(c_float, 'float', 'analogueOffset'),
(c_enum, 'PS6000_BANDWIDTH_LIMITER', 'bandwidth')]
),
('ps6000SetDataBuffer', 'SetDataBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS6000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'buffer'),
(c_uint32, 'uint32_t', 'bufferLth'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode')]
),
('ps6000SetDataBufferBulk', 'SetDataBufferBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS6000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'buffer'),
(c_uint32, 'uint32_t', 'bufferLth'),
(c_uint32, 'uint32_t', 'waveform'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode')]
),
('ps6000SetDataBuffers', 'SetDataBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS6000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'bufferMax'),
(POINTER(c_int16), 'int16_t*', 'bufferMin'),
(c_uint32, 'uint32_t', 'bufferLth'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode')]
),
('ps6000SetDataBuffersBulk', 'SetDataBuffersBulk', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS6000_CHANNEL', 'channel'),
(POINTER(c_int16), 'int16_t*', 'bufferMax'),
(POINTER(c_int16), 'int16_t*', 'bufferMin'),
(c_uint32, 'uint32_t', 'bufferLth'),
(c_uint32, 'uint32_t', 'waveform'),
(c_enum, 'PS6000_RATIO_MODE', 'downSampleRatioMode')]
),
('ps6000SetEts', 'SetEts', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS6000_ETS_MODE', 'mode'),
(c_int16, 'int16_t', 'etsCycles'),
(c_int16, 'int16_t', 'etsInterleave'),
(POINTER(c_int32), 'int32_t*', 'sampleTimePicoseconds')]
),
('ps6000SetEtsTimeBuffer', 'SetEtsTimeBuffer', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int64), 'int64_t*', 'buffer'),
(c_uint32, 'uint32_t', 'bufferLth')]
),
('ps6000SetEtsTimeBuffers', 'SetEtsTimeBuffers', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_uint32), 'uint32_t*', 'timeUpper'),
(POINTER(c_uint32), 'uint32_t*', 'timeLower'),
(c_uint32, 'uint32_t', 'bufferLth')]
),
('ps6000SetExternalClock', 'SetExternalClock', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS6000_EXTERNAL_FREQUENCY', 'frequency'),
(c_int16, 'int16_t', 'threshold')]
),
('ps6000SetNoOfCaptures', 'SetNoOfCaptures', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'nCaptures')]
),
('ps6000SetPulseWidthQualifier', 'SetPulseWidthQualifier', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS6000PwqConditions), 'PS6000_PWQ_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions'),
(c_enum, 'PS6000_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'lower'),
(c_uint32, 'uint32_t', 'upper'),
(c_enum, 'PS6000_PULSE_WIDTH_TYPE', 'type')]
),
('ps6000SetSigGenArbitrary', 'SetSigGenArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(ndpointer(dtype=c_int16, ndim=1, flags='C_CONTIGUOUS'), 'int16_t*', 'arbitraryWaveform'),
(c_int32, 'int32_t', 'arbitraryWaveformSize'),
(c_enum, 'PS6000_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS6000_EXTRA_OPERATIONS', 'operation'),
(c_enum, 'PS6000_INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS6000_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS6000_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps6000SetSigGenBuiltIn', 'SetSigGenBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_int16, 'int16_t', 'waveType'),
(c_float, 'float', 'startFrequency'),
(c_float, 'float', 'stopFrequency'),
(c_float, 'float', 'increment'),
(c_float, 'float', 'dwellTime'),
(c_enum, 'PS6000_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS6000_EXTRA_OPERATIONS', 'operation'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS6000_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS6000_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps6000SetSigGenBuiltInV2', 'SetSigGenBuiltInV2', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_int16, 'int16_t', 'waveType'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'PS6000_SWEEP_TYPE', 'sweepType'),
(c_enum, 'PS6000_EXTRA_OPERATIONS', 'operation'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS6000_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS6000_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps6000SetSigGenPropertiesArbitrary', 'SetSigGenPropertiesArbitrary', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_uint32, 'uint32_t', 'startDeltaPhase'),
(c_uint32, 'uint32_t', 'stopDeltaPhase'),
(c_uint32, 'uint32_t', 'deltaPhaseIncrement'),
(c_uint32, 'uint32_t', 'dwellCount'),
(c_enum, 'PS6000_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS6000_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS6000_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps6000SetSigGenPropertiesBuiltIn', 'SetSigGenPropertiesBuiltIn', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int32, 'int32_t', 'offsetVoltage'),
(c_uint32, 'uint32_t', 'pkToPk'),
(c_double, 'double', 'startFrequency'),
(c_double, 'double', 'stopFrequency'),
(c_double, 'double', 'increment'),
(c_double, 'double', 'dwellTime'),
(c_enum, 'PS6000_SWEEP_TYPE', 'sweepType'),
(c_uint32, 'uint32_t', 'shots'),
(c_uint32, 'uint32_t', 'sweeps'),
(c_enum, 'PS6000_SIGGEN_TRIG_TYPE', 'triggerType'),
(c_enum, 'PS6000_SIGGEN_TRIG_SOURCE', 'triggerSource'),
(c_int16, 'int16_t', 'extInThreshold')]
),
('ps6000SetSimpleTrigger', 'SetSimpleTrigger', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'enable'),
(c_enum, 'PS6000_CHANNEL', 'source'),
(c_int16, 'int16_t', 'threshold'),
(c_enum, 'PS6000_THRESHOLD_DIRECTION', 'direction'),
(c_uint32, 'uint32_t', 'delay'),
(c_int16, 'int16_t', 'autoTrigger_ms')]
),
('ps6000SetTriggerChannelConditions', 'SetTriggerChannelConditions', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS6000TriggerConditions), 'PS6000_TRIGGER_CONDITIONS*', 'conditions'),
(c_int16, 'int16_t', 'nConditions')]
),
('ps6000SetTriggerChannelDirections', 'SetTriggerChannelDirections', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_enum, 'PS6000_THRESHOLD_DIRECTION', 'channelA'),
(c_enum, 'PS6000_THRESHOLD_DIRECTION', 'channelB'),
(c_enum, 'PS6000_THRESHOLD_DIRECTION', 'channelC'),
(c_enum, 'PS6000_THRESHOLD_DIRECTION', 'channelD'),
(c_enum, 'PS6000_THRESHOLD_DIRECTION', 'ext'),
(c_enum, 'PS6000_THRESHOLD_DIRECTION', 'aux')]
),
('ps6000SetTriggerChannelProperties', 'SetTriggerChannelProperties', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(PS6000TriggerChannelProperties), 'PS6000_TRIGGER_CHANNEL_PROPERTIES*', 'channelProperties'),
(c_int16, 'int16_t', 'nChannelProperties'),
(c_int16, 'int16_t', 'auxOutputEnable'),
(c_int32, 'int32_t', 'autoTriggerMilliseconds')]
),
('ps6000SetTriggerDelay', 'SetTriggerDelay', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'delay')]
),
('ps6000SetWaveformLimiter', 'SetWaveformLimiter', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_uint32, 'uint32_t', 'nWaveformsPerSecond')]
),
('ps6000SigGenArbitraryMinMaxValues', 'SigGenArbitraryMinMaxValues', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(POINTER(c_int16), 'int16_t*', 'minArbitraryWaveformValue'),
(POINTER(c_int16), 'int16_t*', 'maxArbitraryWaveformValue'),
(POINTER(c_uint32), 'uint32_t*', 'minArbitraryWaveformSize'),
(POINTER(c_uint32), 'uint32_t*', 'maxArbitraryWaveformSize')]
),
('ps6000SigGenFrequencyToPhase', 'SigGenFrequencyToPhase', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_double, 'double', 'frequency'),
(c_enum, 'PS6000_INDEX_MODE', 'indexMode'),
(c_uint32, 'uint32_t', 'bufferLength'),
(POINTER(c_uint32), 'uint32_t*', 'phase')]
),
('ps6000SigGenSoftwareControl', 'SigGenSoftwareControl', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle'),
(c_int16, 'int16_t', 'state')]
),
('ps6000Stop', 'Stop', PICO_STATUS, 'errcheck_api',
[(c_int16, 'int16_t', 'handle')]
),
]
| {
"alphanum_fraction": 0.6318985477,
"author": null,
"avg_line_length": 45.7677806341,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "74da2420650abf785e652717210d379f29d9d371",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2022-03-09T08:54:04.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-02-07T22:08:37.000Z",
"max_forks_repo_head_hexsha": "56bc467e97a2a0a60aa6f031dd30bf1d98ebda5c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "SwiftyMorgan/msl-equipment",
"max_forks_repo_path": "msl/equipment/resources/picotech/picoscope/functions.py",
"max_issues_count": 7,
"max_issues_repo_head_hexsha": "56bc467e97a2a0a60aa6f031dd30bf1d98ebda5c",
"max_issues_repo_issues_event_max_datetime": "2022-01-16T20:16:33.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-24T09:14:51.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "SwiftyMorgan/msl-equipment",
"max_issues_repo_path": "msl/equipment/resources/picotech/picoscope/functions.py",
"max_line_length": 125,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "56bc467e97a2a0a60aa6f031dd30bf1d98ebda5c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "SwiftyMorgan/msl-equipment",
"max_stars_repo_path": "msl/equipment/resources/picotech/picoscope/functions.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-09T08:45:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-07-26T05:07:58.000Z",
"num_tokens": 51748,
"path": null,
"reason": "from numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 160233
} |
import numpy as np
from scipy.interpolate import interp1d
from skfmm import travel_time, distance
from scipy.signal import resample
def resample2d( x, shape=[] ):
if len(shape)==0:
raise ValueError('shape should not be empty.')
x1=resample(x,shape[0],axis=0)
x2=resample(x1,shape[1],axis=1)
return x2
def transform_normal_scores(scores, nscore):
"""
map standard quantiles to empirical probability distribution from
dynamic rupture simulation. values outside the empirical distribution
are mapped to the ends.
"""
x = nscore['nscore']
y = nscore['x']
fill_value = (y.min(), y.max())
f = interp1d(x,y,bounds_error=False,fill_value=fill_value)
return f(scores)
def linear_taper(n, inds=(0,-1), vals=(0.0,1.0) ):
"""
Returns normalized coefficient for linear taper between (start, end) and
values (start_value, end_value)
Args:
n (int) : length of taper
inds (tuple) : indexes of taper, default n
vals (tuple) : coresponding to inds, default {0, 1.0}
Returns:
coef (ndarray) : coefficient {0 .. 1.0} of linear taper over indexes = inds with
values = vals
"""
import numpy as np
# vars
ix = np.arange(n)
coef = np.ones(n)
# linear model
delta_y = vals[1] - vals[0]
if inds == (0,-1):
delta_x = n
else:
delta_x = inds[1] - inds[0]
slope = delta_y / delta_x
intercept = vals[0] - slope * inds[0]
coef[inds[0]:inds[1]] = slope * ix[inds[0]:inds[-1]] + intercept
# returns
return coef
def boundary_taper( field, taper_width=10, free_surface=True, values=0 ):
"""
returns a field tapered along to boundary to zero.
can add taper to some percentage later.
field (2d ndarray) : rupture field to taper.
taper_width (int) : boundary to taper
free_surface (bool) : (true) taper the free surface
(false) do NOT taper free surface
values sequence or int (optional) : ending values for taper. default is zero. value should be specfied
in terms of percentages.
return
tapered_field (ndarray) : tapered field with shape = field.shape
"""
ny, nx = field.shape
if free_surface:
baseline = np.ones( (ny-2*taper_width, nx-2*taper_width) )
padded = np.pad( baseline, ((taper_width,taper_width), (taper_width,taper_width)), 'linear_ramp', end_values=values )
else:
baseline = np.ones( (ny-taper_width, nx-2*taper_width) )
padded = np.pad( baseline, ((0,taper_width), (taper_width,taper_width)), 'linear_ramp', end_values=values )
assert field.shape == padded.shape
return field*padded
"""
Helping functions.
"""
def get_dip(nhat1, nhat2, nhat3):
nz,nx = nhat1.shape
dip = np.ones([nz,nx])
for i in range(nz):
for j in range(nx):
nproj = (nhat1[i,j], 0, nhat3[i,j])
n = (nhat1[i,j], nhat2[i,j], nhat3[i,j])
norm = lambda v: np.sqrt(v[0]**2+v[1]**2+v[2]**2)
scaling = 1.0 / ( norm(nproj) * norm(n) )
arg = scaling*(n[0]**2+n[2]**2)
if np.isclose(1.0, arg):
arg = 1.0
arg=np.arccos(arg)
theta = np.rad2deg(arg)
dip[i,j] = 90 - theta
return dip
def get_moment(slip, vs, rho, params):
mu = vs * vs * rho
area = params['dx'] * params['dx']
moment = mu * area * slip
return moment
def get_strike(nhat1, nhat3, mean_strike=270):
nz,nx = nhat1.shape
strike = np.ones([nz,nx])
for i in range(nz):
for j in range(nx):
nproj = (nhat1[i,j], 0, nhat3[i,j])
x3 = (1,0,0)
norm = lambda v: np.sqrt(v[0]**2+v[1]**2+v[2]**2)
scaling = 1.0 / ( norm(x3) * norm( nproj) )
theta = np.rad2deg(scaling * np.arccos(nproj[2]))
if nhat1[i,j] > 0 and nhat3[i,j] > 0:
strike[i,j] = 270 + theta
elif nhat1[i,j] < 0 and nhat3[i,j] > 0:
strike[i,j] = 270 - theta
elif nhat1[i,j] < 0 and nhat3[i,j] < 0:
# in 3rd quad
strike[i,j] = 270 - theta
elif nhat1[i,j] > 0 and nhat3[i,j] < 0:
# in 4th quad
strike[i,j] = theta - 90
# rotate to different strike
stk = strike - 270 + mean_strike
return stk
def source_time_function():
pass
def compute_trup(vrup, params):
phi = np.ones( (params['nz'],params['nx']) ) #* params['dx']
ihypo = params['ihypo']
phi[ ihypo[0], ihypo[1] ] = -1
trup = travel_time( phi, speed=vrup, dx=params['dx'] )
return np.array(trup)
def expand_bbp_velocity_model(velocity_model_bbp_format, nx, nz, dx):
"""
"""
# create array of discrete depths
z = np.linspace(0, (nz-1)*dx, nz)
# bbp provides layer thickness, so must convert to depth
dep_inc = velocity_model_bbp_format[:,0]
dep = np.cumsum(dep_inc)
# look-up discrete depths in model
layer_idxs = np.searchsorted(dep, z, side='right')
# debugging stuff
vs = np.zeros((nz, nx))
vp = np.zeros((nz, nx))
rho = np.zeros((nz, nx))
for i, idx in enumerate(layer_idxs):
# bbp format has cols: [layer_thickness, vp, vs, rho, qp, qs]
vp[i,:] = velocity_model_bbp_format[idx, 1]
vs[i,:] = velocity_model_bbp_format[idx, 2]
rho[i,:] = velocity_model_bbp_format[idx, 3]
return vp, vs, rho
if __name__ == "__main__":
from utils import plot_2d_image
mod = np.loadtxt('./central_japan_bbp1d.txt')
nx = 273
nz = 136
dx = 0.1
_, vs, _ = expand_bbp_velocity_model(mod, nx, nz, dx)
ax = plot_2d_image(vs, nx=nx, nz=nz, dx=dx,
clabel = r'$c_s$ (km/s) ', xlabel="Distance (km)", ylabel="Distance (km)",
surface_plot=False, contour_plot=False)
| {
"alphanum_fraction": 0.57733692,
"author": null,
"avg_line_length": 30.6597938144,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "30b170cea6ab132619890ee1e5056a10ea009bbf",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-07-20T23:58:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-20T23:58:53.000Z",
"max_forks_repo_head_hexsha": "001fcf8275eb158765de4e99e0d442b1712aa061",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "longyearxuk/sokrg",
"max_forks_repo_path": "krg_utils.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "001fcf8275eb158765de4e99e0d442b1712aa061",
"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": "longyearxuk/sokrg",
"max_issues_repo_path": "krg_utils.py",
"max_line_length": 125,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "001fcf8275eb158765de4e99e0d442b1712aa061",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "longyearxuk/sokrg",
"max_stars_repo_path": "krg_utils.py",
"max_stars_repo_stars_event_max_datetime": "2021-07-20T23:02:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-20T22:59:24.000Z",
"num_tokens": 1758,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 5948
} |
Require Export TopologicalSpaces.
Require Export Continuity.
Inductive homeomorphism {X Y:TopologicalSpace}
(f:point_set X -> point_set Y) : Prop :=
| intro_homeomorphism: forall g:point_set Y -> point_set X,
continuous f -> continuous g ->
(forall x:point_set X, g (f x) = x) ->
(forall y:point_set Y, f (g y) = y) -> homeomorphism f.
Lemma homeomorphism_is_invertible: forall {X Y:TopologicalSpace}
(f:point_set X -> point_set Y),
homeomorphism f -> invertible f.
Proof.
intros.
destruct H as [g].
exists g; trivial.
Qed.
Definition open_map {X Y:TopologicalSpace}
(f:point_set X -> point_set Y) : Prop :=
forall U:Ensemble (point_set X), open U -> open (Im U f).
Lemma homeomorphism_is_open_map: forall {X Y:TopologicalSpace}
(f:point_set X -> point_set Y),
homeomorphism f -> open_map f.
Proof.
intros.
destruct H as [g].
red; intros.
assert (Im U f = inverse_image g U).
apply Extensionality_Ensembles; split; red; intros.
destruct H4.
rewrite H5.
constructor.
rewrite H1; trivial.
destruct H4.
exists (g x); trivial.
symmetry; apply H2.
rewrite H4; apply H0; trivial.
Qed.
Lemma invertible_open_map_is_homeomorphism: forall {X Y:TopologicalSpace}
(f:point_set X -> point_set Y),
invertible f -> continuous f -> open_map f -> homeomorphism f.
Proof.
intros.
destruct H as [g].
exists g; trivial.
red; intros.
assert (inverse_image g V = Im V f).
apply Extensionality_Ensembles; split; red; intros.
destruct H4.
exists (g x); trivial.
symmetry; apply H2.
destruct H4.
constructor.
rewrite H5.
rewrite H; trivial.
rewrite H4; apply H1; trivial.
Qed.
Inductive homeomorphic (X Y:TopologicalSpace) : Prop :=
| intro_homeomorphic: forall f:point_set X -> point_set Y,
homeomorphism f -> homeomorphic X Y.
Require Export Relation_Definitions.
Require Import Relation_Definitions_Implicit.
Lemma homeomorphic_equiv: equivalence homeomorphic.
Proof.
constructor.
red; intros X.
exists (fun x:point_set X => x).
exists (fun x:point_set X => x); trivial;
apply continuous_identity.
red; intros X Y Z ? ?.
destruct H as [f [finv]].
destruct H0 as [g [ginv]].
exists (fun x:point_set X => g (f x)).
exists (fun z:point_set Z => finv (ginv z)); (congruence ||
apply continuous_composition; trivial).
red; intros X Y ?.
destruct H as [f [finv]].
exists finv; exists f; trivial.
Qed.
| {
"alphanum_fraction": null,
"author": "dschepler",
"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/dschepler-coq-topology/coq-topology-462b0777da71e8b860fcd67879278e919b295266/Homeomorphisms.v",
"reason": null,
"repo": "coq-topology",
"save_path": "github-repos/coq/dschepler-coq-topology",
"sha": "462b0777da71e8b860fcd67879278e919b295266",
"size": null
} |
'''Analyse invariance'''
import os
import sys
import numpy as np
from scipy.ndimage import rotate
from skimage.io import imread, imsave
from matplotlib import pyplot as plt
folder_name = 'nate_5_'
im0 = imread('./nate_experiments/activations/{:s}/{:04d}.jpg'.format(folder_name,0))/255.
error = []
errorm = []
for i in xrange(360):
fname = './nate_experiments/activations/{:s}/{:04d}.jpg'.format(folder_name,i)
im = imread(fname)/255.
dev = np.sqrt((im - im0)**2 / (im0**2 + 1e-6))[82:401,82:401]
error.append(np.mean(dev))
dev= (im - im0)
imsave('./nate_experiments/dev/{:s}/{:04d}.jpg'.format(folder_name,i), dev)
plt.plot(error, 'b')
plt.xlabel('Input angle', fontsize=20)
plt.ylabel('Mean discepancy', fontsize=20)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.tight_layout()
plt.show()
'''
z = np.zeros((10,10))
z[2,2] = 1
z[1,1] = 1
z = rotate(z, 90, axes=(1,0), reshape=False, order=1)
print z
plt.imshow(z, vmin=0, vmax=1, interpolation='nearest')
plt.show()
''' | {
"alphanum_fraction": 0.6786427146,
"author": null,
"avg_line_length": 23.3023255814,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "0c5916fb1b8c2bf672bcf19b22de3b4d7095a7cd",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 48,
"max_forks_repo_forks_event_max_datetime": "2020-09-29T02:28:21.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-12-16T23:32:44.000Z",
"max_forks_repo_head_hexsha": "d695fc187d4850c84e1305bbd8bf54ec23f51a43",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "purelazy/harmonicConvolutions",
"max_forks_repo_path": "deprecated/nathan/analyse_invariance.py",
"max_issues_count": 14,
"max_issues_repo_head_hexsha": "d695fc187d4850c84e1305bbd8bf54ec23f51a43",
"max_issues_repo_issues_event_max_datetime": "2020-08-31T21:54:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-12-20T23:16:20.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "purelazy/harmonicConvolutions",
"max_issues_repo_path": "deprecated/nathan/analyse_invariance.py",
"max_line_length": 89,
"max_stars_count": 265,
"max_stars_repo_head_hexsha": "d695fc187d4850c84e1305bbd8bf54ec23f51a43",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "purelazy/harmonicConvolutions",
"max_stars_repo_path": "deprecated/nathan/analyse_invariance.py",
"max_stars_repo_stars_event_max_datetime": "2020-10-22T11:30:18.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-12-13T23:18:43.000Z",
"num_tokens": 327,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1002
} |
import numpy as np
import plotly.express as px
def dataset_Flower(m=10, noise=0.0):
# Inicializujeme matice
X = np.zeros((m, 2), dtype='float')
Y = np.zeros((m, 1), dtype='float')
a = 1.0
pi = 3.141592654
M = int(m/2)
for j in range(2):
ix = range(M*j, M*(j+1))
t = np.linspace(j*pi, (j+1)*pi, M) + np.random.randn(M)*noise
r = a*np.sin(4*t) + np.random.randn(M)*noise
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
Y[ix] = j
return X, Y
def MakeBatches(dataset, batchSize, shuffle:bool):
# Set obsahuje 2 mnoziny - X, Y
X, Y = dataset
# Zistime celkovy pocet vzoriek
m, nx = X.shape
_, ny = Y.shape
if shuffle:
idx = np.arange(len(X))
np.random.shuffle(idx)
X = X[idx]
Y = Y[idx]
# Vysledny zoznam
result = []
# Ak je batchSize = 0, berieme celu mnozinu
if (batchSize <= 0):
batchSize = m
# Celkovy pocet davok sa zaokruhluje nahor
steps = int(np.ceil(m / batchSize))
for i in range(steps):
# Spocitame hranice rezu
mStart = i * batchSize
mEnd = min(mStart + batchSize, m)
# Vyberame data pre aktualny rez - chceme dodrzat rank
minibatchX = X[mStart:mEnd, :]
minibatchY = Y[mStart:mEnd, :]
assert (len(minibatchX.shape) == 2)
assert (len(minibatchY.shape) == 2)
# Pridame novu dvojicu do vysledneho zoznamu
result.append((np.expand_dims(minibatchX, axis=-1), np.expand_dims(minibatchY, axis=-1)))
return result
def draw_dataset(x, y):
fig = px.scatter(x=x[0], y=x[1], color=y[0], width=700, height=700)
fig.show()
if __name__ == '__main__':
x,y = dataset_Flower(128)
draw_dataset(x.T, y.T)
dataset = MakeBatches((x,y),32)
for mini_batch in dataset:
print(mini_batch[0].shape)
| {
"alphanum_fraction": 0.5781584582,
"author": null,
"avg_line_length": 25.2432432432,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "ac3ac647a39f6f77adfe725f78f84af4487a6c79",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 8,
"max_forks_repo_forks_event_max_datetime": "2022-03-07T21:49:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-15T18:19:52.000Z",
"max_forks_repo_head_hexsha": "f94cc30a63f9d9cf0137bd07eb80a65aa3e533b4",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "filipagh/neural_networks_at_fiit_2022",
"max_forks_repo_path": "week_4/dataset.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f94cc30a63f9d9cf0137bd07eb80a65aa3e533b4",
"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": "filipagh/neural_networks_at_fiit_2022",
"max_issues_repo_path": "week_4/dataset.py",
"max_line_length": 97,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "f94cc30a63f9d9cf0137bd07eb80a65aa3e533b4",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "filipagh/neural_networks_at_fiit_2022",
"max_stars_repo_path": "week_4/dataset.py",
"max_stars_repo_stars_event_max_datetime": "2022-02-15T19:58:58.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-15T08:18:21.000Z",
"num_tokens": 619,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1868
} |
"""Unit test on utility for sampling/generating data on planar surfaces.
Authors: Ayush Baid, John Lambert
"""
import numpy as np
import gtsfm.utils.sampling as sampling_utils
def test_sample_points_on_plane() -> None:
"""Assert generated points are on a single 3d plane."""
num_points = 10
# range of x and y coordinates for 3D points
range_x = (-7, 7)
range_y = (-10, 10)
# define the plane equation
# plane at z=10, so ax + by + cz + d = 0 + 0 + -z + 10 = 0
plane_coefficients = (0, 0, -1, 10)
pts = sampling_utils.sample_points_on_plane(plane_coefficients, range_x, range_y, num_points)
# ensure ax + by + cz + d = 0
pts_residuals = pts @ np.array(plane_coefficients[:3]).reshape(3, 1) + plane_coefficients[3]
np.testing.assert_almost_equal(pts_residuals, np.zeros((num_points, 1)))
assert pts.shape == (10, 3)
| {
"alphanum_fraction": 0.6731207289,
"author": null,
"avg_line_length": 28.3225806452,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "6b462838223905019a73e6b20612716addfe81ed",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 13,
"max_forks_repo_forks_event_max_datetime": "2022-03-11T03:16:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-03-12T03:01:27.000Z",
"max_forks_repo_head_hexsha": "8d301eb3ef9172345a1ac1369fd4e19764d28946",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "swershrimpy/gtsfm",
"max_forks_repo_path": "tests/utils/test_sampling_utils.py",
"max_issues_count": 273,
"max_issues_repo_head_hexsha": "8d301eb3ef9172345a1ac1369fd4e19764d28946",
"max_issues_repo_issues_event_max_datetime": "2022-03-16T15:02:33.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-01-30T16:45:26.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "swershrimpy/gtsfm",
"max_issues_repo_path": "tests/utils/test_sampling_utils.py",
"max_line_length": 97,
"max_stars_count": 122,
"max_stars_repo_head_hexsha": "8d301eb3ef9172345a1ac1369fd4e19764d28946",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "swershrimpy/gtsfm",
"max_stars_repo_path": "tests/utils/test_sampling_utils.py",
"max_stars_repo_stars_event_max_datetime": "2022-03-30T13:10:35.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-02-07T23:01:58.000Z",
"num_tokens": 258,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 878
} |
# -*-coding:utf-8-*-
from tqdm import tqdm
import os
import numpy as np
from keras.preprocessing.image import img_to_array, load_img
class Fer2013(object):
def __init__(self):
"""
构造函数
"""
self.folder = '../data/fer2013'
def gen_train(self):
"""
产生训练数据
:return expressions:读取文件的顺序即标签的下标对应
:return x_train: 训练数据集
:return y_train: 训练标签
"""
folder = os.path.join(self.folder, 'Training')
# 这里原来是list出多个表情类别的文件夹,后来发现服务器linux顺序不一致,会造成问题,所以固定读取顺序
expressions = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral', 'contempt']
x_train = []
y_train = []
for i in tqdm(range(len(expressions))):
if expressions[i] == 'contempt':
continue
expression_folder = os.path.join(folder, expressions[i])
images = os.listdir(expression_folder)
for j in range(len(images)):
img = load_img(os.path.join(expression_folder, images[j]), target_size=(48, 48), color_mode="grayscale")
img = img_to_array(img) # 灰度化
x_train.append(img)
y_train.append(i)
x_train = np.array(x_train).astype('float32') / 255.
y_train = np.array(y_train).astype('int')
return expressions, x_train, y_train
def gen_train_no(self):
"""
产生训练数据
:return expressions:读取文件的顺序即标签的下标对应
:return x_train: 训练数据集
:return y_train: 训练标签
"""
folder = os.path.join(self.folder, 'Training')
# 这里原来是list出多个表情类别的文件夹,后来发现服务器linux顺序不一致,会造成问题,所以固定读取顺序
expressions = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral', 'contempt']
x_train = []
y_train = []
import cv2
for i in tqdm(range(len(expressions))):
if expressions[i] == 'contempt':
continue
expression_folder = os.path.join(folder, expressions[i])
images = os.listdir(expression_folder)
for j in range(len(images)):
img = cv2.imread(os.path.join(expression_folder, images[j]), cv2.IMREAD_GRAYSCALE)
x_train.append(img)
y_train.append(i)
x_train = np.array(x_train)
y_train = np.array(y_train).astype('int')
return expressions, x_train, y_train
def gen_valid(self):
"""
产生验证集数据
:return:
"""
folder = os.path.join(self.folder, 'PublicTest')
expressions = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral', 'contempt']
x_valid = []
y_valid = []
for i in tqdm(range(len(expressions))):
if expressions[i] == 'contempt':
continue
expression_folder = os.path.join(folder, expressions[i])
images = os.listdir(expression_folder)
for j in range(len(images)):
img = load_img(os.path.join(expression_folder, images[j]), target_size=(48, 48), color_mode="grayscale")
img = img_to_array(img) # 灰度化
x_valid.append(img)
y_valid.append(i)
x_valid = np.array(x_valid).astype('float32') / 255.
y_valid = np.array(y_valid).astype('int')
return expressions, x_valid, y_valid
def gen_valid_no(self):
"""
产生验证数据
:return expressions:读取文件的顺序即标签的下标对应
:return x_train: 训练数据集
:return y_train: 训练标签
"""
folder = os.path.join(self.folder, 'PublicTest')
# 这里原来是list出多个表情类别的文件夹,后来发现服务器linux顺序不一致,会造成问题,所以固定读取顺序
expressions = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral', 'contempt']
x_train = []
y_train = []
import cv2
for i in tqdm(range(len(expressions))):
if expressions[i] == 'contempt':
continue
expression_folder = os.path.join(folder, expressions[i])
images = os.listdir(expression_folder)
for j in range(len(images)):
img = cv2.imread(os.path.join(expression_folder, images[j]), cv2.IMREAD_GRAYSCALE)
x_train.append(img)
y_train.append(i)
x_train = np.array(x_train)
y_train = np.array(y_train).astype('int')
return expressions, x_train, y_train
def gen_test(self):
"""
产生验证集数据
:return:
"""
folder = os.path.join(self.folder, 'PrivateTest')
expressions = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral', 'contempt']
x_test = []
y_test = []
for i in tqdm(range(len(expressions))):
if expressions[i] == 'contempt':
continue
expression_folder = os.path.join(folder, expressions[i])
images = os.listdir(expression_folder)
for j in range(len(images)):
img = load_img(os.path.join(expression_folder, images[j]), target_size=(48, 48), color_mode="grayscale")
img = img_to_array(img) # 灰度化
x_test.append(img)
y_test.append(i)
x_test = np.array(x_test).astype('float32') / 255.
y_test = np.array(y_test).astype('int')
return expressions, x_test, y_test
def gen_test_no(self):
"""
产生验证数据
:return expressions:读取文件的顺序即标签的下标对应
:return x_train: 训练数据集
:return y_train: 训练标签
"""
folder = os.path.join(self.folder, 'PrivateTest')
# 这里原来是list出多个表情类别的文件夹,后来发现服务器linux顺序不一致,会造成问题,所以固定读取顺序
expressions = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral', 'contempt']
x_train = []
y_train = []
import cv2
for i in tqdm(range(len(expressions))):
if expressions[i] == 'contempt':
continue
expression_folder = os.path.join(folder, expressions[i])
images = os.listdir(expression_folder)
for j in range(len(images)):
img = cv2.imread(os.path.join(expression_folder, images[j]), cv2.IMREAD_GRAYSCALE)
x_train.append(img)
y_train.append(i)
x_train = np.array(x_train)
y_train = np.array(y_train).astype('int')
return expressions, x_train, y_train
class Jaffe(object):
"""
Jaffe没有测试数据,需要自己划分
"""
def __init__(self):
self.folder = '../data/jaffe'
def gen_train(self):
"""
产生训练数据
注意产生的是(213, 48, 48, 1)和(213, )的x和y,如果输入灰度图需要将x的最后一维squeeze掉
:return:
"""
folder = os.path.join(self.folder, 'Training')
expressions = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral', 'contempt']
x_train = []
y_train = []
for i in tqdm(range(len(expressions))):
if expressions[i] == 'contempt':
continue
expression_folder = os.path.join(folder, expressions[i])
images = os.listdir(expression_folder)
for j in range(len(images)):
img = load_img(os.path.join(expression_folder, images[j]), target_size=(48, 48), color_mode="grayscale")
img = img_to_array(img) # 灰度化
x_train.append(img)
y_train.append(i)
x_train = np.array(x_train).astype('float32') / 255.
y_train = np.array(y_train).astype('int')
return expressions, x_train, y_train
def gen_train_no(self):
"""
产生训练数据
:return:
"""
import cv2
folder = os.path.join(self.folder, 'Training')
expressions = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral', 'contempt']
x_train = []
y_train = []
for i in tqdm(range(len(expressions))):
if expressions[i] == 'contempt':
continue
expression_folder = os.path.join(folder, expressions[i])
images = os.listdir(expression_folder)
for j in range(len(images)):
img = cv2.imread(os.path.join(expression_folder, images[j]), cv2.IMREAD_GRAYSCALE)
x_train.append(img)
y_train.append(i)
x_train = np.array(x_train)
y_train = np.array(y_train).astype('int')
return expressions, x_train, y_train
def gen_data(self):
"""
生成划分后的数据集,实际使用需要交叉验证
:return:
"""
_, x, y = self.gen_train()
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2019)
return x_train, x_test, y_train, y_test
class CK(object):
"""
CK+没有测试数据,需要自己划分
"""
def __init__(self):
self.folder = '../data/ck+'
def gen_train(self):
"""
产生训练数据
:return:
"""
folder = self.folder
# 为了模型训练统一,这里加入neural
expressions = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral', 'contempt']
x_train = []
y_train = []
for i in tqdm(range(len(expressions))):
if expressions[i] == 'neutral':
# 没有中性表情,直接跳过
continue
expression_folder = os.path.join(folder, expressions[i])
images = os.listdir(expression_folder)
for j in range(len(images)):
img = load_img(os.path.join(expression_folder, images[j]), target_size=(48, 48), color_mode="grayscale")
img = img_to_array(img) # 灰度化
x_train.append(img)
y_train.append(i)
x_train = np.array(x_train).astype('float32') / 255.
y_train = np.array(y_train).astype('int')
return expressions, x_train, y_train
def gen_train_no(self):
"""
产生训练数据
:return:
"""
import cv2
folder = self.folder
# 为了模型训练统一,这里加入neural
expressions = ['anger', 'disgust', 'fear', 'happy', 'sad', 'surprised', 'neutral', 'contempt']
x_train = []
y_train = []
for i in tqdm(range(len(expressions))):
if expressions[i] == 'neutral':
# 没有中性表情,直接跳过
continue
expression_folder = os.path.join(folder, expressions[i])
images = os.listdir(expression_folder)
for j in range(len(images)):
img = cv2.imread(os.path.join(expression_folder, images[j]), cv2.IMREAD_GRAYSCALE)
x_train.append(img)
y_train.append(i)
x_train = np.array(x_train)
y_train = np.array(y_train).astype('int')
return expressions, x_train, y_train
def gen_data(self):
"""
生成划分后的数据集,实际使用需要交叉验证
:return:
"""
_, x, y = self.gen_train()
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=2019)
return x_train, x_test, y_train, y_test
| {
"alphanum_fraction": 0.5583655837,
"author": null,
"avg_line_length": 37.2852348993,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "21e649dbaad280d205377b061c0c56abab36afbb",
"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": "98d972c42ae9cc0ba1b1e9c1f6cc7b8e0cb43321",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "littlegreedy/AI_Kindergarten",
"max_forks_repo_path": "AI_Projects/src/data.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "98d972c42ae9cc0ba1b1e9c1f6cc7b8e0cb43321",
"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": "littlegreedy/AI_Kindergarten",
"max_issues_repo_path": "AI_Projects/src/data.py",
"max_line_length": 120,
"max_stars_count": 19,
"max_stars_repo_head_hexsha": "98d972c42ae9cc0ba1b1e9c1f6cc7b8e0cb43321",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "littlegreedy/AI_Kindergarten",
"max_stars_repo_path": "AI_Projects/src/data.py",
"max_stars_repo_stars_event_max_datetime": "2022-01-12T05:53:36.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-20T02:54:35.000Z",
"num_tokens": 2975,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 11111
} |
[STATEMENT]
lemma has_integral_neg: "(f has_integral k) S \<Longrightarrow> ((\<lambda>x. -(f x)) has_integral -k) S"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. (f has_integral k) S \<Longrightarrow> ((\<lambda>x. - f x) has_integral - k) S
[PROOF STEP]
by (drule_tac c="-1" in has_integral_cmul) 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": 130,
"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 -*-
import numpy as np
from evaluators.quadratic_weighted_kappa import quadratic_weighted_kappa as qwk
from evaluators.quadratic_weighted_kappa import linear_weighted_kappa as lwk
def assert_inputs(rater_a, rater_b):
assert np.issubdtype(rater_a.dtype, np.integer), 'Integer array expected, got ' + str(rater_a.dtype)
assert np.issubdtype(rater_b.dtype, np.integer), 'Integer array expected, got ' + str(rater_b.dtype)
def quadratic_weighted_kappa(rater_a, rater_b, min_rating, max_rating):
assert_inputs(rater_a, rater_b)
return qwk(rater_a, rater_b, min_rating, max_rating)
def linear_weighted_kappa(rater_a, rater_b, min_rating, max_rating):
assert_inputs(rater_a, rater_b)
return lwk(rater_a, rater_b, min_rating, max_rating)
| {
"alphanum_fraction": 0.8039473684,
"author": null,
"avg_line_length": 42.2222222222,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "d5a7cfdefd1538705023cd3d4dbddcf5192c65fa",
"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": "010aee9b4869c32472ec821f52ce6c9914410a2e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "tushar117/counter-neural-essay-length-copy",
"max_forks_repo_path": "evaluators/my_kappa_calculator.py",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "010aee9b4869c32472ec821f52ce6c9914410a2e",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T15:11:31.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-11-12T06:00:31.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "tushar117/counter-neural-essay-length-copy",
"max_issues_repo_path": "evaluators/my_kappa_calculator.py",
"max_line_length": 101,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "010aee9b4869c32472ec821f52ce6c9914410a2e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "tushar117/counter-neural-essay-length-copy",
"max_stars_repo_path": "evaluators/my_kappa_calculator.py",
"max_stars_repo_stars_event_max_datetime": "2022-01-03T14:22:25.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-13T02:20:42.000Z",
"num_tokens": 212,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 760
} |
import numpy as np
import pickle
def indexVBO(in_vertices,in_uvs,in_normals):
VertexToOutIndex = {}
out_vertices,out_uvs,out_normals,out_indices = [],[],[],[]
# For each input vertex
for i in range(len(in_vertices)):
packed = pickle.dumps([in_vertices[i], in_uvs[i], in_normals[i]])
# Try to find a similar vertex in out_XXXX
if packed in VertexToOutIndex.keys():
# A similar vertex is already in the VBO, use it instead !
out_indices.append( VertexToOutIndex[packed] )
else:
# If not, it needs to be added in the output data.
out_vertices.append( in_vertices[i] )
out_uvs .append( in_uvs[i] )
out_normals .append( in_normals[i] )
newindex = np.uint16( len(out_vertices) - 1 )
out_indices .append( newindex )
VertexToOutIndex[ packed ] = newindex
return np.array(out_indices),np.array(out_vertices),np.array(out_uvs),np.array(out_normals)
| {
"alphanum_fraction": 0.6275862069,
"author": null,
"avg_line_length": 33.8333333333,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "7f7348cd8e7e9650a11d975b50e465f4640cc4e7",
"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": "705aa9c4cb64df0b4b2b4357cfc5131ade28aa92",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "ascendingnode/opengltutorialspython",
"max_forks_repo_path": "vboindexer.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "705aa9c4cb64df0b4b2b4357cfc5131ade28aa92",
"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": "ascendingnode/opengltutorialspython",
"max_issues_repo_path": "vboindexer.py",
"max_line_length": 96,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "705aa9c4cb64df0b4b2b4357cfc5131ade28aa92",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "ascendingnode/opengltutorialspython",
"max_stars_repo_path": "vboindexer.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 251,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1015
} |
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec
import scipy.special as special
inch_fig = 3
f, axs = plt.subplots(nrows=1, ncols=7, figsize=(7*inch_fig, inch_fig), subplot_kw={'projection':'3d'})
plt.subplots_adjust(wspace=-0.7)
kappas = [0.1, 0.5, 1.0, 2.0, 3.0, 5.0, 7.0]
for ax, kappa in zip(axs, kappas):
ax.set_aspect("equal")
phi, theta = np.mgrid[0:2*np.pi:20j, 0:np.pi:30j]
norm = np.sqrt(kappa)/(((2*np.pi)**(1.5))*special.iv(0.5, kappa))
weight = np.exp(kappa*np.cos(theta))
x = norm*weight*np.cos(phi)*np.sin(theta)
y = norm*weight*np.sin(phi)*np.sin(theta)
z = norm*weight*np.cos(theta)
ax.plot_wireframe(x, y, z - 0.7, color="k", lw=0.1)
ax.set_xlim(-0.9, 0.9)
ax.set_ylim(-0.9, 0.9)
ax.set_zlim(-0.9, 0.9)
ax.set_axis_off()
ax.azim = 0
ax.elev = 30
ax.set_title('$\kappa = '+str(kappa)+'$', y=0.9, fontsize=20)
f.savefig('vonmises.pdf')
| {
"alphanum_fraction": 0.6368159204,
"author": null,
"avg_line_length": 33.5,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "a5f841b7c22ad082270e65784fcc6db1f8d4dcee",
"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": "04904871924276fd1662ca15b7224166d271c0d8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "talonchandler/dipsim",
"max_forks_repo_path": "notes/2017-09-19-ensemble-efficiencies/figures/vonmises.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "04904871924276fd1662ca15b7224166d271c0d8",
"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": "talonchandler/dipsim",
"max_issues_repo_path": "notes/2017-09-19-ensemble-efficiencies/figures/vonmises.py",
"max_line_length": 103,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "04904871924276fd1662ca15b7224166d271c0d8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "talonchandler/dipsim",
"max_stars_repo_path": "notes/2017-09-19-ensemble-efficiencies/figures/vonmises.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 377,
"path": null,
"reason": "import numpy,import scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1005
} |
from .dlm import dlm
from .lego import join
from .param import uni as param_uni
from scipy.linalg import block_diag
from scipy.stats import t as t_dist
from scipy.stats import norm
import numpy as np
from numpy.linalg import inv
def is_pos_def(x):
return np.all(np.linalg.eigvals(x) > 0)
class dlm_uni(dlm):
def __init__(self, F, G, V=None, W=None, discount=None):
if discount is not None:
if type(discount) in [int, float]:
assert 0 < discount <= 1, "discount needs to be in unit interval"
self.discount = discount
self.F = F
self.G = G
self.V = V
p = G.shape[0]
self.p = p
if W is None and discount is None:
self.W = np.zeros( (p,p) )
elif W is not None:
self.W = W
elif discount is not None:
self.W = np.zeros( (p,p) ) + np.nan
self.__dimension__ = p
self.__num_components__ = 1
def __add__(self, other):
assert (self.V is None) - (other.V is None) == 0, "Both dlm's must either have known V or unknown V."
F = np.concatenate( (self.F, other.F) )
G = block_diag(self.G, other.G)
V = None if self.V is None else self.V + other.V
W = block_diag(self.W, other.W)
discount = join(self.discount, other.discount)
new_dlm = dlm_uni(F=F, G=G, V=V, W=W, discount=discount)
new_dlm.__dimension__ = join(self.__dimension__, other.__dimension__)
new_dlm.__num_components__ = self.__num_components__ + other.__num_components__
return new_dlm
def __str__(self):
return "F:\n" + self.F.__str__() + "\n\n" + \
"G:\n" + self.G.__str__() + "\n\n" + \
"V:\n" + self.V.__str__() + "\n\n" + \
"W:\n" + self.W.__str__() + "\n\n" + \
"discount:\n" + self.discount.__str__() + "\n\n" + \
"num components:\n" + self.__num_components__.__str__() + "\n\n" + \
"dimension:\n" + self.__dimension__.__str__()
def __get_block__(self, M, i):
cum_dim = np.insert(np.cumsum(self.__dimension__), 0, 0)
dim_lower = cum_dim[:-1]
dim_upper = cum_dim[1:]
return M[dim_lower[i]:dim_upper[i],
dim_lower[i]:dim_upper[i]]
def __compute_W__(self, prev_C):
W_list = [None] * self.__num_components__
d = self.discount if self.__num_components__ > 1 else [self.discount]
### See Section 6.3.2 (Component discounting) of W&H.
for i in range(self.__num_components__):
Gi = self.__get_block__(self.G, i)
prev_Ci = self.__get_block__(prev_C, i)
if d[i] is None:
W_list[i] = self.__get_block__(self.W, i)
else:
W_list[i] = (1-d[i]) / d[i] * Gi * prev_Ci * Gi.T
return reduce(lambda a,b: block_diag(a,b), W_list, np.eye(0))
def onlineUpdate(self, y, prev):
G = self.G
Gt = G.T
Ft = np.asmatrix(self.F)
F = Ft.T
if self.V is not None:
init.S = self.V
n = prev.n + 1
W = self.__compute_W__(prev.C)
a = G * prev.m
R = G * prev.C * Gt + W
f = np.asscalar(Ft * a)
Q = np.asscalar(Ft * R * F) + prev.S
e = y - f
S = (prev.S + prev.S / n * (e*e / Q - 1)) if self.V is None else self.V
A = R * F / Q
m = a + A*e
C = ((S / prev.S) if self.V is None else 1)* (R - A*A.T * Q)
assert Q >= 0, "Q cannot be negative!"
return param_uni(m=m,C=C,a=a,R=R,f=f,Q=Q,n=n,S=S)
def filter(self, y, init):
N = len(y)
out = [init]*N
G = self.G
Gt = G.T
Ft = np.asmatrix(self.F)
F = Ft.T
if self.V is not None:
init.S = self.V
for i in xrange(N):
prev = out[i-1] if i > 0 else init
n = prev.n + 1
W = self.__compute_W__(prev.C)
a = G * prev.m
R = G * prev.C * Gt + W
f = np.asscalar(Ft * a)
Q = np.asscalar(Ft * R * F) + prev.S
e = y[i] - f
S = (prev.S + prev.S / n * (e*e / Q - 1)) if self.V is None else self.V
A = R * F / Q
m = a + A*e
C = ((S / prev.S) if self.V is None else 1)* (R - A*A.T * Q)
if Q < 0:
print "i:"
print i
print "W:"
print W
print "R:"
print R
print "S_prev:"
print prev.S
print "S:"
print S
print "Q:"
print Q
print "C:"
print C
print "discount:"
print self.discount
assert Q >= 0, "Q cannot be negative!"
out[i] = param_uni(m=m,C=C,a=a,R=R,f=f,Q=Q,n=n,S=S)
return out
def forecast(self, filt, nAhead=1, linear_decay=False):
last_param = filt[-1]
init = (last_param.m, last_param.C,
last_param.f, last_param.Q)
G = self.G
Gt = G.T
Ft = np.asmatrix(self.F)
F = Ft.T
W = self.__compute_W__(last_param.C)
out = [None] * nAhead
# TODO: Try Corollary 4.1, 4.2 of W&H
for i in xrange(nAhead):
prev = out[i-1] if i > 0 else init
(prev_a, prev_R, prev_f, prev_Q) = prev
a = G * prev_a
# See W&H 6.3.3 (Practical discounting strategy for k-step ahead forecasts)
if not linear_decay:
# Exponential decay of information
W = self.__compute_W__(prev_R)
R = G * prev_R * Gt + W
f = Ft * a
Q = Ft * R * F + last_param.S
out[i] = (a, R, f, Q)
out_f = map(lambda x: np.asscalar(x[2]), out)
out_Q = map(lambda x: np.asscalar(x[3]), out)
return {'f': out_f, 'Q': out_Q, 'n': last_param.n}
def get_ci(self, f, Q, n, alpha=.05):
assert len(f) == len(Q), "required: len(f) == len(Q)"
len_f = len(f)
lower = [None] * len_f
upper = [None] * len_f
num_std = norm.ppf(1 - alpha/2)
for i in range(len_f):
if self.V is None:
num_std = t_dist(df=n[i]-1).ppf(1 - alpha/2)
lower[i] = f[i] - np.sqrt(Q[i]) * num_std
upper[i] = f[i] + np.sqrt(Q[i]) * num_std
return {'lower': lower, 'upper': upper}
def draw_forecast(self, f, Q, n, num_draws):
"""
f: forecast mean parameter (float)
Q: forecast squared scale parameter (float)
n: number of samples trained from so far (int)
num_draws: number of draws (int)
"""
if self.V is None:
return t_dist(df=n-1).rvs(num_draws) * np.sqrt(Q) + f
else:
return np.random.randn(num_draws) * np.sqrt(Q) + f
# TODO:
def ffbs(self, y, init):
"""
ffbs (Forward filtering Backwards Sampling)
"""
assert self.V is not None, "ffbs can only be used for conditionally Normal models!"
filt = self.filter(y, init)
p = self.p
N = len(y)
theta = np.zeros((N, p))
for t in reversed( xrange(N) ):
if t == N-1:
ht = np.asarray(filt[t].m).flatten()
Ht = filt[t].C
theta[t,:] = np.random.multivariate_normal(ht, Ht)
else:
Ct = filt[t].C
Gt_next = self.G
Rt_next = filt[t+1].R
Bt = Ct * Gt_next.T * inv(Rt_next)
at_next = filt[t+1].a
ht = np.asarray(filt[t].m + Bt * Rt_next * (np.asmatrix(theta[t+1, :]).T - at_next)).flatten()
Ht = Ct - Bt * Rt_next * Bt.T
theta[t, :] = np.random.multivariate_normal(ht, Ht)
return theta
| {
"alphanum_fraction": 0.4872082865,
"author": null,
"avg_line_length": 31.5472440945,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "520a5e674955db8c23d18ecead9e80ed482db53f",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-09-01T19:52:48.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-09-01T19:52:48.000Z",
"max_forks_repo_head_hexsha": "c3d6328b1260c795759637cd8d26d3f79febd950",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "luiarthur/dlmPython",
"max_forks_repo_path": "dlmPython/dlm_uni.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c3d6328b1260c795759637cd8d26d3f79febd950",
"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": "luiarthur/dlmPython",
"max_issues_repo_path": "dlmPython/dlm_uni.py",
"max_line_length": 110,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "c3d6328b1260c795759637cd8d26d3f79febd950",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "luiarthur/dlmPython",
"max_stars_repo_path": "dlmPython/dlm_uni.py",
"max_stars_repo_stars_event_max_datetime": "2019-09-01T19:52:46.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-11-25T15:00:48.000Z",
"num_tokens": 2285,
"path": null,
"reason": "import numpy,from numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 8013
} |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for the experimental input pipeline ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numpy as np
from tensorflow.contrib.data.python.kernel_tests import dataset_serialization_test_base
from tensorflow.contrib.data.python.ops import dataset_ops as contrib_dataset_ops
from tensorflow.contrib.data.python.ops import shuffle_ops
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.data.ops import iterator_ops
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import test
class ShuffleDatasetTest(test.TestCase):
def testShuffleDataset(self):
components = (
np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]),
np.array([9.0, 10.0, 11.0, 12.0])
)
count_placeholder = array_ops.placeholder_with_default(
constant_op.constant(5, dtypes.int64), shape=[])
buffer_size_placeholder = array_ops.placeholder(dtypes.int64, shape=[])
seed_placeholder = array_ops.placeholder(dtypes.int64, shape=[])
repeat_dataset = (
contrib_dataset_ops.Dataset.from_tensor_slices(components)
.repeat(count_placeholder))
shuffle_dataset = repeat_dataset.shuffle(buffer_size_placeholder,
seed_placeholder)
self.assertEqual(tuple([c.shape[1:] for c in components]),
shuffle_dataset.output_shapes)
# Create initialization ops for iterators without and with
# shuffling, respectively.
iterator = iterator_ops.Iterator.from_structure(
shuffle_dataset.output_types, shuffle_dataset.output_shapes)
init_fifo_op = iterator.make_initializer(repeat_dataset)
init_shuffle_op = iterator.make_initializer(shuffle_dataset)
get_next = iterator.get_next()
with self.test_session() as sess:
# First run without shuffling to collect the "ground truth".
sess.run(init_fifo_op)
unshuffled_elements = []
for _ in range(20):
unshuffled_elements.append(sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
# Assert that the shuffled dataset has the same elements as the
# "ground truth".
sess.run(
init_shuffle_op,
feed_dict={buffer_size_placeholder: 100,
seed_placeholder: 37})
shuffled_elements = []
for _ in range(20):
shuffled_elements.append(sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
self.assertAllEqual(
sorted(unshuffled_elements), sorted(shuffled_elements))
# Assert that shuffling twice with the same seeds gives the same sequence.
sess.run(
init_shuffle_op,
feed_dict={buffer_size_placeholder: 100,
seed_placeholder: 37})
reshuffled_elements_same_seed = []
for _ in range(20):
reshuffled_elements_same_seed.append(sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
self.assertEqual(shuffled_elements, reshuffled_elements_same_seed)
# Assert that shuffling twice with a different seed gives a different
# permutation of the same elements.
sess.run(
init_shuffle_op,
feed_dict={buffer_size_placeholder: 100,
seed_placeholder: 1037})
reshuffled_elements_different_seed = []
for _ in range(20):
reshuffled_elements_different_seed.append(sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
self.assertNotEqual(shuffled_elements, reshuffled_elements_different_seed)
self.assertAllEqual(
sorted(shuffled_elements), sorted(reshuffled_elements_different_seed))
# Assert that the shuffled dataset has the same elements as the
# "ground truth" when the buffer size is smaller than the input
# dataset.
sess.run(
init_shuffle_op,
feed_dict={buffer_size_placeholder: 2,
seed_placeholder: 37})
reshuffled_elements_small_buffer = []
for _ in range(20):
reshuffled_elements_small_buffer.append(sess.run(get_next))
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
self.assertAllEqual(
sorted(unshuffled_elements), sorted(reshuffled_elements_small_buffer))
# Test the case of shuffling an empty dataset.
sess.run(init_shuffle_op, feed_dict={buffer_size_placeholder: 2,
seed_placeholder: 37,
count_placeholder: 0})
with self.assertRaises(errors.OutOfRangeError):
sess.run(get_next)
def testDefaultArguments(self):
components = [0, 1, 2, 3, 4]
iterator = (
contrib_dataset_ops.Dataset.from_tensor_slices(components).shuffle(5)
.repeat().make_one_shot_iterator())
get_next = iterator.get_next()
with self.test_session() as sess:
counts = collections.defaultdict(lambda: 0)
for _ in range(10):
for _ in range(5):
counts[sess.run(get_next)] += 1
for i in range(5):
self.assertEqual(10, counts[i])
class ShuffleDatasetSerializationTest(
dataset_serialization_test_base.DatasetSerializationTestBase):
def _build_shuffle_dataset(
self,
range_limit=10,
num_repeats=5,
buffer_size=5,
seed=None,
reshuffle_each_iteration=None,
):
return dataset_ops.Dataset.range(range_limit).shuffle(
buffer_size,
seed=seed,
reshuffle_each_iteration=reshuffle_each_iteration).repeat(num_repeats)
def testShuffleCore(self):
seed = 55
range_limit = 10
num_repeats = 5
num_outputs = range_limit * num_repeats
buffer_sizes = [1, 3, 8, 10, 25, 50]
reshuffle_each_iteration = False
# pylint: disable=cell-var-from-loop
# pylint: disable=g-long-lambda
for buffer_size in buffer_sizes:
self.run_core_tests(
lambda: self._build_shuffle_dataset(
range_limit=range_limit,
num_repeats=num_repeats,
buffer_size=buffer_size,
seed=seed,
reshuffle_each_iteration=reshuffle_each_iteration),
lambda: self._build_shuffle_dataset(
range_limit=range_limit,
num_repeats=num_repeats,
buffer_size=buffer_size,
seed=10,
reshuffle_each_iteration=reshuffle_each_iteration),
num_outputs)
# pylint: enable=cell-var-from-loop
# pylint: enable=g-long-lambda
class ShuffleAndRepeatTest(
dataset_serialization_test_base.DatasetSerializationTestBase):
def _build_ds(self, seed, count=5, num_elements=20):
return dataset_ops.Dataset.range(num_elements).apply(
shuffle_ops.shuffle_and_repeat(buffer_size=5, count=count, seed=seed))
def testCorrectOutput(self):
output = self.gen_outputs(lambda: self._build_ds(10), [], 100)
self.assertSequenceEqual(
sorted(output), sorted(
np.array([range(20) for _ in range(5)]).flatten()))
for i in range(5):
self.assertSequenceEqual(sorted(output[i * 20:(i + 1) * 20]), range(20))
def testReshuffling(self):
# Check that the output orders of different epochs are indeed different.
output = self.gen_outputs(lambda: self._build_ds(10), [], 100)
for i in range(4):
epoch1 = output[i * 20:(i + 1) * 20]
epoch2 = output[(i + 1) * 20:(i + 2) * 20]
self.assertNotEqual(epoch1, epoch2)
def testSameOrderForSameSeeds(self):
output1 = self.gen_outputs(lambda: self._build_ds(10), [], 100)
output2 = self.gen_outputs(lambda: self._build_ds(10), [], 100)
self.assertEqual(output1, output2)
def testDifferentOrderForDifferentSeeds(self):
output1 = self.gen_outputs(lambda: self._build_ds(10), [], 100)
output2 = self.gen_outputs(lambda: self._build_ds(20), [], 100)
self.assertNotEqual(output1, output2)
self.assertEqual(sorted(output1), sorted(output2))
def testCountNone(self):
output1 = self.gen_outputs(
lambda: self._build_ds(10, count=None), [], 100, verify_exhausted=False)
output2 = self.gen_outputs(
lambda: self._build_ds(20, count=None), [], 100, verify_exhausted=False)
self.assertNotEqual(output1, output2)
self.assertEqual(sorted(output1), sorted(output2))
def testCountMinusOne(self):
output1 = self.gen_outputs(
lambda: self._build_ds(10, count=-1), [], 100, verify_exhausted=False)
output2 = self.gen_outputs(
lambda: self._build_ds(20, count=-1), [], 100, verify_exhausted=False)
self.assertNotEqual(output1, output2)
self.assertEqual(sorted(output1), sorted(output2))
def testInfiniteOutputs(self):
# Asserting the iterator is exhausted after producing 100 items should fail.
with self.assertRaises(AssertionError):
self.gen_outputs(lambda: self._build_ds(10, count=None), [], 100)
with self.assertRaises(AssertionError):
self.gen_outputs(lambda: self._build_ds(10, count=-1), [], 100)
def testInfiniteEmpty(self):
with self.assertRaises(errors.OutOfRangeError):
self.gen_outputs(lambda: self._build_ds(10, count=None, num_elements=0),
[], 100)
with self.assertRaises(errors.OutOfRangeError):
self.gen_outputs(lambda: self._build_ds(10, count=-1, num_elements=0), [],
100)
class ShuffleAndRepeatSerializationTest(
dataset_serialization_test_base.DatasetSerializationTestBase):
def _build_ds(self, seed):
return dataset_ops.Dataset.range(20).apply(
shuffle_ops.shuffle_and_repeat(buffer_size=5, count=5, seed=seed))
def testCore(self):
self.run_core_tests(lambda: self._build_ds(10), lambda: self._build_ds(20),
100)
if __name__ == "__main__":
test.main()
| {
"alphanum_fraction": 0.6866002215,
"author": null,
"avg_line_length": 38.4255319149,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "918bcb0952bb6e80a9049d62c02ea6700f31b3a9",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 3,
"max_forks_repo_forks_event_max_datetime": "2018-05-07T19:14:34.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-01-20T06:47:34.000Z",
"max_forks_repo_head_hexsha": "f5de234d7f601214443f371e90fbadc8f128bb9a",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "worldveil/tensorflow",
"max_forks_repo_path": "tensorflow/contrib/data/python/kernel_tests/shuffle_dataset_op_test.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f5de234d7f601214443f371e90fbadc8f128bb9a",
"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": "worldveil/tensorflow",
"max_issues_repo_path": "tensorflow/contrib/data/python/kernel_tests/shuffle_dataset_op_test.py",
"max_line_length": 87,
"max_stars_count": 22,
"max_stars_repo_head_hexsha": "98d20962172301385aae694141801a375debd2bc",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "jhabikal21/tensorflow",
"max_stars_repo_path": "tensorflow/contrib/data/python/kernel_tests/shuffle_dataset_op_test.py",
"max_stars_repo_stars_event_max_datetime": "2018-07-05T01:00:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-01-13T14:52:47.000Z",
"num_tokens": 2389,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 10836
} |
# Test osqp python module
import osqp
from osqp import constant, default_algebra
# import osqppurepy as osqp
import numpy as np
from scipy import sparse
# Unit Test
import unittest
import pytest
import numpy.testing as nptest
class non_convex_tests(unittest.TestCase):
def setUp(self):
# Simple QP problem
self.P = sparse.triu([[2., 5.], [5., 1.]], format='csc')
self.q = np.array([3, 4])
self.A = sparse.csc_matrix([[-1.0, 0.], [0., -1.],
[-1., 3.], [2., 5.], [3., 4]])
self.u = np.array([0., 0., -15, 100, 80])
self.l = -np.inf * np.ones(len(self.u))
self.model = osqp.OSQP()
@pytest.mark.skipif(default_algebra() not in ('legacy', 'default'), reason='Only applicable for legacy/default algebra')
def test_non_convex_small_sigma(self):
opts = {'verbose': False, 'sigma': 1e-6}
try:
# Setup should fail due to (P + sigma I) having a negative
# eigenvalue
test_setup = 1
self.model.setup(P=self.P, q=self.q, A=self.A,
l=self.l, u=self.u, **opts)
except ValueError:
test_setup = 0
# Assert test_setup flag
self.assertEqual(test_setup, 0)
def test_non_convex_big_sigma(self):
# Setup workspace with new sigma
opts = {'verbose': False, 'sigma': 5}
self.model.setup(P=self.P, q=self.q, A=self.A,
l=self.l, u=self.u, **opts)
# Solve problem
res = self.model.solve()
# Assert close
self.assertEqual(res.info.status_val, constant('OSQP_NON_CVX'))
nptest.assert_approx_equal(res.info.obj_val, np.nan)
def test_nan(self):
nptest.assert_approx_equal(constant('OSQP_NAN'), np.nan)
| {
"alphanum_fraction": 0.5755909841,
"author": null,
"avg_line_length": 31.9122807018,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "6f2dcc0895c468d608e01b4c75e972a0baf2bb86",
"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": "f456e830df84a3dc7ee13a11b9c8df2e59df40be",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "vineetbansal/osqp_cuda",
"max_forks_repo_path": "src/osqp/tests/non_convex_test.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f456e830df84a3dc7ee13a11b9c8df2e59df40be",
"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": "vineetbansal/osqp_cuda",
"max_issues_repo_path": "src/osqp/tests/non_convex_test.py",
"max_line_length": 124,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f456e830df84a3dc7ee13a11b9c8df2e59df40be",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "vineetbansal/osqp_cuda",
"max_stars_repo_path": "src/osqp/tests/non_convex_test.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 479,
"path": null,
"reason": "import numpy,from scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1819
} |
from skimage import io
import numpy as np
import timeit
def Derivatives(order,F,begin_timer):
deriv_axis = []
dF = np.zeros(F.shape)
First_Derivative_Check = 0
for derivatives in range(3):
order_axis = np.zeros(3)
if derivatives == 0:
order_axis[1] = 1
if derivatives == 1:
order_axis[2] = 1
if derivatives == 2:
order_axis[0] = 1
if order[derivatives] > 0:
for derivs in range(order[derivatives]):
if First_Derivative_Check != 0:
Upper = F[0:int(dF.shape[0]-2*order_axis[0]),0:int(dF.shape[1]-2*order_axis[1]),0:int(dF.shape[2]-2*order_axis[2])]
Middle = F[int(1*order_axis[0]):int(dF.shape[0]-1*order_axis[0]),int(1*order_axis[1]):int(dF.shape[1]-1*order_axis[1]),int(1*order_axis[2]):int(dF.shape[2]-1*order_axis[2])]
Lower = F[int(2*order_axis[0]):dF.shape[0],int(2*order_axis[1]):dF.shape[1],int(2*order_axis[2]):dF.shape[2]]
dF = -Upper+Middle+Lower
if First_Derivative_Check == 0:
First_Derivative_Check = 1
Upper = F[0:int(F.shape[0]-2*order_axis[0]),0:int(F.shape[1]-2*order_axis[1]),0:int(F.shape[2]-2*order_axis[2])]
Middle = F[int(1*order_axis[0]):int(F.shape[0]-1*order_axis[0]),int(1*order_axis[1]):int(F.shape[1]-1*order_axis[1]),int(1*order_axis[2]):int(F.shape[2]-1*order_axis[2])]
Lower = F[int(2*order_axis[0]):F.shape[0],int(2*order_axis[1]):F.shape[1],int(2*order_axis[2]):F.shape[2]]
dF = -Upper+Middle+Lower
c5 = np.array([-3,12,17,12,-3])/35
c7 = np.array([-2,3,6,7,6,3,-2])/21
for smooth in range(order[derivatives]+1):
if deriv_axis == 'x':
dF[2,:,:] = (dF[1,:,:]+dF[2,:,:]+dF[3,:,:])/3
dF[dF.shape[0]-3,:,:] = (dF[dF.shape[0]-4,:,:]+dF[dF.shape[0]-3,:,:]+dF[dF.shape[0]-2,:,:])/3
dF[3,:,:] = c5[0]*dF[1,:,:]+c5[1]*dF[2,:,:]+c5[2]*dF[3,:,:]+c5[3]*dF[4,:,:]+c5[4]*dF[5,:,:]
dF[dF.shape[0]-4,:,:] = c5[0]*dF[dF.shape[0]-6,:,:]+c5[1]*dF[dF.shape[0]-5,:,:]+c5[2]*dF[dF.shape[0]-4,:,:]+c5[3]*dF[dF.shape[0]-3,:,:]+c5[4]*dF[dF.shape[0]-2,:,:]
dF[4:dF.shape[0]-4,:,:] = c7[0]*dF[1:dF.shape[0]-7,:,:]+c7[1]*dF[2:dF.shape[0]-6,:,:]+c7[2]*dF[3:dF.shape[0]-5,:,:]+c7[3]*dF[4:dF.shape[0]-4,:,:]+c7[4]*dF[5:dF.shape[0]-3,:,:]+c7[5]*dF[6:dF.shape[0]-2,:,:]+c7[6]*dF[7:dF.shape[0]-1,:,:]
if deriv_axis == 'y':
dF[:,2,:] = (dF[:,1,:]+dF[:,2,:]+dF[:,3,:])/3
dF[:,dF.shape[1]-3,:] = (dF[:,dF.shape[1]-4,:]+dF[:,dF.shape[1]-3,:]+dF[:,dF.shape[1]-2,:])/3
dF[:,3,:] = c5[0]*dF[:,1,:]+c5[1]*dF[:,2,:]+c5[2]*dF[:,3,:]+c5[3]*dF[:,4,:]+c5[4]*dF[:,5,:]
dF[:,dF.shape[1]-4,:] = c5[0]*dF[:,dF.shape[1]-6,:]+c5[1]*dF[:,dF.shape[1]-5,:]+c5[2]*dF[:,dF.shape[1]-4,:]+c5[3]*dF[:,dF.shape[1]-3,:]+c5[4]*dF[:,dF.shape[1]-2,:]
dF[:,4:dF.shape[1]-4,:] = c7[0]*dF[:,1:dF.shape[1]-7,:]+c7[1]*dF[:,2:dF.shape[1]-6,:]+c7[2]*dF[:,3:dF.shape[1]-5,:]+c7[3]*dF[:,4:dF.shape[1]-4,:]+c7[4]*dF[:,5:dF.shape[1]-3,:]+c7[5]*dF[:,6:dF.shape[1]-2,:]+c7[6]*dF[:,7:dF.shape[1]-1,:]
if deriv_axis == 'z':
dF[:,:,2] = (dF[:,:,1]+dF[:,:,2]+dF[:,:,3])/3
dF[:,:,dF.shape[2]-3] = (dF[:,:,dF.shape[2]-4]+dF[:,:,dF.shape[2]-3]+dF[:,:,dF.shape[2]-2])/3
dF[:,:,3] = c5[0]*dF[:,:,1]+c5[1]*dF[:,:,2]+c5[2]*dF[:,:,3]+c5[3]*dF[:,:,4]+c5[4]*dF[:,:,5]
dF[:,:,dF.shape[2]-4] = c5[0]*dF[:,:,dF.shape[2]-6]+c5[1]*dF[:,:,dF.shape[2]-5]+c5[2]*dF[:,:,dF.shape[2]-4]+c5[3]*dF[:,:,dF.shape[2]-3]+c5[4]*dF[:,:,dF.shape[2]-2]
dF[:,:,4:dF.shape[2]-4] = c7[0]*dF[:,:,1:dF.shape[2]-7]+c7[1]*dF[:,:,2:dF.shape[2]-6]+c7[2]*dF[:,:,3:dF.shape[2]-5]+c7[3]*dF[:,:,4:dF.shape[2]-4]+c7[4]*dF[:,:,5:dF.shape[2]-3]+c7[5]*dF[:,:,6:dF.shape[2]-2]+c7[6]*dF[:,:,7:dF.shape[2]-1]
return dF
'''
order = np.array([1,0,0])
F = np.random.randint(1,10,(50,2048,2048))
begin_timer = timeit.default_timer()
F = Derivatives(order,F,begin_timer)
end_timer = timeit.default_timer()
print(end_timer-begin_timer)
''' | {
"alphanum_fraction": 0.471360652,
"author": null,
"avg_line_length": 70.1111111111,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "8f66512e930a33fde4937d2cbc23f334f05d2eba",
"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": "0c7790f71e940b42e9b362b9186cb53654f92a58",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "NikoRanta/DHM_Pipeline",
"max_forks_repo_path": "Derivative.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0c7790f71e940b42e9b362b9186cb53654f92a58",
"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": "NikoRanta/DHM_Pipeline",
"max_issues_repo_path": "Derivative.py",
"max_line_length": 257,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0c7790f71e940b42e9b362b9186cb53654f92a58",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "NikoRanta/DHM_Pipeline",
"max_stars_repo_path": "Derivative.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1794,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 4417
} |
"""
Planar data classification using 1 hidden layer
Authors:
Nalin Das (nalindas9@gmail.com)
Graduate Student pursuing Masters in Robotics,
University of Maryland, College Park
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
import utils
import time
from tensorboardX import SummaryWriter
def load_dataset():
"""
Planar flower training dataset definition
Arguments:
None
Returns:
X - input feature dataset of shape (input size, number of examples)
Y - labels of shape (output size, number of examples)
"""
np.random.seed(1)
m = 400 # number of examples
N = int(m/2) # number of points per class
D = 2 # dimensionality
X = np.zeros((m,D)) # data matrix where each row is a single example
Y = np.zeros((m,1), dtype='uint8') # labels vector (0 for red, 1 for blue)
a = 4 # maximum ray of the flower
for j in range(2):
ix = range(N*j,N*(j+1))
t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta
r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
Y[ix] = j
X = X.T
Y = Y.T
return X, Y
def load_test_dataset():
"""
Planar flower test dataset definition
Arguments:
None
Returns:
X - input feature dataset of shape (input size, number of examples)
Y - labels of shape (output size, number of examples)
"""
np.random.seed(5)
m = 400 # number of examples
N = int(m/2) # number of points per class
D = 2 # dimensionality
X = np.zeros((m,D)) # data matrix where each row is a single example
Y = np.zeros((m,1), dtype='uint8') # labels vector (0 for red, 1 for blue)
a = 4 # maximum ray of the flower
for j in range(2):
ix = range(N*j,N*(j+1))
t = np.linspace(j*3.12,(j+1)*3.12,N) + np.random.randn(N)*0.2 # theta
r = a*np.sin(4*t) + np.random.randn(N)*0.2 # radius
X[ix] = np.c_[r*np.sin(t), r*np.cos(t)]
Y[ix] = j
X = X.T
Y = Y.T
return X, Y
# Define input, output and hidden layer size
def layer_sizes(X, Y):
"""
Arguments:
X - input feature dataset of shape (input size, number of examples)
Y - labels of shape (output size, number of examples)
Returns:
n_X - size of input layer
n_H - size of hidden layer
n_Y - size of output layer
"""
n_X = X.shape[0]
n_H = 15
n_Y = Y.shape[0]
return n_X, n_H, n_Y
# Initialize Model Parameters
def initialize_parameters(n_X, n_H, n_Y):
"""
Arguments:
n_X - size of input layer
n_H - size of hidden layer
n_Y - size of output layer
Returns:
params - Dictionary containing weights and biases
W1 -- Weight matrix of shape (n_H, n_X)
b1 -- Bias matrix of shape (n_H, 1)
W2 -- Weight matrix of shape (n_Y, n_H)
b2 -- Bias matrix of shape (n_Y, 1)
"""
W1 = np.random.randn(n_H, n_X)*0.01
b1 = np.zeros((n_H, 1))
W2 = np.random.randn(n_Y, n_H)*0.01
b2 = np.zeros((n_Y, 1))
params = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return params
# Forward Propagation
def forward_propagation(X, params):
"""
Args:
X -- Input data of shape (n_x, m) n_x -> no of input nodes; m -> no of training examples
params -- Dictionary with the initialized weights and the biases
Returns:
A2 -- Sigmoid output of 2nd or output layer of shape (n_y, m)
neuron_functions -- Dictionary containing the computed linear function Z and activation function A for each neuron
"""
W1 = params["W1"]
b1 = params["b1"]
W2 = params["W2"]
b2 = params["b2"]
# Compute the linear function Z and sigmoid Activation function for each neuron
Z1 = np.dot(W1,X) + b1
A1 = utils.sigmoid(Z1)
Z2 = np.dot(W2,A1) + b2
A2 = utils.sigmoid(Z2)
neuron_functions = {"Z1": Z1,
"A1": A1,
"Z2": Z2,
"A2": A2}
return A2, neuron_functions
# Compute cost function
def compute_cost(A2, Y):
"""
Args:
A2 -- Predicted output value using sigmoid activation of shape (n_y, m)
Y -- Labels of shape (n_y, m)
Returns:
cost -- Average of cross entropy cost over m training examples
"""
m = Y.shape[1] # number of training examples
logprob = Y*np.log(A2) + (1-Y)*np.log(1-A2)
cost = -(1/m)*np.sum(logprob)
return cost
# Backward Propagation
def backward_propagation(neuron_functions, params, X, Y):
"""
Args:
neuron_functions -- Dictionary of neuron linear and action functions computed
during forward propagation
Returns:
gradients - Dictionary with gradients of Loss w.r.t the weights and biases
"""
m = X.shape[1]
W1 = params["W1"]
W2 = params["W2"]
A1 = neuron_functions["A1"]
A2 = neuron_functions["A2"]
dZ2 = A2 - Y # (n_y, m)
dW2 = (1/m)*np.dot(dZ2, A1.T)
db2 = (1/m)*np.sum(dZ2, axis = 1, keepdims = True)
dZ1 = np.dot(W2.T,dZ2)*(1-np.power(A1, 2))
dW1 = (1/m)*np.dot(dZ1, X.T)
db1 = (1/m)*np.sum(dZ1, axis = 1, keepdims = True)
gradients = {
"dW1": dW1,
"db1": db1,
"dW2": dW2,
"db2": db2
}
return gradients
def update_parameters(params, gradients, learning_rate=1.2):
"""
Updates parameters using gradient descent update rule
Args:
params -- Dictionary containing weights and biases
W1 -- Weight matrix of shape (n_H, n_X)
b1 -- Bias matrix of shape (n_H, 1)
W2 -- Weight matrix of shape (n_Y, n_H)
b2 -- Bias matrix of shape (n_Y, 1)
gradients -- Dictionary with gradients of Loss w.r.t the weights and biases
learning_rate - Learning rate for gradient descent
Returns:
params -- Updated weights and biases
"""
W1 = params["W1"]
b1 = params["b1"]
W2 = params["W2"]
b2 = params["b2"]
dW1 = gradients["dW1"]
db1 = gradients["db1"]
dW2 = gradients["dW2"]
db2 = gradients["db2"]
# Update parameters
W1 = W1-learning_rate*dW1
b1 = b1-learning_rate*db1
W2 = W2-learning_rate*dW2
b2 = b2-learning_rate*db2
params = {"W1": W1,
"b1": b1,
"W2": W2,
"b2": b2}
return params
def nn_model_train(X, Y, num_iterations = 10000, lr=1.2, print_cost=False, print_cost_itr=1000):
"""
Train the Neural Network
Args:
X -- Input dataset
Y -- Labels
num_iterations -- Number of training iterations
print_cost -- Set True to print cost during training
print_cost_itr -- Print cost after every "print_cost_itr" iterations
Returns:
params -- Learned weights and biases after training
"""
# Setup tensorboard for logging
writer = SummaryWriter('runs/planar_data_classification')
# Get NN layer sizes
n_X, n_H, n_Y = layer_sizes(X, Y)
print("Size of I/P layer: {}, hidden layer: {}, O/P layer: {}".format(n_X, n_H, n_Y))
# Initialize weights and biases
params = initialize_parameters(n_X, n_H, n_Y)
print("Weights and biases matrix initialized as: {}".format(params))
# Training loop
for i in range(0, num_iterations):
start_time = time.time()
# Forward Propagation
A2, neuron_functions = forward_propagation(X, params)
# Cost function
cost = compute_cost(A2, Y)
# Backpropagation
gradients = backward_propagation(neuron_functions, params, X, Y)
# Gradient descent update weights and biases
params = update_parameters(params, gradients, learning_rate=lr)
# Print cost every "print_cost_itr" iterations
if print_cost and i%print_cost_itr == 0:
print('Cost after {} iterations: {}'.format(i, cost))
writer.add_scalar('Cost/train', cost, i)
print('Cost after {} iterations: {}'.format(i, cost))
writer.add_scalar('Cost/train', cost, i)
end_time = time.time()
training_time = end_time - start_time
print('Training time: ', training_time)
return params
def predict(X, Y, params):
"""
Predict class on each example in test data
Arguments:
X -- Input dataset
params -- Learned weights and biases after training
Returns:
prediction -- Predicted class for each example in test dataset
"""
A2, neuron_functions = forward_propagation(X, params)
prediction = A2 > 0.5 # if A2 for each example > 0.5, then 1 else 0
# Print Accuracy
print('Accuracy: {}%'. format(float((np.dot(Y, prediction.T)+np.dot(1-Y, 1-prediction.T))/float(Y.size))*100))
return prediction
def main():
X, Y = load_dataset()
X_t, Y_t = load_test_dataset()
print('Loaded the planar flower dataset.')
print('Input training features: ', X)
print('')
print('Training Labels Red = 0, Blue = 1: ', Y)
print('Input test features: ', X)
print('')
print('Test Labels Red = 0, Blue = 1: ', Y)
# Visualize train dataset
plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);
plt.show()
# Visualize test dataset
plt.scatter(X_t[0, :], X_t[1, :], c=Y_t, s=40, cmap=plt.cm.Spectral);
plt.show()
params = nn_model_train(X, Y, 2000, 6.0, print_cost=True)
print('Learned weights and biases: ', params)
prediction = predict(X_t, Y_t, params)
print('Predictions: ', prediction)
if __name__ == '__main__':
main()
| {
"alphanum_fraction": 0.5996684625,
"author": null,
"avg_line_length": 29.4268292683,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "e91ad6ff4d65227a88de758018f510eaef989680",
"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": "0c47bdde2a95be1944c19423527ad26cf2a27210",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "nalindas9/neural-network-scratch",
"max_forks_repo_path": "classifying_planar_data/planar_data_classification.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0c47bdde2a95be1944c19423527ad26cf2a27210",
"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": "nalindas9/neural-network-scratch",
"max_issues_repo_path": "classifying_planar_data/planar_data_classification.py",
"max_line_length": 118,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0c47bdde2a95be1944c19423527ad26cf2a27210",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "nalindas9/neural-network-scratch",
"max_stars_repo_path": "classifying_planar_data/planar_data_classification.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2730,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 9652
} |
"""
My Python startup file, carefully gathered from different sources (see below)
Get code from Github::
git clone https://github.com/jezdez/python-startup.git ~/.python
Put this in your shell profile::
export PYTHONSTARTUP=$HOME/.python/startup.py
In case you haven't saved these files in $HOME/.python make sure to set
PYTHONUSERDIR approppriately, too::
export PYTHONUSERDIR=/path/to/dir
"""
# python-startup.py
# Author: Nathan Gray, based on interactive.py by Robin Friedrich and an
# evil innate desire to customize things.
# E-Mail: n8gray@caltech.edu
#
# Version: 0.6
# These modules are always nice to have in the namespace
############################################################################
# Below this is Robin Friedrich's interactive.py with some edits to decrea7se
# namespace pollution and change the help functionality
# NG
#
# Also enhanced 'which' to return filename/lineno
# Patch from Stephan Fiedler to allow multiple args to ls variants
# NG 10/21/01 -- Corrected a bug in _glob
#
########################### interactive.py ###########################
# """Functions for doing shellish things in Python interactive mode.
#
# Meant to be imported at startup via environment:
# setenv PYTHONSTARTUP $HOME/easy.py
# or
# export PYTHONSTARTUP=$HOME/easy.py
#
# - Robin Friedrich
# """
import functools
import cProfile, pstats, io
import glob
import os
import re
import shutil
import subprocess
import sys
import time
import types
from itertools import islice
from pprint import pprint
import pickle
import numpy as np
import pandas as pd
from functools import wraps
from datetime import datetime
# environment settings:
pd.set_option('display.max_column', None)
pd.set_option('display.max_rows', 100)
pd.set_option('display.max_colwidth', 1000)
pd.set_option('display.width', 1000)
# pd.set_option('display.float_format', lambda x: '%.2f' % x)
def profile(fnc):
"""A decorator that uses cProfile to profile a function"""
def inner(*args, **kwargs):
pr = cProfile.Profile()
pr.enable()
retval = fnc(*args, **kwargs)
pr.disable()
s = io.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
return retval
return inner
try:
from pydoc import help
except ImportError:
def help(*objects):
"""Print doc strings for object(s).
Usage: >>> help(object, [obj2, objN]) (brackets mean [optional] argument)
"""
if len(objects) == 0:
help(help)
return
for obj in objects:
try:
print('****', obj.__name__, '****')
print(obj.__doc__)
except AttributeError:
print(obj, 'has no __doc__ attribute')
print
try:
from collections import defaultdict
except ImportError:
pass
# home = os.path.expandvars('$HOME')
# user_dir = os.path.join(home, os.environ.get("PYTHONUSERDIR", ".python"))
# sys.path.append(user_dir)
##### Some settings you may want to change #####
# Define the editor used by the edit() function. Try to use the editor
# defined in the Unix environment, or default to vi if not set.
# (patch due to Stephan Fiedler)
#
# %(lineno)s gets replaced by the line number. Ditto %(fname)s the filename
EDITOR = os.environ.get('EDITOR', 'vim')
editorbase = EDITOR.split()[0]
if editorbase in ['nedit', 'nc', 'ncl', 'emacs', 'emacsclient', 'xemacs']:
# We know these editors supoprt a linenumber argument
EDITOR = EDITOR + ' +%(lineno)s %(fname)s &'
elif editorbase in ['vi', 'vim', 'jed']:
# Don't want to run vi in the background!
# If your editor requires a terminal (e.g. joe) use this as a template
EDITOR = 'xterm -e ' + EDITOR + ' +%(lineno)s %(fname)s &'
else:
# Guess that the editor only supports the filename
EDITOR = EDITOR + ' %(fname)s &'
del editorbase
# The place to store your command history between sessions
# histfile = os.path.join(user_dir, "history")
# Functions automatically added to the builtins namespace so that you can
# use them in the debugger and other unusual environments
autobuiltins = ['edit', 'which', 'ls', 'cd', 'mv', 'cp', 'rm', 'help', 'rmdir',
'ln', 'pwd', 'pushd', 'popd', 'env', 'mkdir']
# LazyPython only works for Python versions 2.1 and above
# try:
# # Try to use LazyPython
# from LazyPython import LazyPython
#
# sys.excepthook = LazyPython()
# except ImportError:
# pass
#
# try:
# Try to set up command history completion/saving/reloading
# import readline, atexit, rlcompleter
#
# readline.parse_and_bind('tab: complete')
# try:
# readline.read_history_file(histfile)
# except IOError:
# pass # It doesn't exist yet.
#
#
# def savehist():
# try:
# global histfile
# readline.write_history_file(histfile)
# except:
# print('Unable to save Python command history')
#
#
# atexit.register(savehist)
# del atexit
# except ImportError:
# pass
# Make an "edit" command that sends you to the right file *and line number*
# to edit a module, class, method, or function!
# Note that this relies on my enhanced version of which().
# def edit(object, editor=EDITOR):
# """Edit the source file from which a module, class, method, or function
# was imported.
# Usage: >>> edit(mysteryObject)
# """
#
# if type(object) is type(""):
# fname = object;
# lineno = 1
# print(editor % locals())
# subprocess.Popen(editor % locals(), shell=True)
# return
#
# ret = which(object)
# if not ret:
# print("Can't edit that!")
# return
# fname, lineno = ret
# if fname[-4:] == '.pyc' or fname[-4:] == '.pyo':
# fname = fname[:-1]
# print(editor % locals())
# subprocess.Popen(editor % locals(), shell=True)
def edit(object):
"""Edit the source file from which a module, class, method, or function
was imported.
Usage: >>> edit(mysteryObject)
"""
subprocess.Popen(f'subl + {object}', shell=True)
def openf(directory):
os.startfile(directory)
def reimport(mod, locals=None):
if isinstance(mod, str):
modname = mod
else:
modname = mod.__name__
sys.modules[modname] = None
del sys.modules[modname]
new_mod = __import__(modname)
if locals is not None:
locals[modname] = new_mod
return new_mod
def _glob(filenames):
"""Expand a filename or sequence of filenames with possible
shell metacharacters to a list of valid filenames.
Ex: _glob(('*.py*',)) == ['able.py','baker.py','charlie.py']
"""
if type(filenames) is str:
return glob.glob(filenames)
flist = []
for filename in filenames:
globbed = glob.glob(filename)
if globbed:
for file in globbed:
flist.append(file)
else:
flist.append(filename)
return flist
def _expandpath(d):
"""Convert a relative path to an absolute path.
"""
return os.path.join(os.getcwd(), os.path.expandvars(d))
lsdir = os.listdir
mkdir = os.mkdir
def rm(*args):
"""Delete a file or files.
Usage: >>> rm('file.c' [, 'file.h']) (brackets mean [optional] argument)
Alias: delete
"""
filenames = _glob(args)
for item in filenames:
try:
os.remove(item)
except OSError as detail:
print(f'{detail} : {item}')
delete = rm
def rmdir(directory):
"""Remove a directory.
Usage: >>> rmdir('dirname')
If the directory isn't empty, can recursively delete all sub-files.
"""
try:
os.rmdir(directory)
except os.error:
# directory wasn't empty
answer = raw_input(directory + " isn't empty. Delete anyway?[n] ")
if answer and answer[0] in 'Yy':
subprocess.Popen('rm -rf %s' % directory, shell=True)
print(directory + ' Deleted.')
else:
print(directory + ' Unharmed.')
def mv(*args):
"""Move files within a filesystem.
Usage: >>> mv('file1', ['fileN',] 'fileordir')
If two arguments - both must be files
If more arguments - last argument must be a directory
"""
filenames = _glob(args)
nfilenames = len(filenames)
if nfilenames < 2:
print('Need at least two arguments')
elif nfilenames == 2:
try:
os.rename(filenames[0], filenames[1])
except OSError as detail:
print("%s: %s" % (detail[1], filenames[1]))
else:
for filename in filenames[:-1]:
try:
dest = filenames[-1] + '/' + filename
if not os.path.isdir(filenames[-1]):
print('Last argument needs to be a directory')
return
os.rename(filename, dest)
except OSError as detail:
print("%s: %s" % (detail[1], filename))
def cp(*args):
"""Copy files along with their mode bits.
Usage: >>> cp('file1', ['fileN',] 'fileordir')
If two arguments - both must be files
If more arguments - last argument must be a directory
"""
filenames = _glob(args)
nfilenames = len(filenames)
if nfilenames < 2:
print('Need at least two arguments')
elif nfilenames == 2:
try:
shutil.copy(filenames[0], filenames[1])
except OSError as detail:
print("%s: %s" % (detail[1], filenames[1]))
else:
for filename in filenames[:-1]:
try:
dest = filenames[-1] + '/' + filename
if not os.path.isdir(filenames[-1]):
print('Last argument needs to be a directory')
return
shutil.copy(filename, dest)
except OSError as detail:
print("%s: %s" % (detail[1], filename))
def cpr(src, dst):
"""Recursively copy a directory tree to a new location
Usage: >>> cpr('directory0', 'newdirectory')
Symbolic links are copied as links not source files.
"""
shutil.copytree(src, dst)
def ln(src, dst):
"""Create a symbolic link.
Usage: >>> ln('existingfile', 'newlink')
"""
os.symlink(src, dst)
def lnh(src, dst):
"""Create a hard file system link.
Usage: >>> ln('existingfile', 'newlink')
"""
os.link(src, dst)
def cd(directory=-1):
"""Change directory. Environment variables are expanded.
Usage:
cd('rel/$work/dir') change to a directory relative to your own
cd('/abs/path') change to an absolute directory path
cd() list directories you've been in
cd(int) integer from cd() listing, jump to that directory
"""
global cdlist
if type(directory) is int:
if directory in range(len(cdlist)):
cd(cdlist[directory])
return
else:
pprint(cdlist)
return
directory = _glob(directory)[0]
if not os.path.isdir(directory):
print(directory + ' is not a directory')
return
directory = _expandpath(directory)
if directory not in cdlist:
cdlist.append(directory)
os.chdir(directory)
def env():
"""List environment variables.
Usage: >>> env()
"""
# unfortunately environ is an instance not a dictionary
pprint(os.environ)
interactive_dir_stack = []
def pushd(directory):
"""Place the current dir on stack and change directory.
Usage: >>> pushd(['dirname']) (brackets mean [optional] argument)
pushd() goes home.
"""
global interactive_dir_stack
interactive_dir_stack.append(os.getcwd())
cd(directory)
def popd():
"""Change to directory popped off the top of the stack.
Usage: >>> popd()
"""
global interactive_dir_stack
try:
cd(interactive_dir_stack[-1])
print(interactive_dir_stack[-1])
del interactive_dir_stack[-1]
except IndexError:
print('Stack is empty')
def syspath():
"""Print the Python path.
Usage: >>> syspath()
"""
import sys
pprint(sys.path)
def which(object):
"""Print the source file from which a module, class, function, or method
was imported.
Usage: >>> which(mysteryObject)
Returns: Tuple with (file_name, line_number) of source file, or None if
no source file exists
Alias: whence
"""
object_type = type(object)
if object_type is types.ModuleType:
if hasattr(object, '__file__'):
print('Module from', object.__file__)
return (object.__file__, 1)
else:
print('Built-in module.')
elif object_type is types.ClassType:
if object.__module__ == '__main__':
print('Built-in class or class loaded from $PYTHONSTARTUP')
else:
print('Class', object.__name__, 'from', \
sys.modules[object.__module__].__file__)
# Send you to the first line of the __init__ method
return (sys.modules[object.__module__].__file__,
object.__init__.im_func.func_code.co_firstlineno)
elif object_type in (types.BuiltinFunctionType, types.BuiltinMethodType):
print("Built-in or extension function/method.")
elif object_type is types.FunctionType:
print('Function from', object.func_code.co_filename)
return (object.func_code.co_filename, object.func_code.co_firstlineno)
elif object_type is types.MethodType:
print('Method of class', object.im_class.__name__, 'from', )
fname = sys.modules[object.im_class.__module__].__file__
print(fname)
return (fname, object.im_func.func_code.co_firstlineno)
else:
print("argument is not a module or function.")
return None
whence = which
#######################################################################################################
#######################################################################################################
#######################################################################################################
#######################################################################################################
#######################################################################################################
#######################################################################################################
def parse_simple_date(date, **kwargs):
return datetime.strptime(str(date), '%Y-%m-%d')
def __ParseUTC__(d):
return datetime.strptime(str(d)[:-4], '%Y-%m-%dT%H:%M:%S.%f')
def fast_parse(df, col, parser=__ParseUTC__, name=None):
'''
'''
dt = pd.DataFrame(df[col].unique())
dt.columns = [col + '_tmp']
dt[col] = dt[col + '_tmp'].apply(parser)
date_dict = dt.set_index(col + '_tmp').to_dict()
if name == None:
df[col] = df[col].map(date_dict[col])
else:
df[name] = df[col].map(date_dict[col])
return df
def rcsv(path, **kwargs):
return pd.read_csv(path, **kwargs)
def rexcel(path, **kwargs):
return pd.read_excel(path, **kwargs)
def timer(f):
@wraps(f)
def wrap(*args, **kw):
ts = datetime.now()
result = f(*args, **kw)
te = datetime.now()
print(f'Function:{f.__name__} with args: took: {te - ts} seconds')
return result
return wrap
def folder_space(_workDir_: str, subfolder_name: str, local_folder: bool = True):
'''
:param name: folder name
:return: folder path
'''
if _workDir_ == '':
CurrDir = os.getcwd().replace('\\', '/') + '/'
workDir = CurrDir if local_folder else CurrDir + 'New folder/'
else:
workDir = _workDir_ if _workDir_[-1] == '/' else _workDir_ + '/'
# filename = workDir + subfolder_name + '/'
# else:
# filename = filename_temp
filename = workDir + subfolder_name + '/'
try:
os.makedirs(filename)
# print("Directory " , dirName , " Created ")
except FileExistsError:
# print("Directory " , name , " already exists")
pass
return filename
def getd(device='HPC'):
if device == 'HPC' or device == 0:
return 'C:/Users/PC-user/Desktop/'
elif device == 'UNSW' or device == 1:
return 'C:/Users/z3446244/Desktop/'
elif device == 'linux' or device == 2:
return '/home/shinc/'
elif device == 'lib' or device == 3:
return 'D:/Anaconda/mylib/'
elif device == 'linuxd' or device == 4:
return '/run/media/shinc/8C36A64636A6315E/'
elif device == 'pych' or device == 5:
return '/run/media/shinc/8C36A64636A6315E/PycharmProjects/'
else:
print('Please enter HPC/UNSW/MAC')
return os.getcwd()
device = sys.platform
workDir = getd(device)
cdlist = [getd(i) for i in range(0, 6)]
def read(fname, nlines=10):
'''read any file for first n line'''
try:
with open(fname) as f:
for line in islice(f, nlines):
print(line)
except:
with open(fname, encoding="utf8") as f:
for line in islice(f, nlines):
print(line)
def findint(s):
'''
find integer from strings
:param s:
:return:
'''
return int(re.search(r'\d+', s).group())
def savepickle(var, filename):
with open(filename, 'wb') as f:
pickle.dump(var, f)
def loadpickle(filename):
with open(filename, 'rb') as f:
temp = pickle.load(f)
return temp
def qprint(df, first_n=5):
print([{c: df[c].unique()[0:first_n]} for c in df.columns.tolist()])
def marketshare(df, col):
'''
calculate market share based on col
'''
total_sum = df[col].sum()
df[col + '_mrkshr'] = df[col] / total_sum * 100
return df
def tw_metrics(df, col, timeindex):
temp = df.groupby(timeindex)[col].sum().reset_index()
temp = temp.sort_values(by=timeindex)
temp['time_d'] = (temp[timeindex].diff(1)).dt.total_seconds()
temp[col + '_tw'] = temp[col] * temp['time_d']
tw_col = temp[col + '_tw'].sum() / temp.dropna(subset=[col])['time_d'].sum()
return tw_col
def findcol(df, word, ignore=True):
cols=df.columns.tolist()
if ignore:
cols_temp = [x.lower() for x in cols]
word=word.lower()
return [cols[i] for i,x in enumerate(cols_temp) if word in x]
def _set_digit(digit):
pd.set_option('display.max_column', None)
pd.set_option('display.max_colwidth', 1000)
pd.set_option('display.float_format', lambda x: '%.3f' % x)
print('=' * 70)
print('User: Jiayuan Chen (jiayuanchen@outlook.com)')
print('=' * 70)
#
| {
"alphanum_fraction": 0.5851312573,
"author": null,
"avg_line_length": 29.3572542902,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "be377a4efa528a2b196e0b173a111a60b9a58d99",
"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": "6d40dc3f0bfdb2fd3c652e9c2db01f56ae6d2620",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Shin-C/dotfiles",
"max_forks_repo_path": "pythonstartup/startup.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6d40dc3f0bfdb2fd3c652e9c2db01f56ae6d2620",
"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": "Shin-C/dotfiles",
"max_issues_repo_path": "pythonstartup/startup.py",
"max_line_length": 103,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6d40dc3f0bfdb2fd3c652e9c2db01f56ae6d2620",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Shin-C/dotfiles",
"max_stars_repo_path": "pythonstartup/startup.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 4557,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 18818
} |
import os
import sys
from setuptools import setup, PEP420PackageFinder, Extension
from setuptools.command.build_ext import build_ext
if 'EPICS_BASE' not in os.environ or 'EPICS_HOST_ARCH' not in os.environ:
print(sys.stderr, 'EPICS_BASE and EPICS_HOST_ARCH must be set')
sys.exit(-1)
if sys.platform == 'darwin':
libsrc = 'Darwin'
compiler = 'clang'
elif sys.platform.startswith('linux'):
libsrc = 'Linux'
compiler = 'gcc'
epics_base = os.environ['EPICS_BASE']
epics_host_arch = os.environ['EPICS_HOST_ARCH']
epics_inc = os.path.join(epics_base, 'include')
epics_lib = os.path.join(epics_base, 'lib', epics_host_arch)
cas_path = 'src/channel_access/server/cas'
cas_extension = Extension('channel_access.server.cas',
language = 'c++',
sources = list(map(lambda s: os.path.join(cas_path, s), [
'cas.cpp',
'server.cpp',
'pv.cpp',
'convert.cpp',
'async.cpp'
])),
include_dirs = [
cas_path,
epics_inc,
os.path.join(epics_inc, 'os', libsrc),
os.path.join(epics_inc, 'compiler', compiler),
],
library_dirs = [ epics_lib ],
runtime_library_dirs = [ epics_lib ],
extra_compile_args = ['-Wall', '-std=c++11'],
libraries=['Com', 'ca', 'cas', 'gdd']
)
class BuildExtensionCommand(build_ext):
def finalize_options(self):
super().finalize_options()
use_numpy = os.environ.get('CA_WITH_NUMPY')
if use_numpy is None:
try:
import numpy
except ImportError:
use_numpy = False
else:
use_numpy = True
else:
use_numpy = bool(int(use_numpy))
if self.define is None:
self.define = []
self.define.append(('CA_SERVER_NUMPY_SUPPORT', int(use_numpy)))
if use_numpy:
import numpy
if self.include_dirs is None:
self.include_dirs = []
self.include_dirs.append(numpy.get_include())
with open('README.rst', encoding='utf-8') as f:
long_description = f.read()
setup(
name = 'channel_access.server',
description = 'Channel Access server library',
long_description = long_description,
license='MIT',
author = 'André Althaus',
author_email = 'andre.althaus@tu-dortmund.de',
classifiers = [
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Scientific/Engineering'
],
keywords = 'epics ca cas channel_access',
packages = PEP420PackageFinder.find('src'),
package_dir = { '': 'src' },
ext_modules = [ cas_extension ],
python_requires = '>= 3.5',
setup_requires = [ 'setuptools_scm' ],
install_requires = [ 'channel_access.common' ],
extras_require = {
'numpy': [ 'numpy' ],
'dev': [ 'tox', 'sphinx', 'pytest' ],
'doc': [ 'sphinx' ],
'test': [ 'pytest' ]
},
use_scm_version = True,
cmdclass={
'build_ext': BuildExtensionCommand,
}
)
| {
"alphanum_fraction": 0.6011739265,
"author": null,
"avg_line_length": 29.4272727273,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "0f8bddaba7763ec98ca41820af6f0c1f38b48c82",
"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": "21a7707da1f3421ed38773095e577f48b798daac",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "delta-accelerator/channel_access.server",
"max_forks_repo_path": "setup.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "21a7707da1f3421ed38773095e577f48b798daac",
"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": "delta-accelerator/channel_access.server",
"max_issues_repo_path": "setup.py",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "21a7707da1f3421ed38773095e577f48b798daac",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "delta-accelerator/channel_access.server",
"max_stars_repo_path": "setup.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": 3237
} |
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
⊢ Category.{?u.2036, u₁} (Skeleton C)
[PROOFSTEP]
apply InducedCategory.category
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
⊢ Full (fromSkeleton C)
[PROOFSTEP]
apply InducedCategory.full
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
⊢ Faithful (fromSkeleton C)
[PROOFSTEP]
apply InducedCategory.faithful
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
⊢ Skeletal (Skeleton C)
[PROOFSTEP]
rintro X Y ⟨h⟩
[GOAL]
case intro
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
X Y : Skeleton C
h : X ≅ Y
⊢ X = Y
[PROOFSTEP]
have : X.out ≈ Y.out := ⟨(fromSkeleton C).mapIso h⟩
[GOAL]
case intro
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
X Y : Skeleton C
h : X ≅ Y
this : Quotient.out X ≈ Quotient.out Y
⊢ X = Y
[PROOFSTEP]
simpa using Quotient.sound this
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
⊢ ∀ (a₁ b₁ a₂ b₂ : C), a₁ ≈ a₂ → b₁ ≈ b₂ → (fun X Y => Nonempty (X ⟶ Y)) a₁ b₁ = (fun X Y => Nonempty (X ⟶ Y)) a₂ b₂
[PROOFSTEP]
rintro _ _ _ _ ⟨i₁⟩ ⟨i₂⟩
[GOAL]
case intro.intro
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
a₁✝ b₁✝ a₂✝ b₂✝ : C
i₁ : a₁✝ ≅ a₂✝
i₂ : b₁✝ ≅ b₂✝
⊢ (fun X Y => Nonempty (X ⟶ Y)) a₁✝ b₁✝ = (fun X Y => Nonempty (X ⟶ Y)) a₂✝ b₂✝
[PROOFSTEP]
exact propext ⟨Nonempty.map fun f => i₁.inv ≫ f ≫ i₂.hom, Nonempty.map fun f => i₁.hom ≫ f ≫ i₂.inv⟩
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
⊢ ∀ (a : ThinSkeleton C), a ≤ a
[PROOFSTEP]
refine' Quotient.ind fun a => _
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
a : C
⊢ Quotient.mk (isIsomorphicSetoid C) a ≤ Quotient.mk (isIsomorphicSetoid C) a
[PROOFSTEP]
exact ⟨𝟙 _⟩
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
x✝¹ x✝ : ThinSkeleton C
⊢ ∀ (a b : x✝¹ ⟶ x✝), a = b
[PROOFSTEP]
rintro ⟨⟨f₁⟩⟩ ⟨⟨_⟩⟩
[GOAL]
case up.up.up.up
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
x✝¹ x✝ : ThinSkeleton C
f₁ down✝ : x✝¹ ≤ x✝
⊢ { down := { down := f₁ } } = { down := { down := down✝ } }
[PROOFSTEP]
rfl
[GOAL]
C : Type u₁
inst✝³ : Category.{v₁, u₁} C
D : Type u₂
inst✝² : Category.{v₂, u₂} D
E : Type u₃
inst✝¹ : Category.{v₃, u₃} E
inst✝ : Quiver.IsThin C
src✝ : Preorder (ThinSkeleton C) := preorder C
⊢ ∀ (a b : C),
Quotient.mk (isIsomorphicSetoid C) a ≤ Quotient.mk (isIsomorphicSetoid C) b →
Quotient.mk (isIsomorphicSetoid C) b ≤ Quotient.mk (isIsomorphicSetoid C) a →
Quotient.mk (isIsomorphicSetoid C) a = Quotient.mk (isIsomorphicSetoid C) b
[PROOFSTEP]
rintro _ _ ⟨f⟩ ⟨g⟩
[GOAL]
case intro.intro
C : Type u₁
inst✝³ : Category.{v₁, u₁} C
D : Type u₂
inst✝² : Category.{v₂, u₂} D
E : Type u₃
inst✝¹ : Category.{v₃, u₃} E
inst✝ : Quiver.IsThin C
src✝ : Preorder (ThinSkeleton C) := preorder C
a✝ b✝ : C
f : a✝ ⟶ b✝
g : b✝ ⟶ a✝
⊢ Quotient.mk (isIsomorphicSetoid C) a✝ = Quotient.mk (isIsomorphicSetoid C) b✝
[PROOFSTEP]
apply Quotient.sound (equiv_of_both_ways f g)
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
R : D ⥤ C
L : C ⥤ D
h : L ⊣ R
X : ThinSkeleton C
⊢ (𝟭 (ThinSkeleton C)).obj X ⟶ (map L ⋙ map R).obj X
[PROOFSTEP]
letI := isIsomorphicSetoid C
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
R : D ⥤ C
L : C ⥤ D
h : L ⊣ R
X : ThinSkeleton C
this : Setoid C := isIsomorphicSetoid C
⊢ (𝟭 (ThinSkeleton C)).obj X ⟶ (map L ⋙ map R).obj X
[PROOFSTEP]
refine' Quotient.recOnSubsingleton X fun x => homOfLE ⟨h.unit.app x⟩
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
R : D ⥤ C
L : C ⥤ D
h : L ⊣ R
X : ThinSkeleton D
⊢ (map R ⋙ map L).obj X ⟶ (𝟭 (ThinSkeleton D)).obj X
[PROOFSTEP]
letI := isIsomorphicSetoid D
[GOAL]
C : Type u₁
inst✝² : Category.{v₁, u₁} C
D : Type u₂
inst✝¹ : Category.{v₂, u₂} D
E : Type u₃
inst✝ : Category.{v₃, u₃} E
R : D ⥤ C
L : C ⥤ D
h : L ⊣ R
X : ThinSkeleton D
this : Setoid D := isIsomorphicSetoid D
⊢ (map R ⋙ map L).obj X ⟶ (𝟭 (ThinSkeleton D)).obj X
[PROOFSTEP]
refine' Quotient.recOnSubsingleton X fun x => homOfLE ⟨h.counit.app x⟩
| {
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": 2729,
"mathlib_filename": "Mathlib.CategoryTheory.Skeletal",
"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
} |
\documentclass[
fontsize = 12pt,
paper = a4
]
{scrartcl}%koma-klasse
\addtokomafont{disposition}{\rmfamily}
\usepackage[
backend=biber,
citestyle=numeric,
sortcites=true,
natbib=true,
url=false,
doi=true,
eprint=false
]{biblatex}
\addbibresource{bibliography.bib}
\usepackage[subpreambles=true]{standalone} % Um das LaTeX-Dokument in mehrere Dateien zu trennen
\usepackage[british]{babel}%silbentrennung und benennungen
\usepackage[T1]{fontenc}%umlaute als eigene zeichen, macht silbentrennung und suche bei umlauten erst möglich
\usepackage{csquotes}
\usepackage{lmodern}%schriftartpaket. schöne sans serif schrift.
\usepackage{microtype} %typografieverbesserungen
\usepackage[per-mode=symbol]{siunitx}
\usepackage{textcomp} % Um Probleme zwischen sinunitx & microtype zu richten
\usepackage{isotope}
\usepackage{chemformula}
\usepackage{booktabs} % bessere Tabellen
\usepackage{tablefootnote}
\usepackage{multirow}
\usepackage{afterpage} % zum Einfügen von Leerseiten
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage[defaultlines=3,all]{nowidow} % widows und orphans verhindern
\usepackage{refstyle} %für unterschiedliche Referenzenstile
\usepackage{varioref}
\usepackage[hidelinks]{hyperref}%zum schluss, macht hyperlinks in das pdf, hidelinks entfernt farbige Rahmen
\usepackage{cleveref}
\usepackage{caption}
\usepackage{subcaption} %Abbildungsbeschriftungen nebeneinander
\usepackage{tabularx}
\newcolumntype{L}[1]{>{\raggedright\arraybackslash}p{#1}}
\newcolumntype{C}[1]{>{\centering\arraybackslash}m{#1}}
\newcolumntype{R}[1]{>{\raggedleft\arraybackslash}m{#1}}
\usepackage{multirow}
\usepackage{pdflscape}
\usepackage{floatrow}
\usepackage{vcell}
% TikZ -- TikZ ist kein Zeichenprogramm
\usepackage{tikz}
\usepackage{tikz-timing}
\usepackage{etoolbox}
\usetikzlibrary{mindmap}
\usetikzlibrary{shapes}
\usetikzlibrary{arrows}
\usetikzlibrary{decorations}
\usetikzlibrary{shapes.symbols}
\usetikzlibrary{shapes.geometric}
\usetikzlibrary{shapes.multipart}
\usetikzlibrary{positioning}
\usetikzlibrary{patterns}
\usetikzlibrary{calc}
\usetikzlibrary{scopes} % cf. pgfmanual p.66
\usetikzlibrary{chains} % cf. pgfmanual p.284
\usetikzlibrary{fit}
\usetikzlibrary{matrix}
\usetikzlibrary{decorations}
\usetikzlibrary{circuits.logic}
\usetikzlibrary{circuits.logic.IEC}
\usetikzlibrary{shapes.gates.logic.IEC}
\usetikzlibrary{circuits.logic.US}
\usetikzlibrary{shapes.gates.logic.US}
\usetikzlibrary{circuits.ee}
\usetikzlibrary{circuits.ee.IEC}
\usetikzlibrary{backgrounds}
\usetikzlibrary{automata}
\usetikzlibrary{intersections}
\usetikzlibrary{plotmarks}
\usepgflibrary{fpu}
\usetikzlibrary{decorations.pathreplacing}
\usepackage[figurename=Fig.]{caption} %Fig.: statt Figure:
\hfuzz=1pt %ignoriere horizontalen Überstand 0-1pt und gib keine Warnung aus
\usepackage{chngcntr} %Vertikales padding für Tabellen global
\setlength{\parskip}{0.3cm plus0.1cm minus 0.1cm} %Vertikales padding für Absätze
%\counterwithin{table}{section} %1.1, 1.2 usw. für Tabellen und Abbildungen
%\counterwithin{figure}{section}
\renewcommand{\arraystretch}{1,5}
\floatsetup[subfigure]{style=plain,heightadjust=object,
capbesideposition={left,top},capbesidesep=space}
\newcommand{\?}{\ensuremath{^\texttt{\textbf [CITATION~NEEDED]}}}
\newcommand\blankpage{%
\null
\thispagestyle{empty}%
\addtocounter{page}{-1}%
\newpage}
\setcounter{tocdepth}{2} %remove subsubsection from table of content
%hier werden die pdf-infos gesetzt
\hypersetup{pdfinfo={
Title={FPGA-Accelerated Image Super Resolution Convolutional Neural Network},
Author={Jakob Essbüchl, Philipp Lehninger, Benedikt Morgenbesser}
}}
% -----------------------------------------------------------------
\begin{document}
\begin{titlepage}
\begin{center}
%%
% title block
%%
\vspace*{1.5cm}
\huge
\textsc{{FPGA-Accelerated Image Super Resolution Convolutional Neural Network}}\\
\vspace*{1cm}
%%
% author block
%%
\vspace{2cm}
\Large
\textsc{Report}\\
{\normalsize \textsc{by}}\\
\textsc{Jakob Essbüchl} {\normalsize \textsc{01129145}}\\
\textsc{Philipp Lehninger} {\normalsize \textsc{01327039}}\\
\textsc{Benedikt Morgenbesser} {\normalsize \textsc{01027440}}\\
%%
% hand-over block
%%
\vspace{6.5cm}
\textsc{\today}\\
%%
% university block
%%
\vspace{1cm}
\textsc{Vienna University of Technology}\\
{\normalsize \textsc{Institute of Computer Technology}}\\
\end{center}
%\afterpage{\blankpage}
\end{titlepage}
\clearpage
\section*{Abstract}
\setcounter{page}{1}
\pagenumbering{Roman}
This project is part of the course System on Chip Design Lab at the Technical University of Vienna. The defined goal was to implement a convolutional neural network (CNN) as a form of digital signal processor (DSP) on a field-programmable gate array (FPGA). After this, a second DSP utilising approximate computing should be designed and both designs should be compared.
The neural network implements a Super Resolution (SR) algorithm for upscaling images. The chosen algorithm is simply called \emph{Super Resolution Convolutional Neural Network (SRCNN)} \cite{dong2015image}. To achieve the stated goal, the following was done in order:
\begin{enumerate}
\item Implement the neural network in PyTorch to train the network and gain weights for it's nodes.
\item Implement the neural network in NumPy to improve understanding of the algorithm and remove PyTorch dependency.
\item Implement the convolutions in C and wrap them in Python to allow acceleration on the FPGA.
\item Implement parts of the convolutions in the FPGA using VHDL to accelerate the upscaling operation.
\begin{enumerate}
\item One implementation works with any image size but is slower than the purely CPU-run variant without FPGA acceleration.
\item A second implementation is much faster than the CPU-run variant but is limited in image size.
\end{enumerate}
\item \label{enum:approxDsp} \textit{Create and implement an approximate DSP version of the neural network.}
\item \label{enum:approxComp} \textit{Compare both approaches (accurate and approximate) in image quality, performance, area, etc.}
\end{enumerate}
Because of time constraints \cref{enum:approxDsp,enum:approxComp} could not be completed before the deadline. Unfortunately there is an unsolved bug in the FPGA implementation that makes using larger images impossible. Before that had been solved continuing with the approximate design was not warranted.
Our implementation creates images with good image quality metrics in respect to the algorithms compared in the original paper \cite{dong2015image}. In two metrics (SSIM and MSSSIM) it's the best of the compared papers while in three others (PSNR, IFC and NQM) it's in the better half.
As mentioned in the roadmap one FPGA implementation was actually slower than without FPGA acceleration while the other implementation was much faster (over 22 times).
\newpage
\tableofcontents
\clearpage
\section{Introduction}
\setcounter{page}{1}
\pagenumbering{arabic}
\subsection{Single Image Super-Resolution}
\label{sec:SR}
The aim of single image super-resolution (SR) is to recover a high-resolution (HR) image from a single low-resolution (LR) image. HR images are required in a lot of different applications. For example in medical imaging, satellite imaging, high-definition television (HDTV) etc. The problem of up-scaling images is underdetermined: For any low-resolution pixel a variety of different solutions exist. The resolution space has to be constrained to deal with that fact. To do so, prior information is needed. Approaches to get this information can be categorised in four types: prediction models, edge-based methods, image statistical methods and example-based methods. Internal example-based methods exploit the self similarity property. Exemplar patches are generated from the input image. For external example-based methods a mapping between LR \& HR patches is taught from external data-sets. The majority of SR algorithms focus on grey-scale or single-channel image super-resolution. To get a coloured image from a single-channel image SR the YCbCr colour space can be used. (See section \ref{sec:YCbCr}.) An example for single image super resolution is shown in figure \ref{fig:superres}. \cite{abd2012image}
\begin{figure}[H]
\centering
\includegraphics[width=0.5\textwidth]{fig/superresolution.PNG}
\caption{Example for a single image super-resolution recovery}
\label{fig:superres}
\end{figure}
\subsection{YCbCr}
\label{sec:YCbCr}
In the YCbCr colour space the image is decomposed into three channels: \textit{luminance (Y), blue-difference chroma (Cb)} \& \textit{red-difference chroma (Cr)}. Figure \ref{fig:ycbcr} shows an image and the associated channels in the YCbCr colour space. The human eye is much more sensitive to changes in luminance than to changes in the chroma channels. Therefore, it is sufficient to apply super-resolution only on the luminance channel, while using computationally cheap methods like bicubic interpolation on the chroma channels to get convincing high-resolution results.
\begin{figure}[H]
\centering
\includegraphics[width=0.9\textwidth]{fig/ycbcrhorizontal.png}
\caption{YCbCr image and channel decomposition. From left to right: Original image, Luminance (Y), Chroma blue (Cb) Chroma red (Cr). Adapted from: \cite{wiki:ycbcr}.}
\label{fig:ycbcr}
\end{figure}
\subsection{Neural Networks}
\label{sec:NN}
Neural networks (NNs) are tools used for efficient optimization. NNs are structures to simulate the method of human thinking based on neurons and activation functions. These massively parallel working networks are designed, similar to the human brain, to store information in the form of patterns. NNs are well suited for image processing.
\subsection{SRCNN}
\label{sec:SRCNN}
For image super-resolution a deep convolutional neural network (SRCNN) can be used as described in \cite{}. With this approach a direct end-to-end mapping between a low resolution input image and a high resolution output image is implemented. The only preprocessing step needed for the SRCNN is to upscale the input image to a desired size. This can be done by bicubic interpolation. Thus the \enquote{low-resolution} input image for the neural network has already the same size as the output image. In this context the terms \enquote{low- \& high-resolution} actually refer to the image quality and not the image size. The goal of the CNN is to recover an image \textbf{X} from the input image \textbf{Y} that is as similar as possible to the ground truth. (The ground truth is the ideal solution). The mapping F(\textbf{Y}) consists of three operations: \textit{Patch extraction and representation}, \textit{non-linear mapping}, and \textit{reconstruction}. These operations form the convolutional neural network as shown in figure \ref{fig:SRCNN}. The purposes of the three steps are:
\begin{enumerate}
\item \textbf{Patch extraction and representation:} \newline Patches from the LR input image are extracted in this step. For each patch a high-dimensional vector that comprises a set of \textit{n\textsubscript{1}} feature maps is generated. For a single channel input image this layer gives a \textit{n\textsubscript{1}} channel output.
\item \textbf{Non-linear mapping:} \newline In this layer the high-dimensional vectors from layer 1 are non-linearly mapped onto other \textit{n\textsubscript{2}}-dimensional vectors. Conceptually, each of these \textit{n\textsubscript{2}} vectors represent now a high-resolution patch.
\item \textbf{Reconstruction:} \newline In the last layer the final image is reconstructed from the high-resolution, patch-wise representation from layer 2. The output of this layer is the single channel, high resolution image that ideally fits the ground truth.
\end{enumerate}
Although the layers comprise of apparently different operations they lead to the same form as convolutional layers. The filtering weights and biases of the CNN are subject to optimisation by training. \cite{dong2015image}.
\begin{figure}[H]
\centering
\includegraphics[width=\textwidth]{fig/srcnn.pdf}
\caption{Convolutional layers of the SRCNN. Source: \cite{dong2015image}.}
\label{fig:SRCNN}
\end{figure}
An example for a SR image is shown in figure \ref{fig:srexample}. The right-most image is the ground truth, i.e. the ideal solution. The image on the left side was upscaled with a simple bicubic interpolation. In the centre the output of the super-resolution deep convolutianal network is shown.
\begin{figure}[!hbt]
\centering
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/butterfly_GT}
\caption{Ground truth}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/butterfly_bicubic_x3}
\caption{Bicubic interpolation x3}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/butterfly_srcnn_x3}
\caption{SRCNN x3}
\end{subfigure}
\caption{Comparison of ground truth, bicubic interpolation and SRCNN.}
\label{fig:srexample}
\end{figure}
\newpage
\section{Implementations}
\label{sec:Implementation}
Three implementations using different Python modules and sometimes different hardware were done and will be described in the following sections.
All three implementations follow the same general program structure:
\begin{enumerate}
\item Load weights \& biases
\item Open image
\item Downsize image to the closest multiple of the chosen scale factor. This becomes the \emph{ground truth image (GT)} used as a comparison with the upscaled images.
\item Downsize the GT image by using the chosen scale factor.
\item Upscale the downsized image by the chosen scale factor using bicubic interpolation. This is the \emph{bicubic interpolation image}.
\item Convert the image from RGB colour space to YCbCr colour space, extract the Y channel and scale the pixel values from 0-255 to 0-1.
\item Upscale the Y channel by the chosen scale factor using the neural network. Roughly speaking this means calculating a lot of 2D convolutions which themselves consist of a lot of multiplications and additions.
\item Scale the pixel values back from 0-1 to 0-255
\item Combine the Y channel with the Cb and Cr channels from before and save the image. This is the upscaled \emph{SRCNN image}.
\item Calculate the image metrics PSNR and SSIM as well as execution time.
\end{enumerate}
\subsection{PyTorch}
\label{sec:Torch}
For the first implementation of the SRCNN PyTorch was used. PyTorch is an open-source machine learning library that allows an easy and efficient implementation of neural networks. A key feature of PyTorch is that calculations can be accelerated using the CUDA Cores of Nvidia GPUs. However, there are two main drawbacks:
First, most of the calculations when upscaling an image happen inside the functions of the PyTorch library. In this way it acts similarly to a black box. This would not allow accelerating parts of the calculations on the FPGA since there is no easy access. While possible in theory it would mean reading into and understanding the inner workings of the very complex PyTorch library.
Secondly, PyTorch is a large library with a size of several GB and does not offer builds for ARM CPUs, which the ZedBoard is using. This would require building the whole library on the ZedBoard itself which would take hours due to the slow CPU and is prone to errors because of missing dependencies.
In the end PyTorch was used not only as a first implementation, but also for playing around with different network sizes, training the network and extracting weights and biases to use with the other two implementations.
\subsection{NumPy}
\label{sec:Numpy}
Since PyTorch is such a large library and the convolution calculations are hidden inside the library functions it wasn't feasible to use it together with FPGA acceleration. Easiest access to the FPGA hardware would be with pure C code but we wanted to keep as much of code in python as possible to make development easier and faster.
Thus, the decision was made to remove the PyTorch dependency and try to implement the convolutions in NumPy. This was both for understanding how to actually \enquote{manually} calculate the two-dimensional convolutions as well as serve as a stepping stone to the FPGA hardware. The plan was to possibly port the large amount of multiplications that the convolutions consist off over to C and go from there to the FPGA hardware.
In practice it turned out that the NumPy implementation was \emph{very} slow. An image that took about 3 seconds in PyTorch took 14 minutes in NumPy (see Table~\ref{tab:exetime}). Part of this is because of for loops which are notoriously slow in Python. Of four nested for loops, two could be removed by utilising NumPy's vectorised operations. These are executed in heavily optimised C (which NumPy is mostly written in in the back-end). Two loops remained nonetheless and are probably the root cause for the slow execution time.
This implementation could likely be optimised much further, but since we needed to switch to C anyway we decided to leave it as is.
\subsection{Cython}
\label{sec:cython}
The Cython implementation is a direct derivative of the NumPy implementation. The 2D convolutions were completely rewritten in C while NumPy was kept for type conversions and scaling of pixel values prior to and after the convolutions. The convolutions are imported into the python code as an external library using the ctypes module.
All of the convolution operations as well as weights and biases were converted from 32-bit floating point number format to 32-bit Q6.26 fixed-point integer format. This was done because it's much easier to implement fixed-point arithmetic in the FPGA compared to floating point arithmetic. Also, with pixel values originally having 256 possible values between 0 and 255, there is not much dynamic range needed, making a fixed-point implementation a good fit.
The Cython implementation has three sub-implementations:
\begin{enumerate}
\item All calculations run on the CPU, single-threaded
\item 2D Convolutions run on the FPGA, the rest runs on the CPU. Works with any image size but is slow (referred to as FPGA1)
\item Several improvements upon 2. Only works with images up to a certain size but is much faster (referred to as FPGA2)
\end{enumerate}
These will be described in detail in the following section.
Both implementations with HDL designs on the FPGA fill the streams to the FPGA concurrently with child processes.
\subsection{FPGA Implementations}
\label{sec:fpgaimpl}
\subsubsection{Number Representation}
The data written to and read from the design on the FPGA is in the 32-bit Q6.26 fixed point format. This means that the last 26 bits are fractal digits whereas the highest 6 bits represent an integer. Note that the MSB is a sign bit, negative values are expressed in two's complement.
The C code accessing the hardware and the pure software implementation (Cython) also use this number representation, the Python script converts all floating point numbers to 32-bit Q6.26 fixed point representations.
\subsubsection{General Overview}
The core task of the hardware design is to apply a kernel multiplication to a selected image/feature patch.
Therefore, the patch and kernel data pairs have to be acquired concurrently via two separate streams.
The kernel multiplication multiplies each kernel value with its corresponding value from the patch, the results are accumulated to one pixel value.
For example, the kernel multiplication of a 5x5 kernel (kernel size 5) with a 5x5 patch will execute 25 fixed point multiplications, add the products up and yield one fixed point number.
This behaviour is described in the VHDL file \emph{patch\_mult.vhdl}.
The main difference between the two HDL implementations is,
that the \emph{patch\_mul\allowbreak ti\allowbreak plier\_pipe\allowbreak line}, also referred to as \enquote{FPGA Implementation 1}, just performs this kernel multiplication, however, the second HDL design (\emph{fea\allowbreak ture\_convo\allowbreak lution\_pipe\allowbreak line}, \enquote{FPGA Implementation 2}), also has to do the patch selection and the padding at the edges of the feature/image.
\subsubsection{FPGA Implementation 1}
\label{sec:fpgaimpl1}
The first FPGA implementation reads patch and kernel data from two separate FIFOs which are filled by two separate asynchronous Xillybus streams (xillybus\_write\_patch\_32 and xillybus\_write\_kernel\_32).
As the basic Xillybus IP core, that is contained in the basic xillydemo project has only one 32-bit write stream (downstream, CPU to FPGA), a custom Xillybus IP Core had to be generated.
The relevant interfaces of this custom IP core are:
\begin{itemize}
\item xillybus\_write\_patch\_32: 32-bit asynchronous stream for patch data
\item xillybus\_write\_kernel\_32: 32-bit asynchronous stream for kernel data
\item xillybus\_read\_32: 32-bit asynchronous stream reading back the results
\end{itemize}
The multiplier has been generated via the Vivado IP Catalog.
It has two pipeline stages and a Clock-Enable pin for stall functionality.
This IP Core is configured to use the integrated multipliers on the FPGA instead of LUTs.
A combinatorial adder and a register form the accumulator and therefore the third pipeline stage of the \emph{patch\_mult} entity.
The output is ready, when a counter has counted through all kernel entries.
The result of the kernel multiplications is written into a FIFO that is connected to the output stream.
All three FIFOs are single-clock non-FWFT (First Word Fall Through) 32-bit FIFOS with a depth of 512 values.
\subsubsection{FPGA Implementation 2}
\label{sec:fpgaimpl2}
The second implementation contains several improvements.
At first, a new custom Xillybus IP core has been generated:
\begin{itemize}
\item xillybus\_config: 32-bit synchronous stream for storing config data
\item xillybus\_command: 8-bit synchronous stream for control flow commands
\item xillybus\_write\_feature\_32: 32-bit asynchronous stream for feature data
\item xillybus\_write\_kernel\_32: 32-bit asynchronous stream for kernel data
\item xillybus\_read\_32: 32-bit asynchronous stream reading back the results
\end{itemize}
The config stream allows to set the height and width of the image, which is a requirement to be able to write a whole feature instead of patches to the FPGA logic. This is necessary because the logic design has to iterate through all pixel positions of a feature and do the patch extraction by itself.
Moreover, the kernel size is not a VHDL generic anymore but can also be set via the config stream.
The feature and kernel data is still acquired via two separate asynchronous streams, however, the data is not written into FIFOs but into BRAM.
For the patch extraction and padding logic the data has to be addressable and accessible multiple times.
Counters calculate the addresses and check if a whole feature and kernel have been written. When all necessary data is present, the convolution of this one feature can start.
As for padding the read addresses of the feature RAM have to be altered and multiplications in address calculations have to be avoided in general, so the address calculation is non-trivial and surely the most complex part of this hardware implementation.
The patch extraction logic will yield a value of a patch and its corresponding kernel value from the memory and pass these two values to the \emph{patch\_mult} entity from the first implementation.
The results will again be written into an output FIFO.
These changes promise a faster execution but also lead to new limitations:
\begin{itemize}
\item memory capacities limit the maximum size of features and kernels
\item data flow is more sporadic, DMA buffers have to be flushed regularly
\item synchronization of hardware accesses gets a bit more complicated
\end{itemize}
To enable to send control commands to the hardware the synchronous 8-bit command stream has been added to the Xillybus IP core.
In the current implementation it has been used to skip feature re-transmissions.
Thereby, the loops for output and input channels can be interchanged in the software and each feature has to be sent only once.
The idea was, that the software can send a skip command instead of re-sending the whole feature.
However, this functionality still has synchronisation problems and the resulting images are damaged (refer to Section~\ref{sec:bug} for details).
\newpage
\section{Development platform}
\label{sec:fpga}
\subsection{ZedBoard}
\label{sec:zedboard}
For this project a ZedBoard development board was used. It includes the Zynq\textregistered-7000 All Programmable SoC with a programmable logic and an ARM\textregistered-based processing system. The Ethernet port was used for communication via SSH. The SD card includes the boot files and the Linux file-system of the embedded Xillinux. A photo of the board is shown in figure \ref{fig:zedboard}.
\begin{figure}[H]
\centering
\includegraphics[width=0.5\textwidth]{fig/ZedBoard.png}
\caption{The ZedBoard development board. Source: \cite{zedboard}.}
\label{fig:zedboard}
\end{figure}
\subsection{Xillinux}
\label{sec:xillinux}
Xillinux is a Linux distribution for different FPGA boards including the ZedBoard. It is based upon Ubuntu LTS 16.04 for ARM. The embedded OS uses the SD card as hard disk and supports plug \& play for various devices, like a USB mouse or keyboard. Xillinux also provides a graphical user interface. A computer screen can be connected via VGA or HDMI. The relevant software can be downloaded from: \hyperlink{http://xillybus.com/xillinux}{http://xillybus.com/xillinux}. It includes an SD card image for the operating system and a boot partition kit. An introduction on how to build Xillinux (generate bitstream, load SD image..) is given in the \hyperlink{http://xillybus.com/downloads/doc/xillybus_getting_started_zynq.pdf}{Getting started with Xillinux for Zynq-7000} document.
\newpage
\subsection{Xillybus IP}
\label{sec:xilibusip}
For the data transport between Xillinux and the FPGA Xillybus IP cores were used. Xillybus consists of an FPGA IP core and a Linux driver. Xillybus uses direct memory access (DMA) and the AXI bus. The communication between the user application and the IP core happens through standard FIFO's and BRAM. A custom Xillybus IP core can be configured in the \hyperlink{http://xillybus.com/ipfactory/}{IP core factory}. A simplified block diagram for the Xillybus IP core is shown in figure \ref{fig:xillibus}.
\begin{figure}[H]
\centering
\includegraphics[width=\textwidth]{fig/xillybus.png}
\caption{Simplified block diagram for the Xillybus IP core. Adapted from: \cite{xillibus}.}
\label{fig:xillibus}
\end{figure}
Note: Xillinux and Xillybus have several license variants. A no-fee educational license is granted for student projects. The free license is only applicable, if no commercial interest is followed.
\newpage
\section{Evaluation - Image Quality}
\label{sec:imqual}
For the evaluation of the quality of the upscaled image, the result has to be compared with the ground truth. The ground truth is the ideal solution. For a real world usage scenario the ground truth is naturally not known. To evaluate the performance of the algorithm, the original image is sampled down. The LR image is then used as input. The original image acts as ground truth and can be compared with the output image. Both scenarios are illustrated in figure \ref{fig:gt}.
\begin{figure}[H]
\centering
\includegraphics[width=0.9\textwidth]{fig/comparison}
\caption{Left: Real world usage scenario. An input image is fed to the network and upscaled. Right: The original image acts as ground truth. The image is scaled down and up again.}
\label{fig:gt}
\end{figure}
\subsection{Metrics}
\label{sec:metrics}
There are different metrics to evaluate the difference between ground truth and output image. The two most important metrics are PSNR and SSIM. The approaches are described in section \ref{sec:PSNR} \& \ref{sec:ssim}. Other metrics used to evaluate the image quality are discussed in section \ref{sec:othermetrics}.
\subsubsection{PSNR}
\label{sec:PSNR}
The peak signal to noise ratio (PSNR) between two images can be used as a straightforward image quality measure. The ratio in dB can be computed using equation \ref{eq:PSNR}.
\begin{equation}
PSNR = 10 \cdot log_{10}\Big(\frac{R^2}{MSE}\Big)
\label{eq:PSNR}
\end{equation}\newline
$R$ is the maximum fluctuation of the input image data type. Hence, for a pixel value between 0 and 255 $R = 255$. $MSE$ is the mean squared error between the ground truth and the output image. For $M$ rows and $N$ columns the $MSE$ can be calculated as seen in equation \ref{eq:MSE}.
\begin{equation}
MSE = \frac{\sum_{M,N}[I_1(m,n)-I_2(m,n)]^2}{M \cdot N}
\label{eq:MSE}
\end{equation}
Colour images are usually converted to the YCbCr space and the PSNR is calculated for the luminance channel. (See section \ref{fig:ycbcr}). Naturally, a high PSNR is desired. \cite{PSNR}
\subsubsection{SSIM}
\label{sec:ssim}
The structural similarity index (SSIM) was developed as an improved image quality measure. While the PSNR calculates the absolute deviation between two images, SSIM is a method that also takes the human perception into account. The SSIM combines three components, a luminance comparison ($l$), a contrast comparison ($c$) and a structure comparison ($s$). (see equation \ref{eq:components}). The relative importance of the terms can be set with the parameters: $\alpha,\,\beta\,\&\,\gamma$. The variables $x\,\&\,y$ refer to the two images.
\begin{equation}
SSIM(x,y) = [l(x,y)]^\alpha \cdot [c(x,y)]^\beta \cdot [s(x,y)]^\gamma
\label{eq:components}
\end{equation}
In \cite{ssim} the formula for the structural similarity index is derived to equation \ref{eq:ssim}. With the average value $\mu$ and the variance $\sigma$ of the images. The coefficients $C_1\,\&\,C_2$ serve as stabiliser for a small denominator.
\begin{equation}
SSIM(x,y) = \frac{(2\mu_x\mu_y + C_1)(2\sigma_{xy} + C_2)}{(\mu_x^2 + \mu_y^2 + C_1)(\sigma_x^2+\sigma_y^2+C_2)}
\label{eq:ssim}
\end{equation}
The structural similarity index ranges from 0 to 1. A SSIM of 1 implies two identical images, a SSIM of 0 two complete different ones. \cite{ssim}
\subsubsection{Other Metrics}
\label{sec:othermetrics}
Other metrics used to compare the image quality are MSSSIM, IFC \& NQM.
\begin{enumerate}
\item The multi-scale structural similarity index (MSSSIM) is a more advanced form of the structural similarity index. The method incorporates details of the image at different resolutions. The image is therefore iteratively low-pass filtered and downsampled. The MSSSIM index is a combination of the measures at these different scales. The optimal coincidence is given by a MSSSIM index of 1. \cite{MSSSIM}
\item The information fidelity criterion (IFC) analyses the image fidelity in an information-theoretical framework. The mutual information between the input (ground truth) and the output (upscaled image) is quantified statistically. A higher score indicates a better similarity. \cite{IFC}
\item The noise quality measure (NQM) takes variation in contrast sensitivity, variation in the local luminance mean, contrast interaction between spatial frequencies and contrast masking effects into account. The NQM assesses additive noise in images. It is given in dB. \cite{NQM}
\end{enumerate}
\subsection{Results}
\label{sec:imqualresults}
Table \ref{tab:qualresults} compares the different metrics for the image quality of our SRCNN implementation, with the one from \cite{dong2015image}, the bicubic interpolation and various other image enhancing algorithms. These are:
\begin{enumerate}
\item \textit{SC} - sparse coding based method \cite{SC},
\item \textit{NE+LLE} - neighbour embedding + locally linear embedding method \cite{NELLE},
\item \textit{KK} - A method developed by Kim, K.I. and Kwon, Y. \cite{KK},
\item \textit{ANR} - Anchored Neighbourhood Regression method \cite{ANR}, and
\item \textit{A+} - Adjusted Anchored Neighbourhood Regression method \cite{A+}.
\end{enumerate}
The values in table \ref{tab:qualresults} are the average values for the images from the Set5 dataset. The set of images is attached in Appendix \ref{Appendix:set5}, the individual scores are listed in Appendix \ref{Appendix:tables}. For IFC \& NQM the A+ algorithm shows the best results. The SRCNN implementation by Dong shows the best PSNR. Our implementation of the SRCNN achieves the best index for SSIM. For MSSSIM these three approaches share the highest achieved score. The relative improvement of the SRCNN compared to a bicubic interpolation is shown in table \ref{tab:improvement}.
The results confirm the qualitative impression that the algorithm performs in particular well with images with sharp edges as it is the case in the \enquote{butterfly.bmp} (figure \ref{fig:set5imagesI}) image. For images that consist mostly of lightly textured surfaces like the \enquote{baby.bmp} (figure \ref{fig:set5imagesII}) the improvement is smaller.
\begin{table}
\centering
\caption{The average results of PSNR (dB), SSIM, IFC, NQM (dB), and MSSSIM on the Set5 dataset.}
\label{tab:qualresults}
\begin{tabular}{lcccccccc}
\toprule
\begin{tabular}[c]{@{}c@{}}Metric\\\,\end{tabular} & \begin{tabular}[c]{@{}c@{}}Bicubic\\\,\end{tabular} & \begin{tabular}[c]{@{}c@{}}SC\\\cite{SC}\end{tabular} & \begin{tabular}[c]{@{}c@{}}NE+LLE\\\cite{NELLE}\end{tabular} & \begin{tabular}[c]{@{}c@{}}KK\\\cite{KK}\end{tabular} & \begin{tabular}[c]{@{}c@{}}ANR\\\cite{ANR}\end{tabular} & \begin{tabular}[c]{@{}c@{}}A+\\\cite{A+}\end{tabular} & \begin{tabular}[c]{@{}c@{}}SRCNN\\(Dong) \cite{dong2015image}\end{tabular} & \begin{tabular}[c]{@{}c@{}}SRCNN\\(Ours)\end{tabular} \\
\hline
PSNR & 29.56 & 31.42 & 31.84 & 32.28 & 31.92 & 32.59 & \textbf{32.75} & 31.92\\
SSIM & 0.871 & 0.882 & 0.896 & 0.903 & 0.897 & 0.909 & 0.909 & \textbf{0.913}\\
IFC & 3.49 & 3.16 & 4.40 & 4.14 & 4.52 & \textbf{4.84} & 4.58 & 4.41\\
NQM & 27.93 & 27.29 & 32.77 & 32.10 & 33.10 & \textbf{34.48} & 33.21 & 33.04\\
MSSSIM & 0.975 & 0.980 & 0.984 & 0.985 & 0.984 & \textbf{0.987} & \textbf{0.987} & \textbf{0.987}\\
\bottomrule
\end{tabular}
\end{table}
\begin{table}
\centering
\caption{Relative improvement of image quality metrics between SRCNN and bicubic interpolation.}
\label{tab:improvement}
\begin{tabular}{lccccc}
\toprule
Metric & baby.bmp & bird.bmp & butterfly.bmp & head.bmp & woman.bmp \\
\hline
PSNR & 39\,\% & 88\,\% & 149\,\% & 25\,\% & 86\,\% \\
SSIM & 2\,\% & 3\,\% & 11\,\% & 3\,\% & 5\,\% \\
IFC & 15\,\% & 25\,\% & 46\,\% & 16\,\% & 29\,\% \\
NQM & -3\,\% & 343\,\% & 412\,\% & 257\,\% & 361\,\% \\
MSSSIM & 0.7\,\% & 0.9\,\% & 2.1\,\% & 0.9\,\% & 1.3\,\% \\
\hline
Average & 11\,\% & 92\,\% & 124\,\% & 60\,\% & 97\,\% \\
\bottomrule
\end{tabular}
\end{table}
\clearpage
\section{Evaluation - Execution Time}
Besides the image quality, the execution time was also investigated. The different implementations of the SRCNN are compared in table \ref{tab:exetime}. The measurement of the execution time is done in Python. The basis for the execution times are the original (\enquote{butterfly.bmp}) image from the Set5 dataset (256\,x\,256\,px size) and smaller version (99\,x\,99\,px size) of the same image.
\subsection{Results}
Table \ref{tab:exetime} shows execution time for the different implementations of the SRCNN for the two image sizes. A visualization of this data is shown in figure \ref{fig.exectime}. As expected, the PyTorch-based algorithm shows the best performance. This is because calculations are accelerated on the GPU. PyTorch is an optimised library and the utilised hardware is much faster than the one on the ZedBoard. The second fastest execution time is achieved by the FPGA2 implementation which shows the acceleration potential of specialised hardware. It is over 22 times faster than the pure CPU variant running on the ZedBoard.
Even with the strong desktop hardware, the NumPy implementation is very slow (up to 350 times slower than GPU-accelerated PyTorch and up to 33 times slower than the purely CPU-using C variant). This is due to the inefficient implementation and could be vastly improved, as discussed in section~\ref{sec:Numpy}.
Implementations with very short execution times (PyTorch and Cython on the desktop CPU) show very little difference in execution times between image sizes. This is because of (mostly) static set up times. The program does not only measure the time the 2D convolutions take but also all of the prior and subsequent actions of the program. These change very little to not at all between image sizes and implementations.
\clearpage
\begin{table}[H]
\centering
\caption{Execution times for a 256\,x\,256\,px \& a 99\,x\,99\,px image \enquote{butterfly.bmp}.\vspace{2mm}\\
The FPGA2 implementation does not have an execution time for the 256\,x\,256\,px sized image because of an unsolved bug with larger images. For details on this bug see section~\ref{sec:bug}.}
\label{tab:exetime}
\begin{tabular}{llcccc}
\toprule
& & \multicolumn{4}{c}{Execution time} \\
& & \multicolumn{2}{c}{256\,x\,256\,px} & \multicolumn{2}{c}{99\,x\,99\,px} \\\cmidrule(r){3-4} \cmidrule(){5-6}
Implementation & Device & s & min & s & min \\
\midrule
PyTorch (CPU \& GPU) & Desktop\tablefootnote{CPU: Intel Core i5-8400 2.80GHz GPU: Nvidia Geforce GTX 1070TI} & 2.64 & 0.04 & 2.43 & 0.04 \\
NumPy (CPU) & Desktop & 924 & 14.4 & 559 & 9.3 \\
Cython (CPU) & Desktop & 29 & 0.5 & 17 & 0.3 \\
Cython (CPU) & ZedBoard\tablefootnote{CPU: Zynq-7000 SoC XC7Z020-CLG484-1; Dual ARM Cortex-A9 MPCore 667 MHz} & 631 & 10.5 & 195 & 3.2 \\
Cython (FPGA 1) & ZedBoard & 1413 & 23.6 & 227 & 3.8 \\
Cython (FPGA 2) & ZedBoard & N/A & N/A & 8.67 & 0.14 \\
\bottomrule
\end{tabular}
\end{table}
\begin{figure}[H]
\centering
\includestandalone[scale=1]{fig/execTimesChart}
\caption{Visualization of the execution times in seconds of table~\ref{tab:exetime}.}
\label{fig.exectime}
\end{figure}
\newpage
\section{Evaluation - Space}
\begin{table}[H]
\centering
\caption{Resource utilization of the FPGA for FPGA implementation 1 \& 2.}
\label{tab:util}
\begin{tabular}{lrrSrS}
\toprule
& \multicolumn{1}{l}{} & \multicolumn{2}{c}{FPGA1} & \multicolumn{2}{c}{FPGA2} \\
\cmidrule(r){3-4}\cmidrule(){5-6}
Resource & Available & \multicolumn{1}{l}{Utilization} & \% & \multicolumn{1}{l}{Utilization} & \% \\
\midrule
LUT & 53200 & 3484 & 6.6 & 4233 & 8.0 \\
LUTRAM & 17400 & 271 & 1.6 & 233 & 1.3 \\
FF & 106400 & 3927 & 3.7 & 4191 & 3.9 \\
BRAM & 140 & 4 & 2.9 & 100 & 71.1 \\
DSP & 220 & 4 & 1.8 & 4 & 1.8 \\
IO & 200 & 81 & 40.5 & 81 & 40.5 \\
BUFG & 32 & 2 & 6.3 & 2 & 6.3 \\
PLL & 4 & 1 & 25.0 & 1 & 25.0 \\
\bottomrule
\end{tabular}
\end{table}
\begin{figure}[H]
\centering
\includestandalone[scale=1]{fig/spaceChart}
\caption{Visualization of the resource utilization of the FPGA in \% of available space.}
\label{fig.util}
\end{figure}
\clearpage
\section{Discussion}
\subsection{Image Quality}
As seen in table \ref{tab:qualresults} our implementation of the SRCNN shows good results with regard to the quality of the upscaled image. The implementation achieves the highest score for two of the five metrics, SSIM and MSSIM (for a detailed look refer to section~\ref{sec:imqual}. The algorithm is particularly suitable for images with hard edges. With textured surfaces it only gets a small qualitative improvement over bicubic interpolation. To achieve better results in this area, a larger and much more complex neural network would be needed.
The largest relative improvement compared to bicubic interpolation is achieved for the butterfly image (see table \ref{tab:improvement}). The butterfly (see figure \ref{fig:set5imagesI}) has a lot of sharp edges which suits the algorithm. The improvement is less visible for example for the image of the baby (see figure \ref{fig:set5imagesII}), an image where the relatively untextured skin dominates. The lack of edges and structure naturally results in a lack of features for the algorithm.
\subsection{Thoughts on Parallelization}
The idea to accelerate the image convolution with a large amount of hardware multipliers soon turned out to be very difficult to implement. The main problem is that the data arrives sequentially on the FPGA design, therefore the design tends to be pipelined but not fully parallel.
Multi-port RAM would allow to partially parallelize the design, but eventually only dual-port RAM could be implemented with the on-chip BRAM.\\
It is possible to get more ports if some identical RAM blocks are mirrored, but this multiplies the amount of used BRAM and the limitation on the maximum achievable image sizes is hard enough.
As all multiplications of a kernel multiplication have to be accumulated, the accumulator would become the bottleneck. A tree of adders, like a \emph{Wallace Tree Adder} \cite{sharma2016design}, would be a possibility to optimise such a design, so that it could make use of parallel multiplications.
With the use of dual-port BRAM, the throughput of the HDL design could theoretically be nearly doubled, however, it has to be considered that also the complexity of the patch extraction and padding logic would increase significantly.
\newpage
\subsection{Thoughts on Approximation}
As the second FPGA implementation has been added at a very late stage of this project and still has some bugs, approximation of the multiplier or the accumulator has not been considered anymore.
The whole design runs with the 100 MHz bus\_clk of the Xillybus IP core.
Therefore, a speed-up of either of those logic blocks would only be interesting, if clock cycles / pipeline stages could be saved, but not in order to increase the possible maximum clock frequency.
For the multiplier, the target for an approximated version would have to be to fit in just one pipeline stage.
In case of the adder, only the speed-up of an adder tree (e.g. Wallace tree adder \cite{sharma2016design}) would make sense, this would require an at least partially parallelized design reading the data for the pipeline from multi-port RAM.
Therefore, future work could include a check if a dual-read-port BRAM is applicable and then possibly the approximation of an adder tree.
Another thing to consider is whether to approximate globally or just parts of the calculations. While global approximation would yield the largest possible time/area savings the detrimental effect on image quality might be too strong. A compromise would be to not approximate but there, where approximation errors have the smallest impact on image quality. Of course this introduces a lot of additional complexity into development and it's questionable whether it's worth the effort.
\subsection{Limitations and Solutions}
Especially the second FPGA implementation seems to be promising, but has still some bugs or rather room for optimisation. Bugs and ideas for improvements are listed here:
\subsubsection{Dark image bug}
\label{sec:bug}
When running the FPGA2 implementation on images with sizes above a certain size (more than 99x99 pixels but less than 256x256 pixels), the resulting images will be extremely dark. The original image is still recognisable but colours are shifted. Very bright spots turn completely black.
After this bug has occurred once, all future results will show this bug, even if the image size is small. A system reboot will be necessary to get correct results again.
Up to now, it has not been determined from where this problem originates from. It's not even clear if it's a software memory bug or a bug of the HDL implementation.
This bug is the reason why no execution speed for the 256x256 pixel butterfly image is listed. The implementation calculates the resulting image very quickly (over 22 times faster than without acelleration), but the result will not be correct.
\newpage
\subsubsection{Feature Re-Transmission Skip}
As already mentioned in section \ref{sec:fpgaimpl2}, the second HDL implementation should also support a functionality named \enquote{feature re-transmission skip}.
The software could send a skip command instead of re-sending the whole feature. Thus, the loops for output and input channels can be interchanged in the software and each feature has to be sent only once.
Due to the fact that there seem to be still synchronization problems, this functionality has not been used for measurements and is currently not used in the C code. If this would be fixed, this should allow a further speed-up.
\subsubsection{Handling BRAM Limitations}
Even if the dark image bug was fixed, the maximum image sizes would be limited by the BRAM size. A 300x300 pixel image occupies 71 \% of BRAM. However, bigger images could still be upscaled if a stitching algorithm was implemented. The algorithm would split the image into smaller padded sub-images before passing them to the convolution algorithm and recombines them afterwards.
\clearpage
%\nocite{*}
\newpage
\appendix
\section{Appendix: Set5 Images}
\label{Appendix:set5}
\begin{figure}[!ht]
\centering
\begin{subfigure}[b]{0.3\textwidth}
\centering
\caption{Ground truth}
\includegraphics[width=\textwidth]{fig/examples/butterfly_GT}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\caption{Bicubic interpolation x3}
\includegraphics[width=\textwidth]{fig/examples/butterfly_bicubic_x3}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\caption{SRCNN x3}
\includegraphics[width=\textwidth]{fig/examples/butterfly_srcnn_x3}
\end{subfigure}\\
\vspace{5mm}
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/head_GT}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/head_bicubic_x3}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/head_srcnn_x3}
\end{subfigure}\\
\vspace{5mm}
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/woman_GT}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/woman_bicubic_x3}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/woman_srcnn_x3}
\end{subfigure}
\caption{Comparison of ground truth, bicubic interpolation and SRCNN of Set5 images \enquote{butterfly}, \enquote{head} and \enquote{woman}}
\label{fig:set5imagesI}
\end{figure}
\begin{figure}[!ht]
\centering
\begin{subfigure}[b]{0.3\textwidth}
\centering
\caption{Ground truth}
\includegraphics[width=\textwidth]{fig/examples/bird_GT}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\caption{Bicubic interpolation x3}
\includegraphics[width=\textwidth]{fig/examples/bird_bicubic_x3}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\caption{SRCNN x3}
\includegraphics[width=\textwidth]{fig/examples/bird_srcnn_x3}
\end{subfigure}\\
\vspace{5mm}
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/baby_GT}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/baby_bicubic_x3}
\end{subfigure}
\hfill
\begin{subfigure}[b]{0.3\textwidth}
\centering
\includegraphics[width=\textwidth]{fig/examples/baby_srcnn_x3}
\end{subfigure}
\caption{Comparison of ground truth, bicubic interpolation and SRCNN of Set5 images \enquote{bird} and \enquote{baby}.}
\label{fig:set5imagesII}
\end{figure}
\clearpage
\section{Appendix: Quality Measures}
\label{Appendix:tables}
\begin{table}[H]
\centering
\caption{Results for the images from dataset5 for \textbf{bicubic} interpolation.}
\label{tab:resultsbicubic}
\begin{tabular}{lccccc}
\toprule
Metric & baby.bmp & bird.bmp & butterfly.bmp & head.bmp & woman.bmp \\
\hline
PSNR [dB] & 33.30 & 31.15 & 23.15 & 32.81 & 27.37 \\
SSIM & 0.907 & 0.919 & 0.823 & 0.824 & 0.884 \\
IFC & 3.65 & 3.85 & 3.42 & 3.23 & 3.33 \\
NQM [dB] & 41.58 & 24.77 & 19.57 & 30.32 & 23.38 \\
MSSSIM & 0.981 & 0.983 & 0.969 & 0.969 & 0.975 \\
\bottomrule
\end{tabular}
\end{table}
\begin{table}[H]
\centering
\caption{Results for the images from dataset5 for our \textbf{SRCNN} implementation.}
\label{tab:resultssrcnn}
\begin{tabular}{lccccc}
\toprule
Metric & baby.bmp & bird.bmp & butterfly.bmp & head.bmp & woman.bmp \\
\hline
PSNR [dB] & 34.72 & 33.89 & 27.12 & 33.78 & 30.07 \\
SSIM & 0.927 & 0.949 & 0.914 & 0.851 & 0.925 \\
IFC & 4.21 & 4.79 & 5.00 & 3.73 & 4.32 \\
NQM [dB] & 41.45 & 31.24 & 26.67 & 35.84 & 30.02 \\
MSSSIM & 0.988 & 0.992 & 0.989 & 0.977 & 0.988 \\
\bottomrule
\end{tabular}
\end{table}
\newpage
\section*{Team}
A flat hierarchy was used. Neural networks were new to all team members, so everyone was participating in research, coding, etc. Nonetheless various areas were appointed to each member. They ultimately take main responsibility for the respective areas.
\begin{figure}[H]
\centering
\includestandalone[width=0.6\textwidth]{fig/hierarchy}
\caption{Assigned areas for each team member. Team members did not work solely on their assigned areas but had the main responsibility for them.}
\label{fig.hierarchy}
\end{figure}
\newpage
\printbibliography
\end{document} | {
"alphanum_fraction": 0.7520830888,
"author": null,
"avg_line_length": 59.8665105386,
"converted": null,
"ext": "tex",
"file": null,
"hexsha": "a65afd7f2fb5eda872f0f7164eaff4c5a81e6413",
"include": null,
"lang": "TeX",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T16:44:51.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-03-29T16:44:51.000Z",
"max_forks_repo_head_hexsha": "614d70360800ad446aaeb47afc3454635094018e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Fivefold/SRCNN",
"max_forks_repo_path": "Report/source/main.tex",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "614d70360800ad446aaeb47afc3454635094018e",
"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": "Fivefold/SRCNN",
"max_issues_repo_path": "Report/source/main.tex",
"max_line_length": 1211,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "614d70360800ad446aaeb47afc3454635094018e",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Fivefold/SRCNN",
"max_stars_repo_path": "Report/source/main.tex",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 13610,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 51126
} |
Denise Platt Lichtig practices acupuncture, Meditation, and traditional Chinese Medicine. She also offers classes in Tai Chi.
Acupuncture
Denise Lichtig has been practicing Acupuncture and Traditional Chinese Medicine in Davis for over 15 years and have helped hundreds of clients. She is a licensed and certified acupuncturist in the State of California and has a Master of Science in Traditional Chinese Medicine. She is also a medical intuitive and a healer; she teaches both meditation and Tai Chi and can show you how to use these practices to improve your healing process. She brings a multitude of modalities to your treatment to assist in your overall improvement.
The majority of clients come to her with common goals including:
chronic pain reduction
improving sense of wellbeing
strengthening the immune system
lowering stress and anxiety
decreasing the sideeffects of chemotherapy and/or radiation therapy
reducing symptoms of asthma, allergies and other respiratory aliments
relief from insomnia, migraines, PMS, or menopausal symptoms
The acupuncture needles she uses are sterile, disposable and FDA approved to ensure your safety.
Each treatment plan is as individual as you are; she considers the whole person and does not rush sessions. Expect an hour for treatment and a little longer for the initial visit. She offers a safe and compassionate environment so you can fully relax and align your body with its natural rhythm.
Tai Chi
Tai Chi is a both a Martial Arts and Self Defense martial art and a slow and gentle exercise program that builds your strength. Beginning and continuing Tai Chi classes at the Davis Art Center, Wednesday Evenings. Sessions last for six weeks after which another session will begin. Prices are $90/set of six classes paid at the first class of the session. Arrive 10 minutes prior to the start of the lesson. Please wear tennis shoes and comfy clothes.
Register online at the Davis Art Center or on website before the first class of the session.
CURRENT SESSION: April 9th May 28th on Wednesday evenings from 67pm.
Register here: http://www.deniselichtig.com/classschedule.htm
Meditation
Meditation is a serious longterm healing practice, as well as providing a way to focus your mind and intentions on a daily basis. It can open channels & meridians, realign chakra energies and calm the nervous system so it can heal. Through meditation, you can experience a deep relaxation, improve your cognitive functions and increase your mental clarity. Meditation practice can also reduce your stress & anxiety and promote a sense of wellbeing.
Continuing classes start Monday, 6:00 6:45 p.m.
20130515 11:12:13 nbsp Wonderful. I love Denise. I have been going to her for years. I would highly recommend her. Users/Yogagirl
| {
"alphanum_fraction": 0.8078571429,
"author": null,
"avg_line_length": 73.6842105263,
"converted": null,
"ext": "f",
"file": null,
"hexsha": "2420b1c565077a04b400c7e2d7d5940077682f8b",
"include": null,
"lang": "FORTRAN",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "voflo/Search",
"max_forks_repo_path": "lab/davisWiki/Denise_Platt_Lichtig%2C_M.S.%2C_L._Ac.f",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "voflo/Search",
"max_issues_repo_path": "lab/davisWiki/Denise_Platt_Lichtig%2C_M.S.%2C_L._Ac.f",
"max_line_length": 534,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "voflo/Search",
"max_stars_repo_path": "lab/davisWiki/Denise_Platt_Lichtig%2C_M.S.%2C_L._Ac.f",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 574,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 2800
} |
#!/usr/bin/python3
#Import packages and libraries
import datetime as dt
import json
import pandas as pd
import numpy as np
from sqlalchemy import Column, Integer, String, Float, DateTime, Boolean, func
import iotfunctions.bif as bif
from iotfunctions.metadata import EntityType, LocalEntityType
from iotfunctions.db import Database
from iotfunctions.dbtables import FileModelStore
#Connect to the service
with open('credentials_as_monitor_demo.json', encoding='utf-8') as F:
credentials = json.loads(F.read())
db_schema = None
db = Database(credentials=credentials)
#Write the function
def f(df, parameters = None):
adjusted_distance = df['distance'] * 0.9
return adjusted_distance
#Save the function to a local model store
model_store = FileModelStore()
model_store.store_model('adjusted_distance', f)
| {
"alphanum_fraction": 0.7871046229,
"author": null,
"avg_line_length": 26.5161290323,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "a61f891747d6ee1d9eee42e6fed218f9e459d354",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2021-10-01T16:01:32.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-10-16T18:55:16.000Z",
"max_forks_repo_head_hexsha": "1969eb198058ec4d4339f3a953f33d4d09675de8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "sedgewickmm18/mmfunctions",
"max_forks_repo_path": "PythonFunction_register.py",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "1969eb198058ec4d4339f3a953f33d4d09675de8",
"max_issues_repo_issues_event_max_datetime": "2020-06-02T14:32:30.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-02-06T11:47:02.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "sedgewickmm18/mmfunctions",
"max_issues_repo_path": "PythonFunction_register.py",
"max_line_length": 78,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "1969eb198058ec4d4339f3a953f33d4d09675de8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "sedgewickmm18/mmfunctions",
"max_stars_repo_path": "PythonFunction_register.py",
"max_stars_repo_stars_event_max_datetime": "2021-02-19T14:59:32.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-10-14T16:09:20.000Z",
"num_tokens": 189,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 822
} |
[STATEMENT]
lemma R_choice_law: "X \<le> rel_R \<lceil>P\<rceil> \<lceil>Q\<rceil> \<Longrightarrow> Y \<le> rel_R \<lceil>P\<rceil> \<lceil>Q\<rceil> \<Longrightarrow> X \<union> Y \<le> rel_R \<lceil>P\<rceil> \<lceil>Q\<rceil>"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>X \<subseteq> rel_R \<lceil>P\<rceil> \<lceil>Q\<rceil>; Y \<subseteq> rel_R \<lceil>P\<rceil> \<lceil>Q\<rceil>\<rbrakk> \<Longrightarrow> X \<union> Y \<subseteq> rel_R \<lceil>P\<rceil> \<lceil>Q\<rceil>
[PROOF STEP]
using le_supI
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>?a \<le> ?x; ?b \<le> ?x\<rbrakk> \<Longrightarrow> sup ?a ?b \<le> ?x
goal (1 subgoal):
1. \<lbrakk>X \<subseteq> rel_R \<lceil>P\<rceil> \<lceil>Q\<rceil>; Y \<subseteq> rel_R \<lceil>P\<rceil> \<lceil>Q\<rceil>\<rbrakk> \<Longrightarrow> X \<union> Y \<subseteq> rel_R \<lceil>P\<rceil> \<lceil>Q\<rceil>
[PROOF STEP]
. | {
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": "Hybrid_Systems_VCs_KleeneAlgebraTests_HS_VC_KAT_rel",
"hexsha": null,
"include": null,
"lang": null,
"length": 2,
"llama_tokens": 396,
"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
} |
struct UniformPolicy <: Network
net::Network
end
initial_inference(n::UniformPolicy, game::MuZeroGame) = initial_inference(n, game.game)
# @todo just have initial_inference(x::UniformPolicy, args...)
initial_inference(x::UniformPolicy, game::AbstractEnv) = initial_inference(x.net, game)
initial_inference(x::UniformPolicy, games::Vector{<:AbstractEnv}) = initial_inference(x.net, games)
initial_inference(x::UniformPolicy, hidden_state::AbstractArray{Float32, 4}) = initial_inference(x.net, hidden_state)
function recurrent_inference(x::UniformPolicy, hidden_state::AbstractArray{Float32, 3}, action::Integer)
recurrent_inference(x.net, hidden_state, action)
end
function recurrent_inference(x::UniformPolicy, hidden_state::Array{Float32, 4}, action::Array{Float32, 4})
recurrent_inference(x.net, hidden_state, action)
end
function prediction(x::UniformPolicy, hidden_state::AbstractArray{Float32})
policy_logits, state_values = prediction(x.net, hidden_state)
zeros(Float32, size(policy_logits)...), state_values
end | {
"alphanum_fraction": 0.7898272553,
"author": null,
"avg_line_length": 47.3636363636,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "64cced09696c45e82dc6b0b18cebe65d4fae7ea2",
"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": "2fcb23e8d5b49b6030987f2441f6b7157c3c7601",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "JuliaRL/MuZero.jl",
"max_forks_repo_path": "src/networks/uniform_policy.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "2fcb23e8d5b49b6030987f2441f6b7157c3c7601",
"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": "JuliaRL/MuZero.jl",
"max_issues_repo_path": "src/networks/uniform_policy.jl",
"max_line_length": 117,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2fcb23e8d5b49b6030987f2441f6b7157c3c7601",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "JuliaRL/MuZero.jl",
"max_stars_repo_path": "src/networks/uniform_policy.jl",
"max_stars_repo_stars_event_max_datetime": "2021-11-11T21:27:53.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-11T21:27:53.000Z",
"num_tokens": 256,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 1042
} |
""""
Configuration reader for LADiM version 2
with compability wrapper for LADiM version 1 configuration
"""
# -----------------------------------
# Bjørn Ådlandsvik <bjorn@hi.no>
# Institute of Marine Research
# December 2020
# -----------------------------------
import sys
from pathlib import Path
import logging
from typing import Union, Literal, Any
import numpy as np
from netCDF4 import Dataset, num2date # type: ignore
import yaml # type: ignore
DEBUG = False
logger = logging.getLogger(__name__)
if DEBUG:
logger.setLevel(logging.DEBUG)
def configure(
config_file: Union[Path, str], version: Literal[1, 2] = 2
) -> dict[str, Any]:
"""Main configuration function of LADiM
Args:
config_file:
Name of configuration file
version:
configuration format version,
= 1 for LADiM version 1.x
= 2 for LADiM version 2.x
Returns:
2-level configuration dictionary
"""
logger.info("Configuration")
logger.info(" Configuration file %s:", config_file)
if not Path(config_file).exists():
logger.critical("No configuration file %s:", config_file)
raise SystemExit(3)
try:
with open(config_file, encoding="utf-8") as fid:
config: dict[str, Any] = yaml.safe_load(fid)
except yaml.parser.ParserError as err:
logger.critical("Not a valid yaml file: %s", config_file)
raise SystemExit(3) from err
logger.info(" Configuration file version: %s", version)
# Try old configure version
if version == 1:
if config.get("version", None) == 2:
logger.warning("Configuration format mismatch")
logger.warning("Trying version 1 as requested by command line")
config = configure_v1(config)
elif version != 2:
logger.warning("Configuration version should be 1 or 2, trying version 2")
# Some sections may be missing
if "state" not in config:
config["state"] = dict()
if "grid" not in config:
config["grid"] = dict()
if "ibm" not in config:
config["ibm"] = dict()
if "warm_start" not in config:
config["warm_start"] = dict()
# Handle non-orthogonality
# If grid["filename"] is missing, use forcing["filename"]
if "module" not in config["grid"]:
config["grid"]["module"] = config["forcing"]["module"]
if "filename" not in config["grid"]:
filename = Path(config["forcing"]["filename"])
# glob if necessary and use first file
if ("*" in str(filename)) or ("?" in str(filename)):
directory = filename.parent
filename = sorted(directory.glob(filename.name))[0]
config["grid"]["filename"] = filename
# Warm start
if "filename" in config["warm_start"]:
warm_start_file = config["warm_start"]["filename"]
# Warm start overrides start time
try:
nc = Dataset(warm_start_file)
except (FileNotFoundError, OSError) as err:
logging.critical("Could not open warm start file:%s", warm_start_file)
raise SystemExit(1) from err
tvar = nc.variables["time"]
# Use last record in restart file
warm_start_time = np.datetime64(num2date(tvar[-1], tvar.units))
warm_start_time = warm_start_time.astype("M8[s]")
config["time"]["start"] = warm_start_time
logging.info(" Warm start at %s", warm_start_time)
if "variables" not in config["warm_start"]:
config["warm_start"]["variables"] = []
# warm start -> release
config["release"]["warm_start_file"] = config["warm_start"]["filename"]
# skip_initial is default with warm start
if "filename" in config["warm_start"] and "skip_initial" not in config["output"]:
config["output"]["skip_initial"] = True
# Possible improvement: write a yaml-file
if DEBUG:
yaml.dump(config, stream=sys.stdout)
return config
# --------------------------------------------------------------------
def configure_v1(config: dict[str, Any]) -> dict[str, Any]:
"""Tries to read version 1 configuration files
This function may fail for valid configuration files for LADiM version 1.
Ordinary use cases at IMR should work.
"""
conf2: dict[str, Any] = dict() # output version 2 configuration
# time
conf2["time"] = dict(
start=config["time_control"]["start_time"],
stop=config["time_control"]["stop_time"],
dt=config["numerics"]["dt"],
)
if "reference_time" in config["time_control"]:
conf2["time"]["reference"] = config["time_control"]["reference_time"]
# grid and forcing
conf2["grid"] = dict()
conf2["forcing"] = dict()
if "ladim.gridforce.ROMS" in config["gridforce"]["module"]:
conf2["grid"]["module"] = "ladim2.ROMS"
if "gridfile" in config["gridforce"]:
conf2["grid"]["filename"] = config["gridforce"]["gridfile"]
elif "gridfile" in config["files"]:
conf2["grid"]["filename"] = config["files"]["gridfile"]
conf2["forcing"]["module"] = "ladim2.ROMS"
if "input_file" in config["gridforce"]:
conf2["forcing"]["filename"] = config["gridforce"]["input_file"]
elif "input_file" in config["files"]:
conf2["forcing"]["filename"] = config["files"]["input_file"]
if "subgrid" in config["gridforce"]:
conf2["grid"]["subgrid"] = config["gridforce"]["subgrid"]
if "ibm_forcing" in config["gridforce"]:
conf2["forcing"]["ibm_forcing"] = config["gridforce"]["ibm_forcing"]
# state
conf2["state"] = dict()
instance_variables = dict()
particle_variables = dict()
if "ibm" in config and "variables" in config["ibm"]:
for var in config["ibm"]["variables"]:
instance_variables[var] = "float"
for var in config["particle_release"]:
if var in ["mult", "X", "Y", "Z"]: # Ignore
continue
if (
"particle_variables" in config["particle_release"]
and var in config["particle_release"]["particle_variables"]
):
particle_variables[var] = config["particle_release"].get(var, "float")
conf2["state"]["instance_variables"] = instance_variables
conf2["state"]["particle_variables"] = particle_variables
conf2["state"]["default_values"] = dict()
for var in conf2["state"]["instance_variables"]:
conf2["state"]["default_values"][var] = 0
# tracker
conf2["tracker"] = dict(advection=config["numerics"]["advection"])
if config["numerics"]["diffusion"]:
conf2["tracker"]["diffusion"] = config["numerics"]["diffusion"]
# release
conf2["release"] = dict(
release_file=config["files"]["particle_release_file"],
names=config["particle_release"]["variables"],
)
if "release_type" in config["particle_release"]:
if config["particle_release"]["release_type"] == "continuous":
conf2["release"]["continuous"] = True
conf2["release"]["release_frequency"] = config["particle_release"][
"release_frequency"
]
# ibm
if "ibm" in config:
conf2["ibm"] = dict()
for var in config["ibm"]:
if var == "ibm_module":
conf2["ibm"]["module"] = config["ibm"][var]
continue
if var != "variables":
conf2["ibm"][var] = config["ibm"][var]
# output
conf2["output"] = dict(
filename=config["files"]["output_file"],
output_period=config["output_variables"]["outper"],
instance_variables=dict(),
particle_variables=dict(),
ncargs=dict(
data_model=config["output_variables"].get("format", "NETCDF3_CLASSIC")
),
)
for var in config["output_variables"]["instance"]:
conf2["output"]["instance_variables"][var] = dict()
D = config["output_variables"][var].copy()
conf2["output"]["instance_variables"][var]["encoding"] = dict(
datatype=D.pop("ncformat")
)
conf2["output"]["instance_variables"][var]["attributes"] = D
for var in config["output_variables"]["particle"]:
conf2["output"]["particle_variables"][var] = dict()
D = config["output_variables"][var].copy()
conf2["output"]["particle_variables"][var]["encoding"] = dict(
datatype=D.pop("ncformat")
)
conf2["output"]["particle_variables"][var]["attributes"] = D
return conf2
| {
"alphanum_fraction": 0.5981123281,
"author": null,
"avg_line_length": 35.316872428,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "12334c6faeb585ccf3f76ed41e4f1ec90c0dd766",
"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": "f6c1be9028ca54370ce33dde25b005d5b0bb4677",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "bjornaa/ladim2",
"max_forks_repo_path": "ladim2/configure.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "f6c1be9028ca54370ce33dde25b005d5b0bb4677",
"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": "bjornaa/ladim2",
"max_issues_repo_path": "ladim2/configure.py",
"max_line_length": 85,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "f6c1be9028ca54370ce33dde25b005d5b0bb4677",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "bjornaa/ladim2",
"max_stars_repo_path": "ladim2/configure.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2016,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 8582
} |
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE PulseTest
#include <boost/test/unit_test.hpp>
#include <exception>
#include <stdio.h>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
#include <iostream>
#include <algorithm>
#include "../src/network.hpp"
#include "../src/network.cpp"
//TODO Add test void forEachPath(FuncType functor) const;
PSLProblem* initProblem() {
ifstream in;
in.open("benchmarks/instances/sample-server.dat");
if (!in) {
cout << "Unable to open file";
exit(1); // terminate with error
}
PSLProblem* problem = new PSLProblem();
in >> *problem;
in.close();
problem->setSeed(SEED);
problem->generateNetwork(true);
//#ifndef NDEBUG //Mode Debug
// cout << *problem << endl << endl;
//#endif
return problem;
}
BOOST_AUTO_TEST_SUITE(Tests)
BOOST_AUTO_TEST_CASE(NetworkIterators)
{
PSLProblem* problem = initProblem();
/////////////////////////////////////////////////
// UnitTest LinkIterator
////////////////////////////////////////////////
LinkIterator itL = problem->getRoot()->lbegin();
//Copy ctor
//
LinkIterator itL_copy(itL);
BOOST_CHECK(itL == itL_copy);
//Operator =
LinkIterator itL_copy2 = problem->getRoot()->lbegin();
itL_copy2 = itL;
BOOST_CHECK(itL == itL_copy2);
//Operator ++
//
itL++;
itL_copy++;
BOOST_CHECK(itL == itL_copy);
//Operator !=
//
BOOST_CHECK(itL != problem->getRoot()->lbegin());
BOOST_CHECK(itL_copy != problem->getRoot()->lbegin());
//Operator *
//
BOOST_CHECK(*itL == *itL_copy);
BOOST_CHECK(*itL != *(problem->getRoot()->lbegin()));
//Operator ->
//
BOOST_CHECK(itL->getID() == itL_copy->getID());
BOOST_CHECK(itL->getID() != problem->getRoot()->lbegin()->getID());
//Count Links
//
int count_links = 0;
for( LinkIterator i = problem->getRoot()->lbegin();i != problem->getRoot()->lend();i++) {
count_links++;
}
BOOST_CHECK(count_links == problem->linkCount());
/////////////////////////////////////////////////
// UnitTest NodeIterator
////////////////////////////////////////////////
NodeIterator itN = problem->getRoot()->nbegin();
//Copy ctor
//
NodeIterator itN_copy(itN);
BOOST_CHECK(itN == itN_copy);
//Operator =
NodeIterator itN_copy2 = problem->getRoot()->nbegin();
itN_copy2 = itN;
BOOST_CHECK(itN == itN_copy2);
//Operator ++
//
itN++;
itN_copy++;
BOOST_CHECK(itN == itN_copy);
//Operator !=
//
BOOST_CHECK(itN != problem->getRoot()->nbegin());
BOOST_CHECK(itN_copy != problem->getRoot()->nbegin());
//Operator *
//
BOOST_CHECK(*itN == *itN_copy);
BOOST_CHECK(*itN != *(problem->getRoot()->nbegin()));
//Operator ->
//
BOOST_CHECK(itN->getID() == itN_copy->getID());
BOOST_CHECK(itN->getID() != problem->getRoot()->nbegin()->getID());
//Count nodes
//
int count_nodes = 0;
for( NodeIterator i = problem->getRoot()->nbegin();i != problem->getRoot()->nend();i++) {
count_nodes++;
}
BOOST_CHECK(count_nodes == problem->nodeCount());
/////////////////////////////////////////////////
// UnitTest AncestorIterator
////////////////////////////////////////////////
AncestorIterator itA = problem->getRoot()->getChild(0)->getChild(0)->abegin();
//Copy ctor
//
AncestorIterator itA_copy(itA);
BOOST_CHECK(itA == itA_copy);
//Operator =
AncestorIterator itA_copy2 = problem->getRoot()->getChild(0)->getChild(0)->abegin();
itA_copy2 = itA;
BOOST_CHECK(itA == itA_copy2);
//Operator ++
//
itA++;
itA_copy++;
BOOST_CHECK(itA == itA_copy);
//Operator !=
//
BOOST_CHECK(itA != itA_copy2);
BOOST_CHECK(itA_copy != itA_copy2);
//Operator *
//
BOOST_CHECK(*itA == *itA_copy);
BOOST_CHECK(*itA != *(itA_copy2));
//Operator ->
//
BOOST_CHECK(itA->getID() == itA_copy->getID());
//Count ancestors
int count = 0;
for( AncestorIterator i = problem->getRoot()->getChild(0)->getChild(0)->abegin();i != problem->getRoot()->getChild(0)->getChild(0)->aend();i++) {
count++;
}
BOOST_CHECK(count == 2);
//Count root ancestors
count = 0;
for( AncestorIterator i = problem->getRoot()->abegin();i != problem->getRoot()->aend();i++) {
count++;
}
BOOST_CHECK(count == 0);
/////////////////////////////////////////////////
// UnitTest PathIterator
////////////////////////////////////////////////
//Count paths
count = 0;
for( PathIterator i = problem->getRoot()->pbegin();i != problem->getRoot()->pend();i++) {
// cout << *(*i).first << " -> "<< *(*i).second << endl;
count++;
}
BOOST_CHECK(count == problem->pathCount());
}
BOOST_AUTO_TEST_CASE(networkGeneration)
{
PSLProblem* problem = initProblem();
IntList level1(problem->getLevelNodeCounts());
problem->setSeed(SEED);
problem ->generateNetwork(true);
//FIXME problem->generateNetwork(false);
cout << *problem;
IntList level2(problem->getLevelNodeCounts());
BOOST_CHECK_EQUAL_COLLECTIONS(level1.begin(), level1.end(), level2.begin(), level2.end());
}
BOOST_AUTO_TEST_CASE(networkExample)
{
PSLProblem* problem = initProblem();
ofstream myfile;
char* name = tmpnam(NULL);
myfile.open(name);
//myfile.open ("/tmp/pserver.dot");
problem->toDotty(myfile);
myfile.close();
//Test Ranks
problem->toRanks(cout);
FacilityNode* n0 = problem->getRoot();
FacilityNode* n3 = problem->getRoot()->getChild(0)->getChild(0);
FacilityNode* n6 = problem->getRoot()->getChild(1)->getChild(0);
//cout << *n3 << " " << *n6 << endl;
BOOST_CHECK(problem->rankX(n3) == 3);
BOOST_CHECK(problem->rankX(n6) == 6);
BOOST_CHECK(problem->rankX(n3, 0) == 18);
BOOST_CHECK(problem->rankX(n6, 0) == 21);
BOOST_CHECK(problem->rankY(n3, 0) == 36);
BOOST_CHECK(problem->rankY(n6, 1) == 43);
BOOST_CHECK(problem->rankZ(n3, 0) == 66);
BOOST_CHECK(problem->rankZ(n6, 1) == 73);
BOOST_CHECK(problem->rankY(n3->toFather(), 0) == 94);
BOOST_CHECK(problem->rankY(n6->toFather(), 1) == 101);
BOOST_CHECK(problem->rankZ(n0, n3, 0) == 146);
BOOST_CHECK(problem->rankZ(n0, n6, 1) == 153);
BOOST_CHECK(problem->rankB(n0, n3, 0) == 214);
BOOST_CHECK(problem->rankB(n0, n6, 1) == 221);
}
/*
BOOST_AUTO_TEST_CASE(TestGexf)
{
//cout << "Hello World!!!" << endl; // prints Hello World!!!
//srand(1000);
int sum = 0;
ifstream in;
//FacilityType::setSeed(1000);
in.open("benchmarks/instances/sample-server.dat");
if (!in) {
//exit(1); // terminate with error
BOOST_ERROR("Error : Enable Unable to open file");
}
PSLProblem* problem = new PSLProblem();
in >> *problem;
in.close();
cout << "Sum = " << sum << endl;
cout << *problem;
//FacilityNode* root = new FacilityNode(problem->facilities[0]);
//
FacilityNode* root = problem->generateNetwork();
root->printSubtree();
// generateSubtree(root, *problem);
ofstream myfile;
myfile.open ("testFig1.dot");
myfile << "digraph G {\n";
root->toDotty(myfile);
myfile << "}\n";
myfile.close();
AbstractGexfGen* generatorGexf = new InstanceGexfGen(root);
generatorGexf->writeToFile("testFig1.gexf");
delete generatorGexf;
generatorGexf = new FlowConnectionsGexfGen(root);
generatorGexf->writeToFile("testFig2.gexf");
delete generatorGexf;
}
*/
/*
BOOST_AUTO_TEST_CASE(checkFailure)
{
BOOST_CHECK(add(2, 2) == 5);
}
BOOST_AUTO_TEST_CASE(multipleCheckFailures)
{
BOOST_CHECK(add(2, 2) == 1);
BOOST_CHECK(add(2, 2) == 2);
BOOST_CHECK(add(2, 2) == 3);
}
BOOST_AUTO_TEST_CASE(requireFailure)
{
BOOST_REQUIRE(add(2, 2) == 5);
}
BOOST_AUTO_TEST_CASE(explicitError)
{
BOOST_ERROR("Error message");
}
BOOST_AUTO_TEST_CASE(explicitFailure)
{
BOOST_FAIL("Failure message");
}
BOOST_AUTO_TEST_CASE(errorThenFailure)
{
BOOST_FAIL("Error message");
BOOST_FAIL("Failure message");
}
BOOST_AUTO_TEST_CASE(uncaughtException)
{
throw "Catch me if you can!";
}
BOOST_AUTO_TEST_CASE(stdException)
{
throw new std::exception();
}
BOOST_AUTO_TEST_CASE(checkMessageFailure)
{
BOOST_CHECK_MESSAGE(add(2, 2) == 5, "add(..) result: " << add(2, 2));
}
BOOST_AUTO_TEST_CASE(checkEqualFailure)
{
BOOST_CHECK_EQUAL(add( 2,2 ), 5);
}
BOOST_AUTO_TEST_CASE(threeSeconds)
{
sleep(3);
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE(PassingSuite)
BOOST_AUTO_TEST_CASE(pass1)
{
}
BOOST_AUTO_TEST_CASE(pass2)
{
}
BOOST_AUTO_TEST_CASE(pass3)
{
}
*/
BOOST_AUTO_TEST_SUITE_END()
| {
"alphanum_fraction": 0.6410979047,
"author": null,
"avg_line_length": 22.3589041096,
"converted": null,
"ext": "cpp",
"file": null,
"hexsha": "c71d633e5868abe97b9207f9da78ae77c7dfd47b",
"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": "1854a27c6f83762c8e74243db2df378e7759223a",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "aeolus-project/opossum",
"max_forks_repo_path": "test/main.cpp",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "1854a27c6f83762c8e74243db2df378e7759223a",
"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": "aeolus-project/opossum",
"max_issues_repo_path": "test/main.cpp",
"max_line_length": 146,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "1854a27c6f83762c8e74243db2df378e7759223a",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "aeolus-project/opossum",
"max_stars_repo_path": "test/main.cpp",
"max_stars_repo_stars_event_max_datetime": "2015-07-01T19:43:06.000Z",
"max_stars_repo_stars_event_min_datetime": "2015-07-01T19:43:06.000Z",
"num_tokens": 2243,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 8161
} |
[STATEMENT]
lemma list_decode_inverse [simp]: "list_encode (list_decode n) = n"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. list_encode (list_decode n) = n
[PROOF STEP]
proof (induct n rule: list_decode.induct)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. list_encode (list_decode 0) = 0
2. \<And>n. (\<And>x y. (x, y) = prod_decode n \<Longrightarrow> list_encode (list_decode y) = y) \<Longrightarrow> list_encode (list_decode (Suc n)) = Suc n
[PROOF STEP]
case (2 n)
[PROOF STATE]
proof (state)
this:
(?x, ?y) = prod_decode n \<Longrightarrow> list_encode (list_decode ?y) = ?y
goal (2 subgoals):
1. list_encode (list_decode 0) = 0
2. \<And>n. (\<And>x y. (x, y) = prod_decode n \<Longrightarrow> list_encode (list_decode y) = y) \<Longrightarrow> list_encode (list_decode (Suc n)) = Suc n
[PROOF STEP]
then
[PROOF STATE]
proof (chain)
picking this:
(?x, ?y) = prod_decode n \<Longrightarrow> list_encode (list_decode ?y) = ?y
[PROOF STEP]
show ?case
[PROOF STATE]
proof (prove)
using this:
(?x, ?y) = prod_decode n \<Longrightarrow> list_encode (list_decode ?y) = ?y
goal (1 subgoal):
1. list_encode (list_decode (Suc n)) = Suc n
[PROOF STEP]
by (metis list_encode.simps(2) list_encode_inverse prod_decode_inverse surj_pair)
[PROOF STATE]
proof (state)
this:
list_encode (list_decode (Suc n)) = Suc n
goal (1 subgoal):
1. list_encode (list_decode 0) = 0
[PROOF STEP]
qed auto | {
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": 6,
"llama_tokens": 572,
"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 logging
from typing import TYPE_CHECKING
import numpy as np
import copy
from typing import Union, Optional, Any
from art.attacks.inference.membership_inference.black_box import MembershipInferenceBlackBox
from art.estimators.estimator import BaseEstimator
from art.estimators.classification.classifier import ClassifierMixin
from art.utils import check_and_transform_label_format
if TYPE_CHECKING:
from art.utils import CLASSIFIER_TYPE
logger = logging.getLogger(__name__)
class ShadowModelAttack(MembershipInferenceBlackBox):
attack_params = MembershipInferenceBlackBox.attack_params + [
"shadow_model",
"nb_shadow_models",
"shadow_dataset_size"
]
_estimator_requirements = (BaseEstimator, ClassifierMixin)
def __init__(self,
classifier: Union["CLASSIFIER_TYPE"],
shadow_model: Union["CLASSIFIER_TYPE"],
nb_shadow_models: int = 1,
shadow_dataset_size: int = 1000,
input_type: str = "prediction",
attack_model_type: str = "nn",
attack_model: Optional[Any] = None,
):
super().__init__(classifier=classifier,
input_type=input_type,
attack_model_type=attack_model_type,
attack_model=attack_model
)
self.nb_shadow_models = nb_shadow_models,
self.shadow_dataset_size = shadow_dataset_size
self.shadow_models = []
for _ in range(nb_shadow_models):
self.shadow_models.append(copy.deepcopy(shadow_model))
def fit( # pylint: disable=W0613
self, x: np.ndarray, y: np.ndarray, test_x: np.ndarray, test_y: np.ndarray, **kwargs
):
self._check_fit_params(x, y, test_x, test_y)
predictions, labels, membership = [], [], []
for i, shadow_model in enumerate(self.shadow_models):
sh_x, sh_y, sh_test_x, sh_test_y = self._train_shadow_model(shadow_model, x, y, test_x, test_y, **kwargs)
x_1, x_2, y_new = self._create_attack_dataset(self.estimator, sh_x, sh_y, sh_test_x, sh_test_y)
predictions.extend(x_1)
labels.extend(x_2)
membership.extend(y_new)
predictions, labels, membership = np.array(predictions), np.array(labels), np.array(membership)
self._fit_attack_model(predictions, labels, membership)
def _train_shadow_model(self, shadow_model: Union["CLASSIFIER_TYPE"], x: np.ndarray, y: np.ndarray, test_x: np.ndarray, test_y: np.ndarray, **kwargs):
train_length = len(x)
test_length = len(test_x)
y = check_and_transform_label_format(y, self.estimator.nb_classes)
test_y = check_and_transform_label_format(test_y, self.estimator.nb_classes)
training_idx = np.random.choice(range(train_length), size=self.shadow_dataset_size)
test_idx = np.random.choice(range(test_length), size=self.shadow_dataset_size)
shadow_training_data = x[training_idx]
shadow_training_labels = y[training_idx]
shadow_test_data = test_x[test_idx]
shadow_test_labels = test_y[test_idx]
shadow_model.fit(
shadow_training_data,
shadow_training_labels,
**kwargs
)
pred = shadow_model.predict(shadow_test_data)
acc = np.sum(np.argmax(pred, axis=1) == np.argmax(shadow_test_labels, axis=1)) / self.shadow_dataset_size
print("Accuracy of shadow model (on test set): %f" % acc)
return shadow_training_data, shadow_training_labels, shadow_test_data, shadow_test_labels
def _check_fit_params(self, x: np.ndarray, y: np.ndarray, test_x: np.ndarray, test_y: np.ndarray):
super()._check_fit_params(x, y, test_x, test_y)
train_length = len(x)
test_length = len(test_x)
if train_length < self.shadow_dataset_size:
raise ValueError(
"Size of train dataset (%d) should be at least %d!" % (train_length, self.shadow_dataset_size))
if test_length < self.shadow_dataset_size:
raise ValueError(
"Size of test dataset (%d) should be at least %d!" % (test_length, self.shadow_dataset_size)) | {
"alphanum_fraction": 0.6658873042,
"author": null,
"avg_line_length": 41.125,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "f5eb6630a9bcbb4fb1dcedd042eeae1648750289",
"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": "3454f7f11c3ade9317d11637c8c8621c9f44e8fd",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "minaremeli/adversarial-robustness-toolbox",
"max_forks_repo_path": "art/attacks/inference/membership_inference/shadow_model_attack.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3454f7f11c3ade9317d11637c8c8621c9f44e8fd",
"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": "minaremeli/adversarial-robustness-toolbox",
"max_issues_repo_path": "art/attacks/inference/membership_inference/shadow_model_attack.py",
"max_line_length": 154,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3454f7f11c3ade9317d11637c8c8621c9f44e8fd",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "minaremeli/adversarial-robustness-toolbox",
"max_stars_repo_path": "art/attacks/inference/membership_inference/shadow_model_attack.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 926,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 4277
} |
import copy
import os
import re
from typing import List
import numpy as np
import torch
from kornia import quaternion_to_rotation_matrix
from pose3d_utils.camera import CameraIntrinsics
from experimenting.utils import Skeleton
from ..utils import get_file_paths
from .base import BaseCore
from .h3m import h36m_cameras_extrinsic_params, h36m_cameras_intrinsic_params
class HumanCore(BaseCore):
"""
Human3.6m core class. It provides implementation to load frames, 2djoints, 3d joints
"""
RECORDING_HZ = 50
CAMS_ID_MAP = {'54138969': 0, '55011271': 1, '58860488': 2, '60457274': 3}
JOINTS = [15, 25, 17, 26, 18, 1, 6, 27, 19, 2, 7, 3, 8]
LABELS_MAP = {
'Directions': 0,
'Discussion': 1,
'Eating': 2,
'Greeting': 3,
'Phoning': 4,
'Posing': 5,
'Purchase': 6,
'Sitting': 7,
'SittingDown': 8,
'Smoking': 9,
'Photo': 10,
'Waiting': 11,
'Walking': 12,
'WalkDog': 13,
'WalkTogether': 14,
'Purchases': 15,
'_ALL': 15,
}
MAX_WIDTH = 260 # DVS resolution
MAX_HEIGHT = 346 # DVS resolution
N_JOINTS = 13
N_CLASSES = 2
TORSO_LENGTH = 453
DEFAULT_TEST_SUBJECTS: List[int] = [9, 11]
DEFAULT_TEST_VIEW = [4]
DEFAULT_TRAIN_VIEW = [0, 1, 2, 3]
def __init__(
self,
name,
data_dir,
joints_path,
partition,
n_channels,
movs=None,
test_subjects=None,
train_cams=None,
test_cams=None,
avg_torso_length=TORSO_LENGTH,
*args,
**kwargs,
):
super(HumanCore, self).__init__(name, partition)
self.file_paths = HumanCore._get_file_paths_with_movs(data_dir, movs)
self.in_shape = (HumanCore.MAX_HEIGHT, HumanCore.MAX_WIDTH)
self.n_channels = n_channels
self.avg_torso_length = avg_torso_length
self.classification_labels = [
HumanCore.get_label_from_filename(x_path) for x_path in self.file_paths
]
self.n_joints = HumanCore.N_JOINTS
self.joints = HumanCore.get_pose_data(joints_path)
self.frames_info = [HumanCore.get_frame_info(x) for x in self.file_paths]
self.timestamps_mask = self.get_timestamps_mask()
if test_subjects is None:
self.test_subjects = HumanCore.DEFAULT_TEST_SUBJECTS
else:
self.test_subjects = test_subjects
if train_cams is None:
self.train_cams = HumanCore.DEFAULT_TRAIN_VIEW
else:
self.train_cams = train_cams
if test_cams is None:
self.view = HumanCore.DEFAULT_TEST_VIEW
else:
self.view = test_cams
def get_test_subjects(self):
return self.test_subjects
def get_test_view(self):
return self.view
@staticmethod
def get_label_from_filename(filepath) -> int:
"""
Given the filepath, return the correspondent movement label (range [0, 32])
Args:
filepath (str): frame absolute filepath
Returns:
Frame label
Examples:
>>> HumanCore.get_label_from_filename("S1_session_2_mov_1_frame_249_cam_2.npy")
"""
info = HumanCore.get_frame_info(filepath)
return HumanCore.LABELS_MAP[info['action'].split(" ")[0]]
def get_frame_info_from_id(self, x):
return self.frames_info[x]
@staticmethod
def get_frame_info(filepath):
"""
>>> HumanCore.get_label_frame_info("tests/data/h3m/S1/Directions 1.54138969S1/frame0000001.npy")
{'subject': 1, 'actions': 'Directions', cam': 0, 'frame': '0000007'}
"""
base_subject_dir = filepath[re.search(r'(?<=S)\d+/', filepath).span()[1] :]
infos = base_subject_dir.split('/')
cam = re.search(r"(?<=\.)\d+", base_subject_dir)
cam = HumanCore.CAMS_ID_MAP[cam.group(0)] if cam is not None else None
result = {
"subject": int(re.search(r'(?<=S)\d+', filepath).group(0)),
"action": re.findall(r"(\w+\s?\d?)\.\d+", base_subject_dir)[0],
"cam": cam,
"frame": re.search(r"\d+", infos[-1]).group(0),
}
return result
@staticmethod
def _get_file_paths_with_movs(data_dir, movs):
file_paths = np.array(get_file_paths(data_dir, ['npy']))
if movs is not None:
mov_mask = [
HumanCore.get_label_from_filename(x) in movs for x in file_paths
]
file_paths = file_paths[mov_mask]
return file_paths
def get_timestamps_mask(self) -> np.ndarray:
"""
Return indexes corresponding to multiple of 64th frame of each recording
"""
data_indexes = np.arange(len(self.file_paths))
mask_every_n_frame = 64
freq = mask_every_n_frame / self.RECORDING_HZ
last = 0
mask = np.full(len(self.file_paths), False)
for i in data_indexes:
try:
t = self.try_get_timestamp_from_id(i)
if t < last:
last = 0
if t - last > freq:
mask[i] = True
last = t
except:
continue
return mask
@staticmethod
def get_pose_data(path: str) -> dict:
"""
Parse npz file and extract gt information (3d joints, timestamps, ...)
"""
data = np.load(path, allow_pickle=True)
result = {}
result = HumanCore._get_joints_data(data, result)
result = HumanCore._get_timestamps_data(data, result)
return result
@staticmethod
def _get_timestamps_data(data, result: dict):
result = copy.deepcopy(result)
if 'timestamps' not in data:
return result
data = data['timestamps'].item()
for subject, actions in data.items():
subject_n = int(re.search(r"\d+", subject).group(0))
if subject_n not in result:
result[subject_n] = {}
for action_name, timestamps in actions.items():
if action_name not in result[subject_n]:
result[subject_n][action_name] = {}
result[subject_n][action_name]['timestamps'] = timestamps
return result
@staticmethod
def _get_joints_data(data, result):
result = copy.deepcopy(result)
data = data['positions_3d'].item()
for subject, actions in data.items():
subject_n = int(re.search(r"\d+", subject).group(0))
if subject_n not in result:
result[subject_n] = {}
for action_name, positions in actions.items():
if action_name not in result[subject_n]:
result[subject_n][action_name] = {}
result[subject_n][action_name]['positions'] = positions
result[subject_n][action_name][
'extrinsics'
] = h36m_cameras_extrinsic_params[subject]
return result
@staticmethod
def _build_intrinsic(intrinsic_matrix_params: dict) -> torch.Tensor:
# scale to DVS frame dimension
w_ratio = HumanCore.MAX_WIDTH / intrinsic_matrix_params['res_w']
h_ratio = HumanCore.MAX_HEIGHT / intrinsic_matrix_params['res_h']
intr_linear_matrix = torch.tensor(
[
[
w_ratio * intrinsic_matrix_params['focal_length'][0],
0,
w_ratio * intrinsic_matrix_params['center'][0],
0,
],
[
0,
h_ratio * intrinsic_matrix_params['focal_length'][1],
h_ratio * intrinsic_matrix_params['center'][1],
0,
],
[0, 0, 1, 0],
]
)
return intr_linear_matrix
@staticmethod
def _build_extrinsic(extrinsic_matrix_params: dict) -> torch.Tensor:
quaternion = torch.tensor(extrinsic_matrix_params['orientation'])[[1, 2, 3, 0]]
quaternion[:3] *= -1
R = quaternion_to_rotation_matrix(quaternion)
t = torch.tensor(extrinsic_matrix_params['translation'])
tr = -torch.matmul(R, t)
return torch.cat([torch.cat([R, tr.unsqueeze(1)], dim=1)], dim=0,)
def get_joint_from_id(self, idx):
joints_data = self._get_joint_from_id(idx)
intr_matrix, extr_matrix = self.get_matrices_from_id(idx)
return Skeleton(joints_data), intr_matrix, extr_matrix
def get_matrices_from_id(self, idx):
frame_info = self.get_frame_info_from_id(idx)
intr_matrix = HumanCore._build_intrinsic(
h36m_cameras_intrinsic_params[frame_info['cam']]
)
extr = self.joints[frame_info['subject']][frame_info['action']]['extrinsics'][
frame_info['cam']
]
extr_matrix = HumanCore._build_extrinsic(extr)
return intr_matrix, extr_matrix
def _get_id_from_path(self, path):
return np.where(self.file_paths == path)
def _get_joint_from_id(self, idx):
frame_info = self.get_frame_info_from_id(idx)
frame_n = int(frame_info['frame'])
joints_data = self.joints[frame_info['subject']][frame_info['action']][
'positions'
][frame_n]
joints_data = joints_data[HumanCore.JOINTS] * 1000 # Scale to cm
return joints_data
def try_get_timestamp_from_id(self, idx):
try:
frame_info = self.get_frame_info_from_id(idx)
frame_n = int(frame_info['frame'])
timestamp = self.joints[frame_info['subject']][frame_info['action']][
'timestamps'
][frame_n]
except:
print("Timestamps missing")
raise Exception("Timestamp not found")
return timestamp
def get_frame_from_id(self, idx):
path = self.file_paths[idx]
x = np.load(path, allow_pickle=True) / 255.0
if len(x.shape) == 2:
x = np.expand_dims(x, -1)
return x
def get_cross_subject_partition_function(self):
"""
Get partition function for cross-subject evaluation method. Keep 64th frame
Note:
Core class must implement get_test_subjects
get_frame_info must provide frame's subject
"""
def _get(x):
return (self.frames_info[x]['subject'] in self.get_test_subjects()
and self.timestamps_mask[x])
return _get
# return lambda x: (
# self.frames_info[x]['subject'] in self.get_test_subjects()
# and self.timestamps_mask[x]
# )
def get_cross_view_partition_function(self):
"""
Get partition function for cross-subject evaluation method. Keep 64th frame
Note:
Core class must implement get_test_subjects
get_frame_info must provide frame's subject
"""
def _get(x):
return (self.frames_info[x]['subject'] in self.get_test_subjects()
and self.timestamps_mask[x]
and self.frames_info[x]['cam'] in self.get_test_view())
return _get
# return lambda x: (
# self.frames_info[x]['subject'] in self.get_test_subjects()
# and self.timestamps_mask[x]
# and self.frames_info[x]['cam'] in self.get_test_view()
# )
def train_partition_function(self, x):
return self.frames_info[x]['subject'] not in self.test_subjects and self.frames_info[x]['cam'] in self.train_cams
| {
"alphanum_fraction": 0.5851543236,
"author": null,
"avg_line_length": 32.0463215259,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "d3dd0517ebadd7750ce3a17958ee21ff212de265",
"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": "dfe734ee055900d6ab90c064bf82db7672830ac7",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "miracleyoo/lifting_events_to_3d_hpe",
"max_forks_repo_path": "scripts/experimenting/dataset/core/h3mcore.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "dfe734ee055900d6ab90c064bf82db7672830ac7",
"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": "miracleyoo/lifting_events_to_3d_hpe",
"max_issues_repo_path": "scripts/experimenting/dataset/core/h3mcore.py",
"max_line_length": 121,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "dfe734ee055900d6ab90c064bf82db7672830ac7",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "miracleyoo/lifting_events_to_3d_hpe",
"max_stars_repo_path": "scripts/experimenting/dataset/core/h3mcore.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2768,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 11761
} |
import pyximport; pyximport.install(pyimport=True)
import numpy as np
from gensim.models.callbacks import CallbackAny2Vec
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from vectorize.template import Vectorizer
class EpochLogger(CallbackAny2Vec):
'''Callback to log information about training'''
def __init__(self):
self.epoch = 1
def on_epoch_begin(self, model):
print("Epoch #{} start".format(self.epoch))
def on_epoch_end(self, model):
print("Epoch #{} done".format(self.epoch))
self.epoch += 1
class Doc2VecVectorizer(Vectorizer):
def __init__(self, is_expand_query=False):
super().__init__(is_expand_query)
self.vectroizer = None
def _initalize_model(self, corpus):
corpus = [TaggedDocument(document, [i]) for i, document in enumerate(corpus)]
callbacks = []
# callbacks = [EpochLogger()]
self.vectroizer = Doc2Vec(vector_size=100, min_count=2, epochs=50, callbacks=callbacks)
self.vectroizer.build_vocab(corpus)
self.vectroizer.train(corpus, total_examples=self.vectroizer.corpus_count,
epochs=self.vectroizer.epochs)
def vectorize_documents(self, documents):
corpus = [[word for section in document.sections() for word in section.tokenized]
for i, document in enumerate(documents)]
self._initalize_model(corpus)
return np.array([self.vectroizer.infer_vector(document) for document in corpus])
def vectorize_query(self, query, query_preprocessor):
query = self.prepare_query(query, query_preprocessor)[0]
return np.array([self.vectroizer.infer_vector(query)])
| {
"alphanum_fraction": 0.6924428822,
"author": null,
"avg_line_length": 34.8367346939,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "6ee99b142cad1c2e5018f053e946c8b889b7f6f2",
"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": "2a9e0066e766d8a356a2c4a1ebd51c0aeb3cd4b6",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "SSK-14/Covid19-Search-Engine",
"max_forks_repo_path": "vectorize/doc2vec.py",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "2a9e0066e766d8a356a2c4a1ebd51c0aeb3cd4b6",
"max_issues_repo_issues_event_max_datetime": "2020-05-06T14:28:10.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-05-06T14:28:10.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "SSK-14/Covid19-Search-Engine",
"max_issues_repo_path": "vectorize/doc2vec.py",
"max_line_length": 95,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "2a9e0066e766d8a356a2c4a1ebd51c0aeb3cd4b6",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "SSK-14/Covid19-Search-Engine",
"max_stars_repo_path": "vectorize/doc2vec.py",
"max_stars_repo_stars_event_max_datetime": "2020-06-14T16:52:55.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-06-14T16:52:55.000Z",
"num_tokens": 393,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1707
} |
from collections import defaultdict
import networkx as nx
for part in ['0', '1']:
partial_VP = set(open('chooseVP' + part + '.txt', 'r').read().split('\n'))
fullVP = set(open('fullVP.txt', 'r').read().split('\n'))
fullVP1 = partial_VP & fullVP
graph1 = nx.Graph()
graph2 = nx.Graph()
with open('asrel' + part + '.txt') as f:
for line in f:
if line.startswith('#'):
continue
[asn1, asn2, rel] = line.strip().split('|')
graph1.add_edge(asn1, asn2)
with open('asrel.txt') as f:
for line in f:
if line.startswith('#'):
continue
[asn1, asn2, rel] = line.strip().split('|')
graph2.add_edge(asn1, asn2)
miss = set()
for edge in graph2.edges():
(a, b) = edge
if a in fullVP or b in fullVP:
if a in graph1.nodes() and b in graph1.nodes():
miss.add((a, b))
data = []
pos = defaultdict(set)
cnt = 0
with open('aspaths' + part + '.txt') as f:
for line in f:
if len(line.strip()) == 0:
continue
path = line.strip().split("|")
data.append(path)
cnt += 1
for i in range(len(path)):
pos[path[i]].add(cnt - 1)
path = defaultdict(set)
for edge in miss:
(a, b) = edge
local = pos[a] & pos[b]
for l in local:
i = data[l].index(a)
j = data[l].index(b)
if (i == 0 or j == 0) and data[l][0] in fullVP1:
continue
if j - i != 2 and j - i != -2:
continue
if i < j:
path[edge].add('|'.join(data[l][i:j+1]))
else:
path[edge].add('|'.join(data[l][j:i+1][::-1]))
fout = open('triplet_miss' + part + '.txt', 'w')
for key in path:
fout.write('|'.join(key) + '&' + '#'.join(path[key]) + '\n')
fout.close() | {
"alphanum_fraction": 0.4538192711,
"author": null,
"avg_line_length": 33.3833333333,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "a7d3c7f04486c27fde9256a7b6e2fe063a70125c",
"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": "e995f67983a3d67ae909c688cd3bb0d7c5adc849",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "maq18/TopoScope",
"max_forks_repo_path": "getMissEdge.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e995f67983a3d67ae909c688cd3bb0d7c5adc849",
"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": "maq18/TopoScope",
"max_issues_repo_path": "getMissEdge.py",
"max_line_length": 78,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e995f67983a3d67ae909c688cd3bb0d7c5adc849",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "maq18/TopoScope",
"max_stars_repo_path": "getMissEdge.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 550,
"path": null,
"reason": "import networkx",
"repo": null,
"save_path": null,
"sha": null,
"size": 2003
} |
import topogenesis as tg
import numpy as np
import os
file_directory = os.path.dirname(os.path.abspath(__file__))
sample_data_path = os.path.join(os.path.dirname(file_directory), "data")
np.random.seed(0)
def test_cellular_automata():
"""
Testing the vectorized version of newell method for finding the normal of a triangle with hardcoded data
"""
# Setup
#######
# initiate stencil
s = tg.create_stencil("moore", 1) # create a step one moore neighbourhood
s.set_index([0, 0, 0], 0) # set the center to 0
s.function = tg.sfunc.sum # assign the sum function
"""
print(s)
[[[1 1 1]
[1 1 1]
[1 1 1]]
[[1 1 1]
[1 0 1]
[1 1 1]]
[[1 1 1]
[1 1 1]
[1 1 1]]]
"""
# initiate lattice
l = tg.lattice([[0, -1, -1], [0, 1, 1]], default_value=0, dtype=int)
l[0, :, 1] += 1
"""
print(l)
[[[0 1 0]
[0 1 0]
[0 1 0]]]
"""
expected_lattice = np.array([[[0, 0, 0],
[1, 1, 1],
[0, 0, 0]]])
# Exercise
##########
neighbor_sum = l.apply_stencil(s) # apply the stencil on the lattice
# apply cellular automata rules
# turn off if less than 2 or more than 3
l *= (neighbor_sum >= 2) * (neighbor_sum <= 3)
l[(neighbor_sum == 3)] = 1 # turn on if 3 neighbours are on
computed_latice = l
# Verify
np.testing.assert_allclose(
computed_latice, expected_lattice, rtol=1e-6, atol=0)
# Cleanup
def test_gradient_decent():
"""
Testing the vectorized version of newell method for finding the normal of a triangle with hardcoded data
"""
# Setup
#######
# initiate stencil
# create a step one moore neighbourhood
s = tg.create_stencil("von_neumann", 1)
s.function = tg.sfunc.argmin # assign the arg-minimum function
"""
print(s)
[[[0 0 0]
[0 1 0]
[0 0 0]]
[[0 1 0]
[1 1 1]
[0 1 0]]
[[0 0 0]
[0 1 0]
[0 0 0]]]
"""
# initialize a 2d lattice with random values
r = np.random.rand(1, 5, 5)
l_vals = tg.to_lattice(r, [0, 0, 0])
"""
print(l_vals)
[[[0.5488135 0.71518937 0.60276338 0.54488318 0.4236548 ]
[0.64589411 0.43758721 0.891773 0.96366276 0.38344152]
[0.79172504 0.52889492 0.56804456 0.92559664 0.07103606]
[0.0871293 0.0202184 0.83261985 0.77815675 0.87001215]
[0.97861834 0.79915856 0.46147936 0.78052918 0.11827443]]]
"""
# initialize walkers lattice
z = np.zeros((1, 5, 5))
l_walk = tg.to_lattice(z, [0, 0, 0])
l_walk[0, 2, 2] += 1
"""
print(l_walk)
[[[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0.]]]
"""
# retrieve lattice indices
l_inds = l_vals.indices
"""
print(l_inds)
[[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]]
"""
expected_lattice = np.array([[[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0.]]])
# Exercise
##########
# apply the stencil (function) to the lattice
local_min_neighbour = l_vals.arg_apply_stencil(
l_inds, s, border_condition="pad_outside", padding_value=1.0)
# convert the current positions id and selected neighbour id to lattice indices
old_pos = np.array(np.unravel_index(l_inds[l_walk > 0], l_walk.shape))
new_pos = np.array(np.unravel_index(
local_min_neighbour[l_walk > 0], l_walk.shape))
# apply the movements
l_walk[old_pos[0], old_pos[1], old_pos[2]] -= 1
l_walk[new_pos[0], new_pos[1], new_pos[2]] += 1
computed_latice = l_walk
# Verify
########
np.testing.assert_allclose(
computed_latice, expected_lattice, rtol=1e-6, atol=0)
# Cleanup
#########
def test_boolean_marching_cubes():
"""
Testing the vectorized version of newell method for finding the normal of a triangle with hardcoded data
"""
# Setup
#######
# Specifing all the inputs
vs = 0.05 # voxel size
unit = [vs, vs, vs] # unit size
tol = 1e-09 # intersection tolerance
mesh_path = os.path.relpath('data/bunny_lowpoly.obj')
original_mesh = tg.geometry.load_mesh(mesh_path)
expected_lattice = np.array([[[0, 128, 136, 8],
[0, 160, 170, 10],
[128, 168, 170, 10],
[160, 42, 34, 2]],
[[128, 200, 204, 12],
[160, 250, 255, 15],
[224, 254, 255, 15],
[240, 191, 59, 3]],
[[192, 204, 204, 12],
[240, 255, 255, 15],
[240, 255, 255, 15],
[240, 255, 63, 3]],
[[192, 204, 204, 12],
[112, 247, 255, 15],
[80, 117, 119, 7],
[80, 85, 21, 1]],
[[64, 68, 68, 4],
[16, 81, 85, 5],
[0, 16, 17, 1],
[0, 0, 0, 0]]])
# Exercise
##########
# Sampling the mesh and constructing the point cloud
sample_cloud = tg.geometry.mesh_sampling(original_mesh, unit, tol=tol)
# Voxelating the point cloud to construct the lattice
lattice = sample_cloud.voxelate(unit, closed=True)
# Constructing the Cube Lattice using the Boolea Marching Cube Algorithm
cube_lattice = lattice.boolean_marching_cubes()
computed_latice = cube_lattice
# Verify
########
np.testing.assert_allclose(
computed_latice, expected_lattice, rtol=1e-6, atol=0)
# Cleanup
#########
def test_abm_random_walker():
"""
Testing the vectorized version of newell method for finding the normal of a triangle with hardcoded data
"""
# Setup
#######
# initiate stencil
# create a step one moore neighbourhood
s = tg.create_stencil("von_neumann", 1)
# set the center to 0, to prevent staying at the same point
s.set_index([0, 0, 0], 0)
# set the x-dimension to 0, since we are working in 2d
s.set_index([1, 0, 0], 0)
s.set_index([-1, 0, 0], 0)
# assign the random choice function
s.function = tg.sfunc.random_choice
"""
print(s)
[[[0 0 0]
[0 0 0]
[0 0 0]]
[[0 1 0]
[1 0 1]
[0 1 0]]
[[0 0 0]
[0 0 0]
[0 0 0]]]
"""
# initiate the lattice 0x7x7
l = tg.lattice([[0, -3, -3], [0, 3, 3]], default_value=0, dtype=int)
# place the walker in the center of the lattice
l[0, 3, 3] += 1
"""
print(l)
[[[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 1 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]
[0 0 0 0 0 0 0]]]
"""
# retrieve the indices of cells (0,1,2, ... n)
l_inds = l.indices
"""
print(l_inds)
[[[ 0 1 2 3 4 5 6]
[ 7 8 9 10 11 12 13]
[14 15 16 17 18 19 20]
[21 22 23 24 25 26 27]
[28 29 30 31 32 33 34]
[35 36 37 38 39 40 41]
[42 43 44 45 46 47 48]]]
"""
expected_lattice = np.array([[[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]]])
# Exercise
##########
# apply the stencil (function) to the lattice
random_neighbour = l_inds.apply_stencil(s, border_condition="roll")
# convert the current positions id and selected neighbour id to lattice indices
old_pos = np.array(np.unravel_index(l_inds[l > 0], l.shape))
new_pos = np.array(np.unravel_index(random_neighbour[l > 0], l.shape))
# apply the movements
l[old_pos[0], old_pos[1], old_pos[2]] -= 1
l[new_pos[0], new_pos[1], new_pos[2]] += 1
computed_latice = l
# Verify
########
np.testing.assert_allclose(
computed_latice, expected_lattice, rtol=1e-6, atol=0)
# Cleanup
#########
| {
"alphanum_fraction": 0.490781286,
"author": null,
"avg_line_length": 26.296969697,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "02538783149a05850747136b00d40981d99363c2",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2020-11-19T15:09:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-11-19T15:09:53.000Z",
"max_forks_repo_head_hexsha": "5c73a5adf4afbda781540c6c08d24e2da62810b8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "shervinazadi/topoGenesis",
"max_forks_repo_path": "tests/test_simulations.py",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "5c73a5adf4afbda781540c6c08d24e2da62810b8",
"max_issues_repo_issues_event_max_datetime": "2020-12-17T18:06:01.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-11-23T16:59:21.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "shervinazadi/topoGenesis",
"max_issues_repo_path": "tests/test_simulations.py",
"max_line_length": 108,
"max_stars_count": 11,
"max_stars_repo_head_hexsha": "5c73a5adf4afbda781540c6c08d24e2da62810b8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "shervinazadi/topoGenesis",
"max_stars_repo_path": "tests/test_simulations.py",
"max_stars_repo_stars_event_max_datetime": "2022-01-09T10:16:39.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-09-07T09:29:01.000Z",
"num_tokens": 2951,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 8678
} |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 4 14:10:15 2018
@author: ashreeta
"""
import os
import matplotlib.pyplot as plt
import pandas as pd
import datetime
import grimsel.auxiliary.timemap as timemap
from PROFILE_READER.profile_reader import ProfileReader
svg_file = "/mnt/data/Dropbox/SHARED_DATA/AGORA_SVGS"
fn = 'erzeugung_verbrauch_2012_12.svg'
svg_file = os.path.join(svg_file, fn)
from xml.dom import minidom
class AgoraReader(ProfileReader):
'''
'''
dict_sql_default = dict(sc='profiles_raw', tb='agora_profiles',
db='storage2')
data_dir = os.path.normpath('AGORA_SVGS')
# sql table columns
tb_cols = [('"DateTime"', 'TIMESTAMP'),
('nd_id', 'VARCHAR'),
('fl_id', 'VARCHAR'),
('value', 'DOUBLE PRECISION'),
('year', 'SMALLINT'),
# ('hy', 'SMALLINT')
]
# sql table primary key
tb_pk = ['fl_id', '"DateTime"']
# ''' lignite demand '''
dict_scale_shift = {('2012', '01'): (15.247, 52.111),
('2012', '10'): (20.917, 58.786), # monday after last sunday
('2013', '01'): ( 9.439, 52.782),
('2013', '10'): (11.533, 53.895), # monday after last sunday
('2014', '01'): (16.869, 51.914),
('2014', '10'): (19.626, 54.932), # monday after last sunday
('2015', '01'): (17.526, 54.423),
('2015', '10'): (18.430, 53.173), # monday after last sunday
('2016', '01'): (15.727, 53.277),
('2016', '10'): (18.313, 52.303), # monday after last sunday
('2017', '01'): (13.854, 52.841),
('2017', '10'): (8.187, 53.112), # monday after last sunday
}
dict_fl = {
('2012', '10'): {56: 'wind_offshore', 54: 'photovoltaics',
49: 'pumped_hydro', 57: 'hydro_total',
48: 'others', 58: 'bio_all',
55: 'wind_onshore', 50: 'natural_gas',
51: 'hard_coal', 53: 'nuclear_fuel',
52: 'lignite', 59: 'dmnd'},
('2013', '10'): {53: 'wind_offshore', 51: 'photovoltaics',
46: 'pumped_hydro', 45: 'others',
54: 'hydro_total', 48: 'hard_coal',
55: 'bio_all', 47: 'natural_gas',
50: 'nuclear_fuel', 49: 'lignite',
52: 'wind_onshore', 56: 'dmnd'},
('2014', '10'): {51: 'wind_offshore', 49: 'photovoltaics',
44: 'pumped_hydro', 43: 'others',
52: 'hydro_total', 53: 'bio_all',
50: 'wind_onshore', 45: 'natural_gas',
46: 'hard_coal', 48: 'nuclear_fuel',
47: 'lignite', 54: 'dmnd'},
('2015', '10'): {52: 'photovoltaics', 55: 'hydro_total',
47: 'pumped_hydro', 54: 'wind_offshore',
53: 'wind_onshore', 46: 'others',
56: 'bio_all', 48: 'natural_gas',
51: 'nuclear_fuel', 49: 'hard_coal',
50: 'lignite', 57: 'dmnd'},
('2017', '10'): {51: 'photovoltaics',
52: 'wind_onshore', # 53
50: 'nuclear_fuel',
49: 'lignite', #52
48: 'hard_coal', # 53
47: 'natural_gas',
44: 'others',# 46
53: 'wind_offshore', # 54
54: 'hydro_total', #55
46: 'pumped_hydro',#53
55: 'bio_all', #56
56: 'dmnd'},
('all', '01'): {40: 'others', 41: 'pumped_hydro',
42: 'natural_gas', 43: 'hard_coal',
44: 'lignite', 45: 'nuclear_fuel',
46: 'photovoltaics', 47: 'wind_onshore',
48: 'wind_offshore', 49: 'hydro_total',
50: 'bio_all', 51: 'dmnd'},
('2017', '01'): {49: 'photovoltaics', # 46
53: 'bio_all', # 50
52: 'hydro_total', #49
50: 'wind_onshore', #47
48: 'nuclear_fuel', #45
47: 'lignite', #44
46: 'hard_coal', #43
45: 'natural_gas', #42
44: 'pumped_hydro', #41
42: 'others', #40
40: 'wind_offshore', # 48
51: 'dmnd'},
('2016', '10'): {54: 'photovoltaics',
52: 'lignite',
53: 'nuclear_fuel',
58: 'bio_all',
56: 'wind_offshore',
50: 'natural_gas',
48: 'others',
55: 'wind_onshore',
51: 'hard_coal',
49: 'pumped_hydro',
# 57: 'dmnd',
59: 'hydro_total',
},
# ('2016', '10'): {54: 'photovoltaics',
# : 'hydro_total',
# : 'pumped_hydro',
# : 'wind_offshore',
# : 'wind_onshore',
# : 'others',
# : 'bio_all',
# : 'natural_gas',
# : 'nuclear_fuel',
# : 'hard_coal',
# : 'lignite',
# : 'dmnd'}
}
#self.df_tot_mod.loc[(self.df_tot_mod.DateTime > '2016-12-19 23:00:00+00:00')
# ].pivot_table(columns='fl_id', index='DateTime', values='value').plot.area()
#
#self.df_tot_mod.loc[(self.df_tot_mod.DateTime > '2016-12-20 00:00:00+01:00')].pivot_table(values='value',
# columns='fl_id',
# index='DateTime').abs().plot.area()
def __init__(self, kw_dict):
super().__init__(**kw_dict)
self.last_row = None
self.dict_fl.update({(str(year), '01'): self.dict_fl[('all', '01')]
for year in range(2012, 2018)
if not (str(year), '01') in self.dict_fl.keys()})
def single_post_processing(self, df):
return df
def read(self, fn):
# %
doc = minidom.parse(fn) # parseString also exists
path_strings = [path.getAttribute('d') for path
in doc.getElementsByTagName('path')]
doc.unlink()
yr, mt = fn.split(os.path.sep)[-1].split('.')[0].split('_')[-2:]
# some pre-filtering to get the relevant (i.e. long) paths
list_path = [(npath, len(path),)
for npath, path in enumerate(path_strings)
if len(path) > 200]
# init dataframes to hold all series of the current month
df_tot = pd.DataFrame()
df_tot_dmnd = pd.DataFrame()
# path = [pp for pp in list_path if pp[0] == 51][0]
for path in list_path:
# get dataframe from path
df = pd.DataFrame([pp.replace('M ', '').split(' ')
for pp in path_strings[path[0]].split(' L ')])
# df.applymap(float).plot.scatter(x=0, y=1, linewidth=1)
df = df.applymap(float).set_index(0)[1]
df = df.reset_index()
df.loc[df[0].shift(1) <= df[0], 'dir'] = 'lr'
df.loc[df[0].shift(1) >= df[0], 'dir'] = 'rl'
df['dir'] = df['dir'].fillna('lr')
df_stack = df.pivot_table(values=1, index=0, columns='dir')
df_stack[path[0]] = df_stack.rl - df_stack.lr if 'rl' in df_stack.columns else df_stack.lr
df_stack = df_stack.reset_index(drop=True)
if 'rl' in df_stack.columns:
# df_stack[path[0]].plot.area()
df_tot = pd.concat([df_tot, df_stack[path[0]]], axis=1)
else:
df_tot_dmnd = pd.concat([df_tot_dmnd, df_stack[path[0]]], axis=1)
df_tot = df_tot.T.drop_duplicates().T
df_tot_dmnd = df_tot_dmnd.T.drop_duplicates().T
mtf = int(mt.replace('a', '').replace('b', ''))
yrf = int(yr)
yr_next = yrf if mtf < 12 else yrf + 1
mt_next = mtf + 1 if mtf < 12 else 1
dftm = pd.DataFrame(index=pd.date_range('{}-{:02d}-01'.format(yrf, mtf),
'{}-{:02d}-01 23:30:00'.format(yr_next, mt_next),
tz='Europe/Berlin', freq='H'))
dftm = dftm.reset_index().rename(columns={'index': 'DateTime'})
# get last sunday
last_sunday = dftm.loc[(dftm.DateTime.dt.dayofweek == 6)
& (dftm.DateTime.dt.month == mtf), 'DateTime'].dt.date.iloc[-1]
if '10a' in fn:
# month ends with 'last sunday'
dftm = dftm.loc[dftm.DateTime.dt.date < last_sunday]
dftm = dftm.reset_index(drop=True)
elif '10b' in fn:
# month begins after 'last sunday'
dftm = dftm.loc[dftm.DateTime.dt.date > last_sunday]
dftm = dftm.reset_index(drop=True)
df_tot = pd.concat([dftm, df_tot, df_tot_dmnd], axis=1)
df_tot = df_tot.set_index('DateTime')
df_tot = df_tot.stack().reset_index()
df_tot = df_tot.rename(columns={'level_0': 'DateTime', 'level_1': 'fl_id', 0: 'value'})
df_tot['mt'] = mt
df_tot['year'] = yr
# %
return df_tot
def align_and_scale(self, df, year):
#%
print('?'*60 + '\n', year)
df['dtday'] = df.DateTime.dt.day.apply(lambda x: '{:02d}'.format(x))
df['dtmonth'] = df.DateTime.dt.month.apply(lambda x: '{:02d}'.format(x))
df['dtyear'] = df.DateTime.dt.year.apply(str)
df['dtdate'] = df[['dtyear', 'dtmonth', 'dtday']].apply(lambda x: ' '.join(x), axis=1)
df = df.sort_values(['DateTime'])
# NOTE: mt is month from file name
list_mt = df['mt'].drop_duplicates().values
dfg = df.groupby(['mt'])
# get last row of first month ever
dfg_slct = dfg.get_group(list_mt[0])
dfg_slct.loc[:, 'fl_id'] = dfg_slct.fl_id.replace(self.dict_fl[(year, '01')])
scale_power = (self.dict_scale_shift[(str(year), '01')][0]
/ dfg_slct.loc[dfg_slct.fl_id.isin(['lignite'])].value.iloc[0])
dfg_slct['value'] *= scale_power
# get the last date, which should be the first date in the next file
last_date = dfg_slct.dtdate.iloc[-1]
# get the average production of the last day, to be matched with the next
sum_last_day = dfg_slct.loc[dfg_slct.dtdate == last_date]
sum_last_day = sum_last_day.pivot_table(index='fl_id', values='value')
df_tot_new = dfg_slct.copy()
# start with second month ever
mt = list_mt[1]
for mt in list_mt[1:]:
print('$'*60 + '\n', mt)
#
dfg_slct = dfg.get_group(mt)
if not mt == '10b':
first_date = last_date
else:
first_date = dfg_slct.dtdate.iloc[0]
# get the average production of the last day, to be matched with the next
sum_first_day = dfg_slct.loc[dfg_slct.dtdate == first_date]
sum_first_day= sum_first_day.pivot_table(index='fl_id', values='value')
df_fl_map = pd.concat([sum_first_day.sort_values('value').reset_index(),
sum_last_day.sort_values('value').reset_index().rename(columns={'fl_id': 'fl_last', 'value': 'value_last'})
], axis=1)
df_fl_map ['scale_power'] = df_fl_map['value_last'] / df_fl_map.value
print(df_fl_map)
if not mt == '10b':
dict_fl_map = df_fl_map.set_index('fl_id')['fl_last'].to_dict()
else:
dict_fl_map = self.dict_fl[(year, '10')]
# map fl in dfg_slct
dfg_slct.loc[:, 'fl_id'] = dfg_slct.fl_id.replace(dict_fl_map)
if not mt == '10b':
# no valid scaling factor calculated for 10b
scale_power = df_fl_map.scale_power.mean()
else:
scale_power = (self.dict_scale_shift[(str(year), '10')][0]
/ dfg_slct.loc[dfg_slct.fl_id.isin(['lignite'])].value.iloc[0])
# scale, assuming the scaling factor doesn't change
dfg_slct['value'] *= scale_power
df_tot_new = df_tot_new.loc[-df_tot_new.dtdate.isin([last_date])]
df_tot_new = pd.concat([df_tot_new, dfg_slct])
# redefine last_date
last_date = dfg_slct.dtdate.iloc[-1]
# get the average production of the last day, to be matched with the next
sum_last_day = dfg_slct.loc[dfg_slct.dtdate == last_date]
sum_last_day = sum_last_day.pivot_table(index='fl_id', values='value')
# %
# df_tot_new = df_tot_new.drop_duplicates()
# shift demand
df_tot_new.loc[df_tot_new.fl_id == 'dmnd', 'value'] *= -1
shift_dmnd = (self.dict_scale_shift[(str(year), '01')][1]
- df_tot_new.loc[df_tot_new.fl_id == 'dmnd', 'value'].iloc[0])
df_tot_new.loc[df_tot_new.fl_id == 'dmnd', 'value'] += shift_dmnd
return df_tot_new
def postprocessing_tot(self):
dftotg = self.df_tot.copy().groupby('year')
self.df_tot_mod = pd.DataFrame()
iyr = '2017'
for iyr in list(dftotg.groups.keys()):
df = dftotg.get_group(iyr)
year = iyr
print(year, iyr)
df_add = self.align_and_scale(df, year)
df_add = df_add.loc[df_add.DateTime.dt.year == int(year)]
self.df_tot_mod = pd.concat([self.df_tot_mod, df_add])
self.df_tot_mod['DateTime'] = self.df_tot_mod.DateTime.dt.tz_convert('UTC')
self.df_tot_mod = self.df_tot_mod[[c for c in self.df_tot_mod
if not (c in
['year', 'mt'] or 'dt' in c)]]
self.df_tot_mod.loc[:, 'year'] = self.df_tot_mod.DateTime.dt.year
# self.df_tot_mod = self.get_hour_of_the_year(self.df_tot_mod)
self.df_tot_mod = self.filter_years_by_data_length(self.df_tot_mod)
self.df_tot_mod['nd_id'] = 'DE0'
#
# self.df_tot_mod = (self.df_tot_mod.set_index('DateTime')
# .drop_duplicates()
# .reset_index())
#
for df in self.df_tot_mod.groupby(['fl_id']):
print(df[1].iloc[:3])
self.append_to_sql(df[1])
#
# from grimsel_h.auxiliary.aux_general import print_full
# print_full(
# self.df_tot_mod.loc[self.df_tot_mod.fl_id.isin(['hard_coal'])
# & (self.df_tot_mod.DateTime >= '2012-12-31 00:00:00')
# & (self.df_tot_mod.DateTime <= '2013-01-02 23:00:00')].sort_values('DateTime')
# )
#
# %
if __name__ == '__main__':
kw_dict = dict(dict_sql=dict(db='storage2'),
tm_filt={'year': range(2005, 2018)},
col_filt=[], ext='svg', exclude_substrings=['ch_2'])
op = AgoraReader(kw_dict)
op.get_fn_list()
self = op
fn = op.fn_list[1]
fn = [f for f in op.fn_list if '2017_02' in f][0]
op.read_all(skip_sql=True)
op.postprocessing_tot()
#%%
if __name__ == '__main__':
#
#self.df_tot.loc[self.df_tot.year.isin(['2016'])
# & (self.df_tot.DateTime > '2016-10-10 00:00:00+02:00')].pivot_table(columns='fl_id', index='DateTime', values='value').plot.area()
do = pltpg.PlotPageData.from_df(df=self.df_tot_mod.loc[self.df_tot_mod.year.isin(['2016', '2017'])
& (self.df_tot_mod.DateTime > '2016-10-10 00:00:00+02:00')
& -(self.df_tot_mod.fl_id.isin(['dmnd', 'hydro_total', 'hard_coal']))],
ind_pltx=[], ind_plty=[], ind_axx=['DateTime'],
series=['fl_id'], values='value')
layout_kw = {'left': 0.05, 'right': 0.875, 'wspace': 0.2, 'hspace': 0.2, 'bottom': 0.1}
label_kw = {'label_format':' {:.3f}', 'label_subset':[0], 'label_threshold':1e-6,
'label_ha': 'left'}
plot_kw = dict(kind_def='StackedArea', stacked=True, on_values=True, sharex=True,
sharey=True, linewidth=0,
colormap=False, barwidth=1, linecolor='k', opacitymap=1,
reset_xticklabels=False, legend='plots', marker='o')
plt_0 = pltpg.PlotTiled(do, **layout_kw, **label_kw, **plot_kw)
# %%
#%%
self.df_tot_mod
ax = self.df_tot_mod.loc[self.df_tot_mod.fl_id.isin(['wind_onshore', 'wind_offshore', 'photovoltaics'])].pivot_table(aggfunc=sum, index='DateTime', columns='fl_id', values='value').abs().plot.area()
#self.df_tot_mod.loc[self.df_tot_mod.fl_id == 'dmnd'].pivot_table(aggfunc=sum, index='DateTime', columns='fl_id', values='value').abs().plot(ax=ax, marker='o', color='k')
# %%
df = self.df_tot_mod.copy()
df['DateTime'] = df.DateTime.dt.tz_convert('Europe/Berlin')
df.loc[df.DateTime.dt.year.isin([2015])
& df.DateTime.dt.month.isin([10])
# & df.DateTime.dt.day.isin([29])
# & (df.fl_id == 'wind_offshore')
].pivot_table(index='fl_id', columns='hy', values='value').iloc[:, [0, -1]]
# %%
data_kw = {'data_scale': 1, 'aggfunc': np.mean, 'data_threshold': 1e-10}
indx_kw = dict(ind_axx=['DateTime'], ind_pltx=[],
ind_plty=['year'], series=['fl_id'],
values=['value'],
filt=[('fl_id', ['wind_onshore', 'wind_offshore', 'photovoltaics', 'dmnd'])])
do = pltpg.PlotPageData(db=db, table='profiles_raw.agora_profiles', **indx_kw, **data_kw)
layout_kw = {'left': 0.05, 'right': 0.875, 'wspace': 0.2, 'hspace': 0.2, 'bottom': 0.1}
label_kw = {'label_format':' {:.2f}', 'label_subset':[0], 'label_threshold':1e-6,
'label_ha': 'left'}
plot_kw = dict(kind_def='StackedArea', stacked=True, on_values=False, sharex=True,
sharey=True,
colormap=False, barwidth=1, linecolor='k', opacitymap=1,
reset_xticklabels=False, legend='plots', marker='o')
with plt.style.context(('ggplot')):
plt_0 = pltpg.PlotTiled(do, **layout_kw, **label_kw, **plot_kw)
# %%
import pandas as pd
import grimsel_h.auxiliary.aux_sql_func as aql
from grimsel_h.auxiliary.aux_general import print_full
import grimsel_h.plotting.plotpage as pltpg
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
df = pd.DataFrame(aql.exec_sql('''
WITH tb_dmnd AS (
SELECT "DateTime", value AS dmnd, year FROM profiles_raw.agora_profiles
WHERE fl_id = 'dmnd'
), tb_vre AS (
SELECT "DateTime", SUM(value) AS vre, year FROM profiles_raw.agora_profiles
WHERE fl_id LIKE 'wind%' OR fl_id LIKE 'photo%'
GROUP BY "DateTime", year
), tb_mc AS (
SELECT "DateTime", value AS mc, year FROM profiles_raw.epex_price_volumes
WHERE nd_id = 'DE0' and quantity = 'price_eur_mwh' AND year IN (2012, 2013, 2014, 2015)
)
SELECT 'DE0' AS nd_id, "DateTime", year, dmnd, vre, dmnd - vre AS resload, mc fROM tb_dmnd
NATURAL LEFT JOIN tb_vre
NATURAL LEFT JOIN tb_mc;
''', db='storage2'), columns=['nd_id', 'DateTime', 'year', 'dmnd', 'vre', 'resload', 'mc'])
#cmap = mpl.cm.get_cmap('Spectral') # Colour map (there are many others)
#df.plot.scatter(x='resload', y='mc', c='year', cmap=cmap)
df.loc[df.DateTime.dt.date == datetime.date(2012, 1,1)]
data_kw = {'data_scale': 1, 'aggfunc': np.mean, 'data_threshold': 1e-10}
indx_kw = dict(ind_axx=['resload'], ind_pltx=[],
ind_plty=['year'], series=['nd_id'],
values=['mc'])
do = pltpg.PlotPageData.fromdataframe(df=df, **indx_kw, **data_kw)
layout_kw = {'left': 0.05, 'right': 0.875, 'wspace': 0.2, 'hspace': 0.2, 'bottom': 0.1}
label_kw = {'label_format':' {:.2f}', 'label_subset':[0], 'label_threshold':1e-6,
'label_ha': 'left'}
plot_kw = dict(kind_def='plot.line', stacked=False, on_values=False, sharex=True,
sharey=True, linewidth=0,
colormap=False, barwidth=1, linecolor='k', opacitymap=1,
reset_xticklabels=False, legend='plots', marker='o')
with plt.style.context(('ggplot')):
plt_0 = pltpg.PlotTiled(do, **layout_kw, **label_kw, **plot_kw)
for ax in plt_0.axarr.flatten():
ax.set_ylim([-100, 150])
| {
"alphanum_fraction": 0.4782208185,
"author": null,
"avg_line_length": 41.0756756757,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "369ad70695c7c8b11e73ae032500b73c2c4d1407",
"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": "c14806116cd20ba83620ded90832498451ed9597",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "mcsoini/PROFILE_READER",
"max_forks_repo_path": "sketch_agora.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "c14806116cd20ba83620ded90832498451ed9597",
"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": "mcsoini/PROFILE_READER",
"max_issues_repo_path": "sketch_agora.py",
"max_line_length": 203,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "c14806116cd20ba83620ded90832498451ed9597",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "mcsoini/PROFILE_READER",
"max_stars_repo_path": "sketch_agora.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 5811,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 22797
} |
# diagnosis-name-search-contains
# search diagnoses to find those that contain one of a number of text fragments
library(tidyverse) # for packages stringr & dplyr
# create a small example dataframe with just one column
df1 <- data_frame( diagnosis = c('hodgkins','other','Hodgkins','lymph','Lymphoma','other'))
# create a search string with an OR (|)
# in this case we miss the first letter to avoid issues with case
wanted <- 'ymph|odgkins'
# mutate creates a column containing TRUE if the entry in the diagnosis column
# contains one of the elements in the search string
# (you can replace 'newcolumn' with the name you want for the new column)
df2 <- df1 %>%
mutate(newcolumn = str_detect(diagnosis, wanted))
# to view resulting dataframe
df2
# diagnosis newcolumn
# 1 hodgkins TRUE
# 2 other FALSE
# 3 Hodgkins TRUE
# 4 lymph TRUE
# 5 Lymphoma TRUE
# 6 other FALSE
#to convert multiple conditions (e.g. read from a dataframe) into a search
#use `paste` to create search string & `collapse` that inserts between each element
#diagnoses <- c('odgkins','ymph')
#diagnoses_wanted <- paste(diagnoses, collapse = '|')
#another way of finding matches that ignore upper/lower case
wanted <- 'lymph|hodgkins'
df2 <- df1 %>%
mutate(newcolumn = str_detect(diagnosis, regex(wanted, ignore_case=T)))
# to create a new dataframe containing just the rows matching
# filter out rows
# then select just the column(s) we need
df3 <- df2 %>%
filter(newcolumn==TRUE) %>%
select(diagnosis)
| {
"alphanum_fraction": 0.7262532982,
"author": null,
"avg_line_length": 32.2553191489,
"converted": null,
"ext": "r",
"file": null,
"hexsha": "c509cf5a5430b185d0990902444eb0b7170820c6",
"include": null,
"lang": "R",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2022-01-25T11:11:28.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-09T08:01:41.000Z",
"max_forks_repo_head_hexsha": "008b2bb397e9bdc9b500abdbbe589cad2ab596dc",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "uclh-criu/learning-datascience",
"max_forks_repo_path": "examples-mini/diagnosis-name-search-contains.r",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "008b2bb397e9bdc9b500abdbbe589cad2ab596dc",
"max_issues_repo_issues_event_max_datetime": "2022-01-14T17:52:25.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-09-14T09:52:14.000Z",
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "uclh-criu/learning-datascience",
"max_issues_repo_path": "examples-mini/diagnosis-name-search-contains.r",
"max_line_length": 91,
"max_stars_count": 9,
"max_stars_repo_head_hexsha": "008b2bb397e9bdc9b500abdbbe589cad2ab596dc",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "uclh-criu/learning-datascience",
"max_stars_repo_path": "examples-mini/diagnosis-name-search-contains.r",
"max_stars_repo_stars_event_max_datetime": "2022-03-11T21:33:28.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-08T15:23:15.000Z",
"num_tokens": 408,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 1516
} |
[STATEMENT]
lemma rbt_cases:
obtains (Empty) "t = Empty"
| (Red) l k v r where "t = Branch R l k v r"
| (Black) l k v r where "t = Branch B l k v r"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<lbrakk>t = Empty \<Longrightarrow> thesis; \<And>l k v r. t = Branch R l k v r \<Longrightarrow> thesis; \<And>l k v r. t = Branch B l k v r \<Longrightarrow> thesis\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
proof (cases t)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. \<lbrakk>t = Empty \<Longrightarrow> thesis; \<And>l k v r. t = Branch R l k v r \<Longrightarrow> thesis; \<And>l k v r. t = Branch B l k v r \<Longrightarrow> thesis; t = Empty\<rbrakk> \<Longrightarrow> thesis
2. \<And>x21 x22 x23 x24 x25. \<lbrakk>t = Empty \<Longrightarrow> thesis; \<And>l k v r. t = Branch R l k v r \<Longrightarrow> thesis; \<And>l k v r. t = Branch B l k v r \<Longrightarrow> thesis; t = Branch x21 x22 x23 x24 x25\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
case Empty
[PROOF STATE]
proof (state)
this:
t = Empty
goal (2 subgoals):
1. \<lbrakk>t = Empty \<Longrightarrow> thesis; \<And>l k v r. t = Branch R l k v r \<Longrightarrow> thesis; \<And>l k v r. t = Branch B l k v r \<Longrightarrow> thesis; t = Empty\<rbrakk> \<Longrightarrow> thesis
2. \<And>x21 x22 x23 x24 x25. \<lbrakk>t = Empty \<Longrightarrow> thesis; \<And>l k v r. t = Branch R l k v r \<Longrightarrow> thesis; \<And>l k v r. t = Branch B l k v r \<Longrightarrow> thesis; t = Branch x21 x22 x23 x24 x25\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
with that
[PROOF STATE]
proof (chain)
picking this:
t = Empty \<Longrightarrow> thesis
t = Branch R ?l ?k ?v ?r \<Longrightarrow> thesis
t = Branch B ?l ?k ?v ?r \<Longrightarrow> thesis
t = Empty
[PROOF STEP]
show thesis
[PROOF STATE]
proof (prove)
using this:
t = Empty \<Longrightarrow> thesis
t = Branch R ?l ?k ?v ?r \<Longrightarrow> thesis
t = Branch B ?l ?k ?v ?r \<Longrightarrow> thesis
t = Empty
goal (1 subgoal):
1. thesis
[PROOF STEP]
by blast
[PROOF STATE]
proof (state)
this:
thesis
goal (1 subgoal):
1. \<And>x21 x22 x23 x24 x25. \<lbrakk>t = Empty \<Longrightarrow> thesis; \<And>l k v r. t = Branch R l k v r \<Longrightarrow> thesis; \<And>l k v r. t = Branch B l k v r \<Longrightarrow> thesis; t = Branch x21 x22 x23 x24 x25\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>x21 x22 x23 x24 x25. \<lbrakk>t = Empty \<Longrightarrow> thesis; \<And>l k v r. t = Branch R l k v r \<Longrightarrow> thesis; \<And>l k v r. t = Branch B l k v r \<Longrightarrow> thesis; t = Branch x21 x22 x23 x24 x25\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
case (Branch c)
[PROOF STATE]
proof (state)
this:
t = Branch c x22_ x23_ x24_ x25_
goal (1 subgoal):
1. \<And>x21 x22 x23 x24 x25. \<lbrakk>t = Empty \<Longrightarrow> thesis; \<And>l k v r. t = Branch R l k v r \<Longrightarrow> thesis; \<And>l k v r. t = Branch B l k v r \<Longrightarrow> thesis; t = Branch x21 x22 x23 x24 x25\<rbrakk> \<Longrightarrow> thesis
[PROOF STEP]
with that
[PROOF STATE]
proof (chain)
picking this:
t = Empty \<Longrightarrow> thesis
t = Branch R ?l ?k ?v ?r \<Longrightarrow> thesis
t = Branch B ?l ?k ?v ?r \<Longrightarrow> thesis
t = Branch c x22_ x23_ x24_ x25_
[PROOF STEP]
show thesis
[PROOF STATE]
proof (prove)
using this:
t = Empty \<Longrightarrow> thesis
t = Branch R ?l ?k ?v ?r \<Longrightarrow> thesis
t = Branch B ?l ?k ?v ?r \<Longrightarrow> thesis
t = Branch c x22_ x23_ x24_ x25_
goal (1 subgoal):
1. thesis
[PROOF STEP]
by (cases c) blast+
[PROOF STATE]
proof (state)
this:
thesis
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": 11,
"llama_tokens": 1497,
"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
} |
theory SimpleVariantPG imports HOML MFilter BaseDefs
begin
(*Axiom's of simplified variant with A3 replaced*)
axiomatization where
A1': "\<lfloor>\<^bold>\<not>(\<P>(\<lambda>x.(x\<^bold>\<noteq>x)))\<rfloor>" and
A2': "\<lfloor>\<^bold>\<forall>X Y.(((\<P> X) \<^bold>\<and> ((X\<^bold>\<sqsubseteq>Y)\<^bold>\<or>(X\<Rrightarrow>Y))) \<^bold>\<rightarrow> (\<P> Y))\<rfloor>" and
T2: "\<lfloor>\<P> \<G>\<rfloor>"
(*Necessary existence of a Godlike entity*)
theorem T6: "\<lfloor>\<^bold>\<box>(\<^bold>\<exists>\<^sup>E \<G>)\<rfloor>" sledgehammer (*Proof found*)
proof -
have T1: "\<lfloor>\<^bold>\<forall>X.((\<P> X) \<^bold>\<rightarrow> \<^bold>\<diamond>(\<^bold>\<exists>\<^sup>E X))\<rfloor>" by (metis A1' A2')
have T3: "\<lfloor>\<^bold>\<diamond>(\<^bold>\<exists>\<^sup>E \<G>)\<rfloor>" using T1 T2 by simp
have T5: "\<lfloor>(\<^bold>\<diamond>(\<^bold>\<exists>\<^sup>E \<G>)) \<^bold>\<rightarrow> \<^bold>\<box>(\<^bold>\<exists>\<^sup>E \<G>)\<rfloor>" by (metis A1' A2' T2)
thus ?thesis using T3 by blast qed
lemma True nitpick[satisfy] oops (*Consistency: model found*)
(*Modal collapse and Monotheism: not implied*)
lemma MC: "\<lfloor>\<^bold>\<forall>\<Phi>.(\<Phi> \<^bold>\<rightarrow> \<^bold>\<box>\<Phi>)\<rfloor>" nitpick oops (*Countermodel*)
lemma MT: "\<lfloor>\<^bold>\<forall>x y.(((\<G> x)\<^bold>\<and>(\<G> y))\<^bold>\<rightarrow>(x\<^bold>=y))\<rfloor>"
nitpick oops (*Countermodel*)
end
(*
lemma A3': "\<lfloor>\<^bold>\<forall>\<Z>. \<P>\<o>\<s> \<Z> \<^bold>\<rightarrow> (\<^bold>\<forall>X. (X\<Sqinter>\<Z>) \<^bold>\<rightarrow> \<P> X)\<rfloor>"
nitpick sledgehammer oops
(*Gödel's A1, A4, A5: not implied anymore*)
end
*)
(*
(*Further Tests*)
lemma A3': "\<lfloor>\<^bold>\<forall>X Y.((\<P> X) \<^bold>\<and> (\<P> Y)) \<^bold>\<rightarrow> \<P> (\<lambda>z. X z \<^bold>\<and> Y z)\<rfloor>" sledgehammer(A3) nitpick oops
lemma "\<lfloor>(X\<^bold>\<sqsubseteq>Y)\<^bold>\<rightarrow>(X\<Rrightarrow>Y)\<rfloor>" nitpick oops (*Countermodel*)
lemma "\<lfloor>(X\<Rrightarrow>Y)\<^bold>\<rightarrow>(X\<^bold>\<sqsubseteq>Y)\<rfloor>" sledgehammer nitpick oops (*Countermodel*)
lemma "(\<lfloor>(X\<^bold>\<sqsubseteq>Y)\<rfloor>)\<longrightarrow>(\<lfloor>(X\<Rrightarrow>Y)\<rfloor>)" nitpick oops (*Countermodel*)
lemma "(\<lfloor>(X\<Rrightarrow>Y)\<rfloor>)\<longrightarrow>(\<lfloor>(X\<^bold>\<sqsubseteq>Y)\<rfloor>)" nitpick oops (*Countermodel*)
*)
(*
lemma T2: "\<lfloor>\<P> \<G>\<rfloor>" by (metis A3 G_def)
theorem F1: "\<lfloor>Filter \<P>\<rfloor>" sledgehammer (*Proof found*)
proof -
have 1: "\<lfloor>\<^bold>U\<^bold>\<in>\<P> \<^bold>\<and> \<^bold>\<not>(\<^bold>\<emptyset>\<^bold>\<in>\<P>)\<rfloor>" using A1' by auto
have 2: "\<lfloor>\<^bold>\<forall>\<phi> \<psi>.((\<phi>\<^bold>\<in>\<P> \<^bold>\<and> (\<phi>\<^bold>\<subseteq>\<psi>)) \<^bold>\<rightarrow> \<psi>\<^bold>\<in>\<P>)\<rfloor>" by (metis A2')
have 3: "\<lfloor>\<^bold>\<forall>\<phi> \<psi>.((\<phi>\<^bold>\<in>\<P> \<^bold>\<and> \<psi>\<^bold>\<in>\<P>) \<^bold>\<rightarrow> (\<phi>\<^bold>\<sqinter>\<psi>)\<^bold>\<in>\<P>)\<rfloor>" by (metis (no_types, lifting) A2' G_def A3)
thus ?thesis using 1 2 3 by simp qed
theorem U1: "\<lfloor>Ultrafilter \<P>\<rfloor>" nitpick oops (*Countermodel*)
*)
(*
abbreviation a2::"\<gamma>\<Rightarrow>(\<gamma>\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" (infix"\<^bold>\<in>"81) where "x\<^bold>\<in>S \<equiv> S x"
abbreviation b2::\<gamma> ("\<^bold>\<emptyset>") where "\<^bold>\<emptyset> \<equiv> \<lambda>x. \<^bold>\<bottom>"
abbreviation c2::\<gamma> ("\<^bold>U") where "\<^bold>U \<equiv> \<lambda>x. \<^bold>\<top>"
abbreviation d2::"\<gamma>\<Rightarrow>\<gamma>\<Rightarrow>\<sigma>" ("_\<^bold>\<subseteq>_") where "\<phi>\<^bold>\<subseteq>\<psi> \<equiv> \<^bold>\<forall>x. \<phi> x \<^bold>\<rightarrow> \<psi> x"
abbreviation e2::"\<gamma>\<Rightarrow>\<gamma>\<Rightarrow>\<gamma>" ("_\<^bold>\<sqinter>_") where "\<phi>\<^bold>\<sqinter>\<psi> \<equiv> \<lambda>x. \<phi> x \<^bold>\<and> \<psi> x"
abbreviation f2::"\<gamma>\<Rightarrow>\<gamma>" ("\<inverse>_") where "\<inverse>\<psi> \<equiv> \<lambda>x. \<^bold>\<not>(\<psi> x)"
(*Definition of modal filter*)
abbreviation g::"(\<gamma>\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" ("Filter")
where "Filter \<Phi> \<equiv> \<^bold>U\<^bold>\<in>\<Phi> \<^bold>\<and> \<^bold>\<not>(\<^bold>\<emptyset>\<^bold>\<in>\<Phi>)
\<^bold>\<and> (\<^bold>\<forall>\<phi> \<psi>. (\<phi>\<^bold>\<in>\<Phi> \<^bold>\<and> (\<phi>\<^bold>\<subseteq>\<psi>)) \<^bold>\<rightarrow> \<psi>\<^bold>\<in>\<Phi>)
\<^bold>\<and> (\<^bold>\<forall>\<phi> \<psi>. (\<phi>\<^bold>\<in>\<Phi> \<^bold>\<and> \<psi>\<^bold>\<in>\<Phi>) \<^bold>\<rightarrow> (\<phi>\<^bold>\<sqinter>\<psi>)\<^bold>\<in>\<Phi>)"
(*Definition of modal ultrafilter *)
abbreviation h::"(\<gamma>\<Rightarrow>\<sigma>)\<Rightarrow>\<sigma>" ("Ultrafilter")
where "Ultrafilter \<Phi> \<equiv> Filter \<Phi> \<^bold>\<and> (\<^bold>\<forall>\<phi>. (\<phi>\<^bold>\<in>\<Phi>) \<^bold>\<or> ((\<inverse>\<phi>)\<^bold>\<in>\<Phi>))"
theorem U1: "\<lfloor>Ultrafilter \<P>\<rfloor>"
proof -
have 1: "\<lfloor>\<^bold>U\<^bold>\<in>\<P> \<^bold>\<and> \<^bold>\<not>(\<^bold>\<emptyset>\<^bold>\<in>\<P>)\<rfloor>" using A1' by auto
have 2: "\<lfloor>\<^bold>\<forall>\<phi> \<psi>.((\<phi>\<^bold>\<in>\<P> \<^bold>\<and> (\<phi>\<^bold>\<subseteq>\<psi>)) \<^bold>\<rightarrow> \<psi>\<^bold>\<in>\<P>)\<rfloor>" by (metis A2')
have 3: "\<lfloor>\<^bold>\<forall>\<phi> \<psi>.((\<phi>\<^bold>\<in>\<P> \<^bold>\<and> \<psi>\<^bold>\<in>\<P>) \<^bold>\<rightarrow> (\<phi>\<^bold>\<sqinter>\<psi>)\<^bold>\<in>\<P>)\<rfloor>" using A3 sledgehammer [remote_satallax remote_leo2 remote_leo3] nitpick sorry
have 4: "\<lfloor>\<^bold>\<forall>\<phi>.(\<phi>\<^bold>\<in>\<P> \<^bold>\<or> (\<inverse>\<phi>)\<^bold>\<in>\<P>)\<rfloor>" nitpick oops
thus ?thesis using 1 2 3 4 by simp qed
lemma "\<lfloor>Filter \<P> \<rfloor>" sledgehammer nitpick oops (*Counterm*)
lemma "\<lfloor>Ultrafilter \<P> \<rfloor>" sledgehammer nitpick oops (*Counterm*)
(*Filter and ultrafilter are consistent*)
consts Godlike::\<gamma> NeEx::\<gamma>
axiomatization where
1: "Godlike = \<G>" and
2: "NeEx = \<N>\<E>" and
3: "\<exists>e1::e. \<exists>e2::e. \<not> e1 = e2"
lemma True nitpick[satisfy] oops
lemma MT: "\<lfloor>\<^bold>\<forall>x y. \<G> x \<^bold>\<and> \<G> y \<^bold>\<rightarrow> x \<^bold>= y\<rfloor>" nitpick oops (*Cntm.*)
lemma MT: "\<lfloor>\<^bold>\<forall>\<^sup>Ex y. \<G> x \<^bold>\<and> \<G> y \<^bold>\<rightarrow> x \<^bold>= y\<rfloor>" sledgehammer nitpick [format=2] oops
lemma MT': "\<G> x w \<and> \<G> y w \<and> \<not>\<G> z w \<longrightarrow> x = y" sledgehammer nitpick [format=2] oops
lemma MT'': "\<lfloor>\<^bold>\<forall>\<^sup>Ex y. \<G> x \<^bold>\<and> \<G> y \<^bold>\<rightarrow> (\<^bold>\<forall>P. P x \<^bold>\<rightarrow> P y)\<rfloor>" sledgehammer nitpick [format=2] oops
lemma MC: "\<lfloor>\<^bold>\<forall>\<Phi>.(\<Phi> \<^bold>\<rightarrow> (\<^bold>\<box> \<Phi>))\<rfloor>" nitpick[timeout = 10000] nunchaku oops (*Countermodel*)
lemma A1: "\<lfloor>\<^bold>\<forall>X.(\<^bold>\<not>(\<P> X) \<^bold>\<leftrightarrow> \<P>(\<^bold>\<rightharpoondown>X))\<rfloor>" nitpick[format=4] oops (*Countermodel*)
lemma A4: "\<lfloor>\<^bold>\<forall>X.(\<P> X \<^bold>\<rightarrow> \<^bold>\<box>(\<P> X))\<rfloor>" nitpick[format=4] oops (*Countermodel*)
lemma A5: "\<lfloor>\<P> \<N>\<E>\<rfloor>" nitpick oops (*Countermodel*)
*) | {
"alphanum_fraction": null,
"author": "cbenzmueller",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/isabelle/cbenzmueller-LogiKEy/LogiKEy-5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf/Computational-Metaphysics/2020-KR/SimpleVariantPG.thy",
"reason": null,
"repo": "LogiKEy",
"save_path": "github-repos/isabelle/cbenzmueller-LogiKEy",
"sha": "5c16bdeb68bf8131e24ba9c8d774d4af663cb2cf",
"size": null
} |
//==================================================================================================
/*
Copyright 2017 NumScale SAS
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
//! [any_of]
#include <boost/simd/algorithm/any_of.hpp>
#include <boost/simd/function/is_gtz.hpp>
#include <iostream>
#include <vector>
int main()
{
namespace bs = boost::simd;
std::vector<float> d{ 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
auto rt1 = bs::any_of( d.data(), d.data()+7, bs::is_gtz );
std::cout << "rt1 " << rt1 << "\n";
auto rf1 = bs::any_of( d.data(), d.data()+7, bs::is_ltz);
std::cout << "rf1 " << rf1 << "\n";
auto rt2 = bs::any_of( d.data()+1, d.data()+8);
std::cout << "rt2 " << rt2 << "\n";
auto rf2 = bs::any_of( d.data()+2, d.data()+9, bs::is_nez);
std::cout << "rf2 " << rf2 << "\n";
return 0;
}
//! [any_of]
| {
"alphanum_fraction": 0.4760112888,
"author": null,
"avg_line_length": 33.21875,
"converted": null,
"ext": "cpp",
"file": null,
"hexsha": "d9bcd05d5fa7d46373248731c7d8c8721634fa41",
"include": null,
"lang": "C++",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2020-02-10T14:27:07.000Z",
"max_forks_repo_forks_event_min_datetime": "2017-12-12T12:36:31.000Z",
"max_forks_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de",
"max_forks_repo_licenses": [
"BSL-1.0"
],
"max_forks_repo_name": "remymuller/boost.simd",
"max_forks_repo_path": "test/doc/range/any_of.cpp",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3caefb7ee707e5f68dae94f8f31f72f34b7bb5de",
"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": "remymuller/boost.simd",
"max_issues_repo_path": "test/doc/range/any_of.cpp",
"max_line_length": 100,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "c04d0cc56747188ddb9a128ccb5715dd3608dbc1",
"max_stars_repo_licenses": [
"BSL-1.0"
],
"max_stars_repo_name": "TobiasLudwig/boost.simd",
"max_stars_repo_path": "test/doc/range/any_of.cpp",
"max_stars_repo_stars_event_max_datetime": "2021-01-15T15:13:12.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-02-25T22:23:33.000Z",
"num_tokens": 340,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 1063
} |
# -*- coding: utf-8 -*-
## Display an animated arrowhead following a curve.
## This example uses the CurveArrow class, which is a combination
## of ArrowItem and CurvePoint.
##
## To place a static arrow anywhere in a scene, use ArrowItem.
## To attach other types of item to a curve, use CurvePoint.
import initExample ## Add path to library (just for examples; you do not need this)
import numpy as np
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
app = QtGui.QApplication([])
mw = QtGui.QMainWindow()
mw.resize(300,300)
p = pg.PlotWidget()
mw.setCentralWidget(p)
c = p.plot(x=np.sin(np.linspace(0, 2*np.pi, 1000)), y=np.cos(np.linspace(0, 6*np.pi, 1000)))
a = pg.CurveArrow(c)
p.addItem(a)
mw.show()
anim = a.makeAnimation(loop=-1)
anim.start()
## Start Qt event loop unless running in interactive mode or using pyside.
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
app.exec_()
| {
"alphanum_fraction": 0.7172995781,
"author": null,
"avg_line_length": 26.3333333333,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "ae118507f84d7fd331016c484107b46758886fb4",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 7,
"max_forks_repo_forks_event_max_datetime": "2022-01-01T17:44:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2015-03-27T16:58:07.000Z",
"max_forks_repo_head_hexsha": "481a604339c9fa797817b2b0a55448329685c1d8",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "robertsj/poropy",
"max_forks_repo_path": "pyqtgraph/examples/Arrow.py",
"max_issues_count": 1,
"max_issues_repo_head_hexsha": "481a604339c9fa797817b2b0a55448329685c1d8",
"max_issues_repo_issues_event_max_datetime": "2018-06-12T16:15:31.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-12T16:15:31.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "robertsj/poropy",
"max_issues_repo_path": "pyqtgraph/examples/Arrow.py",
"max_line_length": 92,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "481a604339c9fa797817b2b0a55448329685c1d8",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "robertsj/poropy",
"max_stars_repo_path": "pyqtgraph/examples/Arrow.py",
"max_stars_repo_stars_event_max_datetime": "2018-02-11T11:24:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-02-11T11:24:14.000Z",
"num_tokens": 252,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 948
} |
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn import preprocessing
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import LinearRegression
from joblib import dump
import os
import catboost
def make_model(path, model_name, region):
info = pd.read_csv(path)
info = info.dropna(axis=0)
f = info['price'] < 100000
info = info[f] # Get information only about flats with price < 100'000
X = info[['type', 'size', 'locality']].values
y = info['price'].values
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=20)
scaler_X = preprocessing.StandardScaler().fit(X_train)
X_train = scaler_X.transform(X_train)
X_test = scaler_X.transform(X_test)
# model = catboost.CatBoostRegressor(verbose=False)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print("MSE train: ", np.sqrt(mean_squared_error(y_train, model.predict(X_train))))
print("MSE: ", np.sqrt(mean_squared_error(y_test, y_pred)))
print("-" * 100)
# scores = cross_val_score(model, X, y, cv=5, scoring='neg_mean_squared_error')
# print("MSE: %0.2f" % (np.sqrt(-scores.mean())))
dump(model, model_name + '.joblib', protocol=2) # Save model
dump(scaler_X, 'scalerx-' + region + '.joblib', protocol=2)
os.rename('./scalerx-' + region + '.joblib', './scalers/scalerx-' + region + '.joblib')
make_model('../data/flats_prague_numeric.csv', 'price-predictor-prague', 'prague')
make_model('../data/flats_brno_numeric.csv', 'price-predictor-brno', 'brno')
| {
"alphanum_fraction": 0.7027511962,
"author": null,
"avg_line_length": 34.8333333333,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "fc3cc7de5c65869a7bad48b6369bffc31400a6b5",
"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": "030be949e4a7c10a96d497f082c4a98dcfd02669",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "daniilpastukhov/flat-price-calculator",
"max_forks_repo_path": "webapp/training/training.py",
"max_issues_count": 5,
"max_issues_repo_head_hexsha": "030be949e4a7c10a96d497f082c4a98dcfd02669",
"max_issues_repo_issues_event_max_datetime": "2022-02-26T16:44:06.000Z",
"max_issues_repo_issues_event_min_datetime": "2021-03-09T15:17:27.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "daniilpastukhov/prague-flat-price-calculator",
"max_issues_repo_path": "webapp/training/training.py",
"max_line_length": 93,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "030be949e4a7c10a96d497f082c4a98dcfd02669",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "daniilpastukhov/prague-flat-price-calculator",
"max_stars_repo_path": "webapp/training/training.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 455,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1672
} |
(*
MacBook-Air:~ billw$ /Applications/CoqIDE_8.4pl5.app/Contents/Resources/bin/coqtop
Welcome to Coq 8.4pl5 (October 2014)
Coq < Section Distribution_A.
Coq < Goal forall p q r:Prop, (p /\ (q \/ r)) <-> ((p /\ q) \/ (p /\ r)).
1 subgoal
============================
forall p q r : Prop, p /\ (q \/ r) <-> p /\ q \/ p /\ r
Unnamed_thm < intros.
1 subgoal
p : Prop
q : Prop
r : Prop
============================
p /\ (q \/ r) <-> p /\ q \/ p /\ r
Unnamed_thm < tauto.
No more subgoals.
Unnamed_thm < Qed.
intros.
tauto.
Unnamed_thm is defined
Coq <
*)
Section Distribution_A.
Goal forall p q r:Prop, (p /\ (q \/ r)) <-> ((p /\ q) \/ (p /\ r)).
intros.
tauto.
Qed.
| {
"alphanum_fraction": null,
"author": "billwestfall",
"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/billwestfall-coq_ide/coq_ide-a2985a04f37f9c1c6f23799d543fdb862792d54b/concise/07chapt/page0385c.v",
"reason": null,
"repo": "coq_ide",
"save_path": "github-repos/coq/billwestfall-coq_ide",
"sha": "a2985a04f37f9c1c6f23799d543fdb862792d54b",
"size": null
} |
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
# loading data to tables
file = open("heart.dat")
all = np.loadtxt(file, delimiter=" ")
X = np.zeros((len(all), len(all[0]) - 1), dtype=np.uint8)
y = np.zeros((len(all)), dtype=np.uint8)
for i in range(len(all)):
for j in range(len(all[0]) - 1):
X[i][j] = all[i][j]
y[i] = all[i][len(all[0]) - 1]
features_quantity = len(X[0] - 1)
# feature selection
featureSelection = SelectKBest(f_classif)
featureSelection.fit(X, y)
# sorting by relevance
toSort = np.zeros(
(len(featureSelection.scores_)), dtype=([("key", "<i4"), ("val", "<f8")])
)
for i in range(len(featureSelection.scores_)):
toSort[i]["key"] = i + 1
toSort[i]["val"] = featureSelection.scores_[i]
toSort = np.sort(toSort, order="val")[::-1]
feature_order = []
for i in range(features_quantity):
print("%d. Feature no. %d, Score: %f" % (i + 1, toSort[i][0], toSort[i][1]))
feature_order.append(toSort[i][0])
| {
"alphanum_fraction": 0.6406882591,
"author": null,
"avg_line_length": 29.9393939394,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "309e42be1527f360209aed747fa49dc98db4b591",
"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": "90f55107b954dc0124b2af18a09c3ef54679bce2",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Droniu/cardio-diagnosis-knn",
"max_forks_repo_path": "select-filter.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "90f55107b954dc0124b2af18a09c3ef54679bce2",
"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": "Droniu/cardio-diagnosis-knn",
"max_issues_repo_path": "select-filter.py",
"max_line_length": 80,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "90f55107b954dc0124b2af18a09c3ef54679bce2",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Droniu/cardio-diagnosis-knn",
"max_stars_repo_path": "select-filter.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 307,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 988
} |
import argparse
import contextlib
import json
import os
import sys
import time
from collections import namedtuple
from datetime import datetime
import numpy as np
import pytz
from pyarrow import Schema
import katana.local
from katana.local import Graph, analytics
# TODO(giorgi): This script needs to be tested in CI.
PathExt = namedtuple("PathExt", ["warn_prefix", "path_ext"])
RoutinePaths = namedtuple("RoutinePaths", ["path", "edge_load"])
RoutineFunc = namedtuple("RoutineFunc", ["plan", "routine", "validation", "stats"])
RoutineArgs = namedtuple("RoutineArgs", ["plan", "routine", "validation", "stats"])
Routine = namedtuple("Routine", ["func", "args"])
@contextlib.contextmanager
def time_block(run_name, time_data):
timer_algo_start = time.perf_counter()
yield
timer_algo_end = time.perf_counter()
print(f"[TIMER] Time to run {run_name} : {round((timer_algo_end - timer_algo_start), 2)} seconds")
time_data[run_name] = round(1000 * (timer_algo_end - timer_algo_start))
def check_schema(graph: Graph, property_name):
node_schema: Schema = graph.loaded_node_schema()
num_node_properties = len(node_schema)
new_property_id = num_node_properties - 1
assert node_schema.names[new_property_id] == property_name
def create_empty_statistics(args):
now = datetime.now(pytz.timezone("US/Central"))
data = {
"graph": args.graph,
"threads": args.threads,
"thread-spin": args.thread_spin,
"source-nodes": args.source_nodes,
"trials": args.trials,
"num-sources": args.num_sources,
"routines": {},
"duration": 0,
"datetime": now.strftime("%d/%m/%Y %H:%M:%S"),
}
return data
def save_statistics_as_json(bench_stats, start_time, path):
bench_stats["duration"] = round(1000 * time.time() - start_time)
with open(path, "w") as fp:
try:
json.dump(bench_stats, fp, indent=4)
except SystemError:
print("JSON dump was unsuccessful.")
return False
return True
def run_routine(data, load_time, graph, args, input):
trial_count = 0
num_sources = None
if args.application == "bc":
num_sources = args.num_sources
for _ in range(args.trials):
time_data = default_run(args.application, graph, input, num_sources, args.source_nodes)
data["routines"][f"{args.application}_{trial_count}"] = time_data
data["routines"][f"{args.application}_{trial_count}"]["graph_load"] = load_time
trial_count += 1
print("Run Complete!")
return data
def single_run(
graph,
routine,
routine_args,
assert_validation,
assert_validation_args,
statistics,
statistics_args,
property_name,
time_data,
compare_node=None,
src=0,
):
with time_block(f"{routine.__name__}_{src}", time_data):
routine(*routine_args)
with time_block(check_schema.__name__, time_data):
check_schema(graph, property_name)
if compare_node is not None:
similarities: np.ndarray = graph.get_node_property(property_name).to_numpy()
assert similarities[compare_node] == 1
if assert_validation is not None:
assert_validation(*assert_validation_args)
if statistics:
full_stats = statistics(*statistics_args)
print(f"STATS:\n{full_stats}")
with time_block(f"{graph.remove_node_property.__name__}_{0}", time_data):
graph.remove_node_property(property_name)
def default_run(name, graph, input_args, num_sources=None, source_node_file=""):
"""
default_run is a function that runs the all of the analytics routines based on the inputs.
Steps to add another routine:
1. Determine the steps to run the routine itself.
2. Insert the functions needed for the routine in the appropriate slots.
3. If there are any steps that are required but unfulfilled add them
:name: The name of the routine
:graph: The graph to use
:input_args: The input arguments
:num_sources: The number of sources for BC
:source_node_file: The source file containing source nodes
:return: Benchmarking data dictionary
"""
if name == "tc":
return tc(graph, "")
property_name = "NewProp"
start_node = input_args["source_node"]
compare_node = input_args["source_node"]
edge_prop_name = input_args["edge_wt"]
tolerance = 0.0001
max_iteration = 1000
alpha = 0.85
k = 10
cc_bc_args = [graph, property_name]
k_args = [graph, k, property_name]
jaccard_args = [graph, compare_node, property_name]
bfs_args = [graph, start_node, property_name]
sssp_args = [graph, start_node, edge_prop_name, property_name]
louvain_args = [graph, edge_prop_name, property_name]
pagerank_args = [graph, property_name]
time_data = {}
func_arg_mapping = {
"cc": Routine(
RoutineFunc(
None,
analytics.connected_components,
analytics.connected_components_assert_valid,
analytics.ConnectedComponentsStatistics,
),
RoutineArgs(None, cc_bc_args, cc_bc_args, cc_bc_args),
),
"kcore": Routine(
RoutineFunc(None, analytics.k_core, analytics.k_core_assert_valid, analytics.KCoreStatistics),
RoutineArgs(None, k_args, k_args, k_args),
),
"bfs": Routine(
RoutineFunc(
analytics.BfsPlan.asynchronous
if "road" in input_args["name"]
else analytics.BfsPlan.synchronous_direction_opt,
analytics.bfs,
analytics.bfs_assert_valid,
analytics.BfsStatistics,
),
RoutineArgs([] if "road" in input_args["name"] else [15, 18], bfs_args, bfs_args, (graph, property_name)),
),
"sssp": Routine(
RoutineFunc(
analytics.SsspPlan.delta_step
if "kron" in input_args["name"] or "urand" in input_args["name"]
else analytics.SsspPlan.delta_step_fusion,
analytics.sssp,
analytics.sssp_assert_valid,
analytics.SsspStatistics,
),
RoutineArgs([input_args["sssp_delta"]], sssp_args, sssp_args, (graph, property_name)),
),
"jaccard": Routine(
RoutineFunc(None, analytics.jaccard, analytics.jaccard_assert_valid, analytics.JaccardStatistics),
RoutineArgs(None, jaccard_args, jaccard_args, jaccard_args),
),
"bc": Routine(
RoutineFunc(
analytics.BetweennessCentralityPlan.level,
analytics.betweenness_centrality,
None,
analytics.BetweennessCentralityStatistics,
),
RoutineArgs([], cc_bc_args, None, cc_bc_args),
),
"louvain": Routine(
RoutineFunc(
analytics.LouvainClusteringPlan.do_all,
analytics.louvain_clustering,
analytics.louvain_clustering_assert_valid,
analytics.LouvainClusteringStatistics,
),
RoutineArgs([False, 0.0001, 0.0001, 10000, 100], louvain_args, louvain_args, louvain_args),
),
"pagerank": Routine(
RoutineFunc(
analytics.PagerankPlan.pull_topological,
analytics.pagerank,
analytics.pagerank_assert_valid,
analytics.PagerankStatistics,
),
RoutineArgs((tolerance, max_iteration, alpha), pagerank_args, pagerank_args, pagerank_args),
),
}
routine = func_arg_mapping[name]
routine_args = list(routine.args.routine)
validation_args = None
if routine.args.validation:
validation_args = list(routine.args.validation)
if routine.func.plan:
with time_block(f"plan_{routine.func.plan.__name__}", time_data):
plan = routine.func.plan(*routine.args.plan)
if name == "bc":
routine_args.append(None)
routine_args.append(plan)
if source_node_file:
if not os.path.exists(source_node_file):
print(f"Source node file doesn't exist: {source_node_file}")
with open(source_node_file, "r") as fi:
sources = [int(l) for l in fi.readlines()]
if name == "bc":
assert num_sources <= len(sources)
runs = (len(sources) + num_sources - 1) // num_sources
for run in range(0, runs):
start_idx = (num_sources * run) % len(sources)
rotated_sources = sources[start_idx:] + sources[:start_idx]
sources = rotated_sources[:num_sources]
routine_args[-2] = sources
single_run(
graph,
routine.func.routine,
routine_args,
routine.func.validation,
validation_args,
routine.func.stats,
routine.args.stats,
property_name,
time_data,
src=run,
)
else:
for source in sources:
routine_args[1] = int(source)
validation_args[1] = int(source)
run_args = []
single_run(
graph,
routine.func.routine,
routine_args,
routine.func.validation,
validation_args,
routine.func.stats,
routine.args.stats,
property_name,
time_data,
src=source,
)
else:
if name == "bc":
routine_args[-2] = [start_node]
run_args = [
graph,
routine.func.routine,
routine_args,
routine.func.validation,
validation_args,
routine.func.stats,
routine.args.stats,
property_name,
time_data,
]
if name == "jaccard":
run_args.append(compare_node)
single_run(*run_args)
return time_data
def tc(graph: Graph, _input_args):
time_data = {}
with time_block(analytics.sort_all_edges_by_dest.__name__, time_data):
analytics.sort_all_edges_by_dest(graph)
with time_block(analytics.TriangleCountPlan.__name__, time_data):
tc_plan = analytics.TriangleCountPlan.ordered_count(edges_sorted=True)
with time_block(analytics.triangle_count.__name__, time_data):
n = analytics.triangle_count(graph, tc_plan)
print(f"STATS:\nNumber of Triangles: {n}")
return time_data
def run_all_gap(args):
katana.local.initialize()
print("Using threads:", katana.set_active_threads(args.threads))
if parsed_args.thread_spin:
katana.set_busy_wait()
inputs = [
{
"name": "GAP-road",
"symmetric_input": "GAP-road",
"symmetric_clean_input": "GAP-road",
"transpose_input": "GAP-road",
"source_node": 18944626,
"edge_wt": "value",
"sssp_delta": 13,
},
{
"name": "rmat15",
"symmetric_input": "rmat15_symmetric",
"symmetric_clean_input": "rmat15_cleaned_symmetric",
"transpose_input": "rmat15_transpose",
"source_node": 0,
"edge_wt": "value",
"sssp_delta": 1,
},
{
"name": "GAP-kron",
"symmetric_input": "GAP-kron",
"symmetric_clean_input": "GAP-kron",
"transpose_input": "GAP-kron",
"source_node": 71328660,
"edge_wt": "value",
"sssp_delta": 1,
},
{
"name": "GAP-twitter",
"symmetric_input": "GAP-twitter_symmetric",
"symmetric_clean_input": "GAP-twitter_symmetric_cleaned",
"transpose_input": "GAP-twitter_transpose",
"source_node": 19058681,
"edge_wt": "value",
"sssp_delta": 1,
},
{
"name": "GAP-web",
"symmetric_input": "GAP-web_symmetric",
"symmetric_clean_input": "GAP-web_symmetric_cleaned",
"transpose_input": "GAP-web_transpose",
"source_node": 19879527,
"edge_wt": "value",
"sssp_delta": 1,
},
{
"name": "GAP-urand",
"symmetric_input": "GAP-urand",
"symmetric_clean_input": "GAP-urand",
"transpose_input": "GAP-urand",
"source_node": 27691419,
"edge_wt": "value",
"sssp_delta": 1,
},
]
def load_graph(graph_path, edge_properties=None):
print(f"Running {args.application} on graph: {graph_path}")
with time_block("read Graph", {}):
graph = Graph(graph_path, edge_properties=edge_properties, node_properties=[])
print(f"#Nodes: {len(graph)}, #Edges: {graph.num_edges()}")
return graph
# Load our graph
input = next(item for item in inputs if item["name"] == args.graph)
data = create_empty_statistics(args)
# For a minor optimization group the routines by their edge_load True or False
routine_name_args_mappings = {
"tc": RoutinePaths(PathExt("Symmetric clean", input["symmetric_clean_input"]), True),
"cc": RoutinePaths(PathExt("Symmetric", input["symmetric_input"]), True),
"kcore": RoutinePaths(PathExt("Symmetric", input["symmetric_input"]), True),
"bfs": RoutinePaths(PathExt("", input["name"]), False),
"sssp": RoutinePaths(PathExt("", input["name"]), False),
"jaccard": RoutinePaths(PathExt("", input["name"]), False),
"bc": RoutinePaths(PathExt("", input["name"]), False),
"louvain": RoutinePaths(PathExt("Symmetric", input["symmetric_input"]), False),
"pagerank": RoutinePaths(PathExt("Symmetric", input["transpose_input"]), False),
}
start_time = time.time()
main_warn = "Graph doesn't exist:"
load_timer = {}
if args.application not in ["all"]:
# Select the routine to run
routine_to_run = routine_name_args_mappings[args.application]
graph_path = f"{args.input_dir}/{routine_to_run.path.path_ext}"
if not os.path.exists(graph_path):
print(f"{routine_to_run.path.warn_prefix} {main_warn} {graph_path}")
with time_block("graph_load", load_timer):
if routine_to_run.edge_load:
graph = load_graph(graph_path, [])
else:
graph = load_graph(graph_path)
data = run_routine(data, load_timer["graph_load"], graph, args, input)
else:
first_routine = next(iter(routine_name_args_mappings))
curr_edge_load = not routine_name_args_mappings[first_routine].edge_load
for k in routine_name_args_mappings:
routine_to_run = routine_name_args_mappings[k]
graph_path = f"{args.input_dir}/{routine_to_run.path.path_ext}"
if not os.path.exists(graph_path):
print(f"{routine_to_run.path.warn_prefix} {main_warn} {graph_path}")
if curr_edge_load != routine_to_run.edge_load:
with time_block("graph_load", load_timer):
if routine_to_run.edge_load:
graph = load_graph(graph_path, [])
else:
graph = load_graph(graph_path)
curr_edge_load = routine_to_run.edge_load
args.application = k
data = run_routine(data, load_timer["graph_load"], graph, args, input)
if args.json_output:
save_success = save_statistics_as_json(data, start_time, args.json_output)
if save_success:
return (True, data)
return (False, {})
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Benchmark performance of routines")
parser.add_argument("--input-dir", default="./", help="Path to the input directory (default: %(default)s)")
parser.add_argument(
"--threads",
type=int,
default=None,
help="Number of threads to use (default: query sinfo). Should match max threads.",
)
parser.add_argument("--thread-spin", default=False, action="store_true", help="Busy wait for work in thread pool.")
parser.add_argument("--json-output", help="Path at which to save performance data in JSON")
parser.add_argument(
"--graph",
default="GAP-road",
choices=["GAP-road", "GAP-kron", "GAP-twitter", "GAP-web", "GAP-urand", "rmat15"],
help="Graph name (default: %(default)s)",
)
parser.add_argument(
"--application",
default="bfs",
choices=["bfs", "sssp", "cc", "bc", "pagerank", "tc", "jaccard", "kcore", "louvain", "all"],
help="Application to run (default: %(default)s)",
)
parser.add_argument("--source-nodes", default="", help="Source nodes file(default: %(default)s)")
parser.add_argument("--trials", type=int, default=1, help="Number of trials (default: %(default)s)")
parser.add_argument("--num-sources", type=int, default=4, help="Number of sources (default: %(default)s)")
parsed_args = parser.parse_args()
if not os.path.isdir(parsed_args.input_dir):
print(f"input directory : {parsed_args.input_dir} doesn't exist")
sys.exit(1)
if not parsed_args.threads:
parsed_args.threads = int(os.cpu_count())
print(f"Using input directory: {parsed_args.input_dir} and Threads: {parsed_args.threads}")
run_all_gap(parsed_args)
| {
"alphanum_fraction": 0.6040004495,
"author": null,
"avg_line_length": 35.4541832669,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "78f68a3b4ba2dc0c8ee5070ec1ff31580373ba5b",
"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": "3278a39b504e0aeaec30d06cf629ab97dfeb3f22",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "chakpongchung/katana",
"max_forks_repo_path": "scripts/bench_python_cpp_algos.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3278a39b504e0aeaec30d06cf629ab97dfeb3f22",
"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": "chakpongchung/katana",
"max_issues_repo_path": "scripts/bench_python_cpp_algos.py",
"max_line_length": 119,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "3278a39b504e0aeaec30d06cf629ab97dfeb3f22",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "chakpongchung/katana",
"max_stars_repo_path": "scripts/bench_python_cpp_algos.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3989,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 17798
} |
using CSV, DataFrames, StatsPlots, StanSample
using Distributions, Statistics, Random
ProjDir = @__DIR__
# Simulate the data
Random.seed!(123)
N = 15
obspairs = ((30.0, 53), (35.0, 45), (40.0, 28), (45.0, 26), (50.0, 25))
ppu = []; quantity = []
for i in 1:N in
obs = rand(obspairs, 1)
append!(ppu, [rand(Normal(obs[1][1], 1.0))])
append!(quantity, [rand(Normal(obs[1][2], 1.0))])
end
df = DataFrame()
df[!, :ppu] = ppu
df[!, :quantity] = quantity
df[!, :ppu_l] = log.(ppu)
df[!, :quantity_l] = log.(quantity)
CSV.write(joinpath(ProjDir, "data", "data.csv"), df)
opt_01 = "
data {
int<lower=0> N;
vector[N] q; // Outcome
vector[N] p; // Predictor
}
parameters {
real a;
real b;
real<lower=0> sigma;
}
model {
vector[N] mu; // mu is a vector
a ~ cauchy(0.0, 5.0); // intercept positive
b ~ cauchy(0.0, 5.0); // demand drops as price increases
sigma ~ uniform(0, 15);
mu = a + b * (p - mean(p));
q ~ normal(mu, sigma);
}
";
mean_q_l = mean(df[:, :quantity_l])
mean_p_l = mean(df[:, :ppu_l])
data = Dict(
:N => size(df, 1),
:q => df[:, :quantity_l], # .- mean_q_l,
:p => df[:, :ppu_l] # .- mean_p_l
)
p1 = scatter(df[:, :ppu], df[:, :quantity],
xlabel="ppu", ylabel="quantity sold", leg=false)
p2 = scatter(data[:p], data[:q],
xlabel="log(ppu)", ylabel="log(quantity sold)", leg=false)
plot(p1, p2, layout=(2, 1))
savefig(joinpath(ProjDir, "plots", "data.png"))
sm = SampleModel("opt_01", opt_01)
rc = stan_sample(sm, data=data)
if success(rc)
chns = read_samples(sm; output_format=:mcmcchains)
show(chns)
plot(chns)
savefig(joinpath(ProjDir, "plots", "chains.png"))
dfs = read_samples(sm; output_format=:dataframe)
dfsa = DataFrame(chns)
#density(dfsa[:, Symbol("mu_pred.1")], label="mu_pred.1")
#for i in 2:3:N
# density!(dfsa[:, Symbol("mu_pred.$i")], label="mu_pred.$i")
#end
#savefig(joinpath(ProjDir, "plots", "density.png"))
p = 3.4:0.01:4.0
ps = collect(p)
p1 = scatter(data[:p], data[:q],
#xlims=(3.4, 4.0), ylims=(3.0, 4.0),
xlabel="ppu_l", ylabel="quantity_l sold", leg=false)
a_mean = mean(dfs[:, :a])
b_mean = mean(dfs[:, :b])
mu_q = a_mean .+ b_mean .* (p .- mean(p))
plot!(p1, p, mu_q)
savefig(joinpath(ProjDir, "plots", "regression.png"))
price_points_l = data[:p]
plot(xlabel="Price", ylabel="Quantity", leg=false)
selected_rows = rand(1:size(dfs, 1), 75)
for row in eachrow(dfs[selected_rows,:])
qs = exp.(row[:a] .+ row[:b] .* (ps .- mean(ps)))
plot!(exp.(p), qs, color=:gray)
end
qqs = exp.(a_mean .+ b_mean .* (price_points_l .- mean(ps)))
scatter!(exp.(price_points_l), qqs)
savefig(joinpath(ProjDir, "plots", "sampling.png"))
scatter(dfs[:, :a], dfs[:, :b],
#xlims = (-0.1, 1.0), ylims= (-10.0, 10.0),
xlabel="a", ylabel="b", leg=false)
savefig(joinpath(ProjDir, "plots", "correlations.png"))
end
| {
"alphanum_fraction": 0.6129032258,
"author": null,
"avg_line_length": 25.4144144144,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "9bc923533c11cf713d57f96a5f98955685899a1c",
"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": "a6fae1736bf30f7aeed22452630c3ca3f018c50a",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl",
"max_forks_repo_path": "approaches/optimal_pricing_02/optimal_02.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a",
"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": "StatisticalRethinkingJulia/DynamicPricingExamples.jl",
"max_issues_repo_path": "approaches/optimal_pricing_02/optimal_02.jl",
"max_line_length": 71,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "a6fae1736bf30f7aeed22452630c3ca3f018c50a",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "StatisticalRethinkingJulia/DynamicPricingExamples.jl",
"max_stars_repo_path": "approaches/optimal_pricing_02/optimal_02.jl",
"max_stars_repo_stars_event_max_datetime": "2020-09-21T07:57:57.000Z",
"max_stars_repo_stars_event_min_datetime": "2020-02-19T06:59:09.000Z",
"num_tokens": 1043,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 2821
} |
"""Abrahamson and Silva (1996, :cite:`abrahamson96`) duration model."""
from __future__ import division
import numpy as np
from . import model
__author__ = 'Albert Kottke'
class AbrahamsonSilva1996(model.Model):
"""Abrahamson and Silva (1996, :cite:`abrahamson96`) duration model.
Parameters
----------
scenario : :class:`pygmm.model.Scenario`
earthquake scenario
"""
NAME = 'Abrahamson Silva (1996)'
ABBREV = 'AS96'
PARAMS = [
model.NumericParameter('mag', True, 4, 7.5),
model.NumericParameter('dist_rup', True, 0, 250),
# FIXME add site_cond to Scenario
model.CategoricalParameter('site_cond', True, ['soil', 'rock']),
]
def __init__(self, scenario):
super(AbrahamsonSilva1996, self).__init__(scenario)
s = self._scenario
stress_drop = np.exp(5.204 + 0.851 * (s.mag - 6))
moment = 10 ** (1.5 * s.mag + 16.05)
self._ln_dur = np.log(
(stress_drop / moment) ** (-1/3) / (4.9e6 * 3.2) +
0.805 * (1 if s.site_cond == 'soil' else 0) +
0.063 * max(s.dist_rup - 10, 0)
) + self.calc_ln_dur_incr(0.75)
self._std_err = 0.55
@property
def duration(self):
return np.exp(self._ln_dur)
@property
def std_err(self):
return self._std_err
@staticmethod
def calc_ln_dur_incr(nias):
# Mask out inappropriate values
nias = np.asarray(nias)
mask = (nias < 0.10) | (0.95 < nias)
nias[mask] = np.nan
# Compute the increment due to the difference in the normalized Arias
# intensity
ln_i_ratio = np.log((nias - 0.05) / (1 - nias))
ln_dur_incr = -0.532 + 0.552 * ln_i_ratio - 0.0262 * ln_i_ratio ** 2
return ln_dur_incr
def interp(self, nias, stds=None):
# Mask out inappropriate values
nias = np.asarray(nias)
mask = (nias < 0.10) | (0.95 < nias)
nias[mask] = np.nan
ln_dur = self._ln_dur + self.calc_ln_dur_incr(nias)
if stds is not None:
std_errs = np.interp(
nias,
[0.10, 0.15, 0.20, 0.25, 0.30, 0.35, 0.40, 0.45, 0.50, 0.55,
0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95],
[0.843, 0.759, 0.713, 0.691, 0.674, 0.660, 0.646, 0.636, 0.628,
0.616, 0.605, 0.594, 0.582, 0.565, 0.545, 0.528, 0.510, 0.493]
)
ln_dur = ln_dur + np.array(stds)[:, np.newaxis] * std_errs
return np.exp(ln_dur)
| {
"alphanum_fraction": 0.5540752351,
"author": null,
"avg_line_length": 29,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "0aaf72521e40e6e06227381f450db91ff0d3453b",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-01-11T19:59:39.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-01-11T19:59:39.000Z",
"max_forks_repo_head_hexsha": "0ad5c870a102ec483a725d1f7f87507cd419c378",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "glavrentiadis/pygmm",
"max_forks_repo_path": "pygmm/abrahamson_silva_1996.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "0ad5c870a102ec483a725d1f7f87507cd419c378",
"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": "glavrentiadis/pygmm",
"max_issues_repo_path": "pygmm/abrahamson_silva_1996.py",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "0ad5c870a102ec483a725d1f7f87507cd419c378",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "glavrentiadis/pygmm",
"max_stars_repo_path": "pygmm/abrahamson_silva_1996.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 859,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2552
} |
\section{Conclusions}
\glspl{MSR} feature significant multiphysics interactions which present
computational challenges for many existing multiphysics reactor analysis
software. This paper presents code-to-code verification of Moltres
capabilities in modeling such multiphysics phenomena in fast-spectrum
\glspl{MSR} based on the CNRS benchmark \cite{tiberga_results_2020}.
The CNRS benchmark assesses multiphysics \gls{MSR} simulation
software through several steps involving single-physics and coupled
neutronics/thermal-hydraulics problems.
The results showed that Moltres is consistent with the participating software
presented in the CNRS benchmark paper for the modeling of important phenomena
in fast-spectrum \glspl{MSR}. The percentage discrepancies in the various
neutronics, velocity, and temperature quantities mostly fall below or within
one standard deviation of the average of the benchmark participants.
Minor deviations in the temperature in Steps 0.3 and 1.2
stem from the discontinuous velocity
boundaries on the top corners in the lid-driven cavity flow. We showed that
these deviations are limited to the top boundary of the domain and do not
affect the rest of the physical parameters. The results from
Moltres agree closest with the TUD-S$_2$ software package, which implements the
$S_2$ discrete ordinates method for
neutron transport on a uniform structured mesh with a \gls{DGFEM}-based solver.
These features make Moltres the most similar to the TUD-$S_2$ model compared
to the other models that employ different neutron transport models,
non-uniform meshes, and/or finite volume-based solvers.
This work verifies Moltres' capabilities for future work involving modeling and
simulation of fast-spectrum \glspl{MSR}. Fast-spectrum \glspl{MSR}
under consideration for modeling with Moltres include the European \gls{MSFR}
as a continuation of work done in \cite{park_advancement_2020}, and
TerraPower's \gls{MCFR} \cite{terrapower_terrapower_2021} from publicly
available design specifications. Moltres can play an important role in
supporting further \gls{MSR} development through enabling transient accident
safety analysis and design optimization studies on an open-source platform.
An ongoing research project involves employing Moltres as a
surrogate model for machine learning-based reactor design optimization.
We note that Moltres also supports modeling solid-fueled reactors such as the
\gls{HTGR} by disabling the precursor drift functionality as demonstrated by
\cite{fairhurst-agosta_multi-physics_2020}. Future work pertaining to
further Moltres development include introducing an intermediate-fidelity
turbulence model for highly turbulent flows in \glspl{MSR}, improving
neutronics accuracy in heterogeneous geometries, and enhancing the general
computational performance of existing features.
\FloatBarrier
| {
"alphanum_fraction": 0.8348527349,
"author": null,
"avg_line_length": 59.4166666667,
"converted": null,
"ext": "tex",
"file": null,
"hexsha": "e40d629749bf03b6de814fa011367cec147c845f",
"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": "497be0523d501d7dfc827bc9b07f0dd3910afce4",
"max_forks_repo_licenses": [
"CC-BY-4.0"
],
"max_forks_repo_name": "khurrumsaleem/2021-park-moltres-benchmark",
"max_forks_repo_path": "conclusion.tex",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "497be0523d501d7dfc827bc9b07f0dd3910afce4",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"CC-BY-4.0"
],
"max_issues_repo_name": "khurrumsaleem/2021-park-moltres-benchmark",
"max_issues_repo_path": "conclusion.tex",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "497be0523d501d7dfc827bc9b07f0dd3910afce4",
"max_stars_repo_licenses": [
"CC-BY-4.0"
],
"max_stars_repo_name": "khurrumsaleem/2021-park-moltres-benchmark",
"max_stars_repo_path": "conclusion.tex",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 649,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 2852
} |
#! /usr/bin/julia
# Rosetta Code, Twelve statements
function showflaggedbits{T<:BitArray{1}}(a::T, f::T)
tf = map(x->x ? "T" : "F", a)
flg = map(x->x ? "*" : " ", f)
join(tf .* flg, " ")
end
const props = [s -> length(s) == 12,
s -> sum(s[7:12]) == 3,
s -> sum(s[2:2:end]) == 2,
s -> !s[5] || (s[6] & s[7]),
s -> !any(s[2:4]),
s -> sum(s[1:2:end]) == 4,
s -> s[2] $ s[3],
s -> !s[7] || (s[5] & s[6]),
s -> sum(s[1:6]) == 3,
s -> s[11] & s[12],
s -> sum(s[7:9]) == 1,
s -> sum(s[1:end-1]) == 4]
const NDIG = length(props)
NDIG < WORD_SIZE || println("WARNING, too many propositions!")
mhist = zeros(Int, NDIG+1)
println("Checking the ", NDIG, " statements against all possibilities.\n")
print(" "^15)
for i in 1:NDIG
print(@sprintf "%3d" i)
end
println()
for i in 0:(2^NDIG-1)
s = bitpack(digits(i, 2, NDIG))
t = bitpack([p(s) for p in props])
misses = s$t
mcnt = sum(misses)
mhist[NDIG-mcnt+1] += 1
mcnt < 2 || mcnt == NDIG || continue
if mcnt == 0
print(" Exact Match: ")
elseif mcnt == NDIG
print(" Total Miss: ")
else
print(" Near Miss: ")
end
println(showflaggedbits(t, misses))
end
println()
println("Distribution of matches")
println(" Matches Cases")
for i in (NDIG+1):-1:1
println(@sprintf " %2d => %4d" i-1 mhist[i])
end
| {
"alphanum_fraction": 0.4704711347,
"author": null,
"avg_line_length": 25.5423728814,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "9c722b3a2bbeeb5e69dd0af8c05f826fde4b6efc",
"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": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MichaeLeroy/rosetta-code",
"max_forks_repo_path": "julia/completed/twelve_statements.jl",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5",
"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": "MichaeLeroy/rosetta-code",
"max_issues_repo_path": "julia/completed/twelve_statements.jl",
"max_line_length": 74,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "cb0f45f79704912967cbd37c0c9bdc1e78c964b5",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MichaeLeroy/rosetta-code",
"max_stars_repo_path": "julia/completed/twelve_statements.jl",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 522,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 1507
} |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F #233
import torch.optim as optim
from torchvision import datasets,models,transforms
from PIL import Image
import sys
sys.path.append("..")
from attack import pgd
from netmodels.CNNmodel import Net
model = Net()
print("Load orignial model...")
model.load_state_dict(torch.load("../save_models/mnist_cnn.pt"))
model.eval()
defensemodel = Net()
print("Load pgdtraining model...")
defensemodel.load_state_dict(torch.load("../save_models/mnist_pgdtraining.pt"))
defensemodel.eval()
xx = datasets.MNIST('../data').data[3333]
xx = xx.unsqueeze_(0).float()/255
xx = xx.unsqueeze_(0).float()
## Set Targetå
yy = datasets.MNIST('../data', download=True).targets[3333]
yy = yy.unsqueeze_(0).float()
predict0 = model(xx)
predict0= predict0.argmax(dim=1, keepdim=True)
adversary = pgd.PGD(model)
AdvExArray = adversary.generate(xx,yy, epsilon = 0.3)
predict1 = model(AdvExArray)
predict1= predict1.argmax(dim=1, keepdim=True)
AdvExArray = AdvExArray.cpu()
predict2 = defensemodel(AdvExArray)
predict2= predict2.argmax(dim=1, keepdim=True)
print(predict0)
print(predict1)
print(predict2)
AdvExArray = AdvExArray.cpu().detach().numpy()
import matplotlib.pyplot as plt
plt.imshow(AdvExArray[0,0]*255, cmap='gray', vmin = 0, vmax = 255)
plt.savefig('advexample_pgd.png') | {
"alphanum_fraction": 0.7520355292,
"author": null,
"avg_line_length": 25.4905660377,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "b8524ff8445d93e331bf98cad209636e0c2727e9",
"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": "3f56dcc45f1fed788423d32cc179c26513416e2e",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "lorenzobasile/DeepRobust",
"max_forks_repo_path": "deeprobust/image/defense/test_PGD_defense.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "3f56dcc45f1fed788423d32cc179c26513416e2e",
"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": "lorenzobasile/DeepRobust",
"max_issues_repo_path": "deeprobust/image/defense/test_PGD_defense.py",
"max_line_length": 79,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "ea8871d970257a9c11715cd059a5331177a00395",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "HenryKenlay/DeepRobust",
"max_stars_repo_path": "deeprobust/image/defense/test_PGD_defense.py",
"max_stars_repo_stars_event_max_datetime": "2022-02-22T09:12:59.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-22T09:12:59.000Z",
"num_tokens": 365,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1351
} |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Simulate observations"""
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord, SkyOffsetFrame
from astropy.table import Table
import gammapy
from gammapy.data import EventList
from gammapy.maps import MapCoord
from gammapy.modeling.models import ConstantTemporalModel
from gammapy.utils.random import get_random_state
__all__ = ["MapDatasetEventSampler"]
class MapDatasetEventSampler:
"""Sample events from a map dataset
Parameters
----------
random_state : {int, 'random-seed', 'global-rng', `~numpy.random.RandomState`}
Defines random number generator initialisation.
Passed to `~gammapy.utils.random.get_random_state`.
"""
def __init__(self, random_state="random-seed"):
self.random_state = get_random_state(random_state)
def _sample_coord_time(self, npred, temporal_model, gti):
n_events = self.random_state.poisson(np.sum(npred.data))
coords = npred.sample_coord(n_events=n_events, random_state=self.random_state)
table = Table()
try:
energy = coords["energy_true"]
except KeyError:
energy = coords["energy"]
table["ENERGY_TRUE"] = energy
table["RA_TRUE"] = coords.skycoord.icrs.ra.to("deg")
table["DEC_TRUE"] = coords.skycoord.icrs.dec.to("deg")
time_start, time_stop, time_ref = (gti.time_start, gti.time_stop, gti.time_ref)
time = temporal_model.sample_time(
n_events=n_events,
t_min=time_start,
t_max=time_stop,
random_state=self.random_state,
)
table["TIME"] = u.Quantity(((time.mjd - time_ref.mjd) * u.day).to(u.s)).to("s")
return table
def sample_sources(self, dataset):
"""Sample source model components.
Parameters
----------
dataset : `~gammapy.datasets.MapDataset`
Map dataset.
Returns
-------
events : `~gammapy.data.EventList`
Event list
"""
events_all = []
for idx, evaluator in enumerate(dataset.evaluators.values()):
if evaluator.needs_update:
evaluator.update(
dataset.exposure,
dataset.psf,
dataset.edisp,
dataset._geom,
dataset.mask,
)
flux = evaluator.compute_flux()
npred = evaluator.apply_exposure(flux)
if evaluator.model.temporal_model is None:
temporal_model = ConstantTemporalModel()
else:
temporal_model = evaluator.model.temporal_model
table = self._sample_coord_time(npred, temporal_model, dataset.gti)
if len(table) > 0:
table["MC_ID"] = idx + 1
else:
mcid = table.Column(name="MC_ID", length=0, dtype=int)
table.add_column(mcid)
events_all.append(EventList(table))
return EventList.from_stack(events_all)
def sample_background(self, dataset):
"""Sample background
Parameters
----------
dataset : `~gammapy.datasets.MapDataset`
Map dataset
Returns
-------
events : `gammapy.data.EventList`
Background events
"""
background = dataset.npred_background()
temporal_model = ConstantTemporalModel()
table = self._sample_coord_time(background, temporal_model, dataset.gti)
table["MC_ID"] = 0
table["ENERGY"] = table["ENERGY_TRUE"]
table["RA"] = table["RA_TRUE"]
table["DEC"] = table["DEC_TRUE"]
return EventList(table)
def sample_edisp(self, edisp_map, events):
"""Sample energy dispersion map.
Parameters
----------
edisp_map : `~gammapy.irf.EDispMap`
Energy dispersion map
events : `~gammapy.data.EventList`
Event list with the true energies
Returns
-------
events : `~gammapy.data.EventList`
Event list with reconstructed energy column.
"""
coord = MapCoord(
{
"lon": events.table["RA_TRUE"].quantity,
"lat": events.table["DEC_TRUE"].quantity,
"energy_true": events.table["ENERGY_TRUE"].quantity,
},
frame="icrs",
)
coords_reco = edisp_map.sample_coord(coord, self.random_state)
events.table["ENERGY"] = coords_reco["energy"]
return events
def sample_psf(self, psf_map, events):
"""Sample psf map.
Parameters
----------
psf_map : `~gammapy.irf.PSFMap`
PSF map.
events : `~gammapy.data.EventList`
Event list.
Returns
-------
events : `~gammapy.data.EventList`
Event list with reconstructed position columns.
"""
coord = MapCoord(
{
"lon": events.table["RA_TRUE"].quantity,
"lat": events.table["DEC_TRUE"].quantity,
"energy_true": events.table["ENERGY_TRUE"].quantity,
},
frame="icrs",
)
coords_reco = psf_map.sample_coord(coord, self.random_state)
events.table["RA"] = coords_reco["lon"] * u.deg
events.table["DEC"] = coords_reco["lat"] * u.deg
return events
@staticmethod
def event_det_coords(observation, events):
"""Add columns of detector coordinates (DETX-DETY) to the event list.
Parameters
----------
observation : `~gammapy.data.Observation`
In memory observation.
events : `~gammapy.data.EventList`
Event list.
Returns
-------
events : `~gammapy.data.EventList`
Event list with columns of event detector coordinates.
"""
sky_coord = SkyCoord(events.table["RA"], events.table["DEC"], frame="icrs")
frame = SkyOffsetFrame(origin=observation.pointing_radec.icrs)
pseudo_fov_coord = sky_coord.transform_to(frame)
events.table["DETX"] = pseudo_fov_coord.lon
events.table["DETY"] = pseudo_fov_coord.lat
return events
@staticmethod
def event_list_meta(dataset, observation):
"""Event list meta info.
Parameters
----------
dataset : `~gammapy.datasets.MapDataset`
Map dataset.
observation : `~gammapy.data.Observation`
In memory observation.
Returns
-------
meta : dict
Meta dictionary.
"""
# See: https://gamma-astro-data-formats.readthedocs.io/en/latest/events/events.html#mandatory-header-keywords
meta = {}
meta["HDUCLAS1"] = "EVENTS"
meta["EXTNAME"] = "EVENTS"
meta[
"HDUDOC"
] = "https://github.com/open-gamma-ray-astro/gamma-astro-data-formats"
meta["HDUVERS"] = "0.2"
meta["HDUCLASS"] = "GADF"
meta["OBS_ID"] = observation.obs_id
meta["TSTART"] = (
((observation.tstart.mjd - dataset.gti.time_ref.mjd) * u.day).to(u.s).value
)
meta["TSTOP"] = (
((observation.tstop.mjd - dataset.gti.time_ref.mjd) * u.day).to(u.s).value
)
meta["ONTIME"] = observation.observation_time_duration.to("s").value
meta["LIVETIME"] = observation.observation_live_time_duration.to("s").value
meta["DEADC"] = 1 - observation.observation_dead_time_fraction
meta["RA_PNT"] = observation.pointing_radec.icrs.ra.deg
meta["DEC_PNT"] = observation.pointing_radec.icrs.dec.deg
meta["EQUINOX"] = "J2000"
meta["RADECSYS"] = "icrs"
meta["CREATOR"] = "Gammapy {}".format(gammapy.__version__)
meta["EUNIT"] = "TeV"
meta["EVTVER"] = ""
meta["OBSERVER"] = "Gammapy user"
meta["DSTYP1"] = "TIME"
meta["DSUNI1"] = "s"
meta["DSVAL1"] = "TABLE"
meta["DSREF1"] = ":GTI"
meta["DSTYP2"] = "ENERGY"
meta["DSUNI2"] = "TeV"
meta[
"DSVAL2"
] = f'{dataset._geom.axes["energy"].edges.min().value}:{dataset._geom.axes["energy"].edges.max().value}'
meta["DSTYP3"] = "POS(RA,DEC) "
offset_max = np.max(dataset._geom.width).to_value("deg")
meta[
"DSVAL3"
] = f"CIRCLE({observation.pointing_radec.ra.deg},{observation.pointing_radec.dec.deg},{offset_max})"
meta["DSUNI3"] = "deg "
meta["NDSKEYS"] = " 3 "
# get first non background model component
for model in dataset.models:
if model is not dataset.background_model:
break
else:
model = None
if model:
meta["OBJECT"] = model.name
meta["RA_OBJ"] = model.position.icrs.ra.deg
meta["DEC_OBJ"] = model.position.icrs.dec.deg
meta["TELAPSE"] = dataset.gti.time_sum.to("s").value
meta["MJDREFI"] = int(dataset.gti.time_ref.mjd)
meta["MJDREFF"] = dataset.gti.time_ref.mjd % 1
meta["TIMEUNIT"] = "s"
meta["TIMESYS"] = dataset.gti.time_ref.scale
meta["TIMEREF"] = "LOCAL"
meta["DATE-OBS"] = dataset.gti.time_start.isot[0][0:10]
meta["DATE-END"] = dataset.gti.time_stop.isot[0][0:10]
meta["TIME-OBS"] = dataset.gti.time_start.isot[0][11:23]
meta["TIME-END"] = dataset.gti.time_stop.isot[0][11:23]
meta["TIMEDEL"] = 1e-9
meta["CONV_DEP"] = 0
meta["CONV_RA"] = 0
meta["CONV_DEC"] = 0
for idx, model in enumerate(dataset.models):
meta["MID{:05d}".format(idx + 1)] = idx + 1
meta["MMN{:05d}".format(idx + 1)] = model.name
meta["NMCIDS"] = len(dataset.models)
# Necessary for DataStore, but they should be ALT and AZ instead!
meta["ALTITUDE"] = observation.aeff.meta["CBD50001"][7:-4]
meta["ALT_PNT"] = observation.aeff.meta["CBD50001"][7:-4]
meta["AZ_PNT"] = observation.aeff.meta["CBD60001"][8:-4]
# TO DO: these keywords should be taken from the IRF of the dataset
meta["ORIGIN"] = "Gammapy"
meta["CALDB"] = observation.aeff.meta["CBD20001"][8:-1]
meta["IRF"] = observation.aeff.meta["CBD10001"][5:-2]
meta["TELESCOP"] = observation.aeff.meta["TELESCOP"]
meta["INSTRUME"] = observation.aeff.meta["INSTRUME"]
meta["N_TELS"] = ""
meta["TELLIST"] = ""
meta["GEOLON"] = ""
meta["GEOLAT"] = ""
# TO BE ADDED
# meta["CREATED"] = ""
# meta["OBS_MODE"] = ""
# meta["EV_CLASS"] = ""
return meta
def run(self, dataset, observation=None):
"""Run the event sampler, applying IRF corrections.
Parameters
----------
dataset : `~gammapy.datasets.MapDataset`
Map dataset
observation : `~gammapy.data.Observation`
In memory observation.
edisp : Bool
It allows to include or exclude the Edisp in the simulation.
Returns
-------
events : `~gammapy.data.EventList`
Event list.
"""
if len(dataset.models) > 1:
events_src = self.sample_sources(dataset)
if len(events_src.table) > 0:
if dataset.psf:
events_src = self.sample_psf(dataset.psf, events_src)
else:
events_src.table["RA"] = events_src.table["RA_TRUE"]
events_src.table["DEC"] = events_src.table["DEC_TRUE"]
if dataset.edisp:
events_src = self.sample_edisp(dataset.edisp, events_src)
else:
events_src.table["ENERGY"] = events_src.table["ENERGY_TRUE"]
if dataset.background:
events_bkg = self.sample_background(dataset)
events = EventList.from_stack([events_bkg, events_src])
else:
events = events_src
if len(dataset.models) == 1 and dataset.background_model is not None:
events_bkg = self.sample_background(dataset)
events = EventList.from_stack([events_bkg])
events = self.event_det_coords(observation, events)
events.table["EVENT_ID"] = np.arange(len(events.table))
events.table.meta = self.event_list_meta(dataset, observation)
geom = dataset._geom
selection = geom.contains(events.map_coord(geom))
return events.select_row_subset(selection)
| {
"alphanum_fraction": 0.5671559777,
"author": null,
"avg_line_length": 33.9706666667,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "621116eca743cf62e6581e32fc5380ece9da77f9",
"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": "6a5255cd7221f50079d36250888ca8cc763ebaf7",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "Devot1on/gammapy",
"max_forks_repo_path": "gammapy/datasets/simulate.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6a5255cd7221f50079d36250888ca8cc763ebaf7",
"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": "Devot1on/gammapy",
"max_issues_repo_path": "gammapy/datasets/simulate.py",
"max_line_length": 117,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6a5255cd7221f50079d36250888ca8cc763ebaf7",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "Devot1on/gammapy",
"max_stars_repo_path": "gammapy/datasets/simulate.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 3016,
"path": null,
"reason": "import numpy,import astropy,from astropy",
"repo": null,
"save_path": null,
"sha": null,
"size": 12739
} |
import cv2
import numpy as np
# Find best match
def find_best_match(patch, strip):
# TODO: Find patch in strip and return column index (x value) of topleft corner
# We will use SSD to find out the best match
best_id = 0
min_diff = np.infty
for i in range(int(strip.shape[1] - patch.shape[1])):
temp = strip[:, i: i + patch.shape[1]]
ssd = np.sum((temp - patch) ** 2)
if ssd < min_diff:
min_diff = ssd
best_id = i
return best_id
# Test code:
# Load images
left = cv2.imread('../images/flowers-left.png')
right = cv2.imread('../images/flowers-right.png')
cv2.imshow('Left', left)
cv2.imshow('Right', right)
# Convert to grayscale, double, [0, 1] range for easier computation
left_gray = cv2.cvtColor(left, cv2.COLOR_BGR2GRAY) / 255.
right_gray = cv2.cvtColor(right, cv2.COLOR_BGR2GRAY) / 255.
# Define image patch location (topleft [row col]) and size
patch_loc = [94, 119] # Adapted index values to approximate the difference with the original images shapes
patch_size = [100, 100]
# Extract patch (from left image)
patch_left = left_gray[patch_loc[0]:patch_loc[0] + patch_size[0],
patch_loc[1]:patch_loc[1] + patch_size[1]]
cv2.imshow('Patch', patch_left)
# Extract strip (from right image)
strip_right = right_gray[patch_loc[0]: patch_loc[0] + patch_size[0], :]
cv2.imshow('Strip', strip_right)
# Now look for the patch in the strip and report the best position (column index of topleft corner)
best_x = find_best_match(patch_left, strip_right)
print best_x
patch_right = right_gray[patch_loc[0]: patch_loc[0] + patch_size[0],
best_x: best_x + patch_size[1]]
# Because we had to adjust the index numbers for this quiz, we will
# plot a rectangle where the best match is in the right image. This
# will help us verify if what we did was correct.
cv2.rectangle(right, (best_x, patch_loc[0]),
(best_x + patch_size[0], patch_loc[0] + patch_size[0]),
(0, 0, 255),
2)
cv2.imshow("Match", right)
cv2.waitKey(0)
| {
"alphanum_fraction": 0.6711473836,
"author": null,
"avg_line_length": 32.546875,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "6af5ed0ea9f499ed5e1ec08741e5489c7c6b26d1",
"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-05T19:08:53.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-11-02T08:36:01.000Z",
"max_forks_repo_head_hexsha": "6a36cf96dec40fe4cd5584fbc2d8e384a74a66cf",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "jperuggia/ComputerVision",
"max_forks_repo_path": "CV-lecture-quizzes-python-master/3B-L3/answers/find_best_match.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6a36cf96dec40fe4cd5584fbc2d8e384a74a66cf",
"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": "jperuggia/ComputerVision",
"max_issues_repo_path": "CV-lecture-quizzes-python-master/3B-L3/answers/find_best_match.py",
"max_line_length": 107,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "6a36cf96dec40fe4cd5584fbc2d8e384a74a66cf",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "jperuggia/ComputerVision",
"max_stars_repo_path": "CV-lecture-quizzes-python-master/3B-L3/answers/find_best_match.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 573,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2083
} |
# --- import --------------------------------------------------------------------------------------
import os
import numpy as np
import WrightTools as wt
from . import _pulse
from ._scan import Scan
# --- define --------------------------------------------------------------------------------------
here = os.path.abspath(os.path.dirname(__file__))
# integration defaults
timestep = 4.0
early_buffer = 100.0
late_buffer = 400.0
# --- class ---------------------------------------------------------------------------------------
class Experiment:
"""Experiment."""
def __init__(self, axes, name, pm, pulse_class):
# basic attributes
self.axes = axes
for a in self.axes:
setattr(self, a.name, a)
self.name = name
self.pm = pm
self.npulses = len(pm)
self.timestep = timestep
self.early_buffer = early_buffer
self.late_buffer = late_buffer
# pulse
self.pulse_class = pulse_class
self.pulses = [self.pulse_class() for _ in self.pm]
def __repr__(self):
return '<WrightSim.Experiment object \'{0}\' at {1}>'.format(self.name, str(id(self)))
@property
def active_axes(self):
return [a for a in self.axes if a.active]
@property
def axis_names(self):
return [a.name for a in self.axes]
def run(self, hamiltonian, mp=True):
"""Run the experiment.
Parameters
----------
hamiltonian : WrightSim Hamiltonian
Hamiltonian.
mp : boolean (optional)
Toggle CPU multiprocessing. Default is True.
Returns
-------
WrightSim Scan
Scan that was run."""
out = Scan(self, hamiltonian)
out.run(mp=mp)
# finish
return out
def set_axis(self, axis_name, points):
'''
Activate and define points for one of the experimental axes.
Parameters
----------
axis_name : string
Name of axis.
points : 1D array-like
Points (in native units) to scan over.
'''
# TODO: is there a way to prevent incompatible axes being simultaniously activated?
axis_index = self.axis_names.index(axis_name)
axis = self.axes[axis_index]
axis.points = points
axis.active = True
| {
"alphanum_fraction": 0.516088061,
"author": null,
"avg_line_length": 25.3978494624,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "b83b971270be8b99fd3d68f972b51da0d946b043",
"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-18T01:40:37.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-09-18T01:40:37.000Z",
"max_forks_repo_head_hexsha": "acd9566ccb3e98715e63d3dc03a5ae502fe4a3d1",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "wright-group/WrightSim",
"max_forks_repo_path": "WrightSim/experiment/_experiment.py",
"max_issues_count": 35,
"max_issues_repo_head_hexsha": "acd9566ccb3e98715e63d3dc03a5ae502fe4a3d1",
"max_issues_repo_issues_event_max_datetime": "2021-09-07T18:36:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-11-10T22:22:28.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "wright-group/WrightSim",
"max_issues_repo_path": "WrightSim/experiment/_experiment.py",
"max_line_length": 99,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "acd9566ccb3e98715e63d3dc03a5ae502fe4a3d1",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "wright-group/WrightSim",
"max_stars_repo_path": "WrightSim/experiment/_experiment.py",
"max_stars_repo_stars_event_max_datetime": "2020-09-02T13:58:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-07-16T16:40:40.000Z",
"num_tokens": 494,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2362
} |
# Copyright (C) 2016 Nippon Telegraph and Telephone 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.
# error 163, need change
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_3
from ryu.lib.packet import packet
from ryu.lib.packet import arp
from ryu.lib.packet import ethernet
from ryu.ofproto import ether
from ryu.lib.packet import ipv4
from ryu.lib.packet import ipv6
from ryu import utils
from ryu.topology.api import get_switch, get_link
from ryu.app.wsgi import ControllerBase
from ryu.topology import event, switches
import networkx as nx
class ExampleSwitch13(app_manager.RyuApp):
OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]
def __init__(self, *args, **kwargs):
super(ExampleSwitch13, self).__init__(*args, **kwargs)
# initialize mac address table.
self.mac_to_port = {}
self.datapaths = {}
self.FLAGS = True
self.topology_api_app = self
self.net = nx.DiGraph()
self.nodes = {}
self.links = {}
@set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)
def switch_features_handler(self, ev):
datapath = ev.msg.datapath
ofproto = datapath.ofproto
dpid = datapath.id
parser = datapath.ofproto_parser
# install the table-miss flow entry.
match = parser.OFPMatch()
actions = [parser.OFPActionOutput(ofproto.OFPP_CONTROLLER,
ofproto.OFPCML_NO_BUFFER)]
self.add_flow(datapath, 0,0, match, actions)
self.logger.info("switch:%s connected", dpid)
def add_flow(self, datapath, hard_timeout, priority, match, actions):
ofproto = datapath.ofproto
parser = datapath.ofproto_parser
inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS,
actions)]
mod = parser.OFPFlowMod(datapath=datapath, priority=priority,
hard_timeout=hard_timeout,
match=match, instructions=inst)
datapath.send_msg(mod)
# may can merge with send_out
def _build_packet_out(self, datapath, buffer_id, src_port, dst_port, data):
actions = []
parser = datapath.ofproto_parser
if dst_port:
actions.append(parser.OFPActionOutput(dst_port))
msg_data = None
if buffer_id == datapath.ofproto.OFP_NO_BUFFER:
if data is None:
return None
msg_data = data
out = parser.OFPPacketOut(datapath=datapath, buffer_id=buffer_id,
data=msg_data, in_port=src_port,
actions=actions)
return out
def send_packet_out(self, datapath, buffer_id, src_port, dst_port, data):
out = self._build_packet_out(datapath, buffer_id,
src_port, dst_port, data)
if out:
datapath.send_msg(out)
def flood(self, msg):
datapath = msg.datapath
ofproto = datapath.ofproto
out = self._build_packet_out(datapath, ofproto.OFP_NO_BUFFER,
ofproto.OFPP_CONTROLLER,
ofproto.OFPP_FLOOD, msg.data)
datapath.send_msg(out)
self.logger.debug("Flooding msg")
def arp_forwarding(self, msg, src_ip, dst_ip, eth_pkt):
datapath = msg.datapath
parser = datapath.ofproto_parser
in_port = msg.match['in_port']
out_port = self.mac_to_port[datapath.id].get(eth_pkt.dst)
if out_port is not None:
match = parser.OFPMatch(in_port=in_port, eth_dst=eth_pkt.dst,
eth_type=eth_pkt.ethertype)
actions = [parser.OFPActionOutput(out_port)]
self.add_flow(datapath, 0, 1, match, actions)
self.send_packet_out(datapath, msg.buffer_id, in_port,
out_port, msg.data)
self.logger.debug("Reply ARP to knew host")
else:
self.flood(msg)
def mac_learning(self, dpid, src_mac, in_port):
self.mac_to_port.setdefault(dpid, {})
if src_mac in self.mac_to_port[dpid]:
if in_port != self.mac_to_port[dpid][src_mac]:
return False
else:
self.mac_to_port[dpid][src_mac] = in_port
return True
@set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)
def _packet_in_handler(self, ev):
msg = ev.msg
datapath = msg.datapath
dpid = datapath.id
parser = datapath.ofproto_parser
in_port = msg.match['in_port']
pkt = packet.Packet(msg.data)
eth = pkt.get_protocols(ethernet.ethernet)[0]
arp_pkt = pkt.get_protocol(arp.arp)
ip_pkt = pkt.get_protocol(ipv4.ipv4)
if isinstance(arp_pkt, arp.arp):
self.logger.debug("ARP processing")
if self.mac_learning(dpid, eth.src, in_port) is False:
self.logger.debug("ARP packet enter in different ports")
return
self.arp_forwarding(msg, arp_pkt.src_ip, arp_pkt.dst_ip, eth)
if isinstance(ip_pkt, ipv4.ipv4):
self.logger.debug("IPV4 processing")
# mac_to_port_table = self.mac_to_port.get(dpid)
if self.mac_to_port[dpid] is None:
self.logger.info("Dpid is not in mac_to_port")
return
if eth.dst in self.mac_to_port[dpid]:
if dpid == 1 and in_port == 1:
out_port = 3
elif dpid == 1 and in_port == 2:
out_port = 4
elif dpid == 4 and in_port == 3:
out_port = 1
elif dpid == 4 and in_port == 4:
out_port = 2
else:
# Normal flows
out_port = self.mac_to_port[dpid][eth.dst]
actions = [parser.OFPActionOutput(out_port)]
match = parser.OFPMatch(in_port=in_port, eth_dst=eth.dst,
eth_type=eth.ethertype)
self.add_flow(datapath, 0, 2, match, actions)
self.send_packet_out(datapath, msg.buffer_id, in_port,
out_port, msg.data)
else:
if self.mac_learning(dpid, eth.src, in_port) is False:
self.logger.debug("IPV4 packet enter in different ports")
return
else:
self.flood(msg)
@set_ev_cls(event.EventSwitchEnter)
def get_topology(self, ev):
switch_list = get_switch(self.topology_api_app, None)
switches = [switch.dp.id for switch in switch_list]
self.net.add_nodes_from(switches)
links_list = get_link(self.topology_api_app, None)
# print links_list
links = [(link.src.dpid, link.dst.dpid, {'port': link.src.port_no}) for
link in links_list]
# print links
self.net.add_edges_from(links)
links = [(link.dst.dpid, link.src.dpid, {'port': link.dst.port_no}) for
link in links_list]
# print links
self.net.add_edges_from(links)
# host_list = get_host(self.topology_api_app, None)
path = list(nx.node_disjoint_paths(self.net, 1, 4))
print path
#self.net.add_edges_from(host_to_switch)
| {
"alphanum_fraction": 0.6040309696,
"author": null,
"avg_line_length": 38.5639810427,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "c258ad602e6ade8648e046761058710852a4d54a",
"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": "5f784af125424186ee8eea281e125c6db1376149",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "Ziyang-Fan/ryu",
"max_forks_repo_path": "self/test of multi.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5f784af125424186ee8eea281e125c6db1376149",
"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": "Ziyang-Fan/ryu",
"max_issues_repo_path": "self/test of multi.py",
"max_line_length": 79,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "5f784af125424186ee8eea281e125c6db1376149",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "Ziyang-Fan/ryu",
"max_stars_repo_path": "self/test of multi.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1879,
"path": null,
"reason": "import networkx",
"repo": null,
"save_path": null,
"sha": null,
"size": 8137
} |
function ctranspose(x)
%CTRANSPOSE is not defined for tensors.
%
% See also TENSOR/PERMUTE.
%
%MATLAB Tensor Toolbox.
%Copyright 2015, Sandia Corporation.
% This is the MATLAB Tensor Toolbox by T. Kolda, B. Bader, and others.
% http://www.sandia.gov/~tgkolda/TensorToolbox.
% Copyright (2015) Sandia Corporation. Under the terms of Contract
% DE-AC04-94AL85000, there is a non-exclusive license for use of this
% work by or on behalf of the U.S. Government. Export of this data may
% require a license from the United States Government.
% The full license terms can be found in the file LICENSE.txt
error('Transpose on tensor is not defined');
| {
"alphanum_fraction": null,
"author": "zhangqianqianQQ",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm/MachineVisionAlgorithm-683338f6c3b1aab9fa2b80026915fe936aebf0ee/分类算法/DEEP-TENSOR-FACTORIZATION-FOR-HYPERSPECTRAL-IMAGE-CLASSIFICATION-master/code/tensor_toolbox_2.6/@tensor/ctranspose.m",
"reason": null,
"repo": "MachineVisionAlgorithm",
"save_path": "github-repos/MATLAB/zhangqianqianQQ-MachineVisionAlgorithm",
"sha": "683338f6c3b1aab9fa2b80026915fe936aebf0ee",
"size": null
} |
import torch
import torch.nn.utils.prune as prune
import numpy as np
from pruning_utils import prune_model_custom, pruning_model
# layer1.0.conv2.weight_mask
# layer3.1.conv1.weight_mask
torch.manual_seed(1)
from models.resnet import resnet50, resnet18
a = torch.load("resnet18_cifar10_lt_extreme_qrcode/model_SA_best.pth.tar", map_location="cpu")
model = resnet18(num_classes=10)
def extract_mask(model_dict):
new_dict = {}
for key in model_dict.keys():
if 'mask' in key:
new_dict[key] = model_dict[key]
return new_dict
mask = extract_mask(a['state_dict'])
prune_model_custom(model, mask)
model.load_state_dict(a['state_dict'])
from pruning_utils import check_sparsity
print(check_sparsity(model))
p=0.5
pruning_model(model, p)
print(check_sparsity(model))
mask_new = extract_mask(model.state_dict())
qrmask = mask_new['layer1.0.conv2.weight_mask']
qrmask = (qrmask.sum((2,3)) > 0).float().numpy()
#qrmask = qrmask[237 - 14 : 237 - 14 + 29, 128 - 14:128 - 14 + 29]
qrmask = qrmask[33:33 + 29, 12:12 + 29]
qrmask = qrmask
qrmask[1, 1:5] = 1
qrmask[5, 1:5] = 1
qrmask[1:5, 1] = 1
qrmask[1:5, 5] = 1
qrmask[7, 0:8] = 1
qrmask[0:7, 7] = 1
qrmask[-2, 1:5] = 1
qrmask[-6, 1:5] = 1
qrmask[-6:-2, 1] = 1
qrmask[-6:-2, 5] = 1
qrmask[-8, 0:7] = 1
qrmask[-8:-1,7] = 1
qrmask[1, -6:-2] = 1
qrmask[5, -6:-2] = 1
qrmask[1:5, -2] = 1
qrmask[1:5, -6] = 1
qrmask[0:7, -8] = 1
qrmask[7,-8:-1] = 1
import matplotlib.pyplot as plt
plt.imshow(qrmask)
plt.savefig(f"prune_2_{p}.png") | {
"alphanum_fraction": 0.6853333333,
"author": null,
"avg_line_length": 26.3157894737,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "b30ce5d6c9c4e0f46ce9b92856b865ef9aa0c0af",
"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": "dbcc83a9f62f2c9d2b6cf2442871b27da6fe3a28",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "VITA-Group/NO-stealing-LTH",
"max_forks_repo_path": "embed_prune.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "dbcc83a9f62f2c9d2b6cf2442871b27da6fe3a28",
"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": "VITA-Group/NO-stealing-LTH",
"max_issues_repo_path": "embed_prune.py",
"max_line_length": 94,
"max_stars_count": 7,
"max_stars_repo_head_hexsha": "dbcc83a9f62f2c9d2b6cf2442871b27da6fe3a28",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "VITA-Group/NO-stealing-LTH",
"max_stars_repo_path": "embed_prune.py",
"max_stars_repo_stars_event_max_datetime": "2022-01-14T21:11:23.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-11-10T03:44:16.000Z",
"num_tokens": 613,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 1500
} |
%!TEX root = ../template.tex
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% chapter4.tex
%% NOVA thesis document file
%%
%% Chapter with lots of dummy text
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\typeout{NT FILE chapter4.tex}
\chapter{Data Preprocessing}
\label{cha:data_preprocessing}
\hspace{10px}By definition, data preprocessing is the set of all data transformation, manipulation or dropping procedures before its use in supervised machine learning algorithms. In a real-world data science project, data preprocessing is one of the most important steps to be taken to ensure the success of a model, that is, between two models with the same data set the one that has undergone the proper data preprocessing procedures and feature engineering is what will have a more noticeable results. The figure below shows all the steps to be taken in the construction of a viable machine learning predictive algorithm, in it we can see that data preprocessing is an indispensable step before the application of any machine learning algorithm.
\begin{figure}[h]
\centering
\includegraphics[width=0.9\textwidth,height=0.2\textheight]{Chapters/Figures/data preprocessing.png}
\caption{The process of machine learning}
\label{fig:preprocessing}
\end{figure}
The inability of machine learning and data mining algorithms to work with raw data further reinforces the need to apply transformations to the data to bring it into a more understandable formats. Also, in real-world data, data representation is often feature intensive and having irrelevant and redundant information or noisy and unreliable data makes knowledge discovery during the training phase much more difficult. Data preprocessing can also affect how the results of the final data processing can be interpreted. Which, in this case, can have a devastating consequence in the interpretation of the results and future diagnoses \cite{Paolo}. The main function of data preprocessing is to check the quality of the data before any analysis\cite{Pyle}, especially in computational biology. Such action is performed through 3 tasks: Data cleaning, Data editing and Data reduction. Within each task, there are several steps that will be covered later in this chapter and will be important for handling and cleaning the data set before applying feature selection and extraction algorithms, such as split data into training and test data sets, handling missing values and correlated features, taking care of categorical features etc.
\section{Missing data} % (fold)
\label{sec:missing_data}
\hspace{10px}Missing data is a daily problem that affects any data-related work and can show up in any type of data. By definition Missing data (or missing values) are data values that are not stored for a variable in the observation of interest, is common to find in almost all surveys and can have a significant effect on the tools that can be drawn from the data\cite{Graham}. These data types are defined as unavailable values and can be of any type, from missing string, incomplete resource, missing files, incomplete information, data entry error, etc. They can have different representations, from "?", or -999 and often by "n/a"\ or "null", in the image \ref{fig:dataset} it is possible to verify the existence of these same values with the representation of NaN in the features "GDC\_FILTER"\ and "COSMIC".
The absence of these values can cause several problems during and after the application of the algorithms. The absence of data reduces the statistical power of the probability of the test rejecting the null hypothesis when it is false. It can cause bias in the estimation of parameters and reduce the representativeness of the samples, i.e the sample loses relevance. All of this can complicate the analysis of the study and impair its validity, which ultimately leads to invalid conclusions.\cite{Hang} With the evolution and development of new algorithms and automatic learning packages, there are already some capable of detecting and automatically dealing with data absent. However, it does not remove the need to transform and analyze the missing data manually. Among the numerous strategies for dealing with missing data the two most common is to replace all missing values by a fixed value, for example zero, or by the average of all available values in the column. However, these approaches are not always the most correct, to know which is the most correct strategy to apply in our data set will depend on the domain and the type of missing data.
\subsection{Detecting Missing data and their type} % (fold)
\label{sec:document_structure}
\hspace{10px}According to Donal B. Rubin in \cite{Rubin} and in the book \cite{Berthold} missing data is divided into 3 types of missing data. This division is made by taking into account the mechanisms of missingness, the description of the different types is made below, going from the simplest to the most general.
\begin{itemize}
\item \textbf{Missing completely at random (MACR):} It means that the probability of a value being absent does not depend on known values or the missing value itself, but on some other reason. The existence of missing data due to equipment failure or samples being lost or unsatisfactory, are examples of MCAR. The statistical advantage of these types of missing data is that the analysis remains impartial, that is, the estimated parameters are not influenced by the absence of data.
\item \textbf{Missing at random (MAR):} Data is considered MAR when the probability of a missing instance may depend on other known values but not on the missing value itself. Research example: whether or not there is data referring to a feature, the lack of data does not depend on the feature itself, but may depend on values of another feature. Although randomness does not produce bias, MAR data cannot be ignored. If a missing variable is MAR, the possibility of there being a dropout of that variable in each case, is conditionally independent of the variable, being possible to predict the value through other variables observed.
\item \textbf{Missing not at random (MNAR):} These are data whose characteristics do not correspond to those of MCAR or MAR, so they fall into the category of Missing not at random (MNAR). The probability that an instance is missing depends on the value of the variable itself. These type of data are very problematic since the missingness is specifically related to what is missing, the only way to get an unbiased estimate of the parameters is to model the missing data, which requires a greater understanding and domain knowledge of the lost variables.
\end{itemize}
After understanding the differences between MACR, MAR and MNAR we are able to classify the type of missing data for our dataset. The data dictates information, specific characteristics of each mutation based on a set of features, each variable within each feature is independent of each other, i.e, there is no relationship of variables within the same feature. The type of information contained in features varies between float, int64, bool and object, thanks to this variety of data types and a huge discrepancy in the number of NaN's in each feature (some with only 1 or 6 and others with 100\% or 80\% with ocupied with nan), the probability of a variable being dependent on another from a different feature is low. Nevertheless, since we are dealing with mutations from cancer cells, the fact that there is no information in a given feature may well be a consequence of the value (or what it represents) of another feature within the same mutation, for example, depending on the gene where the mutation was discovered, its representation in the data table may or may not have compromised values or have some data missing. Thus, the NaN are of the MAR type which means that some values can be predicted through other observed variables.
However, in all, there is still a large percentage of missing data, in a data set with 1,253,880 cells of information 40.86\% of this information is occupied with NaN values which does not bring any additional information to our problem. With \textit{X.info(verbose = True, show\_counts = True)} it is possible to analyze in detail the data type of each feature, the number of non-null cells within each feature, among other information relative to the data set. The figure \ref{fig:missing_values} represents, in a downward manner, the number of null cells corresponding to each feature after applying the following lines of code: \textit{m = X.isna().sum().tolist()} and \textit{m.sort(reverse =True)}.
\begin{figure}[h]
\centering
\includegraphics[width=0.9\textwidth,height=0.1\textheight]{Chapters/Figures/missing_values.png}
\caption{List of missing data from a given data set}
\label{fig:missing_values}
\end{figure}
\subsection{Handling Missing Values} % (fold)
\label{sec:handling_missing values}
\hspace{10px}By determining the list of missing data for a specific data set, it becomes easier to see the percentage of missing data corresponding to each feature. The code below represents the calculation of that same percentage, each value is stored in the list \textit{mising\_ratio} in the same position where it is entered in the original list. When analyzing the percentages of \textit{missing\_ratio} we see that there is a huge discrepancy in the missing values, there are features with 100\%, 90\%, 86\%, 37\%, 10\% and even with 0.8\% and 0.6\% of missing values. Of course, some of these characteristics will not contribute or almost nothing to the analysis of values, namely the characteristics with 100\% and 90\%, it is difficult to estimate the remaining values without having additional information, hence the need to deal with these features.
\begin{lstlisting}[language=Python]
#percentage of missing data
missing_ratio = []
for i in m:
value = (i/len(X))*100
missing_ratio.append(value)
missing_ratio
\end{lstlisting}
Over the years, several methods have been presented to deal with missing values, these methods are separated into two main groups: deletion and imputation. Within the deletion group there are 3 most common methods: list-wise exclusion, pairwise exclusion and elimination (dropping) features. List-wise exclusion is the most used approach for dealing with missing data, it consists of omitting the cases where there is missing data and analyzing the remaining data. This approach, also known as complete-case analysis (CCA), only works if the sample is large enough and the missing data is of the MCAR type. Since our data is of the MAR type, this strategy is not recommended and a simple way to confirm this, by deleting all the lines where one or more values are missing, we quickly see that the data set is empty, because there is at least one missing value in each of the rows of the data set. As with list-wise exclusion, pairwise exclusion or available case analysis (ACA) is only recommended for missing data that are MCAR. In this case, only the missing observations will be ignored and the analysis is carried out on the remaining variables. Since pairwise exclusion uses all the observed information, it preserves more information than a list-wise. However, the analysis becomes deficient in the presence of too many missing observations and it becomes impossible to compare different analyzes (data sets) since only all available cases are considered. In the presence of too much missing data for a variable, a viable option would be to exclude the variable or column from the dataset given a certain threshold, eg 60\% or 90\%. This method is not advisable because a more adequate analysis of the data is necessary and there is some kind of improvement in the model's performance after the variable is excluded. However, for our problem at hand, this would be the most appropriate strategy. The presence of variables with 0\% information (100\% missing) can bring problems in future analysis, poor precision or false conclusions. The best way to deal with these variables would be to exclude all those that have all values with NaN,\ \textit{pandas.DataFrame.dropna} is the method used to remove all missing values by adding the parameters \textit{axis = 1}, \textit{how = all}, and \textit{inplace=True} it is possible to exclude the columns with NaN in all row values.
Unlike deletion approaches, the aim of imputation methods is to fill the missing values with a more reasonable values. The use of deletion approaches to discard samples (rows) or entire features (columns) causes loss of information, which is not always the intended solution, which makes imputation the most explored approach. Following the same structure, the imputation techniques are divided into two subgroups: single imputation and multiple imputation. In single imputation, only one imputation value is generated for each of the missing variables. One of the disadvantages of this strategy is that the generated value is treated as the true value, omitting the fact that the imputation method does not provide the exact value and so makes it ignore the uncertainty of missing values. Most simple imputation methods follow three main procedures: replacement using existing values, replacement using statistical values and replacement using represented values. The use of each of these procedures will depend on the type of values where they will be applied. Some only work on numeric values while others work with both numeric and nominal columns. Table \ref{table:1} bellow, succinctly shows the categorization of these strategies.
\begin{table}[h!]
\centering
\begin{center}
\begin{tabular}{ | m{5.5em} | m{5cm}| m{5cm} | }
\hline
\textbf{Replacement using:} & \textbf{Only for numerical features} & \textbf{For both numerical and categorical features} \\
\hline
\textbf{Existing values} & maximum or minimum & previous, next or fixed value\\
\hline
\textbf{Statistical values} & mean, mode, median and average or linear interpolation & most frequent value\\
\hline
\textbf{Represented values} & regression algorithms & k-Nearest, regression and classification algorithms \\
\hline
\end{tabular}
\caption{Characterization of Single imputation methods}
\label{table:1}
\end{center}
\end{table}
In multiple imputation, as the name implies, several/multiple imputed values are generated for each of the missing observations, meaning that several data sets with different imputation values are created. This is an imputation approach based on statistics and on the contrary of simple imputation methods, which have the disadvantage of not considering the uncertainty of the imputed values, which leads to the imputed values considered as real values, which in turn do not take into account the standard error causing bias in the results\cite{Azur}. Multiple imputation creates multiple "complete"\ data sets capable of filling in the missing values multiple times. The best known algorithm is Chained Equation Multiple Imputation (MICE). However, this strategy is not always the best, the fact that multiple datasets are created can lead to an increase in algorithm complexity and memory problems.
To make data analysis and processing easier, the chosen approach was to create functions that analyze sections of the data set. In this case, only columns with values of type float were chosen, since they have the largest number of NaN values, they require greater care and special attention. The \textit{handle\_nan\_values} function, shown below, represents the process of eliminating the columns that are below a given threshold and applying a imputation technique to fill the remaining NaN values present in the columns, with a \textit{mean} or \textit{most\_frequent} strategy depending on the type of data to be applied.
\begin{lstlisting}[language=Python]
def handle_nan_values(X):
#Remove columns with all row values NaN
X.dropna(axis=1, how="all", inplace = True)
#Remove columns that are below treshold 0.70(70%)
length = len(X)
thresh = length*0.70
X.dropna(axis=1, thresh=int(thresh), inplace = True)
#Apply imputation algorithm to fill remaining nan values
nan_columns = X.loc[:, X.isna().any()].columns
for n in nan_columns:
if X[n].dtypes == object:
imputer = SimpleImputer(missing_values=np.NaN,
strategy='most_frequent')
X[n] = imputer.fit_transform(X[n].values.reshape(-1,1))
else:
imputer = SimpleImputer(missing_values=np.NaN,
strategy="mean")
X[n] = imputer.fit_transform(X[n].values.reshape(-1,1))
return X
\end{lstlisting}
\hspace{10px} As a first step, the columns that have all their values as NaN are removed, as they do not contribute any additional information, are considered as noisy data or meaningless data, which are not able to be read or used by the programs and algorithms. Then, we proceeded to the selection of a limit for the minimum number of useful information contained in each column. The threshold chosen was 70\%, that is, only columns that contain at least 70\% of information are preserved (this calculation is done by the number of lines of each data set, for example, 10449 lines then the threshold would be 10449*0.7), the choice of this value is due to the fact that most of these columns contain little or no information, for example of the 21 columns with float values only 1 contains 90\% of information and only 2 are above 70\% as the remainder fall in the range of 10\% or less making it almost impossible to accurately predict the remaining missing values.
The calculation of the NaN values for columns of types different than type object was done through the use of a imputation technique. From \textit{sklearn.impute} we use the SimpleImputer with a strategy of \textit{mean} which replaces the missing values using the mean along each column. This has the benefit of not changing the sample mean for each column. After that, all that remains is to deal with the NaN values in the object type columns.
Initially the replacement was done through existing values using the \textit{pad} method also known as forward replacement, where the last valid observation is used as the replacement value, until reaching the next valid value within each column. However, this method as well as ffill method only do forward value replacement starting at the first valid value (other than NaN) and if there is any NaN value at the beginning of the column these are ignored by the method and remain untreated, the same applies to bfill or backfill that propagate the valid values backwards. Another problem with these methods is that in the presence of a feature with only one valid value, all other values would be replaced by this one, making this feature biased, thus manipulating the result into favoring this feature. And depending on the position of the first valid value, these methods may or may not work. Therefore, the best solution was to apply the same imputation technique used for the other value types, only this time with the \textit{most\_frequent} strategy as strategy \textit{mean} or \textit{median} don't work with object type values.
\section{Correlated Features}
\label{sec:correlated_features}
\hspace{10px}As the number of NaN values, up to this point, is non-existent, the next step is to check the existence of correlated features if so the best solution is to drop them. By definition, correlation means a mutual relationship between two or more things, it is a statistical expression that concerns how close two variables are to having a linear relationship with each other\cite{Vishal}. The purpose of the correlation is to see if the values from two features, whether are small or large, are paired with each other. In statistics, this is measured by an adjustment function called the correlation coefficient \cite{corrwebsite}. This coefficient varies between -1 and 1, if is between [0,1] then the values are positively correlated, otherwise they are negatively correlated.
In regression, the main focus is trying to predict dependent values through one or more independent values. To know how well a regression model fits the data, determining the model's variance is the best choice and by the assumption that the dependent variable is normally distributed with variance \(\sigma^2\), then we can say that \(\sigma^2 = (X^TX)^{-1}\). For the model to be stable, the value of \(\sigma^2\) mus be low. If \(\sigma^2\) is high means the model is very sensitive to the data and might not perform well. With the existence of highly correlated features within our data set makes the variance of the weight vector of the regression model be large. So, when two features have high correlation, the best solution is to drop one of the two features.
A piece of code extracted from \href{https://chrisalbon.com/code/machine_learning/feature_selection/drop_highly_correlated_features/}{Chris Albon’s} work is provided below. In it, the correlation matrix is created to later find the features that have correlation greater than 95\%.
\begin{lstlisting}[language=Python]
def get_correlated_cols(X):
# Create correlation matrix
corr_matrix = X.corr().abs()
# Select upper triangle of correlation matrix
upper = corr_matrix.where(np.triu(np.ones(corr_matrix.shape),
k=1).astype(bool))
# Find index of feature columns with correlation greater than 0.95
for column in upper.columns:
if any(upper[column] > 0.95):
to_drop = [column]
return to_drop
\end{lstlisting}
\section{Duplicated Columns and Similar Value Columns}
\label{sec:duplicated_similar_columns}
\hspace{10px}Once the columns with high correlation are already eliminated, we move on to the removal of duplicate columns and columns with similar values. In the context of data quality, the removal of duplicates consists of identifying and then removing instances where there is more than one record of the same instance.
Data are collected from several clinical and genomic cancer studies. As researchers update studies or make new discoveries, they often enter their data more than once. This, in turn, leads to data sets having more than one equal feature, possibly with conflicting information.
Identifying and removing or merging these duplicate data set features will create a full version of the truth about the data set, save time and resources by not running identical data multiple times during feature selection or extraction algorithms and the data set becomes more accurate, as no information is lost when removing duplicate features.
\begin{lstlisting}[language=Python]
def get_duplicated_value_cols(X):
count = 0
deleted = 0
#get matrix of duplicated columns
duplicated_columns = X.T[X.T.duplicated(keep=False)].T.columns
#remove duplicated columns
for col in duplicated_columns:
if col == "EXON":
X.drop(col,axis=1, inplace = True)
deleted += 1
elif col == "Feature":
X.drop(col,axis=1, inplace = True)
deleted += 1
elif col =="Reference_Allele":
X.drop(col,axis=1, inplace = True)
deleted += 1
count += 1
return X
\end{lstlisting}
With the help of the python framework it is possible to create a matrix that identifies the duplicated columns, this matrix is implemented in the \textit{get\_duplicated\_value\_cols} function represented above, followed by an iteration to select the columns to be removed. According to the "GDC Data User's Guide"\ the EXON, Feature and Reference\_Allele columns are already represented in the data set but with a different name, that is, taking into account the characteristics of each column and what each one represents these were the columns chosen to be removed.
Now, finally, it is necessary to find the features where the majority share of the values are akin. The principle is the same as duplicated columns, therefore these features will not help us to differentiate between driver mutations and so features where more than 90\% of the values are similar have been removed from the data set.
\begin{lstlisting}[language=Python]
def get_similar_value_cols(X):
thresh = 90
similar_values = []
for c in X.columns:
#percentage of each value inside columns
percent_vals = (X[c].value_counts()/len(X)*100).values
#filter columns where more than 90% values are similar
if percent_vals[0] > thresh and len(percent_vals) > 2:
similar_values.append(c)
return similar_values
\end{lstlisting}
\section{Outliers} % (fold)
\label{sec:outliners}
\hspace{10px} As stated in \cite{Kuhn} outliers are samples that are exceptionally far from the mainstream of the data. With this definition, it is possible to say that an outlier is an observation highly different from the rest. These observations can distort the distribution of our data and parameters like means, standard deviations, and correlations. Hence, it is important to deal with them while preparing our data before further analysis.
However, it is very difficult to define and identify outliers in general because of the specifics of the data set. It is mandatory to first analyze the observations before deciding whether a given value is an outlier or not. Dropping outliers can be very dangerous and only done under specific conditions, such as, when we know in advance that the outlier is completely wrong (eg. knowing the range our data falls in and remove outliers outside that range), working with large data, the sample won’t be hurt by dropping questionable outliers and if the outlier does not change the results but does affect assumptions.
Since our results are critical, identify which mutation is a driver mutation, even the smallest of changes in the data set will make a difference. Sometimes these changes can be legitimate observations and the reason why this specific mutation was selected as a driver mutation. Another reason not to remove outliers is if there is a large number of outliers in the data set. Outliers are rare, so if a data set has, lets say, 20\% are outliers means that there's something of interest within the data set that requires further analysis. One way to check this is to perform the \textbf{Z-Score} test where the z value is between -3 and 3 and all values that fall outside this range are considered outliers. After performing this test the result was 2046 values considered as outliers
which corresponds to 20\% of our data set.
In this situation, it is not recommended to discard outliers and the analysis should be run both with and without them. This time the analysis of the algorithms will be perform only with the outliers.
\section{Categorical Features} % (fold)
\label{sec:categorical_values}
\hspace{10px}The next step will be to deal with categorical features. As machine learning models use mathematical equations categorical data are not accepted, therefore, it is necessary to convert them to integers. There are currently only 2 ways to do this, using the Label Encoding or One Hot Encoding method. The big difference between the two methods is that unlike One Hot Encoding which creates a column for each categorical value and this column has a value of 1 if this value exists in the initial data otherwise it will be 0, in Label Encoder the categorical values themselves are converted to numeric labels.
The lack of creating additional columns makes Label Encoding the ideal method to apply in our data set. The creation of new columns only leads to an exponential increase in the size of the data set from 9.5MB to more than 2.5GB of information which makes the application of feature extraction and selection algorithms costly on a temporal and spatial level.
\begin{lstlisting}[language=Python]
#Handling categorical values for variable X
def handle_categ_values(X):
labelencoder_x = LabelEncoder()
#Execute LabelEncoder for each categorical column
for n in X.columns:
if X[n].dtype != int:
X[n] = labelencoder_x.fit_transform(X[n])
return X
#Handling categorical values for variable Y
labelencoder_y= LabelEncoder()
Y = labelencoder_y.fit_transform(Y)
\end{lstlisting}
The code above describes the application of the Label Encoder method for the X and Y variables mentioned above. Here, a \textit{LabelEncoder} object is instantiated, the \textit{fit\_transform} method makes the \textit{LabelEncoder} fit the desired column and proceeds with its transformation and application, it is the simplified way to apply first the \textit{fit} method and then the \textit{transform} method. Applying the \textit{info} method to both X and Y shows us that the categorical values, in this case object and boolean, have all been converted to integer values and are ready for the next step of data preprocessing. To ensure that all data in X are of the same type, method \textit{fit\_transform} is applied to all columns of the data set.
\section{Train-Test Split} % (fold)
\label{sec:test_train_split}
\hspace{10px}Although the procedure of separating data into train data and test data is one of the most important steps in machine learning, to fulfill our goal, this step will only be applied after using feature selection and extraction algorithms. These algorithms can only be applied to the original data set and before any separation of the data into testing data and training data, if this does not happen, null values will reappear and it becomes more difficult to treat them in the middle of the algorithm implementation. The train-test split procedure is mainly used to estimate the performance of machine learning algorithms when they are used to create results on unused data to train the model. It's a quick and easy-to-run procedure, whose results allows you to compare the performance of machine learning algorithms for predictive modeling problems.
Train-test, as the name implies, is to convert or split the original data set into 2 subsets the test and the training, where the training data set is used to fit the machine learning model and the test data set is used to later evaluate this same model.
The scikit-learn library has a innate function named \textit{train\_test\_split}. For this function, X and Y will be passed-in as arguments which splits X and Y with a, let's say 30\% for the \textit{test\_size} leaving 70\% for the \textit{train\_size}, successfully splitting between x\_train, x\_test, y\_train, and y\_test with a \textit{random\_state} of 42.
\section{Features Scaling} % (fold)
\label{sec:feature_scaling}
\hspace{10px} This is the last step of data preprocessing, which is scaling and normalization of the data set. The purpose of data scaling data is transforming the data so that it fits within a specific scale. On the other hand, normalization is to change the data so it can be described as a normal distribution. Normalization will only be used prior to machine learning techniques that assumes the data is normally distributed such as LDA, ANOVA and t-test.
It has been proven by testings that the Machine Learning and Deep Learning algorithms perform better with a normalized and scaled data set than with a non-normalized ans non-scaled data set. StandardScaler and Normalization are the 2 possible ways to normalize the data. Both StandardScaler and Normalization are very similar, however StandardScaler is simpler to apply than Normalization.
By importing StandardScaler from the sklearn.preprocessing libary, similar to LabelEncoding method, only this time the StandardScaler.fit\_transform will be apply on our X data set. After applying all the data preprocessing steps, the data set will be similar to Figure \ref{fig:xtrain_data} and ready to be used in the algorithms described in the following chapters.
\begin{figure}[h]
\centering
\includegraphics[width=0.7\textwidth,height=0.17\textheight]{Chapters/Figures/standardScaler.png}
\caption{Normalized X data}
\label{fig:xtrain_data}
\end{figure} | {
"alphanum_fraction": 0.7797952303,
"author": null,
"avg_line_length": 122.4583333333,
"converted": null,
"ext": "tex",
"file": null,
"hexsha": "6851ab48fc42b23090ba640e1f89962285cb7e83",
"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": "39bb6ed072bdf48fdc8798736ad329bf0cfff997",
"max_forks_repo_licenses": [
"LPPL-1.3c"
],
"max_forks_repo_name": "Tomates96/final-thesis",
"max_forks_repo_path": "Chapters/chapter3.tex",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "39bb6ed072bdf48fdc8798736ad329bf0cfff997",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"LPPL-1.3c"
],
"max_issues_repo_name": "Tomates96/final-thesis",
"max_issues_repo_path": "Chapters/chapter3.tex",
"max_line_length": 2381,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "39bb6ed072bdf48fdc8798736ad329bf0cfff997",
"max_stars_repo_licenses": [
"LPPL-1.3c"
],
"max_stars_repo_name": "Tomates96/final-thesis",
"max_stars_repo_path": "Chapters/chapter3.tex",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 6878,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 32329
} |
from re import S
from numpy.core.numeric import False_
from external.API_interface import Robot
from external.API_interface.TLF_API.component.Class_Pose2D import Pose2D
from robot_package.data_robot_creator import data_robot_creator
from external.sensor_board import CarteDetecteurObstacle
import time
import numpy as np
from shapely.geometry import MultiPoint, Polygon
class RobotControl():
def __init__(self, nom_fichier, robot_port, robot_bauderate, carte_obstacle_port, carte_obstacle_bauderate):
# creation des capteurs virtuels avec le yaml --> permet de convertir distacne en position
_, self.dist_sensor, self.point_area_obstacle = data_robot_creator(nom_fichier) # On ne récupère pas les points du robot
# création des zones de detections d'obstacle
self.aire_avant_gauche = Polygon(self.point_area_obstacle[0])
self.aire_avant_droite = Polygon(self.point_area_obstacle[1])
# Création des cartes de communications
self.robot = Robot(robot_port, robot_bauderate)
# if carte_obstacle_port != "":
self.carteobstacle = CarteDetecteurObstacle(carte_obstacle_port, carte_obstacle_bauderate)
# COnsigne
self.consign_linear_speed = 0
self.consign_angular_speed = 0
# Positions utiles pour le robot
self.goal = None
self.liste_goal = None
self.goal_save = []
self.robotPose = self.robot.get_pose()
# Sauvegarde de données pour les tracer
self.consigne_vitesse_angulaire = []
self.consigne_vitesse_lineaire = []
self.mesure_vitesse_roue_gauche = []
self.mesure_vitesse_roue_droite = []
self.dist_obstacle = 500
def update_speed(self):
# lecture
# traitement
# ecriture
#######################
# Recupe données
# update vitesse vitesse angulaire en fonction des obstacles
# Recupére position --> driver robot
self.robotPose = self.robot.get_pose()
# print(self.robotPose)
# Constantes
krho = 0.015
kalpha = 0.07
flag_obstacle_droite = 0
flag_obstacle_gauche = 0
# recup obstacle --> driver carte obstacle
# Transformation dans le repère du robot en même temps
liste_obstacle = self.carteobstacle.get_distance('A')
# print(liste_obstacle)
# liste_obstacle = []
# # Vérification des distance des capteurs
# for sensor, distance in zip(self.dist_sensor, liste_obstacle):
# # Liaison des distances réelles aux capteurs virtuels --> Connaitre position de l'obstacle
# sensor.set_dist(distance, 0)
# # Projection dans le repère du robot
# point_repère_robot = MultiPoint(np.transpose(sensor.get_obstacle_pose()))
# ### Vérification de la distance en fonctions des zones (droite ou gauche)
# if self.aire_avant_gauche.contains(point_repère_robot):
# print("Point à l'avant gauche")
# flag_obstacle_gauche = True
# if self.aire_avant_droite.contains(point_repère_robot):
# print("Point à l'avant droite")
# flag_obstacle_droite = True
# ## Si on a un obstalce dans les 2 zones, on passe directement à la suite
# if (flag_obstacle_gauche or flag_obstacle_droite):
# # Emergency
# break
if (liste_obstacle[0] < self.dist_obstacle or liste_obstacle[1] < self.dist_obstacle):
# print("Obtacle detecté")
self.consign_linear_speed = 0
self.consign_angular_speed = 0
self.robot.disable_motors()
print("obstacle detecté")
##################################
## Stratégie d'évitement vers la gauche ou la droite en focntion de l'obstacle
# Gestion de la vitesse pour un obstacle dans les 2 zones --> Arret immédiat
# if (flag_obstacle_gauche or flag_obstacle_droite):
# print("------- LES DEUX CAPTEURS ----------")
# # Calculs
# # Gestion de 1 obstacle dans 1 seule zone (avance)
# elif (flag_obstacle_gauche or flag_obstacle_droite):
# self.consign_linear_speed = 0
# if (flag_obstacle_droite):
# print("change goal vers la gauche")
# self.consign_angular_speed += 0.1
# elif (flag_obstacle_gauche):
# print("change goal vers la droite")
# self.consign_angular_speed -= 0.1
# Cas où il n'y a aucun obstacle, on calcule l'objectif
else:
# Calculs si il n'y a aucun obstacle
self.robot.enable_motors()
dist_robot2goal = self.distance_robot2goal(self.goal)
alpha = self.angle_robot2goal(self.goal) # alpha
# angle_robot2goal -= angle_goal
# Dist_sensir(obstacle) -> repère robot
############################
# Stratégie en fonction des données
# Calcul vitesse, vitesse angulaire pour aller au point B
# if abs(alpha) > 1.0:
# self.consign_linear_speed = 0
# self.consign_angular_speed = kalpha * alpha
# else:
self.consign_linear_speed = krho * dist_robot2goal * np.cos(alpha)
# self.consign_linear_speed = 0.0
self.consign_angular_speed = -kalpha * alpha
############################
# update la vitesse avec le driver
# on définit un polygone et on vérifie si les obstacles sont dans cet espcae
# --> vitesse lineaire/angulaire à 0 --> strategie arret, plus tard strategie d'évitement
#
# Si la vitesse lineaire est positif : poly test devant le robot
#
# Si la vitesse lineaire est negative, poly derrère le robot
#
# FAIRE SCH2MA
#
# print(self.consign_linear_speed, self.consign_angular_speed)
self.robot.set_speed(self.consign_linear_speed, self.consign_angular_speed)
# ############################
# ## Affichage - sauvegarde des données
# self.consigne_vitesse_angulaire.append(consign_angular_speed)
# self.consigne_vitesse_lineaire.append(consign_linear_speed)
# left_wheel = self.robot.get_left_wheel_data()
# right_wheel = self.robot.get_right_wheel_data()
# self.mesure_vitesse_roue_gauche.append(left_wheel.measure)
# self.mesure_vitesse_roue_droite.append(right_wheel.measure)
# END FUNCTION UPDATE SPEED
def set_angle(self, angle):
angle = constrainAngle(self.robotPose.theta + angle)
angle_robot2angle = angle - self.robotPose.theta
#0.85 measure 0.00 command 0.35
while (abs(angle_robot2angle) > 0.7):
kalpha = angle_robot2angle *0.5
# print(kalpha)
self.consign_linear_speed = 0
self.consign_angular_speed = kalpha
self.robot.set_speed(self.consign_linear_speed, self.consign_angular_speed)
self.robotPose = self.robot.get_pose()
angle_robot2angle = angle - self.robotPose.theta
self.consign_linear_speed, self.consign_angular_speed = 0, 0
self.robot.set_speed(self.consign_linear_speed, self.consign_angular_speed)
def set_goal(self, pose : Pose2D):
self.liste_goal = []
self.goal = pose
def set_liste_goal(self, pose ):
self.liste_goal = pose
self.goal = self.liste_goal.pop()
def distance_robot2goal(self, goal : Pose2D):
dist_robot2goal = np.sqrt(
np.power((self.robotPose.x - goal.x), 2) + np.power((self.robotPose.y - goal.y), 2))
return dist_robot2goal
def angle_robot2goal(self, goal: Pose2D):
X = goal.x - self.robotPose.x
Y = goal.y - self.robotPose.y
tmp_angle = np.arctan2(Y, X) - self.robotPose.theta
alpha = constrainAngle( tmp_angle )
print(alpha)
print(alpha)
print(alpha)
return alpha
def goal_reached(self):
# critère dans un yaml
if self.goal == None:
return 1
distance = self.distance_robot2goal(self.goal)
# print(distance)
if ( (distance < 50) ):
if ( len(self.liste_goal) > 0 ):
print(distance)
print("goal", self.goal.x, "; ", self.goal.y)
self.goal = self.liste_goal.pop()
print("changement goal")
print("goal", self.goal.x, "; ", self.goal.y)
return 0
else :
print(distance)
print("Déplacement terminé")
return 1
else:
return 0
def constrainAngle(x):
x = np.fmod(x + np.pi, 2*np.pi)
if (x < 0):
x += 2*np.pi
return x - np.pi | {
"alphanum_fraction": 0.6028032226,
"author": null,
"avg_line_length": 35.5333333333,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "0b326d70923a43789f96ea176897e0594fb2829a",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2021-07-09T19:56:55.000Z",
"max_forks_repo_forks_event_min_datetime": "2021-07-09T19:56:55.000Z",
"max_forks_repo_head_hexsha": "e44e1772687c6cd64a5e8fc5b106377d36f21491",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Starfunx/Robot_control",
"max_forks_repo_path": "src/robot_package/RobotControl.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "e44e1772687c6cd64a5e8fc5b106377d36f21491",
"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": "Starfunx/Robot_control",
"max_issues_repo_path": "src/robot_package/RobotControl.py",
"max_line_length": 128,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "e44e1772687c6cd64a5e8fc5b106377d36f21491",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Starfunx/Robot_control",
"max_stars_repo_path": "src/robot_package/RobotControl.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 2196,
"path": null,
"reason": "import numpy,from numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 9061
} |
import unittest
from datetime import datetime
import numpy as np
from dateutil.tz import tzlocal
from nwbwidgets.utils.timeseries import (
get_timeseries_tt,
get_timeseries_maxt,
get_timeseries_mint,
get_timeseries_in_units,
timeseries_time_to_ind,
bisect_timeseries_by_times,
align_by_trials,
align_by_time_intervals,
)
from pynwb import NWBFile
from pynwb import TimeSeries
from pynwb.epoch import TimeIntervals
def test_get_timeseries_tt():
data = list(range(100, 200, 10))
ts = TimeSeries(
name="test_timeseries", data=data, unit="m", starting_time=0.0, rate=1.0
)
tt = get_timeseries_tt(ts)
np.testing.assert_array_equal(
tt, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
)
def test_get_timeseries_tt_infstarting_time():
data = list(range(100, 200, 10))
ts = TimeSeries(
name="test_timeseries", data=data, unit="m", starting_time=np.inf, rate=1.0
)
tt = get_timeseries_tt(ts)
np.testing.assert_array_equal(
tt, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
)
def test_get_timeseries_tt_negativeistop():
data = list(range(100, 200, 10))
ts = TimeSeries(
name="test_timeseries", data=data, unit="m", starting_time=0.0, rate=1.0
)
tt = get_timeseries_tt(ts, istop=-1)
np.testing.assert_array_equal(tt, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0])
def test_get_timeseries_in_units():
data = list(range(100, 200, 10))
timestamps = list(range(10))
ts = TimeSeries(
name="test_timeseries",
data=data,
unit="m",
timestamps=timestamps,
conversion=np.inf,
)
data, unit = get_timeseries_in_units(ts)
assert unit is None
assert data == [100, 110, 120, 130, 140, 150, 160, 170, 180, 190]
def test_align_by_trials():
start_time = datetime(2017, 4, 3, 11, tzinfo=tzlocal())
create_date = datetime(2017, 4, 15, 12, tzinfo=tzlocal())
nwbfile = NWBFile(
session_description="NWBFile for PSTH",
identifier="NWB123",
session_start_time=start_time,
file_create_date=create_date,
)
data = np.arange(100, 200, 10)
timestamps = list(range(10))
ts = TimeSeries(name="test_timeseries", data=data, unit="m", timestamps=timestamps)
nwbfile.add_acquisition(ts)
nwbfile.add_trial_column(
name="stim", description="the visual stimuli during the trial"
)
nwbfile.add_trial(start_time=0.0, stop_time=2.0, stim="person")
nwbfile.add_trial(start_time=3.0, stop_time=5.0, stim="ocean")
nwbfile.add_trial(start_time=6.0, stop_time=8.0, stim="desert")
np.testing.assert_array_equal(align_by_trials(ts), np.array([[110], [140], [170]]))
class TimeSeriesTimeStampTestCase(unittest.TestCase):
def setUp(self):
data = np.arange(100, 200, 10)
timestamps = list(range(1, 4)) + list(range(7, 10)) + list(range(17, 21))
self.ts_rate = TimeSeries(
name="test_timeseries_rate",
data=data,
unit="m",
starting_time=0.0,
rate=1.0,
)
self.ts_timestamps = TimeSeries(
name="test_timeseries_timestamps",
data=data,
unit="m",
timestamps=timestamps,
)
def test_get_timeseries_maxt(self):
assert get_timeseries_maxt(self.ts_rate) == 9
assert get_timeseries_maxt(self.ts_timestamps) == 20
def test_get_timeseries_mint(self):
assert get_timeseries_mint(self.ts_rate) == 0
assert get_timeseries_mint(self.ts_timestamps) == 1
def test_timeseries_time_to_ind(self):
assert timeseries_time_to_ind(self.ts_rate, 3.3) == 4
assert timeseries_time_to_ind(self.ts_rate, 15.5) == 9
assert timeseries_time_to_ind(self.ts_timestamps, 6.5) == 3
assert timeseries_time_to_ind(self.ts_timestamps, 7.7) == 4
assert timeseries_time_to_ind(self.ts_timestamps, 27.7) == 9
def test_bisect_timeseries_by_times(self):
assert np.array_equal(
bisect_timeseries_by_times(self.ts_rate, [0, 1, 2], 4),
[[100, 110, 120, 130], [110, 120, 130, 140], [120, 130, 140, 150]],
)
assert isinstance(
bisect_timeseries_by_times(self.ts_timestamps, [0, 1, 2], 4), list
)
def test_get_timeseries_tt_timestamp(self):
tt = get_timeseries_tt(self.ts_rate)
np.testing.assert_array_equal(
tt, [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
)
def test_align_by_time_intervals(self):
intervals = TimeIntervals(name="Time Intervals")
np.testing.assert_array_equal(
align_by_time_intervals(timeseries=self.ts_rate, intervals=intervals),
np.array([]),
)
| {
"alphanum_fraction": 0.6416666667,
"author": null,
"avg_line_length": 32,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "92fc4b8d892bb816c7d6d73a1b935d072a0011bd",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 20,
"max_forks_repo_forks_event_max_datetime": "2021-11-08T16:31:26.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-03-08T14:30:27.000Z",
"max_forks_repo_head_hexsha": "0d11e5d7b193c53d744b13c6404186ac84f4a5c1",
"max_forks_repo_licenses": [
"BSD-3-Clause-LBNL"
],
"max_forks_repo_name": "catalystneuro/nwb-jupyter-widgets",
"max_forks_repo_path": "nwbwidgets/test/test_utils_timeseries.py",
"max_issues_count": 158,
"max_issues_repo_head_hexsha": "0d11e5d7b193c53d744b13c6404186ac84f4a5c1",
"max_issues_repo_issues_event_max_datetime": "2022-03-16T14:35:55.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-03-12T21:40:24.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause-LBNL"
],
"max_issues_repo_name": "catalystneuro/nwb-jupyter-widgets",
"max_issues_repo_path": "nwbwidgets/test/test_utils_timeseries.py",
"max_line_length": 87,
"max_stars_count": 35,
"max_stars_repo_head_hexsha": "0d11e5d7b193c53d744b13c6404186ac84f4a5c1",
"max_stars_repo_licenses": [
"BSD-3-Clause-LBNL"
],
"max_stars_repo_name": "NeurodataWithoutBorders/nwb-jupyter-widgets",
"max_stars_repo_path": "nwbwidgets/test/test_utils_timeseries.py",
"max_stars_repo_stars_event_max_datetime": "2021-11-16T11:50:33.000Z",
"max_stars_repo_stars_event_min_datetime": "2019-03-10T23:39:17.000Z",
"num_tokens": 1448,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 4800
} |
"""Test for io.parquet"""
import numpy as np
import pandas as pd
import pyarrow as pa
import deepr as dpr
def test_io_parquet_dataset_read(tmpdir):
"""Test ParquetDataset"""
path = str(tmpdir.join("df.parquet.snappy"))
df = pd.DataFrame(data={"x": [0, 1], "y": [0, 2]})
df.to_parquet(path)
with dpr.io.ParquetDataset(path).open() as ds:
got = ds.read_pandas().to_pandas()
assert df.equals(got)
def test_io_parquet_dataset_schema(tmpdir):
"""Test schema support"""
path = str(tmpdir.join("df.parquet.snappy"))
df = pd.DataFrame(data={"embedding": [np.random.random([5]).astype(np.float32).tolist()]})
schema = pa.schema([("embedding", pa.list_(pa.float32()))])
with dpr.io.ParquetDataset(path).open() as ds:
ds.write_pandas(df, schema=schema)
with dpr.io.ParquetDataset(path).open() as ds:
reloaded = ds.read_pandas().to_pandas()
assert reloaded.iloc[0].embedding.dtype == np.dtype("float32")
| {
"alphanum_fraction": 0.6642710472,
"author": null,
"avg_line_length": 32.4666666667,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "86ac826fd88cd0d4c25716915a0072a40fddf395",
"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": "672772ea3ce9cf391f9f8efc7ae9c9d438957817",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "drohde/deepr",
"max_forks_repo_path": "tests/unit/io/test_io_parquet.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "672772ea3ce9cf391f9f8efc7ae9c9d438957817",
"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": "drohde/deepr",
"max_issues_repo_path": "tests/unit/io/test_io_parquet.py",
"max_line_length": 94,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "672772ea3ce9cf391f9f8efc7ae9c9d438957817",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "drohde/deepr",
"max_stars_repo_path": "tests/unit/io/test_io_parquet.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 268,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 974
} |
#ifndef FILE_ID_SUPPORT_HPP_INCLUDED
#define FILE_ID_SUPPORT_HPP_INCLUDED
#include <clang-c/Index.h>
#include <algorithm>
#include <functional>
#include <boost/functional/hash/hash.hpp>
namespace std {
template <>
struct hash<CXFileUniqueID> {
std::size_t operator() (CXFileUniqueID const& uid) const {
int constexpr nelems = sizeof(uid.data) / sizeof(uid.data[0]);
std::hash<unsigned long long> hasher;
std::size_t h = hasher(uid.data[0]);
for (int i = 1; i < nelems; ++i)
boost::hash_combine(h, hasher(uid.data[i]));
return h;
}
};
template <>
struct equal_to<CXFileUniqueID> {
bool operator() (CXFileUniqueID const& lhs, CXFileUniqueID const& rhs) const {
return std::equal(
std::begin(lhs.data),
std::end(lhs.data),
std::begin(rhs.data));
}
};
}
#endif
| {
"alphanum_fraction": 0.5802728227,
"author": null,
"avg_line_length": 28.0294117647,
"converted": null,
"ext": "hpp",
"file": null,
"hexsha": "a037b007f4e0fcc2c2c72a0ce0a4f8623428c73e",
"include": null,
"lang": "C++",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 10,
"max_forks_repo_forks_event_max_datetime": "2019-07-07T05:32:13.000Z",
"max_forks_repo_forks_event_min_datetime": "2016-04-03T20:48:01.000Z",
"max_forks_repo_head_hexsha": "f4bb576d22108fdfd65bb8f0796cce4aa84349a6",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Oberon00/synth",
"max_forks_repo_path": "src/FileIdSupport.hpp",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "f4bb576d22108fdfd65bb8f0796cce4aa84349a6",
"max_issues_repo_issues_event_max_datetime": "2017-01-17T18:12:09.000Z",
"max_issues_repo_issues_event_min_datetime": "2016-04-04T05:50:12.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "Oberon00/synth",
"max_issues_repo_path": "src/FileIdSupport.hpp",
"max_line_length": 86,
"max_stars_count": 185,
"max_stars_repo_head_hexsha": "f4bb576d22108fdfd65bb8f0796cce4aa84349a6",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Oberon00/synth",
"max_stars_repo_path": "src/FileIdSupport.hpp",
"max_stars_repo_stars_event_max_datetime": "2021-03-22T20:49:03.000Z",
"max_stars_repo_stars_event_min_datetime": "2016-04-03T16:14:39.000Z",
"num_tokens": 220,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 953
} |
#pragma once
#include <fc/fixed_string.hpp>
#include <gamebank/protocol/authority.hpp>
#include <gamebank/protocol/gamebank_operations.hpp>
#include <gamebank/chain/gamebank_object_types.hpp>
#include <gamebank/chain/witness_objects.hpp>
#include <gamebank/chain/shared_authority.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <numeric>
namespace gamebank { namespace chain {
using gamebank::protocol::authority;
class account_object : public object< account_object_type, account_object >
{
account_object() = delete;
public:
template<typename Constructor, typename Allocator>
account_object( Constructor&& c, allocator< Allocator > a )
:json_metadata( a )
{
c(*this);
};
id_type id;
account_name_type name;
public_key_type memo_key;
shared_string json_metadata;
account_name_type proxy;
time_point_sec last_account_update;
time_point_sec created;
bool mined = true;
account_name_type recovery_account;
account_name_type reset_account = GAMEBANK_NULL_ACCOUNT;
time_point_sec last_account_recovery;
uint32_t comment_count = 0;
uint32_t lifetime_vote_count = 0;
uint32_t post_count = 0; //post and comment
bool can_vote = true;
uint16_t voting_power = GAMEBANK_100_PERCENT; ///< current voting power of this account, it falls after every vote
time_point_sec last_vote_time; ///< used to increase the voting power of this account the longer it goes without voting.
asset balance = asset( 0, GBC_SYMBOL ); ///< total liquid shares held by this account
asset savings_balance = asset( 0, GBC_SYMBOL ); ///< total liquid shares held by this account
/**
* GBD Deposits pay interest based upon the interest rate set by witnesses. The purpose of these
* fields is to track the total (time * gbd_balance) that it is held. Then at the appointed time
* interest can be paid using the following equation:
*
* interest = interest_rate * gbd_seconds / seconds_per_year
*
* Every time the gbd_balance is updated the gbd_seconds is also updated. If at least
* GAMEBANK_MIN_COMPOUNDING_INTERVAL_SECONDS has past since gbd_last_interest_payment then
* interest is added to gbd_balance.
*
* @defgroup gbd_data gbd Balance Data
*/
///@{
asset gbd_balance = asset( 0, GBD_SYMBOL ); /// total gbd balance
uint128_t gbd_seconds; ///< total gbd * how long it has been hel
time_point_sec gbd_seconds_last_update; ///< the last time the gbd_seconds was updated
time_point_sec gbd_last_interest_payment; ///< used to pay interest at most once per month
asset savings_gbd_balance = asset( 0, GBD_SYMBOL ); /// total gbd balance
uint128_t savings_gbd_seconds; ///< total gbd * how long it has been hel
time_point_sec savings_gbd_seconds_last_update; ///< the last time the gbd_seconds was updated
time_point_sec savings_gbd_last_interest_payment; ///< used to pay interest at most once per month
uint8_t savings_withdraw_requests = 0;
///@}
asset reward_gbd_balance = asset( 0, GBD_SYMBOL );
asset reward_gbc_balance = asset( 0, GBC_SYMBOL );
asset reward_vesting_balance = asset( 0, GBS_SYMBOL );
asset reward_vesting_gbc = asset( 0, GBC_SYMBOL );
share_type curation_rewards = 0;
share_type posting_rewards = 0;
asset vesting_shares = asset( 0, GBS_SYMBOL ); ///< total vesting shares held by this account, controls its voting power
asset delegated_vesting_shares = asset( 0, GBS_SYMBOL );
asset received_vesting_shares = asset( 0, GBS_SYMBOL );
asset vesting_withdraw_rate = asset( 0, GBS_SYMBOL ); ///< at the time this is updated it can be at most vesting_shares/104
time_point_sec next_vesting_withdrawal = fc::time_point_sec::maximum(); ///< after every withdrawal this is incremented by 1 week
share_type withdrawn = 0; /// Track how many shares have been withdrawn
share_type to_withdraw = 0; /// Might be able to look this up with operation history.
uint16_t withdraw_routes = 0;
fc::array<share_type, GAMEBANK_MAX_PROXY_RECURSION_DEPTH> proxied_vsf_votes;// = std::vector<share_type>( GAMEBANK_MAX_PROXY_RECURSION_DEPTH, 0 ); ///< the total VFS votes proxied to this account
uint16_t witnesses_voted_for = 0;
time_point_sec last_post;
time_point_sec last_root_post = fc::time_point_sec::min();
uint32_t post_bandwidth = 0;
share_type pending_claimed_accounts = 0;
time_point_sec last_crowdfunding_expire = fc::time_point_sec::min();
uint32_t crowdfunding_count = 0;
/// This function should be used only when the account votes for a witness directly
share_type witness_vote_weight()const {
return std::accumulate( proxied_vsf_votes.begin(),
proxied_vsf_votes.end(),
vesting_shares.amount );
}
share_type proxied_vsf_votes_total()const {
return std::accumulate( proxied_vsf_votes.begin(),
proxied_vsf_votes.end(),
share_type() );
}
};
class account_authority_object : public object< account_authority_object_type, account_authority_object >
{
account_authority_object() = delete;
public:
template< typename Constructor, typename Allocator >
account_authority_object( Constructor&& c, allocator< Allocator > a )
: owner( a ), active( a ), posting( a )
{
c( *this );
}
id_type id;
account_name_type account;
shared_authority owner; ///< used for backup control, can set owner or active
shared_authority active; ///< used for all monetary operations, can set active or posting
shared_authority posting; ///< used for voting and posting
time_point_sec last_owner_update;
};
class vesting_delegation_object : public object< vesting_delegation_object_type, vesting_delegation_object >
{
public:
template< typename Constructor, typename Allocator >
vesting_delegation_object( Constructor&& c, allocator< Allocator > a )
{
c( *this );
}
vesting_delegation_object() {}
id_type id;
account_name_type delegator;
account_name_type delegatee;
asset vesting_shares;
time_point_sec min_delegation_time;
};
class vesting_delegation_expiration_object : public object< vesting_delegation_expiration_object_type, vesting_delegation_expiration_object >
{
public:
template< typename Constructor, typename Allocator >
vesting_delegation_expiration_object( Constructor&& c, allocator< Allocator > a )
{
c( *this );
}
vesting_delegation_expiration_object() {}
id_type id;
account_name_type delegator;
asset vesting_shares;
time_point_sec expiration;
};
class owner_authority_history_object : public object< owner_authority_history_object_type, owner_authority_history_object >
{
owner_authority_history_object() = delete;
public:
template< typename Constructor, typename Allocator >
owner_authority_history_object( Constructor&& c, allocator< Allocator > a )
:previous_owner_authority( allocator< shared_authority >( a ) )
{
c( *this );
}
id_type id;
account_name_type account;
shared_authority previous_owner_authority;
time_point_sec last_valid_time;
};
class account_recovery_request_object : public object< account_recovery_request_object_type, account_recovery_request_object >
{
account_recovery_request_object() = delete;
public:
template< typename Constructor, typename Allocator >
account_recovery_request_object( Constructor&& c, allocator< Allocator > a )
:new_owner_authority( allocator< shared_authority >( a ) )
{
c( *this );
}
id_type id;
account_name_type account_to_recover;
shared_authority new_owner_authority;
time_point_sec expires;
};
class change_recovery_account_request_object : public object< change_recovery_account_request_object_type, change_recovery_account_request_object >
{
public:
template< typename Constructor, typename Allocator >
change_recovery_account_request_object( Constructor&& c, allocator< Allocator > a )
{
c( *this );
}
id_type id;
account_name_type account_to_recover;
account_name_type recovery_account;
time_point_sec effective_on;
};
struct by_proxy;
struct by_next_vesting_withdrawal;
/**
* @ingroup object_index
*/
typedef multi_index_container<
account_object,
indexed_by<
ordered_unique< tag< by_id >,
member< account_object, account_id_type, &account_object::id > >,
ordered_unique< tag< by_name >,
member< account_object, account_name_type, &account_object::name > >,
ordered_unique< tag< by_proxy >,
composite_key< account_object,
member< account_object, account_name_type, &account_object::proxy >,
member< account_object, account_name_type, &account_object::name >
> /// composite key by proxy
>,
ordered_unique< tag< by_next_vesting_withdrawal >,
composite_key< account_object,
member< account_object, time_point_sec, &account_object::next_vesting_withdrawal >,
member< account_object, account_name_type, &account_object::name >
> /// composite key by_next_vesting_withdrawal
>
>,
allocator< account_object >
> account_index;
struct by_account;
typedef multi_index_container <
owner_authority_history_object,
indexed_by <
ordered_unique< tag< by_id >,
member< owner_authority_history_object, owner_authority_history_id_type, &owner_authority_history_object::id > >,
ordered_unique< tag< by_account >,
composite_key< owner_authority_history_object,
member< owner_authority_history_object, account_name_type, &owner_authority_history_object::account >,
member< owner_authority_history_object, time_point_sec, &owner_authority_history_object::last_valid_time >,
member< owner_authority_history_object, owner_authority_history_id_type, &owner_authority_history_object::id >
>,
composite_key_compare< std::less< account_name_type >, std::less< time_point_sec >, std::less< owner_authority_history_id_type > >
>
>,
allocator< owner_authority_history_object >
> owner_authority_history_index;
struct by_last_owner_update;
typedef multi_index_container <
account_authority_object,
indexed_by <
ordered_unique< tag< by_id >,
member< account_authority_object, account_authority_id_type, &account_authority_object::id > >,
ordered_unique< tag< by_account >,
composite_key< account_authority_object,
member< account_authority_object, account_name_type, &account_authority_object::account >,
member< account_authority_object, account_authority_id_type, &account_authority_object::id >
>,
composite_key_compare< std::less< account_name_type >, std::less< account_authority_id_type > >
>,
ordered_unique< tag< by_last_owner_update >,
composite_key< account_authority_object,
member< account_authority_object, time_point_sec, &account_authority_object::last_owner_update >,
member< account_authority_object, account_authority_id_type, &account_authority_object::id >
>,
composite_key_compare< std::greater< time_point_sec >, std::less< account_authority_id_type > >
>
>,
allocator< account_authority_object >
> account_authority_index;
struct by_delegation;
struct by_delegation_time;
typedef multi_index_container <
vesting_delegation_object,
indexed_by <
ordered_unique< tag< by_id >,
member< vesting_delegation_object, vesting_delegation_id_type, &vesting_delegation_object::id > >,
ordered_unique< tag< by_delegation_time >,
composite_key< vesting_delegation_object,
member< vesting_delegation_object, account_name_type, &vesting_delegation_object::delegator >,
member< vesting_delegation_object, time_point_sec, &vesting_delegation_object::min_delegation_time >,
member< vesting_delegation_object, vesting_delegation_id_type, &vesting_delegation_object::id >
>,
composite_key_compare< std::less< account_name_type >, std::less< time_point_sec >, std::less< vesting_delegation_id_type > >
>,
ordered_unique< tag< by_delegation >,
composite_key< vesting_delegation_object,
member< vesting_delegation_object, account_name_type, &vesting_delegation_object::delegator >,
member< vesting_delegation_object, account_name_type, &vesting_delegation_object::delegatee >
>,
composite_key_compare< std::less< account_name_type >, std::less< account_name_type > >
>
>,
allocator< vesting_delegation_object >
> vesting_delegation_index;
struct by_expiration;
struct by_account_expiration;
typedef multi_index_container <
vesting_delegation_expiration_object,
indexed_by <
ordered_unique< tag< by_id >,
member< vesting_delegation_expiration_object, vesting_delegation_expiration_id_type, &vesting_delegation_expiration_object::id > >,
ordered_unique< tag< by_expiration >,
composite_key< vesting_delegation_expiration_object,
member< vesting_delegation_expiration_object, time_point_sec, &vesting_delegation_expiration_object::expiration >,
member< vesting_delegation_expiration_object, vesting_delegation_expiration_id_type, &vesting_delegation_expiration_object::id >
>,
composite_key_compare< std::less< time_point_sec >, std::less< vesting_delegation_expiration_id_type > >
>,
ordered_unique< tag< by_account_expiration >,
composite_key< vesting_delegation_expiration_object,
member< vesting_delegation_expiration_object, account_name_type, &vesting_delegation_expiration_object::delegator >,
member< vesting_delegation_expiration_object, time_point_sec, &vesting_delegation_expiration_object::expiration >,
member< vesting_delegation_expiration_object, vesting_delegation_expiration_id_type, &vesting_delegation_expiration_object::id >
>,
composite_key_compare< std::less< account_name_type >, std::less< time_point_sec >, std::less< vesting_delegation_expiration_id_type > >
>
>,
allocator< vesting_delegation_expiration_object >
> vesting_delegation_expiration_index;
struct by_expiration;
typedef multi_index_container <
account_recovery_request_object,
indexed_by <
ordered_unique< tag< by_id >,
member< account_recovery_request_object, account_recovery_request_id_type, &account_recovery_request_object::id > >,
ordered_unique< tag< by_account >,
composite_key< account_recovery_request_object,
member< account_recovery_request_object, account_name_type, &account_recovery_request_object::account_to_recover >
>,
composite_key_compare< std::less< account_name_type > >
>,
ordered_unique< tag< by_expiration >,
composite_key< account_recovery_request_object,
member< account_recovery_request_object, time_point_sec, &account_recovery_request_object::expires >,
member< account_recovery_request_object, account_name_type, &account_recovery_request_object::account_to_recover >
>,
composite_key_compare< std::less< time_point_sec >, std::less< account_name_type > >
>
>,
allocator< account_recovery_request_object >
> account_recovery_request_index;
struct by_effective_date;
typedef multi_index_container <
change_recovery_account_request_object,
indexed_by <
ordered_unique< tag< by_id >,
member< change_recovery_account_request_object, change_recovery_account_request_id_type, &change_recovery_account_request_object::id > >,
ordered_unique< tag< by_account >,
composite_key< change_recovery_account_request_object,
member< change_recovery_account_request_object, account_name_type, &change_recovery_account_request_object::account_to_recover >
>,
composite_key_compare< std::less< account_name_type > >
>,
ordered_unique< tag< by_effective_date >,
composite_key< change_recovery_account_request_object,
member< change_recovery_account_request_object, time_point_sec, &change_recovery_account_request_object::effective_on >,
member< change_recovery_account_request_object, account_name_type, &change_recovery_account_request_object::account_to_recover >
>,
composite_key_compare< std::less< time_point_sec >, std::less< account_name_type > >
>
>,
allocator< change_recovery_account_request_object >
> change_recovery_account_request_index;
} }
FC_REFLECT( gamebank::chain::account_object,
(id)(name)(memo_key)(json_metadata)(proxy)(last_account_update)
(created)(mined)
(recovery_account)(last_account_recovery)(reset_account)
(comment_count)(lifetime_vote_count)(post_count)(can_vote)(voting_power)(last_vote_time)
(balance)
(savings_balance)
(gbd_balance)(gbd_seconds)(gbd_seconds_last_update)(gbd_last_interest_payment)
(savings_gbd_balance)(savings_gbd_seconds)(savings_gbd_seconds_last_update)(savings_gbd_last_interest_payment)(savings_withdraw_requests)
(reward_gbc_balance)(reward_gbd_balance)(reward_vesting_balance)(reward_vesting_gbc)
(vesting_shares)(delegated_vesting_shares)(received_vesting_shares)
(vesting_withdraw_rate)(next_vesting_withdrawal)(withdrawn)(to_withdraw)(withdraw_routes)
(curation_rewards)
(posting_rewards)
(proxied_vsf_votes)(witnesses_voted_for)
(last_post)(last_root_post)(post_bandwidth)
(pending_claimed_accounts)
(last_crowdfunding_expire)(crowdfunding_count)
)
CHAINBASE_SET_INDEX_TYPE( gamebank::chain::account_object, gamebank::chain::account_index )
FC_REFLECT( gamebank::chain::account_authority_object,
(id)(account)(owner)(active)(posting)(last_owner_update)
)
CHAINBASE_SET_INDEX_TYPE( gamebank::chain::account_authority_object, gamebank::chain::account_authority_index )
FC_REFLECT( gamebank::chain::vesting_delegation_object,
(id)(delegator)(delegatee)(vesting_shares)(min_delegation_time) )
CHAINBASE_SET_INDEX_TYPE( gamebank::chain::vesting_delegation_object, gamebank::chain::vesting_delegation_index )
FC_REFLECT( gamebank::chain::vesting_delegation_expiration_object,
(id)(delegator)(vesting_shares)(expiration) )
CHAINBASE_SET_INDEX_TYPE( gamebank::chain::vesting_delegation_expiration_object, gamebank::chain::vesting_delegation_expiration_index )
FC_REFLECT( gamebank::chain::owner_authority_history_object,
(id)(account)(previous_owner_authority)(last_valid_time)
)
CHAINBASE_SET_INDEX_TYPE( gamebank::chain::owner_authority_history_object, gamebank::chain::owner_authority_history_index )
FC_REFLECT( gamebank::chain::account_recovery_request_object,
(id)(account_to_recover)(new_owner_authority)(expires)
)
CHAINBASE_SET_INDEX_TYPE( gamebank::chain::account_recovery_request_object, gamebank::chain::account_recovery_request_index )
FC_REFLECT( gamebank::chain::change_recovery_account_request_object,
(id)(account_to_recover)(recovery_account)(effective_on)
)
CHAINBASE_SET_INDEX_TYPE( gamebank::chain::change_recovery_account_request_object, gamebank::chain::change_recovery_account_request_index )
| {
"alphanum_fraction": 0.6779101145,
"author": null,
"avg_line_length": 46.223655914,
"converted": null,
"ext": "hpp",
"file": null,
"hexsha": "704dac33a6cb734a39332d94a4b13f720239c63a",
"include": null,
"lang": "C++",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2019-01-03T09:48:54.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-08-06T06:50:46.000Z",
"max_forks_repo_head_hexsha": "12a018de6923f4459d597b53abb96a3bfc846114",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "gamebankdev/gamebankcore",
"max_forks_repo_path": "libraries/chain/include/gamebank/chain/account_object.hpp",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "12a018de6923f4459d597b53abb96a3bfc846114",
"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": "gamebankdev/gamebankcore",
"max_issues_repo_path": "libraries/chain/include/gamebank/chain/account_object.hpp",
"max_line_length": 204,
"max_stars_count": 6,
"max_stars_repo_head_hexsha": "12a018de6923f4459d597b53abb96a3bfc846114",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "gamebankdev/gamebankcore",
"max_stars_repo_path": "libraries/chain/include/gamebank/chain/account_object.hpp",
"max_stars_repo_stars_event_max_datetime": "2019-06-23T13:45:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-08-08T06:10:45.000Z",
"num_tokens": 4566,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 21494
} |
import astropy.units as u
import math
from astropy.coordinates import SkyCoord, EarthLocation, get_sun, get_moon, Galactic
from astropy.time import Time
from astropy_healpix import HEALPix
class obs():
def __init__(self,
observatory="LCO",
obs_date="2020-9-1",
max_sun_alt=-17.0*u.deg,
bright_moon_sun_dist=90*u.deg,
max_airmass=1.5,
delta_days=1,
nside=16,
nside_lowres=16,
nest=False,
campaign_mode=False,
dt_min=-8*u.hour,
dt_max=8*u.hour,
bins_per_hour=4,
verbose=True):
self.Flag1m = [False, True, False, False, False, False, False, True, True, True, True, True, True]
self.verbose = verbose
# These are are observational properties.
self.campaign_mode = campaign_mode
self.date = obs_date
self.local_midnight = Time('%s 00:00:00'%(self.date))
self.set_observatory(observatory)
#This is the initialized value. These are updated each day.
self.utc_midnight = self.local_midnight - self.utcoffset
self.sun = get_sun(self.utc_midnight)
self.moon = get_moon(self.utc_midnight)
# These are survey choices
self.max_sun_alt = max_sun_alt # I shoudl really have a unit here... and it should be degrees
self.bright_moon_sun_dist = bright_moon_sun_dist # angular seperation between the moon and sun to be considered bright time.
self.max_airmass = max_airmass
self.min_continuous_window = 0.25 # hours
self.min_exposure = 0.25 # Shortest exposure
# These are simulation properties
self.delta_days = delta_days # offset between simulated days.
self.bins_per_hour = bins_per_hour
#HPT. This should be a dictionary. In principle it can be populated from a list. Note this can be large as it is updated only upon intialization of the observation
self.LVM_HPT = {'M31':SkyCoord.from_name("M31"),
"M33":SkyCoord.from_name("M33"),
"LMC":SkyCoord.from_name("LMC"),
"SMC":SkyCoord.from_name("SMC")}
self.max_airmass = {'M31':1.5,
"M33":1.5,
"LMC":1.75,
"SMC":1.75,
"MW":1.5}
try:
self.mkIFU(n_spaxels=parameter_list['n_spaxels'])
except:
print("Spaxel number not defined or unreadable. Using 1500")
self.mkIFU(n_spaxels=1500)
# Healpix parameters
self.nest=nest
if nest== True:
self.order = "nested"
else:
self.order = "ring"
self.nside = nside
self.npix=12*self.nside**2
self.hp = HEALPix(nside=self.nside, order=self.order, frame=Galactic())
#gives you the number of pixel
self.healpix_skycoords = self.hp.healpix_to_skycoord(range(self.npix)).transform_to(frame='fk5')
# print the resolution of the healpix array in arcminutes
self.angular_resolution = self.hp.pixel_resolution
self.healpix_pixel_area = self.angular_resolution**2
# I should calculate the minimum window based on this angular resolution. I am not.
self.N_IFU_per_pixel = (self.angular_resolution.to(u.arcsec))**2 / self.A_IFU
# Simulation parameters
if u.Unit(dt_min) == u.Unit(1):
#No unit provided, assuming hours.
self.dt_min = dt_min*u.hour
else:
self.dt_min = dt_min.to(u.hour)
if u.Unit(dt_max) == u.Unit(1):
#No unit provided, assuming hours.
self.dt_max = dt_max*u.hour
else:
self.dt_max = dt_max.to(u.hour)
def set_observatory(self, observatory, reset_date=True):
if observatory == "APO":
self.location = EarthLocation.of_site('Apache Point Observatory')
self.utcoffset = -7.0*u.hour
self.observatory = observatory
elif observatory == "LCO":
self.location = EarthLocation.of_site('Las Campanas Observatory')
self.utcoffset = -5.0*u.hour
self.observatory = observatory
else:
Exception("Observatory location not known")
if reset_date == True:
self.restart_date()
def restart_date(self):
self.local_midnight = Time('%s 00:00:00'%(self.date))
self.utc_midnight = self.local_midnight - self.utcoffset
def next_day(self):
self.local_midnight = self.local_midnight + self.delta_days*u.day
self.utc_midnight = self.local_midnight - self.utcoffset
self.sun = get_sun(self.utc_midnight)
self.moon = get_moon(self.utc_midnight)
if self.verbose == True: print(self.local_midnight)
def mkIFU(self, n_spaxels=1500, tel_diam=0.16*u.m):
self.tel_diam = tel_diam
self.n_spaxels = n_spaxels
self.r_spaxel = (37/2.) * u.arcsec * (0.168*u.m/tel_diam)
self.A_spaxel = 2*math.pi * self.r_spaxel**2
self.A_IFU = self.n_spaxels*self.A_spaxel
self.r_IFU = self.A_IFU**0.5
return({""})
| {
"alphanum_fraction": 0.5962044344,
"author": null,
"avg_line_length": 38.2877697842,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "4a3eba6c047c0d067184460fb279707e2b3558dc",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2019-03-18T17:49:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2019-03-18T17:49:33.000Z",
"max_forks_repo_head_hexsha": "6aa6262042cbd7a212d82820984d7055f1dcc4dc",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "sdss/lvmsurveysim",
"max_forks_repo_path": "lvmsurveysim/utils/obs_class.py",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "6aa6262042cbd7a212d82820984d7055f1dcc4dc",
"max_issues_repo_issues_event_max_datetime": "2021-09-01T15:20:39.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-03-15T04:25:32.000Z",
"max_issues_repo_licenses": [
"BSD-3-Clause"
],
"max_issues_repo_name": "sdss/lvmsurveysim",
"max_issues_repo_path": "lvmsurveysim/utils/obs_class.py",
"max_line_length": 172,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "6aa6262042cbd7a212d82820984d7055f1dcc4dc",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "sdss/lvmsurveysim",
"max_stars_repo_path": "lvmsurveysim/utils/obs_class.py",
"max_stars_repo_stars_event_max_datetime": "2021-09-02T16:17:44.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-01-28T16:45:05.000Z",
"num_tokens": 1325,
"path": null,
"reason": "import astropy,from astropy",
"repo": null,
"save_path": null,
"sha": null,
"size": 5322
} |
%!TEX root = ../../thesis.tex
\section{Browser support}
%% \section{Development of HTML Editing APIs}
With the release of Internet Explorer 5.5 and the introduction of editing capabilities, Microsoft released a short documentation\footnote{\url{https://msdn.microsoft.com/en-us/library/ms537837(VS.85).aspx}, last checked on 07/10/2015}, containing the attributes' possible values and element restrictions along with two code examples. Although a clear purpose has not been stated, the code examples demonstrated how to implement rich-text input fields with it. Mark Pilgrim, author of the ''Dive into'' book series and contributor to the the Web Hypertext Application Technology Working Group (WHATWG), also states that the API's first use case has been for rich-text editing\footnote{\url{https://blog.whatwg.org/the-road-to-html-5-contenteditable}, last checked on 07/10/2015}.
%% With the release of Internet Explorer 5.5 and the introduction of editing capabilities, Microsoft released a sparse documentation\footnote{\url{https://msdn.microsoft.com/en-us/library/ms537837(VS.85).aspx}, last checked on 07/10/2015} describing only the availability and the before-mentioned element restrictions of these attributes.
%% According to Mark Pilgrim, author of the ''Dive into'' book series and contributor to the the Web Hypertext Application Technology Working Group (WHATWG),, but its first use case has been for rich-text editing\footnote{\url{https://blog.whatwg.org/the-road-to-html-5-contenteditable}, last checked on 07/10/2015}.
% It is notable, that the available command identifiers mostly include text-editing (or related) commands, but not exclusively. Other commands include navigating to other URLs or controlling the browser's cache.
In March 2003, the Mozilla Foundation introduced an implementation of Microsoft's designMode, named Midas, for their release of Mozilla 1.3. Mozilla already named this ''rich-text editing support'' on the Mozilla Developer Network (MDN)\footnote{\url{https://developer.mozilla.org/en/docs/Rich-Text\_Editing\_in\_Mozilla}, last checked on 07/10/2015}. In June 2008, Mozilla added support for contentEditable IDL and contenteditable content attributes with Firefox 3.
Mozilla's editing API mostly resembles the API implemented for Internet Explorer, however, to this present day, there are still differences (compare\cite{ad}\cite{am}). This includes the available command identifiers\cite{am}\cite{ad} as well as the markup generated by invoking commands\cite{ai}.
%\footnote{\url{https://msdn.microsoft.com/en-us/library/hh772123(v=vs.85).aspx}, last checked on 07/10/2015}
%\footnote{\url{https://developer.mozilla.org/en-US/docs/Midas}, last checked on 07/10/2015}
%\footnote{\url{https://developer.mozilla.org/en-US/docs/Midas}, last checked on 07/10/2015}
%\footnote{\url{https://msdn.microsoft.com/en-us/library/ms533049(v=vs.85).aspx}, last checked on 07/10/2015}
%\footnote{\url{https://developer.mozilla.org/en/docs/Rich-Text\_Editing\_in\_Mozilla#Internet\_Explorer\_Differences}, last checked on 07/10/2015}
%% Mozilla's command identifiers are restricted to text-editing command, showing the clear purpose of this API.
%% This may show, that even though rich-text editing was its first use case and Mozilla implemented it naming it that, this editing API was not originally intended to be used as such.
In June 2006, Opera Software releases Opera 9\cite{ap}, providing full support for contentEditable and designMode\cite{aq}, followed by Apple in March 2008\cite{ar} providing full support Safari 3.1\cite{caniuse_contenteditable}. MDN lists full support in Google Chrome since version 4\cite{as}, released in January 2010\cite{at}.
%\footnote{\url{http://www.opera.com/docs/changelogs/windows/}, last checked on 07/10/2015}
%\footnote{\url{http://www.opera.com/docs/changelogs/windows/900/}, last checked on 07/10/2015}
%\footnote{\url{https://www.apple.com/pr/library/2008/03/18Apple-Releases-Safari-3-1.html}, last checked on 07/10/2015}
%\footnote{\url{http://caniuse.com/#feat=contenteditable}, last checked on 07/10/2015}
% \footnote{\url{https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content\_Editable}, last checked on 07/10/2015}
%\footnote{\url{http://googlechromereleases.blogspot.de/2010/01/stable-channel-update\_25.html}, last checked on 07/10/2015}
%In March 2008, Apple released Safari 3.1\footnote{\url{https://www.apple.com/pr/library/2008/03/18Apple-Releases-Safari-3-1.html}, last checked on 07/10/2015} including full support for contentEditable and designMode\footnote{\url{http://caniuse.com/#feat=contenteditable}, last checked on 07/10/2015}, followed by Opera Software in June 2006\footnote{\url{http://www.opera.com/docs/changelogs/windows/}, last checked on 07/10/2015} providing full support in Opera 9\footnote{\url{http://www.opera.com/docs/changelogs/windows/900/}, last checked on 07/10/2015}. MDN lists full support in Google Chrome since version 4\footnote{\url{https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Content\_Editable}, last checked on 07/10/2015}, released in January 2010\footnote{\url{http://googlechromereleases.blogspot.de/2010/01/stable-channel-update\_25.html}, last checked on 07/10/2015}.
Starting in November 2004, WHATWG members have started actively discussing to incorporate these editing APIs in the HTML5 standard. Through reverse engineering, the WHATWG developed a specification based on Microsoft's implementation\cite{ah} and finally decided to include it in HTML5. With W3C's coorporation and the split in 2011, similar editing APIs based on this work are now included in W3C's HTML5 Standard\cite{aw} and WHATWG's HTML Standard\cite{av}.
%\footnote{\url{https://blog.whatwg.org/the-road-to-html-5-contenteditable}, last checked on 07/15/2015}
%\footnote{\url{http://www.w3.org/TR/html5/editing.html}, last checked on 07/15/2015}
% \footnote{\url{https://html.spec.whatwg.org/multipage/interaction.html#editing-2}, last checked on 07/15/2015} | {
"alphanum_fraction": 0.783954727,
"author": null,
"avg_line_length": 136.5454545455,
"converted": null,
"ext": "tex",
"file": null,
"hexsha": "6b735b5e08179a280d1494b9d4f994c44b67eedd",
"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": "8d641664b5325512474ab662417c555ff025ff41",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "LukasBombach/old-type-js",
"max_forks_repo_path": "Report/janstyle/content/browser/browser_support.tex",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8d641664b5325512474ab662417c555ff025ff41",
"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": "LukasBombach/old-type-js",
"max_issues_repo_path": "Report/janstyle/content/browser/browser_support.tex",
"max_line_length": 886,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "8d641664b5325512474ab662417c555ff025ff41",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "LukasBombach/old-type-js",
"max_stars_repo_path": "Report/janstyle/content/browser/browser_support.tex",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 1565,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 6008
} |
import numpy as np
from collections import Counter
from gridifier import Gridifier
class Balancer():
@staticmethod
def hypercube_balance(snapshots, bins):
gridified_snapshots = gridify_list_entries(snapshots, bins)
tuple_gridified_snapshots = list(map(tuple, gridified_snapshots))
return get_balanced_weights_from_list(tuple_gridified_snapshots)
@staticmethod
def multidim_balance(snapshots, bins):
gridified_snapshots = gridify_list_entries(snapshots, bins)
gridified_columns = np.transpose(gridified_snapshots)
md_balanced_weights = np.ones(len(snapshots))
for column in gridified_columns:
update_balanced_weights_based_on_column(
md_balanced_weights, column)
md_balanced_weights /= np.mean(md_balanced_weights)
return md_balanced_weights
@staticmethod
def pB_balance(pBs, bins):
gridified_pBs = gridify_list_entries(pBs, bins)
return get_balanced_weights_from_list(gridified_pBs)
def gridify_list_entries(lst, bins):
gridifier = Gridifier(lst, bins)
return gridifier.gridify_snapshots(lst)
def update_balanced_weights_based_on_column(
balanced_weights, column):
balanced_weights *= get_balanced_weights_from_list(column)
def get_balanced_weights_from_list(list_in_need_of_weights):
return get_weights_from_balanced_counter(
get_balanced_counter(list_in_need_of_weights),
list_in_need_of_weights)
def get_balanced_counter(list_in_need_of_weights):
"""Balance weights such that all weight together sum to list_len
and the weights for each key sum together to list_len / counter_len
"""
list_len = len(list_in_need_of_weights)
counter = Counter(list_in_need_of_weights)
counter_len = len(counter)
return {key: list_len / (label * counter_len)
for key, label in counter.items()}
def get_weights_from_balanced_counter(counter, list_in_need_of_weights):
return np.array([counter[i] for i in list_in_need_of_weights])
| {
"alphanum_fraction": 0.753411306,
"author": null,
"avg_line_length": 34.7796610169,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "c14e0680f59804cfd414c285fe1f4eb3b75ee474",
"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": "88a467e4500bc9ab69834209f4eaec9f2d0d7a61",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "MFrassek/CommittorEAE",
"max_forks_repo_path": "NucleationModel/balancer.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "88a467e4500bc9ab69834209f4eaec9f2d0d7a61",
"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": "MFrassek/CommittorEAE",
"max_issues_repo_path": "NucleationModel/balancer.py",
"max_line_length": 73,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "88a467e4500bc9ab69834209f4eaec9f2d0d7a61",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "MFrassek/CommittorEAE",
"max_stars_repo_path": "NucleationModel/balancer.py",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 448,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 2052
} |
Not that I think youre wrong, but do you have a way of knowing that David Greenwald is responsible for CAROLE? Users/PhilipNeustrom
20080607 12:05:28 nbsp Is this Robin Souza? Users/JamesSchwab
20080608 21:14:53 nbsp No it is not. Users/StephenSouza
| {
"alphanum_fraction": 0.7913385827,
"author": null,
"avg_line_length": 36.2857142857,
"converted": null,
"ext": "f",
"file": null,
"hexsha": "c12fe5b786acb7da7d1afd29386f9319d3b4c8fb",
"include": null,
"lang": "FORTRAN",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "voflo/Search",
"max_forks_repo_path": "lab/davisWiki/RobinS.f",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "voflo/Search",
"max_issues_repo_path": "lab/davisWiki/RobinS.f",
"max_line_length": 132,
"max_stars_count": null,
"max_stars_repo_head_hexsha": "55088b2fe6a9d6c90590f090542e0c0e3c188c7d",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "voflo/Search",
"max_stars_repo_path": "lab/davisWiki/RobinS.f",
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": 80,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 254
} |
#=
[eegplotter.jl]
Version = 0.022
Author = "William Herrera"
Copyright = "Copyright 2018 William Herrera"
Created = "12 Jan 2018"
Purpose = "EEG file routines viewer example"
=#
using EDFPlus
using DSP
using Plots
import FileIO
pyplot()
using PyPlot
linspace(start, stop, len) = LinRange{Float64}(start, stop, len)
function averagereference(edfh, channels=edfh.mapped_signals)
data = EDFPlus.signaldata(edfh)
recs = edfh.datarecords
siglen = maximum(x->x.smp_per_record, edfh.signalparam)
avgref = zeros(siglen*recs)
spans = map(chan->EDFPlus.signalindices(edfh, chan), channels)
chancount = length(channels)
for recnum in 1:size(data)[1], channum in 1:chancount
span = spans[channum]
addlen = span[2] - span[1]
addstart = (recnum-1)*siglen+1
avgref[addstart:addstart+addlen] = data[recnum, span[1]:span[2]][:] ./ chancount
end
avgref
end
function eegpages(edfh; channels=collect(3:8), secsperpage=15.0)
epages = Array{Array{Array{Float64,1},1},1}([])
fs = samplerate(edfh, channels[1])
starts = linspace(0.0, edfh.file_duration, div(edfh.file_duration,secsperpage))
for t1 in starts[1:end-1]
t2 = t1 + secsperpage
epage = multichanneltimesegment(edfh, channels, t1, t2, true)
for i in 1:size(epage)[1]
epage[i] = highpassfilter(epage[i], fs, 1.5)
epage[i] = lowpassfilter(epage[i], fs, 24.0)
end
push!(epages, epage)
end
avgref = averagereference(edfh, collect(1:8))
spectpage = spectrogram(avgref)
spectsegment = Plots.contourf(spectpage.time, spectpage.freq, log.(spectpage.power),
xaxis=false, yaxis=false, colorbar=false)
imgname = "tmp.png"
Plots.savefig(spectsegment, imgname)
timepoints = linspace(0.0, secsperpage, length(epages[1][1]))
channelnames = [trim(edfh.signalparam[chan].label) for chan in channels]
epages, timepoints, channelnames, imgname, edfh.path
end
function plotpage(timepoints, page, ylabels, imgname, title)
nchannels = size(page)[1]
plt = Plots.plot(timepoints, page, layout=(nchannels+1,1),
xticks=collect(timepoints[1]:1:timepoints[end]),
yticks=false, legend=false, linetype=:line)
for i in 1:nchannels
Plots.plot!(yaxis=true, xaxis=false, subplot=i, tight_layout=true, ylabel = ylabels[i])
end
plt[nchannels][:xaxis][:showaxis] = true
Plots.plot!(title = title, subplot=1, size=dims)
img = FileIO.load(imgname)
plot!(img, aspect_ratio="auto",subplot=nchannels+1)
plt
end
function vieweeg(filename)
currentpage = 1
maxpage = 1
channelcount = 8
needupdate = false
function onclick(event)
println(event)
println(event[:x], " ", event[:y], " ", event[:canvas][:get_width_height]())
x = event[:x]
y = event[:y]
(width, height) = event[:canvas][:get_width_height]()
global dims = (width, height)
yfrac = div(height, channelcount+2)
ybottom = div(yfrac, 2)
ytop = yfrac + ybottom
if y < ytop && y > ybottom && x < width && x > 0
tmp = Int(round(x * maxpage / width))
oldpage = currentpage
currentpage = (tmp < 1) ? 1 : (tmp > maxpage ? maxpage : tmp)
if oldpage != currentpage
needupdate = true
end
end
end
function onkeypress(event)
println(event)
println(event[:key])
(width, height) = event[:canvas][:get_width_height]()
global dims = (width, height)
tmp = currentpage
if event[:key] in ("up", "right", "pageup", "+")
tmp = currentpage + 1
elseif event[:key] in ("down", "left", "pagedown", "-")
tmp = currentpage - 1
else
return
end
oldpage = currentpage
currentpage = (tmp < 1) ? 1 : (tmp > maxpage ? maxpage : tmp)
if oldpage != currentpage
needupdate = true
end
end
edfh = loadfile(filename)
epages, timepoints, channelnames, imgname, title = eegpages(edfh)
maxpage = length(epages)
plt = plotpage(timepoints, epages[2], channelnames, imgname, title)
display(plt)
fig = PyPlot.gcf()
fig[:canvas][:mpl_connect]("button_press_event", onclick)
fig[:canvas][:mpl_connect]("key_press_event", onkeypress)
println("entering loop...")
while true
yield()
if needupdate
needupdate = false
newpage = epages[currentpage]
xdelta = (currentpage - 1) * timepoints[end]
mins, secs = Int.(floor.(divrem(xdelta, 60)))
newtitle = replace(title, r".+\/([^\/]+)$" => s"\1")
newtitle *= " (Page $currentpage of $maxpage: at $mins minutes, $secs seconds)"
display(plotpage(timepoints .+ xdelta, newpage, channelnames, imgname, newtitle))
println("updated")
yield()
end
sleep(0.1)
end
end
global dims = (1200, 400)
const filename = "../test/EDFPlusTestFile.edf"
vieweeg(filename)
| {
"alphanum_fraction": 0.6066848037,
"author": null,
"avg_line_length": 33.8552631579,
"converted": null,
"ext": "jl",
"file": null,
"hexsha": "4b5360a92a6ab2c3cb51389f3c2158a1c3e77b1e",
"include": null,
"lang": "Julia",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 4,
"max_forks_repo_forks_event_max_datetime": "2021-12-19T12:22:46.000Z",
"max_forks_repo_forks_event_min_datetime": "2020-02-08T11:12:46.000Z",
"max_forks_repo_head_hexsha": "fa8f88e1782fe914cc221770e084165c87cdfd86",
"max_forks_repo_licenses": [
"BSD-2-Clause"
],
"max_forks_repo_name": "wherrera10/EDFPlus",
"max_forks_repo_path": "example/eegplotter.jl",
"max_issues_count": 2,
"max_issues_repo_head_hexsha": "fa8f88e1782fe914cc221770e084165c87cdfd86",
"max_issues_repo_issues_event_max_datetime": "2021-06-28T17:25:46.000Z",
"max_issues_repo_issues_event_min_datetime": "2020-02-08T15:11:54.000Z",
"max_issues_repo_licenses": [
"BSD-2-Clause"
],
"max_issues_repo_name": "wherrera10/EDFPlus",
"max_issues_repo_path": "example/eegplotter.jl",
"max_line_length": 95,
"max_stars_count": 3,
"max_stars_repo_head_hexsha": "fa8f88e1782fe914cc221770e084165c87cdfd86",
"max_stars_repo_licenses": [
"BSD-2-Clause"
],
"max_stars_repo_name": "wherrera10/julia-EDF",
"max_stars_repo_path": "example/eegplotter.jl",
"max_stars_repo_stars_event_max_datetime": "2021-12-19T12:22:51.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-09-24T02:16:05.000Z",
"num_tokens": 1474,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 5146
} |
"""Data and Channel Location Equivalence Tests"""
from __future__ import print_function
# Author: Teon Brooks <teon.brooks@gmail.com>
#
# License: BSD (3-clause)
import os.path as op
import inspect
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_array_equal
from nose.tools import assert_equal, assert_raises, assert_true
import scipy.io
from mne import pick_types, concatenate_raws, Epochs, read_events
from mne.utils import _TempDir, run_tests_if_main
from mne.io import Raw
from mne.io import read_raw_kit, read_epochs_kit
from mne.io.kit.coreg import read_sns
from mne.io.tests.test_raw import _test_concat
FILE = inspect.getfile(inspect.currentframe())
parent_dir = op.dirname(op.abspath(FILE))
data_dir = op.join(parent_dir, 'data')
sqd_path = op.join(data_dir, 'test.sqd')
epochs_path = op.join(data_dir, 'test-epoch.raw')
events_path = op.join(data_dir, 'test-eve.txt')
mrk_path = op.join(data_dir, 'test_mrk.sqd')
mrk2_path = op.join(data_dir, 'test_mrk_pre.sqd')
mrk3_path = op.join(data_dir, 'test_mrk_post.sqd')
elp_path = op.join(data_dir, 'test_elp.txt')
hsp_path = op.join(data_dir, 'test_hsp.txt')
def test_concat():
"""Test EDF concatenation
"""
_test_concat(read_raw_kit, sqd_path)
def test_data():
"""Test reading raw kit files
"""
assert_raises(TypeError, read_raw_kit, epochs_path)
assert_raises(TypeError, read_epochs_kit, sqd_path)
assert_raises(ValueError, read_raw_kit, sqd_path, mrk_path, elp_path)
assert_raises(ValueError, read_raw_kit, sqd_path, None, None, None,
list(range(200, 190, -1)))
assert_raises(ValueError, read_raw_kit, sqd_path, None, None, None,
list(range(167, 159, -1)), '*', 1, True)
# check functionality
_ = read_raw_kit(sqd_path, [mrk2_path, mrk3_path], elp_path,
hsp_path)
raw_py = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path,
stim=list(range(167, 159, -1)), slope='+',
stimthresh=1, preload=True)
assert_true('RawKIT' in repr(raw_py))
# Binary file only stores the sensor channels
py_picks = pick_types(raw_py.info, exclude='bads')
raw_bin = op.join(data_dir, 'test_bin_raw.fif')
raw_bin = Raw(raw_bin, preload=True)
bin_picks = pick_types(raw_bin.info, stim=True, exclude='bads')
data_bin, _ = raw_bin[bin_picks]
data_py, _ = raw_py[py_picks]
# this .mat was generated using the Yokogawa MEG Reader
data_Ykgw = op.join(data_dir, 'test_Ykgw.mat')
data_Ykgw = scipy.io.loadmat(data_Ykgw)['data']
data_Ykgw = data_Ykgw[py_picks]
assert_array_almost_equal(data_py, data_Ykgw)
py_picks = pick_types(raw_py.info, stim=True, ref_meg=False,
exclude='bads')
data_py, _ = raw_py[py_picks]
assert_array_almost_equal(data_py, data_bin)
# Make sure concatenation works
raw_concat = concatenate_raws([raw_py.copy(), raw_py])
assert_equal(raw_concat.n_times, 2 * raw_py.n_times)
def test_epochs():
raw = read_raw_kit(sqd_path, stim=None)
events = read_events(events_path)
raw_epochs = Epochs(raw, events, None, tmin=0, tmax=.099, baseline=None)
data1 = raw_epochs.get_data()
epochs = read_epochs_kit(epochs_path, events_path)
data11 = epochs.get_data()
assert_array_equal(data1, data11)
def test_read_segment():
"""Test writing raw kit files when preload is False
"""
tempdir = _TempDir()
raw1 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<',
preload=False)
raw1_file = op.join(tempdir, 'test1-raw.fif')
raw1.save(raw1_file, buffer_size_sec=.1, overwrite=True)
raw2 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<',
preload=True)
raw2_file = op.join(tempdir, 'test2-raw.fif')
raw2.save(raw2_file, buffer_size_sec=.1, overwrite=True)
data1, times1 = raw1[0, 0:1]
raw1 = Raw(raw1_file, preload=True)
raw2 = Raw(raw2_file, preload=True)
assert_array_equal(raw1._data, raw2._data)
data2, times2 = raw2[0, 0:1]
assert_array_almost_equal(data1, data2)
assert_array_almost_equal(times1, times2)
raw3 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<',
preload=True)
assert_array_almost_equal(raw1._data, raw3._data)
raw4 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<',
preload=False)
raw4.load_data()
buffer_fname = op.join(tempdir, 'buffer')
assert_array_almost_equal(raw1._data, raw4._data)
raw5 = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<',
preload=buffer_fname)
assert_array_almost_equal(raw1._data, raw5._data)
def test_ch_loc():
"""Test raw kit loc
"""
raw_py = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<')
raw_bin = Raw(op.join(data_dir, 'test_bin_raw.fif'))
ch_py = raw_py._raw_extras[0]['sensor_locs'][:, :5]
# ch locs stored as m, not mm
ch_py[:, :3] *= 1e3
ch_sns = read_sns(op.join(data_dir, 'sns.txt'))
assert_array_almost_equal(ch_py, ch_sns, 2)
assert_array_almost_equal(raw_py.info['dev_head_t']['trans'],
raw_bin.info['dev_head_t']['trans'], 4)
for py_ch, bin_ch in zip(raw_py.info['chs'], raw_bin.info['chs']):
if bin_ch['ch_name'].startswith('MEG'):
# the stored ch locs have more precision than the sns.txt
assert_array_almost_equal(py_ch['loc'], bin_ch['loc'], decimal=2)
# test when more than one marker file provided
mrks = [mrk_path, mrk2_path, mrk3_path]
read_raw_kit(sqd_path, mrks, elp_path, hsp_path, preload=False)
def test_stim_ch():
"""Test raw kit stim ch
"""
raw = read_raw_kit(sqd_path, mrk_path, elp_path, hsp_path, stim='<',
slope='+', preload=True)
stim_pick = pick_types(raw.info, meg=False, ref_meg=False,
stim=True, exclude='bads')
stim1, _ = raw[stim_pick]
stim2 = np.array(raw.read_stim_ch(), ndmin=2)
assert_array_equal(stim1, stim2)
run_tests_if_main()
| {
"alphanum_fraction": 0.6778621024,
"author": null,
"avg_line_length": 37.762195122,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "72b3028dbcf208cde460fa47dff4fe626345a22a",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 2,
"max_forks_repo_forks_event_max_datetime": "2018-07-16T23:39:02.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-04-02T06:45:11.000Z",
"max_forks_repo_head_hexsha": "ee45bee6f96cdb6d91184abc16f41bba1546c943",
"max_forks_repo_licenses": [
"BSD-3-Clause"
],
"max_forks_repo_name": "rajegannathan/grasp-lift-eeg-cat-dog-solution-updated",
"max_forks_repo_path": "python-packages/mne-python-0.10/mne/io/kit/tests/test_kit.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "ee45bee6f96cdb6d91184abc16f41bba1546c943",
"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": "rajegannathan/grasp-lift-eeg-cat-dog-solution-updated",
"max_issues_repo_path": "python-packages/mne-python-0.10/mne/io/kit/tests/test_kit.py",
"max_line_length": 77,
"max_stars_count": 2,
"max_stars_repo_head_hexsha": "ee45bee6f96cdb6d91184abc16f41bba1546c943",
"max_stars_repo_licenses": [
"BSD-3-Clause"
],
"max_stars_repo_name": "rajegannathan/grasp-lift-eeg-cat-dog-solution-updated",
"max_stars_repo_path": "python-packages/mne-python-0.10/mne/io/kit/tests/test_kit.py",
"max_stars_repo_stars_event_max_datetime": "2018-07-16T23:39:00.000Z",
"max_stars_repo_stars_event_min_datetime": "2017-08-13T14:09:32.000Z",
"num_tokens": 1746,
"path": null,
"reason": "import numpy,from numpy,import scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 6193
} |
[STATEMENT]
lemma (in infinite_coin_toss_space) bernoulli_stream_pref_prob_neq_zero:
fixes x
assumes "0 < p"
and "p < 1"
shows "emeasure M {w\<in> space M. (stake n w = stake n x)} \<noteq> 0"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0
[PROOF STEP]
proof (induct n)
[PROOF STATE]
proof (state)
goal (2 subgoals):
1. emeasure M {w \<in> space M. stake 0 w = stake 0 x} \<noteq> 0
2. \<And>n. emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0 \<Longrightarrow> emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
[PROOF STEP]
case 0
[PROOF STATE]
proof (state)
this:
goal (2 subgoals):
1. emeasure M {w \<in> space M. stake 0 w = stake 0 x} \<noteq> 0
2. \<And>n. emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0 \<Longrightarrow> emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
[PROOF STEP]
hence "emeasure M {w\<in> space M. (stake 0 w = stake 0 x)} = 1"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. emeasure M {w \<in> space M. stake 0 w = stake 0 x} = 1
[PROOF STEP]
using bernoulli_stream_npref_prob[of M p x]
bernoulli
[PROOF STATE]
proof (prove)
using this:
M = bernoulli_stream p \<Longrightarrow> emeasure M {w \<in> space M. stake 0 w = stake 0 x} = 1
M = bernoulli_stream p
goal (1 subgoal):
1. emeasure M {w \<in> space M. stake 0 w = stake 0 x} = 1
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
emeasure M {w \<in> space M. stake 0 w = stake 0 x} = 1
goal (2 subgoals):
1. emeasure M {w \<in> space M. stake 0 w = stake 0 x} \<noteq> 0
2. \<And>n. emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0 \<Longrightarrow> emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
emeasure M {w \<in> space M. stake 0 w = stake 0 x} = 1
goal (1 subgoal):
1. emeasure M {w \<in> space M. stake 0 w = stake 0 x} \<noteq> 0
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
emeasure M {w \<in> space M. stake 0 w = stake 0 x} \<noteq> 0
goal (1 subgoal):
1. \<And>n. emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0 \<Longrightarrow> emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
[PROOF STEP]
next
[PROOF STATE]
proof (state)
goal (1 subgoal):
1. \<And>n. emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0 \<Longrightarrow> emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
[PROOF STEP]
case (Suc n)
[PROOF STATE]
proof (state)
this:
emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0
goal (1 subgoal):
1. \<And>n. emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0 \<Longrightarrow> emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
[PROOF STEP]
have "emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} =
(emeasure M {w\<in> space M. (stake n w = stake n x)} * prob_component p x n)"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} = emeasure M {w \<in> space M. stake n w = stake n x} * ennreal (prob_component p x n)
[PROOF STEP]
using bernoulli_stream_element_prob_rec
bernoulli assms
[PROOF STATE]
proof (prove)
using this:
\<lbrakk>?M = bernoulli_stream ?p; 0 \<le> ?p; ?p \<le> 1\<rbrakk> \<Longrightarrow> emeasure ?M {w \<in> space ?M. stake (Suc ?n) w = stake (Suc ?n) ?x} = emeasure ?M {w \<in> space ?M. stake ?n w = stake ?n ?x} * ennreal (prob_component ?p ?x ?n)
M = bernoulli_stream p
0 < p
p < 1
goal (1 subgoal):
1. emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} = emeasure M {w \<in> space M. stake n w = stake n x} * ennreal (prob_component p x n)
[PROOF STEP]
by simp
[PROOF STATE]
proof (state)
this:
emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} = emeasure M {w \<in> space M. stake n w = stake n x} * ennreal (prob_component p x n)
goal (1 subgoal):
1. \<And>n. emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0 \<Longrightarrow> emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
[PROOF STEP]
thus ?case
[PROOF STATE]
proof (prove)
using this:
emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} = emeasure M {w \<in> space M. stake n w = stake n x} * ennreal (prob_component p x n)
goal (1 subgoal):
1. emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
[PROOF STEP]
using Suc
[PROOF STATE]
proof (prove)
using this:
emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} = emeasure M {w \<in> space M. stake n w = stake n x} * ennreal (prob_component p x n)
emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0
goal (1 subgoal):
1. emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
[PROOF STEP]
using assms p_gt_0 p_lt_1 prob_component_def
[PROOF STATE]
proof (prove)
using this:
emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} = emeasure M {w \<in> space M. stake n w = stake n x} * ennreal (prob_component p x n)
emeasure M {w \<in> space M. stake n w = stake n x} \<noteq> 0
0 < p
p < 1
0 \<le> p
p \<le> 1
prob_component ?p ?w ?n = (if ?w !! ?n then ?p else 1 - ?p)
goal (1 subgoal):
1. emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
[PROOF STEP]
by auto
[PROOF STATE]
proof (state)
this:
emeasure M {w \<in> space M. stake (Suc n) w = stake (Suc n) x} \<noteq> 0
goal:
No subgoals!
[PROOF STEP]
qed | {
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": "DiscretePricing_Infinite_Coin_Toss_Space",
"hexsha": null,
"include": null,
"lang": null,
"length": 17,
"llama_tokens": 2550,
"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 math import factorial
import numpy as np
import scipy.optimize
def get_airfoil_coord(wu, wl, yute, ylte, x=None):
# N1 and N2 parameters (N1 = 0.5 and N2 = 1 for airfoil shape)
N1 = 0.5
N2 = 1
# Create x coordinate
if x is None: # if x_arr is not provided
N = 161 #TODO: hard coded for now
# x is listed in XFoil format, i.e. counter-clockwise starting from upper trailing edge, wrapping around leading edge and ending at lower trailing edge
x = 0.5 * (1 + np.cos(np.linspace(0, 2*np.pi, N)))
j_le = np.argmin(x)
xu = x[:j_le] # upper surface x-coordinates
xl = x[j_le:] # lower surface x-coordinates
yu = eval_shape_fcn(wu, xu, N1, N2, yute) # upper surface y-coordinates
yl = eval_shape_fcn(wl, xl, N1, N2, ylte) # lower surface y-coordinates
y = np.concatenate([yu, yl])
return np.array([x, y]).T
def eval_shape_fcn(w, x, N1, N2, yte):
"""
compute class and shape function
:param w:
:param x:
:param N1:
:param N2:
:param yte: trailing edge y coordinate
:return:
"""
C = x**N1 * (1-x)**N2
n = len(w) - 1 # degree of Bernstein polynomials
S = np.zeros_like(x)
for j in range(0, n+1):
K = factorial(n)/(factorial(j)*(factorial(n-j)))
S += w[j]*K*x**j * ((1-x)**(n-j))
return C * S + x * yte
def list_to_kulfan_params(var):
nw = len(var) // 2
wu = var[0:nw]
wl = var[nw:(2*nw)]
assert len(var) == (2 * nw)
return wu, wl
def obj_fcn_airfoil_inversion(var, xy_ref):
"""
objective function to minimize: discrepancy between reference coordinates and parametrized airfoil coordinates
:param var: variable to optimize
:param xy_ref: n-by-2 array of reference coordinates following XFoil format (CCW)
:return:
"""
wu, wl = list_to_kulfan_params(var)
yute = xy_ref[0, 1]
ylte = xy_ref[-1, 1]
xy_kulfan = get_airfoil_coord(wu, wl, yute, ylte, x=xy_ref[:, 0])
# scale for normalization
y_scale = np.max(xy_ref[: 1]) - np.min(xy_ref[:, 1])
# y_scale = 1e-2 # an arbitrary scale
# y_scale = np.maximum(1e-2, np.fabs(xy_ref[:, 1]))
# y_scale = np.max(xy_ref[: 1]) - np.min(xy_ref[:, 1]) * (2 - np.cos(2*pi*xy_ref[:, 0]/xte))
npts = xy_ref.shape[0]
return np.sum(((xy_ref[:, 1] - xy_kulfan[:, 1]) / y_scale)**2.0) / npts
def infer_kulfan_params(xy_ref, var_init):
"""
infer kulfan parameters given reference/target airfoil coordinates
"""
nvar = len(var_init)
lb = [-2.] * nvar
ub = [2.] * nvar
if True:
bounds = scipy.optimize.Bounds(lb, ub, keep_feasible=False)
options_opt = {"maxiter": 1e6}
opt_method = "SLSQP"
# opt_method = "L-BFGS-B"
# opt_method = "TNC"
opt_result = scipy.optimize.minimize(obj_fcn_airfoil_inversion, var_init, args=xy_ref,
method=opt_method, tol=1e-16, bounds=bounds, options=options_opt)
else:
obj_fcn = lambda x: obj_fcn_airfoil_inversion(x, xy_ref)
opt_result = scipy.optimize.dual_annealing(obj_fcn, bounds=list(zip(lb, ub)), seed=1234)
print(f"Optimization result:\n{opt_result}")
return list_to_kulfan_params(opt_result.x)
def main():
import sys
if sys.platform == 'darwin': # MacOS
import matplotlib
matplotlib.use('Qt5Agg')
import matplotlib.pyplot as plt
import os
path = './data/'
# reference coordinates
# airfoilname = "RAE2822"
# airfoilname = "b737a-il"
airfoilname = "e387"
# airfoilname = "whitcomb"
# airfoilname = "nasasc2-0714"
fname_input_airfoil = os.path.join(path, f"{airfoilname}.txt")
xy_ref = np.genfromtxt(fname_input_airfoil, dtype=float, skip_header=1)
airfoilname_inverse = f"{airfoilname}_kulfan"
# fix trailing edge y coordinates based on reference airfoil coordinates
yute = xy_ref[0, 1]
ylte = xy_ref[-1, 1]
poly_deg = 5
wu = [0.1] * (poly_deg + 1)
wl = [-0.1] * (poly_deg + 1)
var_init = list()
var_init.extend(wu)
var_init.extend(wl)
xy_coords_init = get_airfoil_coord(wu, wl, yute, ylte)
# plot initial guess of airfoil
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111)
ax.plot(xy_ref[:, 0], xy_ref[:, 1], "k.--", label="Input")
ax.plot(xy_coords_init[:, 0], xy_coords_init[:, 1], "-.", linewidth=2, label="Initial guess")
ax.legend()
ax.grid(True)
ax.set_xlim([0, 1])
ax.axis('equal')
ax.set_xticks(np.arange(0, 1.1, 0.1))
plt.show(block=True)
# infer Kulfan parameters by optimization
wu, wl = infer_kulfan_params(xy_ref, var_init)
# get inferred Kulfan airfoil coordinates
xy_coords = get_airfoil_coord(wu, wl, yute, ylte)
# save to coordinate file
fpath = os.path.join(path, f'{airfoilname_inverse}.dat')
np.savetxt(fpath, xy_coords, delimiter=" ", newline="\n")
# plot airfoil
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111)
ax.plot(xy_coords[:, 0], xy_coords[:, 1], marker=".", linewidth=2, label=airfoilname_inverse)
ax.plot(xy_coords_init[:, 0], xy_coords_init[:, 1], "-.", linewidth=2, label="Initial guess")
ax.plot(xy_ref[:, 0], xy_ref[:, 1], "k.--", label="Input")
ax.legend()
ax.grid(True)
ax.set_xlim([0, 1])
ax.axis('equal')
ax.set_xticks(np.arange(0, 1.1, 0.1))
ax.set_title(f"Kulfan airfoil with parameters: yute={yute:.4e}, ylte={ylte:.4e}\n"
f"wu={wu}\nwl={wl}")
fig.tight_layout()
fig.savefig(os.path.join(path, f'{airfoilname_inverse}.png'))
if __name__ == '__main__':
main()
| {
"alphanum_fraction": 0.617553754,
"author": null,
"avg_line_length": 29.5520833333,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "84ed9d48bedb4a62e1ce275c3ac60fe5cd65f526",
"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": "b6b788786becb32de87b9dea28401077cd2cb8c3",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "zsmeditation/airfoil_param",
"max_forks_repo_path": "kulfan_airfoil.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "b6b788786becb32de87b9dea28401077cd2cb8c3",
"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": "zsmeditation/airfoil_param",
"max_issues_repo_path": "kulfan_airfoil.py",
"max_line_length": 159,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "b6b788786becb32de87b9dea28401077cd2cb8c3",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "zsmeditation/airfoil_param",
"max_stars_repo_path": "kulfan_airfoil.py",
"max_stars_repo_stars_event_max_datetime": "2021-06-21T03:01:08.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-06-21T03:01:08.000Z",
"num_tokens": 1786,
"path": null,
"reason": "import numpy,import scipy",
"repo": null,
"save_path": null,
"sha": null,
"size": 5674
} |
from functools import partial
from functools import update_wrapper
import numpy as np
import pandas as pd
from loguru import logger
from pandas.api.types import is_categorical_dtype
from tqdm import tqdm
from src.utils.exceptions import ModalityNotPresentError
from src.utils.loaders import dataset_importer
__all__ = [
"index_decorator",
"fold_decorator",
"label_decorator",
"PartitionByTrial",
"partitioning_decorator",
]
class DecoratorBase(object):
def __init__(self, func):
update_wrapper(self, func)
self.func = func
def __get__(self, obj, objtype):
return partial(self.__call__, obj)
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
class LabelDecorator(DecoratorBase):
def __init__(self, func):
super(LabelDecorator, self).__init__(func)
def __call__(self, *args, **kwargs):
df = super(LabelDecorator, self).__call__(*args, **kwargs)
# TODO/FIXME: remove this strange pattern
if isinstance(df, tuple):
inv_lookup, df = df
df = pd.DataFrame(df)
for ci in df.columns:
df[ci] = df[ci].apply(lambda ll: inv_lookup[ll])
assert len(df.columns) == 1
df = pd.DataFrame(df)
df.columns = [f"target" for _ in range(len(df.columns))]
if is_categorical_dtype(df["target"]):
df = df.astype(dict(target="category"))
return df
class FoldDecorator(DecoratorBase):
def __init__(self, func):
super(FoldDecorator, self).__init__(func)
def __call__(self, *args, **kwargs):
df = super(FoldDecorator, self).__call__(*args, **kwargs)
if isinstance(df.columns, pd.RangeIndex):
df.columns = [f"fold_{fi}" for fi in range(len(df.columns))]
df = df.astype({col: "category" for col in df.columns})
return df
class IndexDecorator(DecoratorBase):
def __init__(self, func):
super(IndexDecorator, self).__init__(func)
def __call__(self, *args, **kwargs):
df = super(IndexDecorator, self).__call__(*args, **kwargs)
df.columns = ["subject", "trial", "time"]
return df.astype(dict(subject="category", trial="category", time=float))
def infer_data_type(data):
if isinstance(data, np.ndarray):
return "numpy"
elif isinstance(data, pd.DataFrame):
return "pandas"
logger.exception(
TypeError(f"Unsupported data type in infer_data_type ({type(data)}), currently only {{numpy, pandas}}")
)
def slice_data_type(data, inds, data_type_name):
if data_type_name == "numpy":
return data[inds]
elif data_type_name == "pandas":
return data.loc[inds]
logger.exception(
TypeError(f"Unsupported data type in slice_data_type ({type(data)}), currently only {{numpy, pandas}}")
)
def concat_data_type(datas, data_type_name):
if data_type_name == "numpy":
return np.concatenate(datas, axis=0)
elif data_type_name == "pandas":
df = pd.concat(datas, axis=0)
return df.reset_index(drop=True)
logger.exception(
TypeError(f"Unsupported data type in concat_data_type ({type(datas)}), currently only {{numpy, pandas}}")
)
class PartitionByTrial(DecoratorBase):
"""
"""
def __init__(self, func):
super(PartitionByTrial, self).__init__(func=func)
def __call__(self, index, data, *args, **kwargs):
if index.shape[0] != data.shape[0]:
logger.exception(
ValueError(
f"The data and index should have the same length "
"with index: {index.shape}; and data: {data.shape}"
)
)
output = []
trials = index.trial.unique()
data_type = infer_data_type(data)
for trial in tqdm(trials):
inds = index.trial == trial
index_ = index.loc[inds]
data_ = slice_data_type(data, inds, data_type)
vals = self.func(index=index_, data=data_, *args, **kwargs)
opdt = infer_data_type(vals)
if opdt != data_type:
logger.exception(
ValueError(
f"The data type of {self.func} should be the same as the input {data_type} "
f"but instead got {opdt}"
)
)
output.append(vals)
return concat_data_type(output, data_type)
class RequiredModalities(DecoratorBase):
def __init__(self, func, *modalities):
super(RequiredModalities, self).__init__(func=func)
self.required_modalities = set(modalities)
def __call__(self, dataset, *args, **kwargs):
dataset = dataset_importer(dataset)
dataset_modalities = dataset.meta.modalities
for required_modality in self.required_modalities:
if required_modality not in dataset_modalities:
logger.exception(
ModalityNotPresentError(
f"The modality {required_modality} is required by the function {self.func}. "
f"However, the dataset {dataset} does not have {required_modality}. The "
f"available modalities are: {dataset_modalities})"
)
)
super(self, RequiredModalities).__call__(dataset, *args, **kwargs)
required_modalities = RequiredModalities
label_decorator = LabelDecorator
index_decorator = IndexDecorator
fold_decorator = FoldDecorator
partitioning_decorator = PartitionByTrial
| {
"alphanum_fraction": 0.6214578507,
"author": null,
"avg_line_length": 31.1722222222,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "21cc9aae2e277f5f9d32f3f0063c4b59ba7094d8",
"include": true,
"lang": "Python",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 9,
"max_forks_repo_forks_event_max_datetime": "2022-03-30T16:25:47.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-12-12T16:18:39.000Z",
"max_forks_repo_head_hexsha": "68f142ba613ce26f67cdd6b871117f4c24ea603f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "niall-twomey/har_datasets",
"max_forks_repo_path": "src/utils/decorators.py",
"max_issues_count": 3,
"max_issues_repo_head_hexsha": "68f142ba613ce26f67cdd6b871117f4c24ea603f",
"max_issues_repo_issues_event_max_datetime": "2022-03-12T01:03:28.000Z",
"max_issues_repo_issues_event_min_datetime": "2019-07-18T20:14:41.000Z",
"max_issues_repo_licenses": [
"MIT"
],
"max_issues_repo_name": "niall-twomey/har_datasets",
"max_issues_repo_path": "src/utils/decorators.py",
"max_line_length": 113,
"max_stars_count": 24,
"max_stars_repo_head_hexsha": "68f142ba613ce26f67cdd6b871117f4c24ea603f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "niall-twomey/har_datasets",
"max_stars_repo_path": "src/utils/decorators.py",
"max_stars_repo_stars_event_max_datetime": "2021-12-07T08:45:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-12-12T08:54:52.000Z",
"num_tokens": 1241,
"path": null,
"reason": "import numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 5611
} |
function c = char(s,varargin)
% object -> string
if check_option(varargin,'verbose')
c = option2str([{s.pointGroup},s.alignment]);
if ~isempty(s.mineral), c = [s.mineral ' (' c ')']; end
elseif check_option(varargin,'latex')
c = ['$' regexprep(s.pointGroup,'-(\w)','\\bar{$1}') '$'];
elseif check_option(varargin,'compact')
if ~isempty(s.mineral)
c = s.mineral;
else
c = s.pointGroup;
end
if ~getMTEXpref('generatingHelpMode')
id = pushTemp(s);
c = ['<a href="matlab: display(pullTemp(' int2str(id) '),''vName'',''sym'')">' c '</a>'];
end
else
c = ['"',s.pointGroup,'"'];
end
if check_option(varargin,'symmetryType'), c = [' crystal symmetry : ' c]; end
| {
"alphanum_fraction": null,
"author": "mtex-toolbox",
"avg_line_length": null,
"converted": null,
"ext": null,
"file": null,
"hexsha": null,
"include": null,
"lang": null,
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": null,
"max_forks_repo_forks_event_max_datetime": null,
"max_forks_repo_forks_event_min_datetime": null,
"max_forks_repo_head_hexsha": null,
"max_forks_repo_licenses": null,
"max_forks_repo_name": null,
"max_forks_repo_path": null,
"max_issues_count": null,
"max_issues_repo_head_hexsha": null,
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": null,
"max_issues_repo_name": null,
"max_issues_repo_path": null,
"max_line_length": null,
"max_stars_count": null,
"max_stars_repo_head_hexsha": null,
"max_stars_repo_licenses": null,
"max_stars_repo_name": null,
"max_stars_repo_path": null,
"max_stars_repo_stars_event_max_datetime": null,
"max_stars_repo_stars_event_min_datetime": null,
"num_tokens": null,
"path": "github-repos/MATLAB/mtex-toolbox-mtex/mtex-f0ce46a720935e9ae8106ef919340534bca1adcb/geometry/@crystalSymmetry/char.m",
"reason": null,
"repo": "mtex",
"save_path": "github-repos/MATLAB/mtex-toolbox-mtex",
"sha": "f0ce46a720935e9ae8106ef919340534bca1adcb",
"size": null
} |
# Define your item pipelines here
#
# Add pipelines to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
# from itemadapter import ItemAdapter
from numpy import negative
from sqlalchemy.orm import sessionmaker
from scrapy.exceptions import DropItem
from FiScrape.models import Article, Tag, db_connect, create_table, Topic, Source, Author, SnipBlob, Blob, SnipVader, Vader # create_output_table
from FiScrape.search import query
from FiScrape.items import clean_text, extract_standfirst, TestItem
import logging
# pip install -U textblob
from textblob import TextBlob
# pip install vaderSentiment
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
from scrapy.mail import MailSender
from FiScrape.settings import mail_list, cc_list
# from scrapy.signals import engine_stopped
class SaveArticlesPipeline(object):
def __init__(self, stats, settings):
"""
Initializes database connection and sessionmaker
Creates tables
"""
engine = db_connect()
create_table(engine)
self.Session = sessionmaker(bind=engine)
self.stats = stats
self.mailer = MailSender.from_settings(settings)
@classmethod
def from_crawler(cls, crawler):
settings = crawler.settings
return cls(crawler.stats, settings)
def process_item(self, item, spider):
self.stats.inc_value('typecount/%s' % type(item).__name__)
# spider.crawler.stats.inc_value('scraped_items')
self.stats.inc_value('scraped_items')
if isinstance(item, TestItem):
return item
else:
return self.process_article(item, spider)
def process_article(self, item, spider):
"""Save articles in the database
This method is called for every item pipeline component
"""
session = self.Session()
article = Article()
topic = Topic()
source = Source()
author = Author()
tag = Tag()
snip_blob = SnipBlob()
blob = Blob()
snip_vader = SnipVader()
vader = Vader()
article.published_date = item["published_date"]
article.headline = item["headline"]
sf_list = []
for sf_str in item["standfirst"]:
sf_str = extract_standfirst(sf_str)
sf_list.append(sf_str)
sf = ' '.join(sf_list)
sf = clean_text(sf)
article.standfirst = sf
# article.standfirst = item["standfirst"]
if "article_summary" in item:
article.summary = item["article_summary"]
if "image_caption" in item:
article.image_caption = item["image_caption"]
if "article_content" in item:
article.content = item["article_content"]
if "article_footnote" in item:
article.footnote = item["article_footnote"]
article.article_link = item["article_link"]
if "origin_link" in item:
article.origin_link = item["origin_link"]
topic = Topic(name=query.capitalize())
# Check whether the topic already exists in the database
exist_topic = session.query(Topic).filter_by(name=topic.name).first()
if exist_topic is not None: # the current topic exists
topic = exist_topic
article.topics.append(topic)
source.name = spider.name
# Check whether the source already exists in the database
exist_source = session.query(
Source).filter_by(name=source.name).first()
if exist_source is not None: # the current author exists
article.source = exist_source
else:
article.source = source
# check whether the current article has authors or not
if "authors" in item:
try:
for author_name, auth in item["authors"].items():
author = Author(name=author_name)
# author.name = auth['author_name']
if 'author_position' in auth:
author.position = auth['author_position']
if "author_bio" in auth:
author.bio = auth["author_bio"]
if "bio_link" in auth:
author.bio_link = auth["bio_link"]
if "author_twitter" in auth:
author.twitter = auth["author_twitter"]
if "author_fb" in auth:
author.facebook = auth["author_fb"]
if "author_email" in auth:
author.email = auth["author_email"]
if "author_bias" in auth:
author.bias = auth["author_bias"]
if "author_birthday" in auth:
author.birthday = auth["author_birthday"]
if "author_bornlocation" in auth:
author.bornlocation = auth["author_bornlocation"]
except:
for a in item["authors"]:
for author_name, auth in a.items():
author = Author(name=author_name)
if 'author_position' in auth:
author.position = auth['author_position']
if "author_bio" in auth:
author.bio = auth["author_bio"]
if "bio_link" in auth:
author.bio_link = auth["bio_link"]
if "author_twitter" in auth:
author.twitter = auth["author_twitter"]
if "author_linkedin" in auth:
author.linkedin = auth["author_linkedin"]
if "author_fb" in auth:
author.facebook = auth["author_fb"]
if "author_email" in auth:
author.email = auth["author_email"]
if "author_bias" in auth:
author.bias = auth["author_bias"]
if "author_birthday" in auth:
author.birthday = auth["author_birthday"]
if "author_bornlocation" in auth:
author.bornlocation = auth["author_bornlocation"]
# check whether the author exists
exist_author = session.query(
Author).filter_by(name=author.name).first()
if exist_author is not None: # the current author exists
author = exist_author
article.authors.append(author)
# check whether the current article has tags or not
if "tags" in item:
for tag_name in item["tags"]:
tag = Tag(name=tag_name)
# check whether the current tag already exists in the database
exist_tag = session.query(Tag).filter_by(name=tag.name).first()
if exist_tag is not None: # the current tag exists
tag = exist_tag
article.tags.append(tag)
# Add sentiment scores for the snippet
head = article.headline
sf = article.standfirst
# head = item["headline"]
# sf = sf
excerpt = ' — ...'.join(filter(None,[head, sf]))
# print("excerpt:", excerpt)
snip_blob = SnipBlob()
snip_subjectivity_score = self.get_subjectivity(excerpt)
snip_blob.subjectivity = snip_subjectivity_score
snip_polarity_score = self.get_polarity(excerpt)
snip_blob.polarity = snip_polarity_score
snip_vader = SnipVader()
# SIA = 0
SIA = self.get_SIA(excerpt)
snip_compound = (SIA['compound'])
snip_neg = (SIA['neg'])
snip_neu = (SIA['neu'])
snip_pos = (SIA['pos'])
snip_vader.compound = snip_compound
snip_vader.negative = snip_neg
snip_vader.neutral = snip_neu
snip_vader.positive = snip_pos
article.snip_blob = snip_blob
article.snip_vader = snip_vader
# Add sentiment scores for the full text
if article.content:
content = article.content
image_caption = article.image_caption
footnote = article.footnote
fulltext = '\n'.join(filter(None,[head, image_caption, content, footnote]))
# print("fulltext:", fulltext)
blob = Blob()
subjectivity_score = self.get_subjectivity(fulltext)
blob.subjectivity = subjectivity_score
polarity_score = self.get_polarity(fulltext)
blob.polarity = polarity_score
vader = Vader()
# SIA = 0
SIA = self.get_SIA(fulltext)
compound = (SIA['compound'])
neg = (SIA['neg'])
neu = (SIA['neu'])
pos = (SIA['pos'])
vader.compound = compound
vader.negative = neg
vader.neutral = neu
vader.positive = pos
article.blob = blob
article.vader = vader
else:
polarity_score = None
subjectivity_score = None
compound = None
neg = None
neu = None
pos = None
self.send_email(item, spider, query, sf,
snip_polarity_score, snip_subjectivity_score, snip_compound, snip_neg, snip_neu, snip_pos,
polarity_score, subjectivity_score, compound, neg, neu, pos)
try:
session.add(article)
session.commit()
except:
session.rollback()
raise
finally:
session.close()
return item
# Get the subjectivity
def get_subjectivity(self, text):
"""
Returns a subjectivity score between 0 and 1.
0 is objective and 1 is subjective.
"""
return TextBlob(text).sentiment.subjectivity
# Get the polarity
def get_polarity(self, text):
"""
Returns a polarity score between -1 and 1.
-1 is negative sentiment and 1 is positive sentiment.
"""
return TextBlob(text).sentiment.polarity
# Get the sentiment scores
def get_SIA(self, text):
sia = SentimentIntensityAnalyzer()
sentiment = sia.polarity_scores(text)
return sentiment
# def send_email(self, item, sf, polarity_score, subjectivity_score, compound, neg, neu, pos):
# headline = item["headline"]
# subject = headline
# standfirst = sf
# article_link = item["article_link"]
# polarity_score = round(polarity_score, 3)
# subjectivity_score = round(subjectivity_score, 3)
# compound = round(compound, 3)
# neg = round(neg, 3)
# neu = round(neu, 3)
# pos = round(pos, 3)
# email_body = f"{standfirst}\n\n{article_link}\n\nPolarity: {polarity_score} Subjectivity: {subjectivity_score}\n\nVADER Sentiment: {compound} (Negative: {neg}, Neutral: {neu}, Positive: {pos})"
# # cc=["another@example.com" charset='utf-8'
# return self.mailer.send(to=["saran.c@pwecapital.com"], subject=subject, body=email_body, mimetype='text/plain')
def send_email(self, item, spider, query, sf,
snip_polarity_score, snip_subjectivity_score, snip_compound, snip_neg, snip_neu, snip_pos,
polarity_score, subjectivity_score, compound, neg, neu, pos):
if not polarity_score:
polarity_score = snip_polarity_score
snip_warn = '<p style="font-size: small">*The sentiment scores for this article are based only on the headline and snippet/standfirst.</p>'
else:
snip_warn = ''
if not subjectivity_score:
subjectivity_score = snip_subjectivity_score
if not compound:
compound = snip_compound
if not neg:
neg = snip_neg
if not neu:
neu = snip_neu
if not pos:
pos = snip_pos
keyword = "Keyword: " + query.capitalize()
if spider.name in ['cnbc', 'ft', 'wsj', 'zh','bbc']:
source = spider.name.upper()
else:
source = spider.name.capitalize()
source_tag = f"<p>Source: {source}</p>"
headline = item["headline"]
subject = headline
standfirst = sf
article_link = item["article_link"]
polarity_score = round(polarity_score, 3)
if polarity_score > 0:
pol_col = '#69b764' # green
elif polarity_score < 0:
pol_col = '#d82526' # red
else:
pol_col = 'black'
subjectivity_score = round(subjectivity_score, 3)
if subjectivity_score > 0.5:
sub_col = '#2526D8' # blue
elif subjectivity_score < 0.5:
sub_col = '' # teal
else:
sub_col = ''
compound = round(compound, 3)
if compound > 0:
comp_col = '#69b764' # green
elif compound < 0:
comp_col = '#d82526' # red
else:
comp_col = 'black'
neg = round(neg, 3)
neg_col = '#d82526' # red
neu = round(neu, 3)
pos = round(pos, 3)
pos_col = '#69b764' # green
body = f'<p>{standfirst}</p><p>{article_link}</p><p>Polarity: <span style="color:{pol_col};">{polarity_score}</span> Subjectivity: <span style="color:{sub_col};">{subjectivity_score}</span></p><p>VADER Sentiment: <span style="color:{comp_col};">{compound}</span> (Negative: <span style="color:{neg_col};">{neg}</span>, Neutral: {neu}, Positive: <span style="color:{pos_col};">{pos}</span>)</p>'
email_body = f'<p>{keyword}</p>{source_tag}<p><strong><u>{headline}</u></strong></p>{body}{snip_warn}'
return self.mailer.send(to=mail_list, cc=cc_list, subject=subject, body=email_body, mimetype='text/html')
class DuplicatesPipeline(object):
def __init__(self):
"""
Initializes database connection and sesssionmaker.
Creates tables.
"""
engine = db_connect()
create_table(engine)
self.Session = sessionmaker(bind=engine)
logging.info("****DuplicatesPipeline: database connected****")
def process_item(self, item, spider):
if isinstance(item, TestItem):
return item
else:
return self.process_article(item, spider)
def process_article(self, item, spider):
session = self.Session()
exist_article = session.query(Article).filter_by(
article_link=item["article_link"]).first()
session.close()
if exist_article is not None: # the current article exists
topic_name = query.capitalize()
# if topic_name in exist_article.topics:
exist_topic = session.query(
Topic).filter_by(name=topic_name).first()
if exist_topic is not None: # the current topic exists
raise DropItem("Duplicate item found: %s" % item["headline"])
else:
article = exist_article
article.topics.append(topic_name)
raise DropItem("Duplicate item found: %s" % item["headline"])
else:
return item
| {
"alphanum_fraction": 0.5783124674,
"author": null,
"avg_line_length": 38.8253164557,
"converted": null,
"ext": "py",
"file": null,
"hexsha": "2ca0f8fef0c34a723322b75eb977bdfe28616855",
"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-24T11:04:15.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-01-24T11:04:15.000Z",
"max_forks_repo_head_hexsha": "6f9ef43ea7d702a79d63a65c4149a5fc23126c1f",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "Saran33/news_scrape",
"max_forks_repo_path": "FiScrape/pipelines.py",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "6f9ef43ea7d702a79d63a65c4149a5fc23126c1f",
"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": "Saran33/news_scrape",
"max_issues_repo_path": "FiScrape/pipelines.py",
"max_line_length": 402,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "6f9ef43ea7d702a79d63a65c4149a5fc23126c1f",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "Saran33/news_scrape",
"max_stars_repo_path": "FiScrape/pipelines.py",
"max_stars_repo_stars_event_max_datetime": "2021-09-28T15:53:48.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-09-28T15:53:48.000Z",
"num_tokens": 3396,
"path": null,
"reason": "from numpy",
"repo": null,
"save_path": null,
"sha": null,
"size": 15336
} |
/*------------------------------------------------ Included libraries -----------------------------------------------*/
#include <iostream>
#include <cmath>
#include <string>
#include <Eigen/Core>
#include "random_forest.h"
using std::cout;
using std::endl;
using std::string;
using namespace derfcnd;
using namespace Eigen;
/*-------------------------------------------------------------------------------------------------------------------*/
char generateRandomSet(unsigned int nrow, unsigned int ncol_c, unsigned int ncol_d, unsigned int nclass,
string fpath, string fname);
/*------------------------------------------------------- Main ------------------------------------------------------*/
int main(int argc, char *argv[])
{
char s;
unsigned int nrow_train=1000, nrow_test=1000, ncol_c=20, ncol_d=2, nclass=5;
string fpath="", ftrain="ftrain.txt", ftest="ftest.txt", fmodel="fmodel.txt", fmodelbin="fmodel.bin";
SetData training_set, testing_set;
/* default parameters; identical to: RandomForest derf; */
RandomForest derf(N_POP, N_ITER, F, C, CONF_LVL);
VectorXf prec, rec;
MatrixXf certainty;
MatrixXi confmat;
/* generate random training set */
s=generateRandomSet(nrow_train, ncol_c, ncol_d, nclass, fpath, ftrain);
if(!s)
{
cout<<"successful random set generation to file "<<fpath<<ftrain<<endl;
}
else
{
cout<<"ERROR "<<(int) s<<": random set generation to file "<<fpath<<ftrain<<endl;
return 0;
}
/* generate random testing set */
s=generateRandomSet(nrow_test, ncol_c, ncol_d, nclass, fpath, ftest);
if(!s)
{
cout<<"successful random set generation to file "<<fpath<<ftest<<endl;
}
else
{
cout<<"ERROR "<<(int) s<<": random set generation to file "<<fpath<<ftest<<endl;
return 0;
}
/* reading training set */
s=training_set.read(fpath, ftrain);
if(!s)
{
cout<<"successful training set reading from file "<<fpath<<ftrain<<endl;
}
else
{
cout<<"ERROR "<<(int) s<<": training set reading from file "<<fpath<<ftrain<<endl;
return 0;
}
/* reading testing set */
if(!testing_set.read(fpath, ftest))
{
cout<<"successful testing set reading from file "<<fpath<<ftest<<endl;
}
else
{
cout<<"ERROR "<<(int) s<<": testing set reading from file "<<fpath<<ftest<<endl;
return 0;
}
/* generating DERF model */
cout<<"generating DERF model..."<<endl;
derf.generate(training_set, N_TREES, log2(ncol_c)+1);
/* testing DERF model */
cout<<"testing DERF model..."<<endl;
certainty.resize(nrow_test, nclass);
derf.test(testing_set, certainty);
/* computing confusion matrix */
confmat.resize(nclass, nclass+1);
confusionMatrix(testing_set.x_class_, certainty, 0, confmat);
cout<<"confusion matrix:"<<endl<<confmat<<endl;
/* computing precision */
prec.resize(nclass);
precision(confmat, prec);
cout<<"precision:"<<endl<<prec.transpose()<<endl;
/* computing recall */
rec.resize(nclass);
recall(confmat, rec);
cout<<"recall:"<<endl<<rec.transpose()<<endl;
/* writing DERF model */
s=derf.write(fpath, fmodel);
if(!s)
{
cout<<"successful model writing to file "<<fpath<<fmodel<<endl;
}
else
{
cout<<"ERROR "<<(int) s<<": model writing to file "<<fpath<<fmodel<<endl;
return 0;
}
s=derf.writeBin(fpath, fmodelbin);
if(!s)
{
cout<<"successful model writing to file "<<fpath<<fmodelbin<<endl;
}
else
{
cout<<"ERROR "<<(int) s<<": model writing to file "<<fpath<<fmodelbin<<endl;
return 0;
}
/* reading DERF model */
s=derf.read(fpath, fmodel);
if(!s)
{
cout<<"successful model reading from file "<<fpath<<fmodel<<endl;
}
else
{
cout<<"ERROR "<<(int) s<<": model reading from file "<<fpath<<fmodel<<endl;
return 0;
}
/* testing DERF model */
cout<<"testing DERF model..."<<endl;
certainty.resize(nrow_test, nclass);
derf.test(testing_set, certainty);
/* computing confusion matrix */
confmat.resize(nclass, nclass+1);
confusionMatrix(testing_set.x_class_, certainty, 0, confmat);
cout<<"confusion matrix:"<<endl<<confmat<<endl;
/* computing precision */
prec.resize(nclass);
precision(confmat, prec);
cout<<"precision:"<<endl<<prec.transpose()<<endl;
/* computing recall */
rec.resize(nclass);
recall(confmat, rec);
cout<<"recall:"<<endl<<rec.transpose()<<endl;
s=derf.readBin(fpath, fmodelbin);
if(!s)
{
cout<<"successful model reading from file "<<fpath<<fmodelbin<<endl;
}
else
{
cout<<"ERROR "<<(int) s<<": model reading from file "<<fpath<<fmodelbin<<endl;
return 0;
}
/* testing DERF model */
cout<<"testing DERF model..."<<endl;
certainty.resize(nrow_test, nclass);
derf.test(testing_set, certainty);
/* computing confusion matrix */
confmat.resize(nclass, nclass+1);
confusionMatrix(testing_set.x_class_, certainty, 0, confmat);
cout<<"confusion matrix:"<<endl<<confmat<<endl;
/* computing precision */
prec.resize(nclass);
precision(confmat, prec);
cout<<"precision:"<<endl<<prec.transpose()<<endl;
/* computing recall */
rec.resize(nclass);
recall(confmat, rec);
cout<<"recall:"<<endl<<rec.transpose()<<endl;
return 0;
}
/*-------------------------------------------------------------------------------------------------------------------*/
char generateRandomSet(unsigned int nrow, unsigned int ncol_c, unsigned int ncol_d, unsigned int nclass,
string fpath, string fname)
{
unsigned int i, j;
string lbl;
SetData set_data(nrow, ncol_c, ncol_d, nclass);
for(i=0; i<ncol_d; i++)
{
for(j=0; j<nclass; j++)
{
lbl="lbl";
lbl+='1'+i;
lbl+='1'+j;
set_data.x_d_lbl_[i].push_back(lbl);
}
}
for(i=0; i<nclass; i++)
{
lbl="class";
lbl+='0'+i;
set_data.class_lbl_[i]=lbl;
}
for(i=0; i<nrow; i++)
{
for(j=0; j<ncol_c; j++)
{
set_data.x_c_(i, j)=i*ncol_c+j;
}
for(j=0; j<ncol_d; j++)
{
set_data.x_d_(i, j)=rand()%set_data.x_d_lbl_[j].size();
}
set_data.x_class_(i)=rand()%nclass;
}
return set_data.write(fpath, fname);
} | {
"alphanum_fraction": 0.6176470588,
"author": null,
"avg_line_length": 26.8584474886,
"converted": null,
"ext": "cpp",
"file": null,
"hexsha": "d08d47a21c5cba7cf00e2974d13f7508b236e2ab",
"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": "5640586371a16cea7f1ba427949bba8c05ded82c",
"max_forks_repo_licenses": [
"MIT"
],
"max_forks_repo_name": "umgnunes/DERF",
"max_forks_repo_path": "example.cpp",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "5640586371a16cea7f1ba427949bba8c05ded82c",
"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": "umgnunes/DERF",
"max_issues_repo_path": "example.cpp",
"max_line_length": 119,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "5640586371a16cea7f1ba427949bba8c05ded82c",
"max_stars_repo_licenses": [
"MIT"
],
"max_stars_repo_name": "umgnunes/DERF",
"max_stars_repo_path": "example.cpp",
"max_stars_repo_stars_event_max_datetime": "2021-07-10T05:02:40.000Z",
"max_stars_repo_stars_event_min_datetime": "2021-07-10T05:02:40.000Z",
"num_tokens": 1641,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 5882
} |
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! EVB-QMDFF - RPMD molecular dynamics and rate constant calculations on
! black-box generated potential energy surfaces
!
! Copyright (c) 2021 by Julien Steffen (steffen@pctc.uni-kiel.de)
! Stefan Grimme (grimme@thch.uni-bonn.de) (QMDFF code)
!
! 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.
!
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
!
! subroutine eabh0: calculate only energies for hydrogen/halogem bonds
!
! part of QMDFF
!
subroutine eabh0(n,A,B,H,rab,xyz,ca,cb,energy)
use qmdff
implicit none
integer::A,B,H,n
real(kind=8)::xyz(3,n),energy,rab
real(kind=8)::ang,xy,cosabh,d2ij,d2ik,d2jk,term,temp,fa,fb
real(kind=8)::aterm,dampm,dampl,xm,ym,zm,rhm,rab2,ca,cb,da
REAL(kind=8)::longcut=8.
REAL(kind=8)::alp7=12
REAL(kind=8)::alp3= 6
real(kind=8)::rbond(3)
!
! AB distance
!
rab2=rab*rab
!
! long damping
!
dampl=1./(1.+(rab/longcut)**alp7)
!
! cos angle A-B and H (or B-H H) is term
!
rbond(1)=XYZ(1,A)-XYZ(1,H)
rbond(2)=XYZ(2,A)-XYZ(2,H)
rbond(3)=XYZ(3,A)-XYZ(3,H)
!
! apply periodic boundaries, if needed
!
if (periodic) then
call box_image(rbond)
end if
D2IK=rbond(1)**2+rbond(2)**2+rbond(3)**2
rbond(1)=XYZ(1,H)-XYZ(1,B)
rbond(2)=XYZ(2,H)-XYZ(2,B)
rbond(3)=XYZ(3,H)-XYZ(3,B)
!
! apply periodic boundaries, if needed
!
if (periodic) then
call box_image(rbond)
end if
D2JK=rbond(1)**2+rbond(2)**2+rbond(3)**2
if (d2ik.gt.d2jk) then
XY = SQRT(rab2*D2JK)
term = 0.5D0 * (rab2+D2JK-D2IK) / XY
else
XY = SQRT(rab2*D2IK)
term = 0.5D0 * (rab2+D2IK-D2JK) / XY
end if
!
! angle damping term
!
aterm = (0.5d0*(term+1.0d0))**alp3
!
! donor-acceptor term
!
fa=d2jk/d2ik
fb=d2ik/d2jk
da=(ca*fb+cb*fa)/(fa+fb)
energy=-da*dampl*aterm/(rab2*rab)
return
end subroutine eabh0
| {
"alphanum_fraction": 0.6506802721,
"author": null,
"avg_line_length": 28.2692307692,
"converted": null,
"ext": "f90",
"file": null,
"hexsha": "be1f4bb0a5d971423df32dd323c5d2b626f3aa63",
"include": null,
"lang": "FORTRAN",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 1,
"max_forks_repo_forks_event_max_datetime": "2022-02-14T03:51:49.000Z",
"max_forks_repo_forks_event_min_datetime": "2022-02-14T03:51:49.000Z",
"max_forks_repo_head_hexsha": "8d03e1ad073becb0161b0377b630d7b65fe3c290",
"max_forks_repo_licenses": [
"MIT",
"Unlicense"
],
"max_forks_repo_name": "chrinide/EVB-QMDFF",
"max_forks_repo_path": "src/eabh0.f90",
"max_issues_count": null,
"max_issues_repo_head_hexsha": "8d03e1ad073becb0161b0377b630d7b65fe3c290",
"max_issues_repo_issues_event_max_datetime": null,
"max_issues_repo_issues_event_min_datetime": null,
"max_issues_repo_licenses": [
"MIT",
"Unlicense"
],
"max_issues_repo_name": "chrinide/EVB-QMDFF",
"max_issues_repo_path": "src/eabh0.f90",
"max_line_length": 80,
"max_stars_count": 1,
"max_stars_repo_head_hexsha": "8d03e1ad073becb0161b0377b630d7b65fe3c290",
"max_stars_repo_licenses": [
"MIT",
"Unlicense"
],
"max_stars_repo_name": "Trebonius91/EVB-QMDFF",
"max_stars_repo_path": "src/eabh0.f90",
"max_stars_repo_stars_event_max_datetime": "2022-02-13T15:27:13.000Z",
"max_stars_repo_stars_event_min_datetime": "2022-02-13T15:27:13.000Z",
"num_tokens": 950,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 2940
} |
[STATEMENT]
lemma init_fin_lift_state_mbisimI:
"s \<approx>m s' \<Longrightarrow>
FWbisimulation_base.mbisim init_fin_bisim init_fin_bisim_wait (init_fin_lift_state Running s) (init_fin_lift_state Running s')"
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. s \<approx>m s' \<Longrightarrow> FWbisimulation_base.mbisim init_fin_bisim init_fin_bisim_wait (init_fin_lift_state Running s) (init_fin_lift_state Running s')
[PROOF STEP]
apply(rule FWbisimulation_base.mbisimI)
[PROOF STATE]
proof (prove)
goal (7 subgoals):
1. s \<approx>m s' \<Longrightarrow> finite (dom (thr (init_fin_lift_state Running s)))
2. s \<approx>m s' \<Longrightarrow> locks (init_fin_lift_state Running s) = locks (init_fin_lift_state Running s')
3. s \<approx>m s' \<Longrightarrow> wset (init_fin_lift_state Running s) = wset (init_fin_lift_state Running s')
4. s \<approx>m s' \<Longrightarrow> interrupts (init_fin_lift_state Running s) = interrupts (init_fin_lift_state Running s')
5. s \<approx>m s' \<Longrightarrow> wset_thread_ok (wset (init_fin_lift_state Running s)) (thr (init_fin_lift_state Running s))
6. \<And>t. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = None\<rbrakk> \<Longrightarrow> thr (init_fin_lift_state Running s') t = None
7. \<And>t x1 ln. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = \<lfloor>(x1, ln)\<rfloor>\<rbrakk> \<Longrightarrow> \<exists>x2. thr (init_fin_lift_state Running s') t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr (init_fin_lift_state Running s)) \<approx>i (x2, shr (init_fin_lift_state Running s')) \<and> (wset (init_fin_lift_state Running s') t = None \<or> x1 \<approx>iw x2)
[PROOF STEP]
apply(simp add: thr_init_fin_list_state' o_def dom_map_option mbisim_finite1)
[PROOF STATE]
proof (prove)
goal (6 subgoals):
1. s \<approx>m s' \<Longrightarrow> locks (init_fin_lift_state Running s) = locks (init_fin_lift_state Running s')
2. s \<approx>m s' \<Longrightarrow> wset (init_fin_lift_state Running s) = wset (init_fin_lift_state Running s')
3. s \<approx>m s' \<Longrightarrow> interrupts (init_fin_lift_state Running s) = interrupts (init_fin_lift_state Running s')
4. s \<approx>m s' \<Longrightarrow> wset_thread_ok (wset (init_fin_lift_state Running s)) (thr (init_fin_lift_state Running s))
5. \<And>t. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = None\<rbrakk> \<Longrightarrow> thr (init_fin_lift_state Running s') t = None
6. \<And>t x1 ln. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = \<lfloor>(x1, ln)\<rfloor>\<rbrakk> \<Longrightarrow> \<exists>x2. thr (init_fin_lift_state Running s') t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr (init_fin_lift_state Running s)) \<approx>i (x2, shr (init_fin_lift_state Running s')) \<and> (wset (init_fin_lift_state Running s') t = None \<or> x1 \<approx>iw x2)
[PROOF STEP]
apply(simp add: locks_init_fin_lift_state mbisim_def)
[PROOF STATE]
proof (prove)
goal (5 subgoals):
1. s \<approx>m s' \<Longrightarrow> wset (init_fin_lift_state Running s) = wset (init_fin_lift_state Running s')
2. s \<approx>m s' \<Longrightarrow> interrupts (init_fin_lift_state Running s) = interrupts (init_fin_lift_state Running s')
3. s \<approx>m s' \<Longrightarrow> wset_thread_ok (wset (init_fin_lift_state Running s)) (thr (init_fin_lift_state Running s))
4. \<And>t. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = None\<rbrakk> \<Longrightarrow> thr (init_fin_lift_state Running s') t = None
5. \<And>t x1 ln. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = \<lfloor>(x1, ln)\<rfloor>\<rbrakk> \<Longrightarrow> \<exists>x2. thr (init_fin_lift_state Running s') t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr (init_fin_lift_state Running s)) \<approx>i (x2, shr (init_fin_lift_state Running s')) \<and> (wset (init_fin_lift_state Running s') t = None \<or> x1 \<approx>iw x2)
[PROOF STEP]
apply(simp add: wset_init_fin_lift_state mbisim_def)
[PROOF STATE]
proof (prove)
goal (4 subgoals):
1. s \<approx>m s' \<Longrightarrow> interrupts (init_fin_lift_state Running s) = interrupts (init_fin_lift_state Running s')
2. s \<approx>m s' \<Longrightarrow> wset_thread_ok (wset (init_fin_lift_state Running s)) (thr (init_fin_lift_state Running s))
3. \<And>t. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = None\<rbrakk> \<Longrightarrow> thr (init_fin_lift_state Running s') t = None
4. \<And>t x1 ln. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = \<lfloor>(x1, ln)\<rfloor>\<rbrakk> \<Longrightarrow> \<exists>x2. thr (init_fin_lift_state Running s') t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr (init_fin_lift_state Running s)) \<approx>i (x2, shr (init_fin_lift_state Running s')) \<and> (wset (init_fin_lift_state Running s') t = None \<or> x1 \<approx>iw x2)
[PROOF STEP]
apply(simp add: interrupts_init_fin_lift_stae mbisim_def)
[PROOF STATE]
proof (prove)
goal (3 subgoals):
1. s \<approx>m s' \<Longrightarrow> wset_thread_ok (wset (init_fin_lift_state Running s)) (thr (init_fin_lift_state Running s))
2. \<And>t. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = None\<rbrakk> \<Longrightarrow> thr (init_fin_lift_state Running s') t = None
3. \<And>t x1 ln. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = \<lfloor>(x1, ln)\<rfloor>\<rbrakk> \<Longrightarrow> \<exists>x2. thr (init_fin_lift_state Running s') t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr (init_fin_lift_state Running s)) \<approx>i (x2, shr (init_fin_lift_state Running s')) \<and> (wset (init_fin_lift_state Running s') t = None \<or> x1 \<approx>iw x2)
[PROOF STEP]
apply(clarsimp simp add: wset_init_fin_lift_state mbisim_def thr_init_fin_list_state' o_def wset_thread_ok_conv_dom dom_map_option del: subsetI)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>t. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = None\<rbrakk> \<Longrightarrow> thr (init_fin_lift_state Running s') t = None
2. \<And>t x1 ln. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = \<lfloor>(x1, ln)\<rfloor>\<rbrakk> \<Longrightarrow> \<exists>x2. thr (init_fin_lift_state Running s') t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr (init_fin_lift_state Running s)) \<approx>i (x2, shr (init_fin_lift_state Running s')) \<and> (wset (init_fin_lift_state Running s') t = None \<or> x1 \<approx>iw x2)
[PROOF STEP]
apply(drule_tac t=t in mbisim_thrNone_eq)
[PROOF STATE]
proof (prove)
goal (2 subgoals):
1. \<And>t. \<lbrakk>thr (init_fin_lift_state Running s) t = None; (thr s t = None) = (thr s' t = None)\<rbrakk> \<Longrightarrow> thr (init_fin_lift_state Running s') t = None
2. \<And>t x1 ln. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = \<lfloor>(x1, ln)\<rfloor>\<rbrakk> \<Longrightarrow> \<exists>x2. thr (init_fin_lift_state Running s') t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr (init_fin_lift_state Running s)) \<approx>i (x2, shr (init_fin_lift_state Running s')) \<and> (wset (init_fin_lift_state Running s') t = None \<or> x1 \<approx>iw x2)
[PROOF STEP]
apply(simp add: thr_init_fin_list_state)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>t x1 ln. \<lbrakk>s \<approx>m s'; thr (init_fin_lift_state Running s) t = \<lfloor>(x1, ln)\<rfloor>\<rbrakk> \<Longrightarrow> \<exists>x2. thr (init_fin_lift_state Running s') t = \<lfloor>(x2, ln)\<rfloor> \<and> t \<turnstile> (x1, shr (init_fin_lift_state Running s)) \<approx>i (x2, shr (init_fin_lift_state Running s')) \<and> (wset (init_fin_lift_state Running s') t = None \<or> x1 \<approx>iw x2)
[PROOF STEP]
apply(clarsimp simp add: thr_init_fin_list_state shr_init_fin_lift_state wset_init_fin_lift_state init_fin_bisim_iff)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>t b ln. \<lbrakk>s \<approx>m s'; thr s t = \<lfloor>(b, ln)\<rfloor>\<rbrakk> \<Longrightarrow> \<exists>ba. thr s' t = \<lfloor>(ba, ln)\<rfloor> \<and> t \<turnstile> (b, shr s) \<approx> (ba, shr s') \<and> (wset s' t = None \<or> b \<approx>w ba)
[PROOF STEP]
apply(frule (1) mbisim_thrD1)
[PROOF STATE]
proof (prove)
goal (1 subgoal):
1. \<And>t b ln. \<lbrakk>s \<approx>m s'; thr s t = \<lfloor>(b, ln)\<rfloor>; \<exists>x'. thr s' t = \<lfloor>(x', ln)\<rfloor> \<and> t \<turnstile> (b, shr s) \<approx> (x', shr s') \<and> (wset s t = None \<or> b \<approx>w x')\<rbrakk> \<Longrightarrow> \<exists>ba. thr s' t = \<lfloor>(ba, ln)\<rfloor> \<and> t \<turnstile> (b, shr s) \<approx> (ba, shr s') \<and> (wset s' t = None \<or> b \<approx>w ba)
[PROOF STEP]
apply(simp add: mbisim_def)
[PROOF STATE]
proof (prove)
goal:
No subgoals!
[PROOF STEP]
done | {
"alphanum_fraction": null,
"author": null,
"avg_line_length": null,
"converted": null,
"ext": null,
"file": "JinjaThreads_Framework_FWBisimLift",
"hexsha": null,
"include": null,
"lang": null,
"length": 12,
"llama_tokens": 3602,
"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) 2006, 2007 Julio M. Merino Vidal
// Copyright (c) 2008 Ilya Sokolov, Boris Schaeling
// Copyright (c) 2009 Boris Schaeling
// Copyright (c) 2010 Felipe Tanus, Boris Schaeling
// Copyright (c) 2011, 2012 Jeff Flinn, Boris Schaeling
// Copyright (c) 2016 Klemens D. Morgenstern
//
// 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)
#ifndef BOOST_PROCESS_DETAIL_INITIALIZERS_THROW_ON_ERROR_HPP
#define BOOST_PROCESS_DETAIL_INITIALIZERS_THROW_ON_ERROR_HPP
#include <boost/process/detail/config.hpp>
#include <boost/process/detail/handler_base.hpp>
namespace boost { namespace process { namespace detail {
struct throw_on_error_ : ::boost::process::detail::handler
{
template <class Executor>
void on_error(Executor& exec, const std::error_code & ec) const
{
throw process_error(ec, "process creation failed");
}
const throw_on_error_ &operator()() const {return *this;}
};
}
constexpr boost::process::detail::throw_on_error_ throw_on_error;
}}
#endif
| {
"alphanum_fraction": 0.7278314311,
"author": null,
"avg_line_length": 30.7837837838,
"converted": null,
"ext": "hpp",
"file": null,
"hexsha": "d2a9e9394cd3ca8f8c5d99414650e89d14c34c3f",
"include": null,
"lang": "C++",
"length": null,
"llama_tokens": null,
"mathlib_filename": null,
"max_forks_count": 172,
"max_forks_repo_forks_event_max_datetime": "2022-03-29T07:44:33.000Z",
"max_forks_repo_forks_event_min_datetime": "2018-06-22T11:12:00.000Z",
"max_forks_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf",
"max_forks_repo_licenses": [
"Apache-2.0"
],
"max_forks_repo_name": "kindlychung/mediasoup-sfu-cpp",
"max_forks_repo_path": "deps/boost/include/boost/process/detail/throw_on_error.hpp",
"max_issues_count": 32,
"max_issues_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf",
"max_issues_repo_issues_event_max_datetime": "2022-03-29T10:20:37.000Z",
"max_issues_repo_issues_event_min_datetime": "2018-06-23T14:19:37.000Z",
"max_issues_repo_licenses": [
"Apache-2.0"
],
"max_issues_repo_name": "kindlychung/mediasoup-sfu-cpp",
"max_issues_repo_path": "deps/boost/include/boost/process/detail/throw_on_error.hpp",
"max_line_length": 80,
"max_stars_count": 995,
"max_stars_repo_head_hexsha": "f69d2f48f7edbf4f0c57244280a47bea985f39cf",
"max_stars_repo_licenses": [
"Apache-2.0"
],
"max_stars_repo_name": "kindlychung/mediasoup-sfu-cpp",
"max_stars_repo_path": "deps/boost/include/boost/process/detail/throw_on_error.hpp",
"max_stars_repo_stars_event_max_datetime": "2022-03-25T01:22:14.000Z",
"max_stars_repo_stars_event_min_datetime": "2018-06-22T10:39:18.000Z",
"num_tokens": 292,
"path": null,
"reason": null,
"repo": null,
"save_path": null,
"sha": null,
"size": 1139
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.