Search is not available for this dataset
text stringlengths 75 104k |
|---|
def wav2complex(filename):
"""
Return a complex signal vector from a wav file that was used to store
the real (I) and imaginary (Q) values of a complex signal ndarray.
The rate is included as means of recalling the original signal sample
rate.
fs,x = wav2complex(filename)
Mark W... |
def FIR_header(fname_out, h):
"""
Write FIR Filter Header Files
Mark Wickert February 2015
"""
M = len(h)
N = 3 # Coefficients per line
f = open(fname_out, 'wt')
f.write('//define a FIR coefficient Array\n\n')
f.write('#include <stdint.h>\n\n')
f.write('#ifndef ... |
def FIR_fix_header(fname_out, h):
"""
Write FIR Fixed-Point Filter Header Files
Mark Wickert February 2015
"""
M = len(h)
hq = int16(rint(h * 2 ** 15))
N = 8 # Coefficients per line
f = open(fname_out, 'wt')
f.write('//define a FIR coefficient Array\n\n')
f.writ... |
def IIR_sos_header(fname_out, SOS_mat):
"""
Write IIR SOS Header Files
File format is compatible with CMSIS-DSP IIR
Directform II Filter Functions
Mark Wickert March 2015-October 2016
"""
Ns, Mcol = SOS_mat.shape
f = open(fname_out, 'wt')
f.write('//define a IIR SOS C... |
def CA_code_header(fname_out, Nca):
"""
Write 1023 bit CA (Gold) Code Header Files
Mark Wickert February 2015
"""
dir_path = os.path.dirname(os.path.realpath(__file__))
ca = loadtxt(dir_path + '/ca1thru37.txt', dtype=int16, usecols=(Nca - 1,), unpack=True)
M = 1023 # code period
... |
def farrow_resample(x, fs_old, fs_new):
"""
Parameters
----------
x : Input list representing a signal vector needing resampling.
fs_old : Starting/old sampling frequency.
fs_new : New sampling frequency.
Returns
-------
y : List representing the signal vector resampled at the new f... |
def eye_plot(x,L,S=0):
"""
Eye pattern plot of a baseband digital communications waveform.
The signal must be real, but can be multivalued in terms of the underlying
modulation scheme. Used for BPSK eye plots in the Case Study article.
Parameters
----------
x : ndarray of the real input da... |
def scatter(x,Ns,start):
"""
Sample a baseband digital communications waveform at the symbol spacing.
Parameters
----------
x : ndarray of the input digital comm signal
Ns : number of samples per symbol (bit)
start : the array index to start the sampling
Returns
-------
xI : nd... |
def strips(x,Nx,fig_size=(6,4)):
"""
Plots the contents of real ndarray x as a vertical stacking of
strips, each of length Nx. The default figure size is (6,4) inches.
The yaxis tick labels are the starting index of each strip. The red
dashed lines correspond to zero amplitude in each strip.
st... |
def bit_errors(tx_data,rx_data,Ncorr = 1024,Ntransient = 0):
"""
Count bit errors between a transmitted and received BPSK signal.
Time delay between streams is detected as well as ambiquity resolution
due to carrier phase lock offsets of :math:`k*\\pi`, k=0,1.
The ndarray tx_data is Tx 0/1 bits as r... |
def QAM_bb(N_symb,Ns,mod_type='16qam',pulse='rect',alpha=0.35):
"""
QAM_BB_TX: A complex baseband transmitter
x,b,tx_data = QAM_bb(K,Ns,M)
//////////// Inputs //////////////////////////////////////////////////
N_symb = the number of symbols to process
Ns = number of samples per symbol
... |
def QAM_SEP(tx_data,rx_data,mod_type,Ncorr = 1024,Ntransient = 0,SEP_disp=True):
"""
Nsymb, Nerr, SEP_hat =
QAM_symb_errors(tx_data,rx_data,mod_type,Ncorr = 1024,Ntransient = 0)
Count symbol errors between a transmitted and received QAM signal.
The received symbols are assumed to be soft values... |
def GMSK_bb(N_bits, Ns, MSK = 0,BT = 0.35):
"""
MSK/GMSK Complex Baseband Modulation
x,data = gmsk(N_bits, Ns, BT = 0.35, MSK = 0)
Parameters
----------
N_bits : number of symbols processed
Ns : the number of samples per bit
MSK : 0 for no shaping which is standard MSK, MSK <> 0 --> GMS... |
def MPSK_bb(N_symb,Ns,M,pulse='rect',alpha = 0.25,MM=6):
"""
Generate a complex baseband MPSK signal with pulse shaping.
Parameters
----------
N_symb : number of MPSK symbols to produce
Ns : the number of samples per bit,
M : MPSK modulation order, e.g., 4, 8, 16, ...
pulse_type : 'rect... |
def QPSK_rx(fc,N_symb,Rs,EsN0=100,fs=125,lfsr_len=10,phase=0,pulse='src'):
"""
This function generates
"""
Ns = int(np.round(fs/Rs))
print('Ns = ', Ns)
print('Rs = ', fs/float(Ns))
print('EsN0 = ', EsN0, 'dB')
print('phase = ', phase, 'degrees')
print('pulse = ', pulse)
x, b, dat... |
def QPSK_BEP(tx_data,rx_data,Ncorr = 1024,Ntransient = 0):
"""
Count bit errors between a transmitted and received QPSK signal.
Time delay between streams is detected as well as ambiquity resolution
due to carrier phase lock offsets of :math:`k*\\frac{\\pi}{4}`, k=0,1,2,3.
The ndarray sdata is Tx +/... |
def BPSK_tx(N_bits,Ns,ach_fc=2.0,ach_lvl_dB=-100,pulse='rect',alpha = 0.25,M=6):
"""
Generates biphase shift keyed (BPSK) transmitter with adjacent channel interference.
Generates three BPSK signals with rectangular or square root raised cosine (SRC)
pulse shaping of duration N_bits and Ns samples per... |
def rc_imp(Ns,alpha,M=6):
"""
A truncated raised cosine pulse used in digital communications.
The pulse shaping factor :math:`0 < \\alpha < 1` is required as well as the
truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.
Parameters
----------
Ns : number of sam... |
def sqrt_rc_imp(Ns,alpha,M=6):
"""
A truncated square root raised cosine pulse used in digital communications.
The pulse shaping factor :math:`0 < \\alpha < 1` is required as well as the
truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.
Parameters
----------... |
def RZ_bits(N_bits,Ns,pulse='rect',alpha = 0.25,M=6):
"""
Generate return-to-zero (RZ) data bits with pulse shaping.
A baseband digital data signal using +/-1 amplitude signal values
and including pulse shaping.
Parameters
----------
N_bits : number of RZ {0,1} data bits to produce
Ns ... |
def my_psd(x,NFFT=2**10,Fs=1):
"""
A local version of NumPy's PSD function that returns the plot arrays.
A mlab.psd wrapper function that returns two ndarrays;
makes no attempt to auto plot anything.
Parameters
----------
x : ndarray input signal
NFFT : a power of two, e.g., 2**10 = 10... |
def time_delay(x,D,N=4):
"""
A time varying time delay which takes advantage of the Farrow structure
for cubic interpolation:
y = time_delay(x,D,N = 3)
Note that D is an array of the same length as the input signal x. This
allows you to make the delay a function of time. If you want a constant... |
def xcorr(x1,x2,Nlags):
"""
r12, k = xcorr(x1,x2,Nlags), r12 and k are ndarray's
Compute the energy normalized cross correlation between the sequences
x1 and x2. If x1 = x2 the cross correlation is the autocorrelation.
The number of lags sets how many lags to return centered about zero
"""
K... |
def PCM_encode(x,N_bits):
"""
Parameters
----------
x : signal samples to be PCM encoded
N_bits ; bit precision of PCM samples
Returns
-------
x_bits = encoded serial bit stream of 0/1 values. MSB first.
Mark Wickert, Mark 2015
"""
xq = np.int16(np.rint(x*2**(N_bits-1)))
... |
def to_bin(data, width):
"""
Convert an unsigned integer to a numpy binary array with the first
element the MSB and the last element the LSB.
"""
data_str = bin(data & (2**width-1))[2:].zfill(width)
return [int(x) for x in tuple(data_str)] |
def from_bin(bin_array):
"""
Convert binary array back a nonnegative integer. The array length is
the bit width. The first input index holds the MSB and the last holds the LSB.
"""
width = len(bin_array)
bin_wgts = 2**np.arange(width-1,-1,-1)
return int(np.dot(bin_array,bin_wgts)) |
def PCM_decode(x_bits,N_bits):
"""
Parameters
----------
x_bits : serial bit stream of 0/1 values. The length of
x_bits must be a multiple of N_bits
N_bits : bit precision of PCM samples
Returns
-------
xhat : decoded PCM signal samples
Mark Wickert, March 2015
"... |
def mux_pilot_blocks(IQ_data, Np):
"""
Parameters
----------
IQ_data : a 2D array of input QAM symbols with the columns
representing the NF carrier frequencies and each
row the QAM symbols used to form an OFDM symbol
Np : the period of the pilot blocks; e.g., a pilot bl... |
def NDA_symb_sync(z,Ns,L,BnTs,zeta=0.707,I_ord=3):
"""
zz,e_tau = NDA_symb_sync(z,Ns,L,BnTs,zeta=0.707,I_ord=3)
z = complex baseband input signal at nominally Ns samples
per symbol
Ns = Nominal number of samples per symbol (Ts/T) in the symbol
tracking loop, ... |
def DD_carrier_sync(z,M,BnTs,zeta=0.707,type=0):
"""
z_prime,a_hat,e_phi = DD_carrier_sync(z,M,BnTs,zeta=0.707,type=0)
Decision directed carrier phase tracking
z = complex baseband PSK signal at one sample per symbol
M = The PSK modulation order, i.e., 2, 8, or 8.
BnTs = t... |
def time_step(z,Ns,t_step,Nstep):
"""
Create a one sample per symbol signal containing a phase rotation
step Nsymb into the waveform.
:param z: complex baseband signal after matched filter
:param Ns: number of sample per symbol
:param t_step: in samples relative to Ns
:param Nstep: symbol s... |
def phase_step(z,Ns,p_step,Nstep):
"""
Create a one sample per symbol signal containing a phase rotation
step Nsymb into the waveform.
:param z: complex baseband signal after matched filter
:param Ns: number of sample per symbol
:param p_step: size in radians of the phase step
:param Nstep:... |
def PLL1(theta,fs,loop_type,Kv,fn,zeta,non_lin):
"""
Baseband Analog PLL Simulation Model
:param theta: input phase deviation in radians
:param fs: sampling rate in sample per second or Hz
:param loop_type: 1, first-order loop filter F(s)=K_LF; 2, integrator
with lead compensation F... |
def PLL_cbb(x,fs,loop_type,Kv,fn,zeta):
"""
Baseband Analog PLL Simulation Model
:param x: input phase deviation in radians
:param fs: sampling rate in sample per second or Hz
:param loop_type: 1, first-order loop filter F(s)=K_LF; 2, integrator
with lead compensation F(s) = (1 + s ... |
def conv_Pb_bound(R,dfree,Ck,SNRdB,hard_soft,M=2):
"""
Coded bit error probabilty
Convolution coding bit error probability upper bound
according to Ziemer & Peterson 7-16, p. 507
Mark Wickert November 2014
Parameters
----------
R: Code rate
dfree: Free distance of ... |
def hard_Pk(k,R,SNR,M=2):
"""
Pk = hard_Pk(k,R,SNR)
Calculates Pk as found in Ziemer & Peterson eq. 7-12, p.505
Mark Wickert and Andrew Smit 2018
"""
k = int(k)
if M == 2:
p = Q_fctn(np.sqrt(2.*R*SNR))
else:
p = 4./np.log2(M)*(1 - 1./np.sqrt(M))*... |
def soft_Pk(k,R,SNR,M=2):
"""
Pk = soft_Pk(k,R,SNR)
Calculates Pk as found in Ziemer & Peterson eq. 7-13, p.505
Mark Wickert November 2014
"""
if M == 2:
Pk = Q_fctn(np.sqrt(2.*k*R*SNR))
else:
Pk = 4./np.log2(M)*(1 - 1./np.sqrt(M))*\
Q_fctn(... |
def viterbi_decoder(self,x,metric_type='soft',quant_level=3):
"""
A method which performs Viterbi decoding of noisy bit stream,
taking as input soft bit values centered on +/-1 and returning
hard decision 0/1 bits.
Parameters
----------
x: Received noisy... |
def bm_calc(self,ref_code_bits, rec_code_bits, metric_type, quant_level):
"""
distance = bm_calc(ref_code_bits, rec_code_bits, metric_type)
Branch metrics calculation
Mark Wickert and Andrew Smit October 2018
"""
distance = 0
if metric_type == 'soft': # s... |
def conv_encoder(self,input,state):
"""
output, state = conv_encoder(input,state)
We get the 1/2 or 1/3 rate from self.rate
Polys G1 and G2 are entered as binary strings, e.g,
G1 = '111' and G2 = '101' for K = 3
G1 = '1011011' and G2 = '1111001' for K = 7
G... |
def puncture(self,code_bits,puncture_pattern = ('110','101')):
"""
Apply puncturing to the serial bits produced by convolutionally
encoding.
:param code_bits:
:param puncture_pattern:
:return:
Examples
--------
This example uses the fo... |
def depuncture(self,soft_bits,puncture_pattern = ('110','101'),
erase_value = 3.5):
"""
Apply de-puncturing to the soft bits coming from the channel. Erasure bits
are inserted to return the soft bit values back to a form that can be
Viterbi decoded.
:pa... |
def trellis_plot(self,fsize=(6,4)):
"""
Plots a trellis diagram of the possible state transitions.
Parameters
----------
fsize : Plot size for matplotlib.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sk_dsp_comm.fec_c... |
def traceback_plot(self,fsize=(6,4)):
"""
Plots a path of the possible last 4 states.
Parameters
----------
fsize : Plot size for matplotlib.
Examples
--------
>>> import matplotlib.pyplot as plt
>>> from sk_dsp_comm.fec_conv import fe... |
def up(self,x):
"""
Upsample and filter the signal
"""
y = self.M*ssd.upsample(x,self.M)
y = signal.lfilter(self.b,self.a,y)
return y |
def dn(self,x):
"""
Downsample and filter the signal
"""
y = signal.lfilter(self.b,self.a,x)
y = ssd.downsample(y,self.M)
return y |
def filter(self,x):
"""
Filter the signal
"""
y = signal.lfilter(self.b,[1],x)
return y |
def up(self,x,L_change = 12):
"""
Upsample and filter the signal
"""
y = L_change*ssd.upsample(x,L_change)
y = signal.lfilter(self.b,[1],y)
return y |
def dn(self,x,M_change = 12):
"""
Downsample and filter the signal
"""
y = signal.lfilter(self.b,[1],x)
y = ssd.downsample(y,M_change)
return y |
def zplane(self,auto_scale=True,size=2,detect_mult=True,tol=0.001):
"""
Plot the poles and zeros of the FIR filter in the z-plane
"""
ssd.zplane(self.b,[1],auto_scale,size,tol) |
def filter(self,x):
"""
Filter the signal using second-order sections
"""
y = signal.sosfilt(self.sos,x)
return y |
def up(self,x,L_change = 12):
"""
Upsample and filter the signal
"""
y = L_change*ssd.upsample(x,L_change)
y = signal.sosfilt(self.sos,y)
return y |
def dn(self,x,M_change = 12):
"""
Downsample and filter the signal
"""
y = signal.sosfilt(self.sos,x)
y = ssd.downsample(y,M_change)
return y |
def freq_resp(self, mode= 'dB', fs = 8000, ylim = [-100,2]):
"""
Frequency response plot
"""
iir_d.freqz_resp_cas_list([self.sos],mode,fs=fs)
pylab.grid()
pylab.ylim(ylim) |
def zplane(self,auto_scale=True,size=2,detect_mult=True,tol=0.001):
"""
Plot the poles and zeros of the FIR filter in the z-plane
"""
iir_d.sos_zplane(self.sos,auto_scale,size,tol) |
def ser2ber(q,n,d,t,ps):
"""
Converts symbol error rate to bit error rate. Taken from Ziemer and
Tranter page 650. Necessary when comparing different types of block codes.
parameters
----------
q: size of the code alphabet for given modulation type (BPSK=2)
n: number of channel bits
... |
def block_single_error_Pb_bound(j,SNRdB,coded=True,M=2):
"""
Finds the bit error probability bounds according to Ziemer and Tranter
page 656.
parameters:
-----------
j: number of parity bits used in single error correction block code
SNRdB: Eb/N0 values in dB
coded: Select single e... |
def hamm_gen(self,j):
"""
Generates parity check matrix (H) and generator
matrix (G).
Parameters
----------
j: Number of Hamming code parity bits with n = 2^j-1 and k = n-j
returns
-------
G: Systematic generator matrix with left... |
def hamm_encoder(self,x):
"""
Encodes input bit array x using hamming block code.
parameters
----------
x: array of source bits to be encoded by block encoder.
returns
-------
codewords: array of code words generated by generator
... |
def hamm_decoder(self,codewords):
"""
Decode hamming encoded codewords. Make sure code words are of
the appropriate length for the object.
parameters
---------
codewords: bit array of codewords
returns
-------
decoded_bits: bit a... |
def cyclic_encoder(self,x,G='1011'):
"""
Encodes input bit array x using cyclic block code.
parameters
----------
x: vector of source bits to be encoded by block encoder. Numpy array
of integers expected.
returns
-------
codewo... |
def cyclic_decoder(self,codewords):
"""
Decodes a vector of cyclic coded codewords.
parameters
----------
codewords: vector of codewords to be decoded. Numpy array of integers expected.
returns
-------
decoded_blocks: vector of decoded bi... |
def _select_manager(backend_name):
"""Select the proper LockManager based on the current backend used by Celery.
:raise NotImplementedError: If Celery is using an unsupported backend.
:param str backend_name: Class name of the current Celery backend. Usually value of
current_app.extensions['celery... |
def single_instance(func=None, lock_timeout=None, include_args=False):
"""Celery task decorator. Forces the task to have only one running instance at a time.
Use with binded tasks (@celery.task(bind=True)).
Modeled after:
http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html
http:/... |
def task_identifier(self):
"""Return the unique identifier (string) of a task instance."""
task_id = self.celery_self.name
if self.include_args:
merged_args = str(self.args) + str([(k, self.kwargs[k]) for k in sorted(self.kwargs)])
task_id += '.args.{0}'.format(hashlib.md... |
def is_already_running(self):
"""Return True if lock exists and has not timed out."""
redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier)
return self.celery_self.backend.client.exists(redis_key) |
def reset_lock(self):
"""Removed the lock regardless of timeout."""
redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier)
self.celery_self.backend.client.delete(redis_key) |
def is_already_running(self):
"""Return True if lock exists and has not timed out."""
date_done = (self.restore_group(self.task_identifier) or dict()).get('date_done')
if not date_done:
return False
difference = datetime.utcnow() - date_done
return difference < timede... |
def init_app(self, app):
"""Actual method to read celery settings from app configuration and initialize the celery instance.
:param app: Flask application instance.
"""
_state._register_app = self.original_register_app # Restore Celery app registration function.
if not hasattr(... |
def iter_chunksize(num_samples, chunksize):
"""Iterator used to iterate in chunks over an array of size `num_samples`.
At each iteration returns `chunksize` except for the last iteration.
"""
last_chunksize = int(np.mod(num_samples, chunksize))
chunksize = int(chunksize)
for _ in range(int(num_s... |
def iter_chunk_slice(num_samples, chunksize):
"""Iterator used to iterate in chunks over an array of size `num_samples`.
At each iteration returns a slice of size `chunksize`. In the last
iteration the slice may be smaller.
"""
i = 0
for c_size in iter_chunksize(num_samples, chunksize):
... |
def iter_chunk_index(num_samples, chunksize):
"""Iterator used to iterate in chunks over an array of size `num_samples`.
At each iteration returns a start and stop index for a slice of size
`chunksize`. In the last iteration the slice may be smaller.
"""
i = 0
for c_size in iter_chunksize(num_s... |
def reduce_chunk(func, array):
"""Reduce with `func`, chunk by chunk, the passed pytable `array`.
"""
res = []
for slice in iter_chunk_slice(array.shape[-1], array.chunkshape[-1]):
res.append(func(array[..., slice]))
return func(res) |
def map_chunk(func, array, out_array):
"""Map with `func`, chunk by chunk, the input pytable `array`.
The result is stored in the output pytable array `out_array`.
"""
for slice in iter_chunk_slice(array.shape[-1], array.chunkshape[-1]):
out_array.append(func(array[..., slice]))
return out_a... |
def parallel_gen_timestamps(dview, max_em_rate, bg_rate):
"""Generate timestamps from a set of remote simulations in `dview`.
Assumes that all the engines have an `S` object already containing
an emission trace (`S.em`). The "photons" timestamps are generated
from these emission traces and merged into a... |
def merge_ph_times(times_list, times_par_list, time_block):
"""Build an array of timestamps joining the arrays in `ph_times_list`.
`time_block` is the duration of each array of timestamps.
"""
offsets = np.arange(len(times_list)) * time_block
cum_sizes = np.cumsum([ts.size for ts in times_list])
... |
def merge_DA_ph_times(ph_times_d, ph_times_a):
"""Returns a merged timestamp array for Donor+Accept. and bool mask for A.
"""
ph_times = np.hstack([ph_times_d, ph_times_a])
a_em = np.hstack([np.zeros(ph_times_d.size, dtype=np.bool),
np.ones(ph_times_a.size, dtype=np.bool)])
ind... |
def merge_particle_emission(SS):
"""Returns a sim object summing the emissions and particles in SS (list).
"""
# Merge all the particles
P = reduce(lambda x, y: x + y, [Si.particles for Si in SS])
s = SS[0]
S = ParticlesSimulation(t_step=s.t_step, t_max=s.t_max,
parti... |
def load_PSFLab_file(fname):
"""Load the array `data` in the .mat file `fname`."""
if os.path.exists(fname) or os.path.exists(fname + '.mat'):
return loadmat(fname)['data']
else:
raise IOError("Can't find PSF file '%s'" % fname) |
def convert_PSFLab_xz(data, x_step=0.5, z_step=0.5, normalize=False):
"""Process a 2D array (from PSFLab .mat file) containing a x-z PSF slice.
The input data is the raw array saved by PSFLab. The returned array has
the x axis cut in half (only positive x) to take advantage of the
rotational symmetry a... |
def eval(self, x, y, z):
"""Evaluate the function in (x, y, z)."""
xc, yc, zc = self.rc
sx, sy, sz = self.s
## Method1: direct evaluation
#return exp(-(((x-xc)**2)/(2*sx**2) + ((y-yc)**2)/(2*sy**2) +\
# ((z-zc)**2)/(2*sz**2)))
## Method2: evaluation using... |
def eval(self, x, y, z):
"""Evaluate the function in (x, y, z).
The function is rotationally symmetric around z.
"""
ro = np.sqrt(x**2 + y**2)
zs, xs = ro.shape
v = self.eval_xz(ro.ravel(), z.ravel())
return v.reshape(zs, xs) |
def to_hdf5(self, file_handle, parent_node='/'):
"""Store the PSF data in `file_handle` (pytables) in `parent_node`.
The raw PSF array name is stored with same name as the original fname.
Also, the following attribues are set: fname, dir_, x_step, z_step.
"""
tarray = file_handl... |
def hash(self):
"""Return an hash string computed on the PSF data."""
hash_list = []
for key, value in sorted(self.__dict__.items()):
if not callable(value):
if isinstance(value, np.ndarray):
hash_list.append(value.tostring())
else:... |
def git_path_valid(git_path=None):
"""
Check whether the git executable is found.
"""
if git_path is None and GIT_PATH is None:
return False
if git_path is None: git_path = GIT_PATH
try:
call([git_path, '--version'])
return True
except OSError:
return False |
def get_git_version(git_path=None):
"""
Get the Git version.
"""
if git_path is None: git_path = GIT_PATH
git_version = check_output([git_path, "--version"]).split()[2]
return git_version |
def check_clean_status(git_path=None):
"""
Returns whether there are uncommitted changes in the working dir.
"""
output = get_status(git_path)
is_unmodified = (len(output.strip()) == 0)
return is_unmodified |
def get_last_commit_line(git_path=None):
"""
Get one-line description of HEAD commit for repository in current dir.
"""
if git_path is None: git_path = GIT_PATH
output = check_output([git_path, "log", "--pretty=format:'%ad %h %s'",
"--date=short", "-n1"])
return output... |
def get_last_commit(git_path=None):
"""
Get the HEAD commit SHA1 of repository in current dir.
"""
if git_path is None: git_path = GIT_PATH
line = get_last_commit_line(git_path)
revision_id = line.split()[1]
return revision_id |
def print_summary(string='Repository', git_path=None):
"""
Print the last commit line and eventual uncommitted changes.
"""
if git_path is None: git_path = GIT_PATH
# If git is available, check fretbursts version
if not git_path_valid():
print('\n%s revision unknown (git not found).' % ... |
def get_bromo_fnames_da(d_em_kHz, d_bg_kHz, a_em_kHz, a_bg_kHz,
ID='1+2+3+4+5+6', t_tot='480', num_p='30', pM='64',
t_step=0.5e-6, D=1.2e-11, dir_=''):
"""Get filenames for donor and acceptor timestamps for the given parameters
"""
clk_p = t_step/32. # with t_step=0.5us -> 156.25 ns
E_s... |
def set_sim_params(self, nparams, attr_params):
"""Store parameters in `params` in `h5file.root.parameters`.
`nparams` (dict)
A dict as returned by `get_params()` in `ParticlesSimulation()`
The format is:
keys:
used as parameter name
value... |
def numeric_params(self):
"""Return a dict containing all (key, values) stored in '/parameters'
"""
nparams = dict()
for p in self.h5file.root.parameters:
nparams[p.name] = p.read()
return nparams |
def numeric_params_meta(self):
"""Return a dict with all parameters and metadata in '/parameters'.
This returns the same dict format as returned by get_params() method
in ParticlesSimulation().
"""
nparams = dict()
for p in self.h5file.root.parameters:
nparam... |
def add_trajectory(self, name, overwrite=False, shape=(0,), title='',
chunksize=2**19, comp_filter=default_compression,
atom=tables.Float64Atom(), params=dict(),
chunkslice='bytes'):
"""Add an trajectory array in '/trajectories'.
"""
... |
def add_emission_tot(self, chunksize=2**19, comp_filter=default_compression,
overwrite=False, params=dict(),
chunkslice='bytes'):
"""Add the `emission_tot` array in '/trajectories'.
"""
kwargs = dict(overwrite=overwrite, chunksize=chunksize, para... |
def add_emission(self, chunksize=2**19, comp_filter=default_compression,
overwrite=False, params=dict(), chunkslice='bytes'):
"""Add the `emission` array in '/trajectories'.
"""
nparams = self.numeric_params
num_particles = nparams['np']
return self.add_traj... |
def add_position(self, radial=False, chunksize=2**19, chunkslice='bytes',
comp_filter=default_compression, overwrite=False,
params=dict()):
"""Add the `position` array in '/trajectories'.
"""
nparams = self.numeric_params
num_particles = nparams[... |
def wrap_periodic(a, a1, a2):
"""Folds all the values of `a` outside [a1..a2] inside that interval.
This function is used to apply periodic boundary conditions.
"""
a -= a1
wrapped = np.mod(a, a2 - a1) + a1
return wrapped |
def wrap_mirror(a, a1, a2):
"""Folds all the values of `a` outside [a1..a2] inside that interval.
This function is used to apply mirror-like boundary conditions.
"""
a[a > a2] = a2 - (a[a > a2] - a2)
a[a < a1] = a1 + (a1 - a[a < a1])
return a |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.