Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|> matplotlib.use('Agg') saveflag = True dim = 4 class MSTest(unittest.TestCase): def test_MSstatistics(self): ms = MS() datalist = [] for i in range(1, 4): T = 200 * i <|code_end|> . Use current file imports: import unittest import numpy as np import matplotlib import matplotlib.pyplot as plt from sprocket.model import MS from sprocket.util import low_pass_filter and context (classes, functions, or code) from other files: # Path: sprocket/model/ms.py # class MS (object): # """A modulation spectrum (MS) statistics class # Estimate statistics and perform postfilter based on # the MS statistics # # """ # # def __init__(self): # pass # # def estimate(self, datalist): # """Estimate MS statistics from list of data # # Parameters # ---------- # datalist : list, shape ('num_data') # List of several data ([T, dim]) sequence # # Returns # ------- # msstats : array, shape (`dim * 2`, `fftsize // 2 + 1`) # Mean and variance of MS # """ # # # get max length in all data and define fft length # maxlen = np.max(list(map(lambda x: x.shape[0], datalist))) # n_bit = len(bin(maxlen)) - 2 # self.fftsize = 2 ** (n_bit + 1) # # mss = [] # for data in datalist: # logpowerspec = self.logpowerspec(data) # mss.append(logpowerspec) # # # calculate mean and variance in each freq. bin # msm = np.mean(np.array(mss), axis=0) # msv = np.var(np.array(mss), axis=0) # return np.hstack([msm, msv]) # # def postfilter(self, data, msstats, cvmsstats, alpha=1.0, k=0.85, startdim=1): # """Perform postfilter based on MS statistics to data # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of data sequence # msstats : array, shape (`dim * 2`, `fftsize // 2 + 1`) # Array of mean and variance for target MS # cvmsstats : array, shape (`dim * 2`, `fftsize // 2 + 1`) # Array of mean and variance for converted MS # This option replaces the mean variance of the given data # into the mean variance estimated from training data. # alpha : float, optional # Morphing coefficient between MS transformed data and data. # .. math:: # alpha * mspf(data) + (1 - alpha) * data # Default set to 1.0 # k : float, optional # Postfilter emphasis coefficient [0 <= k <= 1] # Default set to 1.0 # startdim : int, optional # Start dimension to perform MS postfilter [1 < startdim < dim] # # Returns # ------- # filtered_data : array, shape (`T`, `data`) # Array of MS postfiltered data sequence # """ # # # get length and dimension # T, dim = data.shape # self.fftsize = msstats.shape[0] # assert dim == msstats.shape[1] // 2 # # # create zero padded data # logpowerspec, phasespec = self.logpowerspec(data, phase=True) # msed_logpowerspec = (1 - k) * logpowerspec + \ # k * (np.sqrt((msstats / cvmsstats)[:, dim:]) * # (logpowerspec - cvmsstats[:, :dim]) + msstats[:, :dim]) # # # reconstruct # reconst_complexspec = np.exp(msed_logpowerspec / 2) * (np.cos(phasespec) + # np.sin(phasespec) * 1j) # filtered_data = np.fft.ifftn(reconst_complexspec)[:T].real # # if startdim == 1: # filtered_data[:, 0] = data[:, 0] # # # apply morphing # filtered_data = alpha * filtered_data + (1 - alpha) * data # # return filtered_data # # def logpowerspec(self, data, phase=False): # """Calculate log power spectrum in each dimension # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of data sequence # # Returns # ------- # logpowerspec : array, shape (`dim`, `fftsize // 2 + 1`) # Log power spectrum of sequence # phasespec : array, shape (`dim`, `fftsize // 2 + 1`), optional # Phase spectrum of sequences # """ # # # create zero padded data # T, dim = data.shape # padded_data = np.zeros((self.fftsize, dim)) # padded_data[:T] += data # # # calculate log power spectum of data # complex_spec = np.fft.fftn(padded_data, axes=(0, 1)) # logpowerspec = 2 * np.log(np.absolute(complex_spec)) # # if phase: # phasespec = np.angle(complex_spec) # return logpowerspec, phasespec # else: # return logpowerspec # # Path: sprocket/util/filter.py # def low_pass_filter(data, cutoff, fs, n_taps=255): # """Apply low-pass filter # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of sequence. # cutoff : int, # Cutoff frequency # fs : int, # Sampling frequency # n_taps : int, optional # Tap number # # Returns # ------- # modified data: array, shape (`T`, `dim`) # Array of modified sequence. # """ # if data.shape[0] < n_taps * 3: # raise ValueError( # 'Length of data should be three times longer than n_taps.') # # fil = firwin(n_taps, cutoff, pass_zero=True, nyq=fs//2) # modified_data = filtfilt(fil, 1, data, axis=0) # return modified_data . Output only the next line.
data = low_pass_filter(np.random.rand(T * dim).reshape(T, dim), 50, fs=200, n_taps=63)
Next line prediction: <|code_start|> for line in fp: f = line.rstrip() h5f = os.path.join(h5dir, f + '.h5') h5 = HDF5(h5f, mode='r') datalist.append(h5.read(ext)) h5.close() return datalist def extsddata(data, npow, power_threshold=-20): """Get power extract static and delta feature vector Paramters --------- data : array, shape (`T`, `dim`) Acoustic feature vector npow : array, shape (`T`) Normalized power vector power_threshold : float, optional, Power threshold Default set to -20 Returns ------- extsddata : array, shape (`T_new` `dim * 2`) Silence remove static and delta feature vector """ <|code_end|> . Use current file imports: (import os import numpy as np from scipy.signal import firwin, lfilter from sprocket.util import HDF5, extfrm, static_delta) and context including class names, function names, or small code snippets from other files: # Path: sprocket/util/extfrm.py # def extfrm(data, npow, power_threshold=-20): # """Extract frame over the power threshold # # Parameters # ---------- # data: array, shape (`T`, `dim`) # Array of input data # npow : array, shape (`T`) # Vector of normalized power sequence. # power_threshold : float, optional # Value of power threshold [dB] # Default set to -20 # # Returns # ------- # data: array, shape (`T_ext`, `dim`) # Remaining data after extracting frame # `T_ext` <= `T` # # """ # # T = data.shape[0] # if T != len(npow): # raise("Length of two vectors is different.") # # valid_index = np.where(npow > power_threshold) # extdata = data[valid_index] # assert extdata.shape[0] <= T # # return extdata # # Path: sprocket/util/delta.py # def static_delta(data, win=[-1.0, 1.0, 0]): # """Calculate static and delta component # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of static matrix sequence. # win: array, optional, shape (`3`) # The shape of window matrix. # Default set to [-1.0, 1.0, 0]. # # Returns # ------- # sddata: array, shape (`T`, `dim*2`) # Array static and delta matrix sequence. # # """ # # sddata = np.c_[data, delta(data, win)] # return sddata # # Path: sprocket/util/hdf5.py # class HDF5(object): # """HDF5 handler # Offer the hdf5 format file handler # # Parameters # --------- # fpath : str, # Path of hdf5 file # # mode : str, # Open h5 as write and/or read mode # `a` : open as read/write (Default) # `w` : open as write only # `r` : open as read only # # Attributes # --------- # h5 : hdf5 class # # """ # # def __init__(self, fpath, mode='a'): # self.fpath = fpath # self.dirname, self.filename = os.path.split(self.fpath) # self.flbl, _ = os.path.splitext(self.filename) # # # os.path.split(path)[0] returns "" if path doesn't contain '/' # if self.filename != "" and self.dirname == "": # self.dirname = os.path.curdir # # if mode is None: # raise ValueError("Please specify the mode.") # else: # self.mode = mode # # # create directory if not exist # if self.mode == 'w' or self.mode == 'a': # # create directory if not exist # if not os.path.exists(self.dirname): # os.makedirs(self.dirname) # # # warn overwriting # if self.mode == 'w': # if os.path.exists(self.fpath): # print("overwrite: " + self.fpath) # # # check file existing for reading # if self.mode == 'r': # if not os.path.exists(self.fpath): # raise FileNotFoundError( # "h5 file does not exist in " + self.fpath) # # # open hdf5 file to fpath # self.h5 = h5py.File(self.fpath, self.mode) # # def read(self, ext=None): # """Read vector or array from h5 file # # Parameters # --------- # ext : str # File extention including h5 file # # Returns # ------- # array : array, # Array of hdf5 packed data # """ # # if ext is None: # raise ValueError("Please specify an existing extention.") # # return self.h5[ext][()] # # def save(self, data, ext=None): # """Write vector or array into h5 file # # Parameters # --------- # data : # Vector or array will be wrote into h5 file # # ext: str # File label of saved file # # """ # # # remove if 'ext' already exist # if ext in self.h5.keys(): # del self.h5[ext] # # self.h5.create_dataset(ext, data=data) # self.h5.flush() # # return # # def close(self): # self.h5.close() # # return # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.close() . Output only the next line.
extsddata = extfrm(static_delta(data), npow,
Using the snippet: <|code_start|> for line in fp: f = line.rstrip() h5f = os.path.join(h5dir, f + '.h5') h5 = HDF5(h5f, mode='r') datalist.append(h5.read(ext)) h5.close() return datalist def extsddata(data, npow, power_threshold=-20): """Get power extract static and delta feature vector Paramters --------- data : array, shape (`T`, `dim`) Acoustic feature vector npow : array, shape (`T`) Normalized power vector power_threshold : float, optional, Power threshold Default set to -20 Returns ------- extsddata : array, shape (`T_new` `dim * 2`) Silence remove static and delta feature vector """ <|code_end|> , determine the next line of code. You have imports: import os import numpy as np from scipy.signal import firwin, lfilter from sprocket.util import HDF5, extfrm, static_delta and context (class names, function names, or code) available: # Path: sprocket/util/extfrm.py # def extfrm(data, npow, power_threshold=-20): # """Extract frame over the power threshold # # Parameters # ---------- # data: array, shape (`T`, `dim`) # Array of input data # npow : array, shape (`T`) # Vector of normalized power sequence. # power_threshold : float, optional # Value of power threshold [dB] # Default set to -20 # # Returns # ------- # data: array, shape (`T_ext`, `dim`) # Remaining data after extracting frame # `T_ext` <= `T` # # """ # # T = data.shape[0] # if T != len(npow): # raise("Length of two vectors is different.") # # valid_index = np.where(npow > power_threshold) # extdata = data[valid_index] # assert extdata.shape[0] <= T # # return extdata # # Path: sprocket/util/delta.py # def static_delta(data, win=[-1.0, 1.0, 0]): # """Calculate static and delta component # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of static matrix sequence. # win: array, optional, shape (`3`) # The shape of window matrix. # Default set to [-1.0, 1.0, 0]. # # Returns # ------- # sddata: array, shape (`T`, `dim*2`) # Array static and delta matrix sequence. # # """ # # sddata = np.c_[data, delta(data, win)] # return sddata # # Path: sprocket/util/hdf5.py # class HDF5(object): # """HDF5 handler # Offer the hdf5 format file handler # # Parameters # --------- # fpath : str, # Path of hdf5 file # # mode : str, # Open h5 as write and/or read mode # `a` : open as read/write (Default) # `w` : open as write only # `r` : open as read only # # Attributes # --------- # h5 : hdf5 class # # """ # # def __init__(self, fpath, mode='a'): # self.fpath = fpath # self.dirname, self.filename = os.path.split(self.fpath) # self.flbl, _ = os.path.splitext(self.filename) # # # os.path.split(path)[0] returns "" if path doesn't contain '/' # if self.filename != "" and self.dirname == "": # self.dirname = os.path.curdir # # if mode is None: # raise ValueError("Please specify the mode.") # else: # self.mode = mode # # # create directory if not exist # if self.mode == 'w' or self.mode == 'a': # # create directory if not exist # if not os.path.exists(self.dirname): # os.makedirs(self.dirname) # # # warn overwriting # if self.mode == 'w': # if os.path.exists(self.fpath): # print("overwrite: " + self.fpath) # # # check file existing for reading # if self.mode == 'r': # if not os.path.exists(self.fpath): # raise FileNotFoundError( # "h5 file does not exist in " + self.fpath) # # # open hdf5 file to fpath # self.h5 = h5py.File(self.fpath, self.mode) # # def read(self, ext=None): # """Read vector or array from h5 file # # Parameters # --------- # ext : str # File extention including h5 file # # Returns # ------- # array : array, # Array of hdf5 packed data # """ # # if ext is None: # raise ValueError("Please specify an existing extention.") # # return self.h5[ext][()] # # def save(self, data, ext=None): # """Write vector or array into h5 file # # Parameters # --------- # data : # Vector or array will be wrote into h5 file # # ext: str # File label of saved file # # """ # # # remove if 'ext' already exist # if ext in self.h5.keys(): # del self.h5[ext] # # self.h5.create_dataset(ext, data=data) # self.h5.flush() # # return # # def close(self): # self.h5.close() # # return # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.close() . Output only the next line.
extsddata = extfrm(static_delta(data), npow,
Using the snippet: <|code_start|> lcf_x = lfilter(fil, 1, x) return lcf_x def read_feats(listf, h5dir, ext='mcep'): """HDF5 handler Create list consisting of arrays listed in the list Parameters --------- listf : str, Path of list file h5dir : str, Path of hdf5 directory ext : str, `mcep` : mel-cepstrum `f0` : F0 Returns --------- datalist : list of arrays """ datalist = [] with open(listf, 'r') as fp: for line in fp: f = line.rstrip() h5f = os.path.join(h5dir, f + '.h5') <|code_end|> , determine the next line of code. You have imports: import os import numpy as np from scipy.signal import firwin, lfilter from sprocket.util import HDF5, extfrm, static_delta and context (class names, function names, or code) available: # Path: sprocket/util/extfrm.py # def extfrm(data, npow, power_threshold=-20): # """Extract frame over the power threshold # # Parameters # ---------- # data: array, shape (`T`, `dim`) # Array of input data # npow : array, shape (`T`) # Vector of normalized power sequence. # power_threshold : float, optional # Value of power threshold [dB] # Default set to -20 # # Returns # ------- # data: array, shape (`T_ext`, `dim`) # Remaining data after extracting frame # `T_ext` <= `T` # # """ # # T = data.shape[0] # if T != len(npow): # raise("Length of two vectors is different.") # # valid_index = np.where(npow > power_threshold) # extdata = data[valid_index] # assert extdata.shape[0] <= T # # return extdata # # Path: sprocket/util/delta.py # def static_delta(data, win=[-1.0, 1.0, 0]): # """Calculate static and delta component # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of static matrix sequence. # win: array, optional, shape (`3`) # The shape of window matrix. # Default set to [-1.0, 1.0, 0]. # # Returns # ------- # sddata: array, shape (`T`, `dim*2`) # Array static and delta matrix sequence. # # """ # # sddata = np.c_[data, delta(data, win)] # return sddata # # Path: sprocket/util/hdf5.py # class HDF5(object): # """HDF5 handler # Offer the hdf5 format file handler # # Parameters # --------- # fpath : str, # Path of hdf5 file # # mode : str, # Open h5 as write and/or read mode # `a` : open as read/write (Default) # `w` : open as write only # `r` : open as read only # # Attributes # --------- # h5 : hdf5 class # # """ # # def __init__(self, fpath, mode='a'): # self.fpath = fpath # self.dirname, self.filename = os.path.split(self.fpath) # self.flbl, _ = os.path.splitext(self.filename) # # # os.path.split(path)[0] returns "" if path doesn't contain '/' # if self.filename != "" and self.dirname == "": # self.dirname = os.path.curdir # # if mode is None: # raise ValueError("Please specify the mode.") # else: # self.mode = mode # # # create directory if not exist # if self.mode == 'w' or self.mode == 'a': # # create directory if not exist # if not os.path.exists(self.dirname): # os.makedirs(self.dirname) # # # warn overwriting # if self.mode == 'w': # if os.path.exists(self.fpath): # print("overwrite: " + self.fpath) # # # check file existing for reading # if self.mode == 'r': # if not os.path.exists(self.fpath): # raise FileNotFoundError( # "h5 file does not exist in " + self.fpath) # # # open hdf5 file to fpath # self.h5 = h5py.File(self.fpath, self.mode) # # def read(self, ext=None): # """Read vector or array from h5 file # # Parameters # --------- # ext : str # File extention including h5 file # # Returns # ------- # array : array, # Array of hdf5 packed data # """ # # if ext is None: # raise ValueError("Please specify an existing extention.") # # return self.h5[ext][()] # # def save(self, data, ext=None): # """Write vector or array into h5 file # # Parameters # --------- # data : # Vector or array will be wrote into h5 file # # ext: str # File label of saved file # # """ # # # remove if 'ext' already exist # if ext in self.h5.keys(): # del self.h5[ext] # # self.h5.create_dataset(ext, data=data) # self.h5.flush() # # return # # def close(self): # self.h5.close() # # return # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.close() . Output only the next line.
h5 = HDF5(h5f, mode='r')
Predict the next line after this snippet: <|code_start|>from __future__ import absolute_import, division, print_function dirpath = os.path.dirname(os.path.realpath(__file__)) listf = os.path.join(dirpath, '/data/test.h5') class hdf5FunctionsTest(unittest.TestCase): def test_HDF5(self): data1d = np.random.rand(100) data1d2 = np.random.rand(50) data2d = np.random.rand(100).reshape(50, 2) # write test path = os.path.join(dirpath, 'data/test.h5') <|code_end|> using the current file's imports: import os import sys import unittest import numpy as np from pathlib import Path from sprocket.util.hdf5 import HDF5 and any relevant context from other files: # Path: sprocket/util/hdf5.py # class HDF5(object): # """HDF5 handler # Offer the hdf5 format file handler # # Parameters # --------- # fpath : str, # Path of hdf5 file # # mode : str, # Open h5 as write and/or read mode # `a` : open as read/write (Default) # `w` : open as write only # `r` : open as read only # # Attributes # --------- # h5 : hdf5 class # # """ # # def __init__(self, fpath, mode='a'): # self.fpath = fpath # self.dirname, self.filename = os.path.split(self.fpath) # self.flbl, _ = os.path.splitext(self.filename) # # # os.path.split(path)[0] returns "" if path doesn't contain '/' # if self.filename != "" and self.dirname == "": # self.dirname = os.path.curdir # # if mode is None: # raise ValueError("Please specify the mode.") # else: # self.mode = mode # # # create directory if not exist # if self.mode == 'w' or self.mode == 'a': # # create directory if not exist # if not os.path.exists(self.dirname): # os.makedirs(self.dirname) # # # warn overwriting # if self.mode == 'w': # if os.path.exists(self.fpath): # print("overwrite: " + self.fpath) # # # check file existing for reading # if self.mode == 'r': # if not os.path.exists(self.fpath): # raise FileNotFoundError( # "h5 file does not exist in " + self.fpath) # # # open hdf5 file to fpath # self.h5 = h5py.File(self.fpath, self.mode) # # def read(self, ext=None): # """Read vector or array from h5 file # # Parameters # --------- # ext : str # File extention including h5 file # # Returns # ------- # array : array, # Array of hdf5 packed data # """ # # if ext is None: # raise ValueError("Please specify an existing extention.") # # return self.h5[ext][()] # # def save(self, data, ext=None): # """Write vector or array into h5 file # # Parameters # --------- # data : # Vector or array will be wrote into h5 file # # ext: str # File label of saved file # # """ # # # remove if 'ext' already exist # if ext in self.h5.keys(): # del self.h5[ext] # # self.h5.create_dataset(ext, data=data) # self.h5.flush() # # return # # def close(self): # self.h5.close() # # return # # def __enter__(self): # return self # # def __exit__(self, exc_type, exc_value, traceback): # self.close() . Output only the next line.
h5 = HDF5(path, 'w')
Based on the snippet: <|code_start|> dirpath = os.path.dirname(os.path.realpath(__file__)) saveflag = False class WSOLATest(unittest.TestCase): def test_wsola(self): path = dirpath + '/data/test16000.wav' fs, x = wavfile.read(path) for speech_rate in (0.5, 0.75, 1.0, 1.5, 2.0): <|code_end|> , predict the immediate next line with the help of imports: import unittest import os import numpy as np from scipy.io import wavfile from sprocket.speech import WSOLA and context (classes, functions, sometimes code) from other files: # Path: sprocket/speech/wsola.py # class WSOLA(object): # # """WSOLA class # # Modify speech rate of a given waveform # # Parameters # ---------- # fs : int # Sampling frequency # speech_rate : float # Relative speech rate of duration modified speech to original speech # shiftms : int, optional # length of shift # # Attributes # ---------- # win : array # Window vector # # """ # # def __init__(self, fs, speech_rate, shiftms=10): # self.fs = fs # self.speech_rate = speech_rate # # self.shiftms = shiftms # shift length [ms] # self.sl = int(self.fs * self.shiftms / 1000) # of samples in a shift # self.fl = self.sl * 2 # of samples in a frame # self.epstep = int(self.sl * self.speech_rate) # step size for WSOLA # self.win = np.hanning(self.fl) # window function for a frame # # def duration_modification(self, x): # """Duration modification based on WSOLA # # Parameters # --------- # x : array, shape ('len(x)') # array of waveform sequence # # Returns # --------- # wsolaed: array, shape (`int(len(x) / speech_rate)`) # Array of WSOLAed waveform sequence # # """ # # wlen = len(x) # wsolaed = np.zeros(int(wlen / self.speech_rate), dtype='d') # # # initialization # sp = self.sl * 2 # rp = sp + self.sl # ep = sp + self.epstep # outp = self.sl # # # allocate first frame of waveform to outp # wsolaed[:outp] = x[:outp] # # while wlen > ep + self.fl: # # copy wavform # ref = x[rp - self.sl:rp + self.sl] # buff = x[ep - self.fl:ep + self.fl] # # # search minimum distance bepween ref and buff # delta = self._search_minimum_distance(ref, buff) # epd = ep + delta # # # store WSOLAed waveform using over-lap add # spdata = x[sp:sp + self.sl] * self.win[self.sl:] # epdata = x[epd - self.sl:epd] * self.win[:self.sl] # if len(spdata) == len(wsolaed[outp:outp + self.sl]): # wsolaed[outp:outp + self.sl] = spdata + epdata # else: # wsolaed_len = len(wsolaed[outp:outp + self.sl]) # wsolaed[outp:outp + self.sl] = spdata[:wsolaed_len] + \ # epdata[:wsolaed_len] # # outp += self.sl # # # transtion to next frame # sp = epd # rp = sp + self.sl # ep += self.epstep # # return wsolaed # # def _search_minimum_distance(self, ref, buff): # if len(ref) < self.fl: # ref = np.r_[ref, np.zeros(self.fl - len(ref))] # # # slicing and windowing one sample by one # buffmat = view_as_windows(buff, self.fl) * self.win # refwin = np.array(ref * self.win).reshape(1, self.fl) # corr = correlate2d(buffmat, refwin, mode='valid') # # return np.argmax(corr) - self.sl . Output only the next line.
wsola = WSOLA(fs, speech_rate)
Based on the snippet: <|code_start|> dirpath = os.path.dirname(os.path.realpath(__file__)) saveflag = False class ShifterTest(unittest.TestCase): def test_shifter(self): path = dirpath + '/data/test16000.wav' fs, x = wavfile.read(path) for f0rate in (0.5, 0.75, 1.0, 1.5, 2.0): if f0rate < 1: completion = True else: completion = False <|code_end|> , predict the immediate next line with the help of imports: import unittest import os import numpy as np from scipy.io import wavfile from scipy.fftpack import fft from sprocket.speech import Shifter and context (classes, functions, sometimes code) from other files: # Path: sprocket/speech/shifter.py # class Shifter(object): # # """Shifter class # # Transform f0 of given waveform signal based on WSOLA and # resampling # # Parameters # ---------- # fs : int # Sampling frequency # f0rate: float # F0 transformation ratio # shiftms : int, optional # length of shift size [ms] # # Attributes # ---------- # win : array # Window vector # # """ # # def __init__(self, fs, f0rate, shiftms=10): # self.fs = fs # self.f0rate = f0rate # # self.shiftms = shiftms # shift size for over-lap add # self.wsola = WSOLA(fs, 1 / f0rate, shiftms=self.shiftms) # # def f0transform(self, x, completion=False): # """Transform F0 of given waveform signals using # # Parameters # --------- # x : array, shape ('len(x)') # array of waveform sequence # # completion : bool, optional # Completion of high frequency range of F0 transformed wavform based on # unvoiced analysis/synthesis voice of given voice and high-pass filter. # This is due to loose the high frequency range caused by resampling # when F0ratio setting to smaller than 1.0. # # Returns # --------- # transformed : array, shape (`len(x)`) # Array of F0 transformed waveform sequence # # """ # # self.xlen = len(x) # # # WSOLA # wsolaed = self.wsola.duration_modification(x) # # # resampling # transformed = resample(wsolaed, self.xlen) # # # Frequency completion when decrease F0 of wavform # if completion: # if self.f0rate > 1.0: # raise ValueError("Do not enable completion if f0rate > 1.") # transformed = self._high_frequency_completion(x, transformed) # # return transformed # # def resampling_by_interpolate(self, x): # """Resampling base on 1st order interpolation # # Parameters # --------- # x : array, shape ('int(len(x) * f0rate)') # array of wsolaed waveform # # Returns # --------- # wsolaed: array, shape (`len(x)`) # Array of resampled (F0 transformed) waveform sequence # # """ # # # interpolate # wedlen = len(x) # intpfunc = interp1d(np.arange(wedlen), x, kind=1) # x_new = np.arange(0.0, wedlen - 1, self.f0rate) # resampled = intpfunc(x_new) # # return resampled # # def _high_frequency_completion(self, x, transformed): # """ # Please see Sect. 3.2 and 3.3 in the following paper to know why we complete the # unvoiced synthesized voice of the original voice into high frequency range # of F0 transformed voice. # # - K. Kobayashi et al., "F0 transformation techniques for statistical voice # conversion with direct waveform modification with spectral differential," # Proc. IEEE SLT 2016, pp. 693-700. 2016. # """ # # construct feature extractor and synthesis # feat = FeatureExtractor(fs=self.fs) # f0, spc, ap = feat.analyze(x) # uf0 = np.zeros(len(f0)) # # # synthesis # synth = Synthesizer(fs=self.fs) # unvoice_anasyn = synth.synthesis_spc(uf0, spc, ap) # # # HPF for synthesized speech # fil = firwin(255, self.f0rate, pass_zero=False) # HPFed_unvoice_anasyn = filtfilt(fil, 1, unvoice_anasyn) # # if len(HPFed_unvoice_anasyn) > len(transformed): # return transformed + HPFed_unvoice_anasyn[:len(transformed)] # else: # transformed[:len(HPFed_unvoice_anasyn)] += HPFed_unvoice_anasyn # return transformed . Output only the next line.
shifter = Shifter(fs, f0rate=f0rate, shiftms=10)
Using the snippet: <|code_start|> matplotlib.use('Agg') saveflag = False class FilterFunctionsTest(unittest.TestCase): def test_filter(self): fs = 8000 f0 = 440 sin = np.array([np.sin(2.0 * np.pi * f0 * n / fs) for n in range(fs * 1)]) noise = np.random.rand(len(sin)) - 0.5 wav = sin + noise <|code_end|> , determine the next line of code. You have imports: import unittest import numpy as np import matplotlib import matplotlib.pyplot as plt from sprocket.util.filter import low_pass_filter, high_pass_filter and context (class names, function names, or code) available: # Path: sprocket/util/filter.py # def low_pass_filter(data, cutoff, fs, n_taps=255): # """Apply low-pass filter # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of sequence. # cutoff : int, # Cutoff frequency # fs : int, # Sampling frequency # n_taps : int, optional # Tap number # # Returns # ------- # modified data: array, shape (`T`, `dim`) # Array of modified sequence. # """ # if data.shape[0] < n_taps * 3: # raise ValueError( # 'Length of data should be three times longer than n_taps.') # # fil = firwin(n_taps, cutoff, pass_zero=True, nyq=fs//2) # modified_data = filtfilt(fil, 1, data, axis=0) # return modified_data # # def high_pass_filter(data, cutoff, fs, n_taps=255): # """Apply high-pass filter # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of sequence. # cutoff : int, # Cutoff frequency # fs : int, # Sampling frequency # n_taps : int, optional # Tap number # # Returns # ------- # modified data: array, shape (`T`, `dim`) # Array of modified sequence. # """ # if data.shape[0] < n_taps * 3: # raise ValueError( # 'Length of data should be three times longer than n_taps.') # # fil = firwin(n_taps, cutoff, pass_zero=False, nyq=fs//2) # modified_data = filtfilt(fil, 1, data, axis=0) # return modified_data . Output only the next line.
lpfed = low_pass_filter(wav, 500, n_taps=255, fs=fs)
Predict the next line after this snippet: <|code_start|> matplotlib.use('Agg') saveflag = False class FilterFunctionsTest(unittest.TestCase): def test_filter(self): fs = 8000 f0 = 440 sin = np.array([np.sin(2.0 * np.pi * f0 * n / fs) for n in range(fs * 1)]) noise = np.random.rand(len(sin)) - 0.5 wav = sin + noise lpfed = low_pass_filter(wav, 500, n_taps=255, fs=fs) <|code_end|> using the current file's imports: import unittest import numpy as np import matplotlib import matplotlib.pyplot as plt from sprocket.util.filter import low_pass_filter, high_pass_filter and any relevant context from other files: # Path: sprocket/util/filter.py # def low_pass_filter(data, cutoff, fs, n_taps=255): # """Apply low-pass filter # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of sequence. # cutoff : int, # Cutoff frequency # fs : int, # Sampling frequency # n_taps : int, optional # Tap number # # Returns # ------- # modified data: array, shape (`T`, `dim`) # Array of modified sequence. # """ # if data.shape[0] < n_taps * 3: # raise ValueError( # 'Length of data should be three times longer than n_taps.') # # fil = firwin(n_taps, cutoff, pass_zero=True, nyq=fs//2) # modified_data = filtfilt(fil, 1, data, axis=0) # return modified_data # # def high_pass_filter(data, cutoff, fs, n_taps=255): # """Apply high-pass filter # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of sequence. # cutoff : int, # Cutoff frequency # fs : int, # Sampling frequency # n_taps : int, optional # Tap number # # Returns # ------- # modified data: array, shape (`T`, `dim`) # Array of modified sequence. # """ # if data.shape[0] < n_taps * 3: # raise ValueError( # 'Length of data should be three times longer than n_taps.') # # fil = firwin(n_taps, cutoff, pass_zero=False, nyq=fs//2) # modified_data = filtfilt(fil, 1, data, axis=0) # return modified_data . Output only the next line.
hpfed = high_pass_filter(wav, 1000, n_taps=255, fs=fs)
Next line prediction: <|code_start|> Default set to world fs : int, optional Sampling frequency of the waveform Default set to 16000 fftl: int, optional FFT length Default set to 1024 shiftms : int, optional Shift size for short-time Fourier transform [ms] Default set to 5 minf0 : float, optional Floor value for F0 estimation Default set to 50 maxf0 : float, optional Ceil value for F0 estimation Default set to 500 """ def __init__(self, analyzer='world', fs=16000, fftl=1024, shiftms=5, minf0=50, maxf0=500): self.analyzer = analyzer self.fs = fs self.fftl = fftl self.shiftms = shiftms self.minf0 = minf0 self.maxf0 = maxf0 # analyzer setting if self.analyzer == 'world': <|code_end|> . Use current file imports: (import pysptk import pyworld import numpy as np from .analyzer import WORLD from .parameterizer import spc2npow) and context including class names, function names, or small code snippets from other files: # Path: sprocket/speech/analyzer.py # class WORLD(object): # """WORLD-based speech analyzer # # Parameters # ---------- # fs : int, optional # Sampling frequency # Default set to 16000 # fftl : int, optional # FFT length # Default set to 1024 # shiftms : int, optional # Shift lengs [ms] # Default set to 5.0 # minf0 : int, optional # Floor in f0 estimation # Default set to 50 # maxf0 : int, optional # Ceil in f0 estimation # Default set to 500 # """ # # def __init__(self, fs=16000, fftl=1024, shiftms=5.0, minf0=40.0, maxf0=500.0): # self.fs = fs # self.fftl = fftl # self.shiftms = shiftms # self.minf0 = minf0 # self.maxf0 = maxf0 # # def analyze(self, x): # """Analyze acoustic features based on WORLD # # analyze F0, spectral envelope, aperiodicity # # Paramters # --------- # x : array, shape (`T`) # monoral speech signal in time domain # # Returns # --------- # f0 : array, shape (`T`,) # F0 sequence # spc : array, shape (`T`, `fftl / 2 + 1`) # Spectral envelope sequence # ap: array, shape (`T`, `fftl / 2 + 1`) # aperiodicity sequence # # """ # f0, time_axis = pyworld.harvest(x, self.fs, f0_floor=self.minf0, # f0_ceil=self.maxf0, frame_period=self.shiftms) # spc = pyworld.cheaptrick(x, f0, time_axis, self.fs, # fft_size=self.fftl) # ap = pyworld.d4c(x, f0, time_axis, self.fs, fft_size=self.fftl) # # assert spc.shape == ap.shape # return f0, spc, ap # # def analyze_f0(self, x): # """Analyze decomposes a speech signal into F0: # # Paramters # --------- # x: array, shape (`T`) # monoral speech signal in time domain # # Returns # --------- # f0 : array, shape (`T`,) # F0 sequence # # """ # # f0, time_axis = pyworld.harvest(x, self.fs, f0_floor=self.minf0, # f0_ceil=self.maxf0, frame_period=self.shiftms) # # return f0 # # def synthesis(self, f0, spc, ap): # """Synthesis re-synthesizes a speech waveform from: # # Parameters # ---------- # f0 : array, shape (`T`) # F0 sequence # spc : array, shape (`T`, `dim`) # Spectral envelope sequence # ap: array, shape (`T`, `dim`) # Aperiodicity sequence # # """ # # return pyworld.synthesize(f0, spc, ap, self.fs, frame_period=self.shiftms) # # Path: sprocket/speech/parameterizer.py # def spc2npow(spectrogram): # """Calculate normalized power sequence from spectrogram # # Parameters # ---------- # spectrogram : array, shape (T, `fftlen / 2 + 1`) # Array of spectrum envelope # # Return # ------ # npow : array, shape (`T`, `1`) # Normalized power sequence # # """ # # # frame based processing # npow = np.apply_along_axis(_spvec2pow, 1, spectrogram) # # meanpow = np.mean(npow) # npow = 10.0 * np.log10(npow / meanpow) # # return npow . Output only the next line.
self.analyzer = WORLD(fs=self.fs,
Predict the next line after this snippet: <|code_start|> def codeap(self): """Return coded aperiodicity sequence Returns ------- codeap : array, shape (`T`, `dim`) Encoded aperiodicity sequence of the waveform The `dim` of code ap is defined based on the `fs` as follow: fs = `16000` : `1` fs = `22050` : `2` fs = `44100` : `5` fs = `48000` : `5` """ self._analyzed_check() return pyworld.code_aperiodicity(self._ap, self.fs) def npow(self): """Return normalized power sequence parameterized from spectral envelope Returns ------- npow: vector, shape (`T`,) Normalized power sequence of the given waveform """ self._analyzed_check() <|code_end|> using the current file's imports: import pysptk import pyworld import numpy as np from .analyzer import WORLD from .parameterizer import spc2npow and any relevant context from other files: # Path: sprocket/speech/analyzer.py # class WORLD(object): # """WORLD-based speech analyzer # # Parameters # ---------- # fs : int, optional # Sampling frequency # Default set to 16000 # fftl : int, optional # FFT length # Default set to 1024 # shiftms : int, optional # Shift lengs [ms] # Default set to 5.0 # minf0 : int, optional # Floor in f0 estimation # Default set to 50 # maxf0 : int, optional # Ceil in f0 estimation # Default set to 500 # """ # # def __init__(self, fs=16000, fftl=1024, shiftms=5.0, minf0=40.0, maxf0=500.0): # self.fs = fs # self.fftl = fftl # self.shiftms = shiftms # self.minf0 = minf0 # self.maxf0 = maxf0 # # def analyze(self, x): # """Analyze acoustic features based on WORLD # # analyze F0, spectral envelope, aperiodicity # # Paramters # --------- # x : array, shape (`T`) # monoral speech signal in time domain # # Returns # --------- # f0 : array, shape (`T`,) # F0 sequence # spc : array, shape (`T`, `fftl / 2 + 1`) # Spectral envelope sequence # ap: array, shape (`T`, `fftl / 2 + 1`) # aperiodicity sequence # # """ # f0, time_axis = pyworld.harvest(x, self.fs, f0_floor=self.minf0, # f0_ceil=self.maxf0, frame_period=self.shiftms) # spc = pyworld.cheaptrick(x, f0, time_axis, self.fs, # fft_size=self.fftl) # ap = pyworld.d4c(x, f0, time_axis, self.fs, fft_size=self.fftl) # # assert spc.shape == ap.shape # return f0, spc, ap # # def analyze_f0(self, x): # """Analyze decomposes a speech signal into F0: # # Paramters # --------- # x: array, shape (`T`) # monoral speech signal in time domain # # Returns # --------- # f0 : array, shape (`T`,) # F0 sequence # # """ # # f0, time_axis = pyworld.harvest(x, self.fs, f0_floor=self.minf0, # f0_ceil=self.maxf0, frame_period=self.shiftms) # # return f0 # # def synthesis(self, f0, spc, ap): # """Synthesis re-synthesizes a speech waveform from: # # Parameters # ---------- # f0 : array, shape (`T`) # F0 sequence # spc : array, shape (`T`, `dim`) # Spectral envelope sequence # ap: array, shape (`T`, `dim`) # Aperiodicity sequence # # """ # # return pyworld.synthesize(f0, spc, ap, self.fs, frame_period=self.shiftms) # # Path: sprocket/speech/parameterizer.py # def spc2npow(spectrogram): # """Calculate normalized power sequence from spectrogram # # Parameters # ---------- # spectrogram : array, shape (T, `fftlen / 2 + 1`) # Array of spectrum envelope # # Return # ------ # npow : array, shape (`T`, `1`) # Normalized power sequence # # """ # # # frame based processing # npow = np.apply_along_axis(_spvec2pow, 1, spectrogram) # # meanpow = np.mean(npow) # npow = 10.0 * np.log10(npow / meanpow) # # return npow . Output only the next line.
return spc2npow(self._spc)
Continue the code snippet: <|code_start|> def main(*argv): argv = argv if argv else sys.argv[1:] dcp = 'Create histogram for speaker-dependent configure' parser = argparse.ArgumentParser(description=dcp) parser.add_argument('speaker', type=str, help='Input speaker label') parser.add_argument('list_file', type=str, help='List file of the input speaker') parser.add_argument('wav_dir', type=str, help='Directory of wav file') parser.add_argument('figure_dir', type=str, help='Directory for figure output') args = parser.parse_args(argv) # open list file with open(args.list_file, 'r') as fp: files = fp.readlines() f0s = [] npows = [] for f in files: # open waveform f = f.rstrip() wavf = os.path.join(args.wav_dir, f + '.wav') fs, x = wavfile.read(wavf) x = np.array(x, dtype=np.float) print("Extract: " + wavf) # constract FeatureExtractor class <|code_end|> . Use current file imports: import argparse import os import sys import matplotlib import numpy as np import matplotlib.pyplot as plt # isort:skip from scipy.io import wavfile from sprocket.speech import FeatureExtractor and context (classes, functions, or code) from other files: # Path: sprocket/speech/feature_extractor.py # class FeatureExtractor(object): # # """Analyze and synthesize acoustic features from a waveform # # Extract several types of acoustic features such as F0, aperiodicity, # spectral envelope, from a given waveform. # # Parameters # ---------- # analyzer : str, optional # Analyzer of acoustic feature # 'world' : WORLD analysis/synthesis framework # Default set to world # fs : int, optional # Sampling frequency of the waveform # Default set to 16000 # fftl: int, optional # FFT length # Default set to 1024 # shiftms : int, optional # Shift size for short-time Fourier transform [ms] # Default set to 5 # minf0 : float, optional # Floor value for F0 estimation # Default set to 50 # maxf0 : float, optional # Ceil value for F0 estimation # Default set to 500 # # """ # # def __init__(self, analyzer='world', fs=16000, fftl=1024, shiftms=5, # minf0=50, maxf0=500): # self.analyzer = analyzer # self.fs = fs # self.fftl = fftl # self.shiftms = shiftms # self.minf0 = minf0 # self.maxf0 = maxf0 # # # analyzer setting # if self.analyzer == 'world': # self.analyzer = WORLD(fs=self.fs, # fftl=self.fftl, # minf0=self.minf0, # maxf0=self.maxf0, # shiftms=self.shiftms # ) # else: # raise( # 'Other analyzer does not support, please use "world" instead') # # self._f0 = None # self._spc = None # self._ap = None # # def analyze(self, x): # """Analyze acoustic features using analyzer # # Parameters # ---------- # x : array # Array of waveform samples # # Returns # ------- # f0 : array, shape (`T`,) # F0 sequence # spc : array, shape (`T`, `fftl / 2 + 1`) # Spectral envelope sequence # ap: array, shape (`T`, `fftl / 2 + 1`) # aperiodicity sequence # """ # # self.x = np.array(x, dtype=np.float) # self._f0, self._spc, self._ap = self.analyzer.analyze(self.x) # # # check non-negative for F0 # self._f0[self._f0 < 0] = 0 # # if np.sum(self._f0) == 0.0: # print("WARNING: F0 values are all zero.") # # return self._f0, self._spc, self._ap # # def analyze_f0(self, x): # """Analyze F0 using analyzer # # Parameters # ---------- # x : array # Array of waveform samples # # Returns # ------- # f0 : array, shape (`T`,) # F0 sequence # """ # # self.x = np.array(x, dtype=np.float) # self._f0 = self.analyzer.analyze_f0(self.x) # # # check non-negative for F0 # self._f0[self._f0 < 0] = 0 # # if np.sum(self._f0) == 0.0: # print("WARNING: F0 values are all zero.") # # return self._f0 # # def mcep(self, dim=24, alpha=0.42): # """Return mel-cepstrum sequence parameterized from spectral envelope # # Parameters # ---------- # dim : int, optional # Dimension of the mel-cepstrum sequence # alpha : int, optional # Parameter of all-path fileter for frequency transformation # # Returns # ------- # mcep : array, shape (`T`, `dim + 1`) # Mel-cepstrum sequence # # """ # self._analyzed_check() # # return pysptk.sp2mc(self._spc, dim, alpha) # # def codeap(self): # """Return coded aperiodicity sequence # # Returns # ------- # codeap : array, shape (`T`, `dim`) # Encoded aperiodicity sequence of the waveform # The `dim` of code ap is defined based on the `fs` as follow: # fs = `16000` : `1` # fs = `22050` : `2` # fs = `44100` : `5` # fs = `48000` : `5` # """ # # self._analyzed_check() # # return pyworld.code_aperiodicity(self._ap, self.fs) # # def npow(self): # """Return normalized power sequence parameterized from spectral envelope # # Returns # ------- # npow: vector, shape (`T`,) # Normalized power sequence of the given waveform # # """ # self._analyzed_check() # # return spc2npow(self._spc) # # def _analyzed_check(self): # if self._f0 is None and self._spc is None and self._ap is None: # raise('Call FeatureExtractor.analyze() before get parameterized features.') . Output only the next line.
feat = FeatureExtractor(analyzer='world', fs=fs)
Continue the code snippet: <|code_start|>from __future__ import division, print_function, absolute_import def get_random_peseudo_mcep(order=24, alpha=0.42): T, N = 100, 513 frames = np.random.rand(T, N) * pysptk.blackman(N) mc = pysptk.mcep(frames, order=order, alpha=alpha) return mc class DistanceTest(unittest.TestCase): def test_melcd(self): org = get_random_peseudo_mcep() tar = get_random_peseudo_mcep() # perform dtw for mel-cd function test <|code_end|> . Use current file imports: import unittest import numpy as np import pysptk from sprocket.util import melcd, estimate_twf and context (classes, functions, or code) from other files: # Path: sprocket/util/distance.py # def melcd(array1, array2): # """Calculate mel-cepstrum distortion # # Calculate mel-cepstrum distortion between the arrays. # This function assumes the shapes of arrays are same. # # Parameters # ---------- # array1, array2 : array, shape (`T`, `dim`) or shape (`dim`) # Arrays of original and target. # # Returns # ------- # mcd : scala, number > 0 # Scala of mel-cepstrum distortion # # """ # if array1.shape != array2.shape: # raise ValueError( # "The shapes of both arrays are different \ # : {} / {}".format(array1.shape, array2.shape)) # # if array1.ndim == 2: # # array based melcd calculation # diff = array1 - array2 # mcd = 10.0 / np.log(10) \ # * np.mean(np.sqrt(2.0 * np.sum(diff ** 2, axis=1))) # elif array1.ndim == 1: # diff = array1 - array2 # mcd = 10.0 / np.log(10) * np.sqrt(2.0 * np.sum(diff ** 2)) # else: # raise ValueError("Dimension mismatch") # # return mcd # # Path: sprocket/util/twf.py # def estimate_twf(orgdata, tardata, distance='melcd', fast=True, otflag=None): # """time warping function estimator # # Parameters # --------- # orgdata : array, shape(`T_org`, `dim`) # Array of source feature # tardata : array, shape(`T_tar`, `dim`) # Array of target feature # distance : str, optional # distance function # `melcd` : mel-cepstrum distortion # fast : bool, optional # Use fastdtw instead of dtw # Default set to `True` # otflag : str, # Perform alignment into either original or target length # `org` : align into original length # `tar` : align into target length # Default set to None # # Returns # --------- # twf : array, shape(`2`, `T`) # Time warping function between original and target # """ # # if distance == 'melcd': # def distance_func(x, y): return melcd(x, y) # else: # raise ValueError('other distance metrics than melcd does not support.') # # if otflag is None: # # use dtw or fastdtw # if fast: # _, path = fastdtw(orgdata, tardata, dist=distance_func) # twf = np.array(path).T # else: # _, _, _, twf = dtw(orgdata, tardata, distance_func) # else: # # use dtw_c to align target/original feature vector # ldim = orgdata.shape[1] - 1 # if otflag == 'org': # _, twf, _, _ = dtw_c.dtw_org_to_trg(tardata, orgdata, # 0, ldim, 5.0, 100.0, 100.0) # else: # _, twf, _, _ = dtw_c.dtw_org_to_trg(orgdata, tardata, # 0, ldim, 5.0, 100.0, 100.0) # twf[:, 1] = np.array(range(twf.shape[0])) # replace target index by frame number # twf = twf.T # if otflag == 'org': # twf = twf[::-1, :] # swap cols # assert twf.shape[0] == orgdata.shape[0] # else: # assert twf.shape[1] == tardata.shape[0] # # return twf . Output only the next line.
def distance_func(x, y): return melcd(x, y)
Given the following code snippet before the placeholder: <|code_start|>from __future__ import division, print_function, absolute_import def get_random_peseudo_mcep(order=24, alpha=0.42): T, N = 100, 513 frames = np.random.rand(T, N) * pysptk.blackman(N) mc = pysptk.mcep(frames, order=order, alpha=alpha) return mc class DistanceTest(unittest.TestCase): def test_melcd(self): org = get_random_peseudo_mcep() tar = get_random_peseudo_mcep() # perform dtw for mel-cd function test def distance_func(x, y): return melcd(x, y) <|code_end|> , predict the next line using imports from the current file: import unittest import numpy as np import pysptk from sprocket.util import melcd, estimate_twf and context including class names, function names, and sometimes code from other files: # Path: sprocket/util/distance.py # def melcd(array1, array2): # """Calculate mel-cepstrum distortion # # Calculate mel-cepstrum distortion between the arrays. # This function assumes the shapes of arrays are same. # # Parameters # ---------- # array1, array2 : array, shape (`T`, `dim`) or shape (`dim`) # Arrays of original and target. # # Returns # ------- # mcd : scala, number > 0 # Scala of mel-cepstrum distortion # # """ # if array1.shape != array2.shape: # raise ValueError( # "The shapes of both arrays are different \ # : {} / {}".format(array1.shape, array2.shape)) # # if array1.ndim == 2: # # array based melcd calculation # diff = array1 - array2 # mcd = 10.0 / np.log(10) \ # * np.mean(np.sqrt(2.0 * np.sum(diff ** 2, axis=1))) # elif array1.ndim == 1: # diff = array1 - array2 # mcd = 10.0 / np.log(10) * np.sqrt(2.0 * np.sum(diff ** 2)) # else: # raise ValueError("Dimension mismatch") # # return mcd # # Path: sprocket/util/twf.py # def estimate_twf(orgdata, tardata, distance='melcd', fast=True, otflag=None): # """time warping function estimator # # Parameters # --------- # orgdata : array, shape(`T_org`, `dim`) # Array of source feature # tardata : array, shape(`T_tar`, `dim`) # Array of target feature # distance : str, optional # distance function # `melcd` : mel-cepstrum distortion # fast : bool, optional # Use fastdtw instead of dtw # Default set to `True` # otflag : str, # Perform alignment into either original or target length # `org` : align into original length # `tar` : align into target length # Default set to None # # Returns # --------- # twf : array, shape(`2`, `T`) # Time warping function between original and target # """ # # if distance == 'melcd': # def distance_func(x, y): return melcd(x, y) # else: # raise ValueError('other distance metrics than melcd does not support.') # # if otflag is None: # # use dtw or fastdtw # if fast: # _, path = fastdtw(orgdata, tardata, dist=distance_func) # twf = np.array(path).T # else: # _, _, _, twf = dtw(orgdata, tardata, distance_func) # else: # # use dtw_c to align target/original feature vector # ldim = orgdata.shape[1] - 1 # if otflag == 'org': # _, twf, _, _ = dtw_c.dtw_org_to_trg(tardata, orgdata, # 0, ldim, 5.0, 100.0, 100.0) # else: # _, twf, _, _ = dtw_c.dtw_org_to_trg(orgdata, tardata, # 0, ldim, 5.0, 100.0, 100.0) # twf[:, 1] = np.array(range(twf.shape[0])) # replace target index by frame number # twf = twf.T # if otflag == 'org': # twf = twf[::-1, :] # swap cols # assert twf.shape[0] == orgdata.shape[0] # else: # assert twf.shape[1] == tardata.shape[0] # # return twf . Output only the next line.
twf = estimate_twf(org, tar, fast=True)
Based on the snippet: <|code_start|>from __future__ import division, print_function, absolute_import class DeltaFunctionsTest(unittest.TestCase): def test_delta(self): data1d = np.random.rand(100) <|code_end|> , predict the immediate next line with the help of imports: import unittest import numpy as np from sprocket.util.delta import delta, construct_static_and_delta_matrix and context (classes, functions, sometimes code) from other files: # Path: sprocket/util/delta.py # def delta(data, win=[-1.0, 1.0, 0]): # """Calculate delta component # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of static matrix sequence. # win: array, optional, shape (`3`) # The shape of window matrix. # Default set to [-1.0, 1.0, 0]. # # Returns # ------- # delta : array, shape (`T`, `dim`) # Array delta matrix sequence. # # """ # # if data.ndim == 1: # # change vector into 1d-array # T = len(data) # dim = data.ndim # data = data.reshape(T, dim) # else: # T, dim = data.shape # # win = np.array(win, dtype=np.float64) # delta = np.zeros((T, dim)) # # delta[0] = win[0] * data[0] + win[1] * data[1] # delta[-1] = win[0] * data[-2] + win[1] * data[-1] # # for i in range(len(win)): # delta[1:T - 1] += win[i] * data[i:T - 2 + i] # # return delta # # def construct_static_and_delta_matrix(T, D, win=[-1.0, 1.0, 0]): # """Calculate static and delta transformation matrix # # Parameters # ---------- # T : scala, `T` # Scala of time length # D : scala, `D` # Scala of the number of dimentsion # win: array, optional, shape (`3`) # The shape of window matrix for delta. # Default set to [-1.0, 1.0, 0]. # # Returns # ------- # W : array, shape (`2 * D * T`, `D * T`) # Array of static and delta transformation matrix. # # """ # # static = [0, 1, 0] # delta = win # assert len(static) == len(delta) # # # generate full W # DT = D * T # ones = np.ones(DT) # row = np.arange(2 * DT).reshape(2 * T, D) # static_row = row[::2] # delta_row = row[1::2] # col = np.arange(DT) # # data = np.array([ones * static[0], ones * static[1], # ones * static[2], ones * delta[0], # ones * delta[1], ones * delta[2]]).flatten() # row = np.array([[static_row] * 3, [delta_row] * 3]).flatten() # col = np.array([[col - D, col, col + D] * 2]).flatten() # # # remove component at first and end frame # valid_idx = np.logical_not(np.logical_or(col < 0, col >= DT)) # # W = scipy.sparse.csr_matrix( # (data[valid_idx], (row[valid_idx], col[valid_idx])), shape=(2 * DT, DT)) # W.eliminate_zeros() # # return W . Output only the next line.
delta1d = delta(data1d)
Continue the code snippet: <|code_start|>from __future__ import division, print_function, absolute_import class DeltaFunctionsTest(unittest.TestCase): def test_delta(self): data1d = np.random.rand(100) delta1d = delta(data1d) assert len(data1d) == len(delta1d) data2d = data1d.reshape(50, 2) delta2d = delta(data2d) assert delta2d.shape[0] == data2d.shape[0] assert delta2d.shape[1] == data2d.shape[1] def test_construct_W_matrix(self): T, D = 100, 4 <|code_end|> . Use current file imports: import unittest import numpy as np from sprocket.util.delta import delta, construct_static_and_delta_matrix and context (classes, functions, or code) from other files: # Path: sprocket/util/delta.py # def delta(data, win=[-1.0, 1.0, 0]): # """Calculate delta component # # Parameters # ---------- # data : array, shape (`T`, `dim`) # Array of static matrix sequence. # win: array, optional, shape (`3`) # The shape of window matrix. # Default set to [-1.0, 1.0, 0]. # # Returns # ------- # delta : array, shape (`T`, `dim`) # Array delta matrix sequence. # # """ # # if data.ndim == 1: # # change vector into 1d-array # T = len(data) # dim = data.ndim # data = data.reshape(T, dim) # else: # T, dim = data.shape # # win = np.array(win, dtype=np.float64) # delta = np.zeros((T, dim)) # # delta[0] = win[0] * data[0] + win[1] * data[1] # delta[-1] = win[0] * data[-2] + win[1] * data[-1] # # for i in range(len(win)): # delta[1:T - 1] += win[i] * data[i:T - 2 + i] # # return delta # # def construct_static_and_delta_matrix(T, D, win=[-1.0, 1.0, 0]): # """Calculate static and delta transformation matrix # # Parameters # ---------- # T : scala, `T` # Scala of time length # D : scala, `D` # Scala of the number of dimentsion # win: array, optional, shape (`3`) # The shape of window matrix for delta. # Default set to [-1.0, 1.0, 0]. # # Returns # ------- # W : array, shape (`2 * D * T`, `D * T`) # Array of static and delta transformation matrix. # # """ # # static = [0, 1, 0] # delta = win # assert len(static) == len(delta) # # # generate full W # DT = D * T # ones = np.ones(DT) # row = np.arange(2 * DT).reshape(2 * T, D) # static_row = row[::2] # delta_row = row[1::2] # col = np.arange(DT) # # data = np.array([ones * static[0], ones * static[1], # ones * static[2], ones * delta[0], # ones * delta[1], ones * delta[2]]).flatten() # row = np.array([[static_row] * 3, [delta_row] * 3]).flatten() # col = np.array([[col - D, col, col + D] * 2]).flatten() # # # remove component at first and end frame # valid_idx = np.logical_not(np.logical_or(col < 0, col >= DT)) # # W = scipy.sparse.csr_matrix( # (data[valid_idx], (row[valid_idx], col[valid_idx])), shape=(2 * DT, DT)) # W.eliminate_zeros() # # return W . Output only the next line.
W = construct_static_and_delta_matrix(T, D)
Given snippet: <|code_start|> def estimate_twf(orgdata, tardata, distance='melcd', fast=True, otflag=None): """time warping function estimator Parameters --------- orgdata : array, shape(`T_org`, `dim`) Array of source feature tardata : array, shape(`T_tar`, `dim`) Array of target feature distance : str, optional distance function `melcd` : mel-cepstrum distortion fast : bool, optional Use fastdtw instead of dtw Default set to `True` otflag : str, Perform alignment into either original or target length `org` : align into original length `tar` : align into target length Default set to None Returns --------- twf : array, shape(`2`, `T`) Time warping function between original and target """ if distance == 'melcd': <|code_end|> , continue by predicting the next line. Consider current file imports: import numpy as np from dtw import dtw from fastdtw import fastdtw from dtw_c import dtw_c from sprocket.util import melcd and context: # Path: sprocket/util/distance.py # def melcd(array1, array2): # """Calculate mel-cepstrum distortion # # Calculate mel-cepstrum distortion between the arrays. # This function assumes the shapes of arrays are same. # # Parameters # ---------- # array1, array2 : array, shape (`T`, `dim`) or shape (`dim`) # Arrays of original and target. # # Returns # ------- # mcd : scala, number > 0 # Scala of mel-cepstrum distortion # # """ # if array1.shape != array2.shape: # raise ValueError( # "The shapes of both arrays are different \ # : {} / {}".format(array1.shape, array2.shape)) # # if array1.ndim == 2: # # array based melcd calculation # diff = array1 - array2 # mcd = 10.0 / np.log(10) \ # * np.mean(np.sqrt(2.0 * np.sum(diff ** 2, axis=1))) # elif array1.ndim == 1: # diff = array1 - array2 # mcd = 10.0 / np.log(10) * np.sqrt(2.0 * np.sum(diff ** 2)) # else: # raise ValueError("Dimension mismatch") # # return mcd which might include code, classes, or functions. Output only the next line.
def distance_func(x, y): return melcd(x, y)
Predict the next line for this snippet: <|code_start|> parser.set_description(__doc__.strip()) parser.add_option("-r", "-R", dest="rel_ids", type='int', metavar="<number>", help="limit consistency check to one or more associations", action="append", default=[]) parser.add_option("-k", dest="kinds", type='string', metavar="<key letter>", help="limit check for uniqueness constraint violations to one or more classes", action="append", default=[]) parser.add_option("-g", "--globals", dest="globals", help="add builtin global data types automatically, e.g. boolean, integer and real", action="store_true", default=False) parser.add_option("-v", "--verbosity", dest='verbosity', action="count", help="increase debug logging level", default=1) (opts, args) = parser.parse_args(args) if len(args) == 0: parser.print_help() sys.exit(1) levels = { 0: logging.ERROR, 1: logging.WARNING, 2: logging.INFO, 3: logging.DEBUG, } logging.basicConfig(level=levels.get(opts.verbosity, logging.DEBUG)) <|code_end|> with the help of current file imports: import logging import optparse import sys import xtuml from bridgepoint import ooaofooa and context from other files: # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) , which may contain function names, class names, or code. Output only the next line.
loader = ooaofooa.Loader(load_globals=opts.globals)
Predict the next line after this snippet: <|code_start|> ); CREATE ROP REF_ID R1 FROM MC Assoc (one_side_ID) PHRASE 'one' TO 1 Class (ID) PHRASE 'other'; CREATE ROP REF_ID R1 FROM MC Assoc (other_side_ID) PHRASE 'other' TO 1 Class (ID) PHRASE 'one'; ''' def setUp(self): l = xtuml.ModelLoader() l.input(self.__class__.__doc__) self.m = l.build_metamodel() def tearDown(self): del self.m def test_serialize(self): s1 = xtuml.serialize(self.m) l = xtuml.ModelLoader() l.input(s1) s2 = xtuml.serialize(l.build_metamodel()) self.assertEqual(s1, s2) def test_relate_assoc_to_class_across_one(self): cls = self.m.new('Class') assoc = self.m.new('Assoc') <|code_end|> using the current file's imports: import unittest import xtuml from xtuml import relate from xtuml import navigate_one as one and any relevant context from other files: # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) . Output only the next line.
self.assertTrue(relate(assoc, cls, 1, 'one'))
Using the snippet: <|code_start|> cls = self.m.new('Class') assoc = self.m.new('Assoc') self.assertTrue(relate(assoc, cls, 1, 'one')) self.assertEqual(assoc.one_side_ID, cls.ID) def test_relate_assoc_to_class_across_other(self): cls = self.m.new('Class') assoc = self.m.new('Assoc') self.assertTrue(relate(assoc, cls, 1, 'other')) self.assertEqual(assoc.other_side_ID, cls.ID) def test_relate_class_to_assoc_across_one(self): cls = self.m.new('Class') assoc = self.m.new('Assoc') self.assertTrue(relate(cls, assoc, 1, 'one')) self.assertEqual(assoc.other_side_ID, cls.ID) def test_relate_class_to_assoc_across_other(self): cls = self.m.new('Class') assoc = self.m.new('Assoc') self.assertTrue(relate(cls, assoc, 1, 'other')) self.assertEqual(assoc.one_side_ID, cls.ID) def test_navigate_assoc_to_class_across_one(self): cls = self.m.new('Class') assoc = self.m.new('Assoc', other_side_ID=cls.ID) <|code_end|> , determine the next line of code. You have imports: import unittest import xtuml from xtuml import relate from xtuml import navigate_one as one and context (class names, function names, or code) available: # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) . Output only the next line.
self.assertTrue(one(assoc).Class[1, 'one']())
Predict the next line after this snippet: <|code_start|># Copyright (C) 2017 John Törnblom # # This file is part of pyxtuml. # # pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class MyWalker(xtuml.Walker): ''' Walk the ooaofooa packageable element tree-like structure ''' def accept_S_SYS(self, inst): ''' A System Model contains top-level packages ''' <|code_end|> using the current file's imports: import sys import xtuml from xtuml import navigate_many as many from xtuml import navigate_subtype as subtype from bridgepoint import ooaofooa and any relevant context from other files: # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_subtype(supertype, rel_id): # ''' # Perform a navigation from *supertype* to its subtype across *rel_id*. The # navigated association must be modeled as a subtype-supertype association. # # The return value will an instance or None. # ''' # if not supertype: # return # # if isinstance(rel_id, int): # rel_id = 'R%d' % rel_id # # metaclass = get_metaclass(supertype) # for kind, rel_id_candidate, _ in metaclass.links: # if rel_id != rel_id_candidate: # continue # # subtype = navigate_one(supertype).nav(kind, rel_id)() # if subtype: # return subtype # # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) . Output only the next line.
for child in many(inst).EP_PKG[1401]():
Predict the next line after this snippet: <|code_start|># version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class MyWalker(xtuml.Walker): ''' Walk the ooaofooa packageable element tree-like structure ''' def accept_S_SYS(self, inst): ''' A System Model contains top-level packages ''' for child in many(inst).EP_PKG[1401](): self.accept(child) def accept_PE_PE(self, inst): ''' Packeable Element is the supertype of something packageable ''' <|code_end|> using the current file's imports: import sys import xtuml from xtuml import navigate_many as many from xtuml import navigate_subtype as subtype from bridgepoint import ooaofooa and any relevant context from other files: # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_subtype(supertype, rel_id): # ''' # Perform a navigation from *supertype* to its subtype across *rel_id*. The # navigated association must be modeled as a subtype-supertype association. # # The return value will an instance or None. # ''' # if not supertype: # return # # if isinstance(rel_id, int): # rel_id = 'R%d' % rel_id # # metaclass = get_metaclass(supertype) # for kind, rel_id_candidate, _ in metaclass.links: # if rel_id != rel_id_candidate: # continue # # subtype = navigate_one(supertype).nav(kind, rel_id)() # if subtype: # return subtype # # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) . Output only the next line.
self.accept(subtype(inst, 8001))
Predict the next line after this snippet: <|code_start|> class MyPrinter(xtuml.NodePrintVisitor): def render_PE_PE(self, inst): '''suppress instances of PE_PE''' pass def render_O_IOBJ(self, inst): '''suppress imported classes''' pass def render_R_REL(self, inst): return 'R%d (Association)' % inst.Numb def default_render(self, inst): if hasattr(inst, 'Name'): return '%s (%s)' % (inst.Name, type(inst).__name__) else: return type(inst).__name__ if len(sys.argv) < 2: print('') print(' usage: %s <path to bridgepoint model folder>' % sys.argv[0]) print('') sys.exit(1) <|code_end|> using the current file's imports: import sys import xtuml from xtuml import navigate_many as many from xtuml import navigate_subtype as subtype from bridgepoint import ooaofooa and any relevant context from other files: # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_subtype(supertype, rel_id): # ''' # Perform a navigation from *supertype* to its subtype across *rel_id*. The # navigated association must be modeled as a subtype-supertype association. # # The return value will an instance or None. # ''' # if not supertype: # return # # if isinstance(rel_id, int): # rel_id = 'R%d' % rel_id # # metaclass = get_metaclass(supertype) # for kind, rel_id_candidate, _ in metaclass.links: # if rel_id != rel_id_candidate: # continue # # subtype = navigate_one(supertype).nav(kind, rel_id)() # if subtype: # return subtype # # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) . Output only the next line.
m = ooaofooa.load_metamodel(sys.argv[1:])
Next line prediction: <|code_start|> class ActionTextGenWalker(Walker): ''' Walk the bridgepoint metamodel and translate action code to its textual representation. ''' def __init__(self, level=-1): Walker.__init__(self) self._buf = '' self._lvl = level def __str__(self): return self._buf def __repr__(self): return self._buf def buf(self, value, *args): self._buf += value self._buf += ''.join(args) def buf_linebreak(self, *args): self._buf += ''.join(args) self._buf += '\n' self._buf += ' ' * self._lvl def default_accept(self, inst): print(inst.__class__.__name__) def accept_S_BRG(self, inst): <|code_end|> . Use current file imports: (import logging from xtuml import navigate_one as one from xtuml import navigate_any as any from xtuml import navigate_many as many from xtuml import navigate_subtype as subtype from xtuml.tools import Walker) and context including class names, function names, or small code snippets from other files: # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_subtype(supertype, rel_id): # ''' # Perform a navigation from *supertype* to its subtype across *rel_id*. The # navigated association must be modeled as a subtype-supertype association. # # The return value will an instance or None. # ''' # if not supertype: # return # # if isinstance(rel_id, int): # rel_id = 'R%d' % rel_id # # metaclass = get_metaclass(supertype) # for kind, rel_id_candidate, _ in metaclass.links: # if rel_id != rel_id_candidate: # continue # # subtype = navigate_one(supertype).nav(kind, rel_id)() # if subtype: # return subtype # # Path: xtuml/tools.py # class Walker(object): # ''' # A walker may be used to walk a tree. # ''' # def __init__(self): # #: A list of *visitors* to notify when visiting nodes. # self.visitors = list() # # def accept(self, node, **kwargs): # ''' # Invoke the visitors before and after decending down the tree. # The walker will also try to invoke a method matching the pattern # *accept_<type name>*, where <type name> is the name of the accepted # *node*. # ''' # if node is None: # return # # for v in self.visitors: # v.enter(node) # # name = 'accept_' + node.__class__.__name__ # fn = getattr(self, name, self.default_accept) # r = fn(node, **kwargs) # # for v in self.visitors: # v.leave(node) # # return r # # def default_accept(self, node, **kwargs): # ''' # The default accept behaviour is to decend into the iterable member # *node.children* (if available). # ''' # if not hasattr(node, 'children'): # return # # for child in node.children: # self.accept(child, **kwargs) . Output only the next line.
self.accept(one(inst).ACT_BRB[697].ACT_ACT[698]())
Predict the next line for this snippet: <|code_start|> for act_el in sorted(many(inst).ACT_EL[682](), key=by_position): self.accept(act_el) self.accept(one(inst).ACT_E[683]()) self.buf('end if') def accept_ACT_EL(self, inst): self.buf('elif ') self.accept(one(inst).V_VAL[659]()) self.accept(one(inst).ACT_BLK[658]()) def accept_ACT_E(self, inst): self.buf('else') self.accept(one(inst).ACT_BLK[606]()) def accept_ACT_FOR(self, inst): self.buf('for each ') self.accept(one(inst).V_VAR[614]()) self.buf(' in ') self.accept(one(inst).V_VAR[652]()) self.accept(one(inst).ACT_BLK[605]()) self.buf('end for') def accept_ACT_FNC(self, inst): s_sync = one(inst).S_SYNC[675]() self.buf('::', s_sync.Name) self.buf('(') first_filter = lambda sel: one(sel).V_PAR[816, 'succeeds']() is None <|code_end|> with the help of current file imports: import logging from xtuml import navigate_one as one from xtuml import navigate_any as any from xtuml import navigate_many as many from xtuml import navigate_subtype as subtype from xtuml.tools import Walker and context from other files: # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_subtype(supertype, rel_id): # ''' # Perform a navigation from *supertype* to its subtype across *rel_id*. The # navigated association must be modeled as a subtype-supertype association. # # The return value will an instance or None. # ''' # if not supertype: # return # # if isinstance(rel_id, int): # rel_id = 'R%d' % rel_id # # metaclass = get_metaclass(supertype) # for kind, rel_id_candidate, _ in metaclass.links: # if rel_id != rel_id_candidate: # continue # # subtype = navigate_one(supertype).nav(kind, rel_id)() # if subtype: # return subtype # # Path: xtuml/tools.py # class Walker(object): # ''' # A walker may be used to walk a tree. # ''' # def __init__(self): # #: A list of *visitors* to notify when visiting nodes. # self.visitors = list() # # def accept(self, node, **kwargs): # ''' # Invoke the visitors before and after decending down the tree. # The walker will also try to invoke a method matching the pattern # *accept_<type name>*, where <type name> is the name of the accepted # *node*. # ''' # if node is None: # return # # for v in self.visitors: # v.enter(node) # # name = 'accept_' + node.__class__.__name__ # fn = getattr(self, name, self.default_accept) # r = fn(node, **kwargs) # # for v in self.visitors: # v.leave(node) # # return r # # def default_accept(self, node, **kwargs): # ''' # The default accept behaviour is to decend into the iterable member # *node.children* (if available). # ''' # if not hasattr(node, 'children'): # return # # for child in node.children: # self.accept(child, **kwargs) , which may contain function names, class names, or code. Output only the next line.
self.accept(any(inst).V_PAR[669](first_filter))
Given snippet: <|code_start|> self.buf('->', o_obj.Key_Lett, '[R', str(r_rel.Numb)) if inst.Rel_Phrase: self.buf('.', inst.Rel_Phrase) self.buf(']') self.accept(one(inst).ACT_LNK[604, 'precedes']()) def accept_ACT_AI(self, inst): if one(inst).V_VAL[609].V_MSV[801](): self.buf('send ') else: self.buf('assign ') self.accept(one(inst).V_VAL[689]()) self.buf(' = ') self.accept(one(inst).V_VAL[609]()) def accept_ACT_WHL(self, inst): self.buf('while ') self.accept(one(inst).V_VAL[626]()) self.accept(one(inst).ACT_BLK[608]()) self.buf('end while') def accept_ACT_IF(self, inst): by_position = lambda inst: (one(inst).ACT_SMT[603]().LineNumber, one(inst).ACT_SMT[603]().StartPosition) self.buf('if ') self.accept(one(inst).V_VAL[625]()) self.accept(one(inst).ACT_BLK[607]()) <|code_end|> , continue by predicting the next line. Consider current file imports: import logging from xtuml import navigate_one as one from xtuml import navigate_any as any from xtuml import navigate_many as many from xtuml import navigate_subtype as subtype from xtuml.tools import Walker and context: # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_subtype(supertype, rel_id): # ''' # Perform a navigation from *supertype* to its subtype across *rel_id*. The # navigated association must be modeled as a subtype-supertype association. # # The return value will an instance or None. # ''' # if not supertype: # return # # if isinstance(rel_id, int): # rel_id = 'R%d' % rel_id # # metaclass = get_metaclass(supertype) # for kind, rel_id_candidate, _ in metaclass.links: # if rel_id != rel_id_candidate: # continue # # subtype = navigate_one(supertype).nav(kind, rel_id)() # if subtype: # return subtype # # Path: xtuml/tools.py # class Walker(object): # ''' # A walker may be used to walk a tree. # ''' # def __init__(self): # #: A list of *visitors* to notify when visiting nodes. # self.visitors = list() # # def accept(self, node, **kwargs): # ''' # Invoke the visitors before and after decending down the tree. # The walker will also try to invoke a method matching the pattern # *accept_<type name>*, where <type name> is the name of the accepted # *node*. # ''' # if node is None: # return # # for v in self.visitors: # v.enter(node) # # name = 'accept_' + node.__class__.__name__ # fn = getattr(self, name, self.default_accept) # r = fn(node, **kwargs) # # for v in self.visitors: # v.leave(node) # # return r # # def default_accept(self, node, **kwargs): # ''' # The default accept behaviour is to decend into the iterable member # *node.children* (if available). # ''' # if not hasattr(node, 'children'): # return # # for child in node.children: # self.accept(child, **kwargs) which might include code, classes, or functions. Output only the next line.
for act_el in sorted(many(inst).ACT_EL[682](), key=by_position):
Next line prediction: <|code_start|> def accept_SPR_PS(self, inst): self.accept(one(inst).ACT_PSB[686].ACT_ACT[698]()) def accept_SPR_RO(self, inst): self.accept(one(inst).ACT_ROB[685].ACT_ACT[698]()) def accept_SPR_RS(self, inst): self.accept(one(inst).ACT_RSB[684].ACT_ACT[698]()) def accept_ACT_ACT(self, inst): self.accept(one(inst).ACT_BLK[666]()) def accept_ACT_BLK(self, inst): self._lvl += 1 if self._lvl: self.buf_linebreak() first_filter = lambda sel: (not one(sel).ACT_SMT[661, 'precedes']() and not one(sel).ACT_EL[603]() and not one(sel).ACT_E[603]()) act_smt = one(inst).ACT_SMT[602](first_filter) while act_smt: self.accept(act_smt) act_smt = one(act_smt).ACT_SMT[661, 'succeeds']() self._lvl -= 1 self.buf_linebreak() def accept_ACT_SMT(self, inst): <|code_end|> . Use current file imports: (import logging from xtuml import navigate_one as one from xtuml import navigate_any as any from xtuml import navigate_many as many from xtuml import navigate_subtype as subtype from xtuml.tools import Walker) and context including class names, function names, or small code snippets from other files: # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_subtype(supertype, rel_id): # ''' # Perform a navigation from *supertype* to its subtype across *rel_id*. The # navigated association must be modeled as a subtype-supertype association. # # The return value will an instance or None. # ''' # if not supertype: # return # # if isinstance(rel_id, int): # rel_id = 'R%d' % rel_id # # metaclass = get_metaclass(supertype) # for kind, rel_id_candidate, _ in metaclass.links: # if rel_id != rel_id_candidate: # continue # # subtype = navigate_one(supertype).nav(kind, rel_id)() # if subtype: # return subtype # # Path: xtuml/tools.py # class Walker(object): # ''' # A walker may be used to walk a tree. # ''' # def __init__(self): # #: A list of *visitors* to notify when visiting nodes. # self.visitors = list() # # def accept(self, node, **kwargs): # ''' # Invoke the visitors before and after decending down the tree. # The walker will also try to invoke a method matching the pattern # *accept_<type name>*, where <type name> is the name of the accepted # *node*. # ''' # if node is None: # return # # for v in self.visitors: # v.enter(node) # # name = 'accept_' + node.__class__.__name__ # fn = getattr(self, name, self.default_accept) # r = fn(node, **kwargs) # # for v in self.visitors: # v.leave(node) # # return r # # def default_accept(self, node, **kwargs): # ''' # The default accept behaviour is to decend into the iterable member # *node.children* (if available). # ''' # if not hasattr(node, 'children'): # return # # for child in node.children: # self.accept(child, **kwargs) . Output only the next line.
self.accept(subtype(inst, 603))
Given snippet: <|code_start|> type_name = 'xs:integer' elif s_dt.name == 'real': type_name = 'xs:decimal' elif s_dt.name == 'string': type_name = 'xs:string' elif s_dt.name == 'unique_id': type_name = 'xs:integer' else: type_name = None if type_name: mapped_type = ET.Element('xs:simpleType', name=s_dt.name) ET.SubElement(mapped_type, 'xs:restriction', base=type_name) return mapped_type def build_enum_type(s_edt): ''' Build an xsd simpleType out of a S_EDT. ''' s_dt = nav_one(s_edt).S_DT[17]() enum = ET.Element('xs:simpleType', name=s_dt.name) enum_list = ET.SubElement(enum, 'xs:restriction', base='xs:string') first_filter = lambda selected: not nav_one(selected).S_ENUM[56, 'succeeds']() <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import optparse import logging import xtuml import xml.etree.ElementTree as ET import xml.dom.minidom from xtuml import navigate_any as nav_any from xtuml import navigate_any as nav_one from xtuml import navigate_many as nav_many from bridgepoint import ooaofooa and context: # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) which might include code, classes, or functions. Output only the next line.
s_enum = nav_any(s_edt).S_ENUM[27](first_filter)
Based on the snippet: <|code_start|># pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. ''' Generate an xsd schema file for an xtUML model. The arguments are either xtuml files, or folders containing *.xtuml files. Note that some type of attributes are not supported, e.g. instance handles or timers. ''' logger = logging.getLogger('gen_xsd_schema') def get_type_name(s_dt): ''' get the xsd name of a S_DT ''' <|code_end|> , predict the immediate next line with the help of imports: import sys import optparse import logging import xtuml import xml.etree.ElementTree as ET import xml.dom.minidom from xtuml import navigate_any as nav_any from xtuml import navigate_any as nav_one from xtuml import navigate_many as nav_many from bridgepoint import ooaofooa and context (classes, functions, sometimes code) from other files: # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) . Output only the next line.
s_cdt = nav_one(s_dt).S_CDT[17]()
Given snippet: <|code_start|> return user def build_type(s_dt): ''' Build a partial xsd tree out of a S_DT and its sub types S_CDT, S_EDT, S_SDT and S_UDT. ''' s_cdt = nav_one(s_dt).S_CDT[17]() if s_cdt: return build_core_type(s_cdt) s_edt = nav_one(s_dt).S_EDT[17]() if s_edt: return build_enum_type(s_edt) s_udt = nav_one(s_dt).S_UDT[17]() if s_udt: return build_user_type(s_udt) # s_sdt = nav_one(s_dt).S_SDT[17]() # if s_sdt: # return build_struct_type(s_sdt) def build_class(o_obj): ''' Build an xsd complex element out of a O_OBJ, including its O_ATTR. ''' cls = ET.Element('xs:element', name=o_obj.key_lett, minOccurs='0', maxOccurs='unbounded') attributes = ET.SubElement(cls, 'xs:complexType') <|code_end|> , continue by predicting the next line. Consider current file imports: import sys import optparse import logging import xtuml import xml.etree.ElementTree as ET import xml.dom.minidom from xtuml import navigate_any as nav_any from xtuml import navigate_any as nav_one from xtuml import navigate_many as nav_many from bridgepoint import ooaofooa and context: # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) which might include code, classes, or functions. Output only the next line.
for o_attr in nav_many(o_obj).O_ATTR[102]():
Here is a snippet: <|code_start|> def build_class(o_obj): ''' Build an xsd complex element out of a O_OBJ, including its O_ATTR. ''' cls = ET.Element('xs:element', name=o_obj.key_lett, minOccurs='0', maxOccurs='unbounded') attributes = ET.SubElement(cls, 'xs:complexType') for o_attr in nav_many(o_obj).O_ATTR[102](): o_attr_ref = get_refered_attribute(o_attr) s_dt = nav_one(o_attr_ref).S_DT[114]() while nav_one(s_dt).S_UDT[17](): s_dt = nav_one(s_dt).S_UDT[17].S_DT[18]() type_name = get_type_name(s_dt) if type_name and not nav_one(o_attr).O_BATTR[106].O_DBATTR[107](): ET.SubElement(attributes, 'xs:attribute', name=o_attr.name, type=type_name) else: logger.warning('Omitting %s.%s' % (o_obj.key_lett, o_attr.Name)) return cls def build_component(m, c_c): ''' Build an xsd complex element out of a C_C, including its packaged S_DT and O_OBJ. ''' component = ET.Element('xs:element', name=c_c.name) classes = ET.SubElement(component, 'xs:complexType') classes = ET.SubElement(classes, 'xs:sequence') <|code_end|> . Write the next line using the current file imports: import sys import optparse import logging import xtuml import xml.etree.ElementTree as ET import xml.dom.minidom from xtuml import navigate_any as nav_any from xtuml import navigate_any as nav_one from xtuml import navigate_many as nav_many from bridgepoint import ooaofooa and context from other files: # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_any(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return an instance or None. # ''' # return NavOneChain(instance_or_set) # # Path: xtuml/meta.py # def navigate_many(instance_or_set): # ''' # Initialize a navigation from an instance, or a set of instances, to # associated instances across a one-to-many or many-to-many association. # # The resulting query will return a set of instances. # ''' # return NavChain(instance_or_set) # # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) , which may include functions, classes, or code. Output only the next line.
scope_filter = lambda selected: ooaofooa.is_contained_in(selected, c_c)
Here is a snippet: <|code_start|># encoding: utf-8 # Copyright (C) 2017 John Törnblom # # This file is part of pyxtuml. # # pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class TestCreate(PrebuildFunctionTestCase): def setUp(self): PrebuildFunctionTestCase.setUp(self) pe_pe = self.metamodel.new('PE_PE') o_obj = self.metamodel.new('O_OBJ', Key_Lett='A') relate(pe_pe, o_obj, 8001) <|code_end|> . Write the next line using the current file imports: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one from xtuml import relate import logging import unittest and context from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True , which may include functions, classes, or code. Output only the next line.
@prebuild_docstring
Given the following code snippet before the placeholder: <|code_start|># License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class TestCreate(PrebuildFunctionTestCase): def setUp(self): PrebuildFunctionTestCase.setUp(self) pe_pe = self.metamodel.new('PE_PE') o_obj = self.metamodel.new('O_OBJ', Key_Lett='A') relate(pe_pe, o_obj, 8001) @prebuild_docstring def test_create_object(self): ''' create object instance inst of A; ''' act_cr = self.metamodel.select_one('ACT_CR') self.assertTrue(act_cr.is_implicit) <|code_end|> , predict the next line using imports from the current file: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one from xtuml import relate import logging import unittest and context including class names, function names, and sometimes code from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True . Output only the next line.
act_smt = one(act_cr).ACT_SMT[603]()
Predict the next line after this snippet: <|code_start|># encoding: utf-8 # Copyright (C) 2017 John Törnblom # # This file is part of pyxtuml. # # pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class TestCreate(PrebuildFunctionTestCase): def setUp(self): PrebuildFunctionTestCase.setUp(self) pe_pe = self.metamodel.new('PE_PE') o_obj = self.metamodel.new('O_OBJ', Key_Lett='A') <|code_end|> using the current file's imports: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one from xtuml import relate import logging import unittest and any relevant context from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True . Output only the next line.
relate(pe_pe, o_obj, 8001)
Predict the next line after this snippet: <|code_start|># encoding: utf-8 # Copyright (C) 2017 John Törnblom # # This file is part of pyxtuml. # # pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class TestAssign(PrebuildFunctionTestCase): @prebuild_docstring def test_positive_integer(self): '''assign x = 1;''' act_ai = self.metamodel.select_one('ACT_AI') self.assertIsNotNone(act_ai) <|code_end|> using the current file's imports: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one import logging import unittest and any relevant context from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) . Output only the next line.
act_smt = one(act_ai).ACT_SMT[603]()
Predict the next line after this snippet: <|code_start|>#!/usr/bin/env python # encoding: utf-8 # Copyright (C) 2017 John Törnblom # # This file is part of pyxtuml. # # pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. m = ooaofooa.empty_model() # # Create top-level package (External Entities - generated by pyxtuml) # ep_pkg = m.new('EP_PKG', Name='External Entities - generated by pyxtuml') pe_pe = m.new('PE_PE', Visibility=True, type=7) <|code_end|> using the current file's imports: import xtuml from bridgepoint import ooaofooa from xtuml import relate from xtuml import where_eq as where and any relevant context from other files: # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True # # Path: xtuml/meta.py # def where_eq(**kwargs): # ''' # Return a where-clause that filters out instances based on named # keywords. # # Usage example: # # >>> from xtuml import where_eq as where # >>> m = xtuml.load_metamodel('db.sql') # >>> inst = m.select_any('My_Modeled_Class', where(My_Number=5)) # ''' # return WhereEqual(kwargs) . Output only the next line.
relate(pe_pe, ep_pkg, 8001)
Given the code snippet: <|code_start|># pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. m = ooaofooa.empty_model() # # Create top-level package (External Entities - generated by pyxtuml) # ep_pkg = m.new('EP_PKG', Name='External Entities - generated by pyxtuml') pe_pe = m.new('PE_PE', Visibility=True, type=7) relate(pe_pe, ep_pkg, 8001) # # Create an external entity (My_External_Entity) # s_ee = m.new('S_EE', Name='My_External_Entity', Key_Lett='My_External_Entity') pe_pe = m.new('PE_PE', Visibility=True, type=5) relate(s_ee, pe_pe, 8001) relate(pe_pe, ep_pkg, 8000) # # Create a bridge operation (My_Bridge_Operation: boolean) # <|code_end|> , generate the next line using the imports in this file: import xtuml from bridgepoint import ooaofooa from xtuml import relate from xtuml import where_eq as where and context (functions, classes, or occasionally code) from other files: # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True # # Path: xtuml/meta.py # def where_eq(**kwargs): # ''' # Return a where-clause that filters out instances based on named # keywords. # # Usage example: # # >>> from xtuml import where_eq as where # >>> m = xtuml.load_metamodel('db.sql') # >>> inst = m.select_any('My_Modeled_Class', where(My_Number=5)) # ''' # return WhereEqual(kwargs) . Output only the next line.
s_dt = m.select_one('S_DT', where(Name='boolean'))
Next line prediction: <|code_start|># encoding: utf-8 # Copyright (C) 2017 John Törnblom # # This file is part of pyxtuml. # # pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class TestConstLiterals(PrebuildFunctionTestCase): @prebuild_docstring def test_positive_integer(self): '''return 1;''' act_ret = self.metamodel.select_one('ACT_RET') self.assertIsNotNone(act_ret) <|code_end|> . Use current file imports: (from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one import logging import unittest) and context including class names, function names, or small code snippets from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) . Output only the next line.
act_smt = one(act_ret).ACT_SMT[603]()
Given the following code snippet before the placeholder: <|code_start|># encoding: utf-8 # Copyright (C) 2017 John Törnblom # # This file is part of pyxtuml. # # pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class TestControl(PrebuildFunctionTestCase): @prebuild_docstring def testControlStop(self): '''control stop;''' act_ctl = self.metamodel.select_one('ACT_CTL') self.assertIsNotNone(act_ctl) <|code_end|> , predict the next line using imports from the current file: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one import logging import unittest and context including class names, function names, and sometimes code from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) . Output only the next line.
act_smt = one(act_ctl).ACT_SMT[603]()
Based on the snippet: <|code_start|> relate(self.metamodel.new('PE_PE'), r3, 8001) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r1, 201) relate(r_oir, a, 201) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r1, 201) relate(r_oir, c, 201) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r2, 201) relate(r_oir, a, 201) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r2, 201) relate(r_oir, b, 201) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r3, 201) relate(r_oir, a, 201) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r3, 201) relate(r_oir, b, 201) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r3, 201) relate(r_oir, c, 201) <|code_end|> , predict the immediate next line with the help of imports: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one from xtuml import relate import logging import unittest and context (classes, functions, sometimes code) from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True . Output only the next line.
@prebuild_docstring
Based on the snippet: <|code_start|> r_oir = self.metamodel.new('R_OIR') relate(r_oir, r2, 201) relate(r_oir, a, 201) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r2, 201) relate(r_oir, b, 201) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r3, 201) relate(r_oir, a, 201) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r3, 201) relate(r_oir, b, 201) r_oir = self.metamodel.new('R_OIR') relate(r_oir, r3, 201) relate(r_oir, c, 201) @prebuild_docstring def test_relate(self): ''' create object instance a of A; create object instance b of B; relate a to b across R2; ''' act_rel = self.metamodel.select_one('ACT_REL') self.assertFalse(act_rel.relationship_phrase) <|code_end|> , predict the immediate next line with the help of imports: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one from xtuml import relate import logging import unittest and context (classes, functions, sometimes code) from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True . Output only the next line.
act_smt = one(act_rel).ACT_SMT[603]()
Using the snippet: <|code_start|># encoding: utf-8 # Copyright (C) 2017 John Törnblom # # This file is part of pyxtuml. # # pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class TestRelation(PrebuildFunctionTestCase): def setUp(self): PrebuildFunctionTestCase.setUp(self) pe_pe = self.metamodel.new('PE_PE') a = self.metamodel.new('O_OBJ', Key_Lett='A') <|code_end|> , determine the next line of code. You have imports: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one from xtuml import relate import logging import unittest and context (class names, function names, or code) available: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True . Output only the next line.
relate(pe_pe, a, 8001)
Given snippet: <|code_start|>INSERT INTO GD_SHP VALUES ("8d93b8a9-a6fe-4f59-8997-dabb2df460a0"); INSERT INTO GD_NCS VALUES ("8d93b8a9-a6fe-4f59-8997-dabb2df460a0"); INSERT INTO DIM_ND VALUES (200.000000, 150.000000, "8d93b8a9-a6fe-4f59-8997-dabb2df460a0"); INSERT INTO DIM_GE VALUES (0.000000, 0.000000, "8d93b8a9-a6fe-4f59-8997-dabb2df460a0", "00000000-0000-0000-0000-000000000000"); INSERT INTO DIM_ELE VALUES ("8d93b8a9-a6fe-4f59-8997-dabb2df460a0", 0, "00000000-0000-0000-0000-000000000000"); INSERT INTO S_SYS_PROXY VALUES ("d8ca6d9b-7cf6-4f9b-9224-bf1bbd4de04a", 'Test', 1, '../Test.xtuml'); """ class TestModel(unittest.TestCase): def test_model(self): <|code_end|> , continue by predicting the next line. Consider current file imports: import unittest from bridgepoint import ooaofooa and context: # Path: bridgepoint/ooaofooa.py # class OoaOfOoaException(Exception): # class Domain(xtuml.MetaModel): # class ModelLoader(xtuml.ModelLoader): # def __init__(self, id_generator=None): # def add_symbol(self, name, handle): # def find_symbol(self, name): # def is_contained_in(pe_pe, root): # def is_global(pe_pe): # def get_defining_component(pe_pe): # def get_attribute_type(o_attr): # def _get_data_type_name(s_dt): # def _get_related_attributes(r_rgo, r_rto): # def mk_enum(s_edt): # def mk_bridge(metamodel, s_brg): # def mk_external_entity(metamodel, s_ee): # def mk_function(metamodel, s_sync): # def mk_constant(cnst_syc): # def mk_operation(metaclass, o_tfr): # def mk_derived_attribute(metaclass, o_dbattr): # def mk_class(m, o_obj, derived_attributes=False): # def mk_simple_association(m, r_simp): # def mk_linked_association(m, r_assoc): # def _mk_assoc(side1, side2): # def mk_subsuper_association(m, r_subsup): # def mk_derived_association(m, r_comp): # def mk_association(m, r_rel): # def mk_component(bp_model, c_c=None, derived_attributes=False): # def __init__(self, load_globals=True): # def filename_input(self, path_or_filename): # def build_component(self, name=None, derived_attributes=False): # def _mk_loader(resource, load_globals): # def load_metamodel(resource=None, load_globals=True): # def load_component(resource, name=None, load_globals=True): # def delete_globals(m, disconnect=False): # EE = collections.namedtuple(s_ee.Key_Lett, names) which might include code, classes, or functions. Output only the next line.
l = ooaofooa.Loader(load_globals=True)
Next line prediction: <|code_start|># pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class TestWhileLoop(PrebuildFunctionTestCase): @prebuild_docstring def test_while_loop(self): ''' assign x = 10; while (x > 0) assign x = x - 1; end while; return x; ''' act_whl = self.metamodel.select_one('ACT_WHL') self.assertIsNotNone(act_whl) <|code_end|> . Use current file imports: (from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one import logging import unittest) and context including class names, function names, or small code snippets from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) . Output only the next line.
act_smt = one(act_whl).ACT_SMT[603]()
Based on the snippet: <|code_start|># encoding: utf-8 # Copyright (C) 2017 John Törnblom # # This file is part of pyxtuml. # # pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class TestBinOp(PrebuildFunctionTestCase): @prebuild_docstring def test_plus(self): '''return 1 + 1;''' act_ret = self.metamodel.select_one('ACT_RET') self.assertIsNotNone(act_ret) <|code_end|> , predict the immediate next line with the help of imports: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one import logging import unittest and context (classes, functions, sometimes code) from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) . Output only the next line.
act_smt = one(act_ret).ACT_SMT[603]()
Here is a snippet: <|code_start|> Drv_Lbl='B2', Mning='my_second_event') self.metamodel.new('SM_ISM', Obj_ID=o_obj.Obj_ID, SM_ID=sm_sm.SM_ID) sm_sm = self.metamodel.new('SM_SM') o_obj = self.metamodel.new('O_OBJ', Key_Lett='C') pe_pe = self.metamodel.new('PE_PE') relate(pe_pe, o_obj, 8001) sm_evt = self.metamodel.new('SM_EVT', SM_ID=sm_sm.SM_ID, SMspd_ID=self.metamodel.id_generator.next(), Numb=1, Drv_Lbl='C1', Mning='my_third_event') s_dt = self.metamodel.select_any('S_DT', where(Name='boolean')) self.metamodel.new('SM_EVTDI', SM_ID=sm_sm.SM_ID, SMevt_ID=sm_evt.SMevt_ID, DT_ID=s_dt.DT_ID, Name='di1') self.metamodel.new('SM_ISM', Obj_ID=o_obj.Obj_ID, SM_ID=sm_sm.SM_ID) <|code_end|> . Write the next line using the current file imports: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one from xtuml import relate from xtuml import where_eq as where import logging import unittest and context from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True # # Path: xtuml/meta.py # def where_eq(**kwargs): # ''' # Return a where-clause that filters out instances based on named # keywords. # # Usage example: # # >>> from xtuml import where_eq as where # >>> m = xtuml.load_metamodel('db.sql') # >>> inst = m.select_any('My_Modeled_Class', where(My_Number=5)) # ''' # return WhereEqual(kwargs) , which may include functions, classes, or code. Output only the next line.
@prebuild_docstring
Here is a snippet: <|code_start|> sm_sm = self.metamodel.new('SM_SM') o_obj = self.metamodel.new('O_OBJ', Key_Lett='C') pe_pe = self.metamodel.new('PE_PE') relate(pe_pe, o_obj, 8001) sm_evt = self.metamodel.new('SM_EVT', SM_ID=sm_sm.SM_ID, SMspd_ID=self.metamodel.id_generator.next(), Numb=1, Drv_Lbl='C1', Mning='my_third_event') s_dt = self.metamodel.select_any('S_DT', where(Name='boolean')) self.metamodel.new('SM_EVTDI', SM_ID=sm_sm.SM_ID, SMevt_ID=sm_evt.SMevt_ID, DT_ID=s_dt.DT_ID, Name='di1') self.metamodel.new('SM_ISM', Obj_ID=o_obj.Obj_ID, SM_ID=sm_sm.SM_ID) @prebuild_docstring def test_generate_to_class(self): ''' generate A2:my_event() to A class; ''' e_gar = self.metamodel.select_one('E_GAR') self.assertIsNotNone(e_gar) <|code_end|> . Write the next line using the current file imports: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one from xtuml import relate from xtuml import where_eq as where import logging import unittest and context from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True # # Path: xtuml/meta.py # def where_eq(**kwargs): # ''' # Return a where-clause that filters out instances based on named # keywords. # # Usage example: # # >>> from xtuml import where_eq as where # >>> m = xtuml.load_metamodel('db.sql') # >>> inst = m.select_any('My_Modeled_Class', where(My_Number=5)) # ''' # return WhereEqual(kwargs) , which may include functions, classes, or code. Output only the next line.
e_gsme = one(e_gar).E_GSME[705]()
Given the code snippet: <|code_start|># encoding: utf-8 # Copyright (C) 2017 John Törnblom # # This file is part of pyxtuml. # # pyxtuml is free software: you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # pyxtuml is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with pyxtuml. If not, see <http://www.gnu.org/licenses/>. class TestGenerate(PrebuildFunctionTestCase): def setUp(self): PrebuildFunctionTestCase.setUp(self) sm_sm = self.metamodel.new('SM_SM') o_obj = self.metamodel.new('O_OBJ', Key_Lett='A') pe_pe = self.metamodel.new('PE_PE') <|code_end|> , generate the next line using the imports in this file: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one from xtuml import relate from xtuml import where_eq as where import logging import unittest and context (functions, classes, or occasionally code) from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True # # Path: xtuml/meta.py # def where_eq(**kwargs): # ''' # Return a where-clause that filters out instances based on named # keywords. # # Usage example: # # >>> from xtuml import where_eq as where # >>> m = xtuml.load_metamodel('db.sql') # >>> inst = m.select_any('My_Modeled_Class', where(My_Number=5)) # ''' # return WhereEqual(kwargs) . Output only the next line.
relate(pe_pe, o_obj, 8001)
Predict the next line after this snippet: <|code_start|> sm_sm = self.metamodel.new('SM_SM') o_obj = self.metamodel.new('O_OBJ', Key_Lett='B') pe_pe = self.metamodel.new('PE_PE') relate(pe_pe, o_obj, 8001) self.metamodel.new('SM_EVT', SM_ID=sm_sm.SM_ID, SMspd_ID=self.metamodel.id_generator.next(), Numb=2, Drv_Lbl='B2', Mning='my_second_event') self.metamodel.new('SM_ISM', Obj_ID=o_obj.Obj_ID, SM_ID=sm_sm.SM_ID) sm_sm = self.metamodel.new('SM_SM') o_obj = self.metamodel.new('O_OBJ', Key_Lett='C') pe_pe = self.metamodel.new('PE_PE') relate(pe_pe, o_obj, 8001) sm_evt = self.metamodel.new('SM_EVT', SM_ID=sm_sm.SM_ID, SMspd_ID=self.metamodel.id_generator.next(), Numb=1, Drv_Lbl='C1', Mning='my_third_event') <|code_end|> using the current file's imports: from tests.test_bridgepoint.utils import PrebuildFunctionTestCase from tests.test_bridgepoint.utils import prebuild_docstring from xtuml import navigate_one as one from xtuml import relate from xtuml import where_eq as where import logging import unittest and any relevant context from other files: # Path: tests/test_bridgepoint/utils.py # class PrebuildFunctionTestCase(CompareAST): # # @classmethod # def setUpClass(cls): # cls.loader = ooaofooa.Loader() # # def setUp(self): # self.metamodel = self.loader.build_metamodel() # pe_pe = self.metamodel.new('PE_PE') # s_sync = self.metamodel.new('S_SYNC') # xtuml.relate(s_sync, pe_pe, 8001) # # s_dt = self.metamodel.select_any('S_DT', lambda sel: sel.Name == 'void') # xtuml.relate(s_dt, s_sync, 25) # # def tearDown(self): # del self.metamodel # # def prebuild_text(self, s): # s_sync = self.metamodel.select_any('S_SYNC') # s_sync.Action_Semantics_internal = s # s_sync.Suc_Pars = 1 # # prebuild.prebuild_model(self.metamodel) # self.assertTrue(self.metamodel.is_consistent()) # # generated_code = sourcegen.gen_text_action(s_sync) # # handwritten_ast = oal.parse(s) # generated_ast = oal.parse(generated_code) # # self.compare(handwritten_ast, generated_ast) # # Path: tests/test_bridgepoint/utils.py # def prebuild_docstring(f): # # def wrapper(self): # self.prebuild_text(f.__doc__) # f(self) # # return wrapper # # Path: xtuml/meta.py # def navigate_one(self, instance): # ''' # Navigate from *instance* across the link. # ''' # return next(iter(self.navigate(instance)), None) # # Path: xtuml/meta.py # def relate(from_instance, to_instance, rel_id, phrase=''): # ''' # Relate *from_instance* to *to_instance* across *rel_id*. For reflexive # association, a *phrase* indicating the direction must also be provided. # # The two instances are related to each other by copying the identifying # attributes from the instance on the TO side of a association to the instance # n the FROM side. Updated values which affect existing associations are # propagated. A set of all affected instances will be returned. # ''' # if None in [from_instance, to_instance]: # return False # # inst1, inst2, ass = _find_link(from_instance, to_instance, rel_id, phrase) # if not ass.source_link.connect(inst1, inst2): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # if not ass.target_link.connect(inst2, inst1): # raise RelateException(from_instance, to_instance, rel_id, phrase) # # return True # # Path: xtuml/meta.py # def where_eq(**kwargs): # ''' # Return a where-clause that filters out instances based on named # keywords. # # Usage example: # # >>> from xtuml import where_eq as where # >>> m = xtuml.load_metamodel('db.sql') # >>> inst = m.select_any('My_Modeled_Class', where(My_Number=5)) # ''' # return WhereEqual(kwargs) . Output only the next line.
s_dt = self.metamodel.select_any('S_DT', where(Name='boolean'))
Predict the next line for this snippet: <|code_start|> class LinkAdmin(admin.ModelAdmin): verbose_name_plural = "links" list_display = ['original_url', 'identifier', 'count', 'created', 'modified', ] readonly_fields = ('test_url', 'created', 'modified', 'count') search_fields = ['original_url', 'identifier'] def test_url(self, instance): site = Site.objects.get_current() response = """<a href="{0}{1}/{2}">{0}{1}/{2}</a>""".format( "http://", site.domain, instance.identifier ) return mark_safe(response) test_url.short_description = "Test URL" test_url.allow_tags = True <|code_end|> with the help of current file imports: from django.conf import settings from django.contrib import admin from django.contrib.sites.models import Site from django.utils.safestring import mark_safe from .models import Link and context from other files: # Path: shortener/links/models.py # class Link(TimeStampedModel): # # original_url = models.CharField(_("URL to be shortened"), max_length=255, unique=True) # identifier = models.CharField(_("Identifier"), # max_length=100, # blank=True, # validators=[validate_five_characters], # db_index=True) # # def __unicode__(self): # return self.original_url # # @property # def count(self): # return self.linklog_set.count() # # def log(self, request): # self.linklog_set.create_from_request( # link=self, # request=request # ) # # def get_identifier_url(self): # try: # return reverse("links:redirect", kwargs={'identifier': self.identifier}) # except NoReverseMatch: # return 'NADA' # # @property # def tiny(self): # return base64.encode(self.pk) # # def get_tiny_url(self): # return reverse("links:redirect", kwargs={'identifier': self.tiny}) # # def amazonify(self): # url = self.original_url # if url.startswith( # ("https://amazon.", # "http://amazon.", # "http://amzn.", # "https://amzn.", # "https://www.amazon.", # "http://www.amazon.") # ): # url = amazonify(url, "mlinar-20") # return url , which may contain function names, class names, or code. Output only the next line.
admin.site.register(Link, LinkAdmin)
Predict the next line after this snippet: <|code_start|> class Link(TimeStampedModel): original_url = models.CharField(_("URL to be shortened"), max_length=255, unique=True) identifier = models.CharField(_("Identifier"), max_length=100, blank=True, <|code_end|> using the current file's imports: from django.core.urlresolvers import reverse, NoReverseMatch from django.db import models from django.utils.baseconv import base64 from django.utils.translation import ugettext_lazy as _ from amazonify import amazonify from model_utils.models import TimeStampedModel from .validators import validate_five_characters and any relevant context from other files: # Path: shortener/links/validators.py # def validate_five_characters(value): # if len(value) < 5: # msg = u"Custom identifiers must have at least 5 characters" # raise ValidationError(msg) . Output only the next line.
validators=[validate_five_characters],
Given snippet: <|code_start|> class LinkLogAdmin(admin.ModelAdmin): readonly_fields = ( "link", "http_accept_language", "http_host", "http_referer", "http_user_agent", "query_string", "remote_addr", "remote_host", "request_method" ) <|code_end|> , continue by predicting the next line. Consider current file imports: from django.contrib import admin from .models import LinkLog and context: # Path: shortener/linkmetrics/models.py # class LinkLog(TimeStampedModel): # """ # TODO - consider moving this to Redis or MongoDB # """ # # link = models.ForeignKey(Link) # # http_accept_language = models.TextField(_("HTTP_ACCEPT_LANGUAGE"), blank=True) # http_host = models.CharField(_("HTTP_HOST"), max_length=255, blank=True) # http_referer = models.CharField(_("HTTP_REFERER"), max_length=255, blank=True) # http_user_agent = models.CharField(_("HTTP_USER_AGENT"), max_length=255, blank=True) # query_string = models.TextField(_("QUERY_STRING"), blank=True) # remote_addr = models.CharField(_("REMOTE_ADDR"), max_length=255, blank=True) # remote_host = models.CharField(_("REMOTE_HOST"), max_length=255, blank=True) # request_method = models.CharField(_("REQUEST_METHOD"), max_length=30, blank=True) # # objects = LingLogManager() # # def __unicode__(self): # return "{0}: {1}".format( # self.created, # self.link.original_url # ) which might include code, classes, or functions. Output only the next line.
admin.site.register(LinkLog, LinkLogAdmin)
Next line prediction: <|code_start|> try: link = Link.objects.get(Q(pk=pk) | Q(identifier=identifier)) except Link.DoesNotExist: raise Http404 return link def get_context_data(self, *args, **kwargs): context = super(LinkDetailView, self).get_context_data(**kwargs) # Ghetto style just to get it working counts = [] for date in self.object.linklog_set.datetimes('created', 'day'): count = LinkLog.objects.filter( created__day=date.day, created__month=date.month, created__year=date.year, link=self.object ).count() counts.append( {"date": date + timezone.timedelta(1), # timezone to fix weird off-by-one "count": count} ) context['counts'] = counts return context class LinkCreateView(LoginRequiredMixin, StaffuserRequiredMixin, FormView): <|code_end|> . Use current file imports: (from django.core.urlresolvers import reverse from django.db.models import Count from django.db.models import Q from django.http import Http404 from django.shortcuts import get_object_or_404, redirect from django.utils.baseconv import base64 from django.utils import timezone from django.views.generic import ( RedirectView, ListView, DetailView, FormView ) from braces.views import LoginRequiredMixin, StaffuserRequiredMixin from .forms import BasicLinkForm from .models import Link from linkmetrics.models import LinkLog) and context including class names, function names, or small code snippets from other files: # Path: shortener/links/forms.py # class BasicLinkForm(forms.ModelForm): # # class Meta: # model = Link # fields = ("original_url", "identifier") # # def clean_original_url(self): # url = self.cleaned_data['original_url'] # if "//" in url[8:]: # raise forms.ValidationError("Don't be silly.") # try: # r = requests.get(url) # except requests.exceptions.MissingSchema: # raise forms.ValidationError("Please enter a real URL.") # if r.status_code not in (200, 301, 302): # raise forms.ValidationError("Please enter a working or accessible URL") # return url # # Path: shortener/links/models.py # class Link(TimeStampedModel): # # original_url = models.CharField(_("URL to be shortened"), max_length=255, unique=True) # identifier = models.CharField(_("Identifier"), # max_length=100, # blank=True, # validators=[validate_five_characters], # db_index=True) # # def __unicode__(self): # return self.original_url # # @property # def count(self): # return self.linklog_set.count() # # def log(self, request): # self.linklog_set.create_from_request( # link=self, # request=request # ) # # def get_identifier_url(self): # try: # return reverse("links:redirect", kwargs={'identifier': self.identifier}) # except NoReverseMatch: # return 'NADA' # # @property # def tiny(self): # return base64.encode(self.pk) # # def get_tiny_url(self): # return reverse("links:redirect", kwargs={'identifier': self.tiny}) # # def amazonify(self): # url = self.original_url # if url.startswith( # ("https://amazon.", # "http://amazon.", # "http://amzn.", # "https://amzn.", # "https://www.amazon.", # "http://www.amazon.") # ): # url = amazonify(url, "mlinar-20") # return url . Output only the next line.
form_class = BasicLinkForm
Continue the code snippet: <|code_start|> class LinkRedirectView(RedirectView): permanent = True query_string = True def get_redirect_url(self, **kwargs): identifier = self.kwargs['identifier'] # If identifier includes a link it means we don't need to do a base64 # decode. Just a fetch based on the identifier if '-' in identifier or '_' in identifier or '.' in identifier: try: <|code_end|> . Use current file imports: from django.core.urlresolvers import reverse from django.db.models import Count from django.db.models import Q from django.http import Http404 from django.shortcuts import get_object_or_404, redirect from django.utils.baseconv import base64 from django.utils import timezone from django.views.generic import ( RedirectView, ListView, DetailView, FormView ) from braces.views import LoginRequiredMixin, StaffuserRequiredMixin from .forms import BasicLinkForm from .models import Link from linkmetrics.models import LinkLog and context (classes, functions, or code) from other files: # Path: shortener/links/forms.py # class BasicLinkForm(forms.ModelForm): # # class Meta: # model = Link # fields = ("original_url", "identifier") # # def clean_original_url(self): # url = self.cleaned_data['original_url'] # if "//" in url[8:]: # raise forms.ValidationError("Don't be silly.") # try: # r = requests.get(url) # except requests.exceptions.MissingSchema: # raise forms.ValidationError("Please enter a real URL.") # if r.status_code not in (200, 301, 302): # raise forms.ValidationError("Please enter a working or accessible URL") # return url # # Path: shortener/links/models.py # class Link(TimeStampedModel): # # original_url = models.CharField(_("URL to be shortened"), max_length=255, unique=True) # identifier = models.CharField(_("Identifier"), # max_length=100, # blank=True, # validators=[validate_five_characters], # db_index=True) # # def __unicode__(self): # return self.original_url # # @property # def count(self): # return self.linklog_set.count() # # def log(self, request): # self.linklog_set.create_from_request( # link=self, # request=request # ) # # def get_identifier_url(self): # try: # return reverse("links:redirect", kwargs={'identifier': self.identifier}) # except NoReverseMatch: # return 'NADA' # # @property # def tiny(self): # return base64.encode(self.pk) # # def get_tiny_url(self): # return reverse("links:redirect", kwargs={'identifier': self.tiny}) # # def amazonify(self): # url = self.original_url # if url.startswith( # ("https://amazon.", # "http://amazon.", # "http://amzn.", # "https://amzn.", # "https://www.amazon.", # "http://www.amazon.") # ): # url = amazonify(url, "mlinar-20") # return url . Output only the next line.
link = Link.objects.get(identifier=identifier)
Given the code snippet: <|code_start|> class LinkLog(TimeStampedModel): """ TODO - consider moving this to Redis or MongoDB """ link = models.ForeignKey(Link) http_accept_language = models.TextField(_("HTTP_ACCEPT_LANGUAGE"), blank=True) http_host = models.CharField(_("HTTP_HOST"), max_length=255, blank=True) http_referer = models.CharField(_("HTTP_REFERER"), max_length=255, blank=True) http_user_agent = models.CharField(_("HTTP_USER_AGENT"), max_length=255, blank=True) query_string = models.TextField(_("QUERY_STRING"), blank=True) remote_addr = models.CharField(_("REMOTE_ADDR"), max_length=255, blank=True) remote_host = models.CharField(_("REMOTE_HOST"), max_length=255, blank=True) request_method = models.CharField(_("REQUEST_METHOD"), max_length=30, blank=True) <|code_end|> , generate the next line using the imports in this file: from django.db import models from django.utils.translation import ugettext_lazy as _ from model_utils.models import TimeStampedModel from .managers import LingLogManager from links.models import Link and context (functions, classes, or occasionally code) from other files: # Path: shortener/linkmetrics/managers.py # class LingLogManager(models.Manager): # # def create_from_request(self, link, request): # linklog = self.model( # link=link, # http_accept_language=request.META.get("HTTP_ACCEPT_LANGUAGE", ""), # http_host=request.META.get("HTTP_HOST", ""), # http_referer=request.META.get("HTTP_REFERER", ""), # http_user_agent=request.META.get("HTTP_USER_AGENT", ""), # query_string=request.META.get("QUERY_STRING", ""), # remote_addr=request.META.get("REMOTE_ADDR", ""), # remote_host=request.META.get("REMOTE_HOST", ""), # request_method=request.META.get("REQUEST_METHOD", ""), # ) # linklog.save() # return linklog . Output only the next line.
objects = LingLogManager()
Given the following code snippet before the placeholder: <|code_start|> Note that this class is outside of the normal gain machine hierarchy. It wraps all the functionality required to manage IFR-based gain (aka baseline-based corrections) calculations. """ def __init__(self, gmfactory, ifrgain_opts, compute=True): """ Initializes the IFR-based gains machinery. Args: gmfactory: a GainMachine Factory is used to manage the solution databases ifrgain_opts: dict of options compute: if False, gains are not computed even if options ask them to """ self.gmfactory = gmfactory load_from = expand_templated_name(ifrgain_opts['load-from']) save_to = expand_templated_name(ifrgain_opts['save-to']) self._ifrgains_per_chan = ifrgain_opts['per-chan'] self._ifrgain = None self._nfreq = gmfactory.grid["freq"] nfreq, nant, ncorr = [len(gmfactory.grid[axis]) for axis in ("freq", "ant", "corr")] if load_from: filename = load_from print(ModColor.Str("applying baseline-based corrections (BBCs) from {}".format(filename), col="green"), file=log(0)) if "//" in filename: filename, prefix = filename.rsplit("//", 1) else: filename, prefix = filename, "BBC" <|code_end|> , predict the next line using imports from the current file: import numpy as np from numpy.ma import masked_array from cubical import param_db from cubical.tools import logger, ModColor from cubical.main import expand_templated_name and context including class names, function names, and sometimes code from other files: # Path: cubical/param_db.py # def create(filename, metadata={}, backup=True): # def load(filename): # G = db['G'] # B = db['B'] # # Path: cubical/tools/logger.py # def logToFile(filename, append=False): # def getLogFilename(): # def __init__(self, logger, level, color=None, bold=None): # def write(self, message, level_override=None, print_once=None): # def print(self, *args): # def __init__(self, logger, verbose=None, log_verbose=None): # def verbosity(self, set_verb=None): # def log_verbosity(self, set_verb=None): # def __call__(self, level, color=None): # def warn(self, msg, color=None, print_once=None): # def error(self, msg, color="red", print_once=None): # def info(self, msg, color=None, print_once=None): # def critical(self, msg, color=None, print_once=None): # def debug(self, msg, color=None, print_once=None): # def exception(self, msg, color=None, print_once=None): # def print(self, *args): # def write(self, message, level=logging.INFO, verbosity=0, print_once=None, color=None): # def enableMemoryLogging(level=1): # def set_subprocess_label(label): # def get_subprocess_label(): # def _sigusr1_handler(signum, frame): # def _sigusr2_handler(signum, frame): # def setMemoryLogging(level): # def filter(self, event): # def __init__(self, fmt, datefmt, strip=True): # def label(self, record): # def format(self, record): # def init(app_name): # def getLogger(name, verbose=None, log_verbose=None): # def setBoring(boring=True): # def setGlobalVerbosity(verbosity): # def setGlobalLogVerbosity(verbosity): # def setSilent(Lname): # def setLoud(Lname): # class _DefaultWriter(object): # class LoggerWrapper(object): # class LogFilter(logging.Filter): # class ColorStrippingFormatter(logging.Formatter): # GB = float(1024 ** 3) # KEYS = _log_memory_types[memlevel] # # Path: cubical/tools/ModColor.py # HEADER = '\033[95m' # OKBLUE = '\033[94m' # OKGREEN = '\033[92m' # WARNING = '\033[93m' # FAIL = '\033[91m' # ENDC = '\033[0m' # HEADER = '' # OKBLUE = '' # OKGREEN = '' # WARNING = '' # FAIL = '' # ENDC = '' # def disableColors(): # def Str(strin0,col="red",Bold=True): # def Sep(strin=None,D=1): # def Title(strin,Big=False): # def disable(): . Output only the next line.
parm = param_db.load(filename).get(prefix)
Predict the next line after this snippet: <|code_start|>log = logger.getLogger("gain_machine") class IfrGainMachine(object): """ Interferometer-based gain machine. Note that this class is outside of the normal gain machine hierarchy. It wraps all the functionality required to manage IFR-based gain (aka baseline-based corrections) calculations. """ def __init__(self, gmfactory, ifrgain_opts, compute=True): """ Initializes the IFR-based gains machinery. Args: gmfactory: a GainMachine Factory is used to manage the solution databases ifrgain_opts: dict of options compute: if False, gains are not computed even if options ask them to """ self.gmfactory = gmfactory load_from = expand_templated_name(ifrgain_opts['load-from']) save_to = expand_templated_name(ifrgain_opts['save-to']) self._ifrgains_per_chan = ifrgain_opts['per-chan'] self._ifrgain = None self._nfreq = gmfactory.grid["freq"] nfreq, nant, ncorr = [len(gmfactory.grid[axis]) for axis in ("freq", "ant", "corr")] if load_from: filename = load_from <|code_end|> using the current file's imports: import numpy as np from numpy.ma import masked_array from cubical import param_db from cubical.tools import logger, ModColor from cubical.main import expand_templated_name and any relevant context from other files: # Path: cubical/param_db.py # def create(filename, metadata={}, backup=True): # def load(filename): # G = db['G'] # B = db['B'] # # Path: cubical/tools/logger.py # def logToFile(filename, append=False): # def getLogFilename(): # def __init__(self, logger, level, color=None, bold=None): # def write(self, message, level_override=None, print_once=None): # def print(self, *args): # def __init__(self, logger, verbose=None, log_verbose=None): # def verbosity(self, set_verb=None): # def log_verbosity(self, set_verb=None): # def __call__(self, level, color=None): # def warn(self, msg, color=None, print_once=None): # def error(self, msg, color="red", print_once=None): # def info(self, msg, color=None, print_once=None): # def critical(self, msg, color=None, print_once=None): # def debug(self, msg, color=None, print_once=None): # def exception(self, msg, color=None, print_once=None): # def print(self, *args): # def write(self, message, level=logging.INFO, verbosity=0, print_once=None, color=None): # def enableMemoryLogging(level=1): # def set_subprocess_label(label): # def get_subprocess_label(): # def _sigusr1_handler(signum, frame): # def _sigusr2_handler(signum, frame): # def setMemoryLogging(level): # def filter(self, event): # def __init__(self, fmt, datefmt, strip=True): # def label(self, record): # def format(self, record): # def init(app_name): # def getLogger(name, verbose=None, log_verbose=None): # def setBoring(boring=True): # def setGlobalVerbosity(verbosity): # def setGlobalLogVerbosity(verbosity): # def setSilent(Lname): # def setLoud(Lname): # class _DefaultWriter(object): # class LoggerWrapper(object): # class LogFilter(logging.Filter): # class ColorStrippingFormatter(logging.Formatter): # GB = float(1024 ** 3) # KEYS = _log_memory_types[memlevel] # # Path: cubical/tools/ModColor.py # HEADER = '\033[95m' # OKBLUE = '\033[94m' # OKGREEN = '\033[92m' # WARNING = '\033[93m' # FAIL = '\033[91m' # ENDC = '\033[0m' # HEADER = '' # OKBLUE = '' # OKGREEN = '' # WARNING = '' # FAIL = '' # ENDC = '' # def disableColors(): # def Str(strin0,col="red",Bold=True): # def Sep(strin=None,D=1): # def Title(strin,Big=False): # def disable(): . Output only the next line.
print(ModColor.Str("applying baseline-based corrections (BBCs) from {}".format(filename),
Given the following code snippet before the placeholder: <|code_start|> bf = broadcast_freqs[f] for d in range(n_dir): for c in range(2): p0cc = param[d,bt,bf,aa,0,c,c] p1cc = param[d,bt,bf,aa,1,c,c] g[d,t,f,aa,c,c] = np.exp(1j*(p0cc + fs[f]*p1cc)) # Cherry-pick other methods from standard kernels # inner_jhj is just a phase J^H.J, with intervals of 1,1 compute_inner_jhj = lambda m,jhj1: phase_only.compute_jhj(m, jhj1, 1, 1) # inner_jhr is just a phase J^H.R with intervals of 1,1 compute_inner_jhr = lambda jh,gh,r,jhr1: phase_only.compute_jhr(jh, gh, r, jhr1, 1, 1) # J^H computed using diagonal gains compute_jh = diag_complex.compute_jh # residuals computed assuming diagonal gains compute_residual = diag_complex.compute_residual # corrected visibilities computed assuming diagonal gains compute_corrected = diag_complex.compute_corrected # gains applied as diagonal apply_gains = diag_complex.apply_gains # gains inverted as diagonal <|code_end|> , predict the next line using imports from the current file: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import diag_complex from cubical.kernels import phase_only from cubical.kernels import tf_plane import numpy as np import cubical.kernels and context including class names, function names, and sometimes code from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): # # Path: cubical/kernels/tf_plane.py # def allocate_param_array(shape, dtype, zeros=False): # def compute_jhj(tmp_jhj, jhj, ts, fs, t_int, f_int): # def compute_jhjinv(jhj, jhjinv, eps): # def compute_jhr(tmp_jhr, jhr, ts, fs, t_int, f_int): # def compute_update(jhr, jhj, upd): # def construct_gains(param, g, ts, fs, t_int, f_int): . Output only the next line.
invert_gains = generics.compute_diag_inverse
Given snippet: <|code_start|> n_dir = g.shape[0] n_tim = g.shape[1] n_fre = g.shape[2] n_ant = g.shape[3] broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): for c in range(2): p0cc = param[d,bt,bf,aa,0,c,c] p1cc = param[d,bt,bf,aa,1,c,c] g[d,t,f,aa,c,c] = np.exp(1j*(p0cc + fs[f]*p1cc)) # Cherry-pick other methods from standard kernels # inner_jhj is just a phase J^H.J, with intervals of 1,1 compute_inner_jhj = lambda m,jhj1: phase_only.compute_jhj(m, jhj1, 1, 1) # inner_jhr is just a phase J^H.R with intervals of 1,1 compute_inner_jhr = lambda jh,gh,r,jhr1: phase_only.compute_jhr(jh, gh, r, jhr1, 1, 1) # J^H computed using diagonal gains <|code_end|> , continue by predicting the next line. Consider current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import diag_complex from cubical.kernels import phase_only from cubical.kernels import tf_plane import numpy as np import cubical.kernels and context: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): # # Path: cubical/kernels/tf_plane.py # def allocate_param_array(shape, dtype, zeros=False): # def compute_jhj(tmp_jhj, jhj, ts, fs, t_int, f_int): # def compute_jhjinv(jhj, jhjinv, eps): # def compute_jhr(tmp_jhr, jhr, ts, fs, t_int, f_int): # def compute_update(jhr, jhj, upd): # def construct_gains(param, g, ts, fs, t_int, f_int): which might include code, classes, or functions. Output only the next line.
compute_jh = diag_complex.compute_jh
Using the snippet: <|code_start|> t_int (int): Number of time slots per solution interval. f_int (int): Number of frequencies per solution interval. """ n_dir = g.shape[0] n_tim = g.shape[1] n_fre = g.shape[2] n_ant = g.shape[3] broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): for c in range(2): p0cc = param[d,bt,bf,aa,0,c,c] p1cc = param[d,bt,bf,aa,1,c,c] g[d,t,f,aa,c,c] = np.exp(1j*(p0cc + fs[f]*p1cc)) # Cherry-pick other methods from standard kernels # inner_jhj is just a phase J^H.J, with intervals of 1,1 <|code_end|> , determine the next line of code. You have imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import diag_complex from cubical.kernels import phase_only from cubical.kernels import tf_plane import numpy as np import cubical.kernels and context (class names, function names, or code) available: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): # # Path: cubical/kernels/tf_plane.py # def allocate_param_array(shape, dtype, zeros=False): # def compute_jhj(tmp_jhj, jhj, ts, fs, t_int, f_int): # def compute_jhjinv(jhj, jhjinv, eps): # def compute_jhr(tmp_jhr, jhr, ts, fs, t_int, f_int): # def compute_update(jhr, jhj, upd): # def construct_gains(param, g, ts, fs, t_int, f_int): . Output only the next line.
compute_inner_jhj = lambda m,jhj1: phase_only.compute_jhj(m, jhj1, 1, 1)
Given snippet: <|code_start|>provided. Common dimensions of arrays are: +----------------+------+ | Dimension | Size | +================+======+ | Direction | d | +----------------+------+ | Model | m | +----------------+------+ | Time | t | +----------------+------+ | Time Intervals | ti | +----------------+------+ | Frequency | f | +----------------+------+ | Freq Intervals | fi | +----------------+------+ | Antenna | a | +----------------+------+ | Correlation | c | +----------------+------+ """ use_parallel = True if cubical.kernels.num_omp_threads > 1 else False use_cache = cubical.kernels.use_cache # Allocators same as for generic full kernel. <|code_end|> , continue by predicting the next line. Consider current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import diag_complex from cubical.kernels import phase_only from cubical.kernels import tf_plane import numpy as np import cubical.kernels and context: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): # # Path: cubical/kernels/tf_plane.py # def allocate_param_array(shape, dtype, zeros=False): # def compute_jhj(tmp_jhj, jhj, ts, fs, t_int, f_int): # def compute_jhjinv(jhj, jhjinv, eps): # def compute_jhr(tmp_jhr, jhr, ts, fs, t_int, f_int): # def compute_update(jhr, jhj, upd): # def construct_gains(param, g, ts, fs, t_int, f_int): which might include code, classes, or functions. Output only the next line.
allocate_vis_array = tf_plane.allocate_vis_array
Given the code snippet: <|code_start|> for d in range(n_dir): for c in range(2): p0cc = param[d,bt,bf,aa,0,c,c] p1cc = param[d,bt,bf,aa,1,c,c] p2cc = param[d,bt,bf,aa,2,c,c] g[d,t,f,aa,c,c] = np.exp(1j*(p0cc + ts[t]*p1cc)) # Cherry-pick other methods from standard kernels # inner_jhj is just a phase J^H.J, with intervals of 1,1 compute_inner_jhj = lambda m,jhj1: phase_only.compute_jhj(m, jhj1, 1, 1) # inner_jhr is just a phase J^H.R with intervals of 1,1 compute_inner_jhr = lambda jh,gh,r,jhr1: phase_only.compute_jhr(jh, gh, r, jhr1, 1, 1) # J^H computed using diagonal gains compute_jh = diag_complex.compute_jh # residuals computed assuming diagonal gains compute_residual = diag_complex.compute_residual # corrected visibilities computed assuming diagonal gains compute_corrected = diag_complex.compute_corrected # gains applied as diagonal apply_gains = diag_complex.apply_gains # gains inverted as diagonal <|code_end|> , generate the next line using the imports in this file: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import diag_complex from cubical.kernels import phase_only from cubical.kernels import tf_plane import numpy as np import cubical.kernels and context (functions, classes, or occasionally code) from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): # # Path: cubical/kernels/tf_plane.py # def allocate_param_array(shape, dtype, zeros=False): # def compute_jhj(tmp_jhj, jhj, ts, fs, t_int, f_int): # def compute_jhjinv(jhj, jhjinv, eps): # def compute_jhr(tmp_jhr, jhr, ts, fs, t_int, f_int): # def compute_update(jhr, jhj, upd): # def construct_gains(param, g, ts, fs, t_int, f_int): . Output only the next line.
invert_gains = generics.compute_diag_inverse
Based on the snippet: <|code_start|> n_tim = g.shape[1] n_fre = g.shape[2] n_ant = g.shape[3] broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): for c in range(2): p0cc = param[d,bt,bf,aa,0,c,c] p1cc = param[d,bt,bf,aa,1,c,c] p2cc = param[d,bt,bf,aa,2,c,c] g[d,t,f,aa,c,c] = np.exp(1j*(p0cc + ts[t]*p1cc)) # Cherry-pick other methods from standard kernels # inner_jhj is just a phase J^H.J, with intervals of 1,1 compute_inner_jhj = lambda m,jhj1: phase_only.compute_jhj(m, jhj1, 1, 1) # inner_jhr is just a phase J^H.R with intervals of 1,1 compute_inner_jhr = lambda jh,gh,r,jhr1: phase_only.compute_jhr(jh, gh, r, jhr1, 1, 1) # J^H computed using diagonal gains <|code_end|> , predict the immediate next line with the help of imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import diag_complex from cubical.kernels import phase_only from cubical.kernels import tf_plane import numpy as np import cubical.kernels and context (classes, functions, sometimes code) from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): # # Path: cubical/kernels/tf_plane.py # def allocate_param_array(shape, dtype, zeros=False): # def compute_jhj(tmp_jhj, jhj, ts, fs, t_int, f_int): # def compute_jhjinv(jhj, jhjinv, eps): # def compute_jhr(tmp_jhr, jhr, ts, fs, t_int, f_int): # def compute_update(jhr, jhj, upd): # def construct_gains(param, g, ts, fs, t_int, f_int): . Output only the next line.
compute_jh = diag_complex.compute_jh
Given snippet: <|code_start|> Number of time slots per solution interval. f_int (int): Number of frequencies per solution interval. """ n_dir = g.shape[0] n_tim = g.shape[1] n_fre = g.shape[2] n_ant = g.shape[3] broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): for c in range(2): p0cc = param[d,bt,bf,aa,0,c,c] p1cc = param[d,bt,bf,aa,1,c,c] p2cc = param[d,bt,bf,aa,2,c,c] g[d,t,f,aa,c,c] = np.exp(1j*(p0cc + ts[t]*p1cc)) # Cherry-pick other methods from standard kernels # inner_jhj is just a phase J^H.J, with intervals of 1,1 <|code_end|> , continue by predicting the next line. Consider current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import diag_complex from cubical.kernels import phase_only from cubical.kernels import tf_plane import numpy as np import cubical.kernels and context: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): # # Path: cubical/kernels/tf_plane.py # def allocate_param_array(shape, dtype, zeros=False): # def compute_jhj(tmp_jhj, jhj, ts, fs, t_int, f_int): # def compute_jhjinv(jhj, jhjinv, eps): # def compute_jhr(tmp_jhr, jhr, ts, fs, t_int, f_int): # def compute_update(jhr, jhj, upd): # def construct_gains(param, g, ts, fs, t_int, f_int): which might include code, classes, or functions. Output only the next line.
compute_inner_jhj = lambda m,jhj1: phase_only.compute_jhj(m, jhj1, 1, 1)
Here is a snippet: <|code_start|>provided. Common dimensions of arrays are: +----------------+------+ | Dimension | Size | +================+======+ | Direction | d | +----------------+------+ | Model | m | +----------------+------+ | Time | t | +----------------+------+ | Time Intervals | ti | +----------------+------+ | Frequency | f | +----------------+------+ | Freq Intervals | fi | +----------------+------+ | Antenna | a | +----------------+------+ | Correlation | c | +----------------+------+ """ use_parallel = True if cubical.kernels.num_omp_threads > 1 else False use_cache = cubical.kernels.use_cache # Allocators same as for generic full kernel. <|code_end|> . Write the next line using the current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import diag_complex from cubical.kernels import phase_only from cubical.kernels import tf_plane import numpy as np import cubical.kernels and context from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): # # Path: cubical/kernels/tf_plane.py # def allocate_param_array(shape, dtype, zeros=False): # def compute_jhj(tmp_jhj, jhj, ts, fs, t_int, f_int): # def compute_jhjinv(jhj, jhjinv, eps): # def compute_jhr(tmp_jhr, jhr, ts, fs, t_int, f_int): # def compute_update(jhr, jhj, upd): # def construct_gains(param, g, ts, fs, t_int, f_int): , which may include functions, classes, or code. Output only the next line.
allocate_vis_array = tf_plane.allocate_vis_array
Using the snippet: <|code_start|> broadcast_dirs = np.array([d%g_dir for d in range(n_dir)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): bd = broadcast_dirs[d] g00 = g[d,t,f,aa,0,0] g11 = g[d,t,f,aa,1,1] g_next00 = g_next[bd,bt,bf,aa,0,0] g_next01 = g_next[bd,bt,bf,aa,0,1] g_next10 = g_next[bd,bt,bf,aa,1,0] g_next11 = g_next[bd,bt,bf,aa,1,1] g[d,t,f,aa,0,0] *= g_next00 g[d,t,f,aa,0,1] *= g_next11 g[d,t,f,aa,1,0] *= g_next00 g[d,t,f,aa,1,1] *= g_next11 # Map compute_jhr method to a generic complex case. compute_jhwr = full_W_complex.compute_jhwr # Map compute_jhj method to a generic complex case. compute_jhwj = full_W_complex.compute_jhwj # Map the J^H.J inversion method to a generic inversion. <|code_end|> , determine the next line of code. You have imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import full_W_complex import numpy as np import cubical.kernels and context (class names, function names, or code) available: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/full_W_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_jhwr(jh, r, w, jhwr, t_int, f_int): # def compute_jhwj(jh, w, jhwj, t_int, f_int): # def compute_weights(r, ic, w, v, npol): # def compute_cov(r, ic, w): . Output only the next line.
compute_jhjinv = generics.compute_2x2_inverse
Next line prediction: <|code_start|>provided. Common dimensions of arrays are: +----------------+------+ | Dimension | Size | +================+======+ | Direction | d | +----------------+------+ | Model | m | +----------------+------+ | Time | t | +----------------+------+ | Time Intervals | ti | +----------------+------+ | Frequency | f | +----------------+------+ | Freq Intervals | fi | +----------------+------+ | Antenna | a | +----------------+------+ | Correlation | c | +----------------+------+ """ use_parallel = True if cubical.kernels.num_omp_threads > 1 else False use_cache = cubical.kernels.use_cache # Allocators same as for generic full kernel <|code_end|> . Use current file imports: (from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import full_W_complex import numpy as np import cubical.kernels) and context including class names, function names, or small code snippets from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/full_W_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_jhwr(jh, r, w, jhwr, t_int, f_int): # def compute_jhwj(jh, w, jhwj, t_int, f_int): # def compute_weights(r, ic, w, v, npol): # def compute_cov(r, ic, w): . Output only the next line.
allocate_vis_array = full_complex.allocate_vis_array
Given snippet: <|code_start|> n_ant = g.shape[3] g_dir = g_next.shape[0] broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) broadcast_dirs = np.array([d%g_dir for d in range(n_dir)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): bd = broadcast_dirs[d] g00 = g[d,t,f,aa,0,0] g11 = g[d,t,f,aa,1,1] g_next00 = g_next[bd,bt,bf,aa,0,0] g_next01 = g_next[bd,bt,bf,aa,0,1] g_next10 = g_next[bd,bt,bf,aa,1,0] g_next11 = g_next[bd,bt,bf,aa,1,1] g[d,t,f,aa,0,0] *= g_next00 g[d,t,f,aa,0,1] *= g_next11 g[d,t,f,aa,1,0] *= g_next00 g[d,t,f,aa,1,1] *= g_next11 # Map compute_jhr method to a generic complex case. <|code_end|> , continue by predicting the next line. Consider current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import full_W_complex import numpy as np import cubical.kernels and context: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/full_W_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_jhwr(jh, r, w, jhwr, t_int, f_int): # def compute_jhwj(jh, w, jhwj, t_int, f_int): # def compute_weights(r, ic, w, v, npol): # def compute_cov(r, ic, w): which might include code, classes, or functions. Output only the next line.
compute_jhwr = full_W_complex.compute_jhwr
Given snippet: <|code_start|>provided. Common dimensions of arrays are: +----------------+------+ | Dimension | Size | +================+======+ | Direction | d | +----------------+------+ | Model | m | +----------------+------+ | Time | t | +----------------+------+ | Time Intervals | ti | +----------------+------+ | Frequency | f | +----------------+------+ | Freq Intervals | fi | +----------------+------+ | Antenna | a | +----------------+------+ | Correlation | c | +----------------+------+ """ use_parallel = True if cubical.kernels.num_omp_threads > 1 else False use_cache = cubical.kernels.use_cache # Allocators are the same as for the 2x2 complex kernel. <|code_end|> , continue by predicting the next line. Consider current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex import numpy as np import cubical.kernels and context: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): which might include code, classes, or functions. Output only the next line.
allocate_vis_array = full_complex.allocate_vis_array
Based on the snippet: <|code_start|># CubiCal: a radio interferometric calibration suite # (c) 2017 Rhodes University & Jonathan S. Kenyon # http://github.com/ratt-ru/CubiCal # This code is distributed under the terms of GPLv2, see LICENSE.md for details from __future__ import print_function log = logger.getLogger("slopes") def _normalize(x, dtype): """ Helper function: normalizes array to [0,1] interval. """ if len(x) > 1: return ((x - x[0]) / (x[-1] - x[0])).astype(dtype) elif len(x) == 1: return np.zeros(1, dtype) else: return x try: builtins.profile except AttributeError: # No line profiler, provide a pass-through version def profile(func): return func builtins.profile = profile <|code_end|> , predict the immediate next line with the help of imports: from cubical.machines.parameterised_machine import ParameterisedGains from numpy.ma import masked_array from cubical.tools import logger from .phase_diag_machine import PhaseDiagGains import numpy as np import cubical.kernels import builtins and context (classes, functions, sometimes code) from other files: # Path: cubical/machines/parameterised_machine.py # class ParameterisedGains(PerIntervalGains): # """ # This is a base class for all gain solution machines that use full-resolution # gain arrays derived from some other parameters. # """ # # def init_gains(self): # """ # Construct gain and flag arrays at full-resolution. Parameterisation of gains may not be at # full resolution. # """ # self.gain_intervals = 1, 1 # self.gain_grid = self.data_grid # self.gain_shape = [self.n_dir,self.n_tim,self.n_fre,self.n_ant,self.n_cor,self.n_cor] # self.gains = np.empty(self.gain_shape, dtype=self.dtype) # self.gains[:] = np.eye(self.n_cor) # self.gflags = np.zeros(self.gain_shape[:-2],FL.dtype) # # # Function used to unpack the gains or flags into full time/freq resolution. # self._gainres_to_fullres = self.copy_or_identity # # # function used to unpack interval resolution to gain resolution. # self._interval_to_gainres = self.unpack_intervals # # Path: cubical/tools/logger.py # def logToFile(filename, append=False): # def getLogFilename(): # def __init__(self, logger, level, color=None, bold=None): # def write(self, message, level_override=None, print_once=None): # def print(self, *args): # def __init__(self, logger, verbose=None, log_verbose=None): # def verbosity(self, set_verb=None): # def log_verbosity(self, set_verb=None): # def __call__(self, level, color=None): # def warn(self, msg, color=None, print_once=None): # def error(self, msg, color="red", print_once=None): # def info(self, msg, color=None, print_once=None): # def critical(self, msg, color=None, print_once=None): # def debug(self, msg, color=None, print_once=None): # def exception(self, msg, color=None, print_once=None): # def print(self, *args): # def write(self, message, level=logging.INFO, verbosity=0, print_once=None, color=None): # def enableMemoryLogging(level=1): # def set_subprocess_label(label): # def get_subprocess_label(): # def _sigusr1_handler(signum, frame): # def _sigusr2_handler(signum, frame): # def setMemoryLogging(level): # def filter(self, event): # def __init__(self, fmt, datefmt, strip=True): # def label(self, record): # def format(self, record): # def init(app_name): # def getLogger(name, verbose=None, log_verbose=None): # def setBoring(boring=True): # def setGlobalVerbosity(verbosity): # def setGlobalLogVerbosity(verbosity): # def setSilent(Lname): # def setLoud(Lname): # class _DefaultWriter(object): # class LoggerWrapper(object): # class LogFilter(logging.Filter): # class ColorStrippingFormatter(logging.Formatter): # GB = float(1024 ** 3) # KEYS = _log_memory_types[memlevel] . Output only the next line.
class PhaseSlopeGains(ParameterisedGains):
Given the code snippet: <|code_start|> bf = broadcast_freqs[f] for d in range(n_dir): for c in range(2): p0cc = param[d,bt,bf,aa,0,c,c] p1cc = param[d,bt,bf,aa,1,c,c] p2cc = param[d,bt,bf,aa,2,c,c] g[d,t,f,aa,c,c] = np.exp(1j*(p0cc + fs[f]*p1cc + ts[t]*p2cc)) # Cherry-pick other methods from standard kernels # inner_jhj is just a phase J^H.J, with intervals of 1,1 compute_inner_jhj = lambda m,jhj1: phase_only.compute_jhj(m, jhj1, 1, 1) # inner_jhr is just a phase J^H.R with intervals of 1,1 compute_inner_jhr = lambda jh,gh,r,jhr1: phase_only.compute_jhr(jh, gh, r, jhr1, 1, 1) # J^H computed using diagonal gains compute_jh = diag_complex.compute_jh # residuals computed assuming diagonal gains compute_residual = diag_complex.compute_residual # corrected visibilities computed assuming diagonal gains compute_corrected = diag_complex.compute_corrected # gains applied as diagonal apply_gains = diag_complex.apply_gains # gains inverted as diagonal <|code_end|> , generate the next line using the imports in this file: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex from cubical.kernels import phase_only import numpy as np import cubical.kernels and context (functions, classes, or occasionally code) from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): . Output only the next line.
invert_gains = generics.compute_diag_inverse
Using the snippet: <|code_start|>provided. Common dimensions of arrays are: +----------------+------+ | Dimension | Size | +================+======+ | Direction | d | +----------------+------+ | Model | m | +----------------+------+ | Time | t | +----------------+------+ | Time Intervals | ti | +----------------+------+ | Frequency | f | +----------------+------+ | Freq Intervals | fi | +----------------+------+ | Antenna | a | +----------------+------+ | Correlation | c | +----------------+------+ """ use_parallel = True if cubical.kernels.num_omp_threads > 1 else False use_cache = cubical.kernels.use_cache # Allocators same as for generic full kernel. <|code_end|> , determine the next line of code. You have imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex from cubical.kernels import phase_only import numpy as np import cubical.kernels and context (class names, function names, or code) available: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): . Output only the next line.
allocate_vis_array = full_complex.allocate_vis_array
Given snippet: <|code_start|> n_dir = g.shape[0] n_tim = g.shape[1] n_fre = g.shape[2] n_ant = g.shape[3] broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): for c in range(2): p0cc = param[d,bt,bf,aa,0,c,c] p1cc = param[d,bt,bf,aa,1,c,c] p2cc = param[d,bt,bf,aa,2,c,c] g[d,t,f,aa,c,c] = np.exp(1j*(p0cc + fs[f]*p1cc + ts[t]*p2cc)) # Cherry-pick other methods from standard kernels # inner_jhj is just a phase J^H.J, with intervals of 1,1 compute_inner_jhj = lambda m,jhj1: phase_only.compute_jhj(m, jhj1, 1, 1) # inner_jhr is just a phase J^H.R with intervals of 1,1 compute_inner_jhr = lambda jh,gh,r,jhr1: phase_only.compute_jhr(jh, gh, r, jhr1, 1, 1) # J^H computed using diagonal gains <|code_end|> , continue by predicting the next line. Consider current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex from cubical.kernels import phase_only import numpy as np import cubical.kernels and context: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): which might include code, classes, or functions. Output only the next line.
compute_jh = diag_complex.compute_jh
Given the code snippet: <|code_start|> t_int (int): Number of time slots per solution interval. f_int (int): Number of frequencies per solution interval. """ n_dir = g.shape[0] n_tim = g.shape[1] n_fre = g.shape[2] n_ant = g.shape[3] broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): for c in range(2): p0cc = param[d,bt,bf,aa,0,c,c] p1cc = param[d,bt,bf,aa,1,c,c] p2cc = param[d,bt,bf,aa,2,c,c] g[d,t,f,aa,c,c] = np.exp(1j*(p0cc + fs[f]*p1cc + ts[t]*p2cc)) # Cherry-pick other methods from standard kernels # inner_jhj is just a phase J^H.J, with intervals of 1,1 <|code_end|> , generate the next line using the imports in this file: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex from cubical.kernels import phase_only import numpy as np import cubical.kernels and context (functions, classes, or occasionally code) from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): . Output only the next line.
compute_inner_jhj = lambda m,jhj1: phase_only.compute_jhj(m, jhj1, 1, 1)
Given snippet: <|code_start|> output_rows.append([]) for ifreq in range(nf): # start new line every NF_PER_COL-th freq chunk, if frequencies span lines if nf_per_col is not None and output_rows[-1] and ifreq%nf_per_col == 0: output_rows.append([]) statrec = self.chunk[itime, ifreq] statrec_dict = {field:statrec[field] for field in self.chunk.dtype.fields} # new line: prepend chunk label label = statrec.label.decode() if hasattr(statrec.label, 'decode') else statrec.label if not output_rows[-1]: output_rows[-1].append((label, False)) # put it in header as well if len(output_rows) == 2: output_rows[0].append((label, False)) # check for threshold warn = False if threshold is not None: for field, value in threshold: if statrec[field] > value: warn = True text = format_string.format(**statrec_dict) output_rows[-1].append((text, warn)) # now work out column widths and format ncol = max([len(row) for row in output_rows]) colwidths = [max([len(row[icol][0]) for row in output_rows if icol<len(row)]) for icol in range(ncol)] colformat = ["{{:{}}} ".format(w) for w in colwidths] output_rows = [[(colformat[icol].format(col), warn) for icol, (col, warn) in enumerate(row)] for row in output_rows] <|code_end|> , continue by predicting the next line. Consider current file imports: from builtins import range from future.moves import pickle from cubical.tools import logger from cubical.tools import ModColor from collections import OrderedDict import math import numpy as np and context: # Path: cubical/tools/logger.py # def logToFile(filename, append=False): # def getLogFilename(): # def __init__(self, logger, level, color=None, bold=None): # def write(self, message, level_override=None, print_once=None): # def print(self, *args): # def __init__(self, logger, verbose=None, log_verbose=None): # def verbosity(self, set_verb=None): # def log_verbosity(self, set_verb=None): # def __call__(self, level, color=None): # def warn(self, msg, color=None, print_once=None): # def error(self, msg, color="red", print_once=None): # def info(self, msg, color=None, print_once=None): # def critical(self, msg, color=None, print_once=None): # def debug(self, msg, color=None, print_once=None): # def exception(self, msg, color=None, print_once=None): # def print(self, *args): # def write(self, message, level=logging.INFO, verbosity=0, print_once=None, color=None): # def enableMemoryLogging(level=1): # def set_subprocess_label(label): # def get_subprocess_label(): # def _sigusr1_handler(signum, frame): # def _sigusr2_handler(signum, frame): # def setMemoryLogging(level): # def filter(self, event): # def __init__(self, fmt, datefmt, strip=True): # def label(self, record): # def format(self, record): # def init(app_name): # def getLogger(name, verbose=None, log_verbose=None): # def setBoring(boring=True): # def setGlobalVerbosity(verbosity): # def setGlobalLogVerbosity(verbosity): # def setSilent(Lname): # def setLoud(Lname): # class _DefaultWriter(object): # class LoggerWrapper(object): # class LogFilter(logging.Filter): # class ColorStrippingFormatter(logging.Formatter): # GB = float(1024 ** 3) # KEYS = _log_memory_types[memlevel] # # Path: cubical/tools/ModColor.py # HEADER = '\033[95m' # OKBLUE = '\033[94m' # OKGREEN = '\033[92m' # WARNING = '\033[93m' # FAIL = '\033[91m' # ENDC = '\033[0m' # HEADER = '' # OKBLUE = '' # OKGREEN = '' # WARNING = '' # FAIL = '' # ENDC = '' # def disableColors(): # def Str(strin0,col="red",Bold=True): # def Sep(strin=None,D=1): # def Title(strin,Big=False): # def disable(): which might include code, classes, or functions. Output only the next line.
return ["".join([(ModColor.Str(col, 'red') if warn else col) for col, warn in row]) for row in output_rows]
Given the following code snippet before the placeholder: <|code_start|> def allocate_gain_array(shape, dtype, zeros=False): """Allocates a gain array of the desired shape, laid out in preferred order""" return cubical.kernels.allocate_reordered_array(shape, dtype, _gain_axis_layout, zeros=zeros) def allocate_flag_array(shape, dtype, zeros=False): """Allocates a flag array of the desired shape, laid out in preferred order""" return cubical.kernels.allocate_reordered_array(shape, dtype, _flag_axis_layout, zeros=zeros) allocate_param_array = allocate_gain_array # compute_residual is identical to the general full complex case. compute_residual = full_complex.compute_residual # compute_jh is identical to the general full complex case. compute_jh = full_complex.compute_jh # compute_update is identical to the general full complex case. compute_update = full_complex.compute_update # compute_corrected is identical to the general full complex case. compute_corrected = full_complex.compute_corrected # apply_gains is identical to the general full complex case. apply_gains = full_complex.apply_gains # right_multiply_gains is identical to the general full complex case. right_multiply_gains = full_complex.right_multiply_gains # Map the J^H.J inversion method to a generic inversion. <|code_end|> , predict the next line using imports from the current file: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex import numpy as np import cubical.kernels and context including class names, function names, and sometimes code from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): . Output only the next line.
compute_jhjinv = generics.compute_2x2_inverse
Continue the code snippet: <|code_start|> use_parallel = True if cubical.kernels.num_omp_threads > 1 else False use_cache = cubical.kernels.use_cache # defines memory layout of model-like arrays (axis layout is NDxNMxNTxNFxNAxNAxNCxNC) _model_axis_layout = [4,5,1,2,3,0,6,7] # layout is AAMTFD # defines memory layout of gain-like arrays (axis layout is NDxNTxNFxNAxNCxNC) _gain_axis_layout = [3,1,2,0,4,5] # layout is ATFD # defines memory layout of flag-like arrays (axis layout is NTxNFxNAxNA) _flag_axis_layout = [2,3,0,1] # layout is AATF def allocate_vis_array(shape, dtype, zeros=False): """Allocates a visibility array of the desired shape, laid out in preferred order""" return cubical.kernels.allocate_reordered_array(shape, dtype, _model_axis_layout, zeros=zeros) def allocate_gain_array(shape, dtype, zeros=False): """Allocates a gain array of the desired shape, laid out in preferred order""" return cubical.kernels.allocate_reordered_array(shape, dtype, _gain_axis_layout, zeros=zeros) def allocate_flag_array(shape, dtype, zeros=False): """Allocates a flag array of the desired shape, laid out in preferred order""" return cubical.kernels.allocate_reordered_array(shape, dtype, _flag_axis_layout, zeros=zeros) allocate_param_array = allocate_gain_array # compute_residual is identical to the general full complex case. <|code_end|> . Use current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex import numpy as np import cubical.kernels and context (classes, functions, or code) from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): . Output only the next line.
compute_residual = full_complex.compute_residual
Continue the code snippet: <|code_start|>''' DDFacet, a facet-based radio imaging package Copyright (C) 2013-2016 Cyril Tasse, l'Observatoire de Paris, SKA South Africa, Rhodes University This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. This file has been ported to CubiCal by the original authors, with minor modifications. ''' from __future__ import absolute_import from __future__ import division from __future__ import print_function <|code_end|> . Use current file imports: from DDFacet.compatibility import range from cubical.tools import logger, ModColor import numpy import os import os.path import sys import pyrap.tables import numpy as np import Siamese.OMS.Utils as Utils import Siamese import Siamese.OMS.InterpolatedBeams as InterpolatedBeams import Cattery.Siamese.OMS.Utils as Utils import Cattery.Siamese as Siamese import Cattery.Siamese.OMS.InterpolatedBeams as InterpolatedBeams import math and context (classes, functions, or code) from other files: # Path: cubical/tools/logger.py # def logToFile(filename, append=False): # def getLogFilename(): # def __init__(self, logger, level, color=None, bold=None): # def write(self, message, level_override=None, print_once=None): # def print(self, *args): # def __init__(self, logger, verbose=None, log_verbose=None): # def verbosity(self, set_verb=None): # def log_verbosity(self, set_verb=None): # def __call__(self, level, color=None): # def warn(self, msg, color=None, print_once=None): # def error(self, msg, color="red", print_once=None): # def info(self, msg, color=None, print_once=None): # def critical(self, msg, color=None, print_once=None): # def debug(self, msg, color=None, print_once=None): # def exception(self, msg, color=None, print_once=None): # def print(self, *args): # def write(self, message, level=logging.INFO, verbosity=0, print_once=None, color=None): # def enableMemoryLogging(level=1): # def set_subprocess_label(label): # def get_subprocess_label(): # def _sigusr1_handler(signum, frame): # def _sigusr2_handler(signum, frame): # def setMemoryLogging(level): # def filter(self, event): # def __init__(self, fmt, datefmt, strip=True): # def label(self, record): # def format(self, record): # def init(app_name): # def getLogger(name, verbose=None, log_verbose=None): # def setBoring(boring=True): # def setGlobalVerbosity(verbosity): # def setGlobalLogVerbosity(verbosity): # def setSilent(Lname): # def setLoud(Lname): # class _DefaultWriter(object): # class LoggerWrapper(object): # class LogFilter(logging.Filter): # class ColorStrippingFormatter(logging.Formatter): # GB = float(1024 ** 3) # KEYS = _log_memory_types[memlevel] # # Path: cubical/tools/ModColor.py # HEADER = '\033[95m' # OKBLUE = '\033[94m' # OKGREEN = '\033[92m' # WARNING = '\033[93m' # FAIL = '\033[91m' # ENDC = '\033[0m' # HEADER = '' # OKBLUE = '' # OKGREEN = '' # WARNING = '' # FAIL = '' # ENDC = '' # def disableColors(): # def Str(strin0,col="red",Bold=True): # def Sep(strin=None,D=1): # def Title(strin,Big=False): # def disable(): . Output only the next line.
log = logger.getLogger("FITSBeamInterpolator")
Based on the snippet: <|code_start|>#!/usr/bin/env python from __future__ import print_function def plot_leakages_cc(D, FS=None, TS=None, ANTS=slice(None), refant=None, plot_diag='ap', plot_offdiag='ri', figtitle=None): """Plots leakages from a CubiCal database""" <|code_end|> , predict the immediate next line with the help of imports: from collections import OrderedDict from pylab import * from cubical.plots import gainsols from collections import OrderedDict import matplotlib.patches as mpatches import re, cmath and context (classes, functions, sometimes code) from other files: # Path: cubical/plots/gainsols.py # class PlotLimits(object): # class PlotOptions(PlotLimits): # def __init__(self): # def __init__(self): # def populate_argparse(parser): # def get_plot_limits(options, sols, time0=0): # def get_plot_counts(nsols, plots_per_sol): # def plot_bandpass(sols, plot_diag='ap', plot_offdiag='', gaintype=("Bandpass", "Offdiag bandpass"), figtitle=None): # def _prep_plot(nplot, ant, num_gaintype, plot_type): # def _make_reim_plot(ax, freq, x1, x2, corrs, legend): # def _make_ap_plot(ax, ax2, freq, x1, x2, corrs, legend): # def plot_gain(sols, plot_diag='ap', plot_offdiag='', gaintype=("Gain", "Offdiag gain"), figtitle=None): # def _prep_plot(nplot, ant, num_gaintype, plot_type): # def _make_real_plot(ax, time, x1, x2, corrs, legend): # def _make_reim_plot(ax, time, x1, x2, corrs, legend): # def _make_ap_plot(ax, AX2, time, x1, x2, corrs, legend): # def get_freq_slice(FS, all_freqs): # def get_time_slice(TS, all_times): # def _get_jones_element_index(G, ant, corr1=0, corr2=0, dir=0): # def _get_jones_element_slice(G, ant, corr1=0, corr2=0, dir=0): # def prepare_sols_dict(G, FS=None, TS=None): # def plot_bandpass_cc(G, FS=None, TS=None, # plot_diag='ap', plot_offdiag='', figtitle=None, component='gain'): # def plot_gain_cc(G, FS=None, TS=None, # plot_diag='ap', plot_offdiag='', figtitle=None, component='gain'): # def read_cubical_gains(filename, label=None, component="gain"): # FS = slice(if0 or 0, if1) # FS = slice(None) # FS = get_freq_slice(FS, G.grid[G.ax.freq]) # TS = get_freq_slice(TS, G.grid[G.ax.time]) . Output only the next line.
sols, have_offdiag, is_complex = gainsols.prepare_sols_dict(D, FS, TS)
Predict the next line for this snippet: <|code_start|> # (Montblanc is finicky about affinities apparently, so we don't do it before) _init_worker(main=True) for itile, tile in enumerate(tile_list): # wait for I/O job on current tile to finish print("waiting for I/O on {}".format(tile.label), file=log(0)) # have a timeout so that if a child process dies, we at least find out done = False while not done: reap_children() done, not_done = cf.wait([io_futures[itile]], timeout=10) # check if result was successful if not io_futures[itile].result(): raise RuntimeError("I/O job on {} failed".format(tile.label)) del io_futures[itile] # immediately schedule I/O job to save previous/load next tile load_next = itile + 1 if itile < len(tile_list) - 1 else None save_prev = itile - 1 if itile else None if load_next is not None or save_prev is not None: io_futures[itile + 1] = io_executor.submit(_io_handler, load=load_next, save=save_prev, load_model=load_model) # submit solver jobs solver_futures = {} print("submitting solver jobs for {}".format(tile.label), file=log(0)) for key in tile.get_chunk_keys(): <|code_end|> with the help of current file imports: from builtins import range from cubical.tools import logger from cubical import solver import multiprocessing, os, sys, traceback import concurrent.futures as cf import re import numba import cubical.kernels import cubical.kernels and context from other files: # Path: cubical/tools/logger.py # def logToFile(filename, append=False): # def getLogFilename(): # def __init__(self, logger, level, color=None, bold=None): # def write(self, message, level_override=None, print_once=None): # def print(self, *args): # def __init__(self, logger, verbose=None, log_verbose=None): # def verbosity(self, set_verb=None): # def log_verbosity(self, set_verb=None): # def __call__(self, level, color=None): # def warn(self, msg, color=None, print_once=None): # def error(self, msg, color="red", print_once=None): # def info(self, msg, color=None, print_once=None): # def critical(self, msg, color=None, print_once=None): # def debug(self, msg, color=None, print_once=None): # def exception(self, msg, color=None, print_once=None): # def print(self, *args): # def write(self, message, level=logging.INFO, verbosity=0, print_once=None, color=None): # def enableMemoryLogging(level=1): # def set_subprocess_label(label): # def get_subprocess_label(): # def _sigusr1_handler(signum, frame): # def _sigusr2_handler(signum, frame): # def setMemoryLogging(level): # def filter(self, event): # def __init__(self, fmt, datefmt, strip=True): # def label(self, record): # def format(self, record): # def init(app_name): # def getLogger(name, verbose=None, log_verbose=None): # def setBoring(boring=True): # def setGlobalVerbosity(verbosity): # def setGlobalLogVerbosity(verbosity): # def setSilent(Lname): # def setLoud(Lname): # class _DefaultWriter(object): # class LoggerWrapper(object): # class LogFilter(logging.Filter): # class ColorStrippingFormatter(logging.Formatter): # GB = float(1024 ** 3) # KEYS = _log_memory_types[memlevel] # # Path: cubical/solver.py # GD = None # SOLVERS = { 'so': SolveOnly, # 'sc': SolveAndCorrect, # 'sr': SolveAndCorrectResiduals, # 'ss': SolveAndSubtract, # 'ac': CorrectOnly, # 'ar': CorrectResiduals, # 'as': SubtractOnly # } # def profile(func): return func # def _solve_gains(gm, stats, madmax, obser_arr, model_arr, flags_arr, sol_opts, label="", compute_residuals=None): # def get_flagging_stats(): # def update_stats(flags, statfields): # def compute_chisq(statfield=None, full=True): # def __init__(self, obser_arr, model_arr, flags_arr, weight_arr, freq_slice): # def weighted_obser(self): # def weighted_model(self): # def corrupt_weighted_model(self): # def corrupt_residual(self, imod=0, idir=slice(None)): # def corrupt_model(self, imod=0, idir=slice(None)): # def __get__(self, cls, owner): # def __init__(self, vdm, gm, soldict, sol_opts, label, metadata): # def is_model_required(cls): # def outputs_full_corrected_residuals(cls): # def run(self): # def finalize(self, corr_vis): # def run(self): # def run(self): # def run(self, correct=False): # def outputs_full_corrected_residuals(self): # def is_model_required(cls): # def run(self): # def run(self): # def outputs_full_corrected_residuals(self): # def run_solver(solver_type, itile, chunk_key, sol_opts, debug_opts): # class _VisDataManager(object): # class classproperty(property): # class SolverMachine(object): # class SolveOnly(SolverMachine): # class SolveAndCorrect(SolveOnly): # class SolveAndSubtract(SolveOnly): # class SolveAndCorrectResiduals(SolveAndSubtract): # class CorrectOnly(SolverMachine): # class SubtractOnly(SolverMachine): # class CorrectResiduals(SubtractOnly): , which may contain function names, class names, or code. Output only the next line.
solver_futures[executor.submit(solver.run_solver, solver_type, itile, key, solver_opts, debug_opts)] = key
Predict the next line after this snippet: <|code_start|> f_int (int): Number of frequencies per solution interval. """ n_dir = g.shape[0] n_tim = g.shape[1] n_fre = g.shape[2] n_ant = g.shape[3] g_dir = g_next.shape[0] broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) broadcast_dirs = np.array([d%g_dir for d in range(n_dir)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): bd = broadcast_dirs[d] g[d,t,f,aa,0,0] *= g_next[bd,bt,bf,aa,0,0] g[d,t,f,aa,0,1] = 0 g[d,t,f,aa,1,0] = 0 g[d,t,f,aa,1,1] *= g_next[bd,bt,bf,aa,1,1] # Map the J^H.J inversion method to a generic diagonal inversion. <|code_end|> using the current file's imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex import numpy as np import cubical.kernels and any relevant context from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): . Output only the next line.
compute_jhjinv = generics.compute_diag_inverse
Predict the next line for this snippet: <|code_start|>provided. Common dimensions of arrays are: +----------------+------+ | Dimension | Size | +================+======+ | Direction | d | +----------------+------+ | Model | m | +----------------+------+ | Time | t | +----------------+------+ | Time Intervals | ti | +----------------+------+ | Frequency | f | +----------------+------+ | Freq Intervals | fi | +----------------+------+ | Antenna | a | +----------------+------+ | Correlation | c | +----------------+------+ """ use_parallel = True if cubical.kernels.num_omp_threads > 1 else False use_cache = cubical.kernels.use_cache # Allocators same as for generic full kernel <|code_end|> with the help of current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex import numpy as np import cubical.kernels and context from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): , which may contain function names, class names, or code. Output only the next line.
allocate_vis_array = full_complex.allocate_vis_array
Given the following code snippet before the placeholder: <|code_start|> broadcast_dirs = np.array([d%g_dir for d in range(n_dir)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): bd = broadcast_dirs[d] g00 = g[d,t,f,aa,0,0] g11 = g[d,t,f,aa,1,1] g_next00 = g_next[bd,bt,bf,aa,0,0] g_next01 = g_next[bd,bt,bf,aa,0,1] g_next10 = g_next[bd,bt,bf,aa,1,0] g_next11 = g_next[bd,bt,bf,aa,1,1] g[d,t,f,aa,0,0] *= g_next00 g[d,t,f,aa,0,1] *= g_next11 g[d,t,f,aa,1,0] *= g_next00 g[d,t,f,aa,1,1] *= g_next11 # Map compute_jhr method to a generic complex case. compute_jhr = full_complex.compute_jhr # Map compute_jhj method to a generic complex case. compute_jhj = full_complex.compute_jhj # Map the J^H.J inversion method to a generic inversion. <|code_end|> , predict the next line using imports from the current file: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex import numpy as np import cubical.kernels and context including class names, function names, and sometimes code from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): . Output only the next line.
compute_jhjinv = generics.compute_2x2_inverse
Given snippet: <|code_start|>provided. Common dimensions of arrays are: +----------------+------+ | Dimension | Size | +================+======+ | Direction | d | +----------------+------+ | Model | m | +----------------+------+ | Time | t | +----------------+------+ | Time Intervals | ti | +----------------+------+ | Frequency | f | +----------------+------+ | Freq Intervals | fi | +----------------+------+ | Antenna | a | +----------------+------+ | Correlation | c | +----------------+------+ """ use_parallel = True if cubical.kernels.num_omp_threads > 1 else False use_cache = cubical.kernels.use_cache # Allocators same as for generic full kernel <|code_end|> , continue by predicting the next line. Consider current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex import numpy as np import cubical.kernels and context: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): which might include code, classes, or functions. Output only the next line.
allocate_vis_array = full_complex.allocate_vis_array
Predict the next line for this snippet: <|code_start|> g_dir = g_next.shape[0] broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) broadcast_dirs = np.array([d%g_dir for d in range(n_dir)]) for aa in prange(n_ant): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): bd = broadcast_dirs[d] g00 = g[d,t,f,aa,0,0] g01 = g[d,t,f,aa,0,1] g10 = g[d,t,f,aa,1,0] g11 = g[d,t,f,aa,1,1] g_next00 = g_next[bd,bt,bf,aa,0,0] g_next01 = g_next[bd,bt,bf,aa,0,1] g_next10 = g_next[bd,bt,bf,aa,1,0] g_next11 = g_next[bd,bt,bf,aa,1,1] g[d,t,f,aa,0,0] = (g00*g_next00 + g01*g_next10) g[d,t,f,aa,0,1] = (g00*g_next01 + g01*g_next11) g[d,t,f,aa,1,0] = (g10*g_next00 + g11*g_next10) g[d,t,f,aa,1,1] = (g10*g_next01 + g11*g_next11) # Map the J^H.J inversion method to a generic inversion. <|code_end|> with the help of current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics import numpy as np import cubical.kernels and context from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): , which may contain function names, class names, or code. Output only the next line.
compute_jhjinv = generics.compute_2x2_inverse
Predict the next line after this snippet: <|code_start|> broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) broadcast_dirs = np.array([d%g_dir for d in range(n_dir)]) for ibl in prange(n_bl): aa, ab = all_bls[ibl,0], all_bls[ibl,1] for i in range(n_mod): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): bd = broadcast_dirs[d] r00 = r[i,t,f,aa,ab,0,0] r11 = r[i,t,f,aa,ab,1,1] jhh00 = jh[d,i,t,f,ab,aa,0,0] jhh11 = jh[d,i,t,f,ab,aa,1,1] jhr[d,bt,bf,aa,0,0] += gh[bd,bt,bf,aa,0,0]*r00*jhh00 jhr[d,bt,bf,aa,1,1] += gh[bd,bt,bf,aa,1,1]*r11*jhh11 # Remaining kernel functions are reused. # J^H is computed assuming diagonal gains. compute_jh = diagdiag_complex.compute_jh # J^H.J inverse is computed assuming diagonal blocks. <|code_end|> using the current file's imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex from cubical.kernels import diagdiag_complex from cubical.kernels import phase_only import numpy as np import cubical.kernels and any relevant context from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diagdiag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): . Output only the next line.
compute_jhjinv = generics.compute_diag_inverse
Given the code snippet: <|code_start|>provided. Common dimensions of arrays are: +----------------+------+ | Dimension | Size | +================+======+ | Direction | d | +----------------+------+ | Model | m | +----------------+------+ | Time | t | +----------------+------+ | Time Intervals | ti | +----------------+------+ | Frequency | f | +----------------+------+ | Freq Intervals | fi | +----------------+------+ | Antenna | a | +----------------+------+ | Correlation | c | +----------------+------+ """ use_parallel = True if cubical.kernels.num_omp_threads > 1 else False use_cache = cubical.kernels.use_cache # Allocators same as for generic full kernel <|code_end|> , generate the next line using the imports in this file: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex from cubical.kernels import diagdiag_complex from cubical.kernels import phase_only import numpy as np import cubical.kernels and context (functions, classes, or occasionally code) from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diagdiag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): . Output only the next line.
allocate_vis_array = full_complex.allocate_vis_array
Using the snippet: <|code_start|> all_bls = np.array([[i,j] for i in range(n_ant) for j in range(n_ant) if i!=j]) n_bl = all_bls.shape[0] broadcast_times = np.array([t//t_int for t in range(n_tim)]) broadcast_freqs = np.array([f//f_int for f in range(n_fre)]) broadcast_dirs = np.array([d%g_dir for d in range(n_dir)]) for ibl in prange(n_bl): aa, ab = all_bls[ibl,0], all_bls[ibl,1] for i in range(n_mod): for t in range(n_tim): bt = broadcast_times[t] for f in range(n_fre): bf = broadcast_freqs[f] for d in range(n_dir): bd = broadcast_dirs[d] r00 = r[i,t,f,aa,ab,0,0] r11 = r[i,t,f,aa,ab,1,1] jhh00 = jh[d,i,t,f,ab,aa,0,0] jhh11 = jh[d,i,t,f,ab,aa,1,1] jhr[d,bt,bf,aa,0,0] += gh[bd,bt,bf,aa,0,0]*r00*jhh00 jhr[d,bt,bf,aa,1,1] += gh[bd,bt,bf,aa,1,1]*r11*jhh11 # Remaining kernel functions are reused. # J^H is computed assuming diagonal gains. <|code_end|> , determine the next line of code. You have imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex from cubical.kernels import diagdiag_complex from cubical.kernels import phase_only import numpy as np import cubical.kernels and context (class names, function names, or code) available: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diagdiag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): . Output only the next line.
compute_jh = diagdiag_complex.compute_jh
Given snippet: <|code_start|> for d in range(n_dir): bd = broadcast_dirs[d] r00 = r[i,t,f,aa,ab,0,0] r11 = r[i,t,f,aa,ab,1,1] jhh00 = jh[d,i,t,f,ab,aa,0,0] jhh11 = jh[d,i,t,f,ab,aa,1,1] jhr[d,bt,bf,aa,0,0] += gh[bd,bt,bf,aa,0,0]*r00*jhh00 jhr[d,bt,bf,aa,1,1] += gh[bd,bt,bf,aa,1,1]*r11*jhh11 # Remaining kernel functions are reused. # J^H is computed assuming diagonal gains. compute_jh = diagdiag_complex.compute_jh # J^H.J inverse is computed assuming diagonal blocks. compute_jhjinv = generics.compute_diag_inverse # Residuals computed assuming diagonal gains. compute_residual = diagdiag_complex.compute_residual # Corrected visibilities computed assuming diagonal gains. compute_corrected = diagdiag_complex.compute_corrected # Gains applied as diagonal. apply_gains = diagdiag_complex.apply_gains # Update computed as in the general phase-only case. <|code_end|> , continue by predicting the next line. Consider current file imports: from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex from cubical.kernels import diagdiag_complex from cubical.kernels import phase_only import numpy as np import cubical.kernels and context: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diagdiag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/phase_only.py # def compute_jhj(m, jhj, t_int=1, f_int=1): # def compute_jhr(gh, jh, r, jhr, t_int=1, f_int=1): # def compute_update(jhr, jhjinv, upd): which might include code, classes, or functions. Output only the next line.
compute_update = phase_only.compute_update
Given snippet: <|code_start|> del self.order[self.order.index(name)] self.ms.removecolkeyword('BITFLAG','FLAGSET_%s'%name) # write new list of bitflags self.ms._putkeyword('BITFLAG','FLAGSETS',-1,False,','.join(self.order)) self.ms.flush() return mask def flag_chisq (st, GD, basename, nddid): """ Flags timeslots and channels based on accumulated chi-squared statistics. Args: st (:obj:`~cubical.statistics.SolverStats`): Object containing solver statistics. GD (dict): Dictionary of global options. basename (str): Base name for output plots. nddid (int): Number of data descriptor identifiers. Returns: np.ndarray: Flag cube of shape (n_times, n_ddids, n_chans). """ chi2 = np.ma.masked_array(st.timechan.chi2, st.timechan.chi2==0) total = (~chi2.mask).sum() if not total: <|code_end|> , continue by predicting the next line. Consider current file imports: from builtins import range from past.builtins import cmp from functools import cmp_to_key from cubical.tools import logger, ModColor from collections import OrderedDict import numpy as np import re import cubical.plots as plots import pylab and context: # Path: cubical/tools/logger.py # def logToFile(filename, append=False): # def getLogFilename(): # def __init__(self, logger, level, color=None, bold=None): # def write(self, message, level_override=None, print_once=None): # def print(self, *args): # def __init__(self, logger, verbose=None, log_verbose=None): # def verbosity(self, set_verb=None): # def log_verbosity(self, set_verb=None): # def __call__(self, level, color=None): # def warn(self, msg, color=None, print_once=None): # def error(self, msg, color="red", print_once=None): # def info(self, msg, color=None, print_once=None): # def critical(self, msg, color=None, print_once=None): # def debug(self, msg, color=None, print_once=None): # def exception(self, msg, color=None, print_once=None): # def print(self, *args): # def write(self, message, level=logging.INFO, verbosity=0, print_once=None, color=None): # def enableMemoryLogging(level=1): # def set_subprocess_label(label): # def get_subprocess_label(): # def _sigusr1_handler(signum, frame): # def _sigusr2_handler(signum, frame): # def setMemoryLogging(level): # def filter(self, event): # def __init__(self, fmt, datefmt, strip=True): # def label(self, record): # def format(self, record): # def init(app_name): # def getLogger(name, verbose=None, log_verbose=None): # def setBoring(boring=True): # def setGlobalVerbosity(verbosity): # def setGlobalLogVerbosity(verbosity): # def setSilent(Lname): # def setLoud(Lname): # class _DefaultWriter(object): # class LoggerWrapper(object): # class LogFilter(logging.Filter): # class ColorStrippingFormatter(logging.Formatter): # GB = float(1024 ** 3) # KEYS = _log_memory_types[memlevel] # # Path: cubical/tools/ModColor.py # HEADER = '\033[95m' # OKBLUE = '\033[94m' # OKGREEN = '\033[92m' # WARNING = '\033[93m' # FAIL = '\033[91m' # ENDC = '\033[0m' # HEADER = '' # OKBLUE = '' # OKGREEN = '' # WARNING = '' # FAIL = '' # ENDC = '' # def disableColors(): # def Str(strin0,col="red",Bold=True): # def Sep(strin=None,D=1): # def Title(strin,Big=False): # def disable(): which might include code, classes, or functions. Output only the next line.
print(ModColor.Str("no valid solutions anywhere: skipping post-solution flagging."), file=log)
Using the snippet: <|code_start|> # Figure out the data points per tile. This is done assuming that the data # is still in rowlike format at this point. TODO: Verify behaviour with # multiple directions. data_points_per_tile = \ n_dir*(along_time*t_per_chunk*n_bl)*(along_freq*f_per_chunk)*n_corr # Figure out the data points per chunk. This is done assuming that the # data is now going to be in the internal data representation. TODO: # verify that this works correctly when varying n_dir and n_ant. data_points_per_chunk = \ n_dir*t_per_chunk*f_per_chunk*n_ant*n_ant*n_corr # Empirically determined values for the slope and intercept for each # solver process. w_slope, w_intercept = 5.77281225e-08, 4.53587065e-01 w_mem_est = w_slope*data_points_per_chunk + w_intercept # Empirically determined values for the slope and intercept for the # I/O process. io_slope, io_intercept = 4.24736385e-08, 3.73958333e-01 io_mem_est = io_slope*data_points_per_tile + io_intercept # Make a guess at the total memory use. <|code_end|> , determine the next line of code. You have imports: from psutil import virtual_memory from cubical import workers from cubical.tools import logger, ModColor and context (class names, function names, or code) available: # Path: cubical/workers.py # def _setup_workers_and_threads(force_serial, ncpu, nworkers, nthreads, montblanc_threads, max_workers): # def setup_parallelism(ncpu, nworker, nthread, force_serial, affinity, io_affinity, main_affinity, use_montblanc, montblanc_threads, max_workers): # def run_process_loop(ms, _tile_list, load_model, single_chunk, solver_type, solver_opts, debug_opts, out_opts): # def _run_multi_process_loop(ms, load_model, solver_type, solver_opts, debug_opts, out_opts): # def reap_children(): # def _run_single_process_loop(ms, load_model, single_chunk, solver_type, solver_opts, debug_opts, out_opts): # def _init_worker(main=False): # def _io_handler(save=None, load=None, load_model=True, finalize=False, out_opts=None): # # Path: cubical/tools/logger.py # def logToFile(filename, append=False): # def getLogFilename(): # def __init__(self, logger, level, color=None, bold=None): # def write(self, message, level_override=None, print_once=None): # def print(self, *args): # def __init__(self, logger, verbose=None, log_verbose=None): # def verbosity(self, set_verb=None): # def log_verbosity(self, set_verb=None): # def __call__(self, level, color=None): # def warn(self, msg, color=None, print_once=None): # def error(self, msg, color="red", print_once=None): # def info(self, msg, color=None, print_once=None): # def critical(self, msg, color=None, print_once=None): # def debug(self, msg, color=None, print_once=None): # def exception(self, msg, color=None, print_once=None): # def print(self, *args): # def write(self, message, level=logging.INFO, verbosity=0, print_once=None, color=None): # def enableMemoryLogging(level=1): # def set_subprocess_label(label): # def get_subprocess_label(): # def _sigusr1_handler(signum, frame): # def _sigusr2_handler(signum, frame): # def setMemoryLogging(level): # def filter(self, event): # def __init__(self, fmt, datefmt, strip=True): # def label(self, record): # def format(self, record): # def init(app_name): # def getLogger(name, verbose=None, log_verbose=None): # def setBoring(boring=True): # def setGlobalVerbosity(verbosity): # def setGlobalLogVerbosity(verbosity): # def setSilent(Lname): # def setLoud(Lname): # class _DefaultWriter(object): # class LoggerWrapper(object): # class LogFilter(logging.Filter): # class ColorStrippingFormatter(logging.Formatter): # GB = float(1024 ** 3) # KEYS = _log_memory_types[memlevel] # # Path: cubical/tools/ModColor.py # HEADER = '\033[95m' # OKBLUE = '\033[94m' # OKGREEN = '\033[92m' # WARNING = '\033[93m' # FAIL = '\033[91m' # ENDC = '\033[0m' # HEADER = '' # OKBLUE = '' # OKGREEN = '' # WARNING = '' # FAIL = '' # ENDC = '' # def disableColors(): # def Str(strin0,col="red",Bold=True): # def Sep(strin=None,D=1): # def Title(strin,Big=False): # def disable(): . Output only the next line.
tot_mem_est = w_mem_est*(workers.num_workers or 1) + io_mem_est
Next line prediction: <|code_start|> Args: jhr (np.float32 or np.float64): Typed memoryview of J\ :sup:`H`\R array with dimensions (d, ti, fi, a, c, c). jhjinv (np.float32 or np.float64): Typed memoryview of (J\ :sup:`H`\J)\ :sup:`-1` array with dimensions (d, ti, fi, a, c, c). upd (np.float32 or np.float64): Typed memoryview of gain update array with dimensions (d, ti, fi, a, c, c). """ n_dir = jhr.shape[0] n_tim = jhr.shape[1] n_fre = jhr.shape[2] n_ant = jhr.shape[3] for aa in prange(n_ant): for t in range(n_tim): for f in range(n_fre): for d in range(n_dir): upd[d,t,f,aa,0,0] = jhjinv[d,t,f,aa,0,0]*jhr[d,t,f,aa,0,0] upd[d,t,f,aa,0,1] = upd[d,t,f,aa,1,0] = 0 upd[d,t,f,aa,1,1] = jhjinv[d,t,f,aa,1,1]*jhr[d,t,f,aa,1,1] # Remaining kernel functions are reused. # J^H is computed assuming diagonal gains. compute_jh = diag_complex.compute_jh # J^H.J inverse is computed assuming diagonal blocks. <|code_end|> . Use current file imports: (from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex import numpy as np import cubical.kernels) and context including class names, function names, or small code snippets from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): . Output only the next line.
compute_jhjinv = generics.compute_diag_inverse
Next line prediction: <|code_start|>Cython kernels for the phase-only gain machine. Functions require output arrays to be provided. Common dimensions of arrays are: +----------------+------+ | Dimension | Size | +================+======+ | Direction | d | +----------------+------+ | Model | m | +----------------+------+ | Time | t | +----------------+------+ | Time Intervals | ti | +----------------+------+ | Frequency | f | +----------------+------+ | Freq Intervals | fi | +----------------+------+ | Antenna | a | +----------------+------+ | Correlation | c | +----------------+------+ """ use_parallel = True if cubical.kernels.num_omp_threads > 1 else False use_cache = cubical.kernels.use_cache <|code_end|> . Use current file imports: (from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex import numpy as np import cubical.kernels) and context including class names, function names, or small code snippets from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): . Output only the next line.
allocate_vis_array = full_complex.allocate_vis_array
Next line prediction: <|code_start|> Given J\ :sup:`H`\R and (J\ :sup:`H`\J)\ :sup:`-1`, computes the gain update. The dimensions of the input should already be consistent, making this operation simple. These arrays are real valued. Args: jhr (np.float32 or np.float64): Typed memoryview of J\ :sup:`H`\R array with dimensions (d, ti, fi, a, c, c). jhjinv (np.float32 or np.float64): Typed memoryview of (J\ :sup:`H`\J)\ :sup:`-1` array with dimensions (d, ti, fi, a, c, c). upd (np.float32 or np.float64): Typed memoryview of gain update array with dimensions (d, ti, fi, a, c, c). """ n_dir = jhr.shape[0] n_tim = jhr.shape[1] n_fre = jhr.shape[2] n_ant = jhr.shape[3] for aa in prange(n_ant): for t in range(n_tim): for f in range(n_fre): for d in range(n_dir): upd[d,t,f,aa,0,0] = jhjinv[d,t,f,aa,0,0]*jhr[d,t,f,aa,0,0] upd[d,t,f,aa,0,1] = upd[d,t,f,aa,1,0] = 0 upd[d,t,f,aa,1,1] = jhjinv[d,t,f,aa,1,1]*jhr[d,t,f,aa,1,1] # Remaining kernel functions are reused. # J^H is computed assuming diagonal gains. <|code_end|> . Use current file imports: (from builtins import range from numba import jit, prange from cubical.kernels import generics from cubical.kernels import full_complex from cubical.kernels import diag_complex import numpy as np import cubical.kernels) and context including class names, function names, or small code snippets from other files: # Path: cubical/kernels/generics.py # def compute_2x2_inverse(x, xinv, flags, eps, flagbit): # def compute_diag_inverse(x, xinv, flags, eps, flagbit): # def compute_chisq(r, chisq): # def compute_chisq_diag(r, chisq): # def compute_chisq_offdiag(r, chisq): # # Path: cubical/kernels/full_complex.py # def allocate_vis_array(shape, dtype, zeros=False): # def allocate_gain_array(shape, dtype, zeros=False): # def allocate_flag_array(shape, dtype, zeros=False): # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_jhr(jh, r, jhr, t_int, f_int): # def compute_jhj(jh, jhj, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): # # Path: cubical/kernels/diag_complex.py # def compute_residual(m, g, gh, r, t_int, f_int): # def compute_jh(m, g, jh, t_int, f_int): # def compute_update(jhr, jhjinv, upd): # def compute_corrected(o, g, gh, corr, t_int, f_int): # def apply_gains(m, g, gh, t_int, f_int): # def right_multiply_gains(g, g_next, t_int, f_int): . Output only the next line.
compute_jh = diag_complex.compute_jh
Given the code snippet: <|code_start|> self.rings = rings self.spatialReference = sref dict.__init__(self, {'spatialReference': sref, 'rings': rings}) pyamf_classes = { _amfFeatureSet: 'com.esri.ags.tasks.FeatureSet', _amfSpatialReference: 'com.esri.ags.SpatialReference', _amfGeometryMapPoint: 'com.esri.ags.geometry.MapPoint', _amfGeometryPolyline: 'com.esri.ags.geometry.Polyline', _amfGeometryPolygon: 'com.esri.ags.geometry.Polygon', _amfFeature: 'com.esri.ags.Feature' } def reserialize_to_arc(content, point_objects): """ Convert from "geo" (GeoJSON) to ESRI's GeoServices REST serialization. Second argument is a boolean flag for whether to use the class _amfGeometryMapPoint for points in ring and path arrays, or tuples. The formal class is needed for AMF responses, plain tuples otherwise. Much of this cribbed from sample server queries and page 191+ of: http://www.esri.com/library/whitepapers/pdfs/geoservices-rest-spec.pdf """ mapPointList = point_objects and _amfGeometryMapPoint or (lambda s, x, y: (x, y)) mapPointDict = point_objects and _amfGeometryMapPoint or (lambda s, x, y: {'x': x, 'y': y}) found_geometry_types = set([feat['geometry']['type'] for feat in content['features']]) found_geometry_types = set([geometry_types.get(type) for type in found_geometry_types]) if len(found_geometry_types) > 1: <|code_end|> , generate the next line using the imports in this file: from operator import add from ..Core import KnownUnknown from ..py3_compat import reduce and context (functions, classes, or occasionally code) from other files: # Path: TileStache/Core.py # class KnownUnknown(Exception): # """ There are known unknowns. That is to say, there are things that we now know we don't know. # # This exception gets thrown in a couple places where common mistakes are made. # """ # pass # # Path: TileStache/py3_compat.py # def is_string_type(val): . Output only the next line.
raise KnownUnknown('Arc serialization needs a single geometry type, not ' + ', '.join(found_geometry_types))
Given the following code snippet before the placeholder: <|code_start|> sref = _amfSpatialReference(crs.get('wkid', None), crs.get('wkt', None)) geometry_type, features = None, [] for feature in content['features']: geometry = feature['geometry'] if geometry['type'] == 'Point': arc_geometry = mapPointDict(sref, *geometry['coordinates']) elif geometry['type'] == 'LineString': path = geometry['coordinates'] paths = [[mapPointList(sref, *xy) for xy in path]] arc_geometry = _amfGeometryPolyline(sref, paths) elif geometry['type'] == 'Polygon': rings = geometry['coordinates'] rings = [[mapPointList(sref, *xy) for xy in ring] for ring in rings] arc_geometry = _amfGeometryPolygon(sref, rings) elif geometry['type'] == 'MultiPoint': points = geometry['coordinates'] points = [mapPointList(sref, *xy) for xy in points] arc_geometry = {'points': points} elif geometry['type'] == 'MultiLineString': paths = geometry['coordinates'] paths = [[mapPointList(sref, *xy) for xy in path] for path in paths] arc_geometry = _amfGeometryPolyline(sref, paths) elif geometry['type'] == 'MultiPolygon': <|code_end|> , predict the next line using imports from the current file: from operator import add from ..Core import KnownUnknown from ..py3_compat import reduce and context including class names, function names, and sometimes code from other files: # Path: TileStache/Core.py # class KnownUnknown(Exception): # """ There are known unknowns. That is to say, there are things that we now know we don't know. # # This exception gets thrown in a couple places where common mistakes are made. # """ # pass # # Path: TileStache/py3_compat.py # def is_string_type(val): . Output only the next line.
rings = reduce(add, geometry['coordinates'])
Given the code snippet: <|code_start|> raise KnownUnknown('Unknown extension in configuration: "%s"' % extension) def setSaveOptionsJPEG(self, quality=None, optimize=None, progressive=None): """ Optional arguments are added to self.jpeg_options for pickup when saving. More information about options: http://effbot.org/imagingbook/format-jpeg.htm """ if quality is not None: self.jpeg_options['quality'] = int(quality) if optimize is not None: self.jpeg_options['optimize'] = bool(optimize) if progressive is not None: self.jpeg_options['progressive'] = bool(progressive) def setSaveOptionsPNG(self, optimize=None, palette=None, palette256=None): """ Optional arguments are added to self.png_options for pickup when saving. Palette argument is a URL relative to the configuration file, and it implies bits and optional transparency options. More information about options: http://effbot.org/imagingbook/format-png.htm """ if optimize is not None: self.png_options['optimize'] = bool(optimize) if palette is not None: <|code_end|> , generate the next line using the imports in this file: import logging import Image from sys import modules from wsgiref.headers import Headers from io import BytesIO from .py3_compat import urljoin from time import time from .Pixels import load_palette, apply_palette, apply_palette256 from PIL import Image from ModestMaps.Core import Coordinate and context (functions, classes, or occasionally code) from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Pixels.py # def load_palette(file_href): # """ Load colors from a Photoshop .act file, return palette info. # # Return tuple is an array of [ (r, g, b), (r, g, b), ... ], # bit depth of the palette, and a numeric transparency index # or None if not defined. # """ # bytes_ = urlopen(file_href).read() # count, t_index = unpack('!HH', bytes_[768:768+4]) # t_index = (t_index <= 0xff) and t_index or None # # palette = [] # # for offset in range(0, count): # if offset == t_index: # rgb = 0xff, 0x99, 0x00 # else: # rgb = unpack('!BBB', bytes_[offset*3:(offset + 1)*3]) # # palette.append(rgb) # # bits = int(ceil(log(len(palette)) / log(2))) # # return palette, bits, t_index # # def apply_palette(image, palette, t_index): # """ Apply a palette array to an image, return a new image. # """ # image = image.convert('RGBA') # pixels = image.tobytes() # # t_value = (t_index in range(256)) and pack('!B', t_index) or None # mapping = {} # indexes = [] # # for offset in range(0, len(pixels), 4): # r, g, b, a = unpack('!BBBB', pixels[offset:offset+4]) # # if a < 0x80 and t_value is not None: # # Sufficiently transparent # indexes.append(t_value) # continue # # try: # indexes.append(mapping[(r, g, b)]) # # except KeyError: # # Never seen this color # mapping[(r, g, b)] = pack('!B', palette_color(r, g, b, palette, t_index)) # # else: # continue # # indexes.append(mapping[(r, g, b)]) # # if hasattr(Image, 'frombytes'): # # Image.fromstring is deprecated past Pillow 2.0 # output = Image.frombytes('P', image.size, b''.join(indexes)) # else: # # PIL still uses Image.fromstring # output = Image.fromstring('P', image.size, b''.join(indexes)) # # bits = int(ceil(log(len(palette)) / log(2))) # # palette += [(0, 0, 0)] * (256 - len(palette)) # palette = reduce(add, palette) # output.putpalette(palette) # # return output # # def apply_palette256(image): # """ Get PIL to generate and apply an optimum 256 color palette to the given image and return it # """ # return image.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=256, dither=Image.NONE) . Output only the next line.
palette = urljoin(self.config.dirpath, palette)
Here is a snippet: <|code_start|> def setSaveOptionsJPEG(self, quality=None, optimize=None, progressive=None): """ Optional arguments are added to self.jpeg_options for pickup when saving. More information about options: http://effbot.org/imagingbook/format-jpeg.htm """ if quality is not None: self.jpeg_options['quality'] = int(quality) if optimize is not None: self.jpeg_options['optimize'] = bool(optimize) if progressive is not None: self.jpeg_options['progressive'] = bool(progressive) def setSaveOptionsPNG(self, optimize=None, palette=None, palette256=None): """ Optional arguments are added to self.png_options for pickup when saving. Palette argument is a URL relative to the configuration file, and it implies bits and optional transparency options. More information about options: http://effbot.org/imagingbook/format-png.htm """ if optimize is not None: self.png_options['optimize'] = bool(optimize) if palette is not None: palette = urljoin(self.config.dirpath, palette) <|code_end|> . Write the next line using the current file imports: import logging import Image from sys import modules from wsgiref.headers import Headers from io import BytesIO from .py3_compat import urljoin from time import time from .Pixels import load_palette, apply_palette, apply_palette256 from PIL import Image from ModestMaps.Core import Coordinate and context from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Pixels.py # def load_palette(file_href): # """ Load colors from a Photoshop .act file, return palette info. # # Return tuple is an array of [ (r, g, b), (r, g, b), ... ], # bit depth of the palette, and a numeric transparency index # or None if not defined. # """ # bytes_ = urlopen(file_href).read() # count, t_index = unpack('!HH', bytes_[768:768+4]) # t_index = (t_index <= 0xff) and t_index or None # # palette = [] # # for offset in range(0, count): # if offset == t_index: # rgb = 0xff, 0x99, 0x00 # else: # rgb = unpack('!BBB', bytes_[offset*3:(offset + 1)*3]) # # palette.append(rgb) # # bits = int(ceil(log(len(palette)) / log(2))) # # return palette, bits, t_index # # def apply_palette(image, palette, t_index): # """ Apply a palette array to an image, return a new image. # """ # image = image.convert('RGBA') # pixels = image.tobytes() # # t_value = (t_index in range(256)) and pack('!B', t_index) or None # mapping = {} # indexes = [] # # for offset in range(0, len(pixels), 4): # r, g, b, a = unpack('!BBBB', pixels[offset:offset+4]) # # if a < 0x80 and t_value is not None: # # Sufficiently transparent # indexes.append(t_value) # continue # # try: # indexes.append(mapping[(r, g, b)]) # # except KeyError: # # Never seen this color # mapping[(r, g, b)] = pack('!B', palette_color(r, g, b, palette, t_index)) # # else: # continue # # indexes.append(mapping[(r, g, b)]) # # if hasattr(Image, 'frombytes'): # # Image.fromstring is deprecated past Pillow 2.0 # output = Image.frombytes('P', image.size, b''.join(indexes)) # else: # # PIL still uses Image.fromstring # output = Image.fromstring('P', image.size, b''.join(indexes)) # # bits = int(ceil(log(len(palette)) / log(2))) # # palette += [(0, 0, 0)] * (256 - len(palette)) # palette = reduce(add, palette) # output.putpalette(palette) # # return output # # def apply_palette256(image): # """ Get PIL to generate and apply an optimum 256 color palette to the given image and return it # """ # return image.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=256, dither=Image.NONE) , which may include functions, classes, or code. Output only the next line.
palette, bits, t_index = load_palette(palette)
Using the snippet: <|code_start|> width, height = self.metaSize(coord) subtiles = self.metaSubtiles(coord) if self.doMetatile() or hasattr(provider, 'renderArea'): # draw an area, defined in projected coordinates tile = provider.renderArea(width, height, srs, xmin, ymin, xmax, ymax, coord.zoom) elif hasattr(provider, 'renderTile'): # draw a single tile width, height = self.dim, self.dim tile = provider.renderTile(width, height, srs, coord) else: raise KnownUnknown('Your provider lacks renderTile and renderArea methods.') if not hasattr(tile, 'save'): raise KnownUnknown('Return value of provider.renderArea() must act like an image; e.g. have a "save" method.') if hasattr(tile, 'size') and tile.size[1] != height: raise KnownUnknown('Your provider returned the wrong image size: %s instead of %d pixels tall.' % (repr(tile.size), self.dim)) if self.bitmap_palette: # this is where we apply the palette if there is one if pass_through: raise KnownUnknown('Cannot apply palette in pass_through mode') if format.lower() == 'png': t_index = self.png_options.get('transparency', None) <|code_end|> , determine the next line of code. You have imports: import logging import Image from sys import modules from wsgiref.headers import Headers from io import BytesIO from .py3_compat import urljoin from time import time from .Pixels import load_palette, apply_palette, apply_palette256 from PIL import Image from ModestMaps.Core import Coordinate and context (class names, function names, or code) available: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Pixels.py # def load_palette(file_href): # """ Load colors from a Photoshop .act file, return palette info. # # Return tuple is an array of [ (r, g, b), (r, g, b), ... ], # bit depth of the palette, and a numeric transparency index # or None if not defined. # """ # bytes_ = urlopen(file_href).read() # count, t_index = unpack('!HH', bytes_[768:768+4]) # t_index = (t_index <= 0xff) and t_index or None # # palette = [] # # for offset in range(0, count): # if offset == t_index: # rgb = 0xff, 0x99, 0x00 # else: # rgb = unpack('!BBB', bytes_[offset*3:(offset + 1)*3]) # # palette.append(rgb) # # bits = int(ceil(log(len(palette)) / log(2))) # # return palette, bits, t_index # # def apply_palette(image, palette, t_index): # """ Apply a palette array to an image, return a new image. # """ # image = image.convert('RGBA') # pixels = image.tobytes() # # t_value = (t_index in range(256)) and pack('!B', t_index) or None # mapping = {} # indexes = [] # # for offset in range(0, len(pixels), 4): # r, g, b, a = unpack('!BBBB', pixels[offset:offset+4]) # # if a < 0x80 and t_value is not None: # # Sufficiently transparent # indexes.append(t_value) # continue # # try: # indexes.append(mapping[(r, g, b)]) # # except KeyError: # # Never seen this color # mapping[(r, g, b)] = pack('!B', palette_color(r, g, b, palette, t_index)) # # else: # continue # # indexes.append(mapping[(r, g, b)]) # # if hasattr(Image, 'frombytes'): # # Image.fromstring is deprecated past Pillow 2.0 # output = Image.frombytes('P', image.size, b''.join(indexes)) # else: # # PIL still uses Image.fromstring # output = Image.fromstring('P', image.size, b''.join(indexes)) # # bits = int(ceil(log(len(palette)) / log(2))) # # palette += [(0, 0, 0)] * (256 - len(palette)) # palette = reduce(add, palette) # output.putpalette(palette) # # return output # # def apply_palette256(image): # """ Get PIL to generate and apply an optimum 256 color palette to the given image and return it # """ # return image.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=256, dither=Image.NONE) . Output only the next line.
tile = apply_palette(tile, self.bitmap_palette, t_index)
Here is a snippet: <|code_start|> if pass_through: raise KnownUnknown('Cannot apply palette in pass_through mode') if format.lower() == 'png': t_index = self.png_options.get('transparency', None) tile = apply_palette(tile, self.bitmap_palette, t_index) if self.pixel_effect: # this is where we apply the pixel effect if there is one if pass_through: raise KnownUnknown( 'Cannot apply pixel effect in pass_through mode' ) # if tile is an image if format.lower() in ('png', 'jpeg', 'tiff', 'bmp', 'gif'): tile = self.pixel_effect.apply(tile) if self.doMetatile(): # tile will be set again later tile, surtile = None, tile for (other, x, y) in subtiles: buff = BytesIO() bbox = (x, y, x + self.dim, y + self.dim) subtile = surtile.crop(bbox) if self.palette256: # this is where we have PIL optimally palette our image <|code_end|> . Write the next line using the current file imports: import logging import Image from sys import modules from wsgiref.headers import Headers from io import BytesIO from .py3_compat import urljoin from time import time from .Pixels import load_palette, apply_palette, apply_palette256 from PIL import Image from ModestMaps.Core import Coordinate and context from other files: # Path: TileStache/py3_compat.py # def is_string_type(val): # # Path: TileStache/Pixels.py # def load_palette(file_href): # """ Load colors from a Photoshop .act file, return palette info. # # Return tuple is an array of [ (r, g, b), (r, g, b), ... ], # bit depth of the palette, and a numeric transparency index # or None if not defined. # """ # bytes_ = urlopen(file_href).read() # count, t_index = unpack('!HH', bytes_[768:768+4]) # t_index = (t_index <= 0xff) and t_index or None # # palette = [] # # for offset in range(0, count): # if offset == t_index: # rgb = 0xff, 0x99, 0x00 # else: # rgb = unpack('!BBB', bytes_[offset*3:(offset + 1)*3]) # # palette.append(rgb) # # bits = int(ceil(log(len(palette)) / log(2))) # # return palette, bits, t_index # # def apply_palette(image, palette, t_index): # """ Apply a palette array to an image, return a new image. # """ # image = image.convert('RGBA') # pixels = image.tobytes() # # t_value = (t_index in range(256)) and pack('!B', t_index) or None # mapping = {} # indexes = [] # # for offset in range(0, len(pixels), 4): # r, g, b, a = unpack('!BBBB', pixels[offset:offset+4]) # # if a < 0x80 and t_value is not None: # # Sufficiently transparent # indexes.append(t_value) # continue # # try: # indexes.append(mapping[(r, g, b)]) # # except KeyError: # # Never seen this color # mapping[(r, g, b)] = pack('!B', palette_color(r, g, b, palette, t_index)) # # else: # continue # # indexes.append(mapping[(r, g, b)]) # # if hasattr(Image, 'frombytes'): # # Image.fromstring is deprecated past Pillow 2.0 # output = Image.frombytes('P', image.size, b''.join(indexes)) # else: # # PIL still uses Image.fromstring # output = Image.fromstring('P', image.size, b''.join(indexes)) # # bits = int(ceil(log(len(palette)) / log(2))) # # palette += [(0, 0, 0)] * (256 - len(palette)) # palette = reduce(add, palette) # output.putpalette(palette) # # return output # # def apply_palette256(image): # """ Get PIL to generate and apply an optimum 256 color palette to the given image and return it # """ # return image.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=256, dither=Image.NONE) , which may include functions, classes, or code. Output only the next line.
subtile = apply_palette256(subtile)