plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
libDirectional/libDirectional-master
stochasticSampling.m
.m
libDirectional-master/examples/stochasticSampling.m
2,375
utf_8
b95cc1ebeba799e1541c14fff85a6289
% This example evaluates stochastic sampling of circular densities. % % Three different sampling methods are compared, a native sample for the % respective density, a generic Metropolis-Hastings sampler, and a sampler % based on inverting the cumulative distribution function. function stochasticSampling %dist = WNDistribution(3, 1.5); dist = VMDistribution(3, 1.5); %dist = WCDistribution(3, 1.5); nSamples = 1000; samples = dist.sample(nSamples); figure(1); compare(samples, dist, 'Native Sampling'); figure(2); samples = dist.sampleMetropolisHastings(nSamples); compare(samples, dist, 'Metropolis-Hastings Sampling'); figure(3); samples = dist.sampleCdf(nSamples); compare(samples, dist, 'Sampling Based on Inversion of CDF'); end function compare(samples, distribution, titlestr) n = size(samples,2); steps = 50; s = zeros(1,steps); firstMomentError = zeros(1,steps); kuiper = zeros(1,steps); for i=1:steps s(i) = floor(i/steps*n); wd = WDDistribution(samples(:,1:s(i))); firstMomentError(i) = abs(wd.trigonometricMoment(1) - distribution.trigonometricMoment(1)); kuiper(i) = wd.kuiperTest(distribution); end [hAx,~,~] = plotyy(s, firstMomentError, s, kuiper); xlabel('samples') ylabel(hAx(1),'first moment error') % left y-axis ylabel(hAx(2),'kuiper test') % right y-axis title(titlestr); wd = WDDistribution(samples); firstMomentErrorTotal = abs(wd.trigonometricMoment(1) - distribution.trigonometricMoment(1)); kuiperTotal = wd.kuiperTest(distribution); fprintf('[%s] first moment error: %f\n', titlestr, firstMomentErrorTotal); fprintf('[%s] kuiper test: %f\n', titlestr, kuiperTotal); %llRatioWN = calculateLikelihoodRatio(samples, distribution, distribution.toWN()) %llRatioVM = calculateLikelihoodRatio(samples, distribution, distribution.toVM()) %llRatioWC = calculateLikelihoodRatio(samples, distribution, distribution.toWC()) %llRatioUniform = calculateLikelihoodRatio(samples, distribution, CircularUniformDistribution) end function lr = calculateLikelihoodRatio(samples, distribution1, distribution2) lr = exp(sum(distribution1.logLikelihood(samples)) - sum(distribution2.logLikelihood(samples))); end
github
libDirectional/libDirectional-master
quaternionMultiplication.m
.m
libDirectional-master/lib/util/quaternionMultiplication.m
725
utf_8
5f8f9db745a1a49bf998e78a0db4f783
% Calculates product of quaternions q and w % Parameters: % q (4 x 1 column vector) % first quaternion % w (4 x 1 column vector) % second quaternion % Returns: % r (4 x 1 column vector) % product q*w function r = quaternionMultiplication(q, w) assert(all(size(q) == [4 1])); assert(all(size(w) == [4 1])); % Formula based on cross product % Hart, J. C.; Francis, G. K. & Kauffman, L. H. % Visualizing Quaternion Rotation ACM Transactions on Graphics, % ACM, 1994, 13, 256-276 q0 = q(1,:); w0 = w(1,:); qvec = q(2:4,:); wvec = w(2:4,:); r = [q0 .* w0 - dot(qvec, wvec); q0 .* wvec + w0 .* qvec + cross(qvec, wvec)]; end
github
libDirectional/libDirectional-master
besselratioInverse.m
.m
libDirectional-master/lib/util/besselratioInverse.m
3,540
utf_8
3bfa2d63da38bd6f3e6a84460c69a82c
function kappa = besselratioInverse(v, x, type) % The inverse of the Ratio I_{v+1}(x)/I_v(x) is computed, where % I_v(x) is the Bessel-I function of order v evaluated at x. % % Parameters: % v (scalar) % order % x (scalar) % where to evaluate % type (string) % can be used to choose between several algorithms arguments v (1,1) double x (1,1) double type char = 'sraamos' end if x == 0 kappa = 0; return end if strcmp(type,'sraamos') assert (v==0); kappa = besselInverseSraAmos(x); elseif strcmp(type,'fisher') assert(v==0); kappa = besselInverseFisher(x); elseif strcmp(type,'amosfsolve') kappa = besselInverseAmosFsolve(v,x); elseif strcmp(type,'matlabfsolve') kappa = besselInverseMatlabFsolve(v,x); elseif strcmp(type,'sra') kappa = besselInverseSra(v,x); end end function kappa = besselInverseFisher(x) % Approximation by Fisher for v=0 % % Fisher, N. I. Statistical Analysis of Circular Data % Cambridge University Press, 1995, eq (3.47) % % recommended if speed is more important than accuracy kappa = (x<0.53).*(2*x+x.^3+5*x.^5/6) + (x>=0.53).*(x<0.85).*(-0.4+1.39*x+0.43./(1-x)) + (x>=0.85)./(x.^3-4*x.^2+3*x); end function kappa = besselInverseAmosFsolve(v,x) % Use fsolve to calculate the inverse, use the approxmation by Amos for % the ratio of bessel functions, only works well until approx. kappa=1000 f = @(t) besselratio(v,t) - x; start = 1; kappa = fsolve(f, start, optimset('Display', 'off', 'TolFun', 1e-40)); end function kappa = besselInverseMatlabFsolve(v,x) % Use fsolve to calculate the inverse, use the Matlab for the ratio of % bessel functions, only works well until approx. kappa=1000 f = @(t) besseli(v+1,t,1)/besseli(v,t,1) - x; start = 1; kappa = fsolve(f, start, optimset('Display', 'off', 'TolFun', 1e-40)); end function kappa = besselInverseSra(v,x) % Sra, S. % A Short Note on Parameter Approximation for von Mises--Fisher Distributions: And a Fast Implementation of Is (x) % Computational Statistics, Springer-Verlag, 2012, 27, 177-190 d=2*v+2; % approximation by Banaerjee et al. kappa = x*(d-x^2)/(1-x^2); % newton approximation by Sra 2012 % relies on matlab bessel functions % Attention: Sra defines A_d differently than we usually do! Ad = @(kappa) besseli(d/2, kappa, 1)/besseli(d/2-1, kappa, 1); newtonStep = @(kappa) kappa - (Ad(kappa)-x)/(1- Ad(kappa)^2 - (d-1)/kappa*Ad(kappa)); for i=2:25 kappaNew = newtonStep(kappa); if kappaNew == kappa break end kappa = kappaNew; end end function kappa = besselInverseSraAmos(x) % Combination of the methods by Sra and Amos % recommended for good if high accuracy is desired, also works for % large kappa % approximation by Banaerjee et al. kappa = x*(2-x^2)/(1-x^2); % newton approximation by Sra 2012 Ad = @(kappa) besselratio(0,kappa); %use approximation by Amos to allow large values of kappa newtonStep = @(kappa) kappa - (Ad(kappa)-x)/(1- Ad(kappa)^2 - 1/kappa*Ad(kappa)); for i=2:25 kappaNew = newtonStep(kappa); if kappaNew == kappa break end kappa = kappaNew; end end
github
libDirectional/libDirectional-master
generateSymbolic.m
.m
libDirectional-master/lib/util/generateSymbolic.m
1,215
utf_8
af1b6b5f9689ff00d9cbe748f7c983d5
function generateSymbolic(D) % Requires the symbolic toolbox, if you need to generate further files. % Files are already generated for d = 2:6. name = 'cBinghamNorm'; filename = mFilePath(D, name); if exist(filename, 'file') == 0 [c, X] = cBinghamNormSymbolic(D); mFileExport(c, X, name); end name = 'cBinghamGradLogNorm'; filename = mFilePath(D, name); if exist(filename, 'file') == 0 grad_log_c = cBinghamGradLogNormSymbolic(c, X); mFileExport(grad_log_c, X, name); end name = 'cBinghamGradNormDividedByNorm'; filename = mFilePath(D, name); if exist(filename, 'file') == 0 grad_c_divided_by_c = cBinghamGradNormDividedByNormSymbolic(c, X); mFileExport(grad_c_divided_by_c, X, name); end end function filename = mFilePath(D, name) thisFilePath = mfilename('fullpath'); filename = sprintf('%s%d.m', name, D); filename = fullfile(fileparts(thisFilePath), ['autogenerated/' filename]); end function mFileExport(expression, variables, name) D = numel(variables); filename = mFilePath(D, name); matlabFunction(expression, 'file', filename, 'vars', {variables}); end
github
libDirectional/libDirectional-master
sphMeanShift.m
.m
libDirectional-master/lib/util/sphMeanShift.m
659
utf_8
958ccbbe80ce6728e0237139b4c65685
function x_mean = sphMeanShift(x, w) % @author Kailai Li [email protected] % @date 2018 x_mean = x(:, 1); while 1 x(:, x_mean'*x < 0) = -x(:, x_mean'*x < 0); x_t = sphLog(x_mean, x); x_mean_t = sum(x_t.*w, 2); if norm(x_mean_t) < 1E-6 break end x_mean = sphExp(x_mean, x_mean_t); end end function x_t = sphLog(x_center, x) % spherical logarithm map % dot_prod = x_center' * x; alpha = acos(dot_prod); x_t = (x - dot_prod .* x_center) ./ sinc(alpha/pi); end function x = sphExp(x_center, x_t) % spherical exponential map % norm_t = vecnorm(x_t); % sqrt(sum(x_t.^2,1)); x = cos(norm_t) .* x_center + x_t .* sinc(norm_t/pi); end
github
libDirectional/libDirectional-master
cubesubdivision.m
.m
libDirectional-master/lib/util/cubesubdivision.m
2,048
utf_8
5fb465876f34031556a8763f0ea61709
% Gerhard Kurz, Florian Pfaff, Uwe D. Hanebeck, % Discretization of SO(3) Using Recursive Tesseract Subdivision % Proceedings of the 2017 IEEE International Conference on Multisensor Fusion and Integration for Intelligent Systems (MFI 2017) % Daegu, Korea, November 2017. function result = cubesubdivision(n, normalize) if nargin < 2 normalize = true; end %number of points is 6*4^n+2 quads = generateCube(); while length(unique(cell2mat(quads),'rows')) < n newQuads = cell(4*length(quads),1); for i=1:length(quads) newQuads(4*i-3:4*i,1) = subdividequad(quads{i}); end quads = newQuads; end result = unique(cell2mat(quads),'rows'); if normalize result = result./repmat(sqrt(sum(result.^2,2)), 1, 3); end end function quads = generateCube() quad2d = (dec2bin(0:3)-'0')*2-1; quads = cell(6,1); for i=1:3 %insert column with +1 or -1 at location i quads{2*i-1} = [quad2d(:,1:i-1), ones(4,1), quad2d(:,i:end)]; quads{2*i} = [quad2d(:,1:i-1), -ones(4,1), quad2d(:,i:end)]; end end function quads = subdividequad(quad) %divides given cube into 8 cubes assert(all(size(quad) == [4 3])); center = mean(quad); quads = cell(4,1); for i=1:4 %create 4 new quads p = quad(i,:); %create cube with corners p and center newCube = generateQuad(p,center); quads {i} = newCube; end end function newQuads = generateQuad(a,b) %generate axis aligned cube with opposite corners a and b x = zeros(8,3); %corner candidates %try all combinations of min/max in each dimension %todo optimize performance for i=1:8 for j=1:3 if bitget(i,j) == 1 x(i,j) = min(a(j),b(j)); else x(i,j) = max(a(j),b(j)); end end end %throw away duplicates newQuads = unique(x,'rows'); end
github
libDirectional/libDirectional-master
angularError.m
.m
libDirectional-master/lib/util/angularError.m
317
utf_8
2e98c005845e7d6a1d6fa3de25e778ea
%% Calculates the angular error between alpha and beta function e = angularError(alpha, beta) arguments alpha double {mustBeNonempty} beta double {mustBeNonempty} end alpha = mod(alpha,2*pi); beta = mod(beta,2*pi); diff = abs(alpha-beta); e = min(diff,2*pi-diff); end
github
libDirectional/libDirectional-master
complexMultiplication.m
.m
libDirectional-master/lib/util/complexMultiplication.m
457
utf_8
8061eca5ea8d1f05e0742757e60cd78d
% Calculates product of complex numbers q and w % Parameters: % q (2 x 1 column vector) % first complex number % w (2 x 1 column vector) % second complex number % Returns: % r (2 x 1 column vector) % product q*w function r = complexMultiplication(q, w) assert(all(size(q) == [2,1])); assert(all(size(w) == [2,1])); r = [q(1,:) .* w(1,:) - q(2,:) .* w(2,:); q(1,:) .* w(2,:) + q(2,:) .* w(1,:)]; end
github
libDirectional/libDirectional-master
tesseractsubdivision.m
.m
libDirectional-master/lib/util/tesseractsubdivision.m
2,141
utf_8
06207da5af3e03c28de06cff44f5f135
% Gerhard Kurz, Florian Pfaff, Uwe D. Hanebeck, % Discretization of SO(3) Using Recursive Tesseract Subdivision % Proceedings of the 2017 IEEE International Conference on Multisensor Fusion and Integration for Intelligent Systems (MFI 2017) % Daegu, Korea, November 2017. function result = tesseractsubdivision(n, normalize) if nargin < 2 normalize = true; end %numer of points is f(2^m) where m=0,1, ... and f(n)=(n+1).^4-(n-1).^4 %f is https://oeis.org/A008511 cubes = generateTesseract(); while length(unique(cell2mat(cubes),'rows')) < n newCubes = cell(8*length(cubes),1); for i=1:length(cubes) newCubes(8*i-7:8*i,1) = subdividecube(cubes{i}); end cubes = newCubes; end result = unique(cell2mat(cubes),'rows'); if normalize result = result./repmat(sqrt(sum(result.^2,2)), 1, 4); end end function cubes = generateTesseract() cube3d = (dec2bin(0:7)-'0')*2-1; cubes = cell(8,1); for i=1:4 %insert column with +1 or -1 at location i cubes{2*i-1} = [cube3d(:,1:i-1), ones(8,1), cube3d(:,i:end)]; cubes{2*i} = [cube3d(:,1:i-1), -ones(8,1), cube3d(:,i:end)]; end end function cubes = subdividecube(cube) %divides given cube into 8 cubes assert(all(size(cube) == [8 4])); center = mean(cube); cubes = cell(8,1); for i=1:8 %create 8 new cubes p = cube(i,:); %create cube with corners p and center newCube = generateCube(p,center); cubes {i} = newCube; end end function newCube = generateCube(a,b) %generate axis aligned cube with opposite corners a and b x = zeros(16,4); %corner candidates %try all combinations of min/max in each dimension %todo optimize performance for i=1:16 for j=1:4 if bitget(i,j) == 1 x(i,j) = min(a(j),b(j)); else x(i,j) = max(a(j),b(j)); end end end %throw away duplicates newCube = unique(x,'rows'); end
github
libDirectional/libDirectional-master
BinghamDistribution.m
.m
libDirectional-master/lib/distributions/Hypersphere/BinghamDistribution.m
44,212
utf_8
c8bf69cc58a27838875cc22e978de144
% The Bingham Distribution. % This class represents a d-dimensional Bingham distribution. % % Notation: % In this class, d represents the dimension of the distribution. % Currently, there is no support for uniform Bingham distributions. % % see % C. Bingham, "An antipodally symmetric distribution on the sphere", % The Annals of Statistics, vol. 2, no. 6, pp. 1201-1225, Nov. 1974. classdef BinghamDistribution < AbstractHypersphericalDistribution properties Z (:,1) double {mustBeNonpositive} % Concentrations as a vector M (:,:) double % Rotation matrix F (1,1) double % Normalization constant dF (1,:) double % Partial derivates of F end properties (Constant) S2 = AbstractHypersphericalDistribution.computeUnitSphereSurface(2) % Circle length end methods function B = BinghamDistribution(Z_, M_) % Constructs a Bingham distribution object. % Parameters: % Z_ (d x 1 column vector) % concentration parameters (have to be increasing, and last % entry has to be zero) % M_ (d x d matrix) % orthogonal matrix that describes rotation % Returns: % B (BinghamDistribution) % an object representing the constructed distribution arguments Z_ (:,1) double M_ (:,:) double end B.dim = size(M_,1); % Check Dimensions assert(size(M_,2) == B.dim, 'M is not square'); assert(size(Z_,1) == B.dim, 'Z has wrong number of rows'); assert(size(Z_,2) == 1, 'Z needs to be column vector'); % Enforce last entry of Z to be zero assert(Z_(B.dim, 1) == 0, 'last entry of Z needs to be zero'); % Enforce z1<=z2<=...<=z(d-1)<=0=z(d) assert(all(Z_(1:end-1) <= Z_(2:end)), 'values in Z have to be ascending'); %enforce that M is orthogonal epsilon = 0.001; assert (max(max(M_*M_' - eye(B.dim,B.dim))) < epsilon, 'M is not orthogonal'); B.Z = Z_; B.M = M_; B.F = BinghamDistribution.computeF(B.Z); B.dF = BinghamDistribution.computeDF(B.Z); end function p = pdf(this, xa) % Evaluates pdf at each column of xa % Parameters: % xa (d x n matrix) % each column represents one of the n points in R^d that the % pdf is evaluated at; can be just a (d x 1) vector as well % Returns: % p (1 x n row vector) % values of the pdf at each column of xa arguments this (1,1) BinghamDistribution xa (:,:) double end assert(size(xa,1) == this.dim); C = this.M * diag(this.Z) * this.M'; p = 1/this.F * exp(sum(xa.*(C*xa))); end function meanDirection(~) error('Due to their symmetry, the mean direction is undefined for Bingham distributions.'); end function B = multiply(this, B2) % Computes the product of two Bingham pdfs % This method makes use of the fact that the Bingham distribution % is closed under Bayesian inference. Thus, the product of two % Bingham pdfs is itself the pdf of a Bingham distribution. This % method computes the parameters of the resulting distribution. % % Parameters: % B2 (BinghamDistribution) % second Bingham Distribution % Returns: % B (BinghamDistribution) % Bingham distribution representing this*B2 (after % renormalization) arguments this (1,1) BinghamDistribution B2 (1,1) BinghamDistribution end assert(isa(B2, 'BinghamDistribution')); if this.dim == B2.dim C = this.M * diag(this.Z) * this.M' + B2.M * diag(B2.Z) * B2.M'; % new exponent C = 0.5*(C+C'); % Ensure symmetry of C, asymmetry may arise as a consequence of a numerical instability earlier. [V,D] = eig(C); % Eigenvalue decomposition [D, order] = sort(diag(D),'ascend'); % sort eigenvalues V = V(:,order); Z_ = D; Z_ = Z_-Z_(end); % last entry should be zero M_ = V; B = BinghamDistribution(Z_,M_); else error('dimensions do not match'); end end function B = compose(this, B2) % Compose two Bingham distributions % Using Moment Matching based approximation, we compose two Bingham % distributions. The mode of the new distribution should be the % quaternion multiplication of the original modes; the uncertainty % should be larger than before % % Parameters: % B2 (BinghamDistribution) % second Bingham Distribution % Returns: % B (BinghamDistribution) % Bingham distribution representing the convolution arguments this (1,1) BinghamDistribution B2 (1,1) BinghamDistribution end B1=this; B1S = B1.moment(); B2S = B2.moment(); if this.dim==2 && B2.dim==2 % for complex numbers % derived from complex multiplication % Gerhard Kurz, Igor Gilitschenski, Simon Julier, Uwe D. Hanebeck, % Recursive Bingham Filter for Directional Estimation Involving 180 Degree Symmetry % Journal of Advances in Information Fusion, 9(2):90 - 105, December 2014. a11 = B1S(1,1); a12 = B1S(1,2); a22 = B1S(2,2); b11 = B2S(1,1); b12 = B2S(1,2); b22 = B2S(2,2); S(1,1) = a11*b11 - 2*a12*b12 + a22*b22; S(1,2) = a11*b12 - a22*b12 - a12*b22 + a12*b11; S(2,1) = S(1,2); S(2,2) = a11*b22 + 2*a12*b12 + a22*b11; B = BinghamDistribution.fitToMoment(S); elseif this.dim==4 && B2.dim==4 % adapted from Glover's C code in libBingham, see also % Glover, J. & Kaelbling, L. P. % Tracking 3-D Rotations with the Quaternion Bingham Filter % MIT, 2013 a11 = B1S(1,1); a12 = B1S(1,2); a13 = B1S(1,3); a14 = B1S(1,4); a22 = B1S(2,2); a23 = B1S(2,3); a24 = B1S(2,4); a33 = B1S(3,3); a34 = B1S(3,4); a44 = B1S(4,4); b11 = B2S(1,1); b12 = B2S(1,2); b13 = B2S(1,3); b14 = B2S(1,4); b22 = B2S(2,2); b23 = B2S(2,3); b24 = B2S(2,4); b33 = B2S(3,3); b34 = B2S(3,4); b44 = B2S(4,4); %can be derived from quaternion multiplication S(1,1) = a11*b11 - 2*a12*b12 - 2*a13*b13 - 2*a14*b14 + a22*b22 + 2*a23*b23 + 2*a24*b24 + a33*b33 + 2*a34*b34 + a44*b44; S(1,2) = a11*b12 + a12*b11 + a13*b14 - a14*b13 - a12*b22 - a22*b12 - a13*b23 - a23*b13 - a14*b24 - a24*b14 - a23*b24 + a24*b23 - a33*b34 + a34*b33 - a34*b44 + a44*b34; S(2,1) = S(1,2); S(1,3) = a11*b13 + a13*b11 - a12*b14 + a14*b12 - a12*b23 - a23*b12 - a13*b33 + a22*b24 - a24*b22 - a33*b13 - a14*b34 - a34*b14 + a23*b34 - a34*b23 + a24*b44 - a44*b24; S(3,1) = S(1,3); S(1,4) = a11*b14 + a12*b13 - a13*b12 + a14*b11 - a12*b24 - a24*b12 - a22*b23 + a23*b22 - a13*b34 - a34*b13 - a23*b33 + a33*b23 - a14*b44 - a24*b34 + a34*b24 - a44*b14; S(4,1) = S(1,4); S(2,2) = 2*a12*b12 + a11*b22 + a22*b11 + 2*a13*b24 - 2*a14*b23 + 2*a23*b14 - 2*a24*b13 - 2*a34*b34 + a33*b44 + a44*b33; S(2,3) = a12*b13 + a13*b12 + a11*b23 + a23*b11 - a12*b24 + a14*b22 - a22*b14 + a24*b12 + a13*b34 - a14*b33 + a33*b14 - a34*b13 + a24*b34 + a34*b24 - a23*b44 - a44*b23; S(3,2) = S(2,3); S(2,4) = a12*b14 + a14*b12 + a11*b24 + a12*b23 - a13*b22 + a22*b13 - a23*b12 + a24*b11 - a14*b34 + a34*b14 + a13*b44 + a23*b34 - a24*b33 - a33*b24 + a34*b23 - a44*b13; S(4,2) = S(2,4); S(3,3) = 2*a13*b13 + 2*a14*b23 - 2*a23*b14 + a11*b33 + a33*b11 - 2*a12*b34 + 2*a34*b12 - 2*a24*b24 + a22*b44 + a44*b22; S(3,4) = a13*b14 + a14*b13 - a13*b23 + a23*b13 + a14*b24 - a24*b14 + a11*b34 + a12*b33 - a33*b12 + a34*b11 + a23*b24 + a24*b23 - a12*b44 - a22*b34 - a34*b22 + a44*b12; S(4,3) = S(3,4); S(4,4) = 2*a14*b14 - 2*a13*b24 + 2*a24*b13 + 2*a12*b34 - 2*a23*b23 - 2*a34*b12 + a11*b44 + a22*b33 + a33*b22 + a44*b11; B = BinghamDistribution.fitToMoment(S); else error('unsupported dimension'); end end function s = sample(this, n) % Stocahastic sampling % Fall back to Kent's method by default % % Parameters: % n (scalar) % number of samples % Returns: % s (dim x n) % one sample per column arguments this (1,1) BinghamDistribution n (1,1) {mustBeInteger, mustBePositive} end s = sampleKent(this, n); end function s = sampleKent(this, n) % Generate samples from Bingham distribution using rejection % sampling based on a angular central Gaussian % % Kent, J. T.; Ganeiber, A. M. & Mardia, K. V. % A New Method to Simulate the Bingham and Related Distributions in Directional Data Analysis with Applications % arXiv preprint arXiv:1310.8110, 2013 arguments this (1,1) BinghamDistribution n (1,1) {mustBeInteger, mustBePositive} end s = zeros(this.dim, n); i = 1; A = - this.M * diag(this.Z) * this.M'; % Kent uses a minus sign here! q = this.dim; % compute b bfun = @(b) sum(1./(b-2*this.Z)) - 1; % use a minus sign before 2*this.z because Kent's matrix is negative b = fsolve(bfun, 1, optimset('display', 'none')); Omega = eye(this.dim) + 2*A/b; %efficiency = 1/(exp(-(q-b)/2) * (q/b)^(q/2)) %Mb = 1/this.F * exp(-(q-b)/2) * (q/b)^(q/2) * det(Omega)^(-1/2); Mbstar = exp(-(q-b)/2) * (q/b)^(q/2); nReject = 0; fbingstar = @(x) exp(-x' * A * x); facgstar = @(x) (x' * Omega * x)^(-q/2); while(i<=n) % draw x from angular central Gaussian y = mvnrnd(zeros(this.dim,1), inv(Omega))'; x = y/norm(y); % check rejection W = rand(1); if W < fbingstar(x) /(Mbstar * facgstar(x)) s(:,i) = x; i = i + 1; else nReject = nReject + 1; end end %nReject end function X = sampleGlover(this, n) % Generate samples from Bingham distribution % based on Glover's implementation in libBingham % uses Metropolis-Hastings % see http://en.wikipedia.org/wiki/Metropolis-Hastings_algorithm % % The implementation has a bug because it just repeats the % previos sample if a sample is rejected. % % Parameters: % n (scalar) % number of samples to generate % Returns: % X (dimx n matrix) % generated samples (one sample per column) arguments this (1,1) BinghamDistribution n (1,1) {mustBeInteger, mustBePositive} end burnin = 5; samplerate = 10; x = this.mode(); z = sqrt(-1./(this.Z - 1)); target = this.pdf(x); % target proposal = acgpdf_pcs(x', z, this.M); % proposal X2 = (randn(n*samplerate+burnin,this.dim).*repmat(z',[n*samplerate+burnin,1]))*this.M'; % sample Gaussian X2 = X2 ./ repmat(sqrt(sum(X2.^2,2)), [1 this.dim]); % normalize Target2 = this.pdf(X2'); Proposal2 = acgpdf_pcs(X2, z, this.M); nAccepts = 0; X = zeros(size(X2)); for i=1:n*samplerate+burnin a = Target2(i) / target * proposal / Proposal2(i); if a > rand() x = X2(i,:); proposal = Proposal2(i); target = Target2(i); nAccepts = nAccepts + 1; end X(i,:) = x; end %accept_rate = num_accepts / (n*sample_rate + burn_in) X = X(burnin+1:samplerate:end,:)'; end function m = mode(this) % Calculate the mode of a Bingham distribution % Returns: % m (column vector) % mode of the distribution (note that -m is the mode as well) arguments this (1,1) BinghamDistribution end m = this.M(:,end); %last column of M end function S = moment(this) arguments this (1,1) BinghamDistribution end % Calculate scatter/covariance matrix of Bingham distribution % Returns: % S (d x d matrix) % scatter/covariance matrix in R^d D = diag(this.dF/this.F); % the sum of the diagonal of D is always 1, however this may % not be the case because dF and F are calculated using % approximations D = D / sum(diag(D)); S = this.M * D * this.M'; S = (S+S')/2; % enforce symmetry end function [samples, weights] = sampleDeterministic(this, lambda) % Computes deterministic samples of a Bingham distribution. % The computed samples represent the current Bingham distribution. % They are choosen in a deterministic way, which is a circular % adaption of the UKF. % % see % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck, % Unscented Orientation Estimation Based on the Bingham Distribution % IEEE Transactions on Automatic Control, January 2016. % % Important: The paper discusses samples from both modes of the % Bingham. This code only samples from one mode. If desired, the samples % from the other mode can be obtained by mirroring: % [s,w] = bd.sampleDeterministic % s2 = [s, -s] % w2 = [w, w]/2 % % Parameters: % lambda (scalar or string) % weighting parameter in [0,1] or the string 'uniform' (only % in 2D) % Returns: % samples (d x ... matrix) % generated samples (one sample per column) % weights (1 x ... vector) % weight > 0 for each sample (weights sum to one) arguments this (1,1) BinghamDistribution lambda = [] end if isempty(lambda) % default value for lambda if this.dim == 2 lambda = 'uniform'; else lambda = 0.5; end end if strcmp(lambda,'uniform') && this.dim == 2 % uniform weights can only be guaranteed for d=2 B = BinghamDistribution(this.Z, eye(2,2)); S = B.moment(); alpha = asin(sqrt(S(1,1)*3/2)); samples = [ 0, 1; sin(alpha), cos(alpha); -sin(alpha), cos(alpha)]; samples = this.M*samples'; weights = [1/3, 1/3, 1/3]; else assert (lambda>=0 && lambda <=1); B = BinghamDistribution(this.Z, eye(this.dim,this.dim)); S = B.moment(); samples = zeros(2*this.dim-1,this.dim); weights = zeros(1, 2*this.dim-1); p = zeros(1, this.dim-1); alpha = zeros(1, this.dim-1); samples(1,end) = 1; %sample at mode for i=1:this.dim-1 p(i) = S(i,i) + (1-lambda)*(S(end,end)/(this.dim-1)); alpha(i) = asin(sqrt(S(i,i)/p(i))); samples(2*i,end) = cos(alpha(i)); samples(2*i+1,end) = cos(alpha(i)); samples(2*i,i) = sin(alpha(i)); samples(2*i+1,i) = -sin(alpha(i)); weights(1,2*i) = p(i)/2; weights(1,2*i+1) = p(i)/2; end weights(1) = 1-sum(weights(2:end)); % = lambda*S(4,4) samples = this.M*samples'; end end function [samples, weights] = sampleOptimalQuantization(this, N) % Computes optimal quantization of the % Bingham distribution using 2*N samples. % % Parameters: % N(scalar) % number of samples on half circle % Returns: % samples (1 x 2N) % 2N samples on the circle, parameterized as [0,2pi) % weights (1 x 2N) % weight for each sample % % Igor Gilitschenski, Gerhard Kurz, Uwe D. Hanebeck, Roland Siegwart, % Optimal Quantization of Circular Distributions % Proceedings of the 19th International Conference on Information Fusion (Fusion 2016), Heidelberg, Germany, July 2016. arguments this (1,1) BinghamDistribution N (1,1) {mustBeInteger, mustBePositive} end assert(this.dim == 2, 'sampleOptimalQuantization only implemented for 2d Bingham'); mu = atan2(this.M(2,2), this.M(1,2)); kappa = (this.Z(2)-this.Z(1))/2; [samples, weights] = VMDistribution(0, kappa).sampleOptimalQuantization(N); samples = [samples/2 (samples/2+pi)]; samples = mod(samples+mu,2*pi); weights = [weights weights]/2; end function [s,w] = sampleWeighted(this, n) % Weighted sample generator. % Generates uniform (w.r.t. the Haar Measure) random samples on % the unit sphere and assigns each sample a weight based on the % pdf. % % Parameters: % n (scalar) % number of samples % % Returns: % samples (d x n matrix) % generated samples (one sample per column) % weights (1 x n vector) arguments this (1,1) BinghamDistribution n (1,1) {mustBeInteger, mustBePositive} end s = mvnrnd(zeros(1,this.dim), eye(this.dim), n)'; s = s./repmat(sqrt(sum(s.^2,1)),this.dim, 1); w = this.pdf(s); w = w/sum(w); % normalize weights end function alpha = bounds(this, p) % Calculates the confidence interval for a given confidence p % Only works for d=2 so far. % Parameters: % p (scalar) % confidence to achieve, 0<p<1 % Returns: % alpha (scalar) % the confidence interval ranges from mode-alpha to % mode+alpha arguments this (1,1) BinghamDistribution p (1,1) {mustBeInRange(p,0,1,'exclusive')} end if this.dim==2 assert(p>0) assert(p<1) f = @(phi) this.pdf([cos(phi); sin(phi)]); mB = this.mode(); mBangle = atan2(mB(2), mB(1)); g = @(alpha) integral(f,mBangle,mBangle+alpha, 'AbsTol', 0.01) - p/2; alpha = fsolve(g, 0.1, optimset('display', 'none')); else error('unsupported dimension'); end end function P = gaussianCovariance(this, angle) % Calculates the covariance to obtain a comparable Gaussian. % Attention: this does not compute the covariance of the entire % Bingham but only on the half sphere! % % Returns: % P (1 x 1 matrix for d=2, if angle = true (angle represenation) % d x d matrix for d>=2, if angle = false (vector % representation) arguments this (1,1) BinghamDistribution angle = false end if angle assert(this.dim==2) m = this.mode(); mAngle = atan2(m(2),m(1)); % sample-based solution: % samples = this.sample(1000); % sampleAngles = atan2(samples(:,2), samples(:,1)); % sampleAngles = mod(sampleAngles + pi/2 + mAngle, pi); % P = cov(sampleAngles); % numerical-integration-based solution P = 2*integral(@(phi) this.pdf([cos(mAngle+phi);sin(mAngle+phi)]).*phi.^2, -pi/2, +pi/2); else if this.dim==2 % numerical-integration-based solution: m = this.mode(); mAngle = atan2(m(2),m(1)); fx = @(phi) 2*this.pdf([cos(phi);sin(phi)]).*(cos(phi)-m(1)).^2; fxy = @(phi) 2*this.pdf([cos(phi);sin(phi)]).*(cos(phi)-m(1)).*(sin(phi)-m(2)); fy = @(phi) 2*this.pdf([cos(phi);sin(phi)]).*(sin(phi)-m(2)).^2; P(1,1) = integral(fx, mAngle-pi/2, mAngle+pi/2); P(1,2) = integral(fxy, mAngle-pi/2, mAngle+pi/2); P(2,1) = P(1,2); P(2,2) = integral(fy, mAngle-pi/2, mAngle+pi/2); else count = 1000; samples = this.sample(count); for i=1:count if samples(:,i)'*this.mode()<0 %scalar product samples(:,i)=-samples(:,i); end end %P = cov(samples); % do not use cov, because the mean of the Gaussian will % be at the mode of the Bingham, not at the mean of the % samples samples = samples - repmat(this.mode(), 1, count); P = samples*samples'/count; end end end end methods (Static) function F = computeF(Z, mode) % Compute normalization constant % Parameters: % Z (d x d matrix) % concentration matrix % mode (string, optional) % choses the algorithm to compute the normalization constant % Returns: % F (scalar) % the calculated normalization constant assert(size(Z,2) == 1); dim = length(Z); if nargin<2 mode = 'default'; end if dim == 2 if strcmp(mode, 'default') || strcmp(mode, 'bessel') % Gerhard Kurz, Igor Gilitschenski, Simon Julier, Uwe D. Hanebeck, % Recursive Bingham Filter for Directional Estimation Involving 180 Degree Symmetry % Journal of Advances in Information Fusion, 9(2):90 - 105, December 2014. F = exp(Z(2))* BinghamDistribution.S2 * besseli(0,(Z(1)-Z(2))/2) * exp((Z(1)-Z(2))/2); elseif strcmp(mode, 'hypergeom') % Gerhard Kurz, Igor Gilitschenski, Simon J. Julier, Uwe D. Hanebeck, % Recursive Estimation of Orientation Based on the Bingham Distribution % Proceedings of the 16th International Conference on Information Fusion (Fusion 2013), Istanbul, Turkey, July 2013. F = exp(Z(2))* BinghamDistribution.S2 * double(hypergeom(0.5,1, vpa(Z(1)-Z(2)))); elseif strcmp(mode, 'mhg') % Koev, P. & Edelman, A. % The Efficient Evaluation of the Hypergeometric Function of a Matrix Argument % Mathematics of Computation., 2006, 75, 833-846 F = BinghamDistribution.S2 * mhg(100, 2, 0.5, dim/2, Z); elseif strcmp(mode, 'saddlepoint') % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck, % Efficient Bingham Filtering based on Saddlepoint Approximations % Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014. F = numericalSaddlepointWithDerivatives(sort(-Z)+1)*exp(1); F = F(3); elseif strcmp(mode, 'glover') % https://code.google.com/p/bingham/ % and % % Glover, J. & Kaelbling, L. P. % Tracking 3-D Rotations with the Quaternion Bingham Filter % MIT, 2013 % http://dspace.mit.edu/handle/1721.1/78248 F = glover(Z); else error('unsupported mode'); end else if strcmp(mode, 'default') || strcmp(mode, 'saddlepoint') % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck, % Efficient Bingham Filtering based on Saddlepoint Approximations % Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014. F = numericalSaddlepointWithDerivatives(sort(-Z)+1)*exp(1); F = F(3); elseif strcmp(mode, 'mhg') % Koev, P. & Edelman, A. % The Efficient Evaluation of the Hypergeometric Function of a Matrix Argument % Mathematics of Computation., 2006, 75, 833-846 F = AbstractHypersphericalDistribution.computeUnitSphereSurface(dim) * mhg(100, 2, 0.5, dim/2, Z); elseif strcmp(mode, 'wood') && dim == 4 % ANDREW T.A. WOOD % ESTIMATION OF THE CONCENTRATION PARAMETERS % OF THE FISHER MATRIX DISTRIBUTION ON SO(3) % AND THE BINGHAM DISTRIBUTION ON Sq, q>= 2 % Austral. J. Statist., S5(1), 1993, 69-79 J = @(Z,u) besseli(0, 0.5 .* abs(Z(1)-Z(2)) .* u) .* besseli(0, 0.5 .* abs(Z(3)-Z(4)) .* (1-u)); ifun = @(u) J(Z,u).*exp(0.5 .* (Z(1)+Z(2)).* u + 0.5.*(Z(3)+Z(4)).*(1-u)); F = 2*pi^2*integral(ifun,0,1); elseif strcmp(mode, 'glover') && dim <= 4 % https://code.google.com/p/bingham/ % and % % Glover, J. & Kaelbling, L. P. % Tracking 3-D Rotations with the Quaternion Bingham Filter % MIT, 2013 % http://dspace.mit.edu/handle/1721.1/78248 if any(abs(Z(1:end-1))<1e-8) warning('Glover''s method currently does not work for Z with more than one zero entry.'); end F = glover(Z); else error('unsupported mode'); end end end %todo: add glover? function dF = computeDF(Z, mode) % Partial derivatives of normalization constant % Parameters: % Z (d x d matrix) % concentration matrix % Returns: % dF (scalar) % the calculated derivative of the normalization constant assert(size(Z,2) == 1); dim = size(Z,1); dF = zeros(1,dim); if nargin<2 mode = 'default'; end if dim==2 if strcmp(mode, 'default') || strcmp(mode, 'bessel') % Gerhard Kurz, Igor Gilitschenski, Simon Julier, Uwe D. Hanebeck, % Recursive Bingham Filter for Directional Estimation Involving 180 Degree Symmetry % Journal of Advances in Information Fusion, 9(2):90 - 105, December 2014. b1 = besseli(1,(Z(1)-Z(2))/2); b0 = besseli(0,(Z(1)-Z(2))/2); dF(1) = BinghamDistribution.S2/2 * (b1 + b0)* exp((Z(1)+Z(2))/2); dF(2) = BinghamDistribution.S2/2 * (-b1 + b0 )* exp((Z(1)+Z(2))/2); elseif strcmp(mode, 'hypergeom') % Gerhard Kurz, Igor Gilitschenski, Simon J. Julier, Uwe D. Hanebeck, % Recursive Estimation of Orientation Based on the Bingham Distribution % Proceedings of the 16th International Conference on Information Fusion (Fusion 2013), Istanbul, Turkey, July 2013. h = double(hypergeom(1.5,2,vpa(Z(1)-Z(2)))); dF(1) = BinghamDistribution.S2 * exp(Z(2)) * 0.5 * h; dF(2) = BinghamDistribution.S2 * exp(Z(2)) * (double(hypergeom(0.5,1, vpa(Z(1)-Z(2)))) - 0.5*h); elseif strcmp(mode, 'saddlepoint') % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck, % Efficient Bingham Filtering based on Saddlepoint Approximations % Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014. for i=1:dim ModZ = Z([1:i i i:dim]); T = numericalSaddlepointWithDerivatives(sort(-ModZ)+1)*exp(1)/(2*pi); dF(i) = T(3); end elseif strncmp(mode, 'finitedifferences', 17) % Approximation by finite Differences % use mode='finitedifferences-method', where method % is a method for calculating the normalizaton % constant for i=1:dim epsilon=0.001; dZ = [zeros(i-1,1); epsilon; zeros(dim-i,1)]; F1 = BinghamDistribution.computeF(Z + dZ, mode(19:end)); F2 = BinghamDistribution.computeF(Z - dZ, mode(19:end)); dF(i) = (F1-F2)/(2*epsilon); end else error('unsupported mode'); end else if strcmp(mode, 'default') || strcmp(mode, 'saddlepoint') % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck, % Efficient Bingham Filtering based on Saddlepoint Approximations % Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014. for i=1:dim ModZ = Z([1:i i i:dim]); T = numericalSaddlepointWithDerivatives(sort(-ModZ)+1)*exp(1)/(2*pi); dF(i) = T(3); end elseif strncmp(mode, 'finitedifferences', 17) for i=1:dim % Approximation by finite differences % use mode='finitedifferences-method', where method % is a method for calculating the normalizaton % constant epsilon=0.001; dZ = [zeros(i-1,1); epsilon; zeros(dim-i,1)]; F1 = BinghamDistribution.computeF(Z + dZ, mode(19:end)); F2 = BinghamDistribution.computeF(Z - dZ, mode(19:end)); dF(i) = (F1-F2)/(2*epsilon); end else error('unsupported mode'); end end end function B = fit(samples, weights, options) % Fits Bingham parameters to a set of samples % Parameters: % samples (d x n matrix) % matrix that contains one sample per column % weights (1 x n row vector) % weight for each sample % options (struct) % parameter to select the MLE algorithm % Returns: % B (BinghamDistribution) % the MLE estimate for a Bingham distribution given the % samples n = size(samples,2); if nargin<2 C = samples*samples'/n; else assert(abs(sum(weights)-1) < 1E-10, 'weights must sum to 1'); %check normalization assert(size(weights,1)==1, 'weights needs to be a row vector'); assert(size(weights,2)==n, 'number of weights and samples needs to match'); C = samples.*weights*samples'; end C = (C+C')/2; % ensure symmetry if nargin<3 B = BinghamDistribution.fitToMoment(C); else B = BinghamDistribution.fitToMoment(C, options); end end function B = fitToMoment(S, options) % Finds a Bingham distribution with a given second moment % % Parameters: % S (d x d matrix) % matrix representing second moment. % options (struct) % parameters to configure the MLE algorithm % Returns: % B (BinghamDistribution) % the MLE estimate for a Bingham distribution given the % scatter matrix S assert(all(all(S == S')), 'S must be symmetric'); if nargin < 2 options.algorithm = 'default'; end assert(isfield(options,'algorithm'), ... 'Options need to contain an algorithm field'); if strcmp(options.algorithm, 'default') || strcmp(options.algorithm, 'fsolve') % Gerhard Kurz, Igor Gilitschenski, Simon Julier, Uwe D. Hanebeck, % Recursive Bingham Filter for Directional Estimation Involving 180 Degree Symmetry % Journal of Advances in Information Fusion, 9(2):90 - 105, December 2014. [eigenvectors,omega] = eig(S); [omega, order] = sort(diag(omega),'ascend'); % sort eigenvalues M_ = eigenvectors(:,order); % swap columns to match the sorted eigenvalues omega = omega / sum(omega); % ensure that entries sum to one Z_ = BinghamDistribution.mleFsolve(omega, options); % This reordering shouldn't be necessary. However, it can % become necessary as a consequence of numerical errors when % fitting to moment matrices with almost equal eigenvalues. [Z_, order] = sort(Z_,'ascend'); %sort eigenvalues M_ = M_(:,order); Z_=Z_-Z_(size(Z_,1)); %subtract last entry to ensure that last entry is zero B = BinghamDistribution(Z_,M_); elseif strcmp(options.algorithm, 'fminunc') [eigenvectors,omega] = eig(S); [omega, order] = sort(diag(omega),'ascend'); % sort eigenvalues M_ = eigenvectors(:,order); % swap columns to match the sorted eigenvalues omega = omega / sum(omega); % ensure that entries sum to one Z_ = BinghamDistribution.mleFminunc(omega, options); % This reordering shouldn't be necessary. However, it can % become necessary as a consequence of numerical errors when % fitting to moment matrices with almost equal eigenvalues. [Z_, order] = sort(Z_,'ascend'); %sort eigenvalues M_ = M_(:,order); Z_=Z_-Z_(size(Z_,1)); %subtract last entry to ensure that last entry is zero B = BinghamDistribution(Z_,M_); elseif strcmp(options.algorithm, 'gaussnewton') % Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck, % Efficient Bingham Filtering based on Saddlepoint Approximations % Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014. [eigenvectors,omega] = eig(S); [omega, order] = sort(diag(omega),'ascend'); %sort eigenvalues M_ = eigenvectors(:,order); %swap columns to match the sorted eigenvalues omega = omega / sum(omega); % ensure that entries sum to one Z_ = numericalBinghamMLE(omega); % This reordering shouldn't be necessary. However, it can % become necessary as a consequence of numerical errors when % fitting to moment matrices with almost equal eigenvalues. [Z_, order] = sort(Z_,'ascend'); %sort eigenvalues M_ = M_(:,order); Z_=Z_-Z_(size(Z_,1)); %subtract last entry to ensure that last entry is zero B = BinghamDistribution(Z_,M_); else error('Unsupported estimation algorithm'); end end function Z = mleFsolve (omega, options) % Calculate maximum likelihood estimate of Z. % Considers only the first three values of omega. % % Parameters: % omega (d x 1 column vector) % eigenvalues of the scatter matrix % Returns: % Z (d x 1 column vector) if nargin < 2 || ~isfield(options, 'Fmethod') options.Fmethod = 'default'; end if nargin < 2 || ~isfield(options, 'dFmethod') options.dFmethod = 'default'; end function r = mleGoalFun(z, rhs) % objective function of MLE. d = size(z,1)+1; %if d == 2 a = BinghamDistribution.computeF([z;0], options.Fmethod); b = BinghamDistribution.computeDF([z;0], options.dFmethod); %else % [a,b] = numericalSaddlepointWithDerivatives([-z; 0]); % a = a(3); % b = b(3,:); %end r = zeros(d-1,1); for i=1:(d-1) r(i) = b(i)/a - rhs(i); end end dim = size(omega,1); f = @(z) mleGoalFun(z, omega); Z = fsolve(f, -ones(dim-1,1), optimset('display', 'off', 'algorithm', 'levenberg-marquardt')); Z = [Z; 0]; end function Z = mleFminunc (omega, options) % Calculate maximum likelihood estimate of Z. % Considers all four values of omega. % % Parameters: % omega (d x 1 column vector) % eigenvalues of the scatter matrix % Returns: % Z (d x 1 column vector) if nargin < 2 || ~isfield(options, 'Fmethod') options.Fmethod = 'default'; end if nargin < 2 || ~isfield(options, 'dFmethod') options.dFmethod = 'default'; end function r = mleGoalFun(z, rhs) % objective function of MLE. d = size(z,1)+1; %if d == 2 a = BinghamDistribution.computeF([z;0], options.Fmethod); b = BinghamDistribution.computeDF([z;0], options.dFmethod); %else % [a,b] = numericalSaddlepointWithDerivatives([-z; 0]); % a = a(3); % b = b(3,:); %end r = zeros(d,1); for i=1:d r(i) = b(i)/a - rhs(i); end r=norm(r); end dim = size(omega,1); f = @(z) mleGoalFun(z, omega); Z = fminunc(f, -ones(dim-1,1), optimoptions('fminunc','algorithm','quasi-newton', 'display', 'off')); Z = [Z; 0]; end end end function P = acgpdf_pcs(X,z,M) %taken from libBingham %P = acgpdf_pcs(X,z,;) -- z and M are the sqrt(eigenvalues) and %eigenvectors of the covariance matrix; x's are in the rows of X S_inv = M*diag(1./(z.^2))*M'; d = size(X,2); P = repmat(1 / (prod(z) * BinghamDistribution.computeUnitSphereSurface(d)), [size(X,1),1]); md = sum((X*S_inv).*X, 2); % mahalanobis distance P = P .* md.^(-d/2); end
github
libDirectional/libDirectional-master
circVMcdf.m
.m
libDirectional-master/lib/external/circVMcdf.m
2,511
utf_8
02fe9e452bc8b1c42bd0b222292d3062
function res = circVMcdf(T,VK) %circVMcdf cumulative Von-Mises distribution VM(0,k) % res = circVMcdf(T,VK) % T - angles at which to compute CDF % VK - kappa value for distribution % % Directly converted from Fortran code published in % % Algorithm 518: Incomplete Bessel Function I0. % The Von Mises Distribution [S14] % ACM Transactions on Mathematical Software (TOMS) % Volume 3 , Issue 3 (September 1977) % Pages: 279 - 284 % Author: Geoffrey W. Hill % % (A BibTeX citation is in a comment at the end of this file) % % By Shai Revzen, Berkeley 2006 % Modified by Gerhard Kurz, KIT 2015 % 8 digit accuracy % CK = 10.5; % 12 digit accuracy CK = 50; if length(VK) ~= 1 error('circ:mustBeScalar','kurtosis must be a scalar') end %T = T-mu; Z = VK; U = mod(T+pi,2*pi); Y = U-pi; if Z>CK res = largeVK(Y, Z); elseif Z<=0 res = (U*0.5)/pi; else V = smallVK(Y, Z); res = (U*0.5+V)/pi; end res(res<0)=0; res(res>1)=1; end function V = smallVK( Y, Z ) % 8 digit accuracy %A1 = 12; A2 = 0.8; A3 = 8.0; A4 = 1.0; % 12 digit accuracy A1 = 28; A2 = 0.5; A3 = 100.0; A4 = 5.0; IP = Z*A2 - A3/(Z+A4) + A1; P = round(IP); S = sin(Y); C = cos(Y); Y = P*Y; SN = sin(Y); CN = cos(Y); R = 0.0; V = 0.0; Z = 2.0/Z; for N=2:round(IP) P = P - 1.0; Y = SN; SN = SN.*C - CN.*S; CN = CN.*C + Y.*S; R = 1.0./(P*Z+R); V = (SN./P+V)*R; end end function res = largeVK( Y, Z ) % 8 digit accuracy % C1 = 56; % 12 digit accuracy C1 = 50.1; C = 24.0 * Z; V = C - C1; R=sqrt((54.0/(347.0/V+26.0-C)-6.0+C)/12.0); Z=sin(Y*0.5)*R; S=Z.*Z*2.0; V = V - S + 3.0; Y = (C-S-S-16.0)/3.0; Y = ((S+1.75)*S+83.5)/V - Y; res=erf(Z-S/(Y.*Y).*Z)*0.5+0.5; end % BibTeX: % @article{355753, % author = {Geoffrey W. Hill}, % title = {Algorithm 518: Incomplete Bessel Function I0. % The Von Mises Distribution [S14]}, % journal = {ACM Trans. Math. Softw.}, % volume = {3}, % number = {3}, % year = {1977}, % issn = {0098-3500}, % pages = {279--284}, % doi = {http://doi.acm.org/10.1145/355744.355753}, % publisher = {ACM Press}, % address = {New York, NY, USA}, % }
github
libDirectional/libDirectional-master
wigner3jm.m
.m
libDirectional-master/lib/external/slepian_alpha/wigner3jm.m
13,476
utf_8
a051e6ecc6ac2a6461d55afb9277a876
function [w3j,j]=wigner3jm(L,l2,l3,m1,m2,m3) % [w3j,j]=WIGNER3JM(L,l2,l3,m1,m2,m3) % % Calculates Wigner 3j symbols by recursion, for all values of j<=L % allowed in the expression (L l2 l3) % (m1 m2 m3) % There is no truncation at any bandwidth - they are all returned % Note the selection rules: % jmin = max(|l2-l3|, |m1|) % jmax = l2 + l3 % m1 + m2 + m3 = 0. % % INPUT: % % L Maximum degree, bandwidth [default: that what's allowed] % l2,l3 Other degrees in the symbol above, don't have to be integers % m1,m2,m3 Orders in the symbol above, don't have to be integers, and % note that the defaults here are not zero! % % OUTPUT: % % w3j The Wigner3j function % j The first degrees from 0 to L % With normalization check % % EXAMPLES: % % wigner3jm('demo1') % Should return nothing if it all works % wigner3jm('demo2') % Reproduces Table I of Schulten and Gordon % % See also: WIGNER0J, GUSEINOV, THREEJ, ZEROJ % % Last modified by fjsimons-at-alum.mit.edu, 06/15/2010 % Last modified by Florian Pfaff for libDirectional, 11/04/2016 % Note, if you truncate, like here, at the degree L, you're actually % doing too much work; you could improve this. % After Fortran (could you tell?) by Mark Wieczorek, who further notes: % Returned values have a relative error less than ~1.d-8 when l2 and l3 are % less than 103 (see below). In practice, this routine is probably usable up % to 165. This routine is based upon the stable non-linear recurrence % relations of Luscombe and Luban (1998) for the "non classical" regions near % jmin and jmax. For the classical region, the standard three term recursion % relationship is used (Schulten and Gordon 1975). Note that this three term % recursion can be unstable and can also lead to overflows. Thus the values % are rescaled by a factor "scalef" whenever the absolute value of the 3j % coefficient becomes greater than unity. Also, the direction of the iteration % starts from low values of j to high values, but when abs(w3j(j+2)/w3j(j)) is % less than one, the iteration will restart from high to low values. More % efficient algorithms might be found for specific cases (for instance, when % all m's are zero). % Verification: % The results have been verified against this routine run in quadruple % precision. For 1.e7 acceptable random values of l2, l3, m2, and m3 between % -200 and 200, the relative error was calculated only for those 3j % coefficients that had an absolute value greater than 1.d-17 (values smaller % than this are for all practical purposed zero, and can be heavily affected % by machine roundoff errors or underflow). 853 combinations of parameters % were found to have relative errors greater than 1.d-8. Here I list the % minimum value of max(l2,l3) for different ranges of error, as well as the % number of times this occured 1.d-7 < error <=1.d-8 = 103 # = 483 1.d-6 < % error <= 1.d-7 = 116 # = 240 1.d-5 < error <= 1.d-6 = 165 # = 93 1.d-4 < % error <= 1.d-5 = 167 # = 36 % Many times (maybe always), the large relative errors occur when the 3j % coefficient changes sign and is close to zero. (I.e., adjacent values are % about 10.e7 times greater in magnitude.) Thus, if one does not need to know % highly accurate values of the 3j coefficients when they are almost zero % (i.e., ~1.d-10) then this routine is probably usable up to about 160. % These results have also been verified for parameter values less than 100 % using a code based on the algorithm of de Blanc (1987), which was originally % coded by Olav van Genabeek, and modified by M. Fang (note that this code was % run in quadruple precision, and only calculates one coefficient for each % call. I also have no idea if this code was verified.) Maximum relative % errors in this case were less than 1.d-8 for a large number of values % (again, only 3j coefficients greater than 1.d-17 were considered here). The % biggest improvement that could be made in this routine is to determine when % one should stop iterating in the forward direction, and start iterating from % high to low values. if ~ischar(L) switch nargin case 0 l2=6;l3=5; L=l2+l3; m1=3;m2=2;m3=-5; case 1 l2=6;l3=5; m1=3;m2=2;m3=-5; case 2 l3=5; m1=3;m2=2;m3=-5; case 3 m1=3;m2=2;m3=-5; case 4 m2=2;m3=-5; case 5 m3=-5; end flag1=0; flag2=0; % Didn't realize this factor was wrong until 10/02/2006 % But - Luscombe and Luban imply that the three-term recursion in the % classical, oscillatory region rarely suffers from the overflows - all % should be probably well scalef=1000; jmin=max(abs(l2-l3),abs(m1)); jmax=l2+l3; jnum=jmax-jmin+1; % Initialize w3j=zeros(1,jnum); if abs(m2)>l2 || abs(m3)>l3 w3j=zeros(L+1,1)'; j=0:L; return elseif m1+m2+m3~=0 w3j=zeros(L+1,1)'; j=0:L; return elseif jmax<jmin w3j=zeros(L+1,1)'; j=0:L; return end % Only one value is allowed if jnum==1 w3j=1/sqrt(2*jmin+1); if (w3j<0 && (-1)^(l2-l3+m2+m3)>0) || ... (w3j>0 && (-1)^(l2-l3+m2+m3)<0) w3j=-w3j; end [w3j,j]=output(jmin,l2,l3,L,w3j); return end % Calculate lower non-classical values for [jmin, jn]. If the second % term can not be calculated because the recursion relationsips give % rise to a 1/0, then set flag1 to 1. If all m's are zero, then this % is not a problem as all odd terms must be zero. [rs,wu,wl]=deal(0); warning off rs(1)=-x(jmin,l2,l3,m1)/y(jmin,l2,l3,m1,m2,m3); warning on if m1==0 && m2==0 && m3==0 wl(1)=1; wl(2)=0; jn=jmin+1; elseif y(jmin,l2,l3,m1,m2,m3)==0 if x(jmin,l2,l3,m1)==0 flag1=1; jn=jmin; else wl(1)=1; wl(2)=0; jn=jmin+1; end elseif rs(1)<=0 wl(1)=1; wl(2)=-y(jmin,l2,l3,m1,m2,m3)/x(jmin,l2,l3,m1); jn=jmin+1; else jn=jmax; for j=jmin+1:jmax-1 denom=y(j,l2,l3,m1,m2,m3)+z(j,l2,l3,m1)*rs(j-jmin); warning off rs(j-jmin+1)=-x(j,l2,l3,m1)/denom; warning on if (rs(j-jmin+1)>1 || rs(j-jmin+1) <= 0 || denom==0) jn=j-1; break end end wl(jn-jmin+1)=1; for k=1:jn-jmin wl(jn-k-jmin+1)=wl(jn-k-jmin+2)*rs(jn-k-jmin+1); end if (jn==jmin) wl(2)=-y(jmin,l2,l3,m1,m2,m3)/x(jmin,l2,l3,m1); jn=jmin+1; end end if jn==jmax w3j(1:jnum)=wl(1:jnum); w3j=normw3j(w3j,jmin,jmax,jnum); w3j=fixsign(w3j,jnum,l2,l3,m2,m3); [w3j,j]=output(jmin,l2,l3,L,w3j); return end % Calculate upper non-classical values for [jp, jmax]. % If the second last term can not be calculated because the % recursion relations give a 1/0, then set flag2 to 1. warning off rs(jnum)=-z(jmax,l2,l3,m1)/y(jmax,l2,l3,m1,m2,m3); warning on if m1==0 && m2==0 && m3==0 wu(jnum)=1; wu(jmax-jmin)=0; jp=jmax-1; elseif y(jmax,l2,l3,m1,m2,m3)==0 if z(jmax,l2,l3,m1)==0 flag2=1; jp=jmax; else wu(jnum)=1; wu(jmax-jmin)=-y(jmax,l2,l3,m1,m2,m3)/z(jmax,l2,l3,m1); jp=jmax-1; end elseif rs(jnum)<=0 wu(jnum)=1; wu(jmax-jmin)=-y(jmax,l2,l3,m1,m2,m3)/z(jmax,l2,l3,m1); jp=jmax-1; else jp=jmin; for j=jmax-1:-1:jn % This appears to be Luscombe and Luban's Eq. (2) denom=y(j,l2,l3,m1,m2,m3)+x(j,l2,l3,m1)*rs(j-jmin+2); warning off rs(j-jmin+1)=-z(j,l2,l3,m1)/denom; warning on if (rs(j-jmin+1)>1 || rs(j-jmin+1) <= 0 || denom==0) jp=j+1; break end end wu(jp-jmin+1)=1; for k=1:jmax-jp wu(jp+k-jmin+1)=wu(jp+k-jmin)*rs(jp+k-jmin+1); end if jp==jmax wu(jmax-jmin)=-y(jmax,l2,l3,m1,m2,m3)/z(jmax,l2,l3,m1); jp=jmax-1; end end % Calculate classical terms for [jn+1, jp-1] using standard three term % rercusion relationship. Start from both jn and jp and stop at the % midpoint. If flag1 is set, then perform the recursion solely from % high to low values. If flag2 is set, then perform the recursion % solely from low to high. if flag1==0 % I think Fortran rounds like this jmid=round((jn+jp)/2); for j=jn:jmid-1 wl(j-jmin+2)=-(z(j,l2,l3,m1)*wl(j-jmin)+... y(j,l2,l3,m1,m2,m3)* ... wl(j-jmin+1))/x(j,l2,l3,m1); if abs(wl(j-jmin+2))>1 wl(1:j-jmin+2)=... wl(1:j-jmin+2)/scalef; end if abs(wl(j-jmin+2)/wl(j-jmin))<1 && ... wl(j-jmin+2)~=0 jmid=j+1; break end end wnmid=wl(jmid-jmin+1); warning off if abs(wnmid/wl(jmid-jmin))<1e-6 && wl(jmid-jmin)~=0 wnmid=wl(jmid-jmin); jmid=jmid-1; end warning on for j=jp:-1:jmid+1 wu(j-jmin)=-(x(j,l2,l3,m1)*wu(j-jmin+2)+... y(j,l2,l3,m1,m2,m3)* ... wu(j-jmin+1))/z(j,l2,l3,m1); if abs(wu(j-jmin))>1 wu(j-jmin:jnum)=... wu(j-jmin:jnum)/scalef; end end wpmid=wu(jmid-jmin+1); if jmid==jmax w3j(1:jnum)=wl(1:jnum); elseif jmid==jmin w3j(1:jnum)=wu(1:jnum); else w3j(1:jmid-jmin+1)=wl(1:jmid-jmin+1)*wpmid/wnmid; w3j(jmid-jmin+2:jnum)=... wu(jmid-jmin+2:jnum); end elseif flag1==1 && flag2==0 for j=jp:-1:jmin+1 wu(j-jmin)=-(x(j,l2,l3,m1)*wu(j-jmin+2)+... y(j,l2,l3,m1,m2,m3)* ... wu(j-jmin+1))/z(j,l2,l3,m1); if abs(wu(j-jmin))>1 wu(j-jmin:jnum)=... wu(j-jmin:jnum)/scalef; end end w3j(1:jnum)=wu(1:jnum); elseif flag2==1 && flag1==0 for j=jn:jp-1 wl(j-jmin+2)=-(z(j,l2,l3,m1)*wl(j-jmin)+... y(j,l2,l3,m1,m2,m3)* ... wl(j-jmin+1))/x(j,l2,l3,m1); if abs(wl(j-jmin+2))>1 wl(1:j-jmin+2)=... wl(1:j-jmin+2)/scalef; end end w3j(1:jnum)=wl(1:jnum); elseif flag1==1 && flag2==1 error('Can not calculate function for input values') end w3j=normw3j(w3j,jmin,jmax,jnum); w3j=fixsign(w3j,jnum,l2,l3,m2,m3); % Output: give output in all degrees from zero to the bandwidth if L<=l2+l3 % Truncate w3j=[repmat(0,1,jmin) w3j(1:L-jmin+1)]; else % Append w3j=[repmat(0,1,jmin) w3j repmat(0,1,L-l2-l3)]; end j=0:L; % Perform normalization check if L==l2+l3 norma=sum((2*[0:L]+1).*w3j.^2); difer(norma-1,[],[],NaN) end elseif strcmp(L,'demo1') difer(wigner3jm(20,10,10,0,0,0)-wigner0j(20,10,10)) difer(wigner3jm(400,200,200,0,0,0)-wigner0j(400,200,200)) difer(wigner3jm(40,10,13,0,0,0)-wigner0j(40,10,13)) difer(indeks(wigner3jm(8,6,5,3,2,-5),'end')-sqrt(42/4199)) difer(indeks(wigner3jm(8,6,5,3,2,-5),'end-1')-35*sqrt(2/138567)) difer(indeks(wigner3jm(8,6,5,3,2,-5),'end-2')-7*sqrt(1/2431)) difer(indeks(wigner3jm(8,6,5,3,2,-5),'end-3')-sqrt(35/2431)) difer(indeks(wigner3jm(8,6,5,3,2,-5),'end-4')-sqrt(5/858)) difer(indeks(wigner3jm(3,2,2,1,0,-1),'end')--sqrt(1/35)) difer(indeks(wigner3jm(0,1,1,0,1,-1),'end')-sqrt(1/3)) difer(indeks(wigner3jm(1,1,1,0,1,-1),'end')-sqrt(1/6)) difer(indeks(wigner3jm(2,1,1,0,1,-1),'end')-sqrt(1/30)) difer(indeks(wigner3jm(3,2,3,-2,0,2),'end')-0) difer(indeks(wigner3jm(6,2,4,-4,1,3),'end')-4*sqrt(1/429)) difer(indeks(wigner3jm(0,1,1,0,0,0),'end')--sqrt(1/3)) difer(indeks(wigner3jm(2,1,1,0,0,0),'end')-sqrt(2/15)) difer(indeks(wigner3jm(3,2,3,3,0,-3),'end')-(1/2)*sqrt(5/21)) difer(indeks(wigner3jm(2,2,3,-2,0,2),'end')--sqrt(1/14)) difer(indeks(wigner3jm(8,6,5,3,2,-5),'end-5')-sqrt(1/1001)) difer(indeks(wigner3jm(20,15,9,-3,2,1),'end')+(311/2)*sqrt(115/1231496049)) difer(indeks(wigner3jm(10,10,12,9,3,-12),'end')--(1/15)*sqrt(4199/9889)) elseif strcmp(L,'demo2') [w,L]=wigner3jm([],9/2,7/2,1,-7/2,5/2); disp(sprintf('------------------------------')) disp(sprintf('L1 Values of 3j coefficients')) disp(sprintf('------------------------------')) disp(sprintf('%2.2i %23.16i\n',[L(2:9)' w(2:9)']')) disp(sprintf('------------------------------')) end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [o,p]=output(jmin,l2,l3,L,w3j) % Output: give output in all degrees from zero to the bandwidth % Perform normalization check before possible completion or truncation norma=sum((2*[jmin:l2+l3]+1).*w3j.^2); difer(norma-1,[],[],NaN) if L<=l2+l3 % Truncate... o=[repmat(0,1,jmin) w3j(1:L-jmin+1)]; else % Append o=[repmat(0,1,jmin) w3j repmat(0,1,L-l2-l3)]; end p=0:L; % The following functions are straight from Table I of Luscombe and Luban %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function o=x(j,l2,l3,m1) o=j*a(j+1,l2,l3,m1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function o=y(j,l2,l3,m1,m2,m3) % This is the Y-function in Table 1 of Luscombe and Luban o=-(2*j+1)*(m1*(l2*(l2+1)-l3*(l3+1))-(m3-m2)*j*(j+1)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function o=z(j,l2,l3,m1) o=(j+1)*a(j,l2,l3,m1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function o=a(j,l2,l3,m1) o=sqrt((j^2-(l2-l3)^2)*((l2+l3+1)^2-j^2)*(j^2-m1^2)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function o=normw3j(w3j,jmin,jmax,jnum) normo=0; for j=jmin:jmax normo=normo+(2*j+1)*w3j(j-jmin+1)^2; end o(1:jnum)=w3j(1:jnum)/sqrt(normo); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function o=fixsign(w3j,jnum,l2,l3,m2,m3) if ((w3j(jnum)<0 & (-1)^(l2-l3+m2+m3)>0) |... (w3j(jnum)>0 & (-1)^(l2-l3+m2+m3)<0)) o(1:jnum)=-w3j(1:jnum); else o(1:jnum)=w3j(1:jnum); end
github
libDirectional/libDirectional-master
xyz2plm.m
.m
libDirectional-master/lib/external/slepian_alpha/xyz2plm.m
10,265
utf_8
c12b5c4b341a7d4cdc70443ff4bfd698
function [lmcosi,dw]=xyz2plm(fthph,L,method,lat,lon,cnd) % [lmcosi,dw]=XYZ2PLM(fthph,L,method,lat,lon,cnd) % % Forward real spherical harmonic transform in the 4pi normalized basis. % % Converts a spatially gridded field into spherical harmonics. % For complete and regular spatial samplings [0 360 -90 90]. % If regularly spaced and complete, do not specify lat,lon. % If not regularly spaced, fthph, lat and lon are column vectors. % % INPUT: % % fthph Real-valued function whose transform we seek: % [1] MxN matrix of values corresponding to a regular grid % defined by lat,lon as described below, OR % [2] an MNx1 vector of values corrsponding to a set of % latitude and longitude values given by lat,lon as below % L Maximum degree of the expansion (Nyquist checked) % method 'im' By inversion (fast, accurate, preferred), % uses FFT on equally spaced longitudes, ok to % specify latitudes only as long as nat>=(L+1), % note: works with the orthogonality of the % cosine/sine of the longitude instead of with % the orthogonality of the Legendre polynomials. % 'gl' By Gauss-Legendre integration (fast, inaccurate) % note: resampling to GL integration points, % uses FFT on equally spaced longitudes % 'simpson' By Simpson integation (fast, inaccurate), % note: requires equidistant latitude spacing, % uses FFT on equally spaced longitudes % 'irr' By inversion (irregular samplings) % 'fib' By Riemann sum on a Fibonacci grid (not done yet) % lat Latitude range for the grid or set of function values: % [1] if unspecified, we assume [90 -90] and a regular grid % [2] 1x2 vector [maximumlatitude minimumlatitude] in degrees % [3] an MNx1 vector of values with the explicit latitudes % lon Longitude range for the grid or set of function values: % [1] if unspecified, we assume [0 360] and a regular grid % [2] 1x2 vector [maximumlatitude minimumlatitude] in degrees % [3] an MNx1 vector of values with the explicit longitudes % cnd Eigenvalue tolerance in the irregular case % % OUTPUT: % % lmcosi Matrix listing l,m,cosine and sine coefficients % dw Eigenvalue spectrum in the irregular case % % Note that the MEAN of the input data deviates from C(1), as sampled % fields lose the orthogonality. The inversion approaches should recover % the exact value of C(1), the true mean of the data, not the sample % mean. % % lmcosi=xyz2plm(ones(randi(100),randi(100))); lmcosi(1,3) is close to one % % See also PLM2XYZ, PLM2SPEC, PLOTPLM, etc. % % Previously modified by fjsimons-at-alum.mit.edu, 09/04/2014 % Last modified by Florian Pfaff for libDirectional, 21/10/2019 arguments fthph (:,:) double L (1,1) {mustBeInteger} = -1 % Will be overwritten if -1 method char = 'im' lat double = zeros(0,1) lon double = zeros(0,1) cnd (1,1) double = 1e-6 end persistent legendreCell t0=clock; if nargin<3 && numel(fthph)>1 % If lat and lon are not given and is only single elementary, enforce matrix assert(size(fthph,1)>1 && size(fthph,2)>1); else assert(numel(lat)==numel(fthph) && numel(lon)==numel(fthph) || (numel(lat)*numel(lon))==numel(fthph)); end dw=[]; % If no grid is specified, assumes equal spacing and complete grid if isempty(lat) && isempty(lon) % Test if data is 2D, and periodic over longitude fthph=reduntest(fthph); polestest(fthph) % Make a complete grid nlon=size(fthph,2); nlat=size(fthph,1); % Nyquist wavelength Lnyq=min([ceil((nlon-1)/2) nlat-1]); % Colatitude and its increment theta=linspace(0,pi,nlat); canUseSaved=true; % Equally spaced % Calculate latitude/longitude sampling interval; no wrap-around left dtheta=pi/(nlat-1); dphi=2*pi/nlon; switch method % Even without lat/lon can still choose the full inversion method % without Fourier transformation case 'irr' [LON,LAT]=meshgrid(linspace(0,2*pi*(1-1/nlon),nlon),... linspace(pi/2,-pi/2,nlat)); lat=LAT(:); lon=LON(:); fthph=fthph(:); theta=pi/2-lat; clear LON LAT end elseif isempty(lon) % If only latitudes are specified; make equal spacing longitude grid % Latitudes can be unequally spaced for 'im', 'irr' and 'gl'. canUseSaved=false; fthph=reduntest(fthph); theta=(90-lat)*pi/180; dtheta=(lat(1)-lat(2))*pi/180; nlat=length(lat); nlon=size(fthph,2); dphi=2*pi/nlon; Lnyq=min([ceil((nlon-1)/2) ceil(pi/dtheta)]); else canUseSaved=false; % Irregularly sampled data fthph=fthph(:); theta=(90-lat)*pi/180; lat=lat(:)*pi/180; lon=lon(:)*pi/180; nlon=length(lon); nlat=length(lat); % Nyquist wavelength adi=[abs(diff(sort(lon))) ; abs(diff(sort(lat)))]; Lnyq=ceil(pi/min(adi(~~adi))); method='irr'; end % Decide on the Nyquist frequency if L==-1 L=Lnyq; end % Never use Libbrecht algorithm... found out it wasn't that good libb=false; %disp(sprintf('Lnyq= %i ; expansion out to degree L= %i',Lnyq,L)) if L>Lnyq || nlat<(L+1) warning('XYZ2PLM: Function undersampled. Aliasing will occur.') end % Make cosine and sine matrices [m,l,mz]=addmon(L); lmcosi=[l m zeros(length(l),2)]; % Define evaluation points switch method case 'gl' % Highest degree of integrand will always be 2*L [w,x]=gausslegendrecof(2*L,[],[-1 1]); % Function interpolated at Gauss-Legendre latitudes; 2D no help fthph=interp1(theta,fthph,acos(x),'spline'); case {'irr','simpson','im'} % Where else to evaluate the Legendre polynomials x=cos(theta); otherwise error('Specify valid method') end if canUseSaved && size(legendreCell,1)>L && size(legendreCell,2)>length(x) && ~isempty(legendreCell{L+1,length(x)+1}) Plm=legendreCell{L+1,length(x)+1}; else mfn=mfilename('fullpath'); fnpl=fullfile(mfn(1:end-8),'LEGENDRE',sprintf('LSSM-%i-%i.mat',L,length(x))); % Expect in folder of xyz2plm if exist(fnpl,'file')==2 && canUseSaved load(fnpl,'Plm') else % Evaluate Legendre polynomials at selected points Plm=NaN(length(x),addmup(L)); if L>200 h=waitbar(0,'Evaluating all Legendre polynomials'); end in1=0; in2=1; for l=0:L if ~libb Plm(:,in1+1:in2)=(legendre(l,x(:)','sch')*sqrt(2*l+1))'; else Plm(:,in1+1:in2)=(libbrecht(l,x(:)','sch')*sqrt(2*l+1))'; end in1=in2; in2=in1+l+2; if L>200 waitbar((l+1)/(L+1),h) end end if L>200 delete(h) end if canUseSaved save(fnpl,'Plm') end end if canUseSaved legendreCell{L+1,length(x)+1}=Plm; disp('Keeping legendre polynomials in memory, call ''clear xyz2plm'' to free memory.'); end end switch method case {'irr'} Plm=[Plm.*cos(lon(:)*m(:)') Plm.*sin(lon(:)*m(:)')]; % Add these into the sensitivity matrix [C,merr,mcov,chi2,L2err,rnk,dw]=datafit(Plm,fthph); lmcosi(:,3)=C(1:end/2); lmcosi(:,4)=C(end/2+1:end); case {'im','gl','simpson'} % Perhaps demean the data for Fourier transform dem=false; if dem meanm=mean(fthph,2); %#ok<UNRCH> fthph=fthph-repmat(meanm,1,nlon); end % Calculate integration over phi by the fast Fourier % transform. Integration of real input field with respect to the second % dimension of r, at wavenumber m, thus at constant latitude. You get % as many wavenumbers m as there are longitudes; only use to L. With % Matlab's FFT, need to multiply by sampling interval. gfft=dphi*fft(fthph,nlon,2); if dem % Add the azimuthal mean back in there gfft(:,1)=2*pi*meanm; %#ok<UNRCH> end % Note these things are only half unique - the maximum m is nlon/2 % But no Nyquist theory exists for the Legendre transform... a=real(gfft); b=-imag(gfft); in1=0; in2=1; otherwise error('Specify valid method') end switch method case 'im' % Loop over the orders. This speeds it up versus 'irr' for ord=0:L a(:,1)=a(:,1)/2; b(:,1)=b(:,1)/2; Pm=Plm(:,mz(ord+1:end)+ord)*pi; [lmcosi(mz(ord+1:end)+ord,3)]=datafit(Pm,a(:,ord+1)); [lmcosi(mz(ord+1:end)+ord,4)]=datafit(Pm,b(:,ord+1)); end case 'simpson' % Loop over the degrees. Could go up to l=nlon if you want for l=0:L % Integrate over theta using Simpson's rule clm=simpson(theta,... repmat(sin(theta(:)),1,l+1).*a(:,1:l+1).*Plm(:,in1+1:in2)); slm=simpson(theta,... repmat(sin(theta(:)),1,l+1).*b(:,1:l+1).*Plm(:,in1+1: ... in2)); in1=in2; in2=in1+l+2; % And stick it in a matrix [l m Ccos Csin] lmcosi(addmup(l-1)+1:addmup(l),3)=clm(:)/4/pi; lmcosi(addmup(l-1)+1:addmup(l),4)=slm(:)/4/pi; end case 'gl' % Loop over the degrees. Could go up to l=nlon if you want for l=0:L % Integrate over theta using Gauss-Legendre integration clm=sum(a(:,1:l+1).*(diag(w)*Plm(:,in1+1:in2))); slm=sum(b(:,1:l+1).*(diag(w)*Plm(:,in1+1:in2))); in1=in2; in2=in1+l+2; % And stick it in a matrix [l m Ccos Csin] lmcosi(addmup(l-1)+1:addmup(l),3)=clm(:)/4/pi; lmcosi(addmup(l-1)+1:addmup(l),4)=slm(:)/4/pi; end end % Get rid of machine precision error lmcosi(abs(lmcosi(:,3))<eps,3)=0; lmcosi(abs(lmcosi(:,4))<eps,4)=0; %disp(sprintf('XYZ2PLM (Analysis) took %8.4f s',etime(clock,t0))) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function grd=reduntest(grd) % Tests if last longitude repeats last (0,360) % and removes last data column if sum(abs(grd(:,1)-grd(:,end))) >= size(grd,2)*eps*10 fprintf('Data violate wrap-around by %8.4e\n',... sum(abs(grd(:,1)-grd(:,end)))); end grd=grd(:,1:end-1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function polestest(grd) % Tests if poles (-90,90) are identical over longitudes var1=var(grd(1,:)); var2=var(grd(end,:)); if var1>eps*10 || var2>eps*10 fprintf('Poles violated by %8.4e and %8.4e\n',var1,var2); end
github
libDirectional/libDirectional-master
project_s3_partition.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/project_s3_partition.m
7,962
utf_8
1a63325e3e5e2ea8d502ba34b4e06f3c
function [movie_frame] = project_s3_partition(N,varargin) %PROJECT_S3_PARTITION Use projection to illustrate an EQ partition of S^3 % %Syntax % [movie_frame] = project_s3_partition(N,options); % %Description % PROJECT_S3_PARTITION(N) uses projection to illustrate the partition of % the unit sphere S^3 into N regions. % % MOVIE_FRAME = PROJECT_S3_PARTITION(N) sets MOVIE_FRAME to be an array of % movie frames for use with MOVIE. The movie frames will contain the region by % region build-up of the illustration. % % PROJECT_S3_PARTITION(N,'offset','extra') uses experimental extra offsets. % For more detail on partition options, see HELP PARTITION_OPTIONS. % % PROJECT_S3_PARTITION(N,options) also recognizes a number of illustration % options, which are specified as name, value pairs. % Any number of pairs can be used, in any order. % % The following illustration options are used. % % PROJECT_S3_PARTITION(N,'fontsize',size) % Font size used in titles (numeric, default 18). % % PROJECT_S3_PARTITION(N,'title','long') % PROJECT_S3_PARTITION(N,'title','short') % Use long or short titles (default 'long'). % % PROJECT_S3_PARTITION(N,'proj','stereo') % PROJECT_S3_PARTITION(N,'proj','eqarea') % Use stereographic or equal area projection (default 'stereo'). % % PROJECT_S3_PARTITION(N,'points','show') % PROJECT_S3_PARTITION(N,'points','hide') % Show or hide center points (default 'show'). % % PROJECT_S3_PARTITION(N,'surf','show') % PROJECT_S3_PARTITION(N,'surf','hide') % Show or hide surfaces of regions (default 'show'). % % For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS. % %Examples % > project_s3_partition(10) % > frames=project_s3_partition(9,'offset','extra','proj','eqarea') % frames = % 1x18 struct array with fields: % cdata % colormap % > project_s3_partition(99,'proj','eqarea','points','hide') % %See also % MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, PROJECT_S2_PARTITION % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Function changed name from s2x to polar2cart % Function changed name from x2s2 to cart2polar2 % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-13 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. pdefault.extra_offset = false; popt = partition_options(pdefault, varargin{:}); gdefault.fontsize = 18; gdefault.stereo = true; gdefault.long_title = true; gdefault.show_points = true; gdefault.show_surfaces = true; gopt = illustration_options(gdefault, varargin{:}); dim = 3; [X,Y,Z] = sphere(90); if gopt.stereo r = 0; else r = (area_of_sphere(dim)/volume_of_ball(dim)).^(1/dim); end hold off if gopt.show_surfaces surf(r*X,r*Y,r*Z,zeros(size(Z)),... 'FaceAlpha',1/20,'FaceColor','interp','FaceLighting','phong','EdgeColor','none') else plot3(0,0,0,'w.') end axis equal;hold on camlight right colormap jet grid off axis off if gopt.long_title if gopt.stereo s = 'Stereographic'; else s = 'Equal volume'; end if gopt.show_points pointstr = ', showing the center point of each region'; else pointstr = ''; end title(sprintf(... '\n%s projection of recursive zonal equal area partition of {S^3} \n into %d regions%s.',... s,N,pointstr),'FontSize',gopt.fontsize); else title(sprintf('\nEQ(3,%d)',N),'FontSize',gopt.fontsize); end axis equal grid off axis off pause(0); if nargout > 0 movie_frame(1) = getframe(gcf); end if gopt.stereo && (N == 1) return; end if popt.extra_offset [R,dim_1_rot] = eq_regions(dim,N,popt.extra_offset); else R = eq_regions(dim,N); end for i = N:-1:2 if popt.extra_offset project_s3_region(R(:,:,i),N,gopt.stereo,gopt.show_surfaces,dim_1_rot{i}); else project_s3_region(R(:,:,i),N,gopt.stereo,gopt.show_surfaces); end pause(0); if nargout > 0 movie_frame(N-i+2) = getframe(gcf); end end if gopt.show_points project_s3_eq_point_set(N,popt.extra_offset,gopt.stereo); if nargout > 0 for k=1:min(N,40) movie_frame(N+k) = getframe(gcf); end end end hold off % % end function function project_s3_region(region, N, stereo, show_surfaces, rot_matrix) %PROJECT_S3_REGION Use projection to illustrate an EQ region of S^3 %Syntax % project_s3_region(region, stereo, show_surfaces, rot_matrix); % %Notes % The region is given as a 3 x 2 matrix in spherical polar coordinates % % The default is to use stereographic projection % If the optional second argument, stereo is false, % then use a equal area projection. if nargin < 3 stereo = true; end if stereo projection = 'x2stereo'; else projection = 'x2eqarea'; end if nargin < 4 show_surfaces = true; end offset_regions = (nargin >= 5); tol = eps*2^5; dim = size(region,1); t = region(:,1); b = region(:,2); if abs(b(1)) < tol b(1) = 2*pi; end pseudo = 0; if abs(t(1)) < tol && abs(b(1)-2*pi) < tol pseudo = 1; end n = 33; delta = 1/(n-1); h = 0:delta:1; [h1, h2] = meshgrid(h,h); t_to_b = zeros(dim,n,n); b_to_t = t_to_b; r = N^(-1/3)/32; for k = 1:dim if ~pseudo || k < 3 L = 1:dim; j(L) = mod(k+L,dim)+1; t_to_b(j(1),:,:) = t(j(1))+(b(j(1))-t(j(1)))*h1; t_to_b(j(2),:,:) = t(j(2))+(b(j(2))-t(j(2)))*h2; t_to_b(j(3),:,:) = t(j(3))*ones(n,n); t_to_b_v = reshape(t_to_b,dim,n*n); if offset_regions t_to_b_x = polar2cart([cart2polar2(rot_matrix*polar2cart(t_to_b_v(1:dim-1,:)));t_to_b_v(dim,:)]); else t_to_b_x = polar2cart(t_to_b_v); end s = reshape(feval(projection,t_to_b_x),dim,n,n); degenerate = (norm(s(:,1,1)-s(:,1,2)) < tol); if ~degenerate && (~pseudo || k > 1) [X,Y,Z] = fatcurve(squeeze(s(:,1,:)),r); surface(X,Y,Z,zeros(size(Z)),... 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none') axis equal; hold on end if show_surfaces surf(squeeze(s(1,:,:)),squeeze(s(2,:,:)),squeeze(s(3,:,:)),t(3)*ones(n,n),... 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none') end axis equal; hold on camlight right b_to_t(j(1),:,:) = b(j(1))-(b(j(1))-t(j(1)))*h1; b_to_t(j(2),:,:) = b(j(2))-(b(j(2))-t(j(2)))*h2; b_to_t(j(3),:,:) = b(j(3))*ones(n,n); b_to_t_v = reshape(b_to_t,dim,n*n); if offset_regions b_to_t_x = polar2cart([cart2polar2(rot_matrix*polar2cart(b_to_t_v(1:dim-1,:)));b_to_t_v(dim,:)]); else b_to_t_x = polar2cart(b_to_t_v); end s = reshape(feval(projection,b_to_t_x),dim,n,n); degenerate = (norm(s(:,1,1)-s(:,1,2)) < tol); if ~degenerate && (~pseudo || (k > 1 && abs(b(2)-pi) > tol)) [X,Y,Z] = fatcurve(squeeze(s(:,1,:)),r); surface(X,Y,Z,zeros(size(Z)),... 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none') end if show_surfaces && k < 2 surf(squeeze(s(1,:,:)),squeeze(s(2,:,:)),squeeze(s(3,:,:)),t(3)*ones(n,n),... 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none') camlight right end end end colormap jet grid off axis off % % end function function project_s3_eq_point_set(N,extra_offset,stereo) %PROJECT_S3_EQ_POINT_SET Use projection to illustrate an EQ point set of S^3 % %Syntax % project_s3_eq_point_set(N,min_energy,stereo); if nargin < 2 extra_offset = true; end if nargin < 3 stereo = true; end if stereo projection = 'stereo'; else projection = 'eqarea'; end x = eq_point_set(3,N,extra_offset); project_point_set(x,'title','hide','proj',projection); % % end function
github
libDirectional/libDirectional-master
project_s3_partition_symm.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/project_s3_partition_symm.m
8,491
utf_8
2a42994a8120fb1cf8dff550211ed31a
function [movie_frame] = project_s3_partition_symm(N,showOnlyHalf,varargin) %PROJECT_S3_PARTITION Use projection to illustrate an EQ partition of S^3 % %Syntax % [movie_frame] = project_s3_partition(N,options); % %Description % PROJECT_S3_PARTITION(N) uses projection to illustrate the partition of % the unit sphere S^3 into N regions. % % MOVIE_FRAME = PROJECT_S3_PARTITION(N) sets MOVIE_FRAME to be an array of % movie frames for use with MOVIE. The movie frames will contain the region by % region build-up of the illustration. % % PROJECT_S3_PARTITION(N,'offset','extra') uses experimental extra offsets. % For more detail on partition options, see HELP PARTITION_OPTIONS. % % PROJECT_S3_PARTITION(N,options) also recognizes a number of illustration % options, which are specified as name, value pairs. % Any number of pairs can be used, in any order. % % The following illustration options are used. % % PROJECT_S3_PARTITION(N,'fontsize',size) % Font size used in titles (numeric, default 18). % % PROJECT_S3_PARTITION(N,'title','long') % PROJECT_S3_PARTITION(N,'title','short') % Use long or short titles (default 'long'). % % PROJECT_S3_PARTITION(N,'proj','stereo') % PROJECT_S3_PARTITION(N,'proj','eqarea') % Use stereographic or equal area projection (default 'stereo'). % % PROJECT_S3_PARTITION(N,'points','show') % PROJECT_S3_PARTITION(N,'points','hide') % Show or hide center points (default 'show'). % % PROJECT_S3_PARTITION(N,'surf','show') % PROJECT_S3_PARTITION(N,'surf','hide') % Show or hide surfaces of regions (default 'show'). % % For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS. % %Examples % > project_s3_partition(10) % > frames=project_s3_partition(9,'offset','extra','proj','eqarea') % frames = % 1x18 struct array with fields: % cdata % colormap % > project_s3_partition(99,'proj','eqarea','points','hide') % %See also % MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, PROJECT_S2_PARTITION % Adapted version by Florian Pfaff for libDirectional 2020-03-07 % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Function changed name from s2x to polar2cart % Function changed name from x2s2 to cart2polar2 % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-13 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. assert(mod(N,2)==0); if nargin==1 showOnlyHalf=false; end if showOnlyHalf N=N/2; end pdefault.extra_offset = false; popt = partition_options(pdefault, varargin{:}); gdefault.fontsize = 18; gdefault.stereo = true; gdefault.long_title = true; gdefault.show_points = true; gdefault.show_surfaces = true; gopt = illustration_options(gdefault, varargin{:}); dim = 3; [X,Y,Z] = sphere(90); if gopt.stereo r = 0; else r = (area_of_sphere(dim)/volume_of_ball(dim)).^(1/dim); end hold off if gopt.show_surfaces surf(r*X,r*Y,r*Z,zeros(size(Z)),... 'FaceAlpha',1/20,'FaceColor','interp','FaceLighting','phong','EdgeColor','none') else plot3(0,0,0,'w.') end axis equal;hold on camlight right colormap jet grid off axis off if gopt.long_title if gopt.stereo s = 'Stereographic'; else s = 'Equal volume'; end if gopt.show_points pointstr = ', showing the center point of each region'; else pointstr = ''; end title(sprintf(... '\n%s projection of recursive zonal equal area partition of {S^3} \n into %d regions%s.',... s,N,pointstr),'FontSize',gopt.fontsize); else title(sprintf('\nEQ(3,%d)',N),'FontSize',gopt.fontsize); end axis equal grid off axis off pause(0); if nargout > 0 movie_frame(1) = getframe(gcf); end if gopt.stereo && (N == 1) return; end if popt.extra_offset error('Unsupported'); else if showOnlyHalf R = eq_regions_symm(dim,2*N,true,popt.extra_offset); else R = eq_regions_symm(dim,N,false,popt.extra_offset); end end for i = N:-1:2 if popt.extra_offset project_s3_region(R(:,:,i),N,gopt.stereo,gopt.show_surfaces,dim_1_rot{i}); else project_s3_region(R(:,:,i),N,gopt.stereo,gopt.show_surfaces); end pause(0); % title(''); % set(gcf,'color',[1,1,1]); % export_fig('-nocrop',sprintf('pres%03d.png',N-i)) if nargout > 0 movie_frame(N-i+2) = getframe(gcf); end end if gopt.show_points project_s3_eq_point_set(N,showOnlyHalf,popt.extra_offset,gopt.stereo); if nargout > 0 for k=1:min(N,40) movie_frame(N+k) = getframe(gcf); end end end hold off % % end function function project_s3_region(region, N, stereo, show_surfaces, rot_matrix) %PROJECT_S3_REGION Use projection to illustrate an EQ region of S^3 %Syntax % project_s3_region(region, stereo, show_surfaces, rot_matrix); % %Notes % The region is given as a 3 x 2 matrix in spherical polar coordinates % % The default is to use stereographic projection % If the optional second argument, stereo is false, % then use a equal area projection. if nargin < 3 stereo = true; end if stereo projection = 'x2stereo'; else projection = 'x2eqarea'; end if nargin < 4 show_surfaces = true; end offset_regions = (nargin >= 5); tol = eps*2^5; dim = size(region,1); t = region(:,1); b = region(:,2); if abs(b(1)) < tol b(1) = 2*pi; end pseudo = 0; if abs(t(1)) < tol && abs(b(1)-2*pi) < tol pseudo = 1; end n = 33; delta = 1/(n-1); h = 0:delta:1; [h1, h2] = meshgrid(h,h); t_to_b = zeros(dim,n,n); b_to_t = t_to_b; r = N^(-1/3)/32; for k = 1:dim if ~pseudo || k < 3 L = 1:dim; j(L) = mod(k+L,dim)+1; t_to_b(j(1),:,:) = t(j(1))+(b(j(1))-t(j(1)))*h1; t_to_b(j(2),:,:) = t(j(2))+(b(j(2))-t(j(2)))*h2; t_to_b(j(3),:,:) = t(j(3))*ones(n,n); t_to_b_v = reshape(t_to_b,dim,n*n); if offset_regions t_to_b_x = polar2cart([cart2polar2(rot_matrix*polar2cart(t_to_b_v(1:dim-1,:)));t_to_b_v(dim,:)]); else t_to_b_x = polar2cart(t_to_b_v); end s = reshape(feval(projection,t_to_b_x),dim,n,n); degenerate = (norm(s(:,1,1)-s(:,1,2)) < tol); if ~degenerate && (~pseudo || k > 1) [X,Y,Z] = fatcurve(squeeze(s(:,1,:)),r); surface(X,Y,Z,zeros(size(Z)),... 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none') axis equal; hold on end if show_surfaces surf(squeeze(s(1,:,:)),squeeze(s(2,:,:)),squeeze(s(3,:,:)),t(3)*ones(n,n),... 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none') end axis equal; hold on camlight right b_to_t(j(1),:,:) = b(j(1))-(b(j(1))-t(j(1)))*h1; b_to_t(j(2),:,:) = b(j(2))-(b(j(2))-t(j(2)))*h2; b_to_t(j(3),:,:) = b(j(3))*ones(n,n); b_to_t_v = reshape(b_to_t,dim,n*n); if offset_regions b_to_t_x = polar2cart([cart2polar2(rot_matrix*polar2cart(b_to_t_v(1:dim-1,:)));b_to_t_v(dim,:)]); else b_to_t_x = polar2cart(b_to_t_v); end s = reshape(feval(projection,b_to_t_x),dim,n,n); degenerate = (norm(s(:,1,1)-s(:,1,2)) < tol); if ~degenerate && (~pseudo || (k > 1 && abs(b(2)-pi) > tol)) [X,Y,Z] = fatcurve(squeeze(s(:,1,:)),r); surface(X,Y,Z,zeros(size(Z)),... 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none') end if show_surfaces && k < 2 surf(squeeze(s(1,:,:)),squeeze(s(2,:,:)),squeeze(s(3,:,:)),t(3)*ones(n,n),... 'FaceAlpha',(t(dim)/pi)/2,'FaceColor','interp','FaceLighting','phong','EdgeColor','none') camlight right end end end colormap jet grid off axis off % % end function function project_s3_eq_point_set(N,showOnlyHalf,extra_offset,stereo) %PROJECT_S3_EQ_POINT_SET Use projection to illustrate an EQ point set of S^3 % %Syntax % project_s3_eq_point_set(N,showOnlyHalf,min_energy,stereo); if nargin < 2 extra_offset = true; end if nargin < 3 stereo = true; end if stereo projection = 'stereo'; else projection = 'eqarea'; end if showOnlyHalf x = eq_point_set_symm(3,2*N,true,'plane',extra_offset); else x = eq_point_set_symm(3,N,false,'plane',extra_offset); end project_point_set(x,'title','hide','proj',projection); % % end function
github
libDirectional/libDirectional-master
show_s2_partition.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/show_s2_partition.m
4,545
utf_8
82695a64c69f1c5c3889d51e8bbc426d
function [movie_frame] = show_s2_partition(N,varargin) %SHOW_S2_PARTITION 3D illustration of an EQ partition of S^2 % %Syntax % [movie_frame] = show_s2_partition(N,options); % %Description % SHOW_S2_PARTITION(N) uses a 3d plot to illustrate the partition of % the unit sphere S^2 into N regions. % % MOVIE_FRAME = SHOW_S2_PARTITION(N) sets MOVIE_FRAME to be an array of % movie frames for use with MOVIE. The movie frames will contain the region by % region build-up of the illustration. % % SHOW_S2_PARTITION(N,'offset','extra') uses experimental extra offsets. % For more detail on partition options, see HELP PARTITION_OPTIONS. % % SHOW_S2_PARTITION(N,options) also recognizes a number of illustration % options, which are specified as name, value pairs. % Any number of pairs can be used, in any order. % % The following illustration options are used. % % SHOW_S2_PARTITION(N,'fontsize',size) % Font size used in titles (numeric, default 16). % % SHOW_S2_PARTITION(N,'title','show') % SHOW_S2_PARTITION(N,'title','hide') % Show or hide title (default 'show'). % % SHOW_S2_PARTITION(N,'points','show') % SHOW_S2_PARTITION(N,'points','hide') % Show or hide center points (default 'show'). % % SHOW_S2_PARTITION(N,'sphere','show') % SHOW_S2_PARTITION(N,'sphere','hide') % Show or hide the unit sphere S^2 (default 'show'). % % For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS. % %Examples % > show_s2_partition(10) % > frames=show_s2_partition(9,'offset','extra') % frames = % 1x10 struct array with fields: % cdata % colormap % > show_s2_partition(99,'points','hide') % %See also % MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, PROJECT_S2_PARTITION % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Function changed name from s2x to polar2cart % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-13 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. pdefault.extra_offset = false; popt = partition_options(pdefault, varargin{:}); gdefault.fontsize = 16; gdefault.show_title = true; gdefault.show_points = true; gdefault.show_sphere = true; gopt = illustration_options(gdefault, varargin{:}); dim = 2; surf_jet; if gopt.show_title if gopt.show_points pointstr = ', showing the center point of each region'; else pointstr = ''; end titlestr = sprintf(... '\nRecursive zonal equal area partition of {S^2} \n into %d regions%s.',... N,pointstr); title(titlestr,'FontWeight','bold','FontUnits','normalized',... 'FontSize',gopt.fontsize/512); end frame_no = 1; if nargout > 0 movie_frame(frame_no) = getframe(gcf); frame_no = frame_no + 1; end if gopt.show_sphere show_s2_sphere; hold on if nargout > 0 movie_frame(frame_no) = getframe(gcf); frame_no = frame_no + 1; end end R = eq_regions(dim,N,popt.extra_offset); top_colat = 0; for i = N:-1:2 if top_colat ~= R(2,1,i) top_colat = R(2,1,i); pause(0); end show_s2_region(R(:,:,i),N); if nargout > 0 movie_frame(frame_no) = getframe(gcf); frame_no = frame_no + 1; end end if gopt.show_points x = eq_point_set(dim,N,popt.extra_offset); show_r3_point_set(x,'sphere','hide','title','hide'); hold on if nargout > 0 movie_frame(frame_no) = getframe(gcf); frame_no = frame_no + 1; end end hold off % % end function function show_s2_region(region,N) %SHOW_S2_REGION Illustrate a region of S^2 % %Syntax % show_s2_region(region,N); % %Description % SHOW_S2_REGION(REGION,N) uses 3D surface plots to illustrate a region of S^2. % The region is given as a 2 x 2 matrix in spherical polar coordinates tol = eps*2^5; dim = size(region,1); t = region(:,1); b = region(:,2); if abs(b(1)) < tol b(1) = 2*pi; end pseudo = 0; if abs(t(1)) < tol && abs(b(1)-2*pi) < tol pseudo = 1; end n = 21; delta = 1/(n-1); h = 0:delta:1; t_to_b = zeros(dim,n); b_to_t = t_to_b; r = sqrt(1/N)/12; for k = 1:dim if ~pseudo || k < 2 L = 1:dim; j(L) = mod(k+L,dim)+1; t_to_b(j(1),:) = t(j(1))+(b(j(1))-t(j(1)))*h; t_to_b(j(2),:) = t(j(2))*ones(1,n); t_to_b_x = polar2cart(t_to_b); [X,Y,Z] = fatcurve(t_to_b_x,r); surface(X,Y,Z,-ones(size(Z)),... 'FaceColor','interp','FaceLighting','phong','EdgeColor','none') axis equal hold on end end grid off axis off % % end function
github
libDirectional/libDirectional-master
illustration_options.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/illustration_options.m
6,138
utf_8
1834482cf5939c4cf12940d3c0151dbb
function gopt = illustration_options(gdefault, varargin) %ILLUSTRATION_OPTIONS Options for illustrations of EQ partitions % %Syntax % gopt = illustration_options(gdefault,options); % %Description % GOPT = ILLUSTRATION_OPTIONS(GDEFAULT,options) collects illustration options, % specified as name, value pairs, and places these into the structure GOPT. % The structure GDEFAULT is used to define default option values. % % The structures gdefault and gopt may contain the following fields: % fontsize: numeric % long_title: boolean % stereo: boolean % show_points: boolean % show_sphere: boolean % show_surfaces: boolean % % The following illustration options are available. % % 'fontsize': Font size used in titles. % number Assigns number to field gopt.fontsize. % % 'title': Length of titles. % 'long': Long titles. % Sets gopt.show_title to true. % Sets gopt.long_title to true. % 'short': Short titles. % Sets gopt.show_title to true. % Sets gopt.long_title to false. % 'none': No titles. % Sets gopt.show_title to false. % Sets gopt.long_title to false. % 'show': Show default titles. % Sets gopt.show_title to true. % 'hide': Same as 'none'. % % 'proj': Projection from the sphere to the plane R^2 or the space R^3. % 'stereo': Stereographic projection from the sphere to the whole space. % Sets gopt.stereo to true. % 'eqarea': Equal area projection from the sphere to the disk or ball. % Sets gopt.stereo to false. % % 'points': Show or hide center points of regions. % 'show': Show center points of regions. % Sets gopt.show_points to true. % 'hide': Hide center points of regions. % Sets gopt.show_points to false. % % 'sphere': Show or hide the sphere S^2. % 'show': Show sphere. % Sets gopt.show_sphere to true. % 'hide': Hide sphere. % Sets gopt.show_sphere to false. % % 'surf': Show or hide surfaces of regions of a partition of S^3. % 'show': Show surfaces of regions. % Sets gopt.show_surfaces to true. % 'hide': Hide surfaces of regions. % Sets gopt.show_surfaces to false. % %Examples % > gdefault.fontsize=14; % > gopt=illustration_options(gdefault,'proj','stereo') % gopt = % fontsize: 14 % stereo: 1 % % > gopt=illustration_options(gdefault,'proj','stereo','fontsize',12) % gopt = % fontsize: 12 % stereo: 1 % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-12 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. gopt = gdefault; nargs = length(varargin); nopts = floor(nargs/2); opt_args = {varargin{1:2:2*nopts-1}}; for k=1:nopts if ~ischar([opt_args{k}]) fprintf('Option names must be character strings\n'); option_error(varargin{:}); end end opt_vals = {varargin{2:2:2*nopts}}; option_name = 'fontsize'; pos = strmatch(option_name,opt_args,'exact'); if ~isempty(pos) if (length(pos) == 1) gopt.fontsize = opt_vals{pos}; else duplicate_error(option_name,varargin{:}); end end option_name = 'title'; pos = strmatch(option_name,opt_args,'exact'); if ~isempty(pos) if (length(pos) == 1) value = opt_vals{pos}; else duplicate_error(option_name,varargin{:}); end switch value case 'long' gopt.show_title = true; gopt.long_title = true; case 'short' gopt.show_title = true; gopt.long_title = false; case 'none' gopt.show_title = false; gopt.long_title = false; case 'hide' gopt.show_title = false; case 'hide' gopt.show_title = false; gopt.long_title = false; case 'show' gopt.show_title = true; otherwise value_error(value,varargin{:}); end end option_name = 'proj'; pos = strmatch(option_name,opt_args); if ~isempty(pos) if (length(pos) == 1) value = opt_vals{pos}; else duplicate_error(option_name,varargin{:}); end switch value case 'stereo' gopt.stereo = true; case 'eqarea' gopt.stereo = false; otherwise value_error(value,varargin{:}); end end option_name = 'points'; pos = strmatch(option_name,opt_args,'exact'); if ~isempty(pos) if (length(pos) == 1) value = opt_vals{pos}; else duplicate_error(option_name,varargin{:}); end switch value case 'show' gopt.show_points = true; case 'hide' gopt.show_points = false; otherwise value_error(value,varargin{:}); end end option_name = 'surf'; pos = strmatch(option_name,opt_args); if ~isempty(pos) if (length(pos) == 1) value = opt_vals{pos}; else duplicate_error(option_name,varargin{:}); end switch value case 'show' gopt.show_surfaces = true; case 'hide' gopt.show_surfaces = false; otherwise value_error(value,varargin{:}); end end option_name = 'sphere'; pos = strmatch(option_name,opt_args); if ~isempty(pos) if (length(pos) == 1) value = opt_vals{pos}; else duplicate_error(option_name,varargin{:}); end switch value case 'show' gopt.show_sphere = true; case 'hide' gopt.show_sphere = false; otherwise value_error(value,varargin{:}); end end % % end function function duplicate_error(option_name,varargin) fprintf('Duplicate option %s\n',option_name); option_error(varargin{:}); % % end function function value_error(value,varargin) fprintf('Invalid option value '); disp(value); option_error(varargin{:}); % % end function function option_error(varargin) fprintf('Error in options:\n'); disp(varargin); error('Please check "help illustration_options" for options'); % % end function
github
libDirectional/libDirectional-master
project_s2_partition.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/project_s2_partition.m
5,591
utf_8
da4b16d4d4515eaa89b78c51d43e6b44
function [movie_frame] = project_s2_partition(N,varargin) %PROJECT_S2_PARTITION Use projection to illustrate an EQ partition of S^2 % %Syntax % [movie_frame] = project_s2_partition(N,options); % %Description % PROJECT_S2_PARTITION(N) uses projection to illustrate the partition of % the unit sphere S^2 into N regions. % % MOVIE_FRAME = PROJECT_S2_PARTITION(N) sets MOVIE_FRAME to be an array of % movie frames for use with MOVIE. The movie frames will contain the region by % region build-up of the illustration. % % PROJECT_S2_PARTITION(N,'offset','extra') uses experimental extra offsets. % For more detail on partition options, see HELP PARTITION_OPTIONS. % % PROJECT_S2_PARTITION(N,options) also recognizes a number of illustration % options, which are specified as name, value pairs. % Any number of pairs can be used, in any order. % % The following illustration options are used. % % PROJECT_S2_PARTITION(N,'fontsize',size) % Font size used in titles (numeric, default 16). % % PROJECT_S2_PARTITION(N,'title','long') % PROJECT_S2_PARTITION(N,'title','short') % Use long or short titles (default 'long'). % % PROJECT_S2_PARTITION(N,'proj','stereo') % PROJECT_S2_PARTITION(N,'proj','eqarea') % Use stereographic or equal area projection (default 'stereo'). % % PROJECT_S2_PARTITION(N,'points','show') % PROJECT_S2_PARTITION(N,'points','hide') % Show or hide center points (default 'show'). % % For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS. % %Examples % > project_s2_partition(10) % > frames=project_s2_partition(9,'offset','extra','proj','eqarea') % frames = % 1x10 struct array with fields: % cdata % colormap % > project_s2_partition(99,'proj','eqarea','points','hide') % %See also % MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, SHOW_S2_PARTITION, % PROJECT_S3_PARTITION % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Function changed name from s2x to polar2cart % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-13 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. pdefault.extra_offset = false; popt = partition_options(pdefault, varargin{:}); gdefault.fontsize = 16; gdefault.stereo = true; gdefault.show_title = true; gdefault.long_title = true; gdefault.show_points = true; gopt = illustration_options(gdefault, varargin{:}); dim = 2; Phi = 2*pi*(0:1/40:1); X = cos(Phi); Y = sin(Phi); if gopt.stereo r = 0; else r = (area_of_sphere(dim)/volume_of_ball(dim)).^(1/dim); end plot(r*X,r*Y,'k') axis equal;hold on colormap jet grid off axis off if gopt.show_title if gopt.long_title if gopt.stereo s = 'Stereographic'; else s = 'Equal area'; end if gopt.show_points pointstr = ', showing the center point of each region'; else pointstr = ''; end titlestr = sprintf(... '%s projection of recursive zonal equal area partition of {S^2}\ninto %d regions%s.',... s,N,pointstr); else titlestr = sprintf('EQ(2,%d)',N); end title(titlestr, ... 'FontWeight','bold','FontUnits','normalized','FontSize',gopt.fontsize/512); end if nargout > 0 movie_frame(1) = getframe(gcf); end R = eq_regions(dim,N,popt.extra_offset); for i = N:-1:2 project_s2_region(R(:,:,i),gopt.stereo); if nargout > 0 movie_frame(N-i+2) = getframe(gcf); end end if gopt.show_points project_s2_eq_point_set(N,popt.extra_offset,gopt.stereo); if nargout > 0 movie_frame(N+1) = getframe(gcf); end end hold off % % end function function project_s2_region(region, stereo) %PROJECT_S2_REGION Use projection to illustrate an EQ region of S^2 % %Syntax % project_s2_region(region, stereo); % %Notes % The region is given as a 2 x 2 matrix in spherical polar coordinates % % The default is to use stereographic projection % If the optional second argument, stereo is false, % then use a equal area projection. if nargin < 2 stereo = true; end if stereo projection = 'x2stereo'; else projection = 'x2eqarea'; end tol = eps*2^5; dim = size(region,1); t = region(:,1); b = region(:,2); if abs(b(1)) < tol b(1) = 2*pi; end pseudo = 0; if abs(t(1)) < tol && abs(b(1)-2*pi) < tol pseudo = 1; end n = 21; delta = 1/(n-1); h = 0:delta:1; t_to_b = zeros(dim,n); b_to_t = t_to_b; for k = 1:dim if ~pseudo || k < 2 L = 1:dim; j(L) = mod(k+L,dim)+1; t_to_b(j(1),:) = t(j(1))+(b(j(1))-t(j(1)))*h; t_to_b(j(2),:) = t(j(2))*ones(1,n); t_to_b_x = polar2cart(t_to_b); s = feval(projection,t_to_b_x); plot(s(1,:),s(2,:),'k'); axis equal; hold on if pseudo axis equal; hold on b_to_t(j(1),:,:) = b(j(1))-(b(j(1))-t(j(1)))*h; b_to_t(j(2),:,:) = b(j(2))*ones(1,n); b_to_t_x = polar2cart(b_to_t); s = feval(projection,b_to_t_x); plot(s(1,:),s(2,:),'k'); end end end grid off axis off % % end function function project_s2_eq_point_set(N,extra_offset,stereo) %PROJECT_S2_EQ_POINT_SET Use projection to illustrate an EQ point set of S^2 % %Syntax % project_s2_eq_point_set(N,extra_offset,stereo); if nargin < 2 extra_offset = true; end if nargin < 3 stereo = true; end if stereo projection = 'stereo'; else projection = 'eqarea'; end x = eq_point_set(2,N,extra_offset); project_point_set(x,'title','hide','proj',projection); hold on % % end function
github
libDirectional/libDirectional-master
show_s2_partition_symm.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_illustrations/show_s2_partition_symm.m
5,246
utf_8
127934bf827e86dae624f46407897ce4
function [movie_frame] = show_s2_partition_symm(N,showOnlyHalf,symmetryType,varargin) %SHOW_S2_PARTITION 3D illustration of an EQ partition of S^2 % %Syntax % [movie_frame] = show_s2_partition(N,options); % %Description % SHOW_S2_PARTITION(N) uses a 3d plot to illustrate the partition of % the unit sphere S^2 into N regions. % % MOVIE_FRAME = SHOW_S2_PARTITION(N) sets MOVIE_FRAME to be an array of % movie frames for use with MOVIE. The movie frames will contain the region by % region build-up of the illustration. % % SHOW_S2_PARTITION(N,'offset','extra') uses experimental extra offsets. % For more detail on partition options, see HELP PARTITION_OPTIONS. % % SHOW_S2_PARTITION(N,options) also recognizes a number of illustration % options, which are specified as name, value pairs. % Any number of pairs can be used, in any order. % % The following illustration options are used. % % SHOW_S2_PARTITION(N,'fontsize',size) % Font size used in titles (numeric, default 16). % % SHOW_S2_PARTITION(N,'title','show') % SHOW_S2_PARTITION(N,'title','hide') % Show or hide title (default 'show'). % % SHOW_S2_PARTITION(N,'points','show') % SHOW_S2_PARTITION(N,'points','hide') % Show or hide center points (default 'show'). % % SHOW_S2_PARTITION(N,'sphere','show') % SHOW_S2_PARTITION(N,'sphere','hide') % Show or hide the unit sphere S^2 (default 'show'). % % For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS. % %Examples % > show_s2_partition(10) % > frames=show_s2_partition(9,'offset','extra') % frames = % 1x10 struct array with fields: % cdata % colormap % > show_s2_partition(99,'points','hide') % %See also % MOVIE, PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, PROJECT_S2_PARTITION % Adapted version by Florian Pfaff ([email protected]) for libDirectional % 2020-03-28 % % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Function changed name from s2x to polar2cart % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-13 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. arguments N (1,1) double {mustBeInteger} showOnlyHalf (1,1) logical = false symmetryType char = 'mirror' end arguments (Repeating) varargin end assert(mod(N,2)==0); if nargin==1 showOnlyHalf=false; end if showOnlyHalf N=N/2; end pdefault.extra_offset = false; popt = partition_options(pdefault, varargin{:}); gdefault.fontsize = 16; gdefault.show_title = true; gdefault.show_points = true; gdefault.show_sphere = true; gopt = illustration_options(gdefault, varargin{:}); dim = 2; surf_jet; if gopt.show_title if gopt.show_points pointstr = ', showing the center point of each region'; else pointstr = ''; end titlestr = sprintf(... '\nRecursive zonal equal area partition of {S^2} \n into %d regions%s.',... N,pointstr); title(titlestr,'FontWeight','bold','FontUnits','normalized',... 'FontSize',gopt.fontsize/512); end frame_no = 1; if nargout > 0 movie_frame(frame_no) = getframe(gcf); frame_no = frame_no + 1; end if gopt.show_sphere if showOnlyHalf show_s2_hemisphere else show_s2_sphere; end hold on if nargout > 0 movie_frame(frame_no) = getframe(gcf); frame_no = frame_no + 1; end end if showOnlyHalf R = eq_regions_symm(dim,2*N,true,symmetryType,popt.extra_offset); else R = eq_regions_symm(dim,N,false,symmetryType,popt.extra_offset); end top_colat = 0; for i = N:-1:2 if top_colat ~= R(2,1,i) top_colat = R(2,1,i); pause(0); end show_s2_region(R(:,:,i),N); if nargout > 0 movie_frame(frame_no) = getframe(gcf); frame_no = frame_no + 1; end end if gopt.show_points if showOnlyHalf x = eq_point_set_symm(dim,2*N,true,symmetryType,popt.extra_offset); else x = eq_point_set_symm(dim,N,false,symmetryType,popt.extra_offset); end show_r3_point_set(x,'sphere','hide','title','hide'); hold on if nargout > 0 movie_frame(frame_no) = getframe(gcf); frame_no = frame_no + 1; end end hold off % % end function function show_s2_region(region,N) %SHOW_S2_REGION Illustrate a region of S^2 % %Syntax % show_s2_region(region,N); % %Description % SHOW_S2_REGION(REGION,N) uses 3D surface plots to illustrate a region of S^2. % The region is given as a 2 x 2 matrix in spherical polar coordinates tol = eps*2^5; dim = size(region,1); t = region(:,1); b = region(:,2); if abs(b(1)) < tol b(1) = 2*pi; end pseudo = 0; if abs(t(1)) < tol && abs(b(1)-2*pi) < tol pseudo = 1; end n = 21; delta = 1/(n-1); h = 0:delta:1; t_to_b = zeros(dim,n); b_to_t = t_to_b; r = sqrt(1/N)/12; for k = 1:dim if ~pseudo || k < 2 L = 1:dim; j(L) = mod(k+L,dim)+1; t_to_b(j(1),:) = t(j(1))+(b(j(1))-t(j(1)))*h; t_to_b(j(2),:) = t(j(2))*ones(1,n); t_to_b_x = polar2cart(t_to_b); [X,Y,Z] = fatcurve(t_to_b_x,r); surface(X,Y,Z,-ones(size(Z)),... 'FaceColor','interp','FaceLighting','phong','EdgeColor','none') axis equal hold on end end grid off axis off % % end function
github
libDirectional/libDirectional-master
calc_energy_coeff.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_point_set_props/calc_energy_coeff.m
4,435
utf_8
2d3fad0cecbe7e98770c8fb861b465f9
function coeff = calc_energy_coeff(dim,N,s,energy) %CALC_ENERGY_COEFF Coefficient of second term in expansion of energy % %Syntax % coeff = calc_energy_coeff(d,N,s,energy); % %Description % COEFF = CALC_ENERGY_COEFF(dim,N,s,ENERGY) sets COEFF to be the coefficient of % the second term of an expansion of ENERGY with the same form as the expansion % of E(dim,N,s), the minimum r^(-s) energy of a set of N points on S^dim. % % Specifically, for s not equal to 0, COEFF is the solution to % % ENERGY == (SPHERE_INT_ENERGY(dim,s)/2) N^2 + COEFF N^(1+s/dim), % % and for s == 0 (the logarithmic potential), COEFF is the solution to % % ENERGY == (SPHERE_INT_ENERGY(dim,0)/2) N^2 + COEFF N LOG(N). % % The argument dim must be a positive integer. % The argument N must be a positive integer or an array of positive integers. % The argument ENERGY must an array of real numbers of the same array size as N. % The result COEFF will be an array of the same size as N. % %Notes % 1) The energy expansion is not valid for N == 1, and in particular, % % EQ_ENERGY_COEFF(dim,N,0,energy) := 0. % % 2) For s > 0, [KuiS98 (1.6) p524] has % % E(dim,N,s) == (SPHERE_INT_ENERGY(dim,s)/2) N^2 + COEFF N^(1+s/dim) + ... % % where SPHERE_INT_ENERGY(dim,s) is the energy integral of the r^(-s) potential % on S^dim. % % The case s == 0 (logarithmic potential) can be split into subcases. % For s == 0 and dim == 1, E(1,N,0) is obtained by equally spaced points on S^1, % and the formula for the log potential for N equally spaced points on a circle % gives % % E(1,N,0) == (-1/2) N LOG(N) exactly. % % For s == 0 and dim == 2, [SafK97 (4) p7] has % % E(2,N,0) == (SPHERE_INT_ENERGY(2,0)/2) N^2 + COEFF N LOG(N) + o(N LOG(N)). % % In general, for s == 0, % % E(dim,N,0) == (SPHERE_INT_ENERGY(dim,0)/2) N^2 + COEFF N LOG(N) + ... % % with sphere_int_energy(1,0) == 0. % % CALC_ENERGY_COEFF just uses this general formula for s == 0, so for s == 0 and % dim == 1, the coefficient returned is actually the coefficient of the first % non-zero term. % %Examples % > N=2:6 % N = % 2 3 4 5 6 % % > energy=eq_energy_dist(2,N,0) % energy = % -0.6931 -1.3863 -2.7726 -4.4205 -6.2383 % % > calc_energy_coeff(2,N,0,energy) % ans = % -0.2213 -0.1569 -0.2213 -0.2493 -0.2569 % %See also % EQ_ENERGY_DIST, EQ_ENERGY_COEFF % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-12 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. % % Compute the energy coefficient: subtract the first term in the expansion of % the minimum energy and divide by the power of N in the second term. % if s > 0 % % The first term in the expansion of the minimum energy. % Ref: [KuiS98 (1.6) p524] % first_term = (sphere_int_energy(dim,s)/2) * N.^2; coeff = (energy-first_term) ./ (N.^(1+s/dim)); else % % Flatten N into a row vector. % shape = size(N); n_partitions = prod(shape); N = reshape(N,1,n_partitions); % % Refs for s==0, dim == 2: % [SafK97 (4) p. 7] [Zho95 (5.6) p. 68, 3.11 - corrected) p. 42] % first_term = (sphere_int_energy(dim,s)/2) * N.^2; % % Avoid division by zero. % coeff = zeros(size(N)); neq1 = (N ~= 1); coeff(neq1) = (energy(neq1)-first_term(neq1)) ./ (N(neq1) .* log(N(neq1))); % % Reshape output to same array size as original N. % coeff = reshape(coeff,shape); % end % % end function function energy = sphere_int_energy(dim,s) %SPHERE_INT_ENERGY Energy integral of r^(-s) potential % %Syntax % energy = sphere_int_energy(d,s); % %Description % ENERGY = SPHERE_INT_ENERGY(dim,s) sets ENERGY to be the energy integral % on S^dim of the r^(-s) potential, defined using normalized Lebesgue measure. % % Ref for s > 0: [KuiS98 (1.6) p524] % Ref for s == 0 and dim == 2: SafK97 (4) p. 7] % For s == 0 and dim >= 2, integral was obtained using Maple: % energy = (1/2)*(omega(dim)/omega(dim+1)* ... % int(-log(2*sin(theta/2)*(sin(theta))^(dim-1),theta=0..Pi), % where omega(dim+1) == area_of_sphere(dim). if s ~= 0 energy = (gamma((dim+1)/2)*gamma(dim-s)/(gamma((dim-s+1)/2)*gamma(dim-s/2))); elseif dim ~= 1 energy = (psi(dim)-psi(dim/2)-log(4))/2; else energy = 0; end % % end function
github
libDirectional/libDirectional-master
point_set_energy_dist.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_point_set_props/point_set_energy_dist.m
2,278
utf_8
8d415c577d853255ac6e39d54d3c7e04
function [energy,min_dist] = point_set_energy_dist(points,s) %POINT_SET_ENERGY_DIST Energy and minimum distance of a point set % %Syntax % [energy,min_dist] = point_set_energy_dist(points,s); % %Description % [ENERGY,MIN_DIST] = POINT_SET_ENERGY_DIST(POINTS,s) sets ENERGY to be the % energy of the r^(-s) potential on the point set POINTS, and sets MIN_DIST % to be the minimum Euclidean distance between points of POINTS. % % POINTS must be an array of real numbers of size (M by N), where M and N % are positive integers, with each of the N columns representing a point of % R^M in Cartesian coordinates. % The result MIN_DIST is optional. % % [ENERGY,MIN_DIST] = POINT_SET_ENERGY_DIST(POINTS) uses the default value of % dim-1 for s. % %Notes % The value of ENERGY for a single point is 0. % Since this function is usually meant to be used for points on a unit sphere, % the value of MIN_DIST for a single point is defined to be 2. % %Examples % > x % x = % 0 0 0.0000 0 % 0 0 0 0 % 0 1.0000 -1.0000 0.0000 % 1.0000 0.0000 0.0000 -1.0000 % % > [e,d]=point_set_energy_dist(x) % e = % 2.5000 % d = % 1.4142 % %See also % EUCLIDEAN_DIST, EQ_ENERGY_DIST, POINT_SET_MIN_DIST % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-22 $ % Documentation files renamed % Fix nasty but obvious bug by using separate variables dist and min_dist % $Revision 1.00 $ $Date 2005-02-12 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. dim = size(points,1)-1; % % The default value of s is dim-1. % if nargin < 2 s = dim-1; end energy = 0; if nargout > 1 min_dist = 2; end n_points = size(points,2); for i = 1:(n_points-1) j = (i+1):n_points; dist = euclidean_dist(points(:,i)*ones(1,n_points-i),points(:,j)); energy = energy + sum(potential(s,dist)); if nargout > 1 min_dist = min(min_dist,min(dist)); end end % % end function function pot = potential(s,r) %POTENTIAL r^(-s) potential at Euclidean radius r. % %Syntax % pot = potential(s,r); switch s case 0 pot = -log(r); otherwise pot = r.^(-s); end % % end function
github
libDirectional/libDirectional-master
partition_options.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_partitions/partition_options.m
3,298
utf_8
66003a1c85613d062acb28376dd1550c
function popt = partition_options(pdefault, varargin) %PARTITION_OPTIONS Options for EQ partition % %Syntax % popt = partition_options(pdefault,options); % %Description % POPT = PARTITION_OPTIONS(PDEFAULT,options) collects partition options, % specified as name, value pairs, and places these into the structure POPT. % The structure PDEFAULT is used to define default option values. % % The structures pdefault and popt may contain the following fields: % extra_offset: boolean % % The following partition options are available. % % 'offset': Control extra rotation offsets for S^2 and S^3 regions. % 'extra': Use extra rotation offsets for S^2 and S^3 regions, to try % to minimize energy. % Sets opt.extra_offset to true. % 'normal': Do not use extra offsets % Sets opt.extra_offset to false. % % Some shortcuts are also provided. % POPT = PARTITION_OPTIONS(pdefault) just sets POPT to PDEFAULT. % % The following are equivalent to PARTITION_OPTIONS(PDEFAULT,'offset','extra'): % PARTITION_OPTIONS(PDEFAULT,true) % PARTITION_OPTIONS(PDEFAULT,'extra') % % The following are equivalent to PARTITION_OPTIONS(PDEFAULT,'offset','normal'): % PARTITION_OPTIONS(PDEFAULT,false) % PARTITION_OPTIONS(PDEFAULT,'normal') % %Examples % > pdefault.extra_offset=false; % > popt=partition_options(pdefault,'offset','extra') % popt = % extra_offset: 1 % % > popt=partition_options(pdefault,false) % popt = % extra_offset: 0 % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-12 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. popt = pdefault; nargs = length(varargin); if nargs == 1 % % Short circuit: single argument is value of extra_offset % value = varargin{1}; switch value case true popt.extra_offset = true; case false popt.extra_offset = false; case 'extra' popt.extra_offset = true; case 'normal' popt.extra_offset = false; otherwise value_error(value,varargin{:}); end return; end nopts = floor(nargs/2); opt_args = {varargin{1:2:2*nopts-1}}; for k=1:nopts if ~ischar([opt_args{k}]) fprintf('Option names must be character strings\n'); option_error(varargin{:}); end end opt_vals = {varargin{2:2:2*nopts}}; option_name = 'offset'; pos = strmatch(option_name,opt_args,'exact'); if ~isempty(pos) if (length(pos) == 1) value = opt_vals{pos}; else duplicate_error(option_name,varargin{:}); end switch value case 'extra' popt.extra_offset = true; case 'normal' popt.extra_offset = false; otherwise value_error(value,varargin{:}); end end function duplicate_error(option_name,varargin) fprintf('Duplicate option %s\n',option_name); option_error(varargin{:}); % % end function function value_error(value,varargin) fprintf('Invalid option value '); disp(value); option_error(varargin{:}); % % end function function option_error(varargin) fprintf('Error in options:\n'); disp(varargin); error('Please check "help partition_options" for options'); % % end function
github
libDirectional/libDirectional-master
illustrate_eq_algorithm.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_partitions/illustrate_eq_algorithm.m
10,506
utf_8
d513f0f352186d48897941b08abbdeed
function illustrate_eq_algorithm(dim,N,varargin) %ILLUSTRATE_EQ_ALGORITHM Illustrate the EQ partition algorithm % %Syntax % illustrate_eq_algorithm(dim,N,options); % %Description % ILLUSTRATE_EQ_ALGORITHM(dim,N) illustrates the recursive zonal equal area % sphere partitioning algorithm, which partitions S^dim (the unit sphere in % dim+1 dimensional space) into N regions of equal area and small diameter. % % The illustration consists of four subplots: % 1. Steps 1 and 2 % 2. Steps 3 to 5 % 3. Steps 6 and 7 % 4. Lower dimensional partitions (if dim == 2 or dim == 3) % % ILLUSTRATE_EQ_ALGORITHM(dim,N,'offset','extra') uses experimental extra % offsets for S^2 and S^3. If dim > 3, extra offsets are not used. % For more detail on partition options, see HELP PARTITION_OPTIONS. % % ILLUSTRATE_EQ_ALGORITHM(dim,N,options) also recognizes a number of % illustration options, which are specified as name, value pairs. % Any number of pairs can be used, in any order. % % The following illustration options are used. % % ILLUSTRATE_EQ_ALGORITHM(dim,N,'fontsize',size) % Font size used in titles (numeric, default 16). % % ILLUSTRATE_EQ_ALGORITHM(dim,N,'title','long') % ILLUSTRATE_EQ_ALGORITHM(dim,N,'title','short') % Use long or short titles (default 'short'). % % ILLUSTRATE_EQ_ALGORITHM(dim,N,'proj','stereo') % ILLUSTRATE_EQ_ALGORITHM(dim,N,'proj','eqarea') % Use stereographic or equal area projection (default 'stereo'). % % ILLUSTRATE_EQ_ALGORITHM(dim,N,'points','show') % ILLUSTRATE_EQ_ALGORITHM(dim,N,'points','hide') % Show or hide center points (default 'show'). % % See examples below. % For more detail on illustration options, see HELP ILLUSTRATION_OPTIONS. % %Notes % The step numbers refer to the following steps of the the recursive zonal % equal area sphere partitioning algorithm, which partition the sphere into % zones. % % 1. Determine the colatitudes of the North and South polar caps. % 2. Determine an ideal collar angle. % 3. Use the angle between the North and South polar caps and the ideal collar % angle to determine an ideal number of collars. % 4. Use a rounding procedure to determine the actual number of collars, % given the ideal number of collars. % 5. Create a list containing the ideal number of regions in each collar. % 6. Use a rounding procedure to create a list containing the actual number of % regions in each collar, given the list containing the ideal number of % regions. % 7. Create a list containing the colatitude of the top of each zone, % given the list containing the actual number of regions in each collar, % and the colatitudes of the polar caps. % %Examples % > illustrate_eq_algorithm(3,99) % > illustrate_eq_algorithm(3,99,'offset','extra','proj','eqarea') % > illustrate_eq_algorithm(3,99,'proj','eqarea','points','hide') % %See also % PARTITION_OPTIONS, ILLUSTRATION_OPTIONS, SUBPLOT % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-13 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. pdefault.extra_offset = false; popt = partition_options(pdefault, varargin{:}); gdefault.fontsize = 16; gdefault.show_title = true; gdefault.long_title = false; gdefault.stereo = false; gdefault.show_points = true; gopt = illustration_options(gdefault, varargin{:}); opt_args = option_arguments(popt,gopt); subplot(2,2,1);axis off illustrate_steps_1_2(dim,N,opt_args); subplot(2,2,2);axis off illustrate_steps_3_5(dim,N,opt_args); subplot(2,2,3);axis off illustrate_steps_6_7(dim,N,opt_args); subplot(2,2,4);axis off cla gopt.fontsize = 32; switch dim case 2 opt_args = option_arguments(popt,gopt); project_s2_partition(N,opt_args{:}); case 3 opt_args = option_arguments(popt,gopt); [s,m] = eq_caps(dim,N); max_collar = min(4,size(m,2)-2); for k = 1:max_collar subn = 9+2*k-mod(k-1,2); subplot(4,4,subn);axis off project_s2_partition(m(1+k),opt_args{:}); end end % % end function function illustrate_steps_1_2(dim,N,varargin) % Illustrate steps 1 and 2 of the EQ partition of S^dim into N regions; % % illustrate_steps_1_2(dim,N,options); gdefault.fontsize = 14; gdefault.show_title = true; gdefault.long_title = false; gopt = illustration_options(gdefault, varargin{:}); h = [0:1/90:1]; % Plot a circle to represent dth coordinate of S^d Phi = h*2*pi; plot(sin(Phi),cos(Phi),'k','LineWidth',1) axis equal;axis off;hold on c_polar = polar_colat(dim,N); k = [-1:1/20:1]; j = ones(size(k)); % Plot the bounding parallels of the polar caps plot(sin(c_polar)*k, cos(c_polar)*j,'r','LineWidth',2) plot(sin(c_polar)*k,-cos(c_polar)*j,'r','LineWidth',2) % Plot the North-South axis plot(zeros(size(j)),k,'b','LineWidth',1) % Plot the polar angle plot(sin(c_polar)*h,cos(c_polar)*h,'b','LineWidth',2) text(0.05,2/3,'\theta_c','Fontsize',gopt.fontsize); % Plot the ideal collar angle Delta_I = ideal_collar_angle(dim,N); theta = c_polar + Delta_I; plot(sin(theta)*h,cos(theta)*h,'b','LineWidth',2) mid = c_polar + Delta_I/2; text(sin(mid)*2/3,cos(mid)*2/3,'\Delta_I','Fontsize',gopt.fontsize); % Plot an arc to indicate angles theta = h*(c_polar + Delta_I); plot(sin(theta)/5,cos(theta)/5,'b','LineWidth',1) text(-0.9,-0.1,sprintf('V(\\theta_c) = V_R \n = \\sigma(S^{%d})/%d',dim,N),... 'Fontsize',gopt.fontsize); caption_angle = min(mid + 2*Delta_I,pi-c_polar); text(sin(caption_angle)/3,cos(caption_angle)/3,sprintf('\\Delta_I = V_R^{1/%d}',dim),... 'Fontsize',gopt.fontsize); if gopt.show_title title_str = sprintf('EQ(%d,%d) Steps 1 to 2\n',dim,N); title(title_str,'Fontsize',gopt.fontsize); end hold off % % end function function illustrate_steps_3_5(dim,N,varargin) % Illustrate steps 3 to 5 of the EQ partition of S^dim into N regions; % % illustrate_steps_3_5(dim,N,options); gdefault.fontsize = 14; gdefault.show_title = true; gdefault.long_title = false; gopt = illustration_options(gdefault, varargin{:}); h = [0:1/90:1]; Phi = h*2*pi; plot(sin(Phi),cos(Phi),'k','LineWidth',1) axis equal;axis off;hold on c_polar = polar_colat(dim,N); n_collars = num_collars(N,c_polar,ideal_collar_angle(dim,N)); r_regions = ideal_region_list(dim,N,c_polar,n_collars); s_cap = cap_colats(dim,N,c_polar,r_regions); k = [-1:1/20:1]; j = ones(size(k)); plot(sin(c_polar)*k, cos(c_polar)*j,'r','LineWidth',2); plot(zeros(size(j)),k,'b','LineWidth',1) for collar_n = 0:n_collars zone_n = 1+collar_n; theta = s_cap(zone_n); plot(sin(theta)*h,cos(theta)*h,'b','LineWidth',2); theta_str = sprintf('\\theta_{F,%d}',zone_n); text(sin(theta)*1.1,cos(theta)*1.1,theta_str,'Fontsize',gopt.fontsize); if collar_n ~= 0 plot(sin(theta)*k, cos(theta)*j,'r','LineWidth',2); theta_p = s_cap(collar_n); arc = theta_p + (theta-theta_p)*h; plot(sin(arc)/5,cos(arc)/5,'b','LineWidth',1); mid = (theta_p + theta)/2; text(sin(mid)/2,cos(mid)/2,'\Delta_F','Fontsize',gopt.fontsize); y_str = sprintf('y_{%d} = %3.1f...',collar_n,r_regions(zone_n)); text(-sin(mid)+1/20,cos(mid)+(mid-pi)/30,y_str,'Fontsize',gopt.fontsize); end end if gopt.show_title title_str = sprintf('EQ(%d,%d) Steps 3 to 5\n',dim,N); title(title_str,'Fontsize',gopt.fontsize); end hold off % % end function function illustrate_steps_6_7(dim,N,varargin) % Illustrate steps 6 to 7 of the EQ partition of S^dim into N regions; % % illustrate_steps_6_7(dim,N,options); gdefault.fontsize = 14; gdefault.show_title = true; gdefault.long_title = false; gopt = illustration_options(gdefault, varargin{:}); h = [0:1/90:1]; Phi = h*2*pi; plot(sin(Phi),cos(Phi),'k','LineWidth',1) axis equal;axis off;hold on c_polar = polar_colat(dim,N); n_collars = num_collars(N,c_polar,ideal_collar_angle(dim,N)); r_regions = ideal_region_list(dim,N,c_polar,n_collars); n_regions = round_to_naturals(N,r_regions); s_cap = cap_colats(dim,N,c_polar,n_regions); k = [-1:1/20:1]; j = ones(size(k)); plot(sin(c_polar)*k, cos(c_polar)*j,'r','LineWidth',2); plot(zeros(size(j)),k,'b','LineWidth',1) for collar_n = 0:n_collars zone_n = 1+collar_n; theta = s_cap(zone_n); plot(sin(theta)*h,cos(theta)*h,'b','LineWidth',2); theta_str = sprintf('\\theta_{%d}',zone_n); text(sin(theta)*1.1,cos(theta)*1.1,theta_str,'Fontsize',gopt.fontsize); if collar_n ~= 0 plot(sin(theta)*k, cos(theta)*j,'r','LineWidth',2); theta_p = s_cap(collar_n); arc = theta_p + (theta-theta_p)*h; plot(sin(arc)/5,cos(arc)/5,'b','LineWidth',1); mid = (theta_p + theta)/2; Delta_str = sprintf('\\Delta_{%i}',collar_n); text(sin(mid)/2,cos(mid)/2,Delta_str,'Fontsize',gopt.fontsize); m_str = sprintf('m_{%d} =%3.0f',collar_n,n_regions(zone_n)); text(-sin(mid)+1/20,cos(mid)+(mid-pi)/30,m_str,'Fontsize',gopt.fontsize); end end if gopt.show_title title_str = sprintf('EQ(%d,%d) Steps 6 to 7\n',dim,N); title(title_str,'Fontsize',gopt.fontsize); end hold off % % end function function arg = option_arguments(popt,gopt) k = 1; if isfield(popt,'extra_offset') arg{k} = 'offset'; if popt.extra_offset arg{k+1} = 'extra'; else arg{k+1} = 'normal'; end k = k+2; end if isfield(gopt,'fontsize') arg{k} = 'fontsize'; arg{k+1} = gopt.fontsize; k = k+2; end if isfield(gopt,'stereo') arg{k} = 'proj'; if gopt.stereo arg{k+1} = 'stereo'; else arg{k+1} = 'eqarea'; end k = k+2; end if isfield(gopt,'show_title') arg{k} = 'title'; if gopt.show_title if isfield(gopt,'long_title') if gopt.long_title arg{k+1} = 'long'; else arg{k+1} = 'short'; end else arg{k+1} = 'show'; end else arg{k+1} = 'none'; end k = k+2; elseif isfield(gopt,'long_title') arg{k} = 'title'; if gopt.long_title arg{k+1} = 'long'; else arg{k+1} = 'short'; end k = k+2; end if isfield(gopt,'show_points') arg{k} = 'points'; if gopt.show_points arg{k+1} = 'show'; else arg{k+1} = 'hide'; end k = k+2; end if isfield(gopt,'show_surfaces') arg{k} = 'surf'; if gopt.show_surfaces arg{k+1} = 'show'; else arg{k+1} = 'hide'; end k = k+2; end
github
libDirectional/libDirectional-master
expand_region_for_diam.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_region_props/private/expand_region_for_diam.m
1,159
utf_8
7e9858ac0283f7c2396c3d6727ead0b7
function expanded_region = expand_region_for_diam(region) %EXPAND_REGION_FOR_DIAM The set of 2^d vertices of a region % % Expand a region from the 2 vertex definition to the set of 2^dim vertices % of the pseudo-region of a region, so that the Euclidean diameter of a region % is approximated by the diameter of this set. % % expanded_region = expand_region_for_diam(region); % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-12 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. dim = size(region,1); if dim > 1 s_top = region(dim,1); s_bot = region(dim,2); region_1 = expand_region_for_diam(region(1:dim-1,:)); expanded_region = [append(region_1, s_top), append(region_1, s_bot)]; else expanded_region = pseudo_region_for_diam(region); end % % end function function result = append(matrix,value) % Append a coordinate value to each column of a matrix. % % result = append(matrix,value); result = [matrix; ones(1,size(matrix,2))*value]; % % end function
github
libDirectional/libDirectional-master
max_vertex_diam_of_regions.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_region_props/private/max_vertex_diam_of_regions.m
1,945
utf_8
06d6d3f18a8b458a382632d6c252e136
function vertex_diam = max_vertex_diam_of_regions(regions) %MAX_VERTEX_DIAM_OF_REGIONS The max vertex diameter in a cell array of regions % % vertex_diam = max_vertex_diam_of_regions(regions); % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Function changed name from s2x to polar2cart % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-12 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. dim = size(regions,1); if dim == 1 vertex_diam = vertex_diam_region(regions(:,:,1)); else colatitude = -inf*ones(dim-1,1); vertex_diam = 0; N = size(regions,3); for region_n = 1:N top = regions(:,1,region_n); if norm(top(2:dim)-colatitude) ~= 0 colatitude = top(2:dim); vertex_diam = max(vertex_diam,vertex_diam_region(regions(:,:,region_n))); end end end % % end function function diam = vertex_diam_region(region) % Calculate the Euclidean diameter of the set of 2^dim vertices % of the pseudo-region of a region. % % diam = vertex_diam_region(region); expanded_region = expand_region_for_diam(region); dim = size(expanded_region,1); full = size(expanded_region,2); half = floor(full/2); top = expanded_region(:,1); bot = expanded_region(:,full); diam = 0; if sin(top(dim)) > sin(bot(dim)) for point_n_1 = 1:2:half for point_n_2 = point_n_1+1:2:full x1 = polar2cart(expanded_region(:,point_n_1)); x2 = polar2cart(expanded_region(:,point_n_2)); diam = max(diam,euclidean_dist(x1,x2)); end end else for point_n_1 = full:-2:half+1 for point_n_2 = point_n_1-1:-2:1 x1 = polar2cart(expanded_region(:,point_n_1)); x2 = polar2cart(expanded_region(:,point_n_2)); diam = max(diam,euclidean_dist(x1,x2)); end end end % % end function
github
libDirectional/libDirectional-master
max_diam_bound_of_regions.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_region_props/private/max_diam_bound_of_regions.m
1,775
utf_8
40cdd90073575c36f53cfb9196f84187
function diam_bound = max_diam_bound_of_regions(regions) %MAX_DIAM_BOUND_OF_REGIONS The maximum diameter bound in an array of regions % % diam_bound = max_diam_bound_of_regions(regions); % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Function s2e changed name to sph2euc_dist % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-12 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. dim = size(regions,1); if dim == 1 diam_bound = diam_bound_region(regions(:,:,1)); else colatitude = -inf*ones(dim-1,1); diam_bound = 0; N = size(regions,3); for region_n = 1:N top = regions(:,1,region_n); if norm(top(2:dim)-colatitude) ~= 0 colatitude = top(2:dim); diam_bound = max(diam_bound,diam_bound_region(regions(:,:,region_n))); end end end % % end function function diam_bound = diam_bound_region(region) % Calculate the per-region bound on the Euclidean diameter of a region. % % diam_bound = diam_bound_region(region) tol = eps*2^5; pseudo_region = pseudo_region_for_diam(region); dim = size(pseudo_region,1); top = pseudo_region(:,1); bot = pseudo_region(:,2); diam_bound = 0; s = bot(dim)-top(dim); e = sph2euc_dist(s); if dim == 1 diam_bound = e; else max_sin = max(sin(top(dim)),sin(bot(dim))); if (top(dim) <= pi/2) && (bot(dim) >= pi/2) max_sin = 1; end if (abs(top(dim)) < tol) || (abs(pi-bot(dim)) < tol) diam_bound = 2*max_sin; else region_1 = [top(1:dim-1),bot(1:dim-1)]; diam_bound_1 = max_sin*diam_bound_region(region_1); diam_bound = min(2,sqrt(e^2+diam_bound_1^2)); end end % % end function
github
libDirectional/libDirectional-master
eq_area_error.m
.m
libDirectional-master/lib/external/eq_sphere_partitions/eq_test/eq_area_error.m
3,108
utf_8
167106e355712248825d71c9393c02b0
function [total_error, max_error] = eq_area_error(dim,N) %EQ_AREA_ERROR Total area error and max area error per region of an EQ partition % %Syntax % [total_error, max_error] = eq_area_error(dim,N) % %Description % [TOTAL_ERROR, MAX_ERROR] = EQ_AREA_ERROR(dim,N) does the following: % 1) uses the recursive zonal equal area sphere partitioning algorithm to % partition the unit sphere S^dim into N regions, % 2) sets TOTAL_ERROR to be the absolute difference between the total area of % all regions of the partition, and the area of S^dim, and % 3) sets MAX_ERROR to be the maximum absolute difference between the area of % any region of the partition, and the ideal area of a region as given by % AREA_OF_IDEAL_REGION(dim,N), which is 1/N times the area of S^dim. % % The argument dim must be a positive integer. % The argument N must be a positive integer or an array of positive integers. % The results TOTAL_ERROR and MAX_ERROR will be arrays of the same size as N. % %Examples % > [total_error, max_error] = eq_area_error(2,10) % total_error = % 1.7764e-15 % % max_error = % 4.4409e-16 % % > [total_error, max_error] = eq_area_error(3,1:6) % total_error = % 1.0e-12 * % 0.0036 0.0036 0.1847 0.0142 0.0142 0.2132 % % max_error = % 1.0e-12 * % 0.0036 0.0018 0.1954 0.0284 0.0440 0.0777 % %See also % EQ_REGIONS, AREA_OF_SPHERE, AREA_OF_IDEAL_REGION % Copyright 2004-2005 Paul Leopardi for the University of New South Wales. % $Revision 1.10 $ $Date 2005-06-01 $ % Documentation files renamed % $Revision 1.00 $ $Date 2005-02-12 $ % % For licensing, see COPYING. % For references, see AUTHORS. % For revision history, see CHANGELOG. % % Check number of arguments % narginchk(2,2); nargoutchk(2,2); % % Flatten N into a row vector. % shape = size(N); n_partitions = prod(shape); N = reshape(N,1,n_partitions); total_error = zeros(size(N)); max_error = zeros(size(N)); sphere_area = area_of_sphere(dim); for partition_n = 1:n_partitions n = N(partition_n); regions = eq_regions(dim,n); ideal_area = area_of_ideal_region(dim,n); total_area = 0; for region_n = 1:size(regions,3) area = area_of_region(regions(:,:,region_n)); total_area = total_area + area; region_error = abs(area - ideal_area); if region_error > max_error(partition_n) max_error(partition_n) = region_error; end end total_error(partition_n) = abs(sphere_area - total_area); end % % Reshape output to same array size as original N. % total_error = reshape(total_error,shape); max_error = reshape(max_error,shape); % % end function function area = area_of_region(region) %AREA_OF_REGION Area of given region % % area = area_of_region(region); dim = size(region,1); s_top = region(dim,1); s_bot = region(dim,2); if dim > 1 area = area_of_collar(dim, s_top, s_bot)*area_of_region(region(1:dim-1,:))/area_of_sphere(dim-1); else if s_bot == 0 s_bot = 2*pi; end if s_top == s_bot s_bot = s_top + 2*pi; end area = s_bot - s_top; end % % end function
github
libDirectional/libDirectional-master
DiscreteHypersphericalFilter.m
.m
libDirectional-master/lib/filters/DiscreteHypersphericalFilter.m
21,276
utf_8
8956277005138d99e8f538738913764f
classdef DiscreteHypersphericalFilter < AbstractHypersphericalFilter % A discrete filter on the hypersphere properties d w DT end methods function this = DiscreteHypersphericalFilter(nParticles, dim, method) % Constructor % % Parameters: % nParticles (integer > 0) % number of particles to use if nargin < 3 method = 'equalarea'; end this.d = DiscreteHypersphericalFilter.computeDiscretization(nParticles, dim, method); nParticles = size(this.d,2); %the actual number of particles may be different from the requested number of particles this.w = ones(1,nParticles)/nParticles; %this.DT = delaunayTriangulation(this.d') ; this.DT = convhulln(this.d'); end function setState(this, distribution) % Sets the current system state % % Parameters: % distribution (AbstractHypersphericalDistribution) % new state assert(isa(distribution, 'AbstractHypersphericalDistribution')); this.w = distribution.pdf(this.d); this.w = this.w/sum(this.w); end function d = dim(this) d = size(this.d,1); end function predictNonlinear(this, f, noiseDistribution) % where w(k) is noise given by noiseDistribution. % Predicts assuming a nonlinear system model, i.e., % f(x(k+1)|x_k) = VMF(x(k+1) ; mu = f(x_k), kappa_k^w) % where w is noise given by sysNoise. % % Parameters: % f (function handle) % function from S^(dim-1) to S^(dim-1) % noiseDistribution (VMFDistribution) % distribution of noise assert(isa (noiseDistribution, 'VMFDistribution')); %todo generalize to Watson etc. assert(isa(f,'function_handle')); %apply f nParticles = length(this.d); w_ = zeros(size(this.w)); % set all weights to zero for i=1:nParticles newLocation = f(this.d(:,i)); noiseDistribution.mu = newLocation; w_ = w_ + this.w(i)*noiseDistribution.pdf(this.d); end this.w = w_; end function predictNonlinearNonAdditive(this, f, noiseSamples, noiseWeights, mode) % Predicts assuming a nonlinear system model, i.e., % x(k+1) = f(x(k), w(k)) % where w(k) is non-additive noise given by samples and weights. % % Parameters: % f (function handle) % function from S^(dim-1) x W to S^(dim-1) (W is the space % containing the noise samples) % noiseSamples (d2 x n matrix) % n samples of the noise as d2-dimensional vectors % noiseWeights (1 x n vector) % weight of each sample % (samples, weights) are discrete approximation of noise assert(size(noiseWeights,1) == 1, 'weights most be row vector') assert(size(noiseSamples,2) == size(noiseWeights,2), 'samples and weights must match in size'); assert(isa(f,'function_handle')); noiseWeights = noiseWeights/sum(noiseWeights); % ensure normalization if nargin <= 4 mode = 'nn'; end % apply f nParticles = length(this.d); oldWeights = this.w; this.w = zeros(size(this.w)); % set all weights to zero for i=1:nParticles for j=1:length(noiseSamples) newLocation = f(this.d(:,i),noiseSamples(:,j)); newWeight = oldWeights(i)*noiseWeights(j); if strcmp(mode, 'nn') %simple nearest neighbor assignment for now idx = knnsearch(this.d', newLocation'); this.w(idx) = this.w(idx) + newWeight; elseif strcmp(mode, 'delaunay') %todo: only works in 3D so far? if this.dim == 3 %find triangle [t,u,v] = this.findTriangle(newLocation); %interpolate in triangle this.w(t(1)) = this.w(t(1)) + (1-u-v)*newWeight; this.w(t(2)) = this.w(t(2)) + u*newWeight; this.w(t(3)) = this.w(t(3)) + v*newWeight; else error('not supported') end elseif strcmp(mode, 'knn') k=3; [idx,D] = knnsearch(this.d', newLocation', 'K', k); %todo test, verify that weights sum to 1 %todo this can lead to negative weights! for l=1:k this.w(idx(l)) = this.w(idx(l)) + (sum(D)-(k-1)*D(l))/sum(D)*newWeight; end else error('unsupported mode'); end end end end function [triangle, u, v] = findTriangle(this, x) [int, ~, u, v] = TriangleRayIntersection([0,0,0], x, this.d(:,this.DT(:,1)), this.d(:,this.DT(:,2)), this.d(:,this.DT(:,3))); index = find(int,1); assert(~isempty(index)); %if this fails, no triangle was found due to numerical inaccuracy - how to handle that? triangle = this.DT(index,:); u = u(index); v = v(index); end function updateNonlinear(this, likelihood, z) % Updates assuming nonlinear measurement model given by a % likelihood function likelihood(z,x) = f(z|x), where z is the % measurement. The function can be created using the % LikelihoodFactory. % % Parameters: % likelihood (function handle) % function from Z x [0,2pi) to [0, infinity), where Z is % the measurement space containing z % z (arbitrary) % measurement assert(isa(likelihood,'function_handle')); % You can either use a likelihood depending on z and x % and specify the measurement as z or use a likelihood that % depends only on x and omit z. if nargin==2 this.w = this.w .* likelihood(this.d); else this.w = this.w .* likelihood(z, this.d); end end function [d,w] = getEstimate(this) % Return current estimate % % Returns: d = this.d; w = this.w; end function plotEstimate(this) switch this.dim case 2 scatter3(this.d(1,:), this.d(2,:), this.w) case 3 scatter3(this.d(1,:), this.d(2,:), this.d(3,:), length(this.w)*10*this.w) otherwise error('not implemented') end end function m = getEstimateMean(this) m = sum(this.d.*repmat(this.w, this.dim, 1),2); m = m/norm(m); end end methods (Static) function d = computeDiscretization(nParticles, dim, method) function r = goalFun (d) d = d./repmat(sqrt(sum(d.^2)),size(d,1),1); [~, dist] = knnsearch(d',d', 'K', 2); r = -sum((dist(:,2))); end if strcmp(method, 'random') d = rand(dim, nParticles)-0.5; d = d./repmat(sqrt(sum(d.^2)),dim,1); elseif strcmp(method, 'stratified') assert(dim == 3); d = RandSampleSphere(nParticles, 'stratified')'; elseif strcmp(method, 'optimize') if dim == 2 % use simple closed form solution in 2D phi = linspace(0,2*pi,nParticles + 1); phi = phi(1:end-1); d = [cos(phi);sin(phi)]; else [pathstr,~,~] = fileparts(mfilename('fullpath')); filename = sprintf('%s/../util/autogenerated/optimize-%i-%i.mat', pathstr, nParticles, dim); if exist(filename, 'file') load (filename); else %initialize with random values %d = rand(dim, nParticles)-0.5; %d = d./repmat(sqrt(sum(d.^2)),dim,1); %initialize with equal area solution d = eq_point_set(dim-1, nParticles); %todo improve solution quality and performance d = fminunc(@goalFun, d, optimoptions('fminunc', 'display', 'iter', 'MaxFunEvals', 1E6)); d = d./repmat(sqrt(sum(d.^2)),dim,1); save(filename, 'd'); end end elseif strcmp(method, 'platonic') assert(dim == 3); %todo generate next larger polyhedron instead of insisting %on number of particles switch nParticles case 4 d = DiscreteHypersphericalFilter.tetrahedron(); case 6 d = DiscreteHypersphericalFilter.octahedron(); case 8 d = DiscreteHypersphericalFilter.hexahedron(); case 12 d = DiscreteHypersphericalFilter.icosahedron(); case 20 d = DiscreteHypersphericalFilter.dodecahedron(); otherwise error('unsupported number of particles'); end elseif strcmp(method, 'spiral') assert(dim == 3); d = SpiralSampleSphere(nParticles)'; elseif strcmp(method, 'reisz') assert(dim == 3); if nParticles<14 nParticles = 14; end d = ParticleSampleSphere('N', nParticles)'; elseif strcmp(method, 'cubesubdivision') %number of points: 6*4.^n+2 assert(dim == 3); c = QuadCubeMesh(); while size(c.vertices, 1) < nParticles % subdivide untile we have at least nParticles c = SubdivideSphericalMesh(c,1); end d = c.vertices'; elseif strcmp(method, 'pentakissubdivision') %number of points 30*4.^n+2 assert(dim == 3); c = DodecahedronMesh(); while size(c.Points, 1) < nParticles % subdivide untile we have at least nParticles c = SubdivideSphericalMesh(c,1); end d = c.Points'; elseif strcmp(method, 'rhombicsubdivision') %number of points 12*4.^n+2 assert(dim == 3); c = QuadRhombDodecMesh(); while size(c.vertices, 1) < nParticles % subdivide untile we have at least nParticles c = SubdivideSphericalMesh(c,1); end d = c.vertices'; elseif strcmp(method, 'icosahedronsubdivision') %number of points: 10*4.^n+2 %https://oeis.org/A122973 assert(dim == 3); c = IcosahedronMesh(); while size(c.Points, 1) < nParticles % subdivide untile we have at least nParticles c = SubdivideSphericalMesh(c,1); end d = c.Points'; elseif strcmp(method, 'equalarea') d = eq_point_set(dim-1, nParticles); elseif strcmp(method, 'gridsphere') assert(dim == 3); [lat,lon] = GridSphere(nParticles); lat = lat/180*pi; lon = lon/180*pi; x = cos(lat) .* cos(lon); y = cos(lat) .* sin(lon); z = sin(lat); d = [x'; y'; z']; elseif strcmp(method, 'schaefer') assert(dim == 4); %will return 2*8^n points for n=1,2,3,... d = tessellate_S3(nParticles); elseif strcmp(method, 'regular4polytope') assert(dim == 4); %todo implement remaining 4 polytopes? if nParticles <=24 d = DiscreteHypersphericalFilter.generate24cell(); elseif nParticles <=120 d = DiscreteHypersphericalFilter.generate600cell(); elseif nParticles<=600 d = DiscreteHypersphericalFilter.generate120cell(); else d = DiscreteHypersphericalFilter.generate120cell(); %todo warning/error? end elseif strcmp(method, 'tesseractsubdivision') assert(dim == 4); d = tesseractsubdivision(nParticles)'; else error('unsupported method') end end function d = tetrahedron() % see https://en.wikipedia.org/wiki/Tetrahedron#Formulas_for_a_regular_tetrahedron d = [1 0 -1/sqrt(2); -1 0 -1/sqrt(2); 0 1 1/sqrt(2); 0 -1 1/sqrt(2)]'; d = d./repmat(sqrt(sum(d.^2)),size(d,1),1); end function d = hexahedron() % see https://en.wikipedia.org/wiki/Cube#Cartesian_coordinates d = [1 1 1; 1 1 -1; 1 -1 1; 1 -1 -1; -1 1 1; -1 1 -1; -1 -1 1; -1 -1 -1]'/sqrt(3); end function d = octahedron() % see https://en.wikipedia.org/wiki/Octahedron#Cartesian_coordinates d = [1 0 0 ; 0 1 0; 0 0 1]'; d = [d -d]; end function d = dodecahedron() % see https://en.wikipedia.org/wiki/Dodecahedron#Cartesian_coordinates h = (sqrt(5)-1)/2; % inverse golden ratio a = 1+h; b = 1-h^2; d = [1 1 1; 1 1 -1; 1 -1 1; 1 -1 -1; -1 1 1; -1 1 -1; -1 -1 1; -1 -1 -1; 0 a b; 0 a -b; 0 -a b; 0 -a -b; a, b, 0; a, -b, 0; -a, b, 0; -a, -b, 0; b, 0, a; b, 0, -a; -b, 0, a; -b, 0, -a; ]'; d = d./repmat(sqrt(sum(d.^2)),size(d,1),1); end function d = icosahedron() % see https://en.wikipedia.org/wiki/Regular_icosahedron#Cartesian_coordinates phi = (1+sqrt(5))/2; % golden ratio d = [0 1 phi; 1 phi 0; phi 0 1; 0 -1 phi; -1 phi 0; phi 0 -1]'; d = [d -d]; d = d./repmat(sqrt(sum(d.^2)),size(d,1),1); end function d = generate600cell() % Generates 600 cell in 4D % see https://en.wikipedia.org/wiki/600-cell % The 600 cell has 120 vertices! phi = (1+sqrt(5))/2; % golden ratio signs3 = 2*(dec2bin(0:7)-'0')-1; p = evenperms(4); %16 vertices on [+-0.5, +-0.5, +-0.5, +-0.5] d1 = dec2bin(0:2^4-1)-'0'-0.5; %8 vertices on permutations of [0 0 0 +-1] d2 = dec2bin(2.^(0:3))-'0'; d3 = -d2; %96 vertices on even permutations of 0.5 [+-phi, +-1, +-1/phi,0] d4 = zeros(96,4); index = 1; for j=1:size(p,1) %iterate over permutations for i=1:size(signs3,1) %iterate over 8 different combinations of signs currentPoint = 0.5* [ [phi , 1 , 1/phi].*signs3(i,:), 0]; d4(index,:) = currentPoint(p(j,:)); index = index + 1; end end d = [d1; d2; d3; d4]'; d = d./repmat(sqrt(sum(d.^2)),size(d,1),1); end function d = generate120cell() % Generates 120 cell in 4D % see https://en.wikipedia.org/wiki/120-cell % and http://mathworld.wolfram.com/120-Cell.html % The 120 cell has 600 vertices! phi = (1+sqrt(5))/2; % golden ratio signs3 = 2*(dec2bin(0:7)-'0')-1; signs4 = 2*(dec2bin(0:15)-'0')-1; p = evenperms(4); shiftRight = [0 1 0 0; 0 0 1 0; 0 0 0 1; 1 0 0 0]; % permutations of [0, 0, +-2, +-2] %d1 = [zeros(4,2) (dec2bin(0:3)-'0')*4-2]; d1 = [perms([0 0 -2 -2]); perms([0 0 -2 2]); perms([0 0 2 2])]; d1 = unique(d1,'rows'); % permutations of [+-1, +-1, +-1,, +-sqrt(5)] d2 = signs4.*repmat([1 1 1 sqrt(5)], 16, 1); d2 = [d2; d2*shiftRight; d2*shiftRight^2; d2*shiftRight^3]; % permutations of [+- phi^(-2), +-phi, +-phi, +-phi] d3 = signs4.*repmat([phi^(-2), phi, phi, phi], 16, 1); d3 = [d3; d3*shiftRight; d3*shiftRight^2; d3*shiftRight^3]; % permutations of [+- phi^(-1), +- phi^(-1), +-phi^(-1), +-phi^2] d4 = signs4.*repmat([phi^(-1), phi^(-1), phi^(-1), phi^2], 16, 1); d4 = [d4; d4*shiftRight; d4*shiftRight^2; d4*shiftRight^3]; %even permutations of [0, +-phi^(-2), +-1, +-phi^2] d5 = zeros(96,4); index = 1; for j=1:size(p,1) %iterate over permutations for i=1:size(signs3,1) %iterate over 8 different combinations of signs currentPoint = [0, [phi^(-2) , 1 , phi^2].*signs3(i,:)]; d5(index,:) = currentPoint(p(j,:)); index = index + 1; end end %even permutations of [0, +-phi^(-1), +-phi, +-sqrt(5)] d6 = zeros(96,4); index = 1; for j=1:size(p,1) %iterate over permutations for i=1:size(signs3,1) %iterate over 8 different combinations of signs currentPoint = [0, [phi^(-1) , phi , sqrt(5)].*signs3(i,:)]; d6(index,:) = currentPoint(p(j,:)); index = index + 1; end end %even permutations of [+-phi^(-1), +-1, +-phi, +-2] d7 = zeros(192,4); index = 1; for j=1:size(p,1) %iterate over permutations for i=1:size(signs4,1) %iterate over 16 different combinations of signs currentPoint = [phi^(-1), 1, phi, 2].*signs4(i,:); d7(index,:) = currentPoint(p(j,:)); index = index + 1; end end d = [d1; d2; d3; d4; d5; d6; d7]'; d = d./repmat(sqrt(sum(d.^2)),size(d,1),1); end function d = generate24cell() % Generates 24 cell in 4D % see https://en.wikipedia.org/wiki/24-cell % The 24 cell has 24 vertices! signs4 = 2*(dec2bin(0:15)-'0')-1; shiftRight = [0 1 0 0; 0 0 1 0; 0 0 0 1; 1 0 0 0]; %permutations of [+-1, 0, 0, 0] d1 = [1 0 0 0; -1 0 0 0]; d1 = [d1; d1*shiftRight; d1*shiftRight^2; d1*shiftRight^3]; %[+-0.5,+-0.5,+-0.5,+-0.5] d2 = signs4 * 0.5; d = [d1; d2;]'; d = d./repmat(sqrt(sum(d.^2)),size(d,1),1); end end end function p = evenperms(n) %returns even permutations of 1,..,n p = perms(1:n); M = eye(n,n); e = false(1,size(p,1)); for j=1:size(p,1) %iterate over permutations currentPerm = p(j,:); if det(M(currentPerm,:))==1 %check if permutation is even e(j)=1; end end p = p(e,:); end
github
jmportilla/stanford_dl_ex-master
WolfeLineSearch.m
.m
stanford_dl_ex-master/common/minFunc_2012/minFunc/WolfeLineSearch.m
10,590
utf_8
f962bc5ae0a1e9f80202a9aaab106dab
function [t,f_new,g_new,funEvals,H] = WolfeLineSearch(... x,t,d,f,g,gtd,c1,c2,LS_interp,LS_multi,maxLS,progTol,debug,doPlot,saveHessianComp,funObj,varargin) % % Bracketing Line Search to Satisfy Wolfe Conditions % % Inputs: % x: starting location % t: initial step size % d: descent direction % f: function value at starting location % g: gradient at starting location % gtd: directional derivative at starting location % c1: sufficient decrease parameter % c2: curvature parameter % debug: display debugging information % LS_interp: type of interpolation % maxLS: maximum number of iterations % progTol: minimum allowable step length % doPlot: do a graphical display of interpolation % funObj: objective function % varargin: parameters of objective function % % Outputs: % t: step length % f_new: function value at x+t*d % g_new: gradient value at x+t*d % funEvals: number function evaluations performed by line search % H: Hessian at initial guess (only computed if requested % Evaluate the Objective and Gradient at the Initial Step if nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x+t*d,varargin{:}); end funEvals = 1; gtd_new = g_new'*d; % Bracket an Interval containing a point satisfying the % Wolfe criteria LSiter = 0; t_prev = 0; f_prev = f; g_prev = g; gtd_prev = gtd; nrmD = max(abs(d)); done = 0; while LSiter < maxLS %% Bracketing Phase if ~isLegal(f_new) || ~isLegal(g_new) if debug fprintf('Extrapolated into illegal region, switching to Armijo line-search\n'); end t = (t + t_prev)/2; % Do Armijo if nargout == 5 [t,x_new,f_new,g_new,armijoFunEvals,H] = ArmijoBacktrack(... x,t,d,f,f,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,... funObj,varargin{:}); else [t,x_new,f_new,g_new,armijoFunEvals] = ArmijoBacktrack(... x,t,d,f,f,g,gtd,c1,LS_interp,LS_multi,progTol,debug,doPlot,saveHessianComp,... funObj,varargin{:}); end funEvals = funEvals + armijoFunEvals; return; end if f_new > f + c1*t*gtd || (LSiter > 1 && f_new >= f_prev) bracket = [t_prev t]; bracketFval = [f_prev f_new]; bracketGval = [g_prev g_new]; break; elseif abs(gtd_new) <= -c2*gtd bracket = t; bracketFval = f_new; bracketGval = g_new; done = 1; break; elseif gtd_new >= 0 bracket = [t_prev t]; bracketFval = [f_prev f_new]; bracketGval = [g_prev g_new]; break; end temp = t_prev; t_prev = t; minStep = t + 0.01*(t-temp); maxStep = t*10; if LS_interp <= 1 if debug fprintf('Extending Braket\n'); end t = maxStep; elseif LS_interp == 2 if debug fprintf('Cubic Extrapolation\n'); end t = polyinterp([temp f_prev gtd_prev; t f_new gtd_new],doPlot,minStep,maxStep); elseif LS_interp == 3 t = mixedExtrap(temp,f_prev,gtd_prev,t,f_new,gtd_new,minStep,maxStep,debug,doPlot); end f_prev = f_new; g_prev = g_new; gtd_prev = gtd_new; if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; end if LSiter == maxLS bracket = [0 t]; bracketFval = [f f_new]; bracketGval = [g g_new]; end %% Zoom Phase % We now either have a point satisfying the criteria, or a bracket % surrounding a point satisfying the criteria % Refine the bracket until we find a point satisfying the criteria insufProgress = 0; Tpos = 2; LOposRemoved = 0; while ~done && LSiter < maxLS % Find High and Low Points in bracket [f_LO LOpos] = min(bracketFval); HIpos = -LOpos + 3; % Compute new trial value if LS_interp <= 1 || ~isLegal(bracketFval) || ~isLegal(bracketGval) if debug fprintf('Bisecting\n'); end t = mean(bracket); elseif LS_interp == 2 if debug fprintf('Grad-Cubic Interpolation\n'); end t = polyinterp([bracket(1) bracketFval(1) bracketGval(:,1)'*d bracket(2) bracketFval(2) bracketGval(:,2)'*d],doPlot); else % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nonTpos = -Tpos+3; if LOposRemoved == 0 oldLOval = bracket(nonTpos); oldLOFval = bracketFval(nonTpos); oldLOGval = bracketGval(:,nonTpos); end t = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot); end % Test that we are making sufficient progress if min(max(bracket)-t,t-min(bracket))/(max(bracket)-min(bracket)) < 0.1 if debug fprintf('Interpolation close to boundary'); end if insufProgress || t>=max(bracket) || t <= min(bracket) if debug fprintf(', Evaluating at 0.1 away from boundary\n'); end if abs(t-max(bracket)) < abs(t-min(bracket)) t = max(bracket)-0.1*(max(bracket)-min(bracket)); else t = min(bracket)+0.1*(max(bracket)-min(bracket)); end insufProgress = 0; else if debug fprintf('\n'); end insufProgress = 1; end else insufProgress = 0; end % Evaluate new point if ~saveHessianComp && nargout == 5 [f_new,g_new,H] = funObj(x + t*d,varargin{:}); else [f_new,g_new] = funObj(x + t*d,varargin{:}); end funEvals = funEvals + 1; gtd_new = g_new'*d; LSiter = LSiter+1; armijo = f_new < f + c1*t*gtd; if ~armijo || f_new >= f_LO % Armijo condition not satisfied or not lower than lowest % point bracket(HIpos) = t; bracketFval(HIpos) = f_new; bracketGval(:,HIpos) = g_new; Tpos = HIpos; else if abs(gtd_new) <= - c2*gtd % Wolfe conditions satisfied done = 1; elseif gtd_new*(bracket(HIpos)-bracket(LOpos)) >= 0 % Old HI becomes new LO bracket(HIpos) = bracket(LOpos); bracketFval(HIpos) = bracketFval(LOpos); bracketGval(:,HIpos) = bracketGval(:,LOpos); if LS_interp == 3 if debug fprintf('LO Pos is being removed!\n'); end LOposRemoved = 1; oldLOval = bracket(LOpos); oldLOFval = bracketFval(LOpos); oldLOGval = bracketGval(:,LOpos); end end % New point becomes new LO bracket(LOpos) = t; bracketFval(LOpos) = f_new; bracketGval(:,LOpos) = g_new; Tpos = LOpos; end if ~done && abs(bracket(1)-bracket(2))*nrmD < progTol if debug fprintf('Line-search bracket has been reduced below progTol\n'); end break; end end %% if LSiter == maxLS if debug fprintf('Line Search Exceeded Maximum Line Search Iterations\n'); end end [f_LO LOpos] = min(bracketFval); t = bracket(LOpos); f_new = bracketFval(LOpos); g_new = bracketGval(:,LOpos); % Evaluate Hessian at new point if nargout == 5 && funEvals > 1 && saveHessianComp [f_new,g_new,H] = funObj(x + t*d,varargin{:}); funEvals = funEvals + 1; end end %% function [t] = mixedExtrap(x0,f0,g0,x1,f1,g1,minStep,maxStep,debug,doPlot); alpha_c = polyinterp([x0 f0 g0; x1 f1 g1],doPlot,minStep,maxStep); alpha_s = polyinterp([x0 f0 g0; x1 sqrt(-1) g1],doPlot,minStep,maxStep); if alpha_c > minStep && abs(alpha_c - x1) < abs(alpha_s - x1) if debug fprintf('Cubic Extrapolation\n'); end t = alpha_c; else if debug fprintf('Secant Extrapolation\n'); end t = alpha_s; end end %% function [t] = mixedInterp(bracket,bracketFval,bracketGval,d,Tpos,oldLOval,oldLOFval,oldLOGval,debug,doPlot); % Mixed Case %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% nonTpos = -Tpos+3; gtdT = bracketGval(:,Tpos)'*d; gtdNonT = bracketGval(:,nonTpos)'*d; oldLOgtd = oldLOGval'*d; if bracketFval(Tpos) > oldLOFval alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); alpha_q = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) sqrt(-1)],doPlot); if abs(alpha_c - oldLOval) < abs(alpha_q - oldLOval) if debug fprintf('Cubic Interpolation\n'); end t = alpha_c; else if debug fprintf('Mixed Quad/Cubic Interpolation\n'); end t = (alpha_q + alpha_c)/2; end elseif gtdT'*oldLOgtd < 0 alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); alpha_s = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) sqrt(-1) gtdT],doPlot); if abs(alpha_c - bracket(Tpos)) >= abs(alpha_s - bracket(Tpos)) if debug fprintf('Cubic Interpolation\n'); end t = alpha_c; else if debug fprintf('Quad Interpolation\n'); end t = alpha_s; end elseif abs(gtdT) <= abs(oldLOgtd) alpha_c = polyinterp([oldLOval oldLOFval oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],... doPlot,min(bracket),max(bracket)); alpha_s = polyinterp([oldLOval sqrt(-1) oldLOgtd bracket(Tpos) bracketFval(Tpos) gtdT],... doPlot,min(bracket),max(bracket)); if alpha_c > min(bracket) && alpha_c < max(bracket) if abs(alpha_c - bracket(Tpos)) < abs(alpha_s - bracket(Tpos)) if debug fprintf('Bounded Cubic Extrapolation\n'); end t = alpha_c; else if debug fprintf('Bounded Secant Extrapolation\n'); end t = alpha_s; end else if debug fprintf('Bounded Secant Extrapolation\n'); end t = alpha_s; end if bracket(Tpos) > oldLOval t = min(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t); else t = max(bracket(Tpos) + 0.66*(bracket(nonTpos) - bracket(Tpos)),t); end else t = polyinterp([bracket(nonTpos) bracketFval(nonTpos) gtdNonT bracket(Tpos) bracketFval(Tpos) gtdT],doPlot); end end
github
jmportilla/stanford_dl_ex-master
minFunc_processInputOptions.m
.m
stanford_dl_ex-master/common/minFunc_2012/minFunc/minFunc_processInputOptions.m
4,103
utf_8
8822581c3541eabe5ce7c7927a57c9ab
function [verbose,verboseI,debug,doPlot,maxFunEvals,maxIter,optTol,progTol,method,... corrections,c1,c2,LS_init,cgSolve,qnUpdate,cgUpdate,initialHessType,... HessianModify,Fref,useComplex,numDiff,LS_saveHessianComp,... Damped,HvFunc,bbType,cycle,... HessianIter,outputFcn,useMex,useNegCurv,precFunc,... LS_type,LS_interp,LS_multi,DerivativeCheck] = ... minFunc_processInputOptions(o) % Constants SD = 0; CSD = 1; BB = 2; CG = 3; PCG = 4; LBFGS = 5; QNEWTON = 6; NEWTON0 = 7; NEWTON = 8; TENSOR = 9; verbose = 1; verboseI= 1; debug = 0; doPlot = 0; method = LBFGS; cgSolve = 0; o = toUpper(o); if isfield(o,'DISPLAY') switch(upper(o.DISPLAY)) case 0 verbose = 0; verboseI = 0; case 'FINAL' verboseI = 0; case 'OFF' verbose = 0; verboseI = 0; case 'NONE' verbose = 0; verboseI = 0; case 'FULL' debug = 1; case 'EXCESSIVE' debug = 1; doPlot = 1; end end DerivativeCheck = 0; if isfield(o,'DERIVATIVECHECK') switch(upper(o.DERIVATIVECHECK)) case 1 DerivativeCheck = 1; case 'ON' DerivativeCheck = 1; end end LS_init = 0; LS_type = 1; LS_interp = 2; LS_multi = 0; Fref = 1; Damped = 0; HessianIter = 1; c2 = 0.9; if isfield(o,'METHOD') m = upper(o.METHOD); switch(m) case 'TENSOR' method = TENSOR; case 'NEWTON' method = NEWTON; case 'MNEWTON' method = NEWTON; HessianIter = 5; case 'PNEWTON0' method = NEWTON0; cgSolve = 1; case 'NEWTON0' method = NEWTON0; case 'QNEWTON' method = QNEWTON; Damped = 1; case 'LBFGS' method = LBFGS; case 'BB' method = BB; LS_type = 0; Fref = 20; case 'PCG' method = PCG; c2 = 0.2; LS_init = 2; case 'SCG' method = CG; c2 = 0.2; LS_init = 4; case 'CG' method = CG; c2 = 0.2; LS_init = 2; case 'CSD' method = CSD; c2 = 0.2; Fref = 10; LS_init = 2; case 'SD' method = SD; LS_init = 2; end end maxFunEvals = getOpt(o,'MAXFUNEVALS',1000); maxIter = getOpt(o,'MAXITER',500); optTol = getOpt(o,'OPTTOL',1e-5); progTol = getOpt(o,'PROGTOL',1e-9); corrections = getOpt(o,'CORRECTIONS',100); corrections = getOpt(o,'CORR',corrections); c1 = getOpt(o,'C1',1e-4); c2 = getOpt(o,'C2',c2); LS_init = getOpt(o,'LS_INIT',LS_init); cgSolve = getOpt(o,'CGSOLVE',cgSolve); qnUpdate = getOpt(o,'QNUPDATE',3); cgUpdate = getOpt(o,'CGUPDATE',2); initialHessType = getOpt(o,'INITIALHESSTYPE',1); HessianModify = getOpt(o,'HESSIANMODIFY',0); Fref = getOpt(o,'FREF',Fref); useComplex = getOpt(o,'USECOMPLEX',0); numDiff = getOpt(o,'NUMDIFF',0); LS_saveHessianComp = getOpt(o,'LS_SAVEHESSIANCOMP',1); Damped = getOpt(o,'DAMPED',Damped); HvFunc = getOpt(o,'HVFUNC',[]); bbType = getOpt(o,'BBTYPE',0); cycle = getOpt(o,'CYCLE',3); HessianIter = getOpt(o,'HESSIANITER',HessianIter); outputFcn = getOpt(o,'OUTPUTFCN',[]); useMex = getOpt(o,'USEMEX',1); useNegCurv = getOpt(o,'USENEGCURV',1); precFunc = getOpt(o,'PRECFUNC',[]); LS_type = getOpt(o,'LS_type',LS_type); LS_interp = getOpt(o,'LS_interp',LS_interp); LS_multi = getOpt(o,'LS_multi',LS_multi); end function [v] = getOpt(options,opt,default) if isfield(options,opt) if ~isempty(getfield(options,opt)) v = getfield(options,opt); else v = default; end else v = default; end end function [o] = toUpper(o) if ~isempty(o) fn = fieldnames(o); for i = 1:length(fn) o = setfield(o,upper(fn{i}),getfield(o,fn{i})); end end end
github
jmportilla/stanford_dl_ex-master
removeDC.m
.m
stanford_dl_ex-master/rica/removeDC.m
420
utf_8
98f8564a2e7aaf2a188d142a08be2c14
% Removes DC component from image patches % Data given as a matrix where each patch is one column vectors % That is, the patches are vectorized. function [Y,meanX]=removeDC(X, dim); % Subtract local mean gray-scale value from each patch in X to give output Y if nargin == 1 dim = 1; end meanX = mean(X,dim); if dim==1 Y = X-meanX(ones(size(X,1),1),:); else Y = X-meanX(:,ones(size(X,2),1)); end return;
github
jmportilla/stanford_dl_ex-master
softICACost.m
.m
stanford_dl_ex-master/rica/softICACost.m
388
utf_8
d9004e62d6d16c20a74f4b05339c197c
%% Your job is to implement the RICA cost and gradient function [cost,grad] = softICACost(theta, x, params) % unpack weight matrix W = reshape(theta, params.numFeatures, params.n); % project weights to norm ball (prevents degenerate bases) Wold = W; W = l2rowscaled(W, 1); %%% YOUR CODE HERE %%% % unproject gradient for minFunc grad = l2rowscaledg(Wold, W, Wgrad, 1); grad = grad(:);
github
jmportilla/stanford_dl_ex-master
bsxfunwrap.m
.m
stanford_dl_ex-master/rica/bsxfunwrap.m
1,030
utf_8
9db0f61375c03b342b2005b39d596726
function c = bsxfunwrap(func, a, b) global usegpu; if usegpu if size(a,1) > 1 && size(b,1) == 1 assert(size(a,2) == size(b,2), 'bsxfunwrap singleton dimensions dont agree'); c = func(a, repmat(b, size(a,1), 1)); elseif size(a,2) > 1 && size(b,2) == 1 assert(size(a,1) == size(b,1), 'bsxfunwrap singleton dimensions dont agree'); c = func(a, repmat(b, 1, size(a,2))); elseif size(b,1) > 1 && size(a,1) == 1 assert(size(b,2) == size(a,2), 'bsxfunwrap singleton dimensions dont agree'); c = func(repmat(a, size(b, 1), 1), b); elseif size(b,2) > 1 && size(a,2) == 1 assert(size(b,1) == size(a,1), 'bsxfunwrap singleton dimensions dont agree'); c = func(repmat(a, 1, size(b, 2)), b); else assert(size(a,1) == size(b,1), 'no bsxfun to do, bsxfunwrap dimensions dont agree'); assert(size(a,2) == size(b,2), 'no bsxfun to do, bsxfunwrap dimensions dont agree'); c = func(a, b); end else c = bsxfun(func, a, b); end end
github
ABCDlab/surfstat-helper-master
saveTable.m
.m
surfstat-helper-master/+abcd/saveTable.m
3,659
utf_8
af8e02e2a64a016617202555de96a114
function saveTable( table, file, varargin ) % A flexible table writer to save tabular data to a file. Accepts data in % several formats, and can handle mixed text and numeric data. % % Usage: saveTable( table, file [, optionName, optionvalue ...]); % % table The input table data. Can be: % - A structure array where each field contains one column. % Column names are taken from the field names. % - A cell array where the first row contains the field names, % and the following rows contain the data values. % % file The output file. Can be: % - A file name % - The fid of an already-open file % % OPTIONS % % 'colDelim' Default is tab ('\t') % % 'rowDelim' Default is newline ('\n') % % 'strict' Require all table rows to have equal number of columns. Default is false. % p = inputParser; p.addParamValue('colDelim', sprintf('\t'), @ischar); p.addParamValue('rowDelim', sprintf('\n'), @ischar); p.addParamValue('strict', false, @islogical); p.parse(varargin{:}); outputTable = {}; if (isa(table, 'struct')) outputTable = cellTableFromStructTable(table, p.Results); end if isnumeric(file) fid = file; elseif ischar(file) fid = fopen(file, 'w'); else error('File must be a filename or fid'); end if fid < 0 error('Error opening outout file'); end writeCellTableToOpenFile(outputTable, fid, p.Results); if fid > 2 % if fid is not STDOUT/STDIN/STDERR fclose(fid); end end %% Private functions . . . function writeCellTableToOpenFile(table, fid, p) for r = 1:size(table,1) for c = 1:size(table,2) if c>1, fprintf(fid, p.colDelim); end if isnumeric(table{r,c}) fprintf(fid, '%s', num2str(table{r,c})); elseif ischar(table{r,c}) fprintf(fid, '%s', table{r,c}); else error('Unrecognized value type in output table, row=%d, col=%s, type=%s', r, c, class(table{r,c})); end end fprintf(fid, p.rowDelim); end end function cellTable = cellTableFromStructTable(structTable, p) f = fieldnames(structTable); maxRows = 0; allColsEqualLength = true; for i = 1:length(f) prevMaxRows = maxRows; if (ischar(structTable.(f{i}))) maxRows = max(maxRows, size(structTable.(f{i}),1)); elseif (isvector(structTable.(f{i})) || isempty(structTable.(f{i}))) maxRows = max(maxRows, length(structTable.(f{i}))); else error(['Received a structure array table, but a column is not a column vector! Field = ' f{i}]); end if (prevMaxRows ~= 0 && prevMaxRows ~= maxRows) allColsEqualLength = false; end end if ~allColsEqualLength if p.strict error('Not all columns have an equal number of values!'); else warning('Not all columns have an equal number of values!'); end end cellTable = cell(maxRows+1, length(f)); cellTable(1,:) = f(:)'; for i = 1:length(f) if (ischar(structTable.(f{i}))) cellTable(2:1+size(structTable.(f{i}),1), i) = cellstr(structTable.(f{i}))'; elseif (iscellstr(structTable.(f{i}))) cellTable(2:1+size(structTable.(f{i}),1), i) = structTable.(f{i})(:)'; elseif ((isvector(structTable.(f{i})) || isempty(structTable.(f{i}))) && isnumeric(structTable.(f{i}))) cellTable(2:1+length(structTable.(f{i})), i) = num2cell(structTable.(f{i})(:))'; else error(['Unrecognized column type, field = ' f{i}]); end end end
github
ABCDlab/surfstat-helper-master
attributeStore.m
.m
surfstat-helper-master/+abcd/@attributeStore/attributeStore.m
5,414
utf_8
c03158b2f6dfbc0d89eef9815363aa6e
classdef attributeStore < handle % AttributeStore is a class to store name-value attributes. % The contents of the store can be rendered to a string in a flexible % format using the asString method. properties Attribs = struct(); end properties (Hidden) StringOptions = []; end methods function obj = attributeStore(varargin) % Create an AttributeStore object if (nargin == 1) arg = varargin{1}; if (isa(arg, class(obj))) % pass through obj = arg; elseif (isa(arg, 'struct')) f = fieldnames(arg); for i=1:numel(f) name = f{1}; obj.set(name, arg.(name)); end end elseif (nargin > 1) obj.set(varargin{:}); end end function value = value(AS, name) % Get value of attribute if (~isfield(AS.Attribs, name)) value = []; else value = AS.Attribs.(name); end end function set(AS, varargin) % Set value of attribute for i=1:2:numel(varargin) name = varargin{i}; value = varargin{i+1}; assert(any(strcmp(class(value),{'char' 'single' 'double' 'logical'}))); AS.Attribs.(name) = value; end end function append(AS, name, value, delimiter) if (nargin < 4), delimiter = ','; end origValue = AS.value(name); if (isempty(origValue)), delimiter = ''; origValue = ''; end if (~isa(origValue, 'char')) error('The append method requires the existing value to be a string or empty'); end AS.set(name, [origValue delimiter value]); end function clear(AS, name) if (nargin < 2) AS.Attribs = struct(); else if (isfield(AS.Attribs, name)) AS.Attribs = rmfield(AS.Attribs, name); end end end function setStringOptions(AS, varargin) AS.StringOptions = parseStringOptions(varargin{:}); end function p = stringOptions(AS, varargin) if (~isempty(varargin)) p = parseStringOptions(varargin{:}); elseif (~isempty(AS.StringOptions)) p = AS.StringOptions; else p = parseStringOptions(); end if (isempty(p)) error('This AttributeStore does not have any stringOptions set yet'); end end function attributeString = asString(AS, varargin) % asString([optionName, optionValue...]) % % itemDelim: delimiter between attributes (default ', ') % before: string preceding each attribute including the first one (default '') % after: string following each attribute including the last one (default '') % attributeNames: attribute names are only included if this is true (default true) % attributeDelim: delimiter between attribute name and value (default '=') p = AS.stringOptions(varargin{:}); attributeString = ''; n = 0; f = fieldnames(AS.Attribs); for i = 1:numel(f) name = f{i}; value = AS.Attribs.(name); valueString = ''; if (isnumeric(value)) valueString = num2str(value); elseif (islogical(value)) valueString = 'false'; if (value) valueString = 'true'; end elseif (ischar(value)) valueString = value; else error('Unknown type for attribute %s', name); end itemDelim = ''; nameString = ''; attributeDelim = ''; if (p.Results.attributeNames) nameString = name; attributeDelim = p.Results.attributeDelim; end if (i > 1), itemDelim = p.Results.itemDelim; end attributeString = [ ... attributeString ... itemDelim ... p.Results.before ... nameString ... attributeDelim ... valueString ... p.Results.after ... ]; end end end end function options = parseStringOptions(varargin) p = inputParser(); p.addParamValue('itemDelim', ', ', @ischar); p.addParamValue('before', '', @ischar); p.addParamValue('after', '', @ischar); % p.addParamValue('wrap', {}, @iscellstr); p.addParamValue('attributeNames', true, @islogical); p.addParamValue('attributeDelim', '=', @ischar); p.parse(varargin{:}); % if (numel(p.Results.wrap) >= 2) % p.Results.before = p.Results.wrap{1}; % p.Results.after = p.Results.wrap{2}; % end options = p; end
github
sensestage/swonder-master
waves.m
.m
swonder-master/twonder_old/waves.m
2,924
utf_8
46497ec3089228a79e83175a1313032d
global rresox=200 global rresoy=200 function mat=calc_circ( center_x, center_y, resox, resoy ) mab=ones( resox, resoy ); for x=1:resox for y=1:resoy mab( x, y ) = sqrt( (x - center_x)^2 + (y - center_y)^2 ); endfor endfor mat=mab; endfunction function bool = fexists( name ) f = fopen( name, "rb" ); if( f != -1 ) fclose( f ); bool = 1; else bool=0; endif endfunction function mat = load_precalc_circle() if( fexists( "circle.bin" ) ) x = load "circle.bin"; mat = x.mat; else mat = calc_circ( 400,400,800,800 ); save -binary "circle.bin" mat; endif endfunction function mat=get_circ( center_x, center_y ) mab=ones( 200, 200 ); for x=1:200 for y=1:200 mab( x, y ) = sqrt( (x - center_x)^2 + (y - center_y)^2 ); endfor endfor mat=mab; endfunction function mat=get_precalc_circ( center_x, center_y, precalc_circ ) mat = precalc_circ( 400-center_x:599-center_x, 400-center_y:599-center_y ); # mat = precalc_circ( 401-center_x:600-center_x, 401-center_y:600-center_y ); # mat = precalc_circ( 399-center_x:598-center_x, 399-center_y:598-center_y ); endfunction function mat=get_wave( center_x, center_y, phi, omega, precalc ) m = get_precalc_circ( center_x, center_y, precalc ); mat = (0.1*m+1).^-1 .* sin( 2*pi*omega*m + phi*omega*2*pi ); endfunction colormap( gray(256) ); #precalculated_circle = calc_circ( 200,200,400,400 ); precalculated_circle = load_precalc_circle(); pic = zeros( 200, 200 ); pic2 = zeros( 200, 200 ); spkmap = zeros( 200, 200 ); spk = zeros( 24*4,2 ); spkn = zeros( 24*4,2 ); weights = ones( 24*4 ); for i=1:24 spk(i,1) = 30; spk(i,2) = 30 + 5 * i; spkn(i,1) = 1; spkn(i,2) = 0; endfor for i=1:24 spk(i+24,1) = 30 + 5 * i; spk(i+24,2) = 30; spkn(i+24,1) = 0; spkn(i+24,2) = 1; endfor ##weights( 1 ) = 0.75; ##weights( 25 ) = 0.75; function res = theint( l, r ) res = ( log( abs( sqrt( l^2 + r^2 ) + l )) * r^2 + l * sqrt( l^2+r^2 ) ) / 2; endfunction omeg = 0.25; for i=1:48 rvec = spk(i,:) - [50, 10]; wrongrlen = sqrt( sumsq( rvec ) ) normproject = dot( rvec, spkn(i,:) ) if( normproject < 0 ) wrongrlen = - wrongrlen endif cosphi = normproject / wrongrlen; rr = dot(rvec, spkn(i,:)); l = dot(rvec, rot90( spkn(i,:) ) ); l0 = l - 2.5; l1 = l + 2.5; rlen = (theint( l1, rr ) - theint( l0,rr )) / 5 if( normproject < 0 ) rlen = - rlen endif #rlen = wrongrlen; #cosphi = dot( rvec, spkn(i,:) ) / rlen; pic = pic + weights(i) /rlen * cosphi * get_wave( spk(i,1), spk(i,2), rlen, omeg, precalculated_circle ); #pic2 = pic2 + weights(i) /wrongrlen * cosphi * get_wave( spk(i,1), spk(i,2), wrongrlen, 0.1, precalculated_circle ); spkmap( spk(i,1), spk(i,2) ) =1.0; endfor #pic2 = get_wave( 50, 10, 0, omeg, precalculated_circle ); #pic2 = pic-pic2; pic = pic .- min(min(pic)); pic = pic ./ max(max(pic)); pic2 = pic2 .- min(min(pic2)); pic2 = pic2 ./ max(max(pic2)); imshow( pic2, pic, spkmap );
github
mstrader/mlib_devel-master
bus_single_port_ram_init.m
.m
mlib_devel-master/casper_library/bus_single_port_ram_init.m
19,918
utf_8
09e8b58ab26d2a4b7d02d66ebfbf8fc3
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bus_single_port_ram_init(blk, varargin) log_group = 'bus_single_port_ram_init_debug'; clog('entering bus_single_port_ram_init', {'trace', log_group}); defaults = { ... 'n_bits', 36, 'bin_pts', 0, ... 'init_vector', zeros(8192,1), ... 'max_fanout', 1, 'mem_type', 'Distributed memory', ... 'bram_optimization', 'Speed', ... %'Speed', 'Area' 'async', 'off', 'misc', 'off', ... 'bram_latency', 1, 'fan_latency', 0, ... 'addr_register', 'on', 'addr_implementation', 'behavioral', ... 'din_register', 'on', 'din_implementation', 'behavioral', ... 'we_register', 'on', 'we_implementation', 'behavioral', ... 'en_register', 'on', 'en_implementation', 'behavioral', ... }; check_mask_type(blk, 'bus_single_port_ram'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); xpos = 50; xinc = 80; ypos = 50; yinc = 20; port_w = 30; port_d = 14; rep_w = 50; rep_d = 30; bus_expand_w = 60; bus_expand_d = 10; bus_create_w = 60; bus_create_d = 10; bram_w = 50; bram_d = 40; del_w = 30; del_d = 20; maxy = 2^13; %Simulink limit n_bits = get_var('n_bits', 'defaults', defaults, varargin{:}); bin_pts = get_var('bin_pts', 'defaults', defaults, varargin{:}); init_vector = get_var('init_vector', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); mem_type = get_var('mem_type', 'defaults', defaults, varargin{:}); bram_optimization = get_var('bram_optimization', 'defaults', defaults, varargin{:}); misc = get_var('misc', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:}); fan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:}); addr_register = get_var('addr_register', 'defaults', defaults, varargin{:}); addr_implementation = get_var('addr_implementation', 'defaults', defaults, varargin{:}); din_register = get_var('din_register', 'defaults', defaults, varargin{:}); din_implementation = get_var('din_implementation', 'defaults', defaults, varargin{:}); we_register = get_var('we_register', 'defaults', defaults, varargin{:}); we_implementation = get_var('we_implementation', 'defaults', defaults, varargin{:}); en_register = get_var('en_register', 'defaults', defaults, varargin{:}); en_implementation = get_var('en_implementation', 'defaults', defaults, varargin{:}); delete_lines(blk); %default state, do nothing if (n_bits(1) == 0), clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_single_port_ram_init', {'trace', log_group}); return; end [riv, civ] = size(init_vector); [rnb, cnb] = size(n_bits); [rbp, cbp] = size(bin_pts); if (cnb ~= 1 && cbp ~= 1) && ((civ ~= cnb) || (civ ~= cbp)), clog('The number of columns in initialisation vector must match the number of values in binary point and number of bits parameter specifications', {'error', log_group}); error('The number of columns in initialisation vector must match the number of values in binary point and number of bits parameter specifications'); end %%%%%%%%%%%%%%% % input ports % %%%%%%%%%%%%%%% %The calculations below anticipate how BRAMs are to be configured by the Xilinx tools %(as detailed in UG190), explicitly generates these, and attempts to control fanout into %these %if optimizing for Area, do the best we can minimising fanout while still using whole BRAMs %fanout for very deep BRAMs will be large %TODO this should depend on FPGA architecture, assuming V5 or V6 if strcmp(bram_optimization, 'Area'), if (riv >= 2^11), max_word_size = 9; elseif (riv >= 2^10), max_word_size = 18; else, max_word_size = 36; end %if optimising for Speed, keep splitting word size even if wasting BRAM resources else, if (riv >= 2^14), max_word_size = 1; elseif (riv >= 2^13), max_word_size = 2; elseif (riv >= 2^12), max_word_size = 4; elseif (riv >= 2^11), max_word_size = 9; elseif (riv >= 2^10), max_word_size = 18; else, max_word_size = 36; end end ctiv = 0; while (ctiv == 0) || ((ctiv * bram_d) > maxy), %if we are going to go beyond Xilinx bounds, double the word width if (ctiv * bram_d) > maxy, clog(['doubling word size from ', num2str(max_word_size), ' to make space'], log_group); if (max_word_size == 1), max_word_size = 2; elseif (max_word_size == 2), max_word_size = 4; elseif (max_word_size == 4), max_word_size = 9; elseif (max_word_size == 9), max_word_size = 18; else, max_word_size = 36; end %if end %if % translate initialisation matrix based on architecture [translated_init_vecs, result] = doubles2unsigned(init_vector, n_bits, bin_pts, max_word_size); if result ~= 0, clog('error translating initialisation matrix', {'error', log_group}); error('error translating initialisation matrix'); end %if [rtiv, ctiv] = size(translated_init_vecs); end %while clog([num2str(ctiv), ' brams required'], log_group); replication = ceil(ctiv/max_fanout); clog(['replication factor of ', num2str(replication), ' required'], log_group); if (cnb == 1), n_bits = repmat(n_bits, 1, civ); bin_pts = repmat(bin_pts, 1, civ); end %if ypos_tmp = ypos; ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'addr', 'built-in/inport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; reuse_block(blk, 'din', 'built-in/inport', ... 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*ctiv/2; ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'we', 'built-in/inport', ... 'Port', '3', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; port_index = 4; % asynchronous A port if strcmp(async, 'on'), ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'en', 'built-in/inport', ... 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; port_index = port_index + 1; end %misc port if strcmp(misc, 'on'), reuse_block(blk, 'misci', 'built-in/inport', ... 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); end xpos = xpos + xinc + port_w/2; %%%%%%%%%%%%%%%%%%%% % replicate inputs % %%%%%%%%%%%%%%%%%%%% xpos = xpos + rep_w/2; ypos_tmp = ypos; %reset ypos % replicate addr if strcmp(addr_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; reuse_block(blk, 'rep_addr', 'casper_library_bus/bus_replicate', ... 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... 'implementation', addr_implementation, ... 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]); add_line(blk, 'addr/1', 'rep_addr/1'); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; % delay din if strcmp(din_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; if strcmp(din_implementation, 'core'), reg_retiming = 'off'; else, reg_retiming = 'on'; end reuse_block(blk, 'ddin', 'xbsIndex_r4/Delay', ... 'latency', num2str(latency), 'reg_retiming', reg_retiming, ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); add_line(blk, ['din/1'], 'ddin/1'); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; % replicate we if strcmp(we_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; reuse_block(blk, 'rep_we', 'casper_library_bus/bus_replicate', ... 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... 'implementation', we_implementation, ... 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]); add_line(blk, 'we/1', 'rep_we/1'); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; if strcmp(async, 'on'), if strcmp(en_register, 'on'), latency = fan_latency; else, latency = 0; end % replicate en ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; reuse_block(blk, 'rep_en', 'casper_library_bus/bus_replicate', ... 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... 'implementation', en_implementation, ... 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]); add_line(blk, 'en/1', 'rep_en/1'); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; end xpos = xpos + xinc + rep_w/2; %%%%%%%%%%%%%%%% % debus inputs % %%%%%%%%%%%%%%%% xpos = xpos + bus_expand_w/2; % debus addra ypos_tmp = ypos + bus_expand_d*ctiv/2; reuse_block(blk, 'debus_addr', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ... 'outputWidth', mat2str(repmat(ceil(log2(rtiv)), 1, replication)), ... 'outputBinaryPt', mat2str(zeros(1, replication)), ... 'outputArithmeticType', mat2str(zeros(1,replication)), 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'rep_addr/1', 'debus_addr/1'); % debus din ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; total_bits = sum(n_bits); extra = mod(total_bits, max_word_size); main = repmat(max_word_size, 1, floor(total_bits/max_word_size)); outputWidth = [main]; if (extra ~= 0), outputWidth = [extra, outputWidth]; end reuse_block(blk, 'debus_din', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', ... 'outputWidth', mat2str(outputWidth), 'outputBinaryPt', mat2str(zeros(1, ctiv)), ... 'outputArithmeticType', mat2str(zeros(1,ctiv)), 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'ddin/1', 'debus_din/1'); % debus we ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; reuse_block(blk, 'debus_we', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ... 'outputWidth', mat2str(ones(1, replication)), ... 'outputBinaryPt', mat2str(zeros(1, replication)), ... 'outputArithmeticType', mat2str(repmat(2,1,replication)), 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'rep_we/1', 'debus_we/1'); if strcmp(async, 'on'), % debus ena ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; reuse_block(blk, 'debus_en', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ... 'outputWidth', mat2str(ones(1, replication)), 'outputBinaryPt', mat2str(zeros(1, replication)), ... 'outputArithmeticType', mat2str(repmat(2,1,replication)), ... 'show_format', 'on', 'outputToWorkspace', 'off', 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'rep_en/1', 'debus_en/1'); end if strcmp(misc, 'on'), % delay misc ypos_tmp = ypos_tmp + del_d/2; reuse_block(blk, 'dmisc0', 'xbsIndex_r4/Delay', ... 'latency', num2str(fan_latency), 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); ypos_tmp = ypos_tmp + del_d/2 + yinc; add_line(blk, 'misci/1', 'dmisc0/1'); end xpos = xpos + xinc + bus_expand_w/2; %%%%%%%%%%%%%% % bram layer % %%%%%%%%%%%%%% ypos_tmp = ypos; xpos = xpos + xinc + bram_w/2; for bram_index = 1:ctiv, % bram self % because the string version of the initVector could be too long (Matlab has upper limits on the length of strings), % we save the values in the UserData parameter of the ram block (available on all Simulink blocks it seems) % and then reference that value from the mask % (It seems that when copying Xilinx blocks this parameter is not preserved and the block must be redrawn to % get the values back) initVector = translated_init_vecs(:, bram_index)'; UserData = struct('initVector', double(initVector)); ypos_tmp = ypos_tmp + bram_d/2; bram_name = ['bram', num2str(bram_index-1)]; clog(['adding ', bram_name], log_group); reuse_block(blk, bram_name, 'xbsIndex_r4/Single Port RAM', ... 'UserData', UserData, 'UserDataPersistent', 'on', ... 'depth', num2str(rtiv), 'write_mode', 'Read Before Write', 'en', async, 'optimize', bram_optimization, ... 'distributed_mem', mem_type, 'latency', num2str(bram_latency), ... 'Position', [xpos-bram_w/2 ypos_tmp-bram_d/2 xpos+bram_w/2 ypos_tmp+bram_d/2]); clog(['done adding ', bram_name], 'bus_single_port_ram_init_desperate_debug'); clog(['setting initVector of ', bram_name], 'bus_single_port_ram_init_desperate_debug'); set_param([blk, '/', bram_name], 'initVector', 'getfield(get_param(gcb, ''UserData''), ''initVector'')'); clog(['done setting initVector of ', bram_name], 'bus_single_port_ram_init_desperate_debug'); ypos_tmp = ypos_tmp + yinc + bram_d/2; % bram connections to replication and debus blocks rep_index = mod(bram_index-1, replication) + 1; %replicated index to use add_line(blk, ['debus_addr/', num2str(rep_index)], [bram_name, '/1']); add_line(blk, ['debus_din/', num2str(bram_index)], [bram_name, '/2']); add_line(blk, ['debus_we/', num2str(rep_index)], [bram_name, '/3']); if strcmp(async, 'on'), add_line(blk, ['debus_en/', num2str(rep_index)], [bram_name, '/4']); end %if end %for % delay for enables and misc if strcmp(async, 'on'), ypos_tmp = ypos_tmp + del_d/2; reuse_block(blk, 'den', 'xbsIndex_r4/Delay', ... 'latency', num2str(bram_latency), 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); ypos_tmp = ypos_tmp + yinc + del_d/2; add_line(blk, ['debus_en/',num2str(replication)], 'den/1'); end; if strcmp(misc, 'on'), ypos_tmp = ypos_tmp + del_d/2; reuse_block(blk, 'dmisc1', 'xbsIndex_r4/Delay', ... 'latency', num2str(bram_latency), 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); ypos_tmp = ypos_tmp + yinc + del_d/2; add_line(blk, 'dmisc0/1', 'dmisc1/1'); end %if xpos = xpos + xinc + bram_w/2; %%%%%%%%%%%%%%%%%%%%%%%%%% % recombine bram outputs % %%%%%%%%%%%%%%%%%%%%%%%%%% xpos = xpos + bus_create_w/2; ypos_tmp = ypos; ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; reuse_block(blk, 'din_bussify', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(ctiv), ... 'Position', [xpos-bus_create_w/2 ypos_tmp-bus_create_d*ctiv/2 xpos+bus_create_w/2 ypos_tmp+bus_create_d*ctiv/2]); ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; for index = 1:ctiv, add_line(blk, ['bram',num2str(index-1),'/1'], ['din_bussify', '/', num2str(index)]); end %for xpos = xpos + xinc + bus_create_w/2; %%%%%%%%%%%%%%%% % output ports % %%%%%%%%%%%%%%%% xpos = xpos + port_w/2; ypos_tmp = ypos; ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; reuse_block(blk, 'dout', 'built-in/outport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; add_line(blk, 'din_bussify/1', 'dout/1'); port_index = 2; if strcmp(async, 'on'), ypos_tmp = ypos_tmp + port_d/2; reuse_block(blk, 'dvalid', 'built-in/outport', ... 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + port_d/2; port_index = port_index + 1; add_line(blk, 'den/1', 'dvalid/1'); end if strcmp(misc, 'on'), ypos_tmp = ypos_tmp + port_d/2; reuse_block(blk, 'misco', 'built-in/outport', ... 'Port', num2str(port_index), ... 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + port_d/2; add_line(blk, 'dmisc1/1', 'misco/1'); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_single_port_ram_init', {'trace', log_group}); end %function bus_single_port_ram_init
github
mstrader/mlib_devel-master
rcmult_init.m
.m
mlib_devel-master/casper_library/rcmult_init.m
4,200
utf_8
48239288509e086f6d81eb521a80beec
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % MeerKAT Radio Telescope Project % % www.kat.ac.za % % Copyright (C) 2013 Andrew Martens (meerKAT) % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rcmult_init(blk, varargin) defaults = {}; check_mask_type(blk, 'rcmult'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); latency = get_var('latency','defaults', defaults, varargin{:}); delete_lines(blk); %default state in library if latency == 0, clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); return; end reuse_block(blk, 'd', 'built-in/Inport'); set_param([blk,'/d'], ... 'Port', '1', ... 'Position', '[15 33 45 47]'); reuse_block(blk, 'sin', 'built-in/Inport'); set_param([blk,'/sin'], ... 'Port', '2', ... 'Position', '[75 138 105 152]'); reuse_block(blk, 'cos', 'built-in/Inport'); set_param([blk,'/cos'], ... 'Port', '3', ... 'Position', '[75 58 105 72]'); reuse_block(blk, 'Mult0', 'xbsIndex_r4/Mult'); set_param([blk,'/Mult0'], ... 'n_bits', '8', ... 'bin_pt', '2', ... 'latency', 'latency', ... 'use_rpm', 'off', ... 'placement_style', 'Rectangular shape', ... 'Position', '[160 27 210 78]'); reuse_block(blk, 'Mult1', 'xbsIndex_r4/Mult'); set_param([blk,'/Mult1'], ... 'n_bits', '8', ... 'bin_pt', '2', ... 'latency', 'latency', ... 'use_rpm', 'off', ... 'placement_style', 'Rectangular shape', ... 'Position', '[160 107 210 158]'); reuse_block(blk, 'real', 'built-in/Outport'); set_param([blk,'/real'], ... 'Port', '1', ... 'Position', '[235 48 265 62]'); reuse_block(blk, 'imag', 'built-in/Outport'); set_param([blk,'/imag'], ... 'Port', '2', ... 'Position', '[235 128 265 142]'); add_line(blk,'cos/1','Mult0/2', 'autorouting', 'on'); add_line(blk,'sin/1','Mult1/2', 'autorouting', 'on'); add_line(blk,'d/1','Mult1/1', 'autorouting', 'on'); add_line(blk,'d/1','Mult0/1', 'autorouting', 'on'); add_line(blk,'Mult0/1','real/1', 'autorouting', 'on'); add_line(blk,'Mult1/1','imag/1', 'autorouting', 'on'); clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); end % rcmult_init
github
mstrader/mlib_devel-master
cosin_init.m
.m
mlib_devel-master/casper_library/cosin_init.m
29,664
utf_8
78c309b6249d7f1414582677b0b52625
% Generate cos/sin % % cosin_init(blk, varargin) % % blk = The block to be configured. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Karoo Array Telesope % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %TODO logic for where conditions don't allow optimization function cosin_init(blk,varargin) clog('entering cosin_init',{'trace', 'cosin_init_debug'}); check_mask_type(blk, 'cosin'); % Set default vararg values. % reg_retiming is not an actual parameter of this block, but it is included % in defaults so that same_state will return false for blocks drawn prior to % adding reg_retiming='on' to some of the underlying Delay blocks. defaults = { ... 'output0', 'cos', ... 'output1', '-sin', ... 'indep_theta', 'off', ... 'phase', 0, ... 'fraction', 3, ... 'store', 3, ... 'table_bits', 5, ... 'n_bits', 18, ... 'bin_pt', 17, ... 'bram_latency', 2, ... 'add_latency', 1, ... 'mux_latency', 1, ... 'neg_latency', 1, ... 'conv_latency', 1, ... 'pack', 'off', ... 'bram', 'BRAM', ... %'BRAM' or 'distributed RAM' 'misc', 'off', ... 'reg_retiming', 'on', ... }; if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); output0 = get_var('output0', 'defaults', defaults, varargin{:}); output1 = get_var('output1', 'defaults', defaults, varargin{:}); indep_theta = get_var('indep_theta', 'defaults', defaults, varargin{:}); phase = get_var('phase', 'defaults', defaults, varargin{:}); fraction = get_var('fraction', 'defaults', defaults, varargin{:}); store = get_var('store', 'defaults', defaults, varargin{:}); table_bits = get_var('table_bits', 'defaults', defaults, varargin{:}); n_bits = get_var('n_bits', 'defaults', defaults, varargin{:}); bin_pt = get_var('bin_pt', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); add_latency = get_var('add_latency', 'defaults', defaults, varargin{:}); mux_latency = get_var('mux_latency', 'defaults', defaults, varargin{:}); neg_latency = get_var('neg_latency', 'defaults', defaults, varargin{:}); conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:}); pack = get_var('pack', 'defaults', defaults, varargin{:}); bram = get_var('bram', 'defaults', defaults, varargin{:}); misc = get_var('misc', 'defaults', defaults, varargin{:}); delete_lines(blk); %default case for storage in the library if table_bits == 0, clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting cosin_init',{'trace', 'cosin_init_debug'}); return; end %if %%%%%%%%%%%%%%% % input ports % %%%%%%%%%%%%%%% port_n=1; reuse_block(blk, 'theta', 'built-in/Inport', 'Port', int2str(port_n), 'Position', [10 88 40 102]); reuse_block(blk, 'assert', 'xbsIndex_r4/Assert', ... 'assert_type', 'on', ... 'type_source', 'Explicitly', ... 'arith_type', 'Unsigned', ... 'n_bits', num2str(table_bits), 'bin_pt', '0', ... 'Position', [70 85 115 105]); add_line(blk, 'theta/1', 'assert/1'); port_n =port_n +1; if strcmp(indep_theta, 'on'), reuse_block(blk, 'theta2', 'built-in/Inport', 'Port', int2str(port_n), 'Position', [10 188 40 202]); reuse_block(blk, 'assert2', 'xbsIndex_r4/Assert', ... 'assert_type', 'on', ... 'type_source', 'Explicitly', ... 'arith_type', 'Unsigned', ... 'n_bits', num2str(table_bits), 'bin_pt', '0', ... 'Position', [70 185 115 205]); add_line(blk, 'theta2/1', 'assert2/1'); port_n =port_n +1; end if strcmp(misc, 'on'), reuse_block(blk, 'misci', 'built-in/Inport', 'Port', int2str(port_n), 'Position', [10 238 40 252]); else reuse_block(blk, 'misci', 'xbsIndex_r4/Constant', ... 'const', '0', 'n_bits', '1', 'arith_type', 'Unsigned', ... 'bin_pt', '0', 'explicit_period', 'on', 'period', '1', ... 'Position', [10 238 40 252]); port_n =port_n +1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % address manipulation logic % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %make sure not storing more than outputting and not storing too few points if (store < fraction) || (fraction <= 2 && store > 2), clog(['need 1/',num2str(fraction),' cycle but want to store 1/',num2str(store),', forcing 1/',num2str(fraction)],{'warning','cosin_init_debug'}); warning(['need 1/',num2str(fraction),' cycle but want to store 1/',num2str(store),', forcing 1/',num2str(fraction)]); store = fraction; end full_cycle_bits = table_bits + fraction; %need full_cycle_bits to be at least 3 so can cut 2 above and 1 low in add_convert if (full_cycle_bits < 3), if ~(store == fraction && strcmp(pack,'on')), clog('forcing all values storage for small number of points',{'trace', 'cosin_init_debug'}); warning('forcing all value storage for small number of points'); end store = fraction; pack = 'on'; end if (fraction > 2), if ~(store == fraction && strcmp(pack,'on')), clog('forcing full storage for output cycle fraction less than a quarter',{'trace', 'cosin_init_debug'}); warning('forcing full storage for output cycle fraction less than a quarter'); end store = fraction; pack = 'on'; end %force separate, complete storage if we have an initial phase offset if phase ~= 0, if ~(store == fraction && strcmp(pack,'on')), clog('forcing full storage for non zero initial phase',{'trace', 'cosin_init_debug'}); warning('forcing full storage for non zero initial phase'); end store = fraction; pack = 'on'; end %if phase %determine optimal lookup functions if not packed if strcmp(pack, 'on'), lookup0 = output0; lookup1 = output1; %not sharing values so store as specified else, if store == 0 || store == 1, lookup0 = 'cos'; lookup1 = 'cos'; elseif store == 2, lookup0 = 'sin'; lookup1 = 'sin'; %minimise amplitude error for last sample with sin end %if store end %if strcmp(pack) %lookup size depends on fraction of cycle stored lookup_bits = full_cycle_bits - store; address_bits = table_bits; draw_basic_partial_cycle(blk, full_cycle_bits, address_bits, lookup_bits, output0, output1, lookup0, lookup1); add_line(blk,'misci/1','add_convert1/2'); if strcmp(indep_theta, 'on'), add_line(blk,'assert2/1','add_convert1/1'); else, add_line(blk,'assert/1','add_convert1/1'); end %%%%%%%%%%%%% % ROM setup % %%%%%%%%%%%%% %misc delay reuse_block(blk, 'Delay', 'xbsIndex_r4/Delay', ... 'latency', 'bram_latency', ... 'reg_retiming', 'on', ... 'Position', [450 336 480 354]); add_line(blk,'add_convert1/3', 'Delay/1'); %determine memory implementation if strcmp(bram, 'BRAM'), distributed_mem = 'Block RAM'; elseif strcmp(bram, 'distributed RAM'), distributed_mem = 'Distributed memory'; else, %TODO end vec_len = 2^lookup_bits; initVector = [lookup0,'((',num2str(phase),'*(2*pi))+(2*pi)/(2^',num2str(full_cycle_bits),')*(0:(2^',num2str(lookup_bits),')-1))']; %pack two outputs into the same word from ROM if strcmp(pack, 'on'), %lookup ROM reuse_block(blk, 'ROM', 'xbsIndex_r4/ROM', ... 'depth', ['2^(',num2str(lookup_bits),')'], ... 'latency', 'bram_latency', ... 'arith_type', 'Unsigned', ... 'n_bits', 'n_bits*2', ... 'bin_pt', '0', ... 'optimize', 'Speed', ... 'distributed_mem', distributed_mem, ... 'Position', [435 150 490 300]); add_line(blk,'add_convert0/2', 'ROM/1'); reuse_block(blk, 'Terminator4', 'built-in/Terminator', 'Position', [285 220 305 240]); add_line(blk,'add_convert1/2', 'Terminator4/1'); %calculate values to be stored in ROM real_vals = gen_vals(output0, phase, full_cycle_bits, vec_len, n_bits, bin_pt); imag_vals = gen_vals(output1, phase, full_cycle_bits, vec_len, n_bits, bin_pt); vals = doubles2unsigned([real_vals',imag_vals'], n_bits, bin_pt, n_bits*2); set_param([blk,'/ROM'], 'initVector', mat2str(vals')); %extract real and imaginary parts of vector reuse_block(blk, 'c_to_ri', 'casper_library_misc/c_to_ri', ... 'n_bits', 'n_bits', 'bin_pt', 'bin_pt', ... 'Position', [510 204 550 246]); add_line(blk,'ROM/1','c_to_ri/1'); elseif strcmp(pack, 'off'), %lookup table reuse_block(blk, 'lookup', 'xbsIndex_r4/Dual Port RAM', ... 'initVector', initVector, ... 'depth', sprintf('2^(%s)',num2str(lookup_bits)), ... 'latency', 'bram_latency', ... 'distributed_mem', distributed_mem, ... 'Position', [435 137 490 298]); add_line(blk,'add_convert0/2','lookup/1'); add_line(blk,'add_convert1/2','lookup/4'); %constant inputs to lookup table reuse_block(blk, 'Constant', 'xbsIndex_r4/Constant', ... 'const', '0', ... 'n_bits', 'n_bits', ... 'bin_pt', 'bin_pt', ... 'Position', [380 170 400 190]); add_line(blk,'Constant/1','lookup/2'); reuse_block(blk, 'Constant2', 'xbsIndex_r4/Constant', ... 'const', '0', ... 'arith_type', 'Boolean', ... 'n_bits', 'n_bits', ... 'bin_pt', 'bin_pt', ... 'Position', [380 195 400 215]); add_line(blk,'Constant2/1','lookup/3'); %add constants if using BRAM (ports don't exist when using distributed RAM) if strcmp(bram, 'BRAM') reuse_block(blk, 'Constant1', 'xbsIndex_r4/Constant', ... 'const', '0', ... 'n_bits', 'n_bits', ... 'bin_pt', 'bin_pt', ... 'Position', [380 245 400 265]); add_line(blk,'Constant1/1','lookup/5'); reuse_block(blk, 'Constant3', 'xbsIndex_r4/Constant', ... 'const', '0', ... 'arith_type', 'Boolean', ... 'n_bits', 'n_bits', ... 'bin_pt', 'bin_pt', ... 'Position', [380 270 400 290]); add_line(blk,'Constant3/1','lookup/6'); end %if strcmp(bram) else, %TODO end %if strcmp(pack) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % delays for negate outputs from address manipulation block % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% reuse_block(blk, 'Delay8', 'xbsIndex_r4/Delay', ... 'latency', 'bram_latency', ... 'reg_retiming', 'on', ... 'Position', [450 116 480 134]); add_line(blk,'add_convert1/1','Delay8/1'); reuse_block(blk, 'Delay10', 'xbsIndex_r4/Delay', ... 'latency', 'bram_latency', ... 'reg_retiming', 'on', ... 'Position', [450 81 480 99]); add_line(blk,'add_convert0/1','Delay10/1'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % data manipulation before output % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(pack, 'on'), src0 = 'c_to_ri/1'; src1 = 'c_to_ri/2'; else, src0 = 'lookup/1'; src1 = 'lookup/2'; end %data reuse_block(blk, 'Constant5', 'xbsIndex_r4/Constant', ... 'const', '0', ... 'arith_type', 'Unsigned', ... 'n_bits', '1', ... 'bin_pt', '0', ... 'explicit_period', 'on', ... 'Position', [770 122 785 138]); reuse_block(blk, 'invert0', 'built-in/SubSystem'); invert_gen([blk,'/invert0']); set_param([blk,'/invert0'], ... 'Position', [800 80 850 142]); add_line(blk,'Delay10/1','invert0/1'); add_line(blk,'Constant5/1','invert0/3'); add_line(blk, src0, 'invert0/2'); reuse_block(blk, 'invert1', 'built-in/SubSystem'); invert_gen([blk,'/invert1']); set_param([blk,'/invert1'], ... 'Position', [800 160 850 222]); add_line(blk,'Delay8/1','invert1/1'); add_line(blk,src1, 'invert1/2'); reuse_block(blk, 'Terminator1', 'built-in/Terminator', ... 'Position', [880 115 900 135]); add_line(blk,'invert0/2','Terminator1/1'); %misc add_line(blk,'Delay/1','invert1/3'); %%%%%%%%%%%%%%%% % output ports % %%%%%%%%%%%%%%%% if strcmp(output0,output1), reuse_block(blk, strcat(output0,'0'), 'built-in/Outport', ... 'Port', '1', ... 'Position', [875 88 905 102]); reuse_block(blk, strcat(output1,'1'), 'built-in/Outport', ... 'Port', '2', ... 'Position', [875 168 905 182]); add_line(blk,'invert0/1',[strcat(output0,'0'),'/1']); add_line(blk,'invert1/1',[strcat(output1,'1'),'/1']); else, reuse_block(blk, output0, 'built-in/Outport', ... 'Port', '1', ... 'Position', [875 88 905 102]); reuse_block(blk, output1, 'built-in/Outport', ... 'Port', '2', ... 'Position', [875 168 905 182]); add_line(blk,'invert0/1',[output0,'/1']); add_line(blk,'invert1/1',[output1,'/1']); end if strcmp(misc, 'on'), reuse_block(blk, 'misco', 'built-in/Outport', ... 'Port', '3', ... 'Position', [875 198 905 212]); else, reuse_block(blk, 'misco', 'built-in/Terminator', 'Position', [875 198 905 212]); end add_line(blk,'invert1/2','misco/1'); %%%%%%%%%%%%%%%%%%%%% % final cleaning up % %%%%%%%%%%%%%%%%%%%%% clean_blocks(blk); fmtstr = sprintf(''); set_param(blk, 'AttributesFormatString', fmtstr); %ensure that parameters we have forced reflect in mask parameters (ensure this matches varargin %passed by block so that hash in same_state can be compared) args = { ... 'output0', output0, 'output1', output1, 'phase', phase, 'fraction', fraction, ... 'table_bits', table_bits, 'n_bits', n_bits, 'bin_pt', bin_pt, 'bram_latency', bram_latency, ... 'add_latency', add_latency, 'mux_latency', mux_latency, 'neg_latency', neg_latency, ... 'conv_latency', conv_latency, 'store', store, 'pack', pack, 'bram', bram, 'misc', misc}; save_state(blk, 'defaults', defaults, args{:}); clog('exiting cosin_init',{'trace', 'cosin_init_debug'}); end %cosin_init function draw_basic_partial_cycle(blk, full_cycle_bits, address_bits, lookup_bits, output0, output1, lookup_function0, lookup_function1) clog(sprintf('full_cycle_bits = %d, address_bits = %d, lookup_bits = %d', full_cycle_bits, address_bits, lookup_bits), {'draw_basic_partial_cycle_debug', 'cosin_init_debug'}); if full_cycle_bits < 3, clog('parameters not sensible so returning', {'draw_basic_partial_cycle_debug', 'cosin_init_debug'}); return; end reuse_block(blk, 'Constant4', 'xbsIndex_r4/Constant', ... 'const', '0', ... 'arith_type', 'Unsigned', ... 'n_bits', '1', ... 'bin_pt', '0', ... 'explicit_period', 'on', ... 'Position', [150 115 175 135]); clog(['adding ',[blk,'/add_convert0']], {'cosin_init_debug', 'draw_basic_partial_cycle_debug'}); reuse_block(blk, 'add_convert0', 'built-in/SubSystem', 'Position', [195 80 265 140]); add_convert_init([blk,'/add_convert0'], full_cycle_bits, address_bits, lookup_bits, lookup_function0, output0); reuse_block(blk, 'Terminator', 'built-in/Terminator'); set_param([blk,'/Terminator'], 'Position', [285 120 305 140]); add_line(blk,'assert/1','add_convert0/1'); add_line(blk,'Constant4/1','add_convert0/2'); add_line(blk,'add_convert0/3','Terminator/1'); clog(['adding ',[blk,'/add_convert1']], {'cosin_init_debug', 'draw_basic_partial_cycle_debug'}); reuse_block(blk, 'add_convert1', 'built-in/SubSystem', 'Position', [195 200 265 260]); add_convert_init([blk,'/add_convert1'], full_cycle_bits, address_bits, lookup_bits, lookup_function1, output1); end %draw_basic_partial_cycle function add_convert_init(blk, full_cycle_bits, address_bits, lookup_bits, lookup_function, output) clog(sprintf('full_cycle_bits = %d, address_bits = %d, lookup_bits = %d. lookup_function = %s, output = %s', full_cycle_bits, address_bits, lookup_bits, lookup_function, output), {'add_convert_init_debug', 'cosin_init_debug'}); pad_bits = full_cycle_bits - address_bits; %need to pad address bits in to get to full cycle diff_bits = full_cycle_bits - lookup_bits; %what fraction of a cycle are we storing %reference using cos as lookup names = {'cos', '-sin', '-cos', 'sin'}; %find how far lookup function is from our reference base = find(strcmp(lookup_function,names)); %now find how far the required output is from our reference offset = find(strcmp(output,names)); %find how many quadrants to shift address by to get to lookup function direction_offset = mod(offset - base,4); if (diff_bits == 2) && (strcmp(lookup_function, 'cos') || strcmp(lookup_function, '-cos')), negate_offset = mod(direction_offset + 1,4); else negate_offset = direction_offset; end clog(sprintf('direction offset = %d, diff_bits = %d', direction_offset, diff_bits), {'add_convert_init_debug', 'cosin_init_debug'}); reuse_block(blk, 'theta', 'built-in/Inport', 'Port', '1', 'Position', [20 213 50 227]); if pad_bits ~= 0, reuse_block(blk, 'pad', 'xbsIndex_r4/Constant', 'const', '0', ... 'arith_type', 'Unsigned', 'n_bits', num2str(pad_bits), ... 'bin_pt', '0', 'Position', [65 185 85 205]); reuse_block(blk, 'fluff', 'xbsIndex_r4/Concat', ... 'num_inputs', '2', 'Position', [105 180 130 235]); add_line(blk, 'theta/1', 'fluff/2'); add_line(blk, 'pad/1', 'fluff/1'); end reuse_block(blk, 'add', 'built-in/Outport', 'Port', '2', 'Position', [840 203 870 217]); reuse_block(blk, 'new_add', 'xbsIndex_r4/Slice', ... 'nbits', num2str(lookup_bits), ... 'mode', 'Lower Bit Location + Width', ... 'Position', [380 242 410 268]); %%%%%%%%%%%%%%%%%%%%%%% % address translation % %%%%%%%%%%%%%%%%%%%%%%% if ~(direction_offset == 0 && diff_bits == 0), reuse_block(blk, 'quadrant', 'xbsIndex_r4/Slice', 'nbits', '2', 'Position', [150 172 180 198]); if pad_bits == 0, add_line(blk,'theta/1','quadrant/1'); else add_line(blk, 'fluff/1', 'quadrant/1'); end reuse_block(blk, 'direction_offset', 'xbsIndex_r4/Constant', ... 'const', num2str(direction_offset), ... 'arith_type', 'Unsigned', ... 'n_bits', '2', ... 'bin_pt', '0', ... 'Position', [55 150 75 170]); reuse_block(blk, 'AddSub5', 'xbsIndex_r4/AddSub', ... 'latency', '0', ... 'precision', 'User Defined', ... 'n_bits', '2', ... 'bin_pt', '0', ... 'use_behavioral_HDL', 'on', ... 'Position', [240 148 285 197]); add_line(blk,'direction_offset/1','AddSub5/1'); add_line(blk,'quadrant/1','AddSub5/2'); reuse_block(blk, 'lookup', 'xbsIndex_r4/Slice', 'nbits', num2str(full_cycle_bits-2), 'mode', 'Lower Bit Location + Width', ... 'Position', [150 252 180 278]); if pad_bits == 0, add_line(blk,'theta/1','lookup/1'); else add_line(blk, 'fluff/1', 'lookup/1'); end reuse_block(blk, 'Concat', 'xbsIndex_r4/Concat', 'num_inputs', '2', 'Position', [320 233 345 277]); add_line(blk,'lookup/1','Concat/2'); add_line(blk,'AddSub5/1','Concat/1'); add_line(blk,'Concat/1','new_add/1'); else, if diff_bits == 0, add_line(blk,'theta/1','new_add/1'); else add_line(blk, 'fluff/1', 'new_add/1'); end end %if diff_bits == 0 reuse_block(blk, 'Delay14', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'on', 'latency', 'add_latency', 'Position', [540 201 570 219]); add_line(blk,'new_add/1','Delay14/1'); reuse_block(blk, 'Convert2', 'xbsIndex_r4/Convert', ... 'arith_type', 'Unsigned', ... 'n_bits', num2str(lookup_bits), ... 'bin_pt', '0', ... 'overflow', 'Saturate', ... 'latency', 'conv_latency', ... 'pipeline', 'on', ... 'Position', [785 201 810 219]); add_line(blk,'Convert2/1','add/1'); %%%%%%%%%%%%% % backwards % %%%%%%%%%%%%% %only need backwards translation for quarter cycle operation if (diff_bits == 2), reuse_block(blk, 'backwards', 'xbsIndex_r4/Slice', ... 'boolean_output', 'on', ... 'mode', 'Lower Bit Location + Width', ... 'bit0', '0', ... 'Position', [380 166 410 184]); reuse_block(blk, 'Constant4', 'xbsIndex_r4/Constant', ... 'const', num2str(2^lookup_bits), ... 'arith_type', 'Unsigned', ... 'n_bits', num2str(lookup_bits+1), ... 'bin_pt', '0', ... 'Position', [450 220 475 240]); reuse_block(blk, 'AddSub', 'xbsIndex_r4/AddSub', ... 'mode', 'Subtraction', ... 'latency', 'add_latency', ... 'precision', 'User Defined', ... 'n_bits', num2str(lookup_bits+1), ... 'bin_pt', '0', ... 'pipelined', 'on', ... 'Position', [530 217 575 268]); reuse_block(blk, 'Mux', 'xbsIndex_r4/Mux', 'latency', 'mux_latency', 'Position', [675 156 700 264]); reuse_block(blk, 'Delay13', 'xbsIndex_r4/Delay', ... 'latency', 'add_latency', ... 'reg_retiming', 'on', ... 'Position', [540 166 570 184]); add_line(blk,'AddSub5/1','backwards/1'); add_line(blk,'backwards/1','Delay13/1'); add_line(blk,'new_add/1','AddSub/2'); add_line(blk,'Constant4/1','AddSub/1'); add_line(blk,'Delay13/1','Mux/1'); add_line(blk,'Delay14/1','Mux/2'); add_line(blk,'AddSub/1','Mux/3'); add_line(blk,'Mux/1','Convert2/1'); else, %no backwards translation so just delay and put new address through reuse_block(blk, 'Delay13', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'on', 'latency', 'mux_latency', 'Position', [675 201 705 219]); add_line(blk,'Delay14/1','Delay13/1'); add_line(blk,'Delay13/1','Convert2/1'); end %backwards translation %%%%%%%%%%%%%%%%%%%%%% % invert logic chain % %%%%%%%%%%%%%%%%%%%%%% reuse_block(blk, 'negate', 'built-in/Outport', 'Port', '1', 'Position', [835 98 865 112]); %need inversion if not got full cycle if (diff_bits ~= 0), reuse_block(blk, 'invert', 'xbsIndex_r4/Slice', ... 'boolean_output', 'on', ... 'Position', [380 96 410 114]); %if different sized offset if (negate_offset ~= direction_offset), reuse_block(blk, 'negate_offset', 'xbsIndex_r4/Constant', ... 'const', num2str(negate_offset), ... 'arith_type', 'Unsigned', ... 'n_bits', '2', ... 'bin_pt', '0', ... 'Position', [55 80 75 100]); reuse_block(blk, 'AddSub1', 'xbsIndex_r4/AddSub', ... 'latency', '0', ... 'precision', 'User Defined', ... 'n_bits', '2', ... 'bin_pt', '0', ... 'pipelined', 'on', ... 'Position', [240 78 285 127]); add_line(blk,'negate_offset/1','AddSub1/1'); add_line(blk,'quadrant/1','AddSub1/2'); add_line(blk,'AddSub1/1','invert/1'); else, add_line(blk,'AddSub5/1','invert/1'); end reuse_block(blk, 'Delay2', 'xbsIndex_r4/Delay', ... 'latency', 'add_latency+mux_latency+conv_latency', ... 'reg_retiming', 'on', ... 'Position', [675 96 705 114]); add_line(blk,'invert/1','Delay2/1'); add_line(blk,'Delay2/1','negate/1'); else, %otherwise no inversion required clog('no inversion required', {'add_convert_init_debug', 'cosin_init_debug'}); reuse_block(blk, 'invert', 'xbsIndex_r4/Constant', ... 'const', '0', ... 'arith_type', 'Boolean', ... 'explicit_period', 'on', ... 'period', '1', ... 'Position', [675 96 705 114]); add_line(blk, 'invert/1', 'negate/1'); end %%%%%%%%%%%%%% % misc chain % %%%%%%%%%%%%%% reuse_block(blk, 'misci', 'built-in/Inport', ... 'Port', '2', ... 'Position', sprintf('[20 303 50 317]')); reuse_block(blk, 'Delay1', 'xbsIndex_r4/Delay', ... 'latency', 'mux_latency+add_latency+conv_latency', ... 'reg_retiming', 'on', ... 'Position', [540 301 570 319]); add_line(blk,'misci/1','Delay1/1'); reuse_block(blk, 'misco', 'built-in/Outport', ... 'Port', '3', ... 'Position', [835 303 865 317]); add_line(blk,'Delay1/1','misco/1'); end % add_convert_init function[vals] = gen_vals(func, phase, table_bits, subset, n_bits, bin_pt), %calculate init vector if strcmp(func, 'sin'), vals = sin((phase*(2*pi))+[0:subset-1]*pi*2/(2^table_bits)); elseif strcmp(func, 'cos'), vals = cos((phase*(2*pi))+[0:subset-1]*pi*2/(2^table_bits)); elseif strcmp(func, '-sin'), vals = -sin((phase*(2*pi))+[0:subset-1]*pi*2/(2^table_bits)); elseif strcmp(func, '-cos'), vals = -cos((phase*(2*pi))+[0:subset-1]*pi*2/(2^table_bits)); end %if strcmp(func) % vals = fi(vals, true, n_bits, bin_pt); %saturates at max so no overflow % vals = fi(vals, false, n_bits, bin_pt, 'OverflowMode', 'wrap'); %wraps negative component so can get back when positive end %gen_vals function invert_gen(blk) invert_mask(blk); invert_init(blk); end % invert_gen function invert_mask(blk) set_param(blk, ... 'Mask', 'on', ... 'MaskSelfModifiable', 'off', ... 'MaskPromptString', 'bit width|binary point|negate latency|mux latency', ... 'MaskStyleString', 'edit,edit,edit,edit', ... 'MaskCallbackString', '|||', ... 'MaskEnableString', 'on,on,on,on', ... 'MaskVisibilityString', 'on,on,on,on', ... 'MaskToolTipString', 'on,on,on,on', ... 'MaskVariables', 'n_bits=@1;bin_pt=@2;neg_latency=@3;mux_latency=@4;', ... 'MaskValueString', 'n_bits|bin_pt|neg_latency|mux_latency', ... 'BackgroundColor', 'white'); end % invert_mask function invert_init(blk) reuse_block(blk, 'negate', 'built-in/Inport', ... 'Port', '1', ... 'Position', [15 43 45 57]); reuse_block(blk, 'in', 'built-in/Inport', ... 'Port', '2', ... 'Position', [15 83 45 97]); reuse_block(blk, 'misci', 'built-in/Inport', ... 'Port', '3', ... 'Position', [15 193 45 207]); reuse_block(blk, 'Delay21', 'xbsIndex_r4/Delay', ... 'latency', 'neg_latency', ... 'reg_retiming', 'on', ... 'Position', [110 41 140 59]); reuse_block(blk, 'Delay20', 'xbsIndex_r4/Delay', ... 'latency', 'neg_latency', ... 'reg_retiming', 'on', ... 'Position', [110 81 140 99]); reuse_block(blk, 'Negate', 'xbsIndex_r4/Negate', ... 'precision', 'User Defined', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', 'n_bits', ... 'bin_pt', 'bin_pt', ... 'latency', 'neg_latency', ... 'overflow', 'Saturate', ... 'Position', [100 119 155 141]); reuse_block(blk, 'mux', 'xbsIndex_r4/Mux', ... 'latency', 'mux_latency', ... 'Position', [215 26 250 154]); reuse_block(blk, 'Delay1', 'xbsIndex_r4/Delay', ... 'latency', 'mux_latency+neg_latency', ... 'reg_retiming', 'on', ... 'Position', [215 191 245 209]); reuse_block(blk, 'out', 'built-in/Outport', ... 'Port', '1', ... 'Position', [300 83 330 97]); reuse_block(blk, 'misco', 'built-in/Outport', ... 'Port', '2', ... 'Position', [300 193 330 207]); add_line(blk,'misci/1','Delay1/1'); add_line(blk,'negate/1','Delay21/1'); add_line(blk,'in/1','Negate/1'); add_line(blk,'in/1','Delay20/1'); add_line(blk,'Delay21/1','mux/1'); add_line(blk,'Delay20/1','mux/2'); add_line(blk,'Negate/1','mux/3'); add_line(blk,'mux/1','out/1'); add_line(blk,'Delay1/1','misco/1'); end % invert_init
github
mstrader/mlib_devel-master
fir_dbl_tap_async_init.m
.m
mlib_devel-master/casper_library/fir_dbl_tap_async_init.m
9,146
utf_8
6ca1f7ee8663db5bce186dca292e24ce
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % MeerKAT Radio Telescope Project % % www.kat.ac.za % % Copyright (C) 2013 Andrew Martens (meerKAT) % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fir_dbl_tap_async_init(blk) clog('entering fir_dbl_tap_async_init', 'trace'); varargin = make_varargin(blk); defaults = {}; check_mask_type(blk, 'fir_tap_async'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end clog('fir_dbl_tap_async_init post same_state', 'trace'); munge_block(blk, varargin{:}); % factor = get_var('factor','defaults', defaults, varargin{:}); % add_latency = get_var('latency','defaults', defaults, varargin{:}); % mult_latency = get_var('latency','defaults', defaults, varargin{:}); coeff_bit_width = get_var('coeff_bit_width','defaults', defaults, varargin{:}); % coeff_bin_pt = get_var('coeff_bin_pt','defaults', defaults, varargin{:}); async_ops = strcmp('on', get_var('async','defaults', defaults, varargin{:})); double_blk = strcmp('on', get_var('dbl','defaults', defaults, varargin{:})); if ~double_blk, error('This script should only be called on a doubled-up tap block.'); end delete_lines(blk); %default state in library if coeff_bit_width == 0, clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); return; end reuse_block(blk, 'a', 'built-in/Inport'); set_param([blk,'/a'], ... 'Port', '1', ... 'Position', '[25 33 55 47]'); reuse_block(blk, 'b', 'built-in/Inport'); set_param([blk,'/b'], ... 'Port', '2', ... 'Position', '[25 123 55 137]'); reuse_block(blk, 'c', 'built-in/Inport'); set_param([blk,'/c'], ... 'Port', '3', ... 'Position', '[25 213 55 227]'); reuse_block(blk, 'd', 'built-in/Inport'); set_param([blk,'/d'], ... 'Port', '4', ... 'Position', '[25 303 55 317]'); if async_ops, reuse_block(blk, 'dv_in', 'built-in/Inport', 'Port', '5', ... 'Position', '[205 0 235 14]'); end reuse_block(blk, 'Register0', 'xbsIndex_r4/Register'); set_param([blk,'/Register0'], ... 'Position', '[315 16 360 64]'); reuse_block(blk, 'Register1', 'xbsIndex_r4/Register'); set_param([blk,'/Register1'], ... 'Position', '[315 106 360 154]'); reuse_block(blk, 'Register2', 'xbsIndex_r4/Register'); set_param([blk,'/Register2'], ... 'Position', '[315 196 360 244]'); reuse_block(blk, 'Register3', 'xbsIndex_r4/Register'); set_param([blk,'/Register3'], ... 'Position', '[315 286 360 334]'); if async_ops, set_param([blk, '/Register0'], 'en', 'on'); set_param([blk, '/Register1'], 'en', 'on'); set_param([blk, '/Register2'], 'en', 'on'); set_param([blk, '/Register3'], 'en', 'on'); else set_param([blk, '/Register0'], 'en', 'off'); set_param([blk, '/Register1'], 'en', 'off'); set_param([blk, '/Register2'], 'en', 'off'); set_param([blk, '/Register3'], 'en', 'off'); end reuse_block(blk, 'coefficient', 'xbsIndex_r4/Constant'); set_param([blk,'/coefficient'], ... 'const', 'factor', ... 'n_bits', 'coeff_bit_width', ... 'bin_pt', 'coeff_bin_pt', ... 'explicit_period', 'on', ... 'Position', '[165 354 285 386]'); reuse_block(blk, 'AddSub0', 'xbsIndex_r4/AddSub'); set_param([blk,'/AddSub0'], ... 'latency', 'add_latency', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', '18', ... 'bin_pt', '16', ... 'use_behavioral_HDL', 'on', ... 'use_rpm', 'on', ... 'Position', '[180 412 230 463]'); reuse_block(blk, 'Mult0', 'xbsIndex_r4/Mult'); set_param([blk,'/Mult0'], ... 'n_bits', '18', ... 'bin_pt', '17', ... 'latency', 'mult_latency', ... 'use_behavioral_HDL', 'on', ... 'use_rpm', 'off', ... 'placement_style', 'Rectangular shape', ... 'Position', '[315 402 365 453]'); reuse_block(blk, 'AddSub1', 'xbsIndex_r4/AddSub'); set_param([blk,'/AddSub1'], ... 'latency', 'add_latency', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', '18', ... 'bin_pt', '16', ... 'use_behavioral_HDL', 'on', ... 'use_rpm', 'on', ... 'Position', '[180 497 230 548]'); reuse_block(blk, 'Mult1', 'xbsIndex_r4/Mult'); set_param([blk,'/Mult1'], ... 'n_bits', '18', ... 'bin_pt', '17', ... 'latency', 'mult_latency', ... 'use_behavioral_HDL', 'on', ... 'use_rpm', 'off', ... 'placement_style', 'Rectangular shape', ... 'Position', '[315 487 365 538]'); reuse_block(blk, 'a_out', 'built-in/Outport'); set_param([blk,'/a_out'], ... 'Port', '1', ... 'Position', '[390 33 420 47]'); reuse_block(blk, 'b_out', 'built-in/Outport'); set_param([blk,'/b_out'], ... 'Port', '2', ... 'Position', '[390 123 420 137]'); reuse_block(blk, 'c_out', 'built-in/Outport'); set_param([blk,'/c_out'], ... 'Port', '3', ... 'Position', '[390 213 420 227]'); reuse_block(blk, 'd_out', 'built-in/Outport'); set_param([blk,'/d_out'], ... 'Port', '4', ... 'Position', '[390 303 420 317]'); reuse_block(blk, 'real', 'built-in/Outport'); set_param([blk,'/real'], ... 'Port', '5', ... 'Position', '[390 423 420 437]'); reuse_block(blk, 'imag', 'built-in/Outport'); set_param([blk,'/imag'], ... 'Port', '6', ... 'Position', '[390 508 420 522]'); if async_ops, add_line(blk, 'dv_in/1', 'Register0/2', 'autorouting', 'on'); add_line(blk, 'dv_in/1', 'Register1/2', 'autorouting', 'on'); add_line(blk, 'dv_in/1', 'Register2/2', 'autorouting', 'on'); add_line(blk, 'dv_in/1', 'Register3/2', 'autorouting', 'on'); end add_line(blk,'d/1','AddSub1/2', 'autorouting', 'on'); add_line(blk,'d/1','Register3/1', 'autorouting', 'on'); add_line(blk,'c/1','AddSub0/2', 'autorouting', 'on'); add_line(blk,'c/1','Register2/1', 'autorouting', 'on'); add_line(blk,'b/1','AddSub1/1', 'autorouting', 'on'); add_line(blk,'b/1','Register1/1', 'autorouting', 'on'); add_line(blk,'a/1','AddSub0/1', 'autorouting', 'on'); add_line(blk,'a/1','Register0/1', 'autorouting', 'on'); add_line(blk,'Register0/1','a_out/1', 'autorouting', 'on'); add_line(blk,'Register1/1','b_out/1', 'autorouting', 'on'); add_line(blk,'Register2/1','c_out/1', 'autorouting', 'on'); add_line(blk,'coefficient/1','Mult0/1', 'autorouting', 'on'); add_line(blk,'coefficient/1','Mult1/1', 'autorouting', 'on'); add_line(blk,'Register3/1','d_out/1', 'autorouting', 'on'); add_line(blk,'AddSub0/1','Mult0/2', 'autorouting', 'on'); add_line(blk,'Mult0/1','real/1', 'autorouting', 'on'); add_line(blk,'AddSub1/1','Mult1/2', 'autorouting', 'on'); add_line(blk,'Mult1/1','imag/1', 'autorouting', 'on'); % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting fir_dbl_tap_async_init', 'trace'); end % fir_dbl_tap_init
github
mstrader/mlib_devel-master
polynomial_init.m
.m
mlib_devel-master/casper_library/polynomial_init.m
9,746
utf_8
1e1f6739e96ec953e2b202317ce5f63a
% Polynomial. % % polynomial_init(blk, varargin) % % blk = The block to be configured. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % n_polys = number of polynomials to implement % degree = polynomial degree % mult_latency = multiplier latency % bits_out = number of bits in output % bin_pt_out = binary point position of output % conv_latency = latency of convert/cast block % quantization = rounding/quantisation strategy % overflow = overflow strategy %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % MeerKAT Radio Telescope Project % % Copyright (C) 2011 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function polynomial_init(blk,varargin) clog('entering polynomial_init', 'trace'); check_mask_type(blk, 'polynomial'); defaults = {'n_polys', 1, 'degree', 3, 'mult_latency', 2, ... 'bits_out', 18, 'bin_pt_out', 17, 'conv_latency', 2, ... 'quantization', 'Truncate', 'overflow', 'Wrap', ... 'bits_in', 8, 'bin_pt_in', 0}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end clog('polynomial_init: post same_state', 'trace'); munge_block(blk, varargin{:}); delete_lines(blk); n_polys = get_var('n_polys', 'defaults', defaults, varargin{:}); degree = get_var('degree', 'defaults', defaults, varargin{:}); mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:}); bits_out = get_var('bits_out', 'defaults', defaults, varargin{:}); bin_pt_out = get_var('bin_pt_out', 'defaults', defaults, varargin{:}); conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); bits_in = get_var('bits_in', 'defaults', defaults, varargin{:}); bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:}); xinc = 50+25*degree; %adder names become larger with higher degree yinc = 100; % Take care of misc reuse_block(blk, 'misc', 'built-in/inport', 'Port', '1', 'Position', [xinc-10 yinc-8 xinc+10 yinc+8]); reuse_block(blk, 'misc_out', 'built-in/outport', 'Port', '1' , ... 'Position', [((degree+3+1)*xinc)-10 yinc-8 ((degree+3+1)*xinc)+10 yinc+8]); if n_polys > 0, reuse_block(blk, 'misc_delay', 'xbsIndex_r4/Delay', ... 'latency', 'mult_latency*(degree+1)+conv_latency', ... 'Position', [(2*xinc)-15 yinc-10 ((degree+3)*xinc)+15 yinc+10]); add_line(blk, 'misc/1', 'misc_delay/1'); add_line(blk, 'misc_delay/1', 'misc_out/1'); else add_line(blk, 'misc/1', 'misc_out/1'); end %set up x delay and mult chain reuse_block(blk, 'x', 'built-in/inport', 'Port', '2', 'Position', [xinc/2-10 2*yinc-8 xinc/2+10 2*yinc+8]); prev_del_blk = 'x'; if n_polys > 0, %don't bother if number of polynomials less than 1 %x must be signed for MACs to be synthesised reuse_block(blk, 'convx', 'xbsIndex_r4/Convert', ... 'arith_type', 'Signed', ... 'latency', '0', 'quantization', 'Truncate', 'overflow', 'Wrap', ... 'n_bits', 'bits_in+1', 'bin_pt', 'bin_pt_in', ... 'Position', [xinc-15 2*yinc-8 xinc+15 2*yinc+8]); add_line(blk, 'x/1', 'convx/1'); prev_mult_blk = 'convx'; prev_del_blk = 'convx'; for n = 2:degree, %delay block if n < degree, cur_del_blk = ['x_d',num2str(n-2)]; latency = 'mult_latency'; xend = n*xinc+15; reuse_block(blk, cur_del_blk, 'xbsIndex_r4/Delay', 'latency', latency, ... 'Position', [n*xinc-15 2*yinc-10 xend 2*yinc+10]); add_line(blk, [prev_del_blk,'/1'], [cur_del_blk,'/1']); prev_del_blk = cur_del_blk; end %mult block cur_mult_blk = ['x^',num2str(n)]; reuse_block(blk, cur_mult_blk, 'xbsIndex_r4/Mult', 'latency', 'mult_latency', ... 'precision', 'Full', 'use_behavioral_HDL', 'on', ... 'Position', [n*xinc-15 3*yinc-15 n*xinc+15 3*yinc+15]); add_line(blk, [prev_del_blk,'/1'],[cur_mult_blk,'/1']); add_line(blk, [prev_mult_blk,'/1'],[cur_mult_blk,'/2']); prev_mult_blk = cur_mult_blk; end end if n_polys > 0, %last delay block cur_del_blk = ['x_d',num2str(max(0,degree-2))]; latency = [num2str(min(degree+1,3)),'*mult_latency+conv_latency']; xend = (degree+3)*xinc+15; reuse_block(blk, cur_del_blk, 'xbsIndex_r4/Delay', 'latency', latency, ... 'Position', [max(degree,2)*xinc-15 2*yinc-10 xend 2*yinc+10]); add_line(blk, [prev_del_blk,'/1'], [cur_del_blk,'/1']); prev_del_blk = cur_del_blk; end reuse_block(blk, 'x_out', 'built-in/outport', 'Port', '2', ... 'Position', [((degree+3+1)*xinc)-10 2*yinc-8 ((degree+3+1)*xinc)+10 2*yinc+8]); add_line(blk, [prev_del_blk,'/1'], 'x_out/1'); %set up polynomial mult chain for each input yoff=5; poff=3; xoff=1; for poly = 0:n_polys-1, src_mult_blk = 'convx'; base = sprintf('%c',('a'+poly)); %a, b, c etc y_offset = yoff+(poly*(degree+1)); p_offset = poff+(poly*(degree+1)); port_name = [base,'0']; %a/b/c...0 input ports reuse_block(blk, port_name, 'built-in/inport', 'Port', ['',num2str(p_offset),''], ... 'Position', [(xoff*xinc)-10 (y_offset*yinc)-8 (xoff*xinc)+10 (y_offset*yinc)+8]); reuse_block(blk, [port_name,'_del'], 'xbsIndex_r4/Delay', 'latency', 'mult_latency', ... 'Position', [((xoff+1)*xinc)-15 (y_offset*yinc)-10 ((xoff+1)*xinc)+15 (y_offset*yinc)+10]); add_line(blk, [port_name,'/1'], [port_name,'_del/1']); add_name = port_name; %adder names starting with coefficient 0 prev_adder = [port_name,'_del']; %input to first adder is delay for n = 1:degree, mult_name = [base,num2str(n),src_mult_blk]; %adder add_name = [add_name,'+',mult_name]; %recursively build adder names reuse_block(blk, add_name, 'xbsIndex_r4/AddSub', 'latency', 'mult_latency', ... 'use_behavioral_HDL', 'on', 'pipelined', 'on', ... 'Position', [((xoff+n+1)*xinc)-20 (y_offset*yinc)-20 (xoff+n+1)*xinc+20 (y_offset*yinc)+20]); add_line(blk, [prev_adder,'/1'], [add_name,'/1']); prev_adder = add_name; %coefficient input port port_name = [base, num2str(n)]; coeff_port = p_offset+n; reuse_block(blk, port_name, 'built-in/inport', 'Port', ['',num2str(coeff_port),''], ... 'Position', [xoff*xinc-10 ((y_offset+n)*yinc)-8 xoff*xinc+10 ((y_offset+n)*yinc)+8]); if n > 1, del_blk = [port_name,'_del']; %coefficient delay reuse_block(blk, del_blk, 'xbsIndex_r4/Delay', 'latency', ['mult_latency*',num2str(n-1)], ... 'Position', [((xoff+1)*xinc)-15 ((y_offset+n)*yinc)-10 ((xoff+n-1)*xinc)+15 ((y_offset+n)*yinc)+10]); add_line(blk, [port_name,'/1'], [del_blk,'/1']); else del_blk = port_name; end %polynomial multiplier reuse_block(blk, mult_name, 'xbsIndex_r4/Mult', 'latency', 'mult_latency', ... 'precision', 'Full', 'use_behavioral_HDL', 'on', ... 'Position', [(xoff+n)*xinc-15 ((y_offset+n)*yinc)-15 (xoff+n)*xinc+15 ((y_offset+n)*yinc)+15]); add_line(blk, [src_mult_blk,'/1'], [mult_name,'/1']); add_line(blk, [del_blk,'/1'], [mult_name,'/2']); src_mult_blk = ['x^',num2str(n+1)]; add_line(blk, [mult_name,'/1'], [add_name,'/2']); end %convert block conv_name = ['conv_',base,'(x)']; reuse_block(blk, conv_name, 'xbsIndex_r4/Convert', ... 'n_bits', 'bits_out', 'bin_pt', 'bin_pt_out', 'pipeline', 'on', ... 'latency', 'conv_latency', 'quantization', quantization, 'overflow', overflow, ... 'Position', [((degree+3)*xinc)-20 ((yoff+poly*(degree+1))*yinc)-20 ((degree+3)*xinc)+20 ((yoff+poly*(degree+1))*yinc)+20]); add_line(blk, [prev_adder,'/1'], [conv_name,'/1']); %output port reuse_block(blk, [base,'(x)'], 'built-in/outport', 'Port', ['',num2str(3+poly),''], ... 'Position', [((degree+3+1)*xinc)-10 ((yoff+poly*(degree+1))*yinc)-8 ((degree+3+1)*xinc)+10 ((yoff+poly*(degree+1))*yinc)+8]); add_line(blk, [conv_name,'/1'], [base,'(x)/1']); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting polynomial_init', 'trace');
github
mstrader/mlib_devel-master
pfb_add_tree_init.m
.m
mlib_devel-master/casper_library/pfb_add_tree_init.m
7,371
utf_8
1e2bd3a590b6dc5ab6214b61484f1e1d
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2007 Terry Filiba, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function pfb_add_tree_init(blk, varargin) % Initialize and configure the Polyphase Filter Bank final summing tree. % % pfb_add_tree_init(blk, varargin) % % blk = The block to configure. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % TotalTaps = Total number of taps in the PFB % BitWidthIn = Input Bitwidth % BitWidthOut = Output Bitwidth % CoeffBitWidth = Bitwidth of Coefficients. % add_latency = Latency through each adder. % quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round % (unbiased: Even Values)' % Declare any default values for arguments you might like. defaults = {}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'pfb_add_tree'); munge_block(blk, varargin{:}); TotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:}); BitWidthIn = get_var('BitWidthIn', 'defaults', defaults, varargin{:}); BitWidthOut = get_var('BitWidthOut', 'defaults', defaults, varargin{:}); CoeffBitWidth = get_var('CoeffBitWidth', 'defaults', defaults, varargin{:}); add_latency = get_var('add_latency', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); delete_lines(blk); % Add ports reuse_block(blk, 'din', 'built-in/inport', 'Position', [15 123 45 137], 'Port', '1'); reuse_block(blk, 'sync', 'built-in/inport', 'Position', [15 28 45 42], 'Port', '2'); reuse_block(blk, 'dout', 'built-in/outport', 'Position', [600 25*TotalTaps+100 630 25*TotalTaps+115], 'Port', '1'); reuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [600 28 630 42], 'Port', '2'); % Add Static Blocks reuse_block(blk, 'adder_tree1', 'casper_library_misc/adder_tree', ... 'n_inputs', num2str(TotalTaps), 'latency', num2str(add_latency), ... 'Position', [200 114 350 50*TotalTaps+114]); reuse_block(blk, 'adder_tree2', 'casper_library_misc/adder_tree', ... 'n_inputs', num2str(TotalTaps), 'latency', num2str(add_latency), ... 'Position', [200 164+50*TotalTaps 350 164+100*TotalTaps]); reuse_block(blk, 'convert1', 'xbsIndex_r4/Convert', ... 'arith_type', 'Signed (2''s comp)', 'n_bits', num2str(BitWidthOut), ... 'bin_pt', num2str(BitWidthOut-1), 'quantization', quantization, ... 'overflow', 'Saturate', 'latency', num2str(add_latency), 'pipeline', 'on',... 'Position', [500 25*TotalTaps+114 530 25*TotalTaps+128]); reuse_block(blk, 'convert2', 'xbsIndex_r4/Convert', ... 'arith_type', 'Signed (2''s comp)', 'n_bits', num2str(BitWidthOut), ... 'bin_pt', num2str(BitWidthOut-1), 'quantization', quantization, ... 'overflow', 'Saturate', 'latency', num2str(add_latency), ... 'Position', [500 158+25*TotalTaps 530 172+25*TotalTaps]); % Delay to compensate for latency of convert blocks reuse_block(blk, 'delay1', 'xbsIndex_r4/Delay', ... 'latency', num2str(add_latency), ... 'Position', [400 50+25*TotalTaps 430 80+25*TotalTaps]); % Scale Blocks are required before casting to n_(n-1) format % Input to adder tree seemes to be n_(n-2) format % each level in the adder tree requires one more shift % so with just two taps, there is one level in the adder tree % so we would have, eg, 17_14 format, so we need to shift by 2 to get % 17_16 which can be converted to 18_17 without overflow. % There are nextpow2(TotalTaps) levels in the adder tree. scale_factor = 1 + nextpow2(TotalTaps); reuse_block(blk, 'scale1', 'xbsIndex_r4/Scale', ... 'scale_factor', num2str(-scale_factor), ... 'Position', [400 25*TotalTaps+114 430 25*TotalTaps+128]); reuse_block(blk, 'scale2', 'xbsIndex_r4/Scale', ... 'scale_factor', num2str(-scale_factor), ... 'Position', [400 158+25*TotalTaps 430 172+25*TotalTaps]); % Add lines %add_line(blk, 'adder_tree1/2', 'convert1/1'); %add_line(blk, 'adder_tree2/2', 'convert2/1'); add_line(blk, 'adder_tree1/2', 'scale1/1'); add_line(blk, 'scale1/1', 'convert1/1'); add_line(blk, 'adder_tree2/2', 'scale2/1'); add_line(blk, 'scale2/1', 'convert2/1'); reuse_block(blk, 'ri_to_c', 'casper_library_misc/ri_to_c', ... 'Position', [550 114+25*TotalTaps 580 144+25*TotalTaps]); add_line(blk, 'convert1/1', 'ri_to_c/1'); add_line(blk, 'convert2/1', 'ri_to_c/2'); add_line(blk, 'ri_to_c/1', 'dout/1'); add_line(blk, 'sync/1', 'adder_tree1/1'); add_line(blk, 'sync/1', 'adder_tree2/1'); %add_line(blk, 'adder_tree1/1', 'sync_out/1'); add_line(blk, 'adder_tree1/1', 'delay1/1'); add_line(blk, 'delay1/1', 'sync_out/1'); for p=0:TotalTaps-1, for q=1:2, slice_name = ['Slice', num2str(p),'_',num2str(q)]; reuse_block(blk, slice_name, 'xbsIndex_r4/Slice', ... 'mode', 'Upper Bit Location + Width', 'nbits', num2str(CoeffBitWidth + BitWidthIn), ... 'base0', 'MSB of Input', 'base1', 'MSB of Input', ... 'bit1', num2str(-(2*p+q-1)*(CoeffBitWidth + BitWidthIn)), 'Position', [70 50*p+25*q+116 115 50*p+25*q+128]); add_line(blk, 'din/1', [slice_name, '/1']); reint_name = ['Reint',num2str(p),'_',num2str(q)]; reuse_block(blk, reint_name, 'xbsIndex_r4/Reinterpret', ... 'force_arith_type', 'on', 'arith_type', 'Signed (2''s comp)', ... 'force_bin_pt', 'on', 'bin_pt', num2str(CoeffBitWidth + BitWidthIn - 2), ... 'Position', [130 50*p+25*q+116 160 50*p+25*q+128]); add_line(blk, [slice_name, '/1'], [reint_name, '/1']); add_line(blk, [reint_name, '/1'], ['adder_tree',num2str(q),'/',num2str(p+2)]); end end clean_blocks(blk); fmtstr = sprintf('taps=%d, add_latency=%d', TotalTaps, add_latency); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:});
github
mstrader/mlib_devel-master
fft_biplex_init.m
.m
mlib_devel-master/casper_library/fft_biplex_init.m
12,957
utf_8
ce01d00a2963f3ab6f7167d1f5912412
% Initialize and configure an fft_biplex block. % % fft_biplex_init(blk, varargin) % % blk = the block to configure % varargin = {'varname', 'value', ...} pairs % % Valid varnames: % n_inputs = Number of simultaneous inputs % FFTSize = Size of the FFT (2^FFTSize points). % input_bit_width = Bit width of input and output data. % bin_pt_in = Binary point position of input data. % coeff_bit_width = Bit width of coefficients. % add_latency = The latency of adders in the system. % mult_latency = The latency of multipliers in the system. % bram_latency = The latency of BRAM in the system. % conv_latency = The latency of convert operations in the system. % quantization = Quantization strategy. % overflow = Overflow strategy. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://casper.berkeley.edu % % Copyright (C) 2007 Terry Filiba, Aaron Parsons % % % % SKA Africa % % www.kat.ac.za % % Copyright (C) 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fft_biplex_init(blk, varargin) clog('entering fft_biplex_init','trace'); % If we are in a library, do nothing if is_library_block(blk) clog('exiting fft_biplex_init (library block)','trace'); return end % If FFTSize is passed as 0, do nothing if get_var('FFTSize', varargin{:}) == 0 clog('exiting fft_biplex_init (FFTSize==0)','trace'); return end % If n_inputs is passed as 0, do nothing if get_var('n_inputs', varargin{:}) == 0 clog('exiting fft_biplex_init (n_inputs==0)','trace'); return end % Make sure block is not too old for current init script try get_param(blk, 'n_streams'); catch errmsg = sprintf(['Block %s is too old for current init script.\n', ... 'Please run "update_casper_block(%s)".\n'], ... blk, blk); % We are not initializing the block because it is too old. Make sure the % user knows this by using a modal error dialog. Using a modal error % dialog is a drastic step, but the situation really needs user attention. errordlg(errmsg, 'FFT Block Too Old', 'modal'); try ex = MException('casper:blockTooOldError', errmsg); throw(ex); catch ex clog('throwing from fft_biplex_init', 'trace'); % We really want to dump this exception, even if its a duplicate of the % previously dumped exception, so reset dump_exception before dumping. dump_exception([]); dump_and_rethrow(ex); end end % Set default vararg values. defaults = { ... 'n_streams', 1, ... 'n_inputs', 1, ... 'FFTSize', 2, ... 'input_bit_width', 18, ... 'bin_pt_in', 17, ... 'coeff_bit_width', 18, ... 'async', 'off', ... 'add_latency', 1, ... 'mult_latency', 2, ... 'bram_latency', 2, ... 'conv_latency', 1, ... 'quantization', 'Round (unbiased: +/- Inf)', ... 'overflow', 'Saturate', ... 'delays_bit_limit', 8, ... 'coeffs_bit_limit', 8, ... 'coeff_sharing', 'on', ... 'coeff_decimation', 'on', ... 'max_fanout', 4, ... 'mult_spec', 2, ... 'bitgrowth', 'off', ... 'max_bits', 18, ... 'hardcode_shifts', 'off', ... 'shift_schedule', [1 1], ... 'dsp48_adders', 'off', ... }; if same_state(blk, 'defaults', defaults, varargin{:}), return, end clog('fft_biplex_init post same_state', {'trace', 'fft_biplex_init_debug'}); check_mask_type(blk, 'fft_biplex'); munge_block(blk, varargin{:}); % Retrieve values from mask fields. n_streams = get_var('n_streams', 'defaults', defaults, varargin{:}); n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:}); FFTSize = get_var('FFTSize', 'defaults', defaults, varargin{:}); input_bit_width = get_var('input_bit_width', 'defaults', defaults, varargin{:}); bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:}); coeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); add_latency = get_var('add_latency', 'defaults', defaults, varargin{:}); mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); delays_bit_limit = get_var('delays_bit_limit', 'defaults', defaults, varargin{:}); coeffs_bit_limit = get_var('coeffs_bit_limit', 'defaults', defaults, varargin{:}); coeff_sharing = get_var('coeff_sharing', 'defaults', defaults, varargin{:}); coeff_decimation = get_var('coeff_decimation', 'defaults', defaults, varargin{:}); max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:}); mult_spec = get_var('mult_spec', 'defaults', defaults, varargin{:}); bitgrowth = get_var('bitgrowth', 'defaults', defaults, varargin{:}); max_bits = get_var('max_bits', 'defaults', defaults, varargin{:}); hardcode_shifts = get_var('hardcode_shifts', 'defaults', defaults, varargin{:}); shift_schedule = get_var('shift_schedule', 'defaults', defaults, varargin{:}); dsp48_adders = get_var('dsp48_adders', 'defaults', defaults, varargin{:}); % bin_pt_in == -1 is a special case for backwards compatibility if bin_pt_in == -1 bin_pt_in = input_bit_width - 1; set_mask_params(blk, 'bin_pt_in', num2str(bin_pt_in)); end ytick = 60; delete_lines(blk); % check the per-stage multiplier specification [temp, mult_spec] = multiplier_specification(mult_spec, FFTSize, blk); clear temp; % % prepare bus creators % reuse_block(blk, 'even_bussify', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(n_inputs*n_streams), 'Position', [150 74 210 116+(((n_streams*n_inputs)-1)*ytick)]); reuse_block(blk, 'odd_bussify', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(n_inputs*n_streams), 'Position', [150 74+((n_streams*n_inputs)*ytick) 210 116+((((n_streams*n_inputs)*2)-1)*ytick)]); % % prepare bus splitters % if strcmp(bitgrowth,'on'), n_bits_out = min(input_bit_width+FFTSize, max_bits); else n_bits_out = input_bit_width; end for index = 0:1, reuse_block(blk, ['pol',num2str(index),'_debus'], 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(n_inputs*n_streams), ... 'outputWidth', num2str(n_bits_out*2), 'outputBinaryPt', '0', 'outputArithmeticType', '0', ... 'Position', [490 49+((n_streams*n_inputs)*index)*ytick 580 81+(((n_streams*n_inputs)*(index+1))-1)*ytick]); end %for %input ports reuse_block(blk, 'sync', 'built-in/inport', 'Position', [15 13 45 27], 'Port', '1'); reuse_block(blk, 'shift', 'built-in/inport', 'Position', [15 43 45 57], 'Port', '2'); reuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [635 25 665 39], 'Port', '1'); reuse_block(blk, 'of', 'built-in/outport', 'Position', [400 150 430 164], 'Port', num2str(1+((n_streams*n_inputs)*2)+1)); if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/inport', ... 'Position', [180 73+(((n_streams*n_inputs*2)+1)*ytick) 210 87+(((n_streams*n_inputs*2)+1)*ytick)], 'Port', num2str(2+(n_streams*n_inputs*2)+1)); reuse_block(blk, 'dvalid', 'built-in/outport', ... 'Position', [490 73+(((n_streams*n_inputs*2)+1)*ytick) 520 87+(((n_streams*n_inputs*2)+1)*ytick)], 'Port', num2str(1+(n_streams*n_inputs*2)+1+1)); end %data inputs, outputs, connections to bus creation and expansion blocks mult = 2; for s = 0:n_streams-1, base = s*(n_inputs*mult); for n = 0:(n_inputs*mult)-1, in = ['pol',num2str(s),num2str(n),'_in']; reuse_block(blk, in, 'built-in/inport', ... 'Position', [15 73+((base+n)*ytick) 45 87+((base+n)*ytick)], ... 'Port', num2str(3+base+n)); out = ['pol',num2str(s),num2str(n),'_out']; reuse_block(blk, out, 'built-in/outport', ... 'Position', [635 53+((base+n)*ytick) 665 67+((base+n)*ytick)], ... 'Port', num2str(2+base+n)); %connect inputs to bus creators if mod(n,mult) == 0, bussify_target = 'even'; else bussify_target = 'odd'; end add_line(blk, [in,'/1'], [bussify_target, '_bussify/', num2str(floor((base+n)/mult)+1)]); %connect debus outputs to output add_line(blk, ['pol', num2str(mod((base+n),mult)), '_debus/', num2str(floor((base+n)/mult)+1)], [out,'/1']); end %for n end %for s reuse_block(blk, 'biplex_core', 'casper_library_ffts/biplex_core', ... 'n_inputs', num2str(n_streams*n_inputs), ... 'FFTSize', num2str(FFTSize), ... 'input_bit_width', num2str(input_bit_width), ... 'bin_pt_in', num2str(bin_pt_in), ... 'coeff_bit_width', num2str(coeff_bit_width), ... 'async', async, ... 'add_latency', num2str(add_latency), ... 'mult_latency', num2str(mult_latency), ... 'bram_latency', num2str(bram_latency), ... 'conv_latency', num2str(conv_latency), ... 'quantization', quantization, ... 'overflow', overflow, ... 'delays_bit_limit', num2str(delays_bit_limit), ... 'coeffs_bit_limit', num2str(coeffs_bit_limit), ... 'coeff_sharing', coeff_sharing, ... 'coeff_decimation', coeff_decimation, ... 'max_fanout', num2str(max_fanout), ... 'mult_spec', mat2str(mult_spec), ... 'bitgrowth', bitgrowth, ... 'max_bits', num2str(max_bits), ... 'hardcode_shifts', hardcode_shifts, ... 'shift_schedule', mat2str(shift_schedule), ... 'dsp48_adders', dsp48_adders, ... 'Position', [250 30 335 125]); add_line(blk, 'sync/1', 'biplex_core/1'); add_line(blk, 'shift/1', 'biplex_core/2'); add_line(blk, 'even_bussify/1', 'biplex_core/3'); add_line(blk, 'odd_bussify/1', 'biplex_core/4'); reuse_block(blk, 'biplex_cplx_unscrambler', 'casper_library_ffts_internal/biplex_cplx_unscrambler', ... 'FFTSize', num2str(FFTSize), ... 'bram_latency', num2str(bram_latency), ... 'coeffs_bit_limit', num2str(coeffs_bit_limit), ... 'async', async, ... 'Position', [380 30 455 120]) add_line(blk, ['biplex_core/1'], ['biplex_cplx_unscrambler/3']); add_line(blk, ['biplex_core/2'], ['biplex_cplx_unscrambler/1']); add_line(blk, ['biplex_core/3'], ['biplex_cplx_unscrambler/2']); add_line(blk, 'biplex_core/4', 'of/1'); %output ports if strcmp(async, 'on'), add_line(blk, 'en/1', 'biplex_core/5'); add_line(blk, 'biplex_core/5', 'biplex_cplx_unscrambler/4'); add_line(blk, 'biplex_cplx_unscrambler/4', 'dvalid/1'); end add_line(blk, 'biplex_cplx_unscrambler/3', 'sync_out/1'); add_line(blk, 'biplex_cplx_unscrambler/1', 'pol0_debus/1'); add_line(blk, 'biplex_cplx_unscrambler/2', 'pol1_debus/1'); clean_blocks(blk); fmtstr = sprintf('%d stages',FFTSize); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting fft_biplex_init', {'trace', 'fft_biplex_init_debug'});
github
mstrader/mlib_devel-master
update_casper_library_links.m
.m
mlib_devel-master/casper_library/update_casper_library_links.m
5,038
utf_8
27eb7a850735a99442bca74c2fc283e2
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://casper.berkeley.edu/ % % Copyright (C) 2013 David MacMahon % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function update_casper_library_links(varargin) % Regexp for blacklisted blocks (e.g. script generated or xBlock based % blocks) persistent blacklist_re; if ~iscell(blacklist_re) blacklist_re = { ... '^casper_library_bus$', ... '^casper_library_multipliers/complex_conj/' ... }; end if nargin == 0 % No arguments given, use all open or loaded CASPER library block diagrams sys = find_system( ... 'RegExp', 'on', ... 'Type', 'block_diagram', ... 'Name', '(casper|xps)_library'); elseif nargin == 1 % Handle single cell array arguments sys = varargin{1}; else sys = varargin; end if ~iscell(sys) sys = {sys}; end linked_blks = {}; for k=1:length(sys) % Ignore this block if it has been blacklisted if any(cell2mat(regexp(sys{k}, blacklist_re))) continue; end % If this block has been linked if strcmp(get_param(sys{k}, 'Type'), 'block') ... && ~strcmp(get_param(sys{k}, 'StaticLinkStatus'), 'none') % Use ^ and $ anchors to blacklist this specific block % (so we don't see it again) blacklist_re{end+1} = sprintf('^%s$', sys{k}); % If this block is linked, blacklist sub-blocks and ignore this one if ~strcmp(get_param(sys{k}, 'StaticLinkStatus'), 'none') blacklist_re{end+1} = sprintf('^%s/', sys{k}); end continue; end % Make sure sys{k}'s block diagram is loaded bd = regexprep(sys{k}, '/.*', ''); if ~bdIsLoaded(bd) fprintf(2, 'loading library %s\n', bd); load_system(bd); end % Find blocks that have inactive link to a CASPER block inactive_links = find_system(sys{k}, 'FollowLinks', 'off', ... 'LookUnderMasks','all', 'RegExp', 'on', ... 'StaticLinkStatus', 'inactive', ... 'AncenstorBlock','(casper|xps)_library'); % Find blocks that have resolved link to a CASPER block resolved_links = find_system(sys{k}, 'FollowLinks', 'off', ... 'LookUnderMasks','all', 'RegExp', 'on', ... 'StaticLinkStatus', 'resolved', ... 'ReferenceBlock','(casper|xps)_library'); % Concatentate the two lists onto linked_blks linked_blks = [linked_blks; resolved_links; inactive_links]; end % Sort linked_blks and remove duplicates linked_blks = unique(sort(linked_blks)); % For each linked block, find its source block for k=1:length(linked_blks) % Skip if blacklisted if any(cell2mat(regexp(linked_blks{k}, blacklist_re))) continue; else % Make sure we skip this block if we see it again blacklist_re{end+1} = sprintf('^%s$', linked_blks{k}); end link_status = get_param(linked_blks{k}, 'StaticLinkStatus'); if strcmp(link_status, 'inactive'), source = get_param(linked_blks{k}, 'AncestorBlock'); elseif strcmp(link_status, 'resolved'), source = get_param(linked_blks{k}, 'ReferenceBlock'); else % Should "never" happen continue; end % Make sure any links in the source block have been updated update_casper_library_links(source); % Make sure linked block's block diagram is unlocked set_param(bdroot(linked_blks{k}), 'Lock', 'off'); % Update linked block fprintf(1, 'updating %s (linked to %s)\n', linked_blks{k}, source); update_casper_block(linked_blks{k}); end end % function
github
mstrader/mlib_devel-master
compute_order.m
.m
mlib_devel-master/casper_library/compute_order.m
380
utf_8
6fa81a3a2aa0a58dde94ccd697afb31e
% Computes the cyclic order of a permutation function rv = compute_order(map) order = 1; for i=1:length(map), j = -1; cur_order = 1; while j+1 ~= i, if j < 0, j = map(i); else, j = map(j+1); cur_order = cur_order + 1; end end order = lcm(order, cur_order); end rv = order;
github
mstrader/mlib_devel-master
save_state.m
.m
mlib_devel-master/casper_library/save_state.m
2,502
utf_8
a9966a2e72bf3417935963e7a092139d
% Saves blk's new state and parameters. % % save_state(blk,varargin) % % blk = The block to check % varargin = The things to compare. % % The block's UserData 'state' parameter is updated with the contents of the hash of % varargin, and the parameters saved in the 'parameters' struct. % the block's UserDataPersistent parameter is set to 'on'. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function save_state(blk,varargin) %check varargin contains even number of variables if( mod(length(varargin),2) ~= 0 ) disp('save_state.m: Non-even parameter list'); return; end; struct.state = hashcell(varargin); struct.parameters = []; % Construct struct of parameter values for j = 1:length(varargin)/2, struct.parameters = setfield( struct.parameters, varargin{j*2-1}, varargin{j*2} ); end set_param(blk,'UserData',struct); set_param(blk,'UserDataPersistent','on');
github
mstrader/mlib_devel-master
twiddle_general_init.m
.m
mlib_devel-master/casper_library/twiddle_general_init.m
11,555
utf_8
28b657eb3a8f35ee083eb58d841f0efe
% twiddle_general_init(blk, varargin) % % blk = The block to configure % varargin = {'varname', 'value, ...} pairs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Karoo Array Telesope % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function twiddle_general_init(blk, varargin) clog('entering twiddle_general_init','trace'); defaults = { ... 'n_inputs', 1, ... 'FFTSize', 2, ... 'async', 'off', ... 'Coeffs', [0 1], ... 'StepPeriod', 0, ... 'input_bit_width', 18, ... 'bin_pt_in', 17, ... 'coeff_bit_width', 18, ... 'add_latency', 1, ... 'mult_latency', 2, ... 'conv_latency', 1, ... 'bram_latency', 2, ... 'coeffs_bit_limit', 9, ... 'coeff_sharing', 'on', ... 'coeff_decimation', 'on', ... 'coeff_generation', 'on', ... 'cal_bits', 1, ... 'n_bits_rotation', 25, ... 'max_fanout', 4, ... 'use_hdl', 'off', ... 'use_embedded', 'off', ... 'quantization', 'Round (unbiased: +/- Inf)', ... 'overflow', 'Wrap'}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end clog('twiddle_general_init post same_state', 'trace'); check_mask_type(blk, 'twiddle_general'); munge_block(blk, varargin{:}); n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:}); FFTSize = get_var('FFTSize', 'defaults', defaults, varargin{:}); Coeffs = get_var('Coeffs', 'defaults', defaults, varargin{:}); StepPeriod = get_var('StepPeriod', 'defaults', defaults, varargin{:}); input_bit_width = get_var('input_bit_width', 'defaults', defaults, varargin{:}); bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:}); coeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:}); add_latency = get_var('add_latency', 'defaults', defaults, varargin{:}); mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:}); conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); coeffs_bit_limit = get_var('coeffs_bit_limit', 'defaults', defaults, varargin{:}); coeff_sharing = get_var('coeff_sharing', 'defaults', defaults, varargin{:}); coeff_decimation = get_var('coeff_decimation', 'defaults', defaults, varargin{:}); coeff_generation = get_var('coeff_generation', 'defaults', defaults, varargin{:}); cal_bits = get_var('cal_bits', 'defaults', defaults, varargin{:}); n_bits_rotation = get_var('n_bits_rotation', 'defaults', defaults, varargin{:}); max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:}); use_hdl = get_var('use_hdl', 'defaults', defaults, varargin{:}); use_embedded = get_var('use_embedded', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); delete_lines(blk); %default case, leave clean block with nothing for storage in the libraries if n_inputs == 0 || FFTSize == 0, clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting twiddle_general_init', 'trace'); return; end %sync signal path reuse_block(blk, 'sync_in', 'built-in/Inport', 'Port', '3', 'Position', [10 108 40 122]); reuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '3', 'Position', [750 233 780 247]); %a signal path reuse_block(blk, 'ai', 'built-in/Inport', 'Port', '1', 'Position', [10 273 40 287]); reuse_block(blk, 'ao', 'built-in/Outport', 'Port', '1', 'Position', [750 283 780 297]); %b signal path reuse_block(blk, 'bi', 'built-in/Inport', 'Port', '2', 'Position', [10 213 40 227]); if strcmp(async, 'on'), inputNum = 4; else, inputNum = 3; end reuse_block(blk, 'bwo', 'built-in/Outport', 'Port', '2', 'Position', [750 133 780 147]); %data valid for asynchronous operation if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/Inport', 'Port', '4', 'Position', [10 183 40 197]); reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', '4', 'Position', [750 333 780 347]); end reuse_block(blk, 'bus_create', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(inputNum), 'Position', [145 204 200 326]); add_line(blk, 'bi/1', 'bus_create/1'); add_line(blk, 'sync_in/1', 'bus_create/2'); add_line(blk, 'ai/1', 'bus_create/3'); % Coefficient generator reuse_block(blk, 'coeff_gen', 'casper_library_ffts_twiddle_coeff_gen/coeff_gen', ... 'FFTSize', 'FFTSize', 'Coeffs', mat2str(Coeffs), ... 'coeff_bit_width', 'coeff_bit_width', 'StepPeriod', 'StepPeriod', ... 'async', async, 'misc', 'on', ... 'bram_latency', 'bram_latency', 'mult_latency', 'mult_latency', ... 'add_latency', 'add_latency', 'conv_latency', 'conv_latency', ... 'coeffs_bit_limit', 'coeffs_bit_limit', 'coeff_sharing', coeff_sharing, ... 'coeff_decimation', coeff_decimation, 'coeff_generation', coeff_generation, ... 'cal_bits', 'cal_bits', 'n_bits_rotation', 'n_bits_rotation', ... 'quantization', quantization, 'Position', [225 78 285 302]); add_line(blk, 'sync_in/1', 'coeff_gen/1'); if strcmp(async, 'on'), add_line(blk, 'en/1', 'bus_create/4'); add_line(blk, 'en/1', 'coeff_gen/2'); add_line(blk, 'bus_create/1', 'coeff_gen/3'); reuse_block(blk, 'Terminator', 'built-in/Terminator', 'Position', [305 180 325 200]); add_line(blk, 'coeff_gen/2', 'Terminator/1'); outputWidth = '[n_inputs*input_bit_width*2, 2+(n_inputs*input_bit_width*2)]'; %for bus_expand else, add_line(blk, 'bus_create/1', 'coeff_gen/2'); outputWidth = '[n_inputs*input_bit_width*2, 1+(n_inputs*input_bit_width*2)]'; %for bus_expand end %bus expand pre multipliers reuse_block(blk, 'bus_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', 'outputNum', '2', ... 'outputWidth', outputWidth, 'outputBinaryPt', '[0 0]', ... 'outputArithmeticType', '[0 0]', 'Position', [345 164 395 366]); if strcmp(async,'on'), add_line(blk, 'coeff_gen/3', 'bus_expand/1'); else add_line(blk, 'coeff_gen/2', 'bus_expand/1'); end if strcmp(use_hdl,'off') & strcmp(use_embedded,'on') multiplier_implementation = 'embedded multiplier core'; elseif strcmp(use_hdl,'off') & strcmp(use_embedded,'off') multiplier_implementation = 'standard core'; else multiplier_implementation = 'behavioral HDL'; end %multipliers reuse_block(blk, 'bus_mult', 'casper_library_bus/bus_mult', ... 'n_bits_a', 'coeff_bit_width', ... 'bin_pt_a', 'coeff_bit_width-1', 'type_a', '1', 'cmplx_a', 'on', ... 'n_bits_b', mat2str(repmat(input_bit_width, 1, n_inputs)), ... 'bin_pt_b', 'bin_pt_in', 'type_b', '1', 'cmplx_b', 'on', ... 'n_bits_out', 'input_bit_width+coeff_bit_width+1', ... 'bin_pt_out', '(bin_pt_in+coeff_bit_width-1)', 'type_out', '1', ... 'quantization', '0', 'overflow', '0', ... 'multiplier_implementation', multiplier_implementation,... 'mult_latency', 'mult_latency', 'add_latency', 'add_latency', 'conv_latency', '0', ... 'max_fanout', 'max_fanout', 'fan_latency', num2str(ceil(log2(n_inputs))+1), ... 'misc', 'on', ... 'Position', [430 66 485 364]); add_line(blk,'coeff_gen/1','bus_mult/1'); add_line(blk,'bus_expand/2','bus_mult/3'); add_line(blk,'bus_expand/1','bus_mult/2'); %convert if strcmp(quantization, 'Truncate'), quant = '0'; elseif strcmp(quantization, 'Round (unbiased: +/- Inf)'), quant = '1'; elseif strcmp(quantization, 'Round (unbiased: Even Values)'), quant = '2'; else %TODO end if strcmp(overflow, 'Wrap'), of = '0'; elseif strcmp(overflow, 'Saturate'), of = '1'; elseif strcmp(overflow, 'Flag as error'), of = '2'; else %TODO end reuse_block(blk, 'bus_convert', 'casper_library_bus/bus_convert', ... 'n_bits_in', 'repmat(input_bit_width+coeff_bit_width+1, 1, n_inputs)', ... 'bin_pt_in', '(bin_pt_in+coeff_bit_width-1)', 'cmplx', 'on', ... 'n_bits_out', 'input_bit_width+1', 'bin_pt_out', 'bin_pt_in', ... 'quantization', quant, 'overflow', of, ... 'latency', 'conv_latency', 'of', 'off', 'misc', 'on', ... 'Position', [515 64 570 366]); add_line(blk, 'bus_mult/1', 'bus_convert/1'); add_line(blk, 'bus_mult/2', 'bus_convert/2'); add_line(blk, 'bus_convert/1', 'bwo/1'); outputWidth = [1 n_inputs*(input_bit_width*2)]; %cut sync out outputBinaryPt = [0 0]; outputArithmeticType = [2 0]; %cut dvalid out again if strcmp(async, 'on'), outputWidth = [outputWidth, 1]; outputBinaryPt = [outputBinaryPt, 0]; outputArithmeticType = [outputArithmeticType, 2]; end reuse_block(blk, 'bus_expand1', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', ... 'outputNum', num2str(inputNum-1), ... 'outputWidth', mat2str(outputWidth) , ... 'outputBinaryPt', mat2str(outputBinaryPt) , ... 'outputArithmeticType', mat2str(outputArithmeticType), ... 'Position', [600 212 650 363]); add_line(blk,'bus_convert/2','bus_expand1/1'); add_line(blk,'bus_expand1/1','sync_out/1'); add_line(blk,'bus_expand1/2','ao/1'); if strcmp(async, 'on'), add_line(blk,'bus_expand1/3','dvalid/1'); end clean_blocks(blk); fmtstr = sprintf('data=(%d,%d)\ncoeffs=(%d,%d)\n(%s,%s)', ... input_bit_width, bin_pt_in, coeff_bit_width, coeff_bit_width-1, quantization, overflow); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting twiddle_general_init', 'trace');
github
mstrader/mlib_devel-master
same_state.m
.m
mlib_devel-master/casper_library/same_state.m
4,645
utf_8
418e3d4fb1b5e950970b0b1c7a7c592b
% Determines if a block's state matches the arguments. % % blk = The block to check % varargin = A cell array of things to compare. % % The compares the block's UserData parameter with the contents of % varargin. If they match, this function returns true. If they do not % match, this function returns false. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function match = same_state(blk,varargin) % Many mask initialization function call same_state early on to see whether the % block's state has changed since the last time it was initialized. Because % same_state is called so early in the initialization process, it is a good % place to check for illegitmately empty parameter values. Some empty % parameter values are legitimate, but an empty parameter value can also be % indicative of an exception that was silently ignored by the mask when % evaluating parameter strings. same_state now checks for empty parameter % values and thoroughly validates those that come from "evaulated" fields in % the mask. % Loop through all name/value pairs for j = 1:length(varargin)/2 param_value = varargin{2*j}; % If this parameter value is empty if isempty(param_value) param_name = varargin{j*2-1}; clog(sprintf('Checking empty value for parameter ''%s''...', param_name), ... 'same_state_debug'); % If it is an evaluated parameter mask_vars = get_param(blk, 'MaskVariables'); pattern = sprintf('(^|;)%s=@', param_name); if regexp(mask_vars, pattern) clog('...it is an evaluated parameter', 'same_state_debug'); % Get its string value param_str = get_param(blk, param_name); % If its string value is not empty if ~isempty(param_str) clog(sprintf('...trying to evaluate its non-empty string: "%s"', ... param_str), 'same_state_debug');... try eval_val = eval_param(blk, param_name); clog('...its non-empty string eval''d OK', 'same_state_debug'); % Raise exception if we did not also get an empty result if ~isempty(eval_val) link = sprintf('<a href="matlab:hilite_system(''%s'')">%s</a>', ... blk, blk); ex = MException('casper:emptyMaskParamError', ... 'Parameter %s of %s is empty in same_state!', param_name, link); throw(ex); end catch ex % We really want to see this exception, even if its a duplicate of the % previous exception, so reset dump_exception before calling % dump_and_rethrow. dump_exception([]); dump_and_rethrow(ex); end % try/catch end % if non-empty param string end % if evaluated clog(sprintf('Empty value for parameter ''%s'' is OK.', param_name), ... 'same_state_debug'); end % if empty end % name/value pair loop % Determine whether the state has changed try match = getfield( get_param(blk,'UserData'), 'state') == hashcell(varargin); catch match = 0; end
github
mstrader/mlib_devel-master
coeff_gen_init.m
.m
mlib_devel-master/casper_library/coeff_gen_init.m
28,562
utf_8
85557fc93abc4baed77457647b63dcb1
% coeff_gen_init(blk, varargin) % % blk = The block to configure % varargin = {'varname', 'value, ...} pairs % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2009, 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function coeff_gen_init(blk, varargin) clog('entering coeff_gen_init.m',{'trace', 'coeff_gen_init_debug'}); FFTSize = 6; % Set default vararg values. % reg_retiming is not an actual parameter of this block, but it is included % in defaults so that same_state will return false for blocks drawn prior to % adding reg_retiming='on' to some of the underlying Delay blocks. defaults = { ... 'FFTSize', FFTSize, ... 'Coeffs', 4, ...%bit_rev([0:2^(FFTSize-1)-1],FFTSize-1), ... 'coeff_bit_width', 18, ... 'StepPeriod', 0, ... 'async', 'off', ... 'misc', 'off', ... 'bram_latency', 2, ... 'mult_latency', 2, ... 'add_latency', 1, ... 'conv_latency', 2, ... 'coeffs_bit_limit', 8, ... 'coeff_sharing', 'on', ... 'coeff_decimation', 'on', ... 'coeff_generation', 'on', ... 'cal_bits', 1, ... 'n_bits_rotation', 25, ... 'quantization', 'Round (unbiased: Even Values)', ... 'reg_retiming', 'on', ... }; check_mask_type(blk, 'coeff_gen'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end clog('coeff_gen_init post same_state',{'trace', 'coeff_gen_init_debug'}); munge_block(blk, varargin{:}); FFTSize = get_var('FFTSize', 'defaults', defaults, varargin{:}); Coeffs = get_var('Coeffs', 'defaults', defaults, varargin{:}); coeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:}); StepPeriod = get_var('StepPeriod', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); misc = get_var('misc', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:}); add_latency = get_var('add_latency', 'defaults', defaults, varargin{:}); conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:}); coeffs_bit_limit = get_var('coeffs_bit_limit', 'defaults', defaults, varargin{:}); coeff_sharing = get_var('coeff_sharing', 'defaults', defaults, varargin{:}); coeff_decimation = get_var('coeff_decimation', 'defaults', defaults, varargin{:}); coeff_generation = get_var('coeff_generation', 'defaults', defaults, varargin{:}); cal_bits = get_var('cal_bits', 'defaults', defaults, varargin{:}); n_bits_rotation = get_var('n_bits_rotation', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); decimation_limit_bits = 6; %do not allow decimation below this many coefficients delete_lines(blk); %default case for library storage, do nothing if FFTSize == 0, clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting coeff_gen_init',{'coeff_gen_init_debug','trace'}); return; end %%%%%%%%% % ports % %%%%%%%%% reuse_block(blk, 'rst', 'built-in/inport', 'Port', '1', 'Position', [25 48 55 62]); reuse_block(blk, 'ri_to_c', 'casper_library_misc/ri_to_c', 'Position', [395 54 435 96]); reuse_block(blk, 'w', 'built-in/outport', 'Port', '1', 'Position', [490 68 520 82]); add_line(blk, 'ri_to_c/1', 'w/1'); port_offset = 1; if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/inport', 'Port', '2', 'Position', [25 198 55 212]); reuse_block(blk, 'dvalid', 'built-in/outport', 'Port', '2', 'Position', [490 198 520 212]); port_offset = 2; end %if async if strcmp(misc, 'on'), reuse_block(blk, 'misci', 'built-in/inport', 'Port', num2str(port_offset+1), 'Position', [25 248 55 262]); reuse_block(blk, 'misco', 'built-in/outport', 'Port', num2str(port_offset+1), 'Position', [490 248 520 262]); end % Compute the complex, bit-reversed values of the twiddle factors br_indices = bit_rev(Coeffs, FFTSize-1); br_indices = -2*pi*1j*br_indices/2^FFTSize; ActualCoeffs = exp(br_indices); %static coefficients if length(ActualCoeffs) == 1, %terminator reuse_block(blk, 'Terminator', 'built-in/Terminator', 'Position', [75 45 95 65]); add_line(blk, 'rst/1', 'Terminator/1'); %constant blocks real_coeff = round(real(ActualCoeffs(1)) * 2^(coeff_bit_width-2)) / 2^(coeff_bit_width-2); imag_coeff = round(imag(ActualCoeffs(1)) * 2^(coeff_bit_width-2)) / 2^(coeff_bit_width-2); reuse_block(blk, 'real', 'xbsIndex_r4/Constant', ... 'arith_type', 'Signed (2''s comp)', ... 'const', num2str(real_coeff), 'n_bits', num2str(coeff_bit_width), ... 'explicit_period', 'on', 'period', '1', ... 'bin_pt', num2str(coeff_bit_width-1), 'Position', [190 43 335 67]); add_line(blk, 'real/1', 'ri_to_c/1'); reuse_block(blk, 'imaginary', 'xbsIndex_r4/Constant', ... 'arith_type', 'Signed (2''s comp)', ... 'const', num2str(imag_coeff), 'n_bits', num2str(coeff_bit_width), ... 'explicit_period', 'on', 'period', '1', ... 'bin_pt', num2str(coeff_bit_width-1), 'Position', [190 83 335 107]); add_line(blk, 'imaginary/1', 'ri_to_c/2'); if strcmp(misc, 'on'), add_line(blk, 'misci/1', 'misco/1'); end if strcmp(async, 'on'), add_line(blk, 'en/1', 'dvalid/1'); end else, vlen = length(ActualCoeffs); % Get FPGA part from System Generator block fpga = 'xc5v'; try xsg_blk = find_system(bdroot(blk), 'SearchDepth', 2, ... 'MaskType','Xilinx System Generator Block'); fpga = get_param(xsg_blk{1},'part'); catch, clog('Could not find FPGA part name - is there a System Generator block in this model? Defaulting FPGA to Virtex5.', {'coeff_gen_init_debug'}); warning('coeff_gen_init: Could not find FPGA part name - is there a System Generator block in this model? Defaulting FPGA to Virtex5.'); end %try/catch %parameters to decide optimisation parameters switch fpga(1:4) case 'xc6v' port_width = 36; %upper limit bram_capacity = 2^9*36; otherwise % including 'xc5v' port_width = 36; %upper limit bram_capacity = 2^9*36; end %switch %could we pack the whole word to output from one port if (coeff_bit_width * 2) <= port_width, can_pack = 1; else, can_pack = 0; end %work out fraction of BRAM for all coefficients coeffs_volume = length(Coeffs) * 2 * coeff_bit_width; n_brams = coeffs_volume/bram_capacity; clog(['Coeffs = ',mat2str(Coeffs)], 'coeff_gen_init_desperate_debug'); % check to see if we can generate by bit reversing a counter inorder = 1; for i = 2:length(Coeffs)-2, if ~((Coeffs(i+1)-Coeffs(i)) == (Coeffs(i)-Coeffs(i-1))), inorder = 0; break; end end %for %if not in order, check if we can generate by undoing bit reversal if inorder == 0, clog(['bit_rev(Coeffs,FFTSize-1) = ',mat2str(bit_rev(Coeffs,FFTSize-1))], 'coeff_gen_init_desperate_debug'); bit_reversed = 1; for i = 2:length(Coeffs)-2, if ~((bit_rev(Coeffs(i+1), FFTSize-1) - bit_rev(Coeffs(i), FFTSize-1)) == (bit_rev(Coeffs(i), FFTSize-1) - bit_rev(Coeffs(i-1), FFTSize-1))), bit_reversed = 0; break; end end %for else bit_reversed = 0; end %if %determine fraction of cycle phase offset and increment if inorder == 0, phase_offset = bit_rev(Coeffs(1), FFTSize-1); phase_step = bit_rev(Coeffs(2), FFTSize-1) - bit_rev(Coeffs(1), FFTSize-1); else, phase_offset = Coeffs(1); phase_step = Coeffs(2) - Coeffs(1); end phase_offset_fraction = phase_offset/(2^(FFTSize-StepPeriod)); phase_multiple = phase_offset/length(Coeffs); %what fraction of the cycle is required if inorder == 0, top = bit_rev(Coeffs(length(Coeffs)), FFTSize-1); bottom = bit_rev(Coeffs(1), FFTSize-1); else top = Coeffs(length(Coeffs)); bottom = Coeffs(1); end multiple = (2^(FFTSize-StepPeriod))/((top+phase_step)-bottom); multiple_bits = log2(multiple); step_bits = multiple_bits+log2(length(Coeffs)); clog(['Need ',num2str(n_brams),' BRAM/s for all coefficients'], 'coeff_gen_init_debug'); clog(['Can pack into same port : ',num2str(can_pack)], 'coeff_gen_init_debug'); clog(['In order : ',num2str(inorder)],'coeff_gen_init_debug'); clog(['Bit reversed : ',num2str(bit_reversed)],'coeff_gen_init_debug'); clog(['Fraction of cycle to output : 1/2^',num2str(multiple_bits)],'coeff_gen_init_debug'); clog(['Step size : 1/2^',num2str(step_bits)],'coeff_gen_init_debug'); clog(['Phase offset : ',num2str(phase_offset),' = ',num2str(phase_multiple),' * output cycle fraction'],'coeff_gen_init_debug'); % % sanity checks %if small number of points, don't generate even if we want to if strcmp(coeff_generation, 'on') && (bit_reversed == 1) && (log2(vlen) <= ceil(log2(mult_latency+add_latency+conv_latency+1)) + cal_bits), clog(['Forcing lookup of coefficients for small number of values relative to latencies'], {'coeff_gen_init_debug'}); warning(['Forcing lookup of coefficients for small number of values relative to latencies']); coeff_generation = 'off'; end %if in order, then must have phase offset of 0 if inorder == 1 && phase_offset ~= 0, clog(['In order coefficients not starting at 0 not handled'], {'error', 'coeff_gen_init_debug'}); error(['In order coefficients not starting at 0 not handled']); return; end %initial phase must be an exact multiple of the number of coefficients if floor(phase_multiple) ~= phase_multiple, clog(['initial phase offset must be an exact multiple of the number of coefficients'], {'error', 'coeff_gen_init_debug'}); error(['initial phase offset must be an exact multiple of the number of coefficients']); return; end %if we don't have a power of two fraction of a cycle then we have a problem if multiple_bits ~= floor(log2(multiple)), clog(['The FFT size must be a power-of-two-multiple of the number of coefficients '], {'error', 'coeff_gen_init_debug'}); error(['The FFT size must be a power-of-two-multiple of the number of coefficients ']); return; end %coefficients must be in order or bit reversed if (inorder == 0) && (bit_reversed == 0), clog(['we don''t know how to generate coefficients that are not in order nor bit reversed'], {'error','coeff_gen_init_debug'}); error(['we don''t know how to generate coefficients that are not in order nor bit reversed']); return; end %If the coefficients to be generated are in order then we can generate them by %bit reversing the output of a counter and performing a lookup on these values % %If the coefficients are bit reversed then we can generate them by taking the output of a %counter and getting the lookup directly. We can also generate the values as the next %value is just the current value rotated by a particular angle. % %An initial coefficient not being 0 can be compensated for by starting the counter with a %non-zero offset. Similarly for final value % %When generating coefficients by phase rotation with a StepPeriod ~= 2^0, we must use a %counter and control using the en port on the oscillator %if not allowed to generate or coeffs in order (bit reversed when being looked up) then store in lookup and use counter if (inorder == 1) || strcmp(coeff_generation, 'off'), table_bits = log2(length(Coeffs)); % % work out optimal output functions depending on phase offset output_ref = {'cos', '-sin', '-cos', 'sin'}; output_ref_index = floor(phase_offset_fraction/(1/4)); output0 = output_ref{output_ref_index+1}; output1 = output_ref{mod(output_ref_index+1,4)+1}; % % adjust initial phase to use new reference point phase_offset = phase_offset_fraction - output_ref_index*(1/4); %can coefficients be derived from each other and themselves if (phase_offset == 0) && (multiple_bits <= 2), derivable = 1; else, derivable = 0; end %n_brams = coeffs_volume/bram_capacity % % determine whether to derive coefficients from each other or pack both % share coefficients if can be derived from each other and allowed % NOTE: we may decide to pack later as well if using single BRAM and can pack into output ports if (derivable == 1) && strcmp(coeff_sharing, 'on'), pack = 'off'; coeffs_volume = coeffs_volume/2; else, pack = 'on'; end %n_brams = coeffs_volume/bram_capacity % % calculate what fraction of cycle we are going to store % if can be derived and allowed to decimate and above limit where allowed to decimate % NOTE: we may decide to decimate by less later if we can fit a larger portion into a BRAM if (derivable == 1) && strcmp(coeff_decimation, 'on') && (table_bits > decimation_limit_bits), store = 2; %decimate to the max coeffs_volume = coeffs_volume/(2^(store-multiple_bits)); n_brams = coeffs_volume/bram_capacity; else, store = multiple_bits; %do not decimate end % % determine if we need to store coefficients in BRAM if coeffs_volume > 2^coeffs_bit_limit, coeffs_bram = 'on'; else, coeffs_bram = 'off'; end % % relook at fraction stored if using BRAM % store a larger fraction of coefficients if not wasting BRAMs % will reduce error as well as logic (large adder) to make address go backwards if strcmp(coeffs_bram, 'on') && (derivable == 1) && strcmp(coeff_decimation, 'on') && (n_brams < 1), if n_brams <= 1/4, new_store = multiple_bits; %store up to a full cycle elseif n_brams <= 1/2, new_store = max(1,multiple_bits); %store up to half a cycle else new_store = 2; %store a quarter of a cycle end coeffs_volume = coeffs_volume * 2^(store-new_store); n_brams = n_brams * 2^(store-new_store); store = new_store; end % % relook at packing if using BRAM % if we can output both from a single port and occupy less than a BRAM with both % i.e if we store both sets and can output through same port, then reduce address logic if strcmp(pack, 'off') && strcmp(coeffs_bram, 'on') && ((can_pack == 1) && (n_brams <= 1/2)), pack = 'on'; coeffs_volume = coeffs_volume * 2; n_brams = n_brams*2; end if strcmp(coeffs_bram, 'on'), bram = 'BRAM'; else bram = 'distributed RAM'; end if strcmp(misc, 'on') || strcmp(async, 'on'), cosin_misc = 'on'; else, cosin_misc = 'off'; end clog(['adding cosin block to ',blk], 'coeff_gen_init_debug'); clog(['output0 = ',output0], 'coeff_gen_init_debug'); clog(['output1 = ',output1], 'coeff_gen_init_debug'); clog(['initial phase offset ',num2str(phase_offset)], 'coeff_gen_init_debug'); clog(['outputting 2^',num2str(table_bits),' points across 1/2^',num2str(multiple_bits),' of a cycle'], 'coeff_gen_init_debug'); clog(['storing 1/2^',num2str(store),' of a cycle in ',num2str(n_brams),' ',bram,'/s'], 'coeff_gen_init_debug'); if strcmp(pack, 'on') clog(['packing coefficients'], 'coeff_gen_init_debug'); end if strcmp(pack, 'off') clog(['not packing coefficients'], 'coeff_gen_init_debug'); end reuse_block(blk, 'Counter', 'xbsIndex_r4/Counter', ... 'cnt_type', 'Free Running', 'start_count', '0', 'cnt_by_val', '1', ... 'arith_type', 'Unsigned', 'n_bits', num2str(log2(vlen)+StepPeriod), ... 'use_behavioral_HDL', 'on', 'bin_pt', '0', 'rst', 'on', 'en', async, ... 'Position', [75 29 125 81]); add_line(blk, 'rst/1', 'Counter/1'); if strcmp(async, 'on'), add_line(blk, 'en/1', 'Counter/2'); end reuse_block(blk, 'Slice', 'xbsIndex_r4/Slice', ... 'nbits', num2str(log2(vlen)), ... 'mode', 'Upper Bit Location + Width', ... 'bit1', '0', 'base1', 'MSB of Input', ... 'Position', [145 41 190 69]); add_line(blk, 'Counter/1', 'Slice/1'); if (strcmp(async, 'on') && strcmp(misc, 'on')), reuse_block(blk, 'Concat', 'xbsIndex_r4/Concat', 'num_inputs', '2', 'Position', [90 182 115 278]); add_line(blk, 'en/1', 'Concat/1'); add_line(blk, 'misci/1', 'Concat/2'); end if inorder == 1, %bit reverse block reuse_block(blk, 'bit_reverse', 'casper_library_misc/bit_reverse', ... 'n_bits', num2str(log2(vlen)), ... 'Position', [205 44 260 66]); add_line(blk, 'Slice/1', 'bit_reverse/1'); end %cosin block reuse_block(blk, 'cosin', 'casper_library_downconverter/cosin', ... 'output0', output0, 'output1', output1, ... 'phase', num2str(phase_offset), ... 'fraction', num2str(multiple_bits), ... 'table_bits', num2str(table_bits), ... 'n_bits', num2str(coeff_bit_width), 'bin_pt', num2str(coeff_bit_width-1), ... 'bram_latency', num2str(bram_latency), 'add_latency', '1', ... 'mux_latency', '2', 'neg_latency', '1', 'conv_latency', '2', ... 'store', num2str(store), 'pack', pack, 'bram', bram, 'misc', cosin_misc, ... 'Position', [280 23 345 147]); if inorder == 1, add_line(blk, 'bit_reverse/1', 'cosin/1'); else, add_line(blk, 'Slice/1', 'cosin/1'); end add_line(blk, 'cosin/1', 'ri_to_c/1'); add_line(blk, 'cosin/2', 'ri_to_c/2'); if strcmp(async, 'on') && strcmp(misc, 'on'), add_line(blk, 'Concat/1', 'cosin/2'); %separate data valid from misco reuse_block(blk, 'Slice1', 'xbsIndex_r4/Slice', ... 'nbits', '1', ... 'mode', 'Upper Bit Location + Width', ... 'bit1', '0', 'base1', 'MSB of Input', ... 'Position', [395 191 440 219]); add_line(blk, 'cosin/3', 'Slice1/1'); add_line(blk, 'Slice1/1', 'dvalid/1'); reuse_block(blk, 'Slice2', 'xbsIndex_r4/Slice', ... 'mode', 'Two Bit Locations', ... 'bit1', '-1', 'base1', 'MSB of Input', ... 'bit0', '0', 'base0', 'LSB of Input', ... 'Position', [395 241 440 269]); add_line(blk, 'cosin/3', 'Slice2/1'); add_line(blk, 'Slice2/1', 'misco/1'); elseif strcmp(async, 'on') && strcmp(misc, 'off'), add_line(blk, 'en/1', 'cosin/2'); add_line(blk, 'cosin/3', 'dvalid/1'); elseif strcmp(async, 'off') && strcmp(misc, 'on'), add_line(blk, 'misci/1', 'cosin/2'); add_line(blk, 'cosin/3', 'misco/1'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % if coefficient indices are bit_reversed (values in order) and allowed to generate % % then generate using feedback oscillator using multipliers % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% elseif ((bit_reversed == 1) && strcmp(coeff_generation,'on')), %concat enable and misc inputs if (strcmp(async, 'on') && strcmp(misc, 'on')), reuse_block(blk, 'Concat', 'xbsIndex_r4/Concat', 'num_inputs', '2', 'Position', [90 182 115 278]); add_line(blk, 'en/1', 'Concat/1'); add_line(blk, 'misci/1', 'Concat/2'); end %derived from feedback_osc_init pipeline_delay_bits = ceil(log2(mult_latency+add_latency+conv_latency+1)); coeffs_volume = (2^(pipeline_delay_bits+cal_bits)) * coeff_bit_width * 2; if coeffs_volume > 2^coeffs_bit_limit, coeffs_bram = 'on'; else, coeffs_bram = 'off'; end clog(['pipeline required based on latencies = ',num2str(2^pipeline_delay_bits)],'coeff_gen_init_desperate_debug'); clog(['calibration points = ',num2str(2^cal_bits)],'coeff_gen_init_desperate_debug'); clog(['total coeffs volume = ',num2str(coeffs_volume),' bits'],'coeff_gen_init_desperate_debug'); clog(['coeffs limit = ',num2str(2^coeffs_bit_limit),' bits'],'coeff_gen_init_desperate_debug'); if strcmp(coeffs_bram, 'on'), bram = 'Block RAM'; else bram = 'Distributed memory'; end %if we have to use a Block RAM, then increase the number of calibration points to the maximum supported %TODO phase_step_bits = step_bits; phase_steps_bits = log2(length(Coeffs)); clog(['adding feedback oscillator block to ',blk], 'coeff_gen_init_debug'); clog(['initial phase is ',num2str(phase_offset_fraction),' * 2*pi stored in ',bram], 'coeff_gen_init_debug'); clog(['outputting 2^',num2str(phase_steps_bits),' steps of size 1/2^',num2str(phase_step_bits),' of a cycle'], 'coeff_gen_init_debug'); %feedback oscillator reuse_block(blk, 'feedback_osc', 'casper_library_downconverter/feedback_osc', ... 'n_bits', 'coeff_bit_width', ... 'n_bits_rotation', 'n_bits_rotation', ... 'phase_initial', num2str(phase_offset_fraction), ... 'phase_step_bits', num2str(phase_step_bits), ... 'phase_steps_bits', num2str(phase_steps_bits), ... 'ref_values_bits', num2str(cal_bits), ... 'bram_latency', num2str(bram_latency), ... 'mult_latency', num2str(mult_latency), ... 'add_latency', num2str(add_latency), ... 'conv_latency', num2str(conv_latency), ... 'bram', bram, ... 'quantization', quantization, ... 'Position', [280 23 345 147]); %generate counter to slow enable if required if StepPeriod ~= 0, reuse_block(blk, 'counter', 'xbsIndex_r4/Counter', ... 'cnt_type', 'Free Running', 'start_count', '0', 'cnt_by_val', '1', ... 'arith_type', 'Unsigned', 'n_bits', num2str(StepPeriod), ... 'implentation', 'Fabric', 'use_behavioral_HDL', 'off', ... 'bin_pt', '0', 'rst', 'on', 'en', async, 'Position', [80 45 120 85]); add_line(blk, 'rst/1', 'counter/1'); if strcmp(async, 'on'), add_line(blk, 'en/1', 'counter/2'); end reuse_block(blk, 'relational', 'xbsIndex_r4/Relational', ... 'mode', 'a=b', 'latency', '0', 'Position', [225 56 255 134]); add_line(blk, 'relational/1', 'feedback_osc/2'); if strcmp(async, 'on'), reuse_block(blk, 'concat1', 'xbsIndex_r4/Concat', ... 'num_inputs', '2', 'Position', [155 55 185 90]); add_line(blk, 'counter/1', 'concat1/1'); add_line(blk, 'en/1', 'concat1/2'); add_line(blk, 'concat1/1', 'relational/1'); len = 'StepPeriod+1'; else add_line(blk, 'counter/1','relational/1'); len = 'StepPeriod'; end reuse_block(blk, 'constant', 'xbsIndex_r4/Constant', ... 'const', ['(2^(',len,'))-1'], 'arith_type', 'Unsigned', ... 'n_bits', len, 'bin_pt', '0', ... 'Position', [145 102 200 128]); add_line(blk, 'constant/1', 'relational/2'); else, if strcmp(async, 'off'), %if StepPeriod 0 but no enable, then create constant to enable always reuse_block(blk, 'en', 'xbsIndex_r4/Constant', ... 'arith_type', 'Boolean', 'const', '1', 'explicit_period', 'on', 'period', '1', ... 'Position', [205 44 260 66]); end add_line(blk, 'en/1', 'feedback_osc/2'); end %if StepPeriod ~= 0 add_line(blk, 'rst/1', 'feedback_osc/1', 'autorouting', 'on'); reuse_block(blk, 't0', 'built-in/Terminator', 'Position', [370 25 390 45]); add_line(blk, 'feedback_osc/1', 't0/1'); reuse_block(blk, 't1', 'built-in/Terminator', 'Position', [370 100 390 120]); add_line(blk, 'feedback_osc/4', 't1/1'); add_line(blk, 'feedback_osc/2', 'ri_to_c/1'); add_line(blk, 'feedback_osc/3', 'ri_to_c/2'); if strcmp(async, 'on') && strcmp(misc, 'on'), add_line(blk, 'Concat/1', 'feedback_osc/3'); %separate data valid from misco reuse_block(blk, 'Slice1', 'xbsIndex_r4/Slice', ... 'nbits', '1', ... 'mode', 'Upper Bit Location + Width', ... 'bit1', '0', 'base1', 'MSB of Input', ... 'Position', [395 191 440 219]); add_line(blk, 'feedback_osc/5', 'Slice1/1'); add_line(blk, 'Slice1/1', 'dvalid/1'); reuse_block(blk, 'Slice2', 'xbsIndex_r4/Slice', ... 'mode', 'Two Bit Locations', ... 'bit1', '-1', 'base1', 'MSB of Input', ... 'bit0', '0', 'base0', 'LSB of Input', ... 'Position', [395 241 440 269]); add_line(blk, 'feedback_osc/5', 'Slice2/1'); add_line(blk, 'Slice2/1', 'misco/1'); elseif strcmp(async, 'on') && strcmp(misc, 'off'), add_line(blk, 'en/1', 'feedback_osc/3'); add_line(blk, 'feedback_osc/5', 'dvalid/1'); elseif strcmp(async, 'off') && strcmp(misc, 'on'), add_line(blk, 'misci/1', 'feedback_osc/3'); add_line(blk, 'feedback_osc/5', 'misco/1'); else add_line(blk, 'rst/1', 'feedback_osc/3', 'autorouting', 'on'); reuse_block(blk, 't2', 'built-in/Terminator', 'Position', [370 125 390 145]); add_line(blk, 'feedback_osc/5', 't2/1'); end else, error('Bad news, this state should not be reached'); %TODO end %if inorder end %if length(ActualCoeffs) clean_blocks(blk); fmtstr = sprintf('%d @ (%d,%d)', length(ActualCoeffs), coeff_bit_width, coeff_bit_width-1); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting coeff_gen_init',{'trace', 'coeff_gen_init_debug'}); end %coeff_gen_init
github
mstrader/mlib_devel-master
bitsnap_callback.m
.m
mlib_devel-master/casper_library/bitsnap_callback.m
3,198
utf_8
680d04a1deb9d1c412fee10711f367bb
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Meerkat radio telescope project % % www.kat.ac.za % % Copyright (C) Andrew Martens 2011 % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bitsnap_callback() clog('entering bitsnap_callback', 'trace'); blk = gcb; check_mask_type(blk, 'bitsnap'); mask_names = get_param(blk, 'MaskNames'); mask_enables = get_param(blk, 'MaskEnables'); mask_visibilities = get_param(blk, 'MaskVisibilities'); storage = get_param(blk, 'snap_storage'); if strcmp(storage, 'bram'), mask_visibilities{ismember(mask_names, 'snap_dram_dimm')} = 'off'; mask_visibilities{ismember(mask_names, 'snap_dram_clock')} = 'off'; mask_enables{ismember(mask_names, 'snap_data_width')} = 'on'; elseif strcmp(storage, 'dram'), mask_visibilities{ismember(mask_names, 'snap_dram_dimm')} = 'on'; mask_visibilities{ismember(mask_names, 'snap_dram_clock')} = 'on'; set_param(blk, 'snap_data_width', '64'); mask_enables{ismember(mask_names, 'snap_data_width')} = 'off'; end if strcmp(get_param(blk,'snap_value'), 'on'), mask_enables{ismember(mask_names, 'extra_names')} = 'on'; mask_enables{ismember(mask_names, 'extra_widths')} = 'on'; mask_enables{ismember(mask_names, 'extra_bps')} = 'on'; mask_enables{ismember(mask_names, 'extra_types')} = 'on'; else mask_enables{ismember(mask_names, 'extra_names')} = 'off'; mask_enables{ismember(mask_names, 'extra_widths')} = 'off'; mask_enables{ismember(mask_names, 'extra_bps')} = 'off'; mask_enables{ismember(mask_names, 'extra_types')} = 'off'; end set_param(gcb, 'MaskEnables', mask_enables); set_param(gcb, 'MaskVisibilities', mask_visibilities); clog('exiting bitsnap_callback', 'trace');
github
mstrader/mlib_devel-master
fir_col_init.m
.m
mlib_devel-master/casper_library/fir_col_init.m
7,197
utf_8
fb82de9a6c3f4e202a20478cef68e0fc
% fir_col_init(blk, varargin) % % blk = The block to initialize. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % n_inputs = The number of parallel input samples. % coeff = The FIR coefficients, top-to-bottom. % add_latency = The latency of adders. % mult_latency = The latency of multipliers. % coeff_bit_width = The number of bits used for coefficients % coeff_bin_pt = The number of fractional bits in the coefficients % first_stage_hdl = Whether to implement the first stage in adder trees % as behavioral HDL so that adders are absorbed into DSP slices used for % multipliers where this is possible. % adder_imp = adder implementation (Fabric, behavioral HDL, DSP48) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fir_col_init(blk,varargin) clog('entering fir_col_init', 'trace'); % Declare any default values for arguments you might like. defaults = {'n_inputs', 1, 'coeff', 0.1, 'add_latency', 2, 'mult_latency', 3, ... 'coeff_bit_width', 25, 'coeff_bin_pt', 24, ... 'first_stage_hdl', 'off', 'adder_imp', 'Fabric'}; check_mask_type(blk, 'fir_col'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end clog('fir_col_init post same_state', 'trace'); munge_block(blk, varargin{:}); n_inputs = get_var('n_inputs','defaults', defaults, varargin{:}); coeff = get_var('coeff','defaults', defaults, varargin{:}); add_latency = get_var('add_latency','defaults', defaults, varargin{:}); mult_latency = get_var('mult_latency','defaults', defaults, varargin{:}); coeff_bit_width = get_var('coeff_bit_width','defaults', defaults, varargin{:}); coeff_bin_pt = get_var('coeff_bin_pt','defaults', defaults, varargin{:}); first_stage_hdl = get_var('first_stage_hdl','defaults', defaults, varargin{:}); adder_imp = get_var('adder_imp','defaults', defaults, varargin{:}); delete_lines(blk); %default library state if n_inputs == 0, clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting fir_col_init', 'trace'); return; end if length(coeff) ~= n_inputs, clog('number of coefficients must be the same as the number of inputs', {'fir_col_init_debug', 'error'}); error('number of coefficients must be the same as the number of inputs'); end for i=1:n_inputs, reuse_block(blk, ['real',num2str(i)], 'built-in/inport', 'Position', [30 i*80 60 15+80*i]); reuse_block(blk, ['imag',num2str(i)], 'built-in/inport', 'Position', [30 i*80+30 60 45+80*i]); reuse_block(blk, ['fir_tap',num2str(i)], 'casper_library_downconverter/fir_tap', ... 'Position', [180 i*160-70 230 50+160*i], 'latency', num2str(mult_latency), ... 'factor',num2str(coeff(i)), 'coeff_bit_width', num2str(coeff_bit_width), ... 'coeff_bin_pt', num2str(coeff_bin_pt)); reuse_block(blk, ['real_out',num2str(i)], 'built-in/outport', 'Position', [350 i*80 380 15+80*i], 'Port', num2str(2*i-1)); reuse_block(blk, ['imag_out',num2str(i)], 'built-in/outport', 'Position', [350 i*80+30 380 45+80*i], 'Port', num2str(2*i)); end reuse_block(blk, 'real_sum', 'built-in/outport', 'Position', [600 10+20*n_inputs 630 30+20*n_inputs], 'Port', num2str(2*n_inputs+1)); reuse_block(blk, 'imag_sum', 'built-in/outport', 'Position', [600 110+20*n_inputs 630 130+20*n_inputs], 'Port', num2str(2*n_inputs+2)); if n_inputs > 1, reuse_block(blk, 'adder_tree1', 'casper_library_misc/adder_tree', ... 'Position', [500 100 550 100+20*n_inputs], 'n_inputs', num2str(n_inputs),... 'latency', num2str(add_latency), 'first_stage_hdl', first_stage_hdl, 'adder_imp', adder_imp); reuse_block(blk, 'adder_tree2', 'casper_library_misc/adder_tree', ... 'Position', [500 200+20*n_inputs 550 200+20*n_inputs+20*n_inputs], 'n_inputs', num2str(n_inputs),... 'latency', num2str(add_latency), 'first_stage_hdl', first_stage_hdl, 'adder_imp', adder_imp); reuse_block(blk, 'c1', 'xbsIndex_r4/Constant', ... 'explicit_period', 'on', 'Position', [450 100 480 110]); reuse_block(blk, 'c2', 'xbsIndex_r4/Constant', ... 'explicit_period', 'on', 'Position', [450 200+20*n_inputs 480 210+20*n_inputs]); reuse_block(blk, 'term1','built-in/Terminator', 'Position', [600 100 615 115]); add_line(blk, 'adder_tree1/1', 'term1/1'); reuse_block(blk, 'term2','built-in/Terminator', 'Position', [600 200+20*n_inputs 615 215+20*n_inputs]); add_line(blk, 'adder_tree2/1', 'term2/1'); add_line(blk, 'c1/1', 'adder_tree1/1'); add_line(blk, 'c2/1', 'adder_tree2/1'); add_line(blk,'adder_tree1/2','real_sum/1'); add_line(blk,'adder_tree2/2','imag_sum/1'); end for i=1:n_inputs, add_line(blk,['real',num2str(i),'/1'],['fir_tap',num2str(i),'/1']); add_line(blk,['imag',num2str(i),'/1'],['fir_tap',num2str(i),'/2']); add_line(blk,['fir_tap',num2str(i),'/1'],['real_out',num2str(i),'/1']); add_line(blk,['fir_tap',num2str(i),'/2'],['imag_out',num2str(i),'/1']); if n_inputs > 1 add_line(blk,['fir_tap',num2str(i),'/3'],['adder_tree1/',num2str(i+1)]); add_line(blk,['fir_tap',num2str(i),'/4'],['adder_tree2/',num2str(i+1)]); else add_line(blk,['fir_tap',num2str(i),'/3'],['real_sum/1']); add_line(blk,['fir_tap',num2str(i),'/4'],['imag_sum/1']); end end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting fir_col_init', 'trace');
github
mstrader/mlib_devel-master
simple_bram_vacc_init.m
.m
mlib_devel-master/casper_library/simple_bram_vacc_init.m
2,999
utf_8
8f8e87fb49dd1595118ad9a02258af3e
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://casper.berkeley.edu % % Copyright (C)2010 Billy Mallard % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function simple_bram_vacc_init(blk, varargin) % Initialize and configure a simple_bram_vacc block. % % simple_bram_vacc_init(blk, varargin) % % blk = The block to configure. % varargin = {'varname', 'value', ...} pairs. % % Valid varnames for this block are: % vec_len = % arith_type = % n_bits = % bin_pt = % Declare any default values for arguments you might like. defaults = {}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'simple_bram_vacc'); munge_block(blk, varargin{:}); vec_len = get_var('vec_len', 'defaults', defaults, varargin{:}); arith_type = get_var('arith_type', 'defaults', defaults, varargin{:}); n_bits = get_var('n_bits', 'defaults', defaults, varargin{:}); bin_pt = get_var('bin_pt', 'defaults', defaults, varargin{:}); % Validate input fields. if vec_len < 6 errordlg('simple_bram_vacc: Invalid vector length. Must be greater than 5.') end if n_bits < 1 errordlg('simple_bram_vacc: Invalid bit width. Must be greater than 0.') end if bin_pt > n_bits errordlg('simple_bram_vacc: Invalid binary point. Cannot be greater than the bit width.') end % Adjust sub-block parameters. set_param([blk, '/Constant'], 'arith_type', arith_type) set_param([blk, '/Adder'], 'arith_type', arith_type) save_state(blk, 'defaults', defaults, varargin{:});
github
mstrader/mlib_devel-master
cross_multiplier_init.m
.m
mlib_devel-master/casper_library/cross_multiplier_init.m
11,071
utf_8
0bdb1cd084e68bc458335523ffe226de
% cross_multiplier_init(blk, varargin) % % Used in refactor block % % blk = The block to configure % varargin = {'varname', 'value, ...} pairs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Karoo Array Telesope % % http://www.kat.ac.za % % Copyright (C) 2009 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function refactor_storage_init(blk, varargin) defaults = {}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'cross_multiplier'); munge_block(blk, varargin{:}); delete_lines(blk); streams = get_var('streams', 'defaults', defaults, varargin{:}); aggregation = get_var('aggregation', 'defaults', defaults, varargin{:}); bit_width_in = get_var('bit_width_in', 'defaults', defaults, varargin{:}); binary_point_in = get_var('binary_point_in', 'defaults', defaults, varargin{:}); bit_width_out = get_var('bit_width_out', 'defaults', defaults, varargin{:}); binary_point_out = get_var('binary_point_out', 'defaults', defaults, varargin{:}); mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:}); add_latency = get_var('add_latency', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); quantisation = get_var('quantisation', 'defaults', defaults, varargin{:}); conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:}); %delay infrastructure reuse_block(blk, 'sync_in', 'built-in/inport', ... 'Port', '1', 'Position', [30 30 60 45]); reuse_block(blk, 'sync_delay', 'xbsIndex_r4/Delay', ... 'latency', 'mult_latency+add_latency+1+conv_latency', ... 'Position', [410 25 460 50]) add_line(blk, 'sync_in/1', 'sync_delay/1'); reuse_block(blk, 'sync_out', 'built-in/outport', ... 'Port', '1', 'Position', [950 30 980 45]); add_line(blk, 'sync_delay/1', 'sync_out/1'); offset = 0; tick=120; for input = 0:streams-1, %number of multipliers to be used %mults = (2*(input+1)-1)*aggregation mults = (streams - input)*aggregation; reuse_block(blk, ['din',num2str(input)], 'built-in/inport', ... 'Port', [num2str(input+2)], 'Position', [30 100+(offset+mults)*tick 60 115+(offset+mults)*tick]); % set up uncram block for each stream reuse_block(blk, ['unpack',num2str(input)], 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', ... 'outputNum', 'aggregation', ... 'outputWidth', 'bit_width_in*2', ... 'outputBinaryPt', '0', 'outputArithmeticType', '0', ... 'Position', [120 100+(offset+mults)*tick 170 100+(offset+mults+aggregation)*tick]); add_line(blk, ['din',num2str(input),'/1'],['unpack',num2str(input),'/1']); %go through each aggregated stream for substream = 0:aggregation-1, %combine real from imaginary parts sub_name = ['c_to_ri', num2str(input), '_', num2str(substream)]; reuse_block(blk, sub_name, 'casper_library_misc/c_to_ri', ... 'n_bits', 'bit_width_in', 'bin_pt', 'binary_point_in', ... 'Position', [200 100+(offset+mults+substream)*tick 250 150+(offset+mults+substream)*tick]); add_line(blk, ['unpack',num2str(input),'/',num2str(substream+1)], [sub_name,'/1']); end end offset = 0; tick=120; for input = 0:streams-1, mults = (streams - input)*aggregation; %go through multipliers for mult = 0:(mults/aggregation)-1, %pick inputs to multipliers, generating mults based on matrix as follows % | A B C D %------------------ %A* | AA* BA* CA* DA* %B* | AB* BB* CB* DB* %C* | AC* BC* CC* DC* %D* | AD* BD* CD* DD* %x_in = min(mult,input) x_in = input %y_in = min(input,mults/aggregation-mult-1) y_in = input+mult; %to recombine streams pack_name = ['pack', num2str(input), '_', num2str(mult)]; reuse_block(blk, pack_name, 'casper_library_flow_control/bus_create', ... 'inputNum', 'aggregation', ... 'Position', [800 100+(offset+(mult*aggregation))*tick 850 130+(offset+(mult*aggregation))*tick]); for substream = 0:aggregation-1, %set up multiplier mult_name = ['cmult', num2str(input), '_', num2str(mult), '_', num2str(substream)]; reuse_block(blk, mult_name, 'casper_library_multipliers/cmult_4bit_hdl*', ... 'mult_latency', 'mult_latency', 'add_latency', 'add_latency', ... 'Position', [550 100+(offset+(mult*aggregation)+substream)*tick 600 195+(offset+(mult*aggregation)+substream)*tick]); %set up delays to remove fanout from c_to_ri blocks delay_name = ['delay', num2str(input), '_', num2str(mult), '_', num2str(substream), '_0']; reuse_block(blk, delay_name, 'xbsIndex_r4/Delay', ... 'latency', '1', ... 'Position', [450 100+(offset+(mult*aggregation)+substream)*tick 480 100+(offset+(mult*aggregation)+substream)*tick+15]); add_line(blk, ['c_to_ri', num2str(x_in), '_', num2str(substream), '/1'], [delay_name,'/1']); add_line(blk, [delay_name,'/1'], [mult_name,'/1']); delay_name = ['delay', num2str(input), '_', num2str(mult), '_', num2str(substream), '_1']; reuse_block(blk, delay_name, 'xbsIndex_r4/Delay', ... 'latency', '1', ... 'Position', [450 100+(offset+(mult*aggregation)+substream)*tick+30 480 100+(offset+(mult*aggregation)+substream)*tick+45]); add_line(blk, ['c_to_ri', num2str(x_in), '_', num2str(substream), '/2'], [delay_name,'/1']); add_line(blk, [delay_name,'/1'], [mult_name,'/2']); delay_name = ['delay', num2str(input), '_', num2str(mult), '_', num2str(substream), '_2']; reuse_block(blk, delay_name, 'xbsIndex_r4/Delay', ... 'latency', '1', ... 'Position', [450 100+(offset+(mult*aggregation)+substream)*tick+60 480 100+(offset+(mult*aggregation)+substream)*tick+75]); add_line(blk, ['c_to_ri', num2str(y_in), '_', num2str(substream), '/1'], [delay_name,'/1']); add_line(blk, [delay_name,'/1'], [mult_name,'/3']); delay_name = ['delay', num2str(input), '_', num2str(mult), '_', num2str(substream), '_3']; reuse_block(blk, delay_name, 'xbsIndex_r4/Delay', ... 'latency', '1', ... 'Position', [450 100+(offset+(mult*aggregation)+substream)*tick+90 480 100+(offset+(mult*aggregation)+substream)*tick+105]); add_line(blk, ['c_to_ri', num2str(y_in), '_', num2str(substream), '/2'], [delay_name,'/1']); add_line(blk, [delay_name,'/1'], [mult_name,'/4']); %TODO finish overflow detection %convert data to output precision cvrt_name = ['cvrt', num2str(input), '_', num2str(mult), '_', num2str(substream)]; reuse_block(blk, [cvrt_name, '_real'], 'casper_library_misc/convert_of', ... 'bit_width_i', tostring(bit_width_in*2+1), 'binary_point_i', tostring(binary_point_in*2), ... 'bit_width_o', tostring(bit_width_out), 'binary_point_o', tostring(binary_point_out), ... 'overflow', tostring(overflow), 'quantization', tostring(quantisation), 'latency', tostring(conv_latency), ... 'Position', [625 100+(offset+(mult*aggregation)+substream)*tick 675 130+(offset+(mult*aggregation)+substream)*tick]); reuse_block(blk, [cvrt_name, '_imag'], 'casper_library_misc/convert_of', ... 'bit_width_i', tostring(bit_width_in*2+1), 'binary_point_i', tostring(binary_point_in*2), ... 'bit_width_o', tostring(bit_width_out), 'binary_point_o', tostring(binary_point_out), ... 'overflow', tostring(overflow), 'quantization', tostring(quantisation), 'latency', tostring(conv_latency), ... 'Position', [625 150+(offset+(mult*aggregation)+substream)*tick 675 180+(offset+(mult*aggregation)+substream)*tick]); add_line(blk, [mult_name,'/1'], [cvrt_name,'_real/1']); add_line(blk, [mult_name,'/2'], [cvrt_name,'_imag/1']); %join results into complex output ri2c_name = ['ri_to_c', num2str(input), '_', num2str(mult), '_', num2str(substream)]; reuse_block(blk, ri2c_name, 'casper_library_misc/ri_to_c', ... 'Position', [725 100+(offset+(mult*aggregation)+substream)*tick 775 130+(offset+(mult*aggregation)+substream)*tick]); add_line(blk, [cvrt_name,'_real/1'], [ri2c_name,'/1']); add_line(blk, [cvrt_name,'_imag/1'], [ri2c_name,'/2']); add_line(blk, [ri2c_name,'/1'], [pack_name,'/',num2str(substream+1)]); end %create output port out_name = ['din', num2str(x_in), '_x_din', num2str(y_in), '*']; reuse_block(blk, out_name, 'built-in/outport', 'Port', num2str((offset/aggregation)+mult+2), ... 'Position', [950 100+(offset+(mult*aggregation))*tick 980 115+(offset+(mult*aggregation))*tick]) add_line(blk, [pack_name,'/1'], [out_name,'/1']); end offset = offset+mults; end clean_blocks(blk); %fmtstr = sprintf('%d:1 %d bit',input_streams, bit_width); %set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:});
github
mstrader/mlib_devel-master
bus_expand_init.m
.m
mlib_devel-master/casper_library/bus_expand_init.m
10,705
utf_8
bb8856be5d72c2cfa78289755e0824bb
% Create a 'bus' of similar signals % % bus_expand_init(blk, varargin) % % blk = The block to be configured. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % outputNum = Number of outputs to split bus into % outputWidth = Total bit width of each output % outputBinaryPt = Binary point of each output % outputArithmeticType = Numerical type of each output % outputToWorkspace = Optionally output each output to the Workspace % variablePrefix = % outputToModeAsWell = %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Meerkat radio telescope project % % www.kat.ac.za % % Copyright (C) Paul Prozesky 2011 % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Sometimes it's nice to 'combine' a bunch of similar signals into one % 'bus' using the bus_create or Xilinx concat blocks. But to split them up % again is a pain in the butt. So this block just provides an easy way of % doing that. function bus_expand_init(blk, varargin) clog('entering bus_expand_init','trace'); check_mask_type(blk, 'bus_expand'); munge_block(blk, varargin{:}); defaults = {'mode', 'divisions of equal size', 'outputNum', 2, 'outputWidth', 8, ... 'outputBinaryPt', 7, 'outputArithmeticType', 1, ... 'outputToWorkspace', 'off', 'variablePrefix', 'out', ... 'outputToModelAsWell', 'off'}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end % check the params mode = get_var('mode', 'defaults', defaults, varargin{:}); outputNum = get_var('outputNum', 'defaults', defaults, varargin{:}); outputWidth = get_var('outputWidth', 'defaults', defaults, varargin{:}); outputBinaryPt = get_var('outputBinaryPt', 'defaults', defaults, varargin{:}); outputArithmeticType = get_var('outputArithmeticType', 'defaults', defaults, varargin{:}); outputToWorkspace = get_var('outputToWorkspace', 'defaults', defaults, varargin{:}); variablePrefix = get_var('variablePrefix', 'defaults', defaults, varargin{:}); outputToModelAsWell = get_var('outputToModelAsWell', 'defaults', defaults, varargin{:}); show_format = get_var('show_format', 'defaults', defaults, varargin{:}); if (strcmp(mode, 'divisions of arbitrary size') == 1), if (((length(outputWidth) ~= length(outputBinaryPt)) && (length(outputBinaryPt) ~= 1)) || ... ((length(outputWidth) ~= length(outputArithmeticType)) && (length(outputArithmeticType) ~= 1))), error('Division width, binary point and arithmetic type vectors must be the same length when using arbitrary divisions'); end if length(outputArithmeticType) == 1, outputArithmeticType = ones(1, length(outputWidth)) * outputArithmeticType; end if length(outputBinaryPt) == 1, outputBinaryPt = ones(1, length(outputWidth)) * outputBinaryPt; end end if strcmp(mode, 'divisions of arbitrary size'), outputNum = length(outputWidth); else if ((outputNum <= 0) || isnan(outputNum) || (~isnumeric(outputNum))), error('Need one or more outputs!'); end end if strcmp(mode, 'divisions of equal size'), vals = 1; else vals = outputNum; end for div = 1:vals, if ((outputWidth(div) <= 0) || isnan(outputWidth(div)) || (~isnumeric(outputWidth(div)))), error('Need non-zero output width!'); end if ((outputBinaryPt(div) > outputWidth(div)) || isnan(outputBinaryPt(div)) || (~isnumeric(outputBinaryPt(div)))), error('Binary point > output width makes no sense!'); end if ( ... ((outputArithmeticType(div) ~= 9) && ... (outputArithmeticType(div) ~= 2) && ... (outputArithmeticType(div) ~= 1) && ... (outputArithmeticType(div) ~= 0)) || ... isnan(outputArithmeticType(div)) || ... (~isnumeric(outputArithmeticType(div))) ... ), error('Arithmetic type must be one of 0,1,2,9!'); end if (outputArithmeticType(div) == 2 && (outputWidth(div) ~= 1 || outputBinaryPt(div) ~= 0)), error('Division width must be 1 and binary point 0 for Boolean Arithmetic type'); end end if strcmp(outputToWorkspace,'on') == 1, if (~isvarname(variablePrefix)), error('That is not a valid variable name!'); end; end munge_block(blk, varargin{:}); % delete all the lines delete_lines(blk); % add the inputs, outputs and gateway out blocks, drawing lines between them xSize = 100; ySize = 20; xStart = 100; yPos = 100; % one input for the bus reuse_block(blk, 'bus_in', 'built-in/inport', 'Position', [xStart, yPos, xStart + (xSize/2), yPos + ySize]); acc_bits = 0; config_string = ''; portnum = 1; % draw the output chains for p = 1 : outputNum, if strcmp(mode, 'divisions of equal size'), index = 1; else index = p; end boolean = 'off'; discard = false; width = outputWidth(index); bin_pt = outputBinaryPt(index); switch outputArithmeticType(index), case 1 arithmeticType = 'Signed (2''s comp)'; config_string = [config_string, sprintf('f%i.%i,', width, bin_pt)]; case 2 boolean = 'on'; config_string = [config_string, 'b,']; case 9 discard = true; config_string = [config_string, 'X,']; otherwise arithmeticType = 'Unsigned'; config_string = [config_string, sprintf('uf%i.%i,', width, bin_pt)]; end if discard == false, xPos = xStart + (xSize * 2); blockNum = outputNum + 1 - p; % the slice block sliceName = sprintf('slice%i', blockNum); reuse_block(blk, sliceName, 'xbsIndex_r4/Slice', ... 'Position', [xPos, yPos, xPos + (xSize/2), yPos + ySize], ... 'boolean_output', boolean, 'nbits', num2str(width), ... 'bit1', num2str(-1 * acc_bits)); xPos = xPos + (xSize * 2); add_line(blk, ['bus_in', '/1'], [sliceName, '/1']); if outputArithmeticType(index) ~= 2, % the reinterpret block if not boolean reinterpretName = sprintf('reinterpret%i', blockNum); reuse_block(blk, reinterpretName, 'xbsIndex_r4/Reinterpret', ... 'Position', [xPos, yPos, xPos + (xSize/2), yPos + ySize], ... 'force_arith_type', 'on', 'arith_type', arithmeticType, ... 'force_bin_pt', 'on', 'bin_pt', num2str(bin_pt)); add_line(blk, [sliceName, '/1'], [reinterpretName, '/1']); end xPos = xPos + (xSize * 2); % to workspace? if strcmp(outputToWorkspace,'on') == 1, % the gateway out block gatewayOutName = sprintf('gatewayOut%i', blockNum); reuse_block(blk, gatewayOutName, 'xbsIndex_r4/Gateway Out', ... 'Position', [xPos, yPos, xPos + (xSize/2), yPos + ySize], 'hdl_port', 'no'); xPos = xPos + (xSize * 2); % the to-workspace block toWorkspaceName = sprintf('toWorkspace%i', blockNum); toWorkspaceVariableName = sprintf('%s_%i', variablePrefix, blockNum); reuse_block(blk, toWorkspaceName, 'built-in/To Workspace', ... 'Position', [xPos, yPos, xPos + (xSize * 2), yPos + ySize], ... 'VariableName', toWorkspaceVariableName, 'MaxDataPoints', 'inf',... 'Decimation', '1','SampleTime', '-1','SaveFormat', 'Structure With Time', 'FixptAsFi', 'yes'); if outputArithmeticType(index) ~= 2, % not boolean add_line(blk, [reinterpretName, '/1'], [gatewayOutName, '/1']); else add_line(blk, [sliceName, '/1'], [gatewayOutName, '/1']); end add_line(blk, [gatewayOutName, '/1'], [toWorkspaceName, '/1'], 'autorouting', 'on'); yPos = yPos + (ySize * 2); end if ((strcmp(outputToWorkspace,'on') == 1) && (strcmp(outputToModelAsWell,'on') == 1)) || (strcmp(outputToWorkspace,'off') == 1), % the output block outName = sprintf('out%i', blockNum); if (blockNum == 1), outName = sprintf('lsb_%s', outName); end if (blockNum == outputNum), outName = sprintf('msb_%s', outName); end reuse_block(blk, outName, 'built-in/outport', 'Position', [xPos, yPos, xPos + (xSize/2), yPos + ySize], 'Port', num2str(portnum)); if outputArithmeticType(index) ~= 2, % not boolean add_line(blk, [reinterpretName, '/1'], [outName, '/1']); else add_line(blk, [sliceName, '/1'], [outName, '/1']); end yPos = yPos + (ySize * 2); end portnum = portnum + 1; end % /discard acc_bits = acc_bits + width; end % remove unconnected blocks clean_blocks(blk); % update format string so we know what's going on with this block if strcmp(show_format, 'on') displayString = sprintf('%d outputs: %s', outputNum, config_string); else displayString = sprintf('%d outputs', outputNum); end if strcmp(outputToWorkspace,'on') == 1, displayString = sprintf('%s, %s_?', displayString, variablePrefix); end set_param(blk, 'AttributesFormatString', displayString); save_state(blk, 'defaults', defaults, varargin{:}); % save and back-populate mask parameter values clog('exiting bus_expand_init','trace'); % end
github
mstrader/mlib_devel-master
bus_dual_port_ram_init.m
.m
mlib_devel-master/casper_library/bus_dual_port_ram_init.m
29,653
utf_8
c6478aedce086e963916fa3618e5d4eb
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bus_dual_port_ram_init(blk, varargin) log_group = 'bus_dual_port_ram_init_debug'; clog('entering bus_dual_port_ram_init', {'trace', log_group}); defaults = { ... 'n_bits', repmat(10, 1, 64), 'bin_pts', repmat(0, 1, 64), ... 'init_vector', repmat(zeros(8192, 1), 1, 64), ... 'max_fanout', 3, 'mem_type', 'Distributed memory', ... 'bram_optimization', 'Speed', ... %'Speed' 'Area' 'async_a', 'off', 'async_b', 'off', 'misc', 'on', ... 'bram_latency', 1, 'fan_latency', 1, ... 'addra_register', 'on', 'addra_implementation', 'behavioral', ... 'dina_register', 'on', 'dina_implementation', 'behavioral', ... 'wea_register', 'on', 'wea_implementation', 'behavioral', ... 'ena_register', 'on', 'ena_implementation', 'behavioral', ... 'addrb_register', 'on', 'addrb_implementation', 'behavioral', ... 'dinb_register', 'on', 'dinb_implementation', 'behavioral', ... 'web_register', 'on', 'web_implementation', 'behavioral', ... 'enb_register', 'on', 'enb_implementation', 'behavioral', ... }; check_mask_type(blk, 'bus_dual_port_ram'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); xpos = 50; xinc = 80; ypos = 50; yinc = 20; port_w = 30; port_d = 14; rep_w = 50; rep_d = 30; bus_expand_w = 50; bus_expand_d = 10; bus_create_w = 50; bus_create_d = 10; bram_w = 50; bram_d = 50; del_w = 30; del_d = 20; maxy = 2^15; %Simulink limit n_bits = get_var('n_bits', 'defaults', defaults, varargin{:}); bin_pts = get_var('bin_pts', 'defaults', defaults, varargin{:}); init_vector = get_var('init_vector', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); mem_type = get_var('mem_type', 'defaults', defaults, varargin{:}); bram_optimization = get_var('bram_optimization', 'defaults', defaults, varargin{:}); misc = get_var('misc', 'defaults', defaults, varargin{:}); async_a = get_var('async_a', 'defaults', defaults, varargin{:}); async_b = get_var('async_b', 'defaults', defaults, varargin{:}); max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:}); fan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:}); addra_register = get_var('addra_register', 'defaults', defaults, varargin{:}); addra_implementation = get_var('addra_implementation', 'defaults', defaults, varargin{:}); dina_register = get_var('dina_register', 'defaults', defaults, varargin{:}); dina_implementation = get_var('dina_implementation', 'defaults', defaults, varargin{:}); wea_register = get_var('wea_register', 'defaults', defaults, varargin{:}); wea_implementation = get_var('wea_implementation', 'defaults', defaults, varargin{:}); ena_register = get_var('ena_register', 'defaults', defaults, varargin{:}); ena_implementation = get_var('ena_implementation', 'defaults', defaults, varargin{:}); addrb_register = get_var('addrb_register', 'defaults', defaults, varargin{:}); addrb_implementation = get_var('addrb_implementation', 'defaults', defaults, varargin{:}); dinb_register = get_var('dinb_register', 'defaults', defaults, varargin{:}); dinb_implementation = get_var('dinb_implementation', 'defaults', defaults, varargin{:}); web_register = get_var('web_register', 'defaults', defaults, varargin{:}); web_implementation = get_var('web_implementation', 'defaults', defaults, varargin{:}); enb_register = get_var('enb_register', 'defaults', defaults, varargin{:}); enb_implementation = get_var('enb_implementation', 'defaults', defaults, varargin{:}); delete_lines(blk); %default state, do nothing if (n_bits(1) == 0), clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_dual_port_ram_init', {'trace', log_group}); return; end [riv, civ] = size(init_vector); [rnb, cnb] = size(n_bits); [rbp, cbp] = size(bin_pts); if (cnb ~= 1 && cbp ~= 1) && ((civ ~= cnb) || (civ ~= cbp)), clog('The number of columns in initialisation vector must match the number of values in binary point and number of bits parameter specifications', {'error', log_group}); error('The number of columns in initialisation vector must match the number of values in binary point and number of bits parameter specifications'); end %%%%%%%%%%%%%%% % input ports % %%%%%%%%%%%%%%% %The calculations below anticipate how BRAMs are to be configured by the Xilinx tools %(as detailed in UG190), explicitly generates these, and attempts to control fanout into %these %if optimizing for Area, do the best we can minimising fanout while still using whole BRAMs %fanout for very deep BRAMs will be large %TODO this should depend on FPGA architecture if strcmp(bram_optimization, 'Area'), if (riv >= 2^12), max_word_size = 9; elseif (riv >= 2^11), max_word_size = 18; else, max_word_size = 36; end %if optimising for Speed, keep splitting word size even if wasting BRAM resources else, if (riv >= 2^15), max_word_size = 1; elseif (riv >= 2^14), max_word_size = 2; elseif (riv >= 2^13), max_word_size = 4; elseif (riv >= 2^12), max_word_size = 9; elseif (riv >= 2^11), max_word_size = 18; else, max_word_size = 36; end end ctiv = 0; while (ctiv == 0) || ((ctiv * bram_d) > maxy), %if we are going to go beyond Xilinx bounds, double the word width if (ctiv * bram_d) > maxy, clog(['doubling word size from ', num2str(max_word_size), ' to make space'], log_group); if (max_word_size == 1), max_word_size = 2; elseif (max_word_size == 2), max_word_size = 4; elseif (max_word_size == 4), max_word_size = 9; elseif (max_word_size == 9), max_word_size = 18; else, max_word_size = 36; end %if end %if % translate initialisation matrix based on architecture [translated_init_vecs, result] = doubles2unsigned(init_vector, n_bits, bin_pts, max_word_size); if result ~= 0, clog('error translating initialisation matrix', {'error', log_group}); error('error translating initialisation matrix'); end [rtiv, ctiv] = size(translated_init_vecs); end %while clog([num2str(ctiv), ' brams required'], log_group); replication = ceil(ctiv/max_fanout); clog(['replication factor of ', num2str(replication), ' required'], log_group); if (cnb == 1), n_bits = repmat(n_bits, 1, civ); bin_pts = repmat(bin_pts, 1, civ); end ypos_tmp = ypos; ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'addra', 'built-in/inport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; reuse_block(blk, 'dina', 'built-in/inport', ... 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*ctiv/2; ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'wea', 'built-in/inport', ... 'Port', '3', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'addrb', 'built-in/inport', ... 'Port', '4', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; port_index = 5; %if we are using Block RAM, then need ports for dinb and web if strcmp(mem_type, 'Block RAM'), ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; reuse_block(blk, 'dinb', 'built-in/inport', ... 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*ctiv/2; port_index = port_index + 1; ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'web', 'built-in/inport', ... 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; port_index = port_index + 1; end % asynchronous A port if strcmp(async_a, 'on'), ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'ena', 'built-in/inport', ... 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; port_index = port_index + 1; end % asynchronous B port if strcmp(async_b, 'on'), ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'enb', 'built-in/inport', ... 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; port_index = port_index + 1; end %misc port if strcmp(misc, 'on'), reuse_block(blk, 'misci', 'built-in/inport', ... 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); end xpos = xpos + xinc + port_w/2; %%%%%%%%%%%%%%%%%%%% % replicate inputs % %%%%%%%%%%%%%%%%%%%% xpos = xpos + rep_w/2; ypos_tmp = ypos; %reset ypos % replicate addra if strcmp(addra_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'rep_addra', 'casper_library_bus/bus_replicate', ... 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... 'implementation', addra_implementation, ... 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]); add_line(blk, 'addra/1', 'rep_addra/1'); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; % delay dina if strcmp(dina_implementation, 'core'), reg_retiming = 'off'; else, reg_retiming = 'on'; end if strcmp(dina_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; reuse_block(blk, 'ddina', 'xbsIndex_r4/Delay', ... 'latency', num2str(latency), 'reg_retiming', reg_retiming, ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); add_line(blk, ['dina/1'], 'ddina/1'); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; % replicate wea if strcmp(wea_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'rep_wea', 'casper_library_bus/bus_replicate', ... 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... 'implementation', wea_implementation, ... 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]); add_line(blk, 'wea/1', 'rep_wea/1'); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; % replicate addrb if strcmp(addrb_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'rep_addrb', 'casper_library_bus/bus_replicate', ... 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... 'implementation', addrb_implementation, ... 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]); add_line(blk, 'addrb/1', 'rep_addrb/1'); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; if strcmp(mem_type, 'Block RAM'), % delay dinb if strcmp(dinb_implementation, 'core'), reg_retiming = 'off'; else, reg_retiming = 'on'; end if strcmp(dinb_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2; reuse_block(blk, 'ddinb', 'xbsIndex_r4/Delay', ... 'latency', num2str(latency), 'reg_retiming', reg_retiming, ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); add_line(blk, ['dinb/1'], 'ddinb/1'); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; % replicate web if strcmp(web_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'rep_web', 'casper_library_bus/bus_replicate', ... 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... 'implementation', web_implementation, ... 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]); add_line(blk, 'web/1', 'rep_web/1'); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; end %if if strcmp(async_a, 'on'), % replicate ena if strcmp(ena_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'rep_ena', 'casper_library_bus/bus_replicate', ... 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... 'implementation', ena_implementation, ... 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]); add_line(blk, 'ena/1', 'rep_ena/1'); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; end if strcmp(async_b, 'on'), % replicate enb if strcmp(enb_register, 'on'), latency = fan_latency; else, latency = 0; end ypos_tmp = ypos_tmp + bus_expand_d*replication/2; reuse_block(blk, 'rep_enb', 'casper_library_bus/bus_replicate', ... 'replication', num2str(replication), 'latency', num2str(latency), 'misc', 'off', ... 'implementation', enb_implementation, ... 'Position', [xpos-rep_w/2 ypos_tmp-rep_d/2 xpos+rep_w/2 ypos_tmp+rep_d/2]); add_line(blk, 'enb/1', 'rep_enb/1'); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; end xpos = xpos + xinc + rep_w/2; %%%%%%%%%%%%%%%% % debus inputs % %%%%%%%%%%%%%%%% xpos = xpos + bus_expand_w/2; % debus addra ypos_tmp = ypos + bus_expand_d*ctiv/2 + yinc; reuse_block(blk, 'debus_addra', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ... 'outputWidth', mat2str(repmat(ceil(log2(rtiv)), 1, replication)), ... 'outputBinaryPt', mat2str(zeros(1, replication)), ... 'outputArithmeticType', mat2str(zeros(1,replication)), 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + yinc + bus_expand_d*replication/2; add_line(blk, 'rep_addra/1', 'debus_addra/1'); % debus dina ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; total_bits = sum(n_bits); extra = mod(total_bits, max_word_size); main = repmat(max_word_size, 1, floor(total_bits/max_word_size)); outputWidth = [main]; if (extra ~= 0), outputWidth = [extra, outputWidth]; end reuse_block(blk, 'debus_dina', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', ... 'outputWidth', mat2str(outputWidth), 'outputBinaryPt', mat2str(zeros(1, ctiv)), ... 'outputArithmeticType', mat2str(zeros(1,ctiv)), 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'ddina/1', 'debus_dina/1'); % debus wea ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; reuse_block(blk, 'debus_wea', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ... 'outputWidth', mat2str(ones(1, replication)), ... 'outputBinaryPt', mat2str(zeros(1, replication)), ... 'outputArithmeticType', mat2str(repmat(2,1,replication)), 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'rep_wea/1', 'debus_wea/1'); % debus addrb ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; reuse_block(blk, 'debus_addrb', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ... 'outputWidth', mat2str(repmat(ceil(log2(rtiv)), 1, replication)), ... 'outputBinaryPt', mat2str(zeros(1, replication)), ... 'outputArithmeticType', mat2str(zeros(1,replication)), 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'rep_addrb/1', 'debus_addrb/1'); if strcmp(mem_type, 'Block RAM'), % debus dinb ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; reuse_block(blk, 'debus_dinb', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', ... 'outputWidth', mat2str(outputWidth), 'outputBinaryPt', mat2str(zeros(1, ctiv)), ... 'outputArithmeticType', mat2str(zeros(1,ctiv)), 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'ddinb/1', 'debus_dinb/1'); % debus web ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; reuse_block(blk, 'debus_web', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ... 'outputWidth', mat2str(ones(1, replication)), 'outputBinaryPt', mat2str(zeros(1, replication)), ... 'outputArithmeticType', mat2str(repmat(2,1,replication)), ... 'show_format', 'on', 'outputToWorkspace', 'off', 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'rep_web/1', 'debus_web/1'); end %if if strcmp(async_a, 'on'), % debus ena ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; reuse_block(blk, 'debus_ena', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ... 'outputWidth', mat2str(ones(1, replication)), 'outputBinaryPt', mat2str(zeros(1, replication)), ... 'outputArithmeticType', mat2str(repmat(2,1,replication)), ... 'show_format', 'on', 'outputToWorkspace', 'off', 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'rep_ena/1', 'debus_ena/1'); end if strcmp(async_b, 'on'), % debus enb ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; reuse_block(blk, 'debus_enb', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ... 'outputWidth', mat2str(ones(1, replication)), 'outputBinaryPt', mat2str(zeros(1, replication)), ... 'outputArithmeticType', mat2str(repmat(2,1,replication)), ... 'show_format', 'on', 'outputToWorkspace', 'off', 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-bus_expand_d*ctiv/2 xpos+bus_expand_w/2 ypos_tmp+bus_expand_d*ctiv/2]); ypos_tmp = ypos_tmp + bus_expand_d*ctiv/2 + yinc; add_line(blk, 'rep_enb/1', 'debus_enb/1'); end if strcmp(misc, 'on'), % delay misc ypos_tmp = ypos_tmp + del_d/2; reuse_block(blk, 'dmisc0', 'xbsIndex_r4/Delay', ... 'latency', num2str(fan_latency), 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); ypos_tmp = ypos_tmp + yinc + del_d/2; add_line(blk, 'misci/1', 'dmisc0/1'); end xpos = xpos + xinc + bus_expand_w/2; %%%%%%%%%%%%%% % bram layer % %%%%%%%%%%%%%% ypos_tmp = ypos; xpos = xpos + xinc + bram_w/2; for bram_index = 1:ctiv, % bram self % because the string version of the initVector could be too long (Matlab has upper limits on the length of strings), % we save the values in the UserData parameter of the dual port ram block (available on all Simulink blocks it seems) % and then reference that value from the mask initVector = translated_init_vecs(:, bram_index)'; UserData = struct('initVector', double(initVector)); if strcmp(bram_optimization, 'Speed'), optimize = 'Speed'; else, optimize = 'Area'; end ypos_tmp = ypos_tmp + bram_d/2; bram_name = ['bram', num2str(bram_index-1)]; reuse_block(blk, bram_name, 'xbsIndex_r4/Dual Port RAM', ... 'UserData', UserData, 'UserDataPersistent', 'on', ... 'depth', num2str(rtiv), 'initVector', ['zeros( 1, ',num2str(rtiv),')'], ... 'write_mode_A', 'Read Before Write', 'write_mode_B', 'Read Before Write', ... 'en_a', async_a, 'en_b', async_b, 'optimize', optimize, ... 'distributed_mem', mem_type, 'latency', num2str(bram_latency), ... 'Position', [xpos-bram_w/2 ypos_tmp-bram_d/2 xpos+bram_w/2 ypos_tmp+bram_d/2]); ypos_tmp = ypos_tmp + yinc + bram_d/2; set_param([blk,'/',bram_name], 'initVector', 'getfield(get_param(gcb, ''UserData''), ''initVector'')'); % bram connections to replication and debus blocks rep_index = mod(bram_index-1, replication) + 1; %replicated index to use add_line(blk, ['debus_addra/', num2str(rep_index)], [bram_name, '/1']); add_line(blk, ['debus_dina/', num2str(bram_index)], [bram_name, '/2']); add_line(blk, ['debus_wea/', num2str(rep_index)], [bram_name, '/3']); add_line(blk, ['debus_addrb/', num2str(rep_index)], [bram_name, '/4']); port_index = 4; if strcmp(mem_type, 'Block RAM'), add_line(blk, ['debus_dinb/', num2str(bram_index)], [bram_name, '/5']); add_line(blk, ['debus_web/', num2str(rep_index)], [bram_name, '/6']); port_index = 6; end %if if strcmp(async_a, 'on'), port_index = port_index+1; add_line(blk, ['debus_ena/', num2str(rep_index)], [bram_name, '/', num2str(port_index)]); end %if if strcmp(async_b, 'on'), port_index = port_index+1; add_line(blk, ['debus_enb/', num2str(rep_index)], [bram_name, '/', num2str(port_index)]); end %if end %for % delay for enables and misc if strcmp(async_a, 'on'), ypos_tmp = ypos_tmp + del_d/2; reuse_block(blk, 'dena', 'xbsIndex_r4/Delay', ... 'latency', num2str(bram_latency), 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); ypos_tmp = ypos_tmp + yinc + del_d/2; add_line(blk, ['debus_ena/',num2str(replication)], 'dena/1'); end; if strcmp(async_b, 'on'), ypos_tmp = ypos_tmp + del_d/2; reuse_block(blk, 'denb', 'xbsIndex_r4/Delay', ... 'latency', num2str(bram_latency), 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); ypos_tmp = ypos_tmp + yinc + del_d/2; add_line(blk, ['debus_enb/1'], 'denb/1'); end %if if strcmp(misc, 'on'), ypos_tmp = ypos_tmp + del_d/2; reuse_block(blk, 'dmisc1', 'xbsIndex_r4/Delay', ... 'latency', num2str(bram_latency), 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); ypos_tmp = ypos_tmp + yinc + del_d/2; add_line(blk, 'dmisc0/1', 'dmisc1/1'); end %if xpos = xpos + xinc + bram_w/2; %%%%%%%%%%%%%%%%%%%%%%%%%% % recombine bram outputs % %%%%%%%%%%%%%%%%%%%%%%%%%% xpos = xpos + bus_create_w/2; ypos_tmp = ypos; ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; reuse_block(blk, 'A_bussify', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(ctiv), ... 'Position', [xpos-bus_create_w/2 ypos_tmp-bus_create_d*ctiv/2 xpos+bus_create_w/2 ypos_tmp+bus_create_d*ctiv/2]); ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; reuse_block(blk, 'B_bussify', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(ctiv), ... 'Position', [xpos-bus_create_w/2 ypos_tmp-bus_create_d*ctiv/2 xpos+bus_create_w/2 ypos_tmp+bus_create_d*ctiv/2]); ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; for index = 1:ctiv, add_line(blk, ['bram',num2str(index-1),'/1'], ['A_bussify', '/', num2str(index)]); add_line(blk, ['bram',num2str(index-1),'/2'], ['B_bussify', '/', num2str(index)]); end %for xpos = xpos + xinc + bus_create_w/2; %%%%%%%%%%%%%%%% % output ports % %%%%%%%%%%%%%%%% xpos = xpos + port_w/2; ypos_tmp = ypos; ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; reuse_block(blk, 'A', 'built-in/outport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; add_line(blk, 'A_bussify/1', 'A/1'); ypos_tmp = ypos_tmp + bus_create_d*ctiv/2; reuse_block(blk, 'B', 'built-in/outport', ... 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + bus_create_d*ctiv/2; add_line(blk, 'B_bussify/1', 'B/1'); port_index = 3; if strcmp(async_a, 'on'), ypos_tmp = ypos_tmp + port_d/2; reuse_block(blk, 'dvalida', 'built-in/outport', ... 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + port_d/2; port_index = port_index + 1; add_line(blk, 'dena/1', 'dvalida/1'); end if strcmp(async_b, 'on'), ypos_tmp = ypos_tmp + port_d/2; reuse_block(blk, 'dvalidb', 'built-in/outport', ... 'Port', num2str(port_index), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + port_d/2; port_index = port_index + 1; add_line(blk, 'denb/1', 'dvalidb/1'); end if strcmp(misc, 'on'), ypos_tmp = ypos_tmp + port_d/2; reuse_block(blk, 'misco', 'built-in/outport', ... 'Port', num2str(port_index), ... 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + port_d/2; add_line(blk, 'dmisc1/1', 'misco/1'); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_dual_port_ram_init', {'trace', log_group}); end %function bus_dual_port_ram_init
github
mstrader/mlib_devel-master
mirror_spectrum_init.m
.m
mlib_devel-master/casper_library/mirror_spectrum_init.m
8,383
utf_8
e4141a1bad1ef5d40637641fadd247c5
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKASA % % www.kat.ac.za % % Copyright (C) Andrew Martens 2013 % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function mirror_spectrum_init(blk, varargin) clog('entering mirror_spectrum_init', {'trace', 'mirror_spectrum_init_debug'}); % Set default vararg values. % reg_retiming is not an actual parameter of this block, but it is included % in defaults so that same_state will return false for blocks drawn prior to % adding reg_retiming='on' to some of the underlying Delay blocks. defaults = { ... 'n_inputs', 1, ... 'FFTSize', 8, ... 'input_bitwidth', 18, ... 'bin_pt_in', 'input_bitwidth-1', ... 'bram_latency', 2, ... 'negate_latency', 1, ... 'negate_mode', 'Logic', ... 'async', 'off', ... 'reg_retiming', 'on', ... }; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'mirror_spectrum'); munge_block(blk, varargin{:}); % Retrieve values from mask fields. n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:}); FFTSize = get_var('FFTSize', 'defaults', defaults, varargin{:}); input_bitwidth = get_var('input_bitwidth', 'defaults', defaults, varargin{:}); bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); negate_latency = get_var('negate_latency', 'defaults', defaults, varargin{:}); negate_mode = get_var('negate_mode', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); delete_lines(blk); %default setup for library if n_inputs == 0 | FFTSize == 0, clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting mirror_spectrum_init',{'trace','mirror_spectrum_init_debug'}); return; end % % sync and counter % reuse_block(blk, 'sync', 'built-in/Inport', 'Port', '1', 'Position', [10 42 40 58]); reuse_block(blk, 'sync_delay0', 'xbsIndex_r4/Delay', ... 'latency', '1 + bram_latency + negate_latency - ceil(log2(n_inputs))', 'reg_retiming', 'on', ... 'Position', [105 39 140 61]); add_line(blk, 'sync/1', 'sync_delay0/1'); reuse_block(blk, 'counter', 'xbsIndex_r4/Counter', ... 'cnt_type', 'Free Running', 'operation', 'Up', 'start_count', '0', 'cnt_by_val', '1', ... 'arith_type', 'Unsigned', 'n_bits', 'FFTSize', 'bin_pt', '0', ... 'rst', 'on', 'en', async, ... 'use_behavioral_HDL', 'off', 'implementation', 'Fabric', ... 'Position', [185 156 245 189]); add_line(blk, 'sync_delay0/1', 'counter/1'); reuse_block(blk, 'constant', 'xbsIndex_r4/Constant', ... 'const', num2str(2^(FFTSize-1)), ... 'arith_type', 'Unsigned', 'n_bits', num2str(FFTSize), 'bin_pt', '0', ... 'explicit_period', 'on', 'period', '1', ... 'Position', [185 207 245 233]); reuse_block(blk, 'relational', 'xbsIndex_r4/Relational', 'latency', '0', 'mode', 'a>b', 'Position', [300 154 340 241]); add_line(blk, 'counter/1', 'relational/1'); add_line(blk, 'constant/1', 'relational/2'); reuse_block(blk, 'sync_delay1', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'on', 'latency', '1 + ceil(log2(n_inputs))', ... 'Position', [375 39 495 61]); add_line(blk, 'sync_delay0/1', 'sync_delay1/1'); reuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '1', 'Position', [550 42 580 58]); add_line(blk, 'sync_delay1/1', 'sync_out/1'); % % data % for index = 0:3, reuse_block(blk, ['din',num2str(index)], 'built-in/Inport', ... 'Port', num2str((index+1)*2), 'Position', [10 310+(125*index) 40 325+(125*index)]); reuse_block(blk, ['delay',num2str(index)], 'xbsIndex_r4/Delay', ... 'latency', '1 + bram_latency + negate_latency', 'reg_retiming', 'on', ... 'Position', [105 307+(125*index) 140 329+(125*index)]); add_line(blk, ['din',num2str(index),'/1'], ['delay',num2str(index),'/1']); reuse_block(blk, ['reo_in',num2str(index)], 'built-in/Inport', ... 'Port', num2str((index+1)*2+1), 'Position', [10 345+(125*index) 40 361+(125*index)]); %from original script (commit 8ea553 and earlier) if strcmp(negate_mode, 'dsp48e'), cc_latency = 3; else, cc_latency = negate_latency; end reuse_block(blk, ['complex_conj',num2str(index)], 'casper_library_misc/complex_conj', ... 'n_inputs', num2str(n_inputs), 'n_bits', num2str(input_bitwidth), ... 'bin_pt', num2str(bin_pt_in), 'latency', num2str(cc_latency), 'overflow', 'Wrap', ... %TODO Wrap really? 'Position', [105 343+(125*index) 140 363+(125*index)]); add_line(blk, ['reo_in',num2str(index),'/1'], ['complex_conj',num2str(index),'/1']); reuse_block(blk, ['sel_replicate',num2str(index)], 'casper_library_bus/bus_replicate', ... 'replication', 'n_inputs', 'latency', 'ceil(log2(n_inputs))', 'misc', 'off', 'implementation', 'core', ... 'Position', [375 274+(125*index) 415 296+(125*index)]); add_line(blk, 'relational/1', ['sel_replicate',num2str(index),'/1']); reuse_block(blk, ['dmux',num2str(index)], 'casper_library_bus/bus_mux', ... 'n_inputs', '2', 'n_bits', mat2str(repmat(input_bitwidth, 1, n_inputs)), 'mux_latency', '1', ... 'cmplx', 'on', 'misc', 'off', ... 'Position', [460 268+(125*index) 495 372+(125*index)]); add_line(blk, ['sel_replicate',num2str(index),'/1'], ['dmux',num2str(index),'/1']); add_line(blk, ['delay',num2str(index),'/1'], ['dmux',num2str(index),'/2']); add_line(blk, ['complex_conj',num2str(index),'/1'], ['dmux',num2str(index),'/3']); reuse_block(blk, ['dout',num2str(index)], 'built-in/Outport', ... 'Port', num2str(index+2), 'Position', [550 312+(125*index) 580 325+(125*index)]); add_line(blk, ['dmux',num2str(index),'/1'], ['dout',num2str(index),'/1']); end if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/Inport', 'Port', '10', 'Position', [10 87 40 103]); reuse_block(blk, 'en_delay0', 'xbsIndex_r4/Delay', ... 'latency', '1 + bram_latency + negate_latency - ceil(log2(n_inputs))', 'reg_retiming', 'on', ... 'Position', [105 84 140 106]); add_line(blk, 'en/1', 'en_delay0/1'); add_line(blk, 'en_delay0/1', 'counter/2'); reuse_block(blk, 'en_delay1', 'xbsIndex_r4/Delay', ... 'latency', '1 + ceil(log2(n_inputs))', 'reg_retiming', 'on', ... 'Position', [375 84 495 106]); add_line(blk, 'en_delay0/1', 'en_delay1/1'); reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', '6', 'Position', [550 87 580 103]); add_line(blk, 'en_delay1/1', 'dvalid/1'); end % Delete all unconnected blocks. clean_blocks(blk); % Save block state to stop repeated init script runs. save_state(blk, 'defaults', defaults, varargin{:}); end % mirror_spectrum_init
github
mstrader/mlib_devel-master
pfb_fir_coeff_gen_init.m
.m
mlib_devel-master/casper_library/pfb_fir_coeff_gen_init.m
15,990
utf_8
1de8ce4de68d6d055f4914665ca8e8a1
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens ([email protected]) % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function pfb_fir_coeff_gen_init(blk, varargin) log_group = 'pfb_fir_coeff_gen_init_debug'; clog('entering pfb_fir_coeff_gen_init', {'trace', log_group}); defaults = { ... 'n_inputs', 2, ... 'pfb_size', 5, ... 'n_taps', 4, ... 'n_bits_coeff', 18, ... 'WindowType', 'hamming', ... 'fwidth', 1, ... 'async', 'on', ... 'bram_latency', 2, ... 'fan_latency', 2, ... 'add_latency', 1, ... 'max_fanout', 1, ... 'bram_optimization', 'Area', ... }; check_mask_type(blk, 'pfb_fir_coeff_gen'); yinc = 40; if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:}); pfb_size = get_var('pfb_size', 'defaults', defaults, varargin{:}); n_taps = get_var('n_taps', 'defaults', defaults, varargin{:}); n_bits_coeff = get_var('n_bits_coeff', 'defaults', defaults, varargin{:}); WindowType = get_var('WindowType', 'defaults', defaults, varargin{:}); fwidth = get_var('fwidth', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); fan_latency = get_var('fan_latency', 'defaults', defaults, varargin{:}); add_latency = get_var('add_latency', 'defaults', defaults, varargin{:}); max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:}); bram_optimization = get_var('bram_optimization', 'defaults', defaults, varargin{:}); delete_lines(blk); %default empty block for storage in library if n_taps == 0, clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting pfb_fir_coeff_gen_init', {'trace', log_group}); return; end %check parameters if n_taps < 4, clog('need at least 4 taps', {'error', log_group}); error('need at least 4 taps'); return; end if mod(n_taps, 2) ~= 0, clog('Number of taps must be an even number', {'error', log_group}); error('Number of taps must be an even number'); return; end %get hardware platform from XSG block try xsg_blk = find_system(bdroot, 'SearchDepth', 1,'FollowLinks','on','LookUnderMasks','all','Tag','xps:xsg'); hw_sys = xps_get_hw_plat(get_param(xsg_blk{1},'hw_sys')); catch, clog('Could not find hardware platform - is there an XSG block in this model? Defaulting platform to ROACH.', {log_group}); warning('pfb_fir_coeff_gen_init: Could not find hardware platform - is there an XSG block in this model? Defaulting platform to ROACH.'); hw_sys = 'ROACH'; end %try/catch %parameters to decide optimisation parameters switch hw_sys case 'ROACH' port_width = 36; %upper limit case 'ROACH2' port_width = 36; %upper limit end %switch yoff = 226; %%%%%%%%%%%%%%%%% % sync pipeline % %%%%%%%%%%%%%%%%% reuse_block(blk, 'sync', 'built-in/Inport', 'Port', '1', 'Position', [15 23 45 37]); reuse_block(blk, 'sync_delay', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'latency', num2str(fan_latency+bram_latency), 'Position', [255 22 515 38]); add_line(blk,'sync/1', 'sync_delay/1'); reuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '1', 'Position', [1060 23 1090 37]); add_line(blk,'sync_delay/1', 'sync_out/1'); %%%%%%%%%%%%%%%% % din pipeline % %%%%%%%%%%%%%%%% reuse_block(blk, 'din', 'built-in/Inport', 'Port', '2', 'Position', [15 68 45 82]); reuse_block(blk, 'din_delay', 'xbsIndex_r4/Delay', 'reg_retiming', 'on',... 'latency', num2str(fan_latency+bram_latency), 'Position', [255 67 515 83]); add_line(blk, 'din/1', 'din_delay/1'); reuse_block(blk, 'dout', 'built-in/Outport', 'Port', '2', 'Position', [1060 68 1090 82]); add_line(blk,'din_delay/1', 'dout/1'); %%%%%%%%%%%%%%%%%%%%%%%%%% % coefficient generation % %%%%%%%%%%%%%%%%%%%%%%%%%% % address generation reuse_block(blk, 'counter', 'xbsIndex_r4/Counter', ... 'cnt_type', 'Free Running', 'operation', 'Up', 'start_count', '0', 'cnt_by_val', '1', ... 'n_bits', num2str(pfb_size-n_inputs), 'arith_type', 'Unsigned', 'bin_pt', '0', ... 'rst', 'on', 'en', async, ... 'Position', [95 211 145 264]); add_line(blk, 'sync/1', 'counter/1'); %we invert the address to get address for the other half of the taps reuse_block(blk, 'inverter', 'xbsIndex_r4/Inverter', ... 'latency', '0', 'Position', [170 303 220 357]); add_line(blk, 'counter/1', 'inverter/1'); % ROM generation outputs_required = 2^n_inputs*(n_taps/2); % constants reuse_block(blk, 'rom_din', 'xbsIndex_r4/Constant', ... 'const', '0', 'arith_type', 'Unsigned', ... 'n_bits', num2str(outputs_required*n_bits_coeff), 'bin_pt', '0', ... 'explicit_period', 'on', 'period', '1', ... 'Position', [255 262 275 278]); reuse_block(blk, 'rom_we', 'xbsIndex_r4/Constant', ... 'const', '0', 'arith_type', 'Boolean', ... 'explicit_period', 'on', 'period', '1', ... 'Position', [255 292 275 308]); % rom init_vector = ''; for tap_index = 1:(n_taps/2), for input_index = 0:(2^n_inputs)-1, vec = ['pfb_coeff_gen_calc(', num2str(pfb_size), ', ', num2str(n_taps), ', ''', WindowType, ''', ', num2str(n_inputs), ', ', num2str(input_index), ', ', num2str(fwidth), ', ', num2str(tap_index), ', false)''']; if(tap_index == 1 && input_index == 0), init_vector = vec; else, init_vector = [init_vector, ', ', vec]; end end %for input_index end %for tap_index reuse_block(blk, 'rom', 'casper_library_bus/bus_dual_port_ram', ... 'n_bits', mat2str(repmat(n_bits_coeff, 1, outputs_required)), ... 'bin_pts', mat2str(repmat(n_bits_coeff-1, 1, outputs_required)), ... 'init_vector', ['[', init_vector, ']'], ... 'max_fanout', num2str(max_fanout), ... 'mem_type', 'Block RAM', 'bram_optimization', bram_optimization, ... 'async_a', 'off', 'async_b', 'off', 'misc', 'off', ... 'bram_latency', num2str(bram_latency), ... 'fan_latency', num2str(fan_latency), ... 'addra_register', 'on', 'addra_implementation', 'core', ... 'dina_register', 'off', 'dina_implementation', 'behavioral', ... 'wea_register', 'off', 'wea_implementation', 'behavioral', ... 'addrb_register', 'on', 'addra_implementation', 'core', ... 'dinb_register', 'off', 'dinb_implementation', 'behavioral', ... 'web_register', 'off', 'web_implementation', 'behavioral', ... 'Position', [330 226 385 404]); add_line(blk, 'counter/1', 'rom/1'); add_line(blk, 'inverter/1', 'rom/4'); add_line(blk, 'rom_din/1', 'rom/2'); add_line(blk, 'rom_din/1', 'rom/5'); add_line(blk, 'rom_we/1', 'rom/3'); add_line(blk, 'rom_we/1', 'rom/6'); % logic for second half of taps % Coefficients are not quite symmetrical, they are off by one, and do not overlap by one % e.g with T taps and fft size of N: tap T-1, sample 0 is not the same as tap 0, sample N-1 % instead it is unique and not included in the coefficients for Tap 0 reuse_block(blk, 'zero', 'xbsIndex_r4/Constant', ... 'const', '0', 'arith_type', 'Unsigned', ... 'n_bits', num2str(pfb_size-n_inputs), 'bin_pt', '0', ... 'explicit_period', 'on', 'period', '1', ... 'Position', [210 122 230 138]); reuse_block(blk, 'first', 'xbsIndex_r4/Relational' , ... 'latency', '1', 'mode', 'a=b', 'Position', [295 114 325 176]); add_line(blk, 'counter/1', 'first/2'); add_line(blk, 'zero/1', 'first/1'); reuse_block(blk, 'dfirst', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'latency', num2str(bram_latency+fan_latency-1-1), 'Position', [455 136 515 154] ); add_line(blk, 'first/1', 'dfirst/1'); % get the first value of the second half of the taps vector = pfb_coeff_gen_calc(pfb_size, n_taps, WindowType, n_inputs, 0, fwidth, n_taps/2+1, false); val = doubles2unsigned(vector(1), n_bits_coeff, n_bits_coeff-1, n_bits_coeff); init = val(1); reuse_block(blk, 'register', 'xbsIndex_r4/Register', ... 'init', num2str(init), 'rst', 'on', 'en', async, ... 'Position', [675 yoff+(outputs_required*yinc) 720 yoff+((outputs_required+1)*yinc)]); add_line(blk, 'dfirst/1', 'register/2'); % reorder output of port B order = zeros(1, n_taps/2 * 2^n_inputs); for tap_index = 0:n_taps/2-1, for input_index = 0:2^n_inputs-1, offset = ((n_taps/2)-tap_index-1) * (2^n_inputs); if input_index == 0, index = offset; else, index = offset + (2^n_inputs - input_index); end order(tap_index*(2^n_inputs) + input_index + 1) = index; end %for end %for reuse_block(blk, 'munge', 'casper_library_flow_control/munge', ... 'divisions', num2str(outputs_required), ... 'div_size', mat2str(repmat(n_bits_coeff, 1, outputs_required)), ... 'order', mat2str(order), 'arith_type_out', 'Unsigned', 'bin_pt_out', '0', ... 'Position', [435 377 475 403] ); add_line(blk, 'rom/2', 'munge/1'); % coefficient extraction reuse_block(blk, 'a_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(outputs_required), ... 'outputWidth', num2str(n_bits_coeff), 'outputBinaryPt', '0', 'outputArithmeticType', '0', ... 'Position', [740 yoff 790 yoff+(outputs_required*yinc)]); add_line(blk, 'rom/1', 'a_expand/1'); reuse_block(blk, 'b_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(outputs_required), ... 'outputWidth', num2str(n_bits_coeff), 'outputBinaryPt', '0', 'outputArithmeticType', '0', ... 'Position', [515 yoff+(outputs_required*yinc) 565 yoff+(outputs_required*yinc*2)]); add_line(blk, 'munge/1', 'b_expand/1'); add_line(blk, 'b_expand/1', 'register/1'); reuse_block(blk, 'coeffs', 'built-in/Outport', 'Port', '3', ... 'Position', [1060 yoff+outputs_required*yinc-7 1090 yoff+outputs_required*yinc+7]); % concat a and b busses together reuse_block(blk, 'concat', 'xbsIndex_r4/Concat', ... 'num_inputs', num2str(outputs_required*2), ... 'Position', [1005 yoff 1035 yoff+(outputs_required*2*yinc)]); add_line(blk, 'concat/1', 'coeffs/1'); % delays for each output for d_index = 0:outputs_required*2-1, d_name = ['d',num2str(d_index)]; latency = (floor((outputs_required*2-d_index-1)/(2^n_inputs)))*add_latency; if d_index >= outputs_required, if mod(d_index, 2^n_inputs) == 0, if mod(d_index, (n_taps/2)*2^n_inputs) ~= 0, latency = latency + 1; end end end %force delay block with 0 latency to have no enable port if latency > 0, en = async; else, en = 'off'; end reuse_block(blk, d_name, 'casper_library_delays/delay_srl', ... 'async', en, 'DelayLen', num2str(latency), ... 'Position', [875 yoff+d_index*yinc 930 yoff+d_index*yinc+18]); add_line(blk, [d_name,'/1'], ['concat/',num2str(d_index+1)]); % join bus expansion blocks to delay if ((d_index/outputs_required) < 1), src_blk = 'a_expand'; else, if (mod(d_index, outputs_required) == 0), src_blk = 'register'; else, src_blk = 'b_expand'; end end %if src_port = mod(d_index, outputs_required) + 1; add_line(blk, [src_blk, '/', num2str(src_port)], [d_name, '/1']); end %for % asynchronous pipeline if strcmp(async, 'on'), yoff = 226; reuse_block(blk, 'en', 'built-in/Inport', 'Port', '3', ... 'Position', [15 243 45 257]); add_line(blk, 'en/1', 'counter/2'); reuse_block(blk, 'den0', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'latency', num2str(bram_latency), ... 'Position', [255 yoff+(outputs_required*2+2)*yinc 280 yoff+(outputs_required*2+2)*yinc+18]); add_line(blk, 'en/1', 'den0/1'); reuse_block(blk, 'den1', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'latency', num2str(fan_latency), ... 'Position', [540 yoff+(outputs_required*2+2)*yinc 565 yoff+(outputs_required*2+2)*yinc+18]); add_line(blk, 'den0/1', 'den1/1'); add_line(blk, 'den1/1', 'register/3'); outputNum = outputs_required*2-(2^n_inputs-1); reuse_block(blk, 'en_replicate', 'casper_library_bus/bus_replicate', ... 'replication', num2str(outputNum), 'latency', num2str(fan_latency+bram_latency), 'misc', 'off', ... 'Position', [245 yoff+(outputs_required*2+4)*yinc 295 yoff+(outputs_required*2+4)*yinc+30]); add_line(blk, 'en/1', 'en_replicate/1'); reuse_block(blk, 'en_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(outputNum), ... 'outputWidth', '1', 'outputBinaryPt', '0', 'outputArithmeticType', '2', ... 'Position', [740 yoff+(outputs_required*2+4)*yinc 790 yoff+(outputs_required*3+4)*yinc]); add_line(blk, 'en_replicate/1', 'en_expand/1'); for d_index = 0:outputs_required*2-1, latency = (floor((outputs_required*2-d_index-1)/(2^n_inputs)))*add_latency; if d_index >= outputs_required, if mod(d_index, 2^n_inputs) == 0, if mod(d_index, (n_taps/2)*2^n_inputs) ~= 0, latency = latency + 1; end end end if(latency > 0), d_name = ['d',num2str(d_index)]; add_line(blk, ['en_expand/',num2str(d_index+1)], [d_name,'/2']); end end %for reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', '4', ... 'Position', [1060 yoff+(outputs_required*2+2)*yinc+2 1090 yoff+(outputs_required*2+2)*yinc+16]); add_line(blk, 'den1/1', 'dvalid/1'); end %if async clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting pfb_fir_coeff_gen_init', {'trace', log_group}); end %pfb_fir_coeff_gen_init
github
mstrader/mlib_devel-master
delay_wideband_prog_init.m
.m
mlib_devel-master/casper_library/delay_wideband_prog_init.m
10,869
utf_8
a754c63e13487297b707da15284afa1f
% Initialize and configure the delay wideband programmable block . % By Jason + Mekhala, mods by Andrew % % delay_wideband_prog_init(blk, varargin) % % blk = The block to configure. % varargin = {'varname', 'value', ...} pairs % % Declare any default values for arguments you might like. function delay_wideband_prog_init(blk, varargin) log_group = 'delay_wideband_prog_init_debug'; clog('entering delay_wideband_prog_init', {log_group, 'trace'}); defaults = { ... 'max_delay', 1024, ... 'n_inputs_bits', 2, ... 'bram_latency', 2, ... 'bram_type', 'Dual Port', ... 'async', 'off'}; % if parameter is changed then only it will redraw otherwise will exit if same_state(blk, 'defaults', defaults, varargin{:}), return, end % Checks whether the block selected is correct with this called function. check_mask_type(blk, 'delay_wideband_prog'); %Sets the variable to the sub-blocks (scripted ones), also checks whether %to update or prevent from any update munge_block(blk, varargin{:}); % sets the variable needed max_delay = get_var('max_delay', 'defaults', defaults, varargin{:}); n_inputs_bits = get_var('n_inputs_bits', 'defaults', defaults, varargin{:}); ram_bits = ceil(log2(max_delay/(2^n_inputs_bits))); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); bram_type = get_var('bram_type', 'defaults', defaults,varargin{:}); async = get_var('async', 'defaults', defaults,varargin{:}); if strcmp(async, 'on') && strcmp(bram_type, 'Single Port'), clog('Delays must be implemented in dual port memories when in asynchronous mode', {log_group, 'error'}); error('Delays must be implemented in dual port memories when in asynchronous mode in the delay_wideband_prog block'); end % Begin redrawing delete_lines(blk); if (max_delay == 0), clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting delay_wideband_prog_init', {log_group, 'trace'}); return; end % delay sync to compensate for delays % through BRAMs as well as for delay offset added % when using single port RAMs if strcmp(bram_type, 'Single Port'), latency = bram_latency + 2; sync_latency = latency + (bram_latency+1)*2^n_inputs_bits; else latency = bram_latency + 1; sync_latency = latency; end % sync reuse_block(blk, 'sync', 'built-in/Inport', 'Port', '1', 'Position', [15 218 45 232]) ; if strcmp(async, 'on'), % en y = 230 + (2^n_inputs_bits)*70; reuse_block(blk, 'en', 'built-in/Inport', 'Port', num2str(1 + 2^n_inputs_bits), ... 'Position',[15 y+28 45 y+42]); reuse_block(blk, 'en_delay0', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'Position', [565 y+21 605 y+49], 'latency', '0'); add_line(blk, 'en/1', 'en_delay0/1'); reuse_block(blk, 'en_delay1', 'xbsIndex_r4/Delay', ... 'Position', [705 y+21 745 y+49], 'latency', num2str(sync_latency), 'reg_retiming', 'on'); add_line(blk, 'en_delay0/1', 'en_delay1/1'); reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', num2str(1 + 2^n_inputs_bits), ... 'Position', [975 y+28 1005 y+42]); end reuse_block(blk, 'sync_delay', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'Position', [705 211 745 239], 'latency', num2str(sync_latency)); reuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '1', 'Position', [975 158 1005 172]); add_line(blk, 'sync/1', 'sync_delay/1'); % register delay value reuse_block(blk, 'delay', 'built-in/Inport', 'Port', '2', 'Position', [15 273 45 287]) ; reuse_block(blk, 'ld_delay', 'built-in/Inport', 'Port', '3', 'Position', [15 303 45 317]) ; reuse_block(blk, 'delay_reg', 'xbsIndex_r4/Register', 'Position',[105 266 160 324], 'en', 'on'); add_line(blk, 'delay/1', 'delay_reg/1', 'autorouting', 'on'); add_line(blk, 'ld_delay/1', 'delay_reg/2', 'autorouting', 'on'); %cut address for BRAM from delay reuse_block(blk, 'bram_rd_addrs', 'xbsIndex_r4/Slice', ... 'Position', [420 282 450 308], ... 'mode', 'Lower Bit Location + Width', ... 'nbits', num2str(ram_bits), ... 'bit0', num2str(n_inputs_bits), ... 'base0', 'LSB of Input'); if strcmp(bram_type, 'Single Port'), % When using single-port BRAMs, a delay offset must added due to limitations in the delay_bram_prog reuse_block(blk, 'delay_offset', 'xbsIndex_r4/Constant', ... 'Position', [230 333 255 357], ... 'const', num2str((bram_latency+1)*2^n_inputs_bits), ... 'arith_type', 'Unsigned', ... 'n_bits', num2str(ceil(log2(max_delay))), ... 'bin_pt', '0', ... 'explicit_period', 'on', ... 'period', '1'); reuse_block(blk, 'delay_adder', 'xbsIndex_r4/AddSub', ... 'Position', [310 266 345 319], ... 'latency', '1', 'mode', 'Addition'); add_line(blk, 'delay_offset/1', 'delay_adder/2', 'autorouting', 'on'); add_line(blk, 'delay_adder/1', 'bram_rd_addrs/1', 'autorouting', 'on'); % This offset must be removed from the max possible delay value (and we force the value to clip at % this lower value) to prevent wrapping when this offset is added reuse_block(blk, 'max_delay', 'xbsIndex_r4/Constant',... 'Position', [115 230 145 250],... 'const', num2str((2^ram_bits * 2^n_inputs_bits)-((bram_latency+1)*2^n_inputs_bits) - 1),... 'arith_type', 'Unsigned',... 'n_bits', num2str(ceil(log2(max_delay))),... 'bin_pt', '0',... 'explicit_period', 'on',... 'period', '1'); reuse_block(blk, 'max_delay_chk', 'xbsIndex_r4/Relational', ... 'latency', '1', 'Position', [185 234 225 276], 'mode', 'a<=b'); add_line(blk, 'delay_reg/1', 'max_delay_chk/1', 'autorouting', 'on'); add_line(blk, 'max_delay/1', 'max_delay_chk/2', 'autorouting', 'on'); reuse_block (blk,'mux_delay','xbsIndex_r4/Mux', 'Position', [250 245 275 315], 'inputs', '2'); add_line(blk, 'mux_delay/1', 'delay_adder/1', 'autorouting', 'on'); add_line(blk, 'max_delay_chk/1', 'mux_delay/1', 'autorouting', 'on'); add_line(blk, 'max_delay/1', 'mux_delay/2', 'autorouting', 'on'); add_line(blk, 'delay_reg/1', 'mux_delay/3', 'autorouting', 'on'); else add_line(blk, 'delay_reg/1', 'bram_rd_addrs/1', 'autorouting', 'on'); end if n_inputs_bits > 0, reuse_block(blk, 'barrel_switcher', 'casper_library_reorder/barrel_switcher', ... 'async', async, 'n_inputs', num2str(n_inputs_bits), ... 'Position', [825 127 910 127+(62*(2+2^n_inputs_bits))]); add_line(blk, 'sync_delay/1', 'barrel_switcher/2'); add_line(blk, 'barrel_switcher/1', 'sync_out/1'); if strcmp(async, 'on'), add_line(blk, 'en_delay1/1', ['barrel_switcher/', num2str(3 + 2^n_inputs_bits)]); add_line(blk, ['barrel_switcher/', num2str(2 + 2^n_inputs_bits)], 'dvalid/1'); end %slice out amount of rotation in barrel shifter from delay value reuse_block(blk, 'shift_sel', 'xbsIndex_r4/Slice', ... 'mode', 'Lower Bit Location + Width', ... 'nbits', num2str(n_inputs_bits), ... 'bit0', '0', 'base0', 'LSB of Input', ... 'Position', [190 153 220 177]); if strcmp(bram_type, 'Single Port') add_line(blk, 'delay_adder/1', 'shift_sel/1', 'autorouting', 'on'); else add_line(blk, 'delay_reg/1', 'shift_sel/1'); end %delay shift value to match delay latency through delay brams reuse_block(blk, 'delay_sel', 'xbsIndex_r4/Delay', 'latency', num2str(latency), ... 'reg_retiming', 'on', 'Position', [705 152 745 178]); add_line(blk, 'shift_sel/1', 'delay_sel/1'); add_line(blk, 'delay_sel/1', 'barrel_switcher/1'); y = 230; for n=0:((2^n_inputs_bits)-1), name = ['data_out', num2str(n)]; reuse_block(blk, name, 'built-in/Outport', 'Port', num2str(n+2), 'Position', [975 y+3 1005 y+17]); add_line(blk, ['barrel_switcher/', num2str((2^n_inputs_bits)-n+1)], [name,'/1']); y=y+70; end y = 260; for n=0:(2^n_inputs_bits)-1, in_name = ['data_in', num2str(n)]; reuse_block(blk, in_name, 'built-in/Inport', 'Port', num2str(n+4), 'Position', [570 y+8 600 y+22]) ; % delay brams if strcmp(bram_type, 'Single Port'), delay_name = ['delay_sp', num2str(n)]; reuse_block(blk, delay_name, 'casper_library_delays/delay_bram_prog', ... 'Position', [705 y+5 745 y+45], ... 'MaxDelay', num2str(ram_bits), ... 'bram_latency', num2str(bram_latency)); else delay_name = ['delay_dp', num2str(n)]; reuse_block(blk, delay_name, 'casper_library_delays/delay_bram_prog_dp', ... 'Position',[705 y+5 745 y+45], ... 'ram_bits', num2str(ram_bits), 'async', async, ... 'bram_latency', num2str(bram_latency)); end add_line(blk, [in_name, '/1'], [delay_name, '/1']); add_line(blk, [delay_name, '/1'], ['barrel_switcher/', num2str((2^n_inputs_bits)-n+2)]); if strcmp(async, 'on'), add_line(blk, 'en_delay0/1', [delay_name, '/3']); end if n > 0, name = ['Constant', num2str(n)]; reuse_block(blk, name, 'xbsIndex_r4/Constant',... 'Position', [295 y+41 310 y+59],... 'const', num2str(2^n_inputs_bits-1-n),... 'arith_type', 'Unsigned',... 'n_bits', num2str(n_inputs_bits),... 'bin_pt', '0',... 'explicit_period', 'on',... 'period', '1' ); name = ['Relational', num2str(n)]; reuse_block(blk, name, 'xbsIndex_r4/Relational', ... 'Position', [335 y+35 380 y+55], ... 'latency', '0', 'mode', 'a>b'); add_line(blk, 'shift_sel/1', ['Relational', num2str(n),'/1']); add_line(blk, ['Constant', num2str(n),'/1'], ['Relational', num2str(n), '/2']); name = ['Convert', num2str(n)]; reuse_block(blk, name, 'xbsIndex_r4/Convert', ... 'Position', [420 y+35 450 y+55], ... 'arith_type', 'Unsigned', 'n_bits', '1', 'bin_pt', '0') ; add_line(blk, ['Relational', num2str(n), '/1'], ['Convert', num2str(n), '/1']); add_name = ['AddSub', num2str(n)]; reuse_block(blk, add_name, 'xbsIndex_r4/AddSub', ... 'Position', [515 y+17 550 y+53], ... 'mode', 'Addition', 'arith_type', 'Unsigned', ... 'n_bits', num2str(ram_bits), ... 'bin_pt', '0', 'quantization', 'Truncate', ... 'overflow', 'Wrap', 'latency', '0'); add_line(blk, 'bram_rd_addrs/1', [add_name, '/1']); add_line(blk, ['Convert', num2str(n), '/1'], [add_name, '/2']); add_line(blk, [add_name, '/1'], [delay_name, '/2']); else, add_line(blk, 'bram_rd_addrs/1', [delay_name, '/2']); end %if y=y+60; end %for else, if strcmp(bram_type, 'Single Port'), add_line(blk, 'delay_sp/1', 'data_out0/1'); else, add_line(blk, 'delay_dp/1', 'data_out0/1'); end add_line(blk, 'sync_delay/1', 'sync_out/1'); if strcmp(async, 'on'), add_line(blk, 'en_delay/1', 'dvalid/1'); end end clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting delay_wideband_prog_init', {log_group, 'trace'});
github
mstrader/mlib_devel-master
fir_dbl_tap_init.m
.m
mlib_devel-master/casper_library/fir_dbl_tap_init.m
7,747
utf_8
b5c58515b786a94c758a38b09fd6d81f
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % MeerKAT Radio Telescope Project % % www.kat.ac.za % % Copyright (C) 2013 Andrew Martens (meerKAT) % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fir_dbl_tap_init(blk, varargin) defaults = {}; check_mask_type(blk, 'fir_dbl_tap'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); factor = get_var('factor','defaults', defaults, varargin{:}); add_latency = get_var('latency','defaults', defaults, varargin{:}); mult_latency = get_var('latency','defaults', defaults, varargin{:}); coeff_bit_width = get_var('coeff_bit_width','defaults', defaults, varargin{:}); coeff_bin_pt = get_var('coeff_bin_pt','defaults', defaults, varargin{:}); delete_lines(blk); %default state in library if coeff_bit_width == 0, clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); return; end reuse_block(blk, 'a', 'built-in/Inport'); set_param([blk,'/a'], ... 'Port', '1', ... 'Position', '[25 33 55 47]'); reuse_block(blk, 'b', 'built-in/Inport'); set_param([blk,'/b'], ... 'Port', '2', ... 'Position', '[25 123 55 137]'); reuse_block(blk, 'c', 'built-in/Inport'); set_param([blk,'/c'], ... 'Port', '3', ... 'Position', '[25 213 55 227]'); reuse_block(blk, 'd', 'built-in/Inport'); set_param([blk,'/d'], ... 'Port', '4', ... 'Position', '[25 303 55 317]'); reuse_block(blk, 'Register0', 'xbsIndex_r4/Register'); set_param([blk,'/Register0'], ... 'Position', '[315 16 360 64]'); reuse_block(blk, 'Register1', 'xbsIndex_r4/Register'); set_param([blk,'/Register1'], ... 'Position', '[315 106 360 154]'); reuse_block(blk, 'Register2', 'xbsIndex_r4/Register'); set_param([blk,'/Register2'], ... 'Position', '[315 196 360 244]'); reuse_block(blk, 'coefficient', 'xbsIndex_r4/Constant'); set_param([blk,'/coefficient'], ... 'const', 'factor', ... 'n_bits', 'coeff_bit_width', ... 'bin_pt', 'coeff_bin_pt', ... 'explicit_period', 'on', ... 'Position', '[165 354 285 386]'); reuse_block(blk, 'Register3', 'xbsIndex_r4/Register'); set_param([blk,'/Register3'], ... 'Position', '[315 286 360 334]'); reuse_block(blk, 'AddSub0', 'xbsIndex_r4/AddSub'); set_param([blk,'/AddSub0'], ... 'latency', 'add_latency', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', '18', ... 'bin_pt', '16', ... 'use_behavioral_HDL', 'on', ... 'use_rpm', 'on', ... 'Position', '[180 412 230 463]'); reuse_block(blk, 'Mult0', 'xbsIndex_r4/Mult'); set_param([blk,'/Mult0'], ... 'n_bits', '18', ... 'bin_pt', '17', ... 'latency', 'mult_latency', ... 'use_behavioral_HDL', 'on', ... 'use_rpm', 'off', ... 'placement_style', 'Rectangular shape', ... 'Position', '[315 402 365 453]'); reuse_block(blk, 'AddSub1', 'xbsIndex_r4/AddSub'); set_param([blk,'/AddSub1'], ... 'latency', 'add_latency', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', '18', ... 'bin_pt', '16', ... 'use_behavioral_HDL', 'on', ... 'use_rpm', 'on', ... 'Position', '[180 497 230 548]'); reuse_block(blk, 'Mult1', 'xbsIndex_r4/Mult'); set_param([blk,'/Mult1'], ... 'n_bits', '18', ... 'bin_pt', '17', ... 'latency', 'mult_latency', ... 'use_behavioral_HDL', 'on', ... 'use_rpm', 'off', ... 'placement_style', 'Rectangular shape', ... 'Position', '[315 487 365 538]'); reuse_block(blk, 'a_out', 'built-in/Outport'); set_param([blk,'/a_out'], ... 'Port', '1', ... 'Position', '[390 33 420 47]'); reuse_block(blk, 'b_out', 'built-in/Outport'); set_param([blk,'/b_out'], ... 'Port', '2', ... 'Position', '[390 123 420 137]'); reuse_block(blk, 'c_out', 'built-in/Outport'); set_param([blk,'/c_out'], ... 'Port', '3', ... 'Position', '[390 213 420 227]'); reuse_block(blk, 'd_out', 'built-in/Outport'); set_param([blk,'/d_out'], ... 'Port', '4', ... 'Position', '[390 303 420 317]'); reuse_block(blk, 'real', 'built-in/Outport'); set_param([blk,'/real'], ... 'Port', '5', ... 'Position', '[390 423 420 437]'); reuse_block(blk, 'imag', 'built-in/Outport'); set_param([blk,'/imag'], ... 'Port', '6', ... 'Position', '[390 508 420 522]'); add_line(blk,'d/1','AddSub1/2', 'autorouting', 'on'); add_line(blk,'d/1','Register3/1', 'autorouting', 'on'); add_line(blk,'c/1','AddSub0/2', 'autorouting', 'on'); add_line(blk,'c/1','Register2/1', 'autorouting', 'on'); add_line(blk,'b/1','AddSub1/1', 'autorouting', 'on'); add_line(blk,'b/1','Register1/1', 'autorouting', 'on'); add_line(blk,'a/1','AddSub0/1', 'autorouting', 'on'); add_line(blk,'a/1','Register0/1', 'autorouting', 'on'); add_line(blk,'Register0/1','a_out/1', 'autorouting', 'on'); add_line(blk,'Register1/1','b_out/1', 'autorouting', 'on'); add_line(blk,'Register2/1','c_out/1', 'autorouting', 'on'); add_line(blk,'coefficient/1','Mult0/1', 'autorouting', 'on'); add_line(blk,'coefficient/1','Mult1/1', 'autorouting', 'on'); add_line(blk,'Register3/1','d_out/1', 'autorouting', 'on'); add_line(blk,'AddSub0/1','Mult0/2', 'autorouting', 'on'); add_line(blk,'Mult0/1','real/1', 'autorouting', 'on'); add_line(blk,'AddSub1/1','Mult1/2', 'autorouting', 'on'); add_line(blk,'Mult1/1','imag/1', 'autorouting', 'on'); % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); end % fir_dbl_tap_init
github
mstrader/mlib_devel-master
get_param_state.m
.m
mlib_devel-master/casper_library/get_param_state.m
1,994
utf_8
77eacf7f9e7eed2d656b20cdfe419cf9
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://casper.berkeley.edu % % Copyright (C) 2010 William Mallard % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [ param_state ] = get_param_state(cursys, param_name) % Check if a mask parameter is enabled or disabled. mask_names = get_param(cursys, 'MaskNames'); param_index = ismember(mask_names, param_name); mask_enables = get_param(cursys, 'MaskEnables'); param_state = mask_enables{param_index}; end
github
mstrader/mlib_devel-master
get_var.m
.m
mlib_devel-master/casper_library/get_var.m
2,305
utf_8
435a2de952a1862c45f78c3bd3f88368
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006-2007 David MacMahon, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function value = get_var(varname, varargin) % Find the value of varname in varargin. If varname is not found, looks % for 'defaults' and tries to find varname in there. If any of this fails, % return Nan. % % value = get_var(varname, varargin) % % varname = the variable name to retrieve (as a string). % varargin = {'varname', value, ...} pairs i = find(strcmp(varname,varargin)); if i >= 1, value = varargin{i+1}; else i = find(strcmp('defaults',varargin)); if i >= 1, value = get_var(varname,varargin{i+1}{:}); else value = nan; end end
github
mstrader/mlib_devel-master
tostring.m
.m
mlib_devel-master/casper_library/tostring.m
1,006
utf_8
b3d643714b38a14e0d24db55ab592352
%Designed to convert things into strings for populating mask text boxes. %Works with 1D arrays (lists) and strings or single values. % YMMV with multidimensional arrays or matrices. function string = tostring( something, precision ) prec = 32; if nargin > 1, if precision > 50, disp(['tostring: maximum precision when converting to string is 50 digits,',precision,' provided']); clog(['tostring: maximum precision when converting to string is 50 digits,',precision,' provided'], 'error'); end prec = precision; end if isa(something, 'char'), string = something; return; end if isa(something, 'numeric'), if length(something)>1, string = ['[',num2str(something,prec),']']; return; else, string = num2str(something,prec); return; end end disp(['tostring: Data passed (', something, ') not numeric nor string']); clog(['tostring: Data passed (', something, ') not numeric nor string'],'error')
github
mstrader/mlib_devel-master
reorder_init.m
.m
mlib_devel-master/casper_library/reorder_init.m
22,713
utf_8
2eec3baa33bc583d333266b32d5c9e1f
% Initialize and configure the reorder block. % % reorder_init(blk, varargin) % % blk = The block to be initialize. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % map = The desired output order. % map_latency = The latency of the map block. % bram_latency = The latency of buffer BRAM blocks. % n_inputs = The number of parallel inputs to be reordered. % double_buffer = Whether to use two buffers to reorder data (instead of % doing it in-place). % bram_map = Whether to use BlockRAM for address mapping (instead of % distributed RAM. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % Meerkat Radio Telescope Project % % http://www.kat.ac.za % % Copyright (C) 2011, 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function reorder_init(blk, varargin) log_group = 'reorder_init_debug'; clog('entering reorder_init', {log_group, 'trace'}); % Declare any default values for arguments you might like. defaults = { ... 'map', [0 7 1 3 2 5 6 4], ... 'n_bits', 0, ... 'map_latency', 2, ... 'bram_latency', 1, ... 'fanout_latency', 0, ... 'n_inputs', 1, ... 'double_buffer', 0, ... 'bram_map', 'on'}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'reorder'); munge_block(blk, varargin{:}); map = get_var('map', 'defaults', defaults, varargin{:}); n_bits = get_var('n_bits', 'defaults', defaults, varargin{:}); map_latency = get_var('map_latency', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); fanout_latency = get_var('fanout_latency', 'defaults', defaults, varargin{:}); n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:}); double_buffer = get_var('double_buffer', 'defaults', defaults, varargin{:}); bram_map = get_var('bram_map', 'defaults', defaults, varargin{:}); mux_latency = 1; yinc = 20; delete_lines(blk); if isempty(map), clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting reorder_init', {log_group, 'trace'}); return; end %if map_length = length(map); map_bits = ceil(log2(map_length)); if double_buffer == 1, order = 2; else, order = compute_order(map); end order_bits = ceil(log2(order)); if (strcmp('on',bram_map)), map_memory_type = 'Block RAM'; else, map_memory_type = 'Distributed memory'; end % if we are using BRAM for mapping then we need to optimise for Speed, otherwise want to optimise Space as % distributed RAM inherently fast if strcmp(bram_map, 'on'), optimize = 'Speed'; else, optimize = 'Area'; end if (double_buffer < 0 || double_buffer > 1) , clog('Double Buffer must be 0 or 1', {log_group, 'error'}); error('Double Buffer must be 0 or 1'); end % Non-power-of-two maps could be supported by adding a counter an a % comparitor, rather than grouping the map and address count into one % counter. if 2^map_bits ~= map_length, clog('Reorder currently only supports maps which are 2^? long.', {log_group, 'error'}) error('Reorder currently only supports maps which are 2^? long.') end % make fanout as low as possible (2) rep_latency = log2(n_inputs); % en stuff % delays on way into buffer depend on double buffering if double_buffer == 0, if order == 2, pre_delay = map_latency + mux_latency; else, pre_delay = 1 + mux_latency + map_latency; end else, pre_delay = map_latency; end reuse_block(blk, 'en', 'built-in/inport', 'Position', [25 43 55 57], 'Port', '2'); reuse_block(blk, 'delay_we0', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'off', 'latency', num2str(pre_delay+rep_latency), 'Position', [305 40 345 60]); add_line(blk, 'en/1', 'delay_we0/1'); reuse_block(blk, 'delay_we1', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'off', 'latency', num2str(pre_delay+rep_latency), 'Position', [305 80 345 100]); add_line(blk, 'en/1', 'delay_we1/1'); reuse_block(blk, 'delay_we2', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'off', 'latency', num2str(pre_delay), 'Position', [305 120 345 140]); add_line(blk, 'en/1', 'delay_we2/1'); reuse_block(blk, 'delay_valid', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'Position', [860 80 900 100], 'latency', num2str(bram_latency+(double_buffer*2)+fanout_latency)); add_line(blk, 'delay_we1/1', 'delay_valid/1'); reuse_block(blk, 'valid', 'built-in/outport', 'Position', [965 82 995 98], 'Port', '2'); add_line(blk, 'delay_valid/1', 'valid/1'); reuse_block(blk, 'we_replicate', 'casper_library_bus/bus_replicate', ... 'latency', num2str(rep_latency), 'replication', num2str(n_inputs), 'misc', 'off', ... 'Position', [490 119 530 141]); add_line(blk, 'delay_we2/1', 'we_replicate/1'); reuse_block(blk, 'we_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(n_inputs), ... 'outputWidth', '1', 'outputBinaryPt', '0', 'outputArithmeticType', '2', ... 'Position', [585 119 635 119+(yinc*n_inputs)]); add_line(blk, 'we_replicate/1', 'we_expand/1'); % sync stuff % delay value here is time into BRAM + time for one vector + time out of BRAM reuse_block(blk, 'sync', 'built-in/inport', 'Position', [25 3 55 17], 'Port', '1'); reuse_block(blk, 'pre_sync_delay', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'off', 'Position', [305 0 345 20], 'latency', num2str(pre_delay+rep_latency)); add_line(blk, 'sync/1', 'pre_sync_delay/1'); reuse_block(blk, 'or', 'xbsIndex_r4/Logical', ... 'logical_function', 'OR', 'Position', [375 19 400 46]); add_line(blk, 'delay_we0/1', 'or/2'); add_line(blk, 'pre_sync_delay/1', 'or/1'); reuse_block(blk, 'sync_delay_en', 'casper_library_delays/sync_delay_en', ... 'Position', [530 5 690 25], 'DelayLen', num2str(map_length)); add_line(blk, 'or/1', 'sync_delay_en/2'); add_line(blk, 'pre_sync_delay/1', 'sync_delay_en/1'); reuse_block(blk, 'post_sync_delay', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'on', 'Position', [860 5 900 25], 'latency', num2str(bram_latency+(double_buffer*2)+fanout_latency)); add_line(blk, 'sync_delay_en/1', 'post_sync_delay/1'); reuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [965 7 995 23], 'Port', '1'); add_line(blk, 'post_sync_delay/1', 'sync_out/1'); base = 160 + (n_inputs-1)*yinc; %Ports for cnt=1:n_inputs, % Ports reuse_block(blk, ['din', num2str(cnt-1)], 'built-in/inport', ... 'Position', [680 base+80*(cnt-1)+43 710 base+80*(cnt-1)+57], 'Port', num2str(2+cnt)); reuse_block(blk, ['delay_din', num2str(cnt-1)], 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'Position', [760 base+80*(cnt-1)+40 800 base+80*(cnt-1)+60], 'latency', num2str(pre_delay+rep_latency)); add_line(blk, ['din', num2str(cnt-1),'/1'], ['delay_din', num2str(cnt-1),'/1']); reuse_block(blk, ['dout', num2str(cnt-1)], 'built-in/outport', ... 'Position', [965 base+80*(cnt-1)+43 995 base+80*(cnt-1)+57], 'Port', num2str(2+cnt)); end %for if order ~= 1, if order == 2, reuse_block(blk, 'Counter', 'xbsIndex_r4/Counter', ... 'Position', [95 base 145 base+55], 'n_bits', num2str(map_bits + order_bits), 'cnt_type', 'Free Running', ... 'use_behavioral_HDL', 'off', 'implementation', 'Fabric', 'arith_type', 'Unsigned', ... 'en', 'on', 'rst', 'on'); add_line(blk, 'sync/1', 'Counter/1'); add_line(blk, 'en/1', 'Counter/2'); reuse_block(blk, 'Slice2', 'xbsIndex_r4/Slice', ... 'Position', [170 base+35 200 base+55], 'mode', 'Lower Bit Location + Width', ... 'nbits', num2str(map_bits)); add_line(blk, 'Counter/1', 'Slice2/1'); if double_buffer == 0, latency = (order-1)*map_latency; else, latency = (order-1)*map_latency + rep_latency; end reuse_block(blk, 'delay_sel', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'Position', [305 base 345 base+20], 'latency', num2str(latency)); reuse_block(blk, 'delay_d0', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'Position', [305 base+35 345 base+55], 'latency', num2str(latency)); add_line(blk, 'Slice2/1', 'delay_d0/1'); end %if order == 2 reuse_block(blk, 'addr_replicate', 'casper_library_bus/bus_replicate', ... 'latency', num2str(rep_latency), 'replication', num2str(n_inputs), 'misc', 'off', ... 'Position', [490 base 530 base+22]); reuse_block(blk, 'addr_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(n_inputs), ... 'outputWidth', num2str(map_bits), 'outputBinaryPt', '0', 'outputArithmeticType', '0', ... 'Position', [585 base 635 base+(yinc*n_inputs)]); add_line(blk, 'addr_replicate/1', 'addr_expand/1'); end %if order % Special case for reorder of order 1 (just delay) if order == 1, for cnt=1:n_inputs, % Delays reuse_block(blk, ['delay_din_bram', num2str(cnt-1)], 'casper_library_delays/delay_bram_en_plus', ... 'DelayLen', 'length(map)', 'bram_latency', 'bram_latency+fanout_latency', ... 'Position', [850 base+80*(cnt-1)+40 915 base+80*(cnt-1)+60]); % Wires add_line(blk, ['delay_din', num2str(cnt-1),'/1'], ['delay_din_bram', num2str(cnt-1),'/1']); add_line(blk, ['delay_din_bram', num2str(cnt-1),'/1'], ['dout', num2str(cnt-1),'/1']); add_line(blk, ['we_expand/',num2str(cnt)], ['delay_din_bram', num2str(cnt-1),'/2']); end %for % Case for order != 1, single-buffered elseif double_buffer == 0, % Add Dynamic Blocks and wires for cnt=1:n_inputs, % BRAMS bram_name = ['buf', num2str(cnt-1)]; % if we dont specify a valid bit width, use generic BRAMs if n_bits == 0, reuse_block(blk, bram_name, 'xbsIndex_r4/Single Port RAM', ... 'depth', num2str(2^map_bits), 'optimize', 'Speed', ... 'write_mode', 'Read Before Write', 'latency', num2str(bram_latency+fanout_latency), ... 'Position', [845 base+80*(cnt-1)-17+40 910 base+80*(cnt-1)+77]); else, %otherwise use brams that help reduce fanout m = floor(n_bits/64); n_bits_in = ['[repmat(64, 1, ', num2str(m),')]']; if m ~= (n_bits/64), n = m+1; n_bits_in = ['[', n_bits_in, ', ', num2str(n_bits - (m*64)),']']; else, n = m; end bin_pts = ['[zeros(1, ', num2str(n),')]']; init_vector = ['[zeros(', num2str(2^map_bits), ',', num2str(n), ')]']; reuse_block(blk, bram_name, 'casper_library_bus/bus_single_port_ram', ... 'n_bits', n_bits_in, 'bin_pts', bin_pts, 'init_vector', init_vector, ... 'max_fanout', '1', 'mem_type', 'Block RAM', 'bram_optimization', 'Speed', ... 'async', 'off', 'misc', 'off', ... 'bram_latency', num2str(bram_latency), 'fan_latency', num2str(fanout_latency), ... 'addr_register', 'on', 'addr_implementation', 'core', ... 'din_register', 'on', 'din_implementation', 'behavioral', ... 'we_register', 'on', 'we_implementation', 'core', ... 'en_register', 'off', 'en_implementation', 'behavioral', ... 'Position', [845 base+80*(cnt-1)-17+40 910 base+80*(cnt-1)+77]); end add_line(blk, ['we_expand/',num2str(cnt)], [bram_name,'/3']); add_line(blk, ['addr_expand/',num2str(cnt)], [bram_name,'/1']); add_line(blk, ['delay_din',num2str(cnt-1),'/1'], [bram_name,'/2']); add_line(blk, [bram_name,'/1'], ['dout',num2str(cnt-1),'/1']); end %special case for order of 2 if order == 2, reuse_block(blk, 'Slice1', 'xbsIndex_r4/Slice', ... 'Position', [170 base 200 base+20], 'mode', 'Upper Bit Location + Width', ... 'nbits', num2str(order_bits)); add_line(blk, 'Counter/1', 'Slice1/1'); add_line(blk, 'Slice1/1', 'delay_sel/1'); reuse_block(blk, 'Mux', 'xbsIndex_r4/Mux', ... 'Position', [415 base 440 base+10+20*order], 'inputs', num2str(order), 'latency', num2str(mux_latency)); add_line(blk, 'delay_sel/1', 'Mux/1'); add_line(blk, 'delay_d0/1', 'Mux/2'); add_line(blk, 'Mux/1', 'addr_replicate/1'); % Add Maps for cnt=1:order-1, mapname = ['map', num2str(cnt)]; reuse_block(blk, mapname, 'xbsIndex_r4/ROM', ... 'depth', num2str(map_length), 'initVector', 'map', 'latency', num2str(map_latency), ... 'arith_type', 'Unsigned', 'n_bits', num2str(map_bits), 'bin_pt', '0', 'optimize', optimize, ... 'distributed_mem', map_memory_type, 'Position', [230 base+50*cnt+35 270 base+50*cnt+55]); reuse_block(blk, ['delay_',mapname], 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'Position', [305 base+50*cnt+35 345 base+50*cnt+55], 'latency', [num2str((order-(cnt+1))*map_latency)]); end for cnt=1:order-1, mapname = ['map',num2str(cnt)]; prevmapname = ['map',num2str(cnt-1)]; if cnt == 1, add_line(blk, 'Slice2/1', 'map1/1'); else, add_line(blk, [prevmapname,'/1'], [mapname,'/1'], 'autorouting', 'on'); end add_line(blk, [mapname,'/1'], ['delay_',mapname,'/1']); add_line(blk, ['delay_',mapname,'/1'], ['Mux/',num2str(cnt+2)]); end %for % for order greater than 2, we use a more optimal bram configuration else, reuse_block(blk, 'Counter', 'xbsIndex_r4/Counter', ... 'n_bits', num2str(map_bits), 'cnt_type', 'Free Running', ... 'use_behavioral_HDL', 'off', 'implementation', 'Fabric', 'arith_type', 'Unsigned', 'en', 'on', 'rst', 'on', ... 'Position', [80 base+300 120 base+340]); add_line(blk, 'sync/1', 'Counter/1'); add_line(blk, 'en/1', 'Counter/2'); % logic to cater for resyncing reuse_block(blk, 'dsync', 'xbsIndex_r4/Delay', 'reg_retiming', 'off', 'latency', '1', 'Position', [85 base+50 115 base+70]); add_line(blk, 'sync/1', 'dsync/1'); reuse_block(blk, 'msb', 'xbsIndex_r4/Slice', 'boolean_output', 'on', ... 'Position', [135 base+65 160 base+85], 'mode', 'Upper Bit Location + Width', 'nbits', '1'); add_line(blk, 'Counter/1', 'msb/1'); reuse_block(blk, 'edge_detect', 'casper_library_misc/edge_detect', ... 'edge', 'Falling', 'polarity', 'Active High', 'Position', [185 base+65 230 base+85]); add_line(blk, 'msb/1', 'edge_detect/1'); reuse_block(blk, 'map_src', 'xbsIndex_r4/Register', ... 'en', 'on', 'rst', 'on', 'Position', [265 base+40 305 base+80]); add_line(blk, 'edge_detect/1', 'map_src/1'); add_line(blk, 'dsync/1', 'map_src/2'); add_line(blk, 'edge_detect/1', 'map_src/3'); reuse_block(blk, 'dmap_src', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', 'latency', num2str(map_latency), ... 'Position', [330 base+50 370 base+70]); add_line(blk, 'map_src/1', 'dmap_src/1'); reuse_block(blk, 'map_mux', 'xbsIndex_r4/Mux', 'latency', num2str(mux_latency), 'inputs', '2', ... 'Position', [440 base+176 470 base+264]); add_line(blk, 'dmap_src/1', 'map_mux/1'); add_line(blk, 'map_mux/1', 'addr_replicate/1'); % lookup of current map reuse_block(blk, 'daddr0', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', 'latency', '1', 'Position', [265 base+310 300 base+330]); add_line(blk, 'Counter/1', 'daddr0/1'); % memory holding current map reuse_block(blk, 'current_map', 'casper_library_bus/bus_dual_port_ram', ... 'n_bits', num2str(map_bits), ... 'bin_pts', '0', ... 'init_vector', ['[0:',num2str((2^map_bits)-1),']'''], ... 'max_fanout', '1', ... 'mem_type', map_memory_type, 'bram_optimization', 'Speed', ... 'async_a', 'off', 'async_b', 'off', 'misc', 'off', ... 'bram_latency', num2str(map_latency), ... 'fan_latency', num2str(1 + map_latency + 1), ... 'addra_register', 'on', 'addra_implementation', 'core', ... 'dina_register', 'off', 'dina_implementation', 'behavioral', ... 'wea_register', 'on', 'wea_implementation', 'core', ... 'addrb_register', 'off', 'addra_implementation', 'behavioral', ... 'dinb_register', 'off', 'dinb_implementation', 'behavioral', ... 'web_register', 'off', 'web_implementation', 'behavioral', ... 'Position', [320 base+150 380 base+280]); add_line(blk, 'daddr0/1', 'current_map/4'); add_line(blk, 'current_map/2', 'map_mux/3'); reuse_block(blk, 'term', 'built-in/Terminator', 'Position', [395 base+175 415 base+195]); add_line(blk, 'current_map/1', 'term/1'); if strcmp(bram_map, 'on'), reuse_block(blk, 'blank', 'xbsIndex_r4/Constant', ... 'const', '0', 'arith_type', 'Unsigned', 'n_bits', num2str(map_bits), 'bin_pt', '0', ... 'explicit_period', 'on', 'period', '1', 'Position', [240 base+237 255 base+253]); add_line(blk, 'blank/1', 'current_map/5'); reuse_block(blk, 'never', 'xbsIndex_r4/Constant', ... 'const', '0', 'arith_type', 'Boolean', 'explicit_period', 'on', 'period', '1', ... 'Position', [265 base+257 280 base+273]); add_line(blk, 'never/1', 'current_map/6'); end reuse_block(blk, 'den', 'xbsIndex_r4/Delay', 'reg_retiming', 'off', ... 'latency', num2str(1 + map_latency), ... 'Position', [265 base+400 385 base+420]); add_line(blk, 'en/1', 'den/1'); add_line(blk, 'den/1', 'current_map/3', 'autorouting', 'on'); reuse_block(blk, 'daddr1', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'latency', num2str(map_latency), ... 'Position', [320 base+310 380 base+330]); add_line(blk, 'daddr0/1', 'daddr1/1'); add_line(blk, 'daddr1/1', 'map_mux/2'); add_line(blk, 'daddr1/1', 'current_map/1', 'autorouting', 'on'); % memory holding change to current map reuse_block(blk, 'map_mod', 'xbsIndex_r4/ROM', ... 'depth', num2str(map_length), 'initVector', 'map', 'latency', num2str(map_latency), ... 'arith_type', 'Unsigned', 'n_bits', num2str(map_bits), 'bin_pt', '0', 'optimize', optimize, ... 'distributed_mem', map_memory_type, 'Position', [520 base+194 570 base+246]); add_line(blk, 'map_mux/1', 'map_mod/1'); reuse_block(blk, 'dnew_map', 'xbsIndex_r4/Delay', 'reg_retiming', 'on', ... 'latency', '1', 'Position', [620 base+210 645 base+230]); add_line(blk, 'map_mod/1', 'dnew_map/1'); add_line(blk, 'dnew_map/1', 'current_map/2', 'autorouting', 'on'); end %if order == 2 % case for order > 1, double-buffered else, %TODO fanout for signals into wr_addr and rw_mode for many inputs not handled reuse_block(blk, 'Slice1', 'xbsIndex_r4/Slice', ... 'Position', [170 base 200 base+20], 'mode', 'Upper Bit Location + Width', ... 'nbits', '1'); add_line(blk, 'Counter/1', 'Slice1/1'); add_line(blk, 'Slice1/1', 'delay_sel/1'); % Add Dynamic Blocks for cnt=1:n_inputs, % BRAMS reuse_block(blk, ['dbl_buffer',num2str(cnt-1)], 'casper_library_reorder/dbl_buffer', ... 'Position', [845 base+80*(cnt-1)-17+40 910 base+80*(cnt-1)+77], 'depth', num2str(2^map_bits), ... 'latency', num2str(bram_latency+fanout_latency)); end % Add Maps mapname = 'map1'; reuse_block(blk, mapname, 'xbsIndex_r4/ROM', ... 'depth', num2str(map_length), 'initVector', 'map', 'latency', num2str(map_latency), ... 'arith_type', 'Unsigned', 'n_bits', num2str(map_bits), 'bin_pt', '0', ... 'distributed_mem', map_memory_type, 'Position', [230 base+15+70 270 base+35+70]); add_line(blk, 'Slice2/1', 'map1/1'); add_line(blk, 'map1/1', 'addr_replicate/1'); % Add dynamic wires for cnt=1:n_inputs bram_name = ['dbl_buffer',num2str(cnt-1)]; add_line(blk, 'delay_d0/1', [bram_name,'/2']); add_line(blk, ['addr_expand/',num2str(cnt)], [bram_name,'/3']); add_line(blk, ['we_expand/',num2str(cnt)], [bram_name,'/5']); add_line(blk, 'delay_sel/1', [bram_name,'/1']); add_line(blk, ['delay_din',num2str(cnt-1),'/1'], [bram_name,'/4']); add_line(blk, [bram_name,'/1'], ['dout',num2str(cnt-1),'/1']); end end clean_blocks(blk); fmtstr = sprintf('order=%d', order); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting reorder_init', {log_group, 'trace'});
github
mstrader/mlib_devel-master
bus_expand_callback.m
.m
mlib_devel-master/casper_library/bus_expand_callback.m
2,941
utf_8
a9578b135a2cf3ba7b12b59590d8ad04
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Meerkat radio telescope project % % www.kat.ac.za % % Copyright (C) Andrew Martens 2011 % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bus_expand_callback() clog('entering bus_expand_callback', 'trace'); blk = gcb; check_mask_type(blk, 'bus_expand'); outputToWorkspace = get_param(blk, 'outputToWorkspace'); mode = get_param(blk, 'mode'); outputWidth = str2double(get_param(blk, 'outputWidth')); mask_names = get_param(blk, 'MaskNames'); mask_enables = get_param(blk, 'MaskEnables'); if strcmp(mode, 'divisions of arbitrary size'), en = 'off'; set_param(blk, 'outputNum', num2str(length(outputWidth))); else en = 'on'; end mask_enables{ismember(mask_names, 'outputNum')} = en; mask_enables{ismember(mask_names, 'variablePrefix')} = outputToWorkspace; mask_enables{ismember(mask_names, 'outputToModelAsWell')} = outputToWorkspace; set_param(gcb, 'MaskEnables', mask_enables); temp = get_param(blk, 'MaskPrompts'); if strcmp(en, 'off'), temp(3) = {'Output width [msb ... lsb]:'}; temp(4) = {'Output binary point position [msb ... lsb]:'}; temp(5) = {'Output arithmetic type (ufix=0, fix=1, bool=2) [msb ... lsb]:'}; else temp(3) = {'Output width:'}; temp(4) = {'Output binary point position:'}; temp(5) = {'Output arithmetic type (ufix=0, fix=1, bool=2):'}; end set_param(blk, 'MaskPrompts', temp); clog('exiting bus_expand_callback', 'trace');
github
mstrader/mlib_devel-master
update_casper_blocks.m
.m
mlib_devel-master/casper_library/update_casper_blocks.m
5,609
utf_8
c520d2a32e492de75f7aec5808065f24
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2013 David MacMahon % % % 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 function updates casper_library and xps_library blocks in sys using the % most recent library versions. Mask parameters are copied over whenever % possible. If sys is a block diagram and is not a library, its solver % parameters are updated using xlConfigureSolver. % % varargin is for experts only! It can be used to specify extra options to % find_system. function update_casper_blocks(sys, varargin) % Clear last dumped exception to ensure that all exceptions are shown. dump_exception([]); % For now, we require that sys is either an unlinked subsytem or a % block_diagram type = get_param(sys,'Type'); if strcmpi(type, 'block') % Make sure it is subsystem that is not linked to a library block_type = get_param(sys,'BlockType'); if ~strcmpi(block_type, 'SubSystem') error('Block %s is not a SubSystem', sys); end link_status = get_param(sys,'LinkStatus'); if ~strcmpi(link_status, 'none') error('SubSystem block %s appears to be linked to a library', sys); end elseif strcmpi(type, 'block_diagram') % If it is not a library if strcmpi(get_param(sys, 'LibraryType'), 'None') fprintf('configuring solver for block diagram %s...\n', sys); xlConfigureSolver(sys); end else error('%s is not a block diagram or a block', sys); end % First, deal with the special cases of blocks whose names % have changed. These can cause broken library links which % will prevent the rest of this script finding these blocks. special_blocks = {'xps_library/XSG core config', ... 'xps_library/software register', ... 'xps_library/Software BRAM', ... 'xps_library/Software FIFO', ... }; for n = 1:length(special_blocks) blks = find_system(sys, 'LookUnderMasks', 'all', ... 'SourceBlock', special_blocks{n}); for m = 1:length(blks) set_param(blks{m}, 'SourceBlock', ... casper_library_forwarding_table(special_blocks{n})); end end fprintf('searching for CASPER blocks to update in %s...', sys); ref_blks = find_system(sys, ... 'RegExp', 'on', ... 'LookUnderMasks', 'all', ... 'FollowLinks', 'off', ... varargin{:}, ... 'ReferenceBlock', '(casper|xps)_library'); %fprintf('found %d blocks with ReferenceBlock\n', length(ref_blks)); %for k = 1:length(ref_blks) % fprintf(' %3d %s\n', k, ref_blks{k}); %end anc_blks = find_system(sys, ... 'RegExp', 'on', ... 'LookUnderMasks', 'all', ... 'FollowLinks', 'off', ... varargin{:}, ... 'AncestorBlock', '(casper|xps)_library'); %fprintf('found %d blocks with AncestorBlock\n', length(anc_blks)); %for k = 1:length(anc_blks) % fprintf(' %3d %s\n', k, anc_blks{k}); %end % Concatenate the lists of blocks then sort. Sorting the list optimizes the % culling process that follows. blks = sort([ref_blks; anc_blks]); % Even though we say "FollowLinks=off", find_system will still search through % block's with disabled links. To make sure we don't update blocks inside % subsystems with disabled links, we need to cull the list of blocks. For % each block found, we remove any blocks that start with "block_name/". keepers = ones(size(blks)); for k = 1:length(blks) % If this block has not yet been culled, cull its sub-blocks. (If it has % already been culled, then its sub-blocks have also been culled already.) if keepers(k) pattern = ['^', blks{k}, '/']; keepers(find(cellfun('length', regexp(blks, pattern)))) = 0; end end blks = blks(find(keepers)); fprintf('found %d\n', length(blks)); for k = 1:length(blks) fprintf('updating block %s...\n', blks{k}); update_casper_block(blks{k}); end % Don't show done message for zero blocks if length(blks) > 0 fprintf('done updating %d blocks in %s\n', length(blks), sys); end end
github
mstrader/mlib_devel-master
reuse_block.m
.m
mlib_devel-master/casper_library/reuse_block.m
6,803
utf_8
f620e6db62266a70cf21654582ac4a59
% Instantiate a block named 'name' from library template 'refblk', % if no such block already exists. Otherwise, just configure that % block with any parameter, value pairs provided in varargin. % If refblk is has an '_init' function, this may still need to be % called after this function is called. % % reuse_block(blk, name, refblk, varargin) % % blk = the overarching system % name = the name of the block to instantiate % refblk = the library block to instantiate % varargin = {'varname', 'value', ...} pairs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % MeerKAT Radio Telescope Project % % www.kat.ac.za % % Copyright (C) 2013 Andrew Martens (meerKAT) % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function reuse_block(blk, name, refblk, varargin) % Wrap whole function in try/catch try existing_blks = find_system(blk, ... 'lookUnderMasks', 'all', 'FollowLinks','on', ... 'SearchDepth', 1, 'Name', name); % Just add block straight away if does not yet exist if isempty(existing_blks) add_block(refblk, [blk,'/',name], 'Name', name, varargin{:}); % Done! return end % If find_system returned more than one block (should "never" happen, but % sometimes it does!) if length(existing_blks) > 1 % Get their handles to see whether they are really the same block handles = cell(size(existing_blks)); for k = 1:length(existing_blks) handles{k} = num2str(get_param(existing_blks{k}, 'Handle')); end % If more than one handle (should "really never" happen...) if length(unique(handles)) > 1 error('casper:MultipleBlocksForName', ... 'More than one block in "%s" has name "%s"', blk, name); end end % A block with that name does exist, so re-use it existing_blk = existing_blks{1}; %check Link status link_status = get_param(existing_blk, 'StaticLinkStatus'); %inactive link (link disabled but not broken) so get AncestorBlock if strcmp(link_status, 'inactive'), source = get_param(existing_blk, 'AncestorBlock'); %resolved link (link in place) so get ReferenceBlock elseif strcmp(link_status, 'resolved'), source = get_param(existing_blk, 'ReferenceBlock'); %no link (broken link, never existed, or built-in) so get block type elseif strcmp(link_status, 'none'), block_type = get_param(existing_blk, 'BlockType'); %if weird (subsystem or s-function not from library) if strcmp(block_type, 'SubSystem') || strcmp(block_type, 'S-Function'), clog([name,': built-in/',block_type,' so forcing replacement'], 'reuse_block_debug'); source = ''; else %assuming built-in source = strcat('built-in/',block_type); end %implicit library block elseif strcmp(link_status, 'implicit'), anc_block = get_param(existing_blk, 'AncestorBlock'); %we have a block in the library derived from another block if ~isempty(anc_block), source = anc_block; %we have a block without a source or built-in else, block_type = get_param(existing_blk, 'BlockType'); %if weird (subsystem or s-function not from library) if strcmp(block_type, 'SubSystem') || strcmp(block_type, 'S-Function'), clog([name,': built-in/',block_type,' so forcing replacement'], 'reuse_block_debug'); source = ''; else, %assuming built-in source = strcat('built-in/',block_type); end end %if ~isempty else, clog([name,' not a library block and not built-in so force replace'], 'reuse_block_debug'); source = ''; end % If source is a cell, take its first element so we can log it if iscell(source) % TODO Warn if length(source) > 1? source = source{1}; end % Change newlines in source to spaces source = strrep(source, char(10), ' '); % Do case-insensitive string comparison if strcmpi(source, refblk), msg = sprintf('%s is already a "%s" so just setting parameters', name, source); clog(msg, {'reuse_block_debug', 'reuse_block_reuse'}); if ~isempty(varargin), set_param([blk,'/',name], varargin{:}); end else, if evalin('base','exist(''casper_force_reuse_block'')') ... && evalin('base','casper_force_reuse_block') msg = sprintf('%s is a "%s" and want "%s" but reuse is being forced', name, source, refblk); % Log as reuse_block_replace even though reuse is being forced clog(msg, {'reuse_block_debug', 'reuse_block_replace'}); set_param([blk,'/',name], varargin{:}); else msg = sprintf('%s is a "%s" but want "%s" so replacing', name, source, refblk); clog(msg, {'reuse_block_debug', 'reuse_block_replace'}); delete_block([blk,'/',name]); add_block(refblk, [blk,'/',name], 'Name', name, varargin{:}); end end catch ex dump_and_rethrow(ex) end % try/catch end % function
github
mstrader/mlib_devel-master
bus_register_init.m
.m
mlib_devel-master/casper_library/bus_register_init.m
8,416
utf_8
56479e2951c05003310a5480efa71460
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bus_register_init(blk, varargin) log_group = 'bus_register_init_debug'; clog('entering bus_register_init', {log_group, 'trace'}); defaults = { ... 'n_bits', [8], ... 'reset', 'on', ... 'cmplx', 'on', ... 'enable', 'on', ... 'misc', 'on'}; check_mask_type(blk, 'bus_register'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); xpos = 50; xinc = 80; ypos = 50; yinc = 50; port_w = 30; port_d = 14; bus_expand_w = 50; bus_compress_w = 50; reg_w = 50; reg_d = 60; del_w = 30; del_d = 20; reset = get_var('reset', 'defaults', defaults, varargin{:}); enable = get_var('enable', 'defaults', defaults, varargin{:}); cmplx = get_var('cmplx', 'defaults', defaults, varargin{:}); n_bits = get_var('n_bits', 'defaults', defaults, varargin{:}); misc = get_var('misc', 'defaults', defaults, varargin{:}); len = length(n_bits); delete_lines(blk); %default state, do nothing if isempty(n_bits), clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_register_init', {log_group, 'trace'}); return; end if strcmp(cmplx,'on'), n_bits = 2*n_bits; end %input ports port_no = 1; ypos_tmp = ypos + reg_d*len/2; reuse_block(blk, 'din', 'built-in/inport', ... 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + reg_d*len; port_no = port_no + 1; if strcmp(reset, 'on'), reuse_block(blk, 'rst', 'built-in/inport', ... 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + reg_d*len; port_no = port_no + 1; end if strcmp(enable, 'on'), reuse_block(blk, 'en', 'built-in/inport', ... 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + reg_d*len; port_no = port_no + 1; end if strcmp(misc, 'on'), reuse_block(blk, 'misci', 'built-in/inport', ... 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); end xpos = xpos + xinc + port_w/2; ypos_tmp = ypos + reg_d*len/2; %reset ypos %data bus expand reuse_block(blk, 'din_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', ... 'outputWidth', ['[',num2str(n_bits),']'], ... 'outputBinaryPt', ['[',num2str(zeros(1, length(n_bits))),']'], ... 'outputArithmeticType', ['[',num2str(zeros(1, length(n_bits))),']'], ... 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-reg_d*len/2 xpos+bus_expand_w/2 ypos_tmp+reg_d*len/2]); add_line(blk, 'din/1', 'din_expand/1'); ypos_tmp = ypos_tmp + reg_d*len + yinc; %reset bus expand if strcmp(reset, 'on'), reuse_block(blk, 'rst_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', ... 'outputNum', num2str(length(n_bits)), ... 'outputWidth', '1', 'outputBinaryPt', '0', ... 'outputArithmeticType', '2', 'show_format', 'on', ... 'outputToWorkspace', 'off', 'variablePrefix', '', ... 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-reg_d*len/2 xpos+bus_expand_w/2 ypos_tmp+reg_d*len/2]); add_line(blk, 'rst/1', 'rst_expand/1'); ypos_tmp = ypos_tmp + reg_d*len + yinc; end %enable bus expand if strcmp(enable, 'on'), reuse_block(blk, 'en_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', ... 'outputNum', num2str(length(n_bits)), ... 'outputWidth', '1', 'outputBinaryPt', '0', ... 'outputArithmeticType', '2', 'show_format', 'on', ... 'outputToWorkspace', 'off', 'variablePrefix', '', ... 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-reg_d*len/2 xpos+bus_expand_w/2 ypos_tmp+reg_d*len/2]); add_line(blk, 'en/1', 'en_expand/1'); end xpos = xpos + xinc + bus_expand_w/2; %register layer ypos_tmp = ypos; %reset ypos for index = 1:len, reg_name = ['reg',num2str(index)]; %data reuse_block(blk, reg_name, 'xbsIndex_r4/Register', ... 'rst', reset, 'en', enable, ... 'Position', [xpos-reg_w/2 ypos_tmp xpos+reg_w/2 ypos_tmp+reg_d-20]); ypos_tmp = ypos_tmp + reg_d; add_line(blk, ['din_expand/',num2str(index)], [reg_name,'/1']); port_index = 2; if strcmp(reset, 'on'), add_line(blk, ['rst_expand/',num2str(index)], [reg_name,'/',num2str(port_index)]); port_index=port_index+1; end if strcmp(enable, 'on'), add_line(blk, ['en_expand/',num2str(index)], [reg_name,'/',num2str(port_index)]); end end if strcmp(misc, 'on'), reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ... 'latency', '1', 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)-del_d/2+(port_no-1)*yinc xpos+del_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+(port_no-1)*yinc+del_d/2]); add_line(blk, 'misci/1', 'dmisc/1'); ypos_tmp = ypos_tmp + reg_d; end %create bus again ypos_tmp = ypos + reg_d*len/2; xpos = xpos + xinc + bus_expand_w/2; reuse_block(blk, 'dout_compress', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(len), ... 'Position', [xpos-bus_compress_w/2 ypos_tmp-reg_d*len/2 xpos+bus_compress_w/2 ypos_tmp+reg_d*len/2]); for index = 1:len, add_line(blk, ['reg',num2str(index),'/1'], ['dout_compress/',num2str(index)]); end %output port/s ypos_tmp = ypos + reg_d*len/2; xpos = xpos + xinc + bus_compress_w/2; reuse_block(blk, 'dout', 'built-in/outport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, ['dout_compress/1'], ['dout/1']); ypos_tmp = ypos_tmp + yinc + port_d/2; if strcmp(misc, 'on'), reuse_block(blk, 'misco', 'built-in/outport', ... 'Port', '2', ... 'Position', [xpos-port_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+((port_no-1)*yinc)-port_d/2 xpos+port_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+((port_no-1)*yinc)+port_d/2]); add_line(blk, 'dmisc/1', 'misco/1'); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_register_init', {log_group, 'trace'}); end %function bus_register_init
github
mstrader/mlib_devel-master
dsp48e_bram_vacc_init.m
.m
mlib_devel-master/casper_library/dsp48e_bram_vacc_init.m
3,432
utf_8
b71af83720863c419ea3b9fa21ccfbd4
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://casper.berkeley.edu % % Copyright (C) 2010 William Mallard % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function dsp48e_bram_vacc_init (blk, varargin) % Initialize and configure a simple_bram_vacc block. % % dsp48e_bram_vacc_init(blk, varargin) % % blk = The block to configure. % varargin = {'varname', 'value', ...} pairs. % % Valid varnames: % * vec_len % * arith_type % * bin_pt_in % * n_bits_out % Set default vararg values. defaults = { ... 'vec_len', 8, ... 'arith_type', 'Unsigned', ... 'bin_pt_in', 0, ... 'n_bits_out', 32, ... }; % Skip init script if mask state has not changed. if same_state(blk, 'defaults', defaults, varargin{:}), return end % Verify that this is the right mask for the block. check_mask_type(blk, 'dsp48e_bram_vacc'); % Disable link if state changes from default. munge_block(blk, varargin{:}); % Retrieve input fields. vec_len = get_var('vec_len', 'defaults', defaults, varargin{:}); arith_type = get_var('arith_type', 'defaults', defaults, varargin{:}); bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:}); n_bits_out = get_var('n_bits_out', 'defaults', defaults, varargin{:}); % Validate input fields. if (vec_len < 6), errordlg([blk, ': Vector length must be greater than 5.']); return end if (bin_pt_in < 0), errordlg([blk, ': Binary point must be non-negative.']); return end if (bin_pt_in > n_bits_out), errordlg([blk, ': Input binary point cannot exceed output bit width.']); return end if (n_bits_out < 1), errordlg([blk, ': Bit width must be greater than 0.']); return end if (n_bits_out > 32), errordlg([blk, ': Bit width cannot exceed 32.']); return end % Update sub-block parameters. set_param([blk, '/Reinterpret'], 'arith_type', arith_type) % Save block state to stop repeated init script runs. save_state(blk, 'defaults', defaults, varargin{:});
github
mstrader/mlib_devel-master
bus_mux_init.m
.m
mlib_devel-master/casper_library/bus_mux_init.m
8,977
utf_8
e6b13766a778f08c129db349ec3c5276
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens ([email protected]) % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bus_mux_init(blk, varargin) log_group = 'bus_mux_init_debug'; clog('entering bus_mux_init', {log_group, 'trace'}); defaults = { 'n_inputs', 1, ... 'n_bits', [8 7 3 4], ... 'mux_latency', 0, ... 'cmplx', 'off', ... 'misc', 'off'}; check_mask_type(blk, 'bus_mux'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); xpos = 50; xinc = 150; ypos = 50; yinc = 60; port_w = 30; port_d = 14; muxi_d = 30; bus_expand_w = 60; bus_create_w = 60; mux_w = 50; del_w = 30; del_d = 20; n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:}); n_bits = get_var('n_bits', 'defaults', defaults, varargin{:}); mux_latency = get_var('mux_latency', 'defaults', defaults, varargin{:}); misc = get_var('misc', 'defaults', defaults, varargin{:}); cmplx = get_var('cmplx', 'defaults', defaults, varargin{:}); delete_lines(blk); %default state, do nothing if n_inputs == 0, clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_mux_init', {log_group, 'trace'}); return; end len = length(n_bits); if strcmp(cmplx, 'on'), n_bits = 2*n_bits; end % the mux depth depends on % whether splitting one input, or many if n_inputs == 1, depth = muxi_d*len; else, depth = muxi_d*n_inputs; end % if doing one, number muxes == 1, otherwise == number of elements if n_inputs == 1, n_muxes = 1; else, n_muxes = len; end %%%%%%%%%%%%%%%%%%%% % input port layer % %%%%%%%%%%%%%%%%%%%% xpos = xpos + port_w/2; ypos_tmp = ypos + (n_muxes*muxi_d)/2; reuse_block(blk, 'sel', 'built-in/inport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); % for the data ports, if only one input then are to mux between separate components of the same % bus, otherwise are to mux between components of separate busses ypos_tmp = ypos_tmp + (n_muxes*muxi_d)/2 + yinc; for n = 0:n_inputs-1, ypos_tmp = ypos_tmp + depth/2; reuse_block(blk, ['d',num2str(n)], 'built-in/inport', ... 'Port', num2str(n+2), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + depth/2 + yinc; end %for if strcmp(misc, 'on'), ypos_tmp = ypos + (yinc + (n_muxes*muxi_d)) + max(n_muxes, n_inputs)*(depth + yinc) + del_d/2; reuse_block(blk, 'misci', 'built-in/inport', ... 'Port', num2str(n_inputs+2), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); end xpos = xpos + xinc + port_w/2; %%%%%%%%%%%%%%%%%%%%%%%%% % data bus expand layer % %%%%%%%%%%%%%%%%%%%%%%%%% if n_inputs == 1, inputs = len; else, inputs = n_inputs; end xpos = xpos + bus_expand_w/2; ypos_tmp = ypos + (n_muxes*muxi_d)/2; % one bus_expand for sel input reuse_block(blk, 'sel_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', ... 'outputNum', num2str(n_muxes), ... 'outputWidth', num2str(ceil(log2(inputs))), 'outputBinaryPt', '0', 'outputArithmeticType', '0', ... 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-(n_muxes*muxi_d)/2 xpos+bus_expand_w/2 ypos_tmp+(n_muxes*muxi_d)/2]); add_line(blk, 'sel/1', 'sel_expand/1'); ypos_tmp = ypos_tmp + (n_muxes*muxi_d)/2 + yinc; % one bus_expand block for each input for n = 0:n_inputs-1, ypos_tmp = ypos_tmp + depth/2; reuse_block(blk, ['expand', num2str(n)], 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', ... 'outputWidth', mat2str(n_bits), ... 'outputBinaryPt', ['[',num2str(zeros(1, length(n_bits))),']'], ... 'outputArithmeticType', ['[',num2str(zeros(1, length(n_bits))),']'], ... 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-depth/2 xpos+bus_expand_w/2 ypos_tmp+depth/2]); add_line(blk, ['d', num2str(n), '/1'], ['expand', num2str(n), '/1']); ypos_tmp = ypos_tmp + depth/2 + yinc; end %for xpos = xpos + xinc + bus_expand_w/2; %%%%%%%%%%%%% % mux layer % %%%%%%%%%%%%% xpos = xpos + mux_w/2; ypos_tmp = ypos + (n_muxes*muxi_d) + yinc; for n = 0:n_muxes-1, ypos_tmp = ypos_tmp + depth/2; reuse_block(blk, ['mux', num2str(n)], 'xbsIndex_r4/Mux', ... 'inputs', num2str(inputs), 'latency', num2str(mux_latency), ... 'Position', [xpos-mux_w/2 ypos_tmp-depth/2 xpos+mux_w/2 ypos_tmp+depth/2]); add_line(blk, ['sel_expand/', num2str(n+1)], ['mux', num2str(n), '/1']); % take all mux inputs from single input if n_inputs == 1, for index = 1:len, add_line(blk, ['expand0/',num2str(index)], ['mux0/',num2str(index+1)]); end %for %or take a mux input from each input else, for in_index = 0:n_inputs-1, add_line(blk, ['expand', num2str(in_index), '/', num2str(n+1)], ['mux',num2str(n), '/', num2str(in_index+2)]) end end %if ypos_tmp = ypos_tmp + depth/2 + yinc; end %for n_muxes if strcmp(misc, 'on'), ypos_tmp = ypos + (yinc + (n_muxes*muxi_d)) + max(n_muxes, n_inputs)*(depth + yinc) + del_d/2; reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ... 'latency', num2str(mux_latency), 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); add_line(blk, 'misci/1', 'dmisc/1'); ypos_tmp = ypos_tmp + del_d/2 + yinc; end xpos = xpos + mux_w/2 + xinc; %%%%%%%%%%%%%%%%%%%%%%% % bus creation layer % %%%%%%%%%%%%%%%%%%%%%%% xpos = xpos + bus_create_w/2; ypos_tmp = ypos + (n_muxes*muxi_d)/2; reuse_block(blk, 'd_bussify', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(n_muxes), ... 'Position', [xpos-bus_create_w/2 ypos_tmp-(n_muxes*muxi_d)/2 xpos+bus_create_w/2 ypos_tmp+(n_muxes*muxi_d)/2]); for n = 0:n_muxes-1, add_line(blk, ['mux', num2str(n), '/1'], ['d_bussify/', num2str(n+1)]) end %for xpos = xpos + xinc + bus_create_w/2; %%%%%%%%%%%%%%%%%%%%% % output port layer % %%%%%%%%%%%%%%%%%%%%% xpos = xpos + port_w/2; ypos_tmp = ypos + (n_muxes*muxi_d)/2; reuse_block(blk, 'out', 'built-in/outport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, 'd_bussify/1', 'out/1'); ypos_tmp = ypos + (n_muxes*muxi_d)/2 + yinc; if strcmp(misc, 'on'), ypos_tmp = ypos + (yinc + (n_muxes*muxi_d)) + max(n_muxes, n_inputs)*(depth + yinc) + del_d/2; reuse_block(blk, 'misco', 'built-in/outport', ... 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, 'dmisc/1', 'misco/1'); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_mux_init', {log_group, 'trace'}); end %function bus_mux_init
github
mstrader/mlib_devel-master
set_mask_params.m
.m
mlib_devel-master/casper_library/set_mask_params.m
3,193
utf_8
a43b90f45d40808d05842252739bc372
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2013 David MacMahon % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Function for setting one or more mask parameters. This updates the % block's MaskValues parameter. Unlike using set_param, this does NOT trigger % the mask init script and can be used to set mask parameters from within a % mask init script (e.g. to replace a placeholder value with a calculated % value). Note that param_names and param_values must both be strings OR both % be cell arrays of equal length. % % Typical usage: % % % Passing strings (sets latency=1 in mask) % set_mask_params(gcb, 'latency', '1'); % % % Passing cells (sets latency=1 and n_inputs=4 in mask) % set_mask_params(gcb, {'latency', 'n_inputs'}, {'1', '4'}) function params = set_mask_params(blk, param_names, param_values) % Make sure we are working with cells if ~iscell(param_names) param_names = {param_names}; end if ~iscell(param_values) param_values = {param_values}; end % Make sure lengths agree if length(param_names) ~= length(param_values) error('param_names and param_values must have same length'); end % Get mask names and values mask_names = get_param(blk, 'MaskNames'); mask_values = get_param(blk, 'MaskValues'); % For each parameter being set for param_idx = 1:length(param_names) % Find its index in the mask mask_idx = find(strcmp(mask_names, param_names{param_idx})); if mask_idx % If found, update mask_values with new value mask_values{mask_idx} = param_values{param_idx}; end end % Store updated mask_values set_param(blk, 'MaskValues', mask_values); end
github
mstrader/mlib_devel-master
bus_convert_init.m
.m
mlib_devel-master/casper_library/bus_convert_init.m
12,096
utf_8
6efe30a309718fd9745a244c78282c49
function bus_convert_init(blk, varargin) clog('entering bus_convert_init', 'trace'); % Set default vararg values. % reg_retiming is not an actual parameter of this block, but it is included % in defaults so that same_state will return false for blocks drawn prior to % adding reg_retiming='on' to some of the underlying Delay blocks. defaults = { ... 'n_bits_in', [8 8 8], ... 'bin_pt_in', 8, ... 'type_in', 1, ... 'cmplx', 'off', ... 'n_bits_out', 8, ... 'bin_pt_out', 4, ... 'type_out', 1, ... 'overflow', 1, ... 'quantization', 1, ... 'misc', 'on', ... 'latency', 2, ... 'of', 'on', ... 'reg_retiming', 'on', ... }; check_mask_type(blk, 'bus_convert'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); xpos = 50; xinc = 80; ypos = 50; yinc = 50; port_w = 30; port_d = 14; bus_expand_w = 50; bus_create_w = 50; convert_w = 50; convert_d = 60; del_w = 30; del_d = 20; n_bits_in = get_var('n_bits_in', 'defaults', defaults, varargin{:}); bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:}); type_in = get_var('type_in', 'defaults', defaults, varargin{:}); cmplx = get_var('cmplx', 'defaults', defaults, varargin{:}); n_bits_out = get_var('n_bits_out', 'defaults', defaults, varargin{:}); bin_pt_out = get_var('bin_pt_out', 'defaults', defaults, varargin{:}); type_out = get_var('type_out', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); latency = get_var('latency', 'defaults', defaults, varargin{:}); misc = get_var('misc', 'defaults', defaults, varargin{:}); of = get_var('of', 'defaults', defaults, varargin{:}); delete_lines(blk); %default state, do nothing if isempty(n_bits_in), clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_convert_init','trace'); return; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % check input lists for consistency % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% lenbi = length(n_bits_in); lenpi = length(bin_pt_in); lenti = length(type_in); i = [lenbi, lenpi, lenti]; unique_i = unique(i); compi = unique_i(length(unique_i)); lenbo = length(n_bits_out); lenpo = length(bin_pt_out); lento = length(type_out); lenq = length(quantization); leno = length(overflow); o = [lenbo, lenpo, lento, lenq, leno]; unique_o = unique(o); compo = unique_o(length(unique_o)); too_many_i = length(unique_i) > 2; conflict_i = (length(unique_i) == 2) && (unique_i(1) ~= 1); if too_many_i | conflict_i, error('conflicting component number for input bus'); clog('conflicting component number for input bus', 'error'); end too_many_o = length(unique_o) > 2; conflict_o = (length(unique_o) == 2) && (unique_o(1) ~= 1); if too_many_o | conflict_o, error('conflicting component number for output bus'); clog('conflicting component number for output bus', 'error'); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % autocomplete input lists where necessary % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% comp = compi; %replicate items if needed for a input n_bits_in = repmat(n_bits_in, 1, compi/lenbi); bin_pt_in = repmat(bin_pt_in, 1, compi/lenpi); type_in = repmat(type_in, 1, compi/lenti); %if complex we need to double down on some of these if strcmp(cmplx, 'on'), compi = compi*2; n_bits_in = reshape([n_bits_in; n_bits_in], 1, compi); bin_pt_in = reshape([bin_pt_in; bin_pt_in], 1, compi); type_in = reshape([type_in; type_in], 1, compi); end %replicate items if needed for output compo = comp; n_bits_out = repmat(n_bits_out, 1, comp/lenbo); bin_pt_out = repmat(bin_pt_out, 1, comp/lenpo); type_out = repmat(type_out, 1, comp/lento); overflow = repmat(overflow, 1, comp/leno); quantization = repmat(quantization, 1, comp/lenq); if strcmp(cmplx, 'on'), compo = comp*2; n_bits_out = reshape([n_bits_out; n_bits_out], 1, compo); bin_pt_out = reshape([bin_pt_out; bin_pt_out], 1, compo); type_out = reshape([type_out; type_out], 1, compo); overflow = reshape([overflow; overflow], 1, compo); quantization= reshape([quantization; quantization], 1, compo); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % at this point all input, output lists should match % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% clog(['n_bits_in = ',mat2str(n_bits_in)],'bus_convert_init_debug'); clog(['n_bits_out = ',mat2str(n_bits_out)],'bus_convert_init_debug'); clog(['bin_pt_out = ',mat2str(bin_pt_out)],'bus_convert_init_debug'); clog(['type_out = ',mat2str(type_out)],'bus_convert_init_debug'); clog(['overflow = ',mat2str(overflow)],'bus_convert_init_debug'); clog(['quantization = ',mat2str(quantization)],'bus_convert_init_debug'); clog(['compi = ',num2str(compi), ' compo = ', num2str(compo)],'bus_convert_init_debug'); %%%%%%%%%%%%%%% % input ports % %%%%%%%%%%%%%%% ypos_tmp = ypos + convert_d*compi/2; reuse_block(blk, 'din', 'built-in/inport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + convert_d*compi/2; %space for of_bussify if strcmp(of, 'on'), ypos_tmp = ypos_tmp + yinc + convert_d*compi; end if strcmp(misc, 'on'), reuse_block(blk, 'misci', 'built-in/inport', ... 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); end xpos = xpos + xinc + port_w/2; %%%%%%%%%%%%%% % bus expand % %%%%%%%%%%%%%% ypos_tmp = ypos + convert_d*compi/2; %reset ypos outputWidth = mat2str(n_bits_in); outputBinaryPt = mat2str(bin_pt_in); outputArithmeticType = mat2str(type_in); reuse_block(blk, 'debus', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', ... 'outputWidth', outputWidth, ... 'outputBinaryPt', outputBinaryPt, ... 'outputArithmeticType', outputArithmeticType, ... 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-convert_d*compi/2 xpos+bus_expand_w/2 ypos_tmp+convert_d*compi/2]); add_line(blk, 'din/1', 'debus/1'); ypos_tmp = ypos_tmp + convert_d*(compi/2) + yinc; xpos = xpos + xinc + bus_expand_w/2; %%%%%%%%%%%%%%%%% % convert layer % %%%%%%%%%%%%%%%%% ypos_tmp = ypos; %reset ypos for index = 1:compo, switch type_out(index), case 0, arith_type = 'Unsigned'; case 1, arith_type = 'Signed'; otherwise, clog(['unknown arithmetic type ',num2str(arith_type)], 'error'); error(['bus_convert_init: unknown arithmetic type ',num2str(arith_type)]); end switch quantization(index), case 0, quant = 'Truncate'; case 1, quant = 'Round (unbiased: +/- Inf)'; case 2, quant = 'Round (unbiased: Even Values)'; end switch overflow(index), case 0, oflow = 'Wrap'; case 1, oflow = 'Saturate'; case 2, oflow = 'Flag as error'; end bits_in = n_bits_in(index); pt_in = bin_pt_in(index); bits_out = n_bits_out(index); pt_out = bin_pt_out(index); clog(['output ',num2str(index), ... ': (', num2str(bits_in), ' ', num2str(pt_in),') => ', ... '(', num2str(bits_out), ' ', num2str(pt_out),') ', ... arith_type,' ',quant,' ', oflow], ... 'bus_convert_init_debug'); conv_name = ['conv',num2str(index)]; position = [xpos-convert_w/2 ypos_tmp xpos+convert_w/2 ypos_tmp+convert_d-20]; %casper convert blocks don't support increasing binary points if strcmp(of, 'on'), reuse_block(blk, conv_name, 'casper_library_misc/convert_of', ... 'bit_width_i', num2str(bits_in), 'binary_point_i', num2str(pt_in), ... 'bit_width_o', num2str(bits_out), 'binary_point_o', num2str(pt_out), ... 'latency', num2str(latency), 'overflow', oflow, 'quantization', quant, ... 'Position', position); else, %CASPER converts can't increase binary points so use generic Xilinx if pt_out > pt_in, reuse_block(blk, conv_name, 'xbsIndex_r4/Convert', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', num2str(bits_out), 'bin_pt', num2str(pt_out), 'latency', num2str(latency), ... 'overflow', oflow, 'quantization', quant, 'pipeline', 'on', ... 'Position', position); else, reuse_block(blk, conv_name, 'casper_library_misc/convert', ... 'bin_pt_in', num2str(pt_in), ... 'n_bits_out', num2str(bits_out), 'bin_pt_out', num2str(pt_out), ... 'overflow', oflow, 'quantization', quant, 'latency', num2str(latency), ... 'Position', position); end end ypos_tmp = ypos_tmp + convert_d; add_line(blk, ['debus/',num2str(index)], [conv_name,'/1']); end ypos_tmp = ypos + yinc + convert_d*compi; %space for of_bussify if strcmp(of, 'on'), ypos_tmp = ypos_tmp + yinc + convert_d*compi; end if strcmp(misc, 'on'), reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ... 'latency', 'latency', 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); add_line(blk, 'misci/1', 'dmisc/1'); ypos_tmp = ypos_tmp + convert_d; end %%%%%%%%%%%%%%%%%%%% % create bus again % %%%%%%%%%%%%%%%%%%%% ypos_tmp = ypos + convert_d*compo/2; xpos = xpos + xinc + bus_expand_w/2; reuse_block(blk, 'bussify', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(compo), ... 'Position', [xpos-bus_create_w/2 ypos_tmp-convert_d*compo/2 xpos+bus_create_w/2 ypos_tmp+convert_d*compo/2]); for index = 1:compo, add_line(blk, ['conv',num2str(index),'/1'], ['bussify/',num2str(index)]); end if strcmp(of, 'on'), ypos_tmp = ypos_tmp + yinc + compo*convert_d; reuse_block(blk, 'of_bussify', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(compo), ... 'Position', [xpos-bus_create_w/2 ypos_tmp-convert_d*compo/2 xpos+bus_create_w/2 ypos_tmp+convert_d*compo/2]); for index = 1:compo, add_line(blk, ['conv',num2str(index),'/2'], ['of_bussify/',num2str(index)]); end end %%%%%%%%%%%%%%%%% % output port/s % %%%%%%%%%%%%%%%%% ypos_tmp = ypos + convert_d*compo/2; xpos = xpos + xinc + bus_create_w/2; reuse_block(blk, 'dout', 'built-in/outport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, ['bussify/1'], ['dout/1']); ypos_tmp = ypos_tmp + yinc + convert_d*compo/2; port_no = 1; if strcmp(of, 'on'), ypos_tmp = ypos_tmp + convert_d*compo/2; reuse_block(blk, 'overflow', 'built-in/outport', ... 'Port', num2str(port_no+1), ... 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, 'of_bussify/1', 'overflow/1'); ypos_tmp = ypos_tmp + yinc + convert_d*compo/2; port_no = port_no + 1; end if strcmp(misc, 'on'), reuse_block(blk, 'misco', 'built-in/outport', ... 'Port', num2str(port_no + 1), ... 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, 'dmisc/1', 'misco/1'); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_convert_init','trace'); end %function bus_convert_init
github
mstrader/mlib_devel-master
bus_delay_init.m
.m
mlib_devel-master/casper_library/bus_delay_init.m
7,548
utf_8
504af36d730100c74211cf950122986b
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bus_delay_init(blk, varargin) log_group = 'bus_delay_init_debug'; clog('entering bus_delay_init', {log_group, 'trace'}); defaults = { ... 'n_bits', [8 8], ... 'cmplx', 'off', ... 'enable', 'on', ... 'latency', 1, ... 'misc', 'off', ... 'reg_retiming', 'on'}; check_mask_type(blk, 'bus_delay'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); xpos = 50; xinc = 80; ypos = 50; yinc = 50; port_w = 30; port_d = 14; bus_expand_w = 50; bus_compress_w = 50; reg_w = 50; reg_d = 60; del_w = 30; del_d = 20; enable = get_var('enable', 'defaults', defaults, varargin{:}); cmplx = get_var('cmplx', 'defaults', defaults, varargin{:}); n_bits = get_var('n_bits', 'defaults', defaults, varargin{:}); misc = get_var('misc', 'defaults', defaults, varargin{:}); latency = get_var('latency', 'defaults', defaults, varargin{:}); reg_retiming = get_var('reg_retiming', 'defaults', defaults, varargin{:}); len = length(n_bits); delete_lines(blk); %default state, do nothing if latency == -1, clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_delay_init', {log_group, 'trace'}); return; end if strcmp(cmplx,'on'), n_bits = 2*n_bits; end %input ports port_no = 1; ypos_tmp = ypos + reg_d*len/2; reuse_block(blk, 'din', 'built-in/inport', ... 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + reg_d*len; port_no = port_no + 1; if strcmp(enable, 'on'), reuse_block(blk, 'en', 'built-in/inport', ... 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + reg_d*len; port_no = port_no + 1; end if strcmp(misc, 'on'), reuse_block(blk, 'misci', 'built-in/inport', ... 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); end xpos = xpos + xinc + port_w/2; ypos_tmp = ypos + reg_d*len/2; %reset ypos %data bus expand reuse_block(blk, 'din_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', ... 'outputWidth', ['[',num2str(n_bits),']'], ... 'outputBinaryPt', ['[',num2str(zeros(1, length(n_bits))),']'], ... 'outputArithmeticType', ['[',num2str(zeros(1, length(n_bits))),']'], ... 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-reg_d*len/2 xpos+bus_expand_w/2 ypos_tmp+reg_d*len/2]); add_line(blk, 'din/1', 'din_expand/1'); ypos_tmp = ypos_tmp + reg_d*len + yinc; %enable bus expand if strcmp(enable, 'on'), reuse_block(blk, 'en_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', ... 'outputNum', num2str(length(n_bits)), ... 'outputWidth', '1', 'outputBinaryPt', '0', ... 'outputArithmeticType', '2', 'show_format', 'on', ... 'outputToWorkspace', 'off', 'variablePrefix', '', ... 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-reg_d*len/2 xpos+bus_expand_w/2 ypos_tmp+reg_d*len/2]); add_line(blk, 'en/1', 'en_expand/1'); end xpos = xpos + xinc + bus_expand_w/2; %delay layer ypos_tmp = ypos; %reset ypos for index = 1:len, delay_name = ['del',num2str(index)]; %data reuse_block(blk, delay_name, 'xbsIndex_r4/Delay', ... 'en', enable, 'reg_retiming', reg_retiming, 'latency', num2str(latency), ... 'Position', [xpos-reg_w/2 ypos_tmp xpos+reg_w/2 ypos_tmp+reg_d-20]); ypos_tmp = ypos_tmp + reg_d; add_line(blk, ['din_expand/',num2str(index)], [delay_name,'/1']); port_index = 2; if strcmp(enable, 'on'), add_line(blk, ['en_expand/', num2str(index)], [delay_name, '/', num2str(port_index)]); end end if strcmp(misc, 'on'), reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ... 'latency', num2str(latency), 'reg_retiming', 'on', ... 'Position', [xpos-del_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)-del_d/2+(port_no-1)*yinc xpos+del_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+(port_no-1)*yinc+del_d/2]); add_line(blk, 'misci/1', 'dmisc/1'); ypos_tmp = ypos_tmp + reg_d; end %create bus again ypos_tmp = ypos + reg_d*len/2; xpos = xpos + xinc + bus_expand_w/2; reuse_block(blk, 'dout_compress', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(len), ... 'Position', [xpos-bus_compress_w/2 ypos_tmp-reg_d*len/2 xpos+bus_compress_w/2 ypos_tmp+reg_d*len/2]); for index = 1:len, add_line(blk, ['del',num2str(index),'/1'], ['dout_compress/',num2str(index)]); end %output port/s ypos_tmp = ypos + reg_d*len/2; xpos = xpos + xinc + bus_compress_w/2; reuse_block(blk, 'dout', 'built-in/outport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, ['dout_compress/1'], ['dout/1']); ypos_tmp = ypos_tmp + yinc + port_d/2; if strcmp(misc, 'on'), reuse_block(blk, 'misco', 'built-in/outport', ... 'Port', '2', ... 'Position', [xpos-port_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+((port_no-1)*yinc)-port_d/2 xpos+port_w/2 ypos+(((port_no-1)+1/2)*reg_d*len)+((port_no-1)*yinc)+port_d/2]); add_line(blk, 'dmisc/1', 'misco/1'); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_delay_init', {log_group, 'trace'}); end %function bus_delay_init
github
mstrader/mlib_devel-master
convert_of_init.m
.m
mlib_devel-master/casper_library/convert_of_init.m
7,714
utf_8
9521c93dea6662366ea24665b32c1297
% Bit width conversion in 2's complement data with indication of % over/underflow % % convert_of_init(blk, varargin) % % blk = The block to initialise % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % % bit_width_i = Total bit width of input data % binary_point_i = Number of fractional bits in input data % bit_width_o = Total bit width of output data % binary_point_o = Number of fractional bits in output data % quantization = Quantization strategy during conversion % overflow = Overflow strategy during conversion % latency = Latency during conversion process %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2008 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function convert_of_init(blk,varargin) defaults = { ... 'bit_width_i', 0, ... 'binary_point_i', 2, ... 'quantization', 'Truncate', ... 'overflow', 'Wrap', ... 'bit_width_o', 8, ... 'binary_point_o', 7, ... 'latency',2, ... }; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'convert_of'); munge_block(blk, varargin{:}); bit_width_i = get_var('bit_width_i', 'defaults', defaults, varargin{:}); %data_type_i = get_var('data_type_i', 'defaults', defaults, varargin{:}); binary_point_i = get_var('binary_point_i', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); bit_width_o = get_var('bit_width_o', 'defaults', defaults, varargin{:}); %data_type_o = get_var('data_type_o', 'defaults', defaults, varargin{:}); binary_point_o = get_var('binary_point_o', 'defaults', defaults, varargin{:}); latency = get_var('latency', 'defaults', defaults, varargin{:}); delete_lines(blk); if bit_width_i == 0 | bit_width_o == 0, clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); return; end %input and output ports reuse_block(blk, 'din', 'built-in/inport', 'Port', '1', 'Position', [50 108 80 122]); reuse_block(blk, 'dout', 'built-in/outport', 'Port', '1', 'Position', [415 108 445 122]); reuse_block(blk, 'of', 'built-in/outport', 'Port', '2', 'Position', [415 188 445 202]); %draw convert block % First delete the convert block that exists so that it can be changed from a % Xilnix convert block to a CASPER convert block. % % It would probably be better to simply change the convert_of block in % casper_library_misc.mdl to use CASPER converts explicitly, but changing % the .mdl file is riskier in that it could lead to merges that tend not to % be pleasant. conv_blk = find_system(blk, ... 'LookUnderMasks','all', 'FollowLinks','on', ... 'SearchDepth',1, 'Name','convert'); if ~isempty(conv_blk) delete_block(conv_blk{1}); end %if within the capabilities of CASPER convert if binary_point_i >= binary_point_o, reuse_block(blk, 'convert', 'casper_library_misc/convert', ... 'bin_pt_in', 'binary_point_i', ... 'n_bits_out', 'bit_width_o', ... 'bin_pt_out', 'binary_point_o', ... 'quantization', quantization, ... 'overflow', overflow, ... 'latency', 'latency', ... 'Position', [275 100 320 130]); else, %use Xilinx convert reuse_block(blk, 'convert', 'xbsIndex_r4/Convert', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', 'bit_width_o', ... 'bin_pt', 'binary_point_o', ... 'quantization', quantization, ... 'overflow', overflow, ... 'latency', 'latency', ... 'pipeline', 'on', ... 'Position', [275 100 320 130]); end %join input port to convert to output port add_line(blk, 'din/1', 'convert/1'); add_line(blk, 'convert/1', 'dout/1'); %only care about bits above binary point wb_lost = max((bit_width_i - binary_point_i) - (bit_width_o - binary_point_o),0); %for case where no overflow issues if wb_lost == 0, reuse_block(blk, 'never', 'xbsIndex_r4/Constant', ... 'arith_type', 'Boolean', 'const','0', ... 'explicit_period', 'on', 'period', '1', ... 'Position', [315 182 370 208]); add_line(blk, 'never/1','of/1'); else %draw 'and' blocks \ %2's complement numbers have overflow if most sig bits to be discarded %are different (i.e not all 1's or all 0's) reuse_block(blk, 'all_0s', 'xbsIndex_r4/Logical', ... 'precision','Full', ... 'inputs', num2str(wb_lost+1), ... 'latency', 'latency', ... 'logical_function', 'NAND', ... 'Position', [275 185 320 185+(wb_lost+1)*20] ); reuse_block(blk, 'all_1s', 'xbsIndex_r4/Logical', ... 'precision','Full', ... 'inputs', num2str(wb_lost+1), ... 'latency', 'latency', ... 'logical_function', 'NAND', ... 'Position', [275 185+(wb_lost+2)*20 320 185+(wb_lost+2)*20+(wb_lost+1)*20] ); %draw slice blocks and inversion blocks for i = 1:(wb_lost+1), reuse_block(blk, ['slice',num2str(i)], 'xbsIndex_r4/Slice', ... 'boolean_output','on', 'mode', 'Upper Bit Location + Width', ... 'bit1', num2str(-1*(i-1)), 'base1', 'MSB of Input', ... 'Position', [140 134+i*50 175 156+i*50]); add_line(blk, 'din/1', ['slice',num2str(i),'/1']); add_line(blk, ['slice',num2str(i),'/1'], ['all_1s','/',num2str(i)]); reuse_block(blk, ['invert',num2str(i)], 'xbsIndex_r4/Inverter', ... 'Position', [200 134+i*50 235 156+i*50]); add_line(blk, ['slice',num2str(i),'/1'], ['invert',num2str(i),'/1']); add_line(blk, ['invert',num2str(i),'/1'], ['all_0s','/',num2str(i)]); end reuse_block(blk, 'and', 'xbsIndex_r4/Logical', ... 'precision','Full', ... 'inputs', '2', ... 'latency', '0', ... 'logical_function', 'AND', ... 'Position', [350 185 390 220] ); add_line(blk, 'all_0s/1', 'and/1'); add_line(blk, 'all_1s/1', 'and/2'); add_line(blk, 'and/1', 'of/1'); end clean_blocks(blk); fmtstr = sprintf('[%d,%d]->[%d,%d]', bit_width_i, binary_point_i, bit_width_o, binary_point_o); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:});
github
mstrader/mlib_devel-master
twiddle_general_4mult_init.m
.m
mlib_devel-master/casper_library/twiddle_general_4mult_init.m
14,577
utf_8
a0dc57fd861b1c01fb32e2a389e2c90a
% twiddle_general_4mult_init(blk, varargin) % % blk = The block to configure % varargin = {'varname', 'value, ...} pairs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Karoo Array Telesope % % http://www.kat.ac.za % % Copyright (C) 2009 Andrew Martens % % % % Radio Astronomy Lab % % University of California, Berkeley % % http://ral.berkeley.edu/ % % Copyright (C) 2010 David MacMahon % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function twiddle_general_4mult_init(blk, varargin) clog('entering twiddle_general_4mult_init','trace'); defaults = {'Coeffs', [0, j], 'StepPeriod', 0, 'input_bit_width', 18, ... 'coeff_bit_width', 18,'add_latency', 1, 'mult_latency', 2, ... 'conv_latency', 1, 'bram_latency', 2, 'arch', 'Virtex5', ... 'coeffs_bram', 'off', 'use_hdl', 'off', 'use_embedded', 'off', ... 'quantization', 'Round (unbiased: +/- Inf)', 'overflow', 'Wrap'}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end clog('twiddle_general_4mult_init post same_state', 'trace'); check_mask_type(blk, 'twiddle_general_4mult'); munge_block(blk, varargin{:}); Coeffs = get_var('Coeffs', 'defaults', defaults, varargin{:}); StepPeriod = get_var('StepPeriod', 'defaults', defaults, varargin{:}); input_bit_width = get_var('input_bit_width', 'defaults', defaults, varargin{:}); coeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:}); add_latency = get_var('add_latency', 'defaults', defaults, varargin{:}); mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:}); conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); arch = get_var('arch', 'defaults', defaults, varargin{:}); coeffs_bram = get_var('coeffs_bram', 'defaults', defaults, varargin{:}); use_hdl = get_var('use_hdl', 'defaults', defaults, varargin{:}); use_embedded = get_var('use_embedded', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); clog(flatstrcell(varargin),'twiddle_general_4mult_init_debug'); if( strcmp(arch,'Virtex2Pro') ), elseif( strcmp(arch,'Virtex5') ), else, clog(['twiddle_general_4mult_init: unknown target architecture ',arch],'error'); error(['twiddle_general_4mult_init: Unknown target architecture ',arch]); return end delete_lines(blk); %default case, leave clean block with nothing for storage in the libraries if isempty(Coeffs) clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting twiddle_general_4mult_init', 'trace'); return; end %a input signal path reuse_block(blk, 'a', 'built-in/inport', 'Port', '1', 'Position',[225 28 255 42]); reuse_block(blk, 'delay0', 'xbsIndex_r4/Delay', ... 'latency','mult_latency + add_latency + bram_latency + conv_latency', ... 'Position', [275 15 315 55]); add_line(blk, 'a/1', 'delay0/1'); reuse_block(blk, 'c_to_ri1', 'casper_library_misc/c_to_ri', ... 'n_bits', 'input_bit_width', 'bin_pt', 'input_bit_width-1', ... 'Position', [340 14 380 56]); add_line(blk,'delay0/1','c_to_ri1/1'); reuse_block(blk, 'a_re', 'built-in/outport', 'Port', '1', 'Position', [405 13 435 27]); reuse_block(blk, 'a_im', 'built-in/outport', 'Port', '2', 'Position', [405 43 435 57]); add_line(blk, 'c_to_ri1/1', 'a_re/1'); add_line(blk, 'c_to_ri1/2', 'a_im/1'); %sync input signal path reuse_block(blk, 'sync', 'built-in/inport', 'Port', '3', 'Position',[40 393 70 407]); reuse_block(blk, 'delay2', 'xbsIndex_r4/Delay', ... 'latency','mult_latency + add_latency + bram_latency + conv_latency', ... 'Position', [280 380 320 420]); add_line(blk, 'sync/1', 'delay2/1'); reuse_block(blk, 'sync_out', 'built-in/outport', 'Port', '5', 'Position', [340 393 370 407]); add_line(blk, 'delay2/1', 'sync_out/1'); %coefficient generator reuse_block(blk, 'coeff_gen', 'casper_library_ffts_twiddle_coeff_gen/coeff_gen', ... 'Coeffs', tostring(Coeffs), ... 'StepPeriod', tostring(StepPeriod), 'coeff_bit_width', 'coeff_bit_width', ... 'bram_latency', 'bram_latency', 'coeffs_bram', coeffs_bram, ... 'Position', [105 249 150 291]); add_line(blk, 'sync/1', 'coeff_gen/1'); reuse_block(blk, 'c_to_ri2', 'casper_library_misc/c_to_ri', ... 'n_bits', 'coeff_bit_width', 'bin_pt', 'coeff_bit_width-2', ... 'Position', [180 249 220 291]); add_line(blk, 'coeff_gen/1', 'c_to_ri2/1'); %b input signal path reuse_block(blk, 'b', 'built-in/inport', 'Port', '2', 'Position',[35 148 65 162]); reuse_block(blk, 'delay1', 'xbsIndex_r4/Delay', 'latency', 'bram_latency', ... 'reg_retiming', 'on', 'Position', [105 135 145 175]); add_line(blk, 'b/1', 'delay1/1'); reuse_block(blk, 'c_to_ri3', 'casper_library_misc/c_to_ri', ... 'n_bits', 'input_bit_width', 'bin_pt', 'input_bit_width-1', ... 'Position', [185 134 225 176]); add_line(blk, 'delay1/1', 'c_to_ri3/1'); %Mult reuse_block(blk, 'mult', 'xbsIndex_r4/Mult', ... 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ... 'latency', 'mult_latency', ... 'Position', [275 128 320 172]); add_line(blk, 'c_to_ri3/1', 'mult/1'); add_line(blk, 'c_to_ri2/1', 'mult/2'); %Mult1 reuse_block(blk, 'mult1', 'xbsIndex_r4/Mult', ... 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ... 'latency', 'mult_latency', ... 'Position', [275 188 320 232]); add_line(blk, 'c_to_ri3/2', 'mult1/1'); add_line(blk, 'c_to_ri2/1', 'mult1/2'); %Mult2 reuse_block(blk, 'mult2', 'xbsIndex_r4/Mult', ... 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ... 'latency', 'mult_latency', ... 'Position', [275 248 320 292]); add_line(blk, 'c_to_ri3/2', 'mult2/1'); add_line(blk, 'c_to_ri2/2', 'mult2/2'); %Mult3 reuse_block(blk, 'mult3', 'xbsIndex_r4/Mult', ... 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ... 'latency', 'mult_latency', ... 'Position', [275 308 320 352]); add_line(blk, 'c_to_ri3/1', 'mult3/1'); add_line(blk, 'c_to_ri2/2', 'mult3/2'); %adders reuse_block(blk, 'AddSub', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ... 'mode', 'Subtraction','use_behavioral_HDL', 'on', ... 'Position', [410 138 455 182]); reuse_block(blk, 'AddSub1', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ... 'mode', 'Addition','use_behavioral_HDL', 'on', ... 'Position', [410 298 455 342]); %output ports reuse_block(blk, 'bw_re', 'built-in/outport', 'Port', '3', 'Position', [670 153 710 167]); reuse_block(blk, 'bw_im', 'built-in/outport', 'Port', '4', 'Position', [670 313 710 327]); % First delete any convert blocks that exist so that different architectures % can use different convert blocks. For Virtex2Pro, use CASPER convert blocks. % For Virtex5 blocks, use Xilinx convert blocks (for "historical" % compatibility; recommend changing V5 to use CASPER convert blocks, too). % Deleting beforehand is needed so that reuse_block for V2P will not try to % configure Xilinx convert blocks (left over from code for V5) as CASPER % convert blocks and vice versa. % % It would probably be better to simply change the block in % casper_library_ffts_twiddle.mdl to use CASPER converts always regardless of % architecture (e.g. V5 vs V2P), but changing the .mdl file is riskier in that % it could lead to merges that tend not to be pleasant. for k=0:3 conv_name = sprintf('convert%d', k); conv_blk = find_system(blk, ... 'LookUnderMasks','all', 'FollowLinks','on', ... 'SearchDepth',1, 'Name',conv_name); if ~isempty(conv_blk) delete_block(conv_blk{1}); end end %architecture specific logic if( strcmp(arch,'Virtex2Pro') ), %add convert blocks to reduce logic in adders % Multiplication by a complex twiddle factor is nothing more than a % rotation in the complex plane. The bit width of the input value being % twiddled can grow no more than one non-fractional bit. The input value % does not gain more precision by being twiddled so therefore it need not % grow any fractional bits. % % Since the growth by one non-fractional bit provides sufficient dynamic % range for the twiddle operation, any "overflow" can (and should!) be % ignored (i.e. set to "Wrap"; *not* set to "Saturate"). reuse_block(blk, 'convert0', 'casper_library_misc/convert', ... 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-2)', ... 'n_bits_out', 'input_bit_width+1', ... 'bin_pt_out', 'input_bit_width-1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', 'Wrap', ... 'Position', [340 135 380 165]); add_line(blk, 'mult/1', 'convert0/1'); reuse_block(blk, 'convert1', 'casper_library_misc/convert', ... 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-2)', ... 'n_bits_out', 'input_bit_width+1', ... 'bin_pt_out', 'input_bit_width-1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', 'Wrap', ... 'Position', [340 195 380 225]); add_line(blk, 'mult1/1', 'convert1/1'); reuse_block(blk, 'convert2', 'casper_library_misc/convert', ... 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-2)', ... 'n_bits_out', 'input_bit_width+1', ... 'bin_pt_out', 'input_bit_width-1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', 'Wrap', ... 'Position', [340 255 380 285]); add_line(blk, 'mult2/1', 'convert2/1'); reuse_block(blk, 'convert3', 'casper_library_misc/convert', ... 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-2)', ... 'n_bits_out', 'input_bit_width+1', ... 'bin_pt_out', 'input_bit_width-1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', 'Wrap', ... 'Position', [340 315 380 345]); add_line(blk, 'mult3/1', 'convert3/1'); %join convert blocks to adders add_line(blk, 'convert0/1', 'AddSub/1'); add_line(blk, 'convert2/1', 'AddSub/2'); add_line(blk, 'convert1/1', 'AddSub1/1'); add_line(blk, 'convert3/1', 'AddSub1/2'); %join adders to ouputs add_line(blk, 'AddSub/1', 'bw_re/1'); add_line(blk, 'AddSub1/1', 'bw_im/1'); % Set output precision on adder outputs set_param([blk,'/AddSub'], ... 'precision', 'User Defined', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', 'input_bit_width+1', ... 'bin_pt', 'input_bit_width-1', ... 'quantization', 'Truncate', ... 'overflow', 'Wrap'); set_param([blk,'/AddSub1'], ... 'precision', 'User Defined', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', 'input_bit_width+1', ... 'bin_pt', 'input_bit_width-1', ... 'quantization', 'Truncate', ... 'overflow', 'Wrap'); elseif( strcmp(arch,'Virtex5') ) %add convert blocks to after adders to ensure adders absorbed into multipliers add_line(blk, 'mult/1', 'AddSub/1'); add_line(blk, 'mult1/1', 'AddSub1/1'); add_line(blk, 'mult2/1', 'AddSub/2'); add_line(blk, 'mult3/1', 'AddSub1/2'); reuse_block(blk, 'convert0', 'xbsIndex_r4/Convert', ... 'pipeline', 'on', ... 'n_bits', 'input_bit_width+4', ... 'bin_pt', 'input_bit_width+1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', tostring(overflow), ... 'Position', [485 145 525 175]); add_line(blk, 'AddSub/1', 'convert0/1'); add_line(blk, 'convert0/1', 'bw_re/1'); reuse_block(blk, 'convert1', 'xbsIndex_r4/Convert', ... 'pipeline', 'on', ... 'n_bits', 'input_bit_width+4', ... 'bin_pt', 'input_bit_width+1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', tostring(overflow), ... 'Position', [485 305 525 335]); add_line(blk, 'AddSub1/1', 'convert1/1'); add_line(blk, 'convert1/1', 'bw_im/1'); else return; end clean_blocks(blk); fmtstr = sprintf('data=(%d,%d)\ncoeffs=(%d,%d)\n%s\n(%s,%s)', ... input_bit_width, input_bit_width-1, coeff_bit_width, coeff_bit_width-2, arch, quantization, overflow); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting twiddle_general_4mult_init', 'trace');
github
mstrader/mlib_devel-master
set_param_state.m
.m
mlib_devel-master/casper_library/set_param_state.m
2,025
utf_8
4cabaa5ab4266c8cda5e954f884f6822
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://casper.berkeley.edu % % Copyright (C) 2010 William Mallard % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function set_param_state(cursys, param_name, param_state) % Enable or disable a mask parameter. mask_names = get_param(cursys, 'MaskNames'); param_index = ismember(mask_names, param_name); mask_enables = get_param(cursys, 'MaskEnables'); mask_enables{param_index} = param_state; set_param(cursys, 'MaskEnables', mask_enables); end
github
mstrader/mlib_devel-master
sincos_init.m
.m
mlib_devel-master/casper_library/sincos_init.m
5,943
utf_8
f46b84e172872452da8ca5c34a2a10e6
% Generate sine/cos. % % sincos_init(blk, varargin) % % blk = The block to be configured. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function sincos_init(blk,varargin) check_mask_type(blk, 'sincos'); defaults = {}; %if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); func = get_var('func', 'defaults', defaults, varargin{:}); neg_sin = get_var('neg_sin', 'defaults', defaults, varargin{:}); neg_cos = get_var('neg_cos', 'defaults', defaults, varargin{:}); bit_width = get_var('bit_width', 'defaults', defaults, varargin{:}); symmetric = get_var('symmetric', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); depth_bits = get_var('depth_bits', 'defaults', defaults, varargin{:}); handle_sync = get_var('handle_sync', 'defaults', defaults, varargin{:}); delete_lines(blk); %default case for storage in library if depth_bits == 0, % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values return; end base = 0; %handle the sync if strcmp(handle_sync, 'on'), reuse_block(blk, 'sync_in', 'built-in/inport', 'Port', '1', 'Position', [80 70 110 90]); reuse_block(blk, 'delay', 'xbsIndex_r4/Delay', ... 'latency', 'bram_latency', ... 'Position', [190 70 230 90]); add_line(blk, 'sync_in/1', 'delay/1'); reuse_block(blk, 'sync_out', 'built-in/outport', 'Port', '1', 'Position', [500 70 530 90]); add_line(blk, 'delay/1', 'sync_out/1'); base = 1; end %input and output ports reuse_block(blk, 'theta', 'built-in/inport', 'Port', num2str(base+1), 'Position', [80 130 110 150]); %draw first lookup if( strcmp(func, 'sine and cosine') || strcmp(func, 'sine') ), if strcmp(neg_sin, 'on') , sin_name = '-sine'; else sin_name = 'sine'; end reuse_block(blk, sin_name, 'built-in/outport', 'Port', num2str(base+1), 'Position', [500 130 530 150]); end if( strcmp(func, 'sine and cosine') || strcmp(func, 'cosine')), if strcmp(neg_cos, 'on') , cos_name = '-cos'; else cos_name = 'cos'; end if strcmp(func, 'sine and cosine') pos = '3'; end reuse_block(blk, cos_name, 'built-in/outport', 'Port', num2str(base+2), 'Position', [500 190 530 210]); end %lookup for sine/cos s = ''; if( strcmp(func, 'sine') || strcmp(func, 'sine and cosine') ), if strcmp(neg_sin, 'on') , s = '-'; end init_vec = sprintf('%ssin(2*pi*(0:(%s))/(%s))',s,'2^depth_bits-1','2^depth_bits'); else if( strcmp(neg_cos, 'on') ), s = '-'; end init_vec = sprintf('%scos(2*pi*(0:(%s))/(%s))',s,'2^depth_bits-1','2^depth_bits'); end bin_pt = 'bit_width-1'; if(strcmp(symmetric, 'on')), bin_pt = 'bit_width-2'; end reuse_block(blk, 'rom0', 'xbsIndex_r4/ROM', ... 'depth', '2^depth_bits', 'initVector', init_vec, ... 'latency', 'bram_latency', 'n_bits', 'bit_width', ... 'bin_pt', bin_pt, ... 'Position', [180 120 240 160]); add_line(blk, 'theta/1', 'rom0/1'); if strcmp(func, 'sine and cosine') || strcmp(func, 'sine'), dest = sin_name; else dest = cos_name; end add_line(blk, 'rom0/1', [dest,'/1']); %have 2 outputs if strcmp(func, 'sine and cosine'), s = ''; if( strcmp(neg_cos, 'on') ), s = '-'; end init_vec = sprintf('%scos(2*pi*(0:(%s))/(%s))',s,'2^depth_bits-1','2^depth_bits'); reuse_block(blk, 'rom1', 'xbsIndex_r4/ROM', ... 'depth', '2^depth_bits', 'initVector', init_vec, ... 'latency', 'bram_latency', 'n_bits', 'bit_width', ... 'bin_pt', bin_pt, ... 'Position', [180 180 240 220]); add_line(blk, 'theta/1', 'rom1/1'); dest = cos_name; add_line(blk, 'rom1/1', [dest,'/1']); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); % Set attribute format string (block annotation) annotation=sprintf(''); set_param(blk,'AttributesFormatString',annotation); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values
github
mstrader/mlib_devel-master
last_tap_real_init.m
.m
mlib_devel-master/casper_library/last_tap_real_init.m
2,685
utf_8
8ea0bf0847220ce597822a7e4e587225
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2007 Terry Filiba, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function last_tap_real_init(blk, varargin) % Initialize and configure the last tap of the Polyphase Filter Bank. % % last_tap_real_init(blk, varargin) % % blk = The block to configure. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % TotalTaps = Total number of taps in the PFB % BitWidthIn = Input Bitwidth % CoeffBitWidth = Bitwidth of Coefficients. % mult_latency = Latency through each multiplier % Declare any default values for arguments you might like. defaults = {}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'last_tap_real'); munge_block(blk, varargin{:}); use_hdl = get_var('use_hdl','defaults', defaults, varargin{:}); use_embedded = get_var('use_embedded','defaults', defaults, varargin{:}); set_param([blk,'/Mult'],'use_embedded',use_embedded); set_param([blk,'/Mult'],'use_behavioral_HDL',use_hdl); save_state(blk, 'defaults', defaults, varargin{:});
github
mstrader/mlib_devel-master
bit_reverse_init.m
.m
mlib_devel-master/casper_library/bit_reverse_init.m
3,419
utf_8
7a63f92cfb4aa1dfddd8dd479d06b938
% Initialize and populate a bit_reverse block. % % bit_reverse_init(blk, varargin) % % blk = The block to initialize. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % n_bits = The number of input bits to reverse %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bit_reverse_init(blk,varargin) check_mask_type(blk, 'bit_reverse'); if same_state(blk, varargin{:}), return, end munge_block(blk, varargin{:}); n_bits = get_var('n_bits',varargin{:}); % When dynamically drawing blocks, first delete all lines in a system. delete_lines(blk); % Draw blocks and lines, using 'reuse_block' to efficiently instantiate blocks. if n_bits <= 1, add_line(blk,'in/1','out/1'); else % Always propagate variables by value (num2str) reuse_block(blk, 'concat', 'xbsIndex_r4/Concat', ... 'Position',[450 100 500 100+n_bits*20],'num_inputs',num2str(n_bits)); for i=n_bits-1:-1:0, bitname=['bit' num2str(i)]; reuse_block(blk, bitname, 'xbsIndex_r4/Slice', ... 'Position',[100 100+i*40 140 120+i*40], ... 'mode','Lower Bit Location + Width', ... 'nbits', '1', 'bit0', num2str(i)); add_line(blk,'in/1',[bitname,'/1'],'autorouting','on'); add_line(blk,[bitname,'/1'],['concat/',num2str(i+1)],'autorouting','on'); end add_line(blk,'concat/1','out/1','autorouting','on'); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); % Set attribute format string (block annotation) annotation=sprintf('%d bits',n_bits); set_param(blk,'AttributesFormatString',annotation); save_state(blk,varargin{:}); % Save and back-populate mask parameter values
github
mstrader/mlib_devel-master
backpopulate_mask.m
.m
mlib_devel-master/casper_library/backpopulate_mask.m
3,100
utf_8
8a41f770a26ae171fd8c088d0458ff61
% Rewrites mask parameters as strings if short enough, otherwise call to extract. % % backpopulate_mask( blk, varargin ) % % blk - The block whose mask will be modified % varargin - {'var', 'value', ...} pairs % % Cycles through the list of mask parameter variable names. Appends a new cell % with the variable value (extracted from varargin) as a string to a cell array if % value short enough, otherwise a call to its value in 'UserData'. Overwrites the % 'MaskValues' parameter with this new cell array. Essentially converts any pointers % or references to strings in the mask. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons, % % Copyright (C) 2008 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function backpopulate_mask(blk,varargin) try % Match mask names to {variables, values} in varargin masknames = get_param(blk, 'MaskNames'); mv = {}; for i=1:length(masknames), varname = masknames{i}; value = get_var(varname, varargin{:}); if isnan(value), error(['No value specified for ',varname]); end %if parameter too large if( length(tostring(value)) > 100 ), mv{i} = ['getfield( getfield( get_param( gcb,''UserData'' ), ''parameters''),''',varname,''')']; else mv{i} = tostring(value); end end %Back populate mask parameter values set_param(blk,'MaskValues',mv); % This call echos blk name if mv contains a matrix ??? catch ex dump_and_rethrow(ex); end
github
mstrader/mlib_devel-master
fft_callback_dsp48_adders.m
.m
mlib_devel-master/casper_library/fft_callback_dsp48_adders.m
2,151
utf_8
a28df53b3efb26e11cfa3e0158f78560
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://casper.berkeley.edu % % Copyright (C) 2010 William Mallard % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fft_callback_dsp48_adders(cursys) % Dialog callback for dsp48_adders parameter in all fft blocks. % if dsp48_adders is set, % force add_latency to 2 % and disable the field. % otherwise, enable it. dsp48_adders = get_param(cursys, 'dsp48_adders'); if strcmp(dsp48_adders, 'on'), set_param(cursys, 'add_latency', '2'); set_param_state(cursys, 'add_latency', 'off'); else set_param_state(cursys, 'add_latency', 'on'); end end
github
mstrader/mlib_devel-master
bus_replicate_init.m
.m
mlib_devel-master/casper_library/bus_replicate_init.m
6,992
utf_8
e36f7955f116f0ce1ce005d256e92bfb
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens ([email protected]) % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bus_replicate_init(blk, varargin) log_group = 'bus_replicate_init_debug'; clog('entering bus_replicate_init', {log_group, 'trace'}); defaults = { ... 'replication', 8, 'latency', 4, 'misc', 'on', ... 'implementation', 'core'}; %'core' 'behavioral' check_mask_type(blk, 'bus_replicate'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); xpos = 50; xinc = 100; ypos = 50; yinc = 50; port_w = 30; port_d = 14; del_w = 30; del_d = 20; bus_create_w = 50; replication = get_var('replication', 'defaults', defaults, varargin{:}); latency = get_var('latency', 'defaults', defaults, varargin{:}); misc = get_var('misc', 'defaults', defaults, varargin{:}); implementation = get_var('implementation', 'defaults', defaults, varargin{:}); delete_lines(blk); %default state, do nothing if replication == 0 || isempty(replication), clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_replicate_init', {log_group, 'trace'}); return; end %%%%%%%%%%%%%%% % input ports % %%%%%%%%%%%%%%% ypos_tmp = ypos + (yinc*replication)/2; reuse_block(blk, 'in', 'built-in/inport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + (replication*yinc)/2; if strcmp(misc, 'on'), reuse_block(blk, 'misci', 'built-in/inport', ... 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); end xpos = xpos + xinc; %%%%%%%%%%%%%%%%%%%%%%%%%%% % delay layer if required % %%%%%%%%%%%%%%%%%%%%%%%%%%% if strcmp(implementation, 'behavioral'), reg_retiming_global = 'on'; else, reg_retiming_global = 'off'; end xpos_tmp = xpos; rps = replication^(1/latency); if latency > 0, prev_rep_required = 1; for stage_index = 0:latency-1, ypos_tmp = ypos; if (stage_index == 0), rep = floor(rps); else, rep = ceil(rps); end %force the final stage to have the full amount of replication if stage_index == latency-1, rep_required = replication; else, rep_required = min(prev_rep_required * rep, replication); end clog([num2str(rep_required), ' replication required for stage ',num2str(stage_index)], log_group); for rep_index = 0:rep_required-1, dname = ['din', num2str(stage_index), '_', num2str(rep_index)]; % implement with behavioral HDL if we have reached the replication amount required % before the final delay stage to potentially save resources if (rep_required == replication) && (stage_index ~= latency-1), reg_retiming = 'on'; else, reg_retiming = reg_retiming_global; end reuse_block(blk, dname, 'xbsIndex_r4/Delay', ... 'reg_retiming', reg_retiming, 'latency', '1', ... 'Position', [xpos_tmp-del_w/2 ypos_tmp-del_d/2 xpos_tmp+del_w/2 ypos_tmp+del_d/2]); if stage_index == 0, add_line(blk, 'in/1', [dname,'/1']); else, add_line(blk, ['din', num2str(stage_index-1), '_', num2str(mod(rep_index, prev_rep_required)), '/1'], [dname, '/1']); end ypos_tmp = ypos_tmp + yinc; end %for prev_rep_required = rep_required; xpos_tmp = xpos_tmp + xinc; end %for stage_index ypos_tmp = ypos + (replication+1)*yinc; if strcmp(misc, 'on'), reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'on', 'latency', num2str(latency), ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); add_line(blk, 'misci/1', 'dmisc/1'); end %if strcmp xpos = xpos + latency*xinc; end %if latency > 0 %%%%%%%%%%%%%% % create bus % %%%%%%%%%%%%%% ypos_tmp = ypos; reuse_block(blk, 'bussify', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(replication), ... 'Position', [xpos-bus_create_w/2 ypos_tmp xpos+bus_create_w/2 ypos_tmp+replication*yinc]); for index = 1:replication, if latency > 0, dsrc = ['din', num2str(latency-1), '_', num2str(index-1),'/1']; msrc = ['dmisc/1']; else, dsrc = 'in/1'; msrc = 'misci/1'; end add_line(blk, dsrc, ['bussify/',num2str(index)]); end %%%%%%%%%%%%%%%%% % output port/s % %%%%%%%%%%%%%%%%% ypos_tmp = ypos + replication*yinc/2; xpos = xpos + xinc + bus_create_w/2; reuse_block(blk, 'out', 'built-in/outport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, ['bussify/1'], ['out/1']); ypos_tmp = ypos_tmp + yinc + replication*yinc/2; if strcmp(misc, 'on'), reuse_block(blk, 'misco', 'built-in/outport', ... 'Port', '2', ... 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, msrc, 'misco/1'); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_replicate_init','trace'); end %function bus_replicate_init
github
mstrader/mlib_devel-master
casper_library_downconverter_init.m
.m
mlib_devel-master/casper_library/casper_library_downconverter_init.m
36,385
utf_8
e4cd6212025975a22f85b003fed1b78d
function casper_library_downconverter_init() warning off Simulink:Engine:MdlFileShadowing; close_system('casper_library_downconverter', 0); mdl = new_system('casper_library_downconverter', 'Library'); blk = get(mdl,'Name'); warning on Simulink:Engine:MdlFileShadowing; add_block('built-in/SubSystem', [blk,'/mixer']); mixer_gen([blk,'/mixer']); set_param([blk,'/mixer'], ... 'freq_div', sprintf('2'), ... 'freq', sprintf('2'), ... 'nstreams', sprintf('0'), ... 'n_bits', sprintf('4'), ... 'bram_latency', sprintf('2'), ... 'mult_latency', sprintf('4'), ... 'Position', sprintf('[15 30 80 120]'), ... 'Tag', sprintf('casper:mixer')); add_block('built-in/SubSystem', [blk,'/sincos']); sincos_gen([blk,'/sincos']); set_param([blk,'/sincos'], ... 'func', sprintf('sine and cosine'), ... 'neg_sin', sprintf('off'), ... 'neg_cos', sprintf('off'), ... 'symmetric', sprintf('on'), ... 'handle_sync', sprintf('off'), ... 'depth_bits', sprintf('0'), ... 'bit_width', sprintf('16'), ... 'bram_latency', sprintf('2'), ... 'Position', sprintf('[102 26 157 64]'), ... 'Tag', sprintf('casper:sincos')); add_block('built-in/SubSystem', [blk,'/feedback_osc']); feedback_osc_gen([blk,'/feedback_osc']); set_param([blk,'/feedback_osc'], ... 'n_bits', sprintf('0'), ... 'n_bits_rotation', sprintf('25'), ... 'phase_initial', sprintf('0'), ... 'phase_step_bits', sprintf('8'), ... 'phase_steps_bits', sprintf('8'), ... 'ref_values_bits', sprintf('1'), ... 'bram_latency', sprintf('2'), ... 'mult_latency', sprintf('2'), ... 'add_latency', sprintf('1'), ... 'conv_latency', sprintf('2'), ... 'bram', sprintf('Distributed memory'), ... 'quantization', sprintf('Round (unbiased: Even Values)'), ... 'Position', sprintf('[105 101 145 139]'), ... 'Tag', sprintf('casper:feedback_osc')); add_block('built-in/SubSystem', [blk,'/cosin']); cosin_gen([blk,'/cosin']); set_param([blk,'/cosin'], ... 'output0', sprintf('sin'), ... 'output1', sprintf('cos'), ... 'indep_theta', sprintf('off'), ... 'phase', sprintf('0'), ... 'fraction', sprintf('0'), ... 'store', sprintf('0'), ... 'table_bits', sprintf('0'), ... 'n_bits', sprintf('18'), ... 'bin_pt', sprintf('17'), ... 'bram_latency', sprintf('1'), ... 'add_latency', sprintf('1'), ... 'mux_latency', sprintf('1'), ... 'neg_latency', sprintf('1'), ... 'conv_latency', sprintf('1'), ... 'pack', sprintf('off'), ... 'bram', sprintf('BRAM'), ... 'misc', sprintf('off'), ... 'Position', sprintf('[175 26 230 64]'), ... 'Tag', sprintf('casper:cosin')); add_block('built-in/SubSystem', [blk,'/dec_fir']); dec_fir_gen([blk,'/dec_fir']); set_param([blk,'/dec_fir'], ... 'n_inputs', sprintf('0'), ... 'coeff', sprintf('0.10000000000000000555111512312578'), ... 'n_bits', sprintf('8'), ... 'n_bits_bp', sprintf('7'), ... 'quantization', sprintf('Round (unbiased: +/- Inf)'), ... 'add_latency', sprintf('1'), ... 'mult_latency', sprintf('2'), ... 'conv_latency', sprintf('2'), ... 'coeff_bit_width', sprintf('25'), ... 'coeff_bin_pt', sprintf('24'), ... 'absorb_adders', sprintf('on'), ... 'adder_imp', sprintf('DSP48'), ... 'lshift', sprintf('1'), ... 'Position', sprintf('[15 215 80 308]'), ... 'Tag', sprintf('casper:dec_fir')); add_block('built-in/SubSystem', [blk,'/lo_osc']); lo_osc_gen([blk,'/lo_osc']); set_param([blk,'/lo_osc'], ... 'n_bits', sprintf('0'), ... 'counter_step', sprintf('3'), ... 'counter_start', sprintf('4'), ... 'counter_width', sprintf('4'), ... 'latency', sprintf('2'), ... 'Position', sprintf('[248 26 288 81]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/fir_tap']); fir_tap_gen([blk,'/fir_tap']); set_param([blk,'/fir_tap'], ... 'factor', sprintf('1'), ... 'latency', sprintf('2'), ... 'coeff_bit_width', sprintf('0'), ... 'coeff_bin_pt', sprintf('24'), ... 'Position', sprintf('[100 215 150 282]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/fir_dbl_tap']); fir_dbl_tap_gen([blk,'/fir_dbl_tap']); set_param([blk,'/fir_dbl_tap'], ... 'factor', sprintf('0.073384000000000004781952611665474'), ... 'add_latency', sprintf('1'), ... 'mult_latency', sprintf('2'), ... 'coeff_bit_width', sprintf('0'), ... 'coeff_bin_pt', sprintf('17'), ... 'Position', sprintf('[172 215 222 282]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/lo_const']); lo_const_gen([blk,'/lo_const']); set_param([blk,'/lo_const'], ... 'n_bits', sprintf('0'), ... 'phase', sprintf('0'), ... 'Position', sprintf('[306 26 346 81]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/fir_dbl_col']); fir_dbl_col_gen([blk,'/fir_dbl_col']); set_param([blk,'/fir_dbl_col'], ... 'n_inputs', sprintf('0'), ... 'coeff', sprintf('0.10000000000000000555111512312578'), ... 'add_latency', sprintf('2'), ... 'mult_latency', sprintf('3'), ... 'coeff_bit_width', sprintf('25'), ... 'coeff_bin_pt', sprintf('24'), ... 'first_stage_hdl', sprintf('off'), ... 'adder_imp', sprintf('Fabric'), ... 'Position', sprintf('[244 215 279 330]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/dds']); dds_gen([blk,'/dds']); set_param([blk,'/dds'], ... 'freq_div', sprintf('4'), ... 'freq', sprintf('1'), ... 'num_lo', sprintf('0'), ... 'n_bits', sprintf('8'), ... 'latency', sprintf('2'), ... 'Position', sprintf('[364 25 404 80]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/fir_col']); fir_col_gen([blk,'/fir_col']); set_param([blk,'/fir_col'], ... 'n_inputs', sprintf('0'), ... 'coeff', sprintf('0.10000000000000000555111512312578'), ... 'add_latency', sprintf('2'), ... 'mult_latency', sprintf('3'), ... 'coeff_bit_width', sprintf('25'), ... 'coeff_bin_pt', sprintf('24'), ... 'first_stage_hdl', sprintf('off'), ... 'adder_imp', sprintf('Fabric'), ... 'Position', sprintf('[301 215 336 330]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/rcmult']); rcmult_gen([blk,'/rcmult']); set_param([blk,'/rcmult'], ... 'latency', sprintf('0'), ... 'Position', sprintf('[422 26 462 81]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/dec_fir_async']); dec_fir_async_gen([blk,'/dec_fir_async']); set_param([blk,'/dec_fir_async'], ... 'n_inputs', sprintf('0'), ... 'coeff', sprintf('0.10000000000000000555111512312578'), ... 'output_width', sprintf('8'), ... 'output_bp', sprintf('7'), ... 'quantization', sprintf('Round (unbiased: +/- Inf)'), ... 'add_latency', sprintf('1'), ... 'mult_latency', sprintf('2'), ... 'conv_latency', sprintf('2'), ... 'coeff_bit_width', sprintf('25'), ... 'coeff_bin_pt', sprintf('24'), ... 'lshift', sprintf('1'), ... 'absorb_adders', sprintf('on'), ... 'adder_imp', sprintf('DSP48'), ... 'async', sprintf('off'), ... 'bus_input', sprintf('off'), ... 'input_width', sprintf('0'), ... 'input_bp', sprintf('0'), ... 'input_type', sprintf('Signed'), ... 'Position', sprintf('[15 405 80 498]'), ... 'Tag', sprintf('casper:dec_fir_async')); add_block('built-in/SubSystem', [blk,'/fir_tap_async']); fir_tap_async_gen([blk,'/fir_tap_async']); set_param([blk,'/fir_tap_async'], ... 'factor', sprintf('1'), ... 'add_latency', sprintf('1'), ... 'mult_latency', sprintf('2'), ... 'coeff_bit_width', sprintf('0'), ... 'coeff_bin_pt', sprintf('24'), ... 'async', sprintf('off'), ... 'dbl', sprintf('off'), ... 'Position', sprintf('[125 404 175 476]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/fir_col_async']); fir_col_async_gen([blk,'/fir_col_async']); set_param([blk,'/fir_col_async'], ... 'n_inputs', sprintf('0'), ... 'coeff', sprintf('0.10000000000000000555111512312578'), ... 'add_latency', sprintf('2'), ... 'mult_latency', sprintf('3'), ... 'coeff_bit_width', sprintf('25'), ... 'coeff_bin_pt', sprintf('24'), ... 'first_stage_hdl', sprintf('off'), ... 'adder_imp', sprintf('Fabric'), ... 'async', sprintf('off'), ... 'bus_input', sprintf('off'), ... 'input_width', sprintf('16'), ... 'input_bp', sprintf('0'), ... 'input_type', sprintf('Signed'), ... 'dbl', sprintf('off'), ... 'Position', sprintf('[226 405 261 520]'), ... 'Tag', sprintf('')); set_param(blk, ... 'Name', sprintf('casper_library_downconverter'), ... 'LibraryType', sprintf('BlockLibrary'), ... 'Lock', sprintf('off'), ... 'PreSaveFcn', sprintf('mdl2m(gcs);'), ... 'SolverName', sprintf('ode45'), ... 'SolverMode', sprintf('SingleTasking'), ... 'StartTime', sprintf('0.0'), ... 'StopTime', sprintf('10.0')); filename = save_system(mdl,[getenv('MLIB_DEVEL_PATH'), '/casper_library/', 'casper_library_downconverter']); if iscell(filename), filename = filename{1}; end; fileattrib(filename, '+w'); end % casper_library_downconverter_init function mixer_gen(blk) mixer_mask(blk); mixer_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('mixer_init(gcb, ...\n ''freq_div'', freq_div, ...\n ''freq'', freq, ...\n ''nstreams'', nstreams, ...\n ''n_bits'', n_bits, ...\n ''bram_latency'', bram_latency, ...\n ''mult_latency'', mult_latency);\n')); end % mixer_gen function mixer_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('mixer'), ... 'MaskDescription', sprintf('Digitally mixes an input signal (which can be several samples in parallel) with an LO of the indicated frequency (which is some fraction of the native FPGA clock rate).'), ... 'MaskPromptString', sprintf('Frequency Divisions (M)|Mixing Frequency (? / M*2pi)|Number of Parallel Streams|Bit Width|BRAM Latency|Mult Latency'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit'), ... 'MaskCallbackString', sprintf('|||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on'), ... 'MaskVariables', sprintf('freq_div=@1;freq=@2;nstreams=@3;n_bits=@4;bram_latency=@5;mult_latency=@6;'), ... 'MaskValueString', sprintf('2|2|0|4|2|4'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ... 'Tag', sprintf('casper:mixer')); end % mixer_mask function mixer_init(blk) end % mixer_init function sincos_gen(blk) sincos_mask(blk); sincos_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('sincos_init(gcb, ...\n ''func'', func, ...\n ''neg_sin'', neg_sin, ...\n ''neg_cos'', neg_cos, ...\n ''symmetric'', symmetric, ...\n ''handle_sync'', handle_sync, ...\n ''depth_bits'', depth_bits, ...\n ''bit_width'', bit_width, ...\n ''bram_latency'', bram_latency);')); end % sincos_gen function sincos_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('sincos'), ... 'MaskPromptString', sprintf('Function|Negative sine|Negative cosine|Symmetric output|Handle sync|Lookup table depth (2^?)|Output bit width|BRAM latency'), ... 'MaskStyleString', sprintf('popup(cosine|sine|sine and cosine),checkbox,checkbox,checkbox,checkbox,edit,edit,edit'), ... 'MaskCallbackString', sprintf('|||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('func=&1;neg_sin=&2;neg_cos=&3;symmetric=&4;handle_sync=&5;depth_bits=@6;bit_width=@7;bram_latency=@8;'), ... 'MaskValueString', sprintf('sine and cosine|off|off|on|off|0|16|2'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ... 'Tag', sprintf('casper:sincos')); end % sincos_mask function sincos_init(blk) end % sincos_init function feedback_osc_gen(blk) feedback_osc_mask(blk); feedback_osc_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('feedback_osc_init(gcb, ...\n ''n_bits'', n_bits, ... \n ''n_bits_rotation'', n_bits_rotation, ... \n ''phase_initial'', phase_initial, ...\n ''phase_step_bits'', phase_step_bits, ...\n ''phase_steps_bits'', phase_steps_bits, ...\n ''ref_values_bits'', ref_values_bits, ...\n ''bram_latency'', bram_latency, ...\n ''mult_latency'', mult_latency, ...\n ''add_latency'', add_latency, ...\n ''conv_latency'', conv_latency, ...\n ''bram'', bram, ...\n ''quantization'', quantization);\n')); end % feedback_osc_gen function feedback_osc_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('feedback_osc'), ... 'MaskDescription', sprintf('A complex exponential generated using an initial vector, complex multiplication\nto rotate it, and feedback. A lookup table of reference vectors is used\nto periodically remove accumulated error.'), ... 'MaskPromptString', sprintf('output bit resolution|rotation vector bit resolution |initial phase ?*(2*pi)|phase step size (2*pi)/2^?|number phase steps 2^?|number calibration locations (2^?)|BRAM latency|multiplier latency|adder latency|convert latency|BRAM implementation|quantization strategy'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,edit,edit,edit,edit,popup(Distributed memory|Block RAM),popup(Truncate|Round (unbiased: +/- Inf)|Round (unbiased: Even Values))'), ... 'MaskTabNameString', sprintf('basic,basic,basic,basic,basic,basic,latency,latency,latency,latency,implementation,implementation'), ... 'MaskCallbackString', sprintf('|||||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits=@1;n_bits_rotation=@2;phase_initial=@3;phase_step_bits=@4;phase_steps_bits=@5;ref_values_bits=@6;bram_latency=@7;mult_latency=@8;add_latency=@9;conv_latency=@10;bram=&11;quantization=&12;'), ... 'MaskValueString', sprintf('0|25|0|8|8|1|2|2|1|2|Distributed memory|Round (unbiased: Even Values)'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ... 'Tag', sprintf('casper:feedback_osc')); end % feedback_osc_mask function feedback_osc_init(blk) end % feedback_osc_init function cosin_gen(blk) cosin_mask(blk); cosin_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('cosin_init(gcb, ...\n ''output0'', output0, ... \n ''output1'', output1, ...\n ''indep_theta'', indep_theta, ...\n ''phase'', phase, ...\n ''fraction'', fraction, ...\n ''table_bits'', table_bits, ... \n ''n_bits'', n_bits, ... \n ''bin_pt'', bin_pt, ... \n ''bram_latency'', bram_latency, ...\n ''add_latency'', add_latency, ...\n ''mux_latency'', mux_latency, ...\n ''neg_latency'', neg_latency, ...\n ''conv_latency'', conv_latency, ...\n ''store'', store, ...\n ''pack'', pack, ...\n ''bram'', bram, ...\n ''misc'', misc);\n')); end % cosin_gen function cosin_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('cosin'), ... 'MaskPromptString', sprintf('first output function|second output function|Independent theta values|initial phase offset (?*(2*pi))|fraction of cycle period to output (1/2^?)|fraction of cycle period to store (1/2^?)|samples in cycle period fraction to output (2^?)|bit width|binary point|bram latency|large adder latency|mux latency|negate latency|convert latency|pack lookup values in same output word|BRAM implementation|Miscellaneous port'), ... 'MaskStyleString', sprintf('popup(sin|cos|-sin|-cos),popup(none|sin|cos|-sin|-cos),checkbox,edit,edit,edit,edit,edit,edit,edit,edit,edit,edit,edit,checkbox,popup(distributed RAM|BRAM),checkbox'), ... 'MaskTabNameString', sprintf('basic,basic,basic,basic,basic,implementation,basic,basic,basic,latency,latency,latency,latency,latency,implementation,implementation,implementation'), ... 'MaskCallbackString', sprintf('||||||||||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('output0=&1;output1=&2;indep_theta=&3;phase=@4;fraction=@5;store=@6;table_bits=@7;n_bits=@8;bin_pt=@9;bram_latency=@10;add_latency=@11;mux_latency=@12;neg_latency=@13;conv_latency=@14;pack=&15;bram=&16;misc=&17;'), ... 'MaskValueString', sprintf('sin|cos|off|0|0|0|0|18|17|1|1|1|1|1|off|BRAM|off'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ... 'MaskDisplay', sprintf('if ~(table_bits == 0),\n color(''black'');port_label(''output'',1,output0);\n color(''black'');port_label(''output'',2,output1);\n color(''black'');disp([''z^{-'',num2str(add_latency+mux_latency+conv_latency+bram_latency+neg_latency+mux_latency),''}''],''texmode'',''on'');color(''black'');port_label(''input'',1,''theta'');\n if strcmp(misc, ''on''),\n color(''black'');port_label(''input'',2,''misci'');\n color(''black'');port_label(''output'',3,''misco'');\n end\nend'), ... 'Tag', sprintf('casper:cosin')); end % cosin_mask function cosin_init(blk) end % cosin_init function dec_fir_gen(blk) dec_fir_mask(blk); dec_fir_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('dec_fir_init(gcb, ...\n ''n_inputs'', n_inputs, ...\n ''coeff'', coeff, ...\n ''n_bits'', n_bits, ...\n ''n_bits_bp'', n_bits_bp, ...\n ''quantization'', quantization, ...\n ''add_latency'', add_latency, ...\n ''mult_latency'', mult_latency, ...\n ''conv_latency'', conv_latency, ...\n ''coeff_bit_width'', coeff_bit_width, ...\n ''coeff_bin_pt'', coeff_bin_pt, ...\n ''absorb_adders'', absorb_adders, ...\n ''adder_imp'', adder_imp, ...\n ''lshift'', lshift);')); end % dec_fir_gen function dec_fir_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('dec_fir'), ... 'MaskDescription', sprintf('FIR filter which can handle multiple time samples in parallel and decimates down to 1 time sample. If coefficients are symmetric, will automatically fold before multiplying.'), ... 'MaskPromptString', sprintf('Number of Parallel Streams|Coefficients|Bit Width Out|Bin Pt Out|Quantization Behavior|Add Latency|Mult Latency|Convert latency|Coefficient bit width|Coefficient binary point|Absorb adders into DSP slices|Adder implementation|Post adder-tree shift'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,popup(Truncate|Round (unbiased: +/- Inf)|Round (unbiased: Even Values)),edit,edit,edit,edit,edit,checkbox,popup(Behavioral|Fabric|DSP48),edit'), ... 'MaskCallbackString', sprintf('||||||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_inputs=@1;coeff=@2;n_bits=@3;n_bits_bp=@4;quantization=&5;add_latency=@6;mult_latency=@7;conv_latency=@8;coeff_bit_width=@9;coeff_bin_pt=@10;absorb_adders=&11;adder_imp=&12;lshift=@13;'), ... 'MaskValueString', sprintf('0|0.10000000000000000555111512312578|8|7|Round (unbiased: +/- Inf)|1|2|2|25|24|on|DSP48|1'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ... 'Tag', sprintf('casper:dec_fir')); end % dec_fir_mask function dec_fir_init(blk) end % dec_fir_init function lo_osc_gen(blk) lo_osc_mask(blk); lo_osc_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('lo_osc_init(gcb, ...\n ''n_bits'', n_bits, ...\n ''counter_step'', counter_step, ...\n ''counter_start'', counter_start, ...\n ''counter_width'', counter_width, ...\n ''latency'', latency);')); end % lo_osc_gen function lo_osc_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('lo_osc'), ... 'MaskDescription', sprintf('Generates -sin and cos data using a look-up \ntable. '), ... 'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Lo_osc'''')'')'), ... 'MaskPromptString', sprintf('Output Bitwidth|counter step|counter start value|Counter Bitwidth|Lookup latency'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit'), ... 'MaskCallbackString', sprintf('||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits=@1;counter_step=@2;counter_start=@3;counter_width=@4;latency=@5;'), ... 'MaskValueString', sprintf('0|3|4|4|2'), ... 'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]')); end % lo_osc_mask function lo_osc_init(blk) end % lo_osc_init function fir_tap_gen(blk) fir_tap_mask(blk); fir_tap_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('fir_tap_init(gcb, ...\n ''factor'', factor, ...\n ''latency'', latency, ...\n ''coeff_bit_width'', coeff_bit_width, ...\n ''coeff_bin_pt'', coeff_bin_pt);')); end % fir_tap_gen function fir_tap_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('fir_tap'), ... 'MaskDescription', sprintf('Multiplies input data with factor specified.'), ... 'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_tap'''')'')'), ... 'MaskPromptString', sprintf('Factor|Mult latency|Coefficient bit width|Coefficient binary point'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit'), ... 'MaskCallbackString', sprintf('|||'), ... 'MaskEnableString', sprintf('on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on'), ... 'MaskVariables', sprintf('factor=@1;latency=@2;coeff_bit_width=@3;coeff_bin_pt=@4;'), ... 'MaskValueString', sprintf('1|2|0|24'), ... 'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]')); end % fir_tap_mask function fir_tap_init(blk) end % fir_tap_init function fir_dbl_tap_gen(blk) fir_dbl_tap_mask(blk); fir_dbl_tap_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('fir_dbl_tap_init(gcb, ...\n ''factor'', factor, ...\n ''add_latency'', add_latency, ...\n ''mult_latency'', mult_latency, ...\n ''coeff_bit_width'', coeff_bit_width, ...\n ''coeff_bin_pt'', coeff_bin_pt);')); end % fir_dbl_tap_gen function fir_dbl_tap_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('fir_dbl_tap'), ... 'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_dbl_tap'''')'')'), ... 'MaskPromptString', sprintf('factor|Add latency|Mult latency|Coefficient bit width|Coefficient binary point '), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit'), ... 'MaskCallbackString', sprintf('||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on'), ... 'MaskVariables', sprintf('factor=@1;add_latency=@2;mult_latency=@3;coeff_bit_width=@4;coeff_bin_pt=@5;'), ... 'MaskValueString', sprintf('0.073384000000000004781952611665474|1|2|0|17'), ... 'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]')); end % fir_dbl_tap_mask function fir_dbl_tap_init(blk) end % fir_dbl_tap_init function lo_const_gen(blk) lo_const_mask(blk); lo_const_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('lo_const_init(gcb, ...\n ''n_bits'', n_bits, ...\n ''phase'', phase);')); end % lo_const_gen function lo_const_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('lo_const'), ... 'MaskDescription', sprintf('Generates a complex constant associated with the \nphase supplied as a parameter.'), ... 'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Lo_const'''')'')'), ... 'MaskPromptString', sprintf('Output Bitwidth|Phase (0 to 2*pi)'), ... 'MaskStyleString', sprintf('edit,edit'), ... 'MaskCallbackString', sprintf('|'), ... 'MaskEnableString', sprintf('on,on'), ... 'MaskVisibilityString', sprintf('on,on'), ... 'MaskToolTipString', sprintf('on,on'), ... 'MaskVariables', sprintf('n_bits=@1;phase=@2;'), ... 'MaskValueString', sprintf('0|0'), ... 'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]')); end % lo_const_mask function lo_const_init(blk) end % lo_const_init function fir_dbl_col_gen(blk) fir_dbl_col_mask(blk); fir_dbl_col_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('fir_dbl_col_init(gcb, ...\n ''n_inputs'', n_inputs, ...\n ''coeff'', coeff, ...\n ''mult_latency'', mult_latency, ...\n ''add_latency'', add_latency, ...\n ''coeff_bit_width'', coeff_bit_width, ...\n ''coeff_bin_pt'', coeff_bin_pt, ...\n ''first_stage_hdl'', first_stage_hdl, ...\n ''adder_imp'', adder_imp);')); end % fir_dbl_col_gen function fir_dbl_col_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('fir_dbl_col'), ... 'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_dbl_col'''')'')'), ... 'MaskPromptString', sprintf('Inputs|Coefficients|Add latency|Mult Latency|Coefficient bit width|Coefficient binary point|Implement first stage of adder trees on output as behavioural HDL|Adder implementation'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,checkbox,popup(Behavioral|Fabric|DSP48)'), ... 'MaskCallbackString', sprintf('|||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_inputs=@1;coeff=@2;add_latency=@3;mult_latency=@4;coeff_bit_width=@5;coeff_bin_pt=@6;first_stage_hdl=&7;adder_imp=&8;'), ... 'MaskValueString', sprintf('0|0.10000000000000000555111512312578|2|3|25|24|off|Fabric'), ... 'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]')); end % fir_dbl_col_mask function fir_dbl_col_init(blk) end % fir_dbl_col_init function dds_gen(blk) dds_mask(blk); dds_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('dds_init(gcb, ...\n ''freq_div'', freq_div, ...\n ''freq'', freq, ...\n ''num_lo'', num_lo, ...\n ''n_bits'', n_bits, ...\n ''latency'', latency);')); end % dds_gen function dds_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('dds'), ... 'MaskDescription', sprintf('Generates P channels of sin and cos data for mixing\nwith input data in a DDC. To generate frequency \nN/M(Fc x P) (where Fc is the clock rate) \nM = "Frequency Divisions", N = "Frequency",\nParallel LOs = P'), ... 'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Dds'''')'')'), ... 'MaskPromptString', sprintf('Frequency divisions (M)|Frequency (? / M*2pi)|Parallel LOs|Bit Width|Latency'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit'), ... 'MaskCallbackString', sprintf('||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on'), ... 'MaskVariables', sprintf('freq_div=@1;freq=@2;num_lo=@3;n_bits=@4;latency=@5;'), ... 'MaskValueString', sprintf('4|1|0|8|2'), ... 'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]')); end % dds_mask function dds_init(blk) end % dds_init function fir_col_gen(blk) fir_col_mask(blk); fir_col_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('fir_col_init(gcb, ...\n ''n_inputs'', n_inputs,...\n ''coeff'', coeff, ...\n ''mult_latency'', mult_latency, ...\n ''add_latency'', add_latency, ...\n ''coeff_bit_width'', coeff_bit_width, ...\n ''coeff_bin_pt'', coeff_bin_pt, ...\n ''first_stage_hdl'', first_stage_hdl, ...\n ''adder_imp'', adder_imp);')); end % fir_col_gen function fir_col_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('fir_col'), ... 'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_col'''')'')'), ... 'MaskPromptString', sprintf('Inputs|Coefficients|Add latency|Mult Latency|Coefficient bit width|Coefficient binary point|Implement first stage of adder trees on output as behavioural HDL|Adder implementation'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,checkbox,popup(Behavioral|Fabric|DSP48)'), ... 'MaskCallbackString', sprintf('|||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_inputs=@1;coeff=@2;add_latency=@3;mult_latency=@4;coeff_bit_width=@5;coeff_bin_pt=@6;first_stage_hdl=&7;adder_imp=&8;'), ... 'MaskValueString', sprintf('0|0.10000000000000000555111512312578|2|3|25|24|off|Fabric'), ... 'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]')); end % fir_col_mask function fir_col_init(blk) end % fir_col_init function rcmult_gen(blk) rcmult_mask(blk); rcmult_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('rcmult_init(gcb, ...\n ''latency'', latency);')); end % rcmult_gen function rcmult_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('rcmult'), ... 'MaskDescription', sprintf('Multiplies input data with cos and sin inputs and\noutputs results on real and imag ports \nrespectively. '), ... 'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Rcmult'''')'')'), ... 'MaskPromptString', sprintf('Multiplier latency'), ... 'MaskStyleString', sprintf('edit'), ... 'MaskEnableString', sprintf('on'), ... 'MaskVisibilityString', sprintf('on'), ... 'MaskToolTipString', sprintf('on'), ... 'MaskVariables', sprintf('latency=@1;'), ... 'MaskValueString', sprintf('0'), ... 'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]')); end % rcmult_mask function rcmult_init(blk) end % rcmult_init function dec_fir_async_gen(blk) dec_fir_async_mask(blk); dec_fir_async_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('dec_fir_async_init(gcb);')); end % dec_fir_async_gen function dec_fir_async_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('dec_fir_async'), ... 'MaskDescription', sprintf('FIR filter which can handle multiple time samples in parallel and decimates down to 1 time sample. If coefficients are symmetric, will automatically fold before multiplying.'), ... 'MaskPromptString', sprintf('Number of Parallel Streams|Coefficients|Output bitwidth|Output binary point|Quantization Behavior|Add Latency|Mult Latency|Convert latency|Coefficient bitwidth|Coefficient binary point|Post adder-tree shift|Absorb adders into DSP slices|Adder implementation|Asynchronous ops|Bus input|Input bitwidth|Input binary point|Input datatype'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,popup(Truncate|Round (unbiased: +/- Inf)|Round (unbiased: Even Values)),edit,edit,edit,edit,edit,edit,checkbox,popup(Behavioral|Fabric|DSP48),checkbox,checkbox,edit,edit,popup(Signed|Unsigned)'), ... 'MaskCallbackString', sprintf('||||||||||||||onoff = get_param(gcb, ''bus_input'');\nset_param_state(gcb, ''input_width'', onoff)\nset_param_state(gcb, ''input_bp'', onoff)\nset_param_state(gcb, ''input_type'', onoff)|||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,off,off,off'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_inputs=@1;coeff=@2;output_width=@3;output_bp=@4;quantization=&5;add_latency=@6;mult_latency=@7;conv_latency=@8;coeff_bit_width=@9;coeff_bin_pt=@10;lshift=@11;absorb_adders=&12;adder_imp=&13;async=&14;bus_input=&15;input_width=@16;input_bp=@17;input_type=&18;'), ... 'MaskValueString', sprintf('0|0.10000000000000000555111512312578|8|7|Round (unbiased: +/- Inf)|1|2|2|25|24|1|on|DSP48|off|off|0|0|Signed'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]'), ... 'Tag', sprintf('casper:dec_fir_async')); end % dec_fir_async_mask function dec_fir_async_init(blk) end % dec_fir_async_init function fir_tap_async_gen(blk) fir_tap_async_mask(blk); fir_tap_async_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('fir_tap_async_init(gcb);')); end % fir_tap_async_gen function fir_tap_async_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('fir_tap_async'), ... 'MaskDescription', sprintf('Multiplies input data with factor specified.'), ... 'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_tap'''')'')'), ... 'MaskPromptString', sprintf('Factor|Add latency|Mult latency|Coefficient bit width|Coefficient binary point|Asynchronous ops|Double tap'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit,checkbox,checkbox'), ... 'MaskCallbackString', sprintf('||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('factor=@1;add_latency=@2;mult_latency=@3;coeff_bit_width=@4;coeff_bin_pt=@5;async=&6;dbl=&7;'), ... 'MaskValueString', sprintf('1|1|2|0|24|off|off'), ... 'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]')); end % fir_tap_async_mask function fir_tap_async_init(blk) end % fir_tap_async_init function fir_col_async_gen(blk) fir_col_async_mask(blk); fir_col_async_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('fir_col_async_init(gcb);')); end % fir_col_async_gen function fir_col_async_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('fir_col_async'), ... 'MaskHelp', sprintf('eval(''xlWeb(''''http://casper.berkeley.edu/wiki/Fir_col'''')'')'), ... 'MaskPromptString', sprintf('Inputs|Coefficients|Add latency|Mult Latency|Coefficient bit width|Coefficient binary point|Implement first stage of adder trees on output as behavioural HDL|Adder implementation|Asynchronous ops|Bus input|Input bitwidth|Input binary point|Input datatype|Double col'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,checkbox,popup(Behavioral|Fabric|DSP48),checkbox,checkbox,edit,edit,popup(Signed|Unsigned),checkbox'), ... 'MaskCallbackString', sprintf('|||||||||onoff = get_param(gcb, ''bus_input'');\nset_param_state(gcb, ''input_width'', onoff)\nset_param_state(gcb, ''input_bp'', onoff)\nset_param_state(gcb, ''input_type'', onoff)||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,off,off,off,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_inputs=@1;coeff=@2;add_latency=@3;mult_latency=@4;coeff_bit_width=@5;coeff_bin_pt=@6;first_stage_hdl=&7;adder_imp=&8;async=&9;bus_input=&10;input_width=@11;input_bp=@12;input_type=&13;dbl=&14;'), ... 'MaskValueString', sprintf('0|0.10000000000000000555111512312578|2|3|25|24|off|Fabric|off|off|16|0|Signed|off'), ... 'BackgroundColor', sprintf('[0.501961, 0.501961, 0.501961]')); end % fir_col_async_mask function fir_col_async_init(blk) end % fir_col_async_init
github
mstrader/mlib_devel-master
last_tap_init.m
.m
mlib_devel-master/casper_library/last_tap_init.m
3,201
utf_8
b4a61bac8f0d784d5db5bf82b9eb1e81
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2007 Terry Filiba, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function last_tap_init(blk, varargin) % Initialize and configure the last tap of the Polyphase Filter Bank. % % last_tap_init(blk, varargin) % % blk = The block to configure. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % TotalTaps = Total number of taps in the PFB % BitWidthIn = Input Bitwidth % BitWidthOut = Output Bitwidth % CoeffBitWidth = Bitwidth of Coefficients. % add_latency = Latency through each adder. % mult_latency = Latency through each multiplier % quantization = 'Truncate', 'Round (unbiased: +/- Inf)', or 'Round % (unbiased: Even Values)' % Declare any default values for arguments you might like. defaults = {}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'last_tap'); munge_block(blk, varargin{:}); propagate_vars([blk,'/pfb_add_tree'], 'defaults', defaults, varargin{:}); use_hdl = get_var('use_hdl','defaults', defaults, varargin{:}); use_embedded = get_var('use_embedded','defaults', defaults, varargin{:}); set_param([blk,'/Mult'],'use_embedded',use_embedded); set_param([blk,'/Mult'],'use_behavioral_HDL',use_hdl); set_param([blk,'/Mult1'],'use_embedded',use_embedded); set_param([blk,'/Mult1'],'use_behavioral_HDL',use_hdl) TotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:}); fmtstr = sprintf('taps=%d', TotalTaps); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:});
github
mstrader/mlib_devel-master
barrel_switcher_init.m
.m
mlib_devel-master/casper_library/barrel_switcher_init.m
7,183
utf_8
1bc6d7d6ad595f2b3ef0271a4dd0a5e4
% Initialize and configure the barrel switcher. % % barrel_switcher_init(blk, varargin) % % blk = The block to configure. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % n_inputs = Number of inputs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2007 Terry Filiba, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function barrel_switcher_init(blk, varargin) clog('entering barrel_switcher_init', {'trace', 'barrel_switcher_init_debug'}); % Declare any default values for arguments you might like. % reg_retiming is not an actual parameter of this block, but it is included % in defaults so that same_state will return false for blocks drawn prior to % adding reg_retiming='on' to some of the underlying Delay blocks. defaults = { ... 'n_inputs', 1, ... 'async', 'off', ... 'reg_retiming', 'on', ... }; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'barrel_switcher') munge_block(blk, varargin{:}) n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); delete_lines(blk); %default case for library storage if n_inputs == 0, clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting barrel_switcher_init', {'trace', 'barrel_switcher_init_debug'}); return; end reuse_block(blk, 'sel', 'built-in/inport', 'Position', [15 23 45 37], 'Port', '1'); % % sync data path % reuse_block(blk, 'sync_in', 'built-in/inport',... 'Position', [15 (2^n_inputs+1)*80+95 45 109+80*(2^n_inputs+1)], 'Port', '2'); reuse_block(blk, 'sync_out', 'built-in/outport',... 'Position', [135 (2^n_inputs+1)*80+95 165 109+80*(2^n_inputs+1)], 'Port', '1'); reuse_block(blk, 'Delay_sync', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'on', 'latency', num2str(n_inputs), ... 'Position', [75 (2^n_inputs+1)*80+95 105 109+80*(2^n_inputs+1)]); add_line(blk, 'sync_in/1', 'Delay_sync/1'); add_line(blk, 'Delay_sync/1', 'sync_out/1'); % % muxes % for i=1:2^n_inputs, reuse_block(blk, ['In',num2str(i)], 'built-in/inport', 'Position', [15 i*80+95 45 109+80*i]); reuse_block(blk, ['Out',num2str(i)], 'built-in/outport', 'Position', [15+150*(n_inputs+1) 95+i*80 45+150*(n_inputs+1) 109+80*i]); for j=1:n_inputs, reuse_block(blk, ['Mux', num2str(10*i + j)], 'xbsIndex_r4/Mux', ... 'latency', '1', 'Position', [15+150*j, 67+80*i, 40+150*j, 133+80*i]); end end for j=1:(n_inputs-1), reuse_block(blk, ['Delay', num2str(j)], 'xbsIndex_r4/Delay', ... 'reg_retiming', 'on', 'Position', [15+150*j 15 45+150*j 45]); end for j=1:n_inputs, reuse_block(blk, ['Slice', num2str(j)], 'xbsIndex_r4/Slice', ... 'Position', [85+150*(j-1) 91 130+150*(j-1) 119], 'bit1', ['-', num2str(j-1)]); end add_line(blk, 'sel/1', 'Slice1/1'); if n_inputs > 1, add_line(blk, 'sel/1', 'Delay1/1'); end for j=1:(n_inputs-2), delayname = ['Delay', num2str(j)]; nextdelay = ['Delay', num2str(j+1)]; add_line(blk, [delayname, '/1'], [nextdelay, '/1']); end for j=1:(n_inputs-1), slicename = ['Slice', num2str(j+1)]; delayname = ['Delay', num2str(j)]; add_line(blk, [delayname, '/1'], [slicename, '/1']); end for j=1:n_inputs, slicename = ['Slice', num2str(j)]; for i=1:2^n_inputs muxname = ['Mux', num2str(10*i + j)]; add_line(blk, [slicename, '/1'], [muxname, '/1']); end end for i=1:2^n_inputs, iport = ['In', num2str(i)]; oport = ['Out', num2str(i)]; firstmux = ['Mux', num2str(10*i + 1)]; if i > 2^n_inputs / 2 swmux = ['Mux', num2str(10*(i-2^n_inputs/2) + 1)]; else swmux = ['Mux', num2str(10*(i-2^n_inputs/2 + 2^n_inputs) + 1)]; end lastmux = ['Mux', num2str(10*i + n_inputs)]; add_line(blk, [iport, '/1'], [firstmux, '/2']); add_line(blk, [iport, '/1'], [swmux, '/3']); add_line(blk, [lastmux, '/1'], [oport, '/1']); end for i=1:2^n_inputs, for j=1:(n_inputs-1) muxname = ['Mux', num2str(10*i + j)]; nextmuxname = ['Mux', num2str(10*i + j+1)]; add_line(blk, [muxname, '/1'], [nextmuxname, '/2']); if i > 2^n_inputs / (2^(j+1)) swmux = ['Mux', num2str(10*(i-2^n_inputs/(2^(j+1))) + j+1)]; else swmux = ['Mux', num2str(10*(i-2^n_inputs/(2^(j+1)) + 2^n_inputs) + j+1)]; end add_line(blk, [muxname, '/1'], [swmux, '/3']); end end % % data valid % if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/inport',... 'Position', [15 (2^n_inputs+2)*80+95 45 109+80*(2^n_inputs+2)], 'Port', num2str(2^n_inputs+3)); reuse_block(blk, 'dvalid', 'built-in/outport',... 'Position', [135 (2^n_inputs+2)*80+95 165 109+80*(2^n_inputs+2)], 'Port', num2str(2^n_inputs+2)); reuse_block(blk, 'den', 'xbsIndex_r4/Delay', ... 'reg_retiming', 'on', 'latency', num2str(n_inputs), ... 'Position', [75 (2^n_inputs+2)*80+95 105 109+80*(2^n_inputs+2)]); add_line(blk, 'en/1', 'den/1'); add_line(blk, 'den/1', 'dvalid/1'); end clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting barrel_switcher_init', {'trace', 'barrel_switcher_init_debug'}); end %function
github
mstrader/mlib_devel-master
rcs_init.m
.m
mlib_devel-master/casper_library/rcs_init.m
12,031
utf_8
c057a49a7b8e6b434c3314e6d96c3705
% Embed revision control info into gateware % % rcs_init(blk, varargin) % % blk = The block to be configured. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % app_src = Revision source for application (git, svn, timestamp) % lib_src = Revision source for libraries (git, svn, timestamp) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2010 Andrew Martens (meerKAT) % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function rcs_init(blk, varargin), clog('entering rcs_init', 'trace'); check_mask_type(blk, 'rcs'); munge_block(blk, varargin); defaults = { 'app_src', 'timestamp', 'lib_src', 'timestamp'}; app_src = get_var('app_src', 'defaults', defaults, varargin{:}); lib_src = get_var('lib_src', 'defaults', defaults, varargin{:}); system_os = determine_os(); % application info path = which(gcs); indices = regexp(path,['/']); if isempty(indices), disp('rcs_init: Model must be saved to get revision info for it, using current time as revision'); app_src = 'timestamp'; else, app_dir = path(1:indices(length(indices))); app_file = path(indices(length(indices))+1:length(path)); end app_revision = 0; app_dirty = 1; if strcmp(app_src, 'svn') == 1 || strcmp(app_src, 'git') == 1, [app_result, app_revision, app_dirty] = get_revision_info(system_os, app_src, app_dir, app_file); if app_result ~= 0, disp('rcs_init: Failed to get revision info for application from specified source, will use timestamp'); app_src = 'timestamp'; end end app_timestamp = 0; if isempty(indices), [app_timestamp_result, app_timestamp] = get_current_time(); else, [app_timestamp_result, app_timestamp] = get_timestamp(system_os, path); end if app_timestamp_result ~= 0, disp('rcs_init: Failed to get timestamp info for design. No revision info possible!'); end %set up application registers result = set_registers(blk, 'app', app_src, app_timestamp, app_revision, app_dirty); if result ~= 0, disp('rcs_init: Failed to set application registers'); end % libraries info path = getenv('MLIB_DEVEL_PATH'); %the new path to the CASPER libraries if isempty(path), path = getenv('MLIB_ROOT'); %the older path to CASPER libraries end if isempty(path), %neither paths give us anything disp('rcs_init: MLIB_DEVEL_PATH or MLIB_ROOT must be defined in your system, using current time as revision'); lib_src = 'timestamp'; end lib_dir = path; lib_revision = 0; lib_dirty = 1; if strcmp(lib_src, 'svn') == 1 || strcmp(lib_src, 'git') == 1, [lib_result, lib_revision, lib_dirty] = get_revision_info(system_os, lib_src, lib_dir, ''); if lib_result ~= 0, disp('rcs_init: Failed to get revision info for libraries from specified source, will use current time as timestamp'); lib_src = 'timestamp'; else end end lib_timestamp = 0; [lib_timestamp_result, lib_timestamp] = get_current_time(); if lib_timestamp_result ~= 0, disp('rcs_init: Failed to get timestamp for libraries. No revision info possible!'); end %set up application registers result = set_registers(blk, 'lib', lib_src, lib_timestamp, lib_revision, lib_dirty); if result ~= 0, disp('rcs_init: Failed to set library registers'); end clog('exiting rcs_init', 'trace'); end function [result] = set_registers(blk, section, info_type, timestamp, revision, dirty) result = 1; if strcmp(info_type, 'git'), clog(sprintf('%s revision :%x dirty :%d', section, revision, dirty),'rcs_init_debug'); elseif strcmp(info_type, 'svn'), clog(sprintf('%s revision :%d dirty :%d', section, revision, dirty),'rcs_init_debug'); end clog(sprintf('%s timestamp :%s', section, num2str(timestamp,10)),'rcs_init_debug'); % set up mux and revision type if strcmp(info_type, 'timestamp'), const = 1; type = 0; elseif strcmp(info_type, 'git'), type = 0; const = 0; elseif strcmp(info_type, 'svn'), const = 0; type = 1; end set_param([blk, '/', section, '_type'], 'const', num2str(const)); % timestamp % blank out most sig bit so fits in 31 bits, valid till set_param([blk, '/', section, '_timestamp'], 'const', num2str(bitset(uint32(timestamp),32,0))); % revision info set_param([blk, '/', section, '_rcs_type'], 'const', num2str(type)); if strcmp(info_type, 'git'), rev = sprintf('hex2dec(''%x'')',revision); else rev = num2str(revision); end set_param([blk, '/', section, '_revision'], 'const', rev); set_param([blk, '/', section, '_dirty'], 'const', num2str(dirty)); result = 0; end % returns current time in number of seconds since epoch function [result, timestamp] = get_current_time() timestamp = round(etime(clock, [1970 1 1 0 0 0])); result = 0; end function [result, timestamp] = get_timestamp(system_os, path) result = 1; if strcmp(system_os,'windows') == 1, %TODO windows timestamp disp('rcs_init: can''t do timestamp in Windoze yet'); clog('rcs_init: can''t do timestamp in Windoze yet','error'); elseif strcmp(system_os, 'linux'), % take last modification time as timestamp % in seconds since epoch [s, r] = system(['ls -l --time-style=+%s ',path]); if s == 0, info = regexp(r,'\s+','split'); timestamp = str2num(info{6}); if isnumeric(timestamp), result = 0; end else disp('rcs_init: failure using ''ls -l ',path,''' in Linux'); clog('rcs_init: failure using ''ls -l ',path,''' in Linux','error'); end else disp(['rcs_init: unknown os ',system_os]); clog(['rcs_init: unknown os ',system_os],'error'); end return; end function [system_os] = determine_os() %following os detection logic lifted from gen_xps_files, thanks Dave G [s,w] = system('uname -a'); system_os = 'linux'; if s ~= 0 system_os = 'windows'; elseif ~isempty(regexp(w,'Linux')) system_os = 'linux'; end clog([system_os,' system detected'],'rcs_init_debug'); end function [result, revision, dirty] = get_revision_info(system_os, rev_sys, dir, file), result = 1; %tough crowd revision = 0; dirty = 1; if strcmp(rev_sys, 'git') == 1 , if strcmp(system_os,'windows') == 1, %TODO git in windows disp('rcs_init: can''t handle git in Windows yet'); clog('rcs_init: can''t handle git in Windows yet','error'); elseif strcmp(system_os,'linux') == 1, %get latest commit [s, r] = system(['cd ',dir,'; git log -n 1 --abbrev-commit ',file,'| grep commit']); if s == 0, % get first commit from log indices=regexp(r,[' ']); if length(indices) ~= 0, revision = uint32(0); % convert text to 28 bit value for n = 0:6, revision = bitor(revision, bitshift(uint32(hex2dec(r(indices(1)+n+1))), (6-n)*4)); end result = 0; end % determine if dirty. If file, must not appear, if whole repository, must be clean if isempty(file), search = 'grep "nothing to commit (working directory clean)"'; else, search = ['grep ',file,' | grep modified']; end dirty = 1; [s, r] = system(['cd ',dir,'; git status |', search]); clog(['cd ',dir,'; git status | ', search], 'rcs_init_debug'); clog([num2str(s),' : ',r], 'rcs_init_debug'); % failed to find modified string if ~isempty(file) && s == 1 && isempty(r), dirty = 0; % git succeeded and found nothing to commit elseif isempty(file) && s == 0, dirty = 0; end else disp(['rcs_init: failure using ''cd ',dir,'; git log -n 1 --abbrev-commit ',file,' | grep commit'' in Linux']); clog(['rcs_init: failure using ''cd ',dir,'; git log -n 1 --abbrev-commit ',file,' | grep commit'' in Linux'], 'error'); end else disp(['rcs_init: unrecognised os ',system_os]); end elseif strcmp(rev_sys, 'svn') == 1, if strcmp(system_os,'windows') == 1, % tortoiseSVN [usr_r,usr_rev] = system(sprintf('%s %s\%s', 'SubWCRev.exe', dir, file)); if (usr_r == 0) %success if (~isempty(regexp(usr_rev,'Local modifications'))) % we have local mods dirty = 1; else dirty = 0; end temp=regexp(usr_rev,'Updated to revision (?<rev>\d+)','tokens'); if (~isempty(temp)) revision = str2num(temp{1}{1}); else temp=regexp(usr_rev,'Last committed at revision (?<rev>\d+)','tokens'); if (~isempty(temp)) revision = str2num(temp{1}{1}); end end clog(['tortioseSVN revision :',num2str(revision),' dirty: ',num2str(dirty)],'rcs_init_debug'); result = 0; else disp(['rcs_init: failure using ''SubWCRev.exe ',dir,'\',file,''' in Windoze']); clog(['rcs_init: failure using ''SubWCRev.exe ',dir,'\',file,''' in Windoze'],'rcs_init_debug'); end elseif strcmp(system_os, 'linux'), % svn in linux %revision number [usr_r,usr_rev] = system(sprintf('%s %s%s', 'svn info', dir, file)); if (usr_r == 0) temp=regexp(usr_rev,'Revision: (?<rev>\d+)','tokens'); if (~isempty(temp)) revision = str2num(temp{1}{1}); end %modified status [usr_r,usr_rev] = system(sprintf('%s %s%s', 'svn status 2>/dev/null | grep ''^[AMD]'' | wc -l', dir, file)); if (usr_r == 0) if (str2num(usr_rev) > 0) dirty = 1; else dirty = 0; end else disp(['rcs_init: failure using ''svn status ',dir,file,''' in Linux']); clog(['rcs_init: failure using ''svn status ',dir,file,''' in Linux'],'error'); end if isnumeric(revision), result = 0; end else disp(sprintf('rcs_init: failure using ''svn info ''%s%s'' in Linux\nError msg: ''%s''', dir, file, usr_rev)); clog(sprintf('rcs_init: failure using ''svn info ''%s%s'' in Linux\nError msg: ''%s''', dir, file ,usr_rev), 'error'); end else disp(['rcs_init: unrecognised os ',system_os]); end else disp(['rcs_init: unrecognised revision system ', rev_sys]); clog(['rcs_init: unrecognised revision system ', rev_sys], 'error'); end %revision system return; end
github
mstrader/mlib_devel-master
delay_bram_prog_dp_init.m
.m
mlib_devel-master/casper_library/delay_bram_prog_dp_init.m
4,950
utf_8
eeab252737022d3657e6b9ada95a8180
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function delay_bram_prog_dp_init(blk, varargin) log_group = 'delay_bram_prog_dp_init_debug'; clog('entering delay_bram_prog_dp_init', {log_group, 'trace'}); defaults = { ... 'ram_bits', 10, ... 'bram_latency', 2, ... 'async', 'off'}; check_mask_type(blk, 'delay_bram_prog_dp'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); ram_bits = get_var('ram_bits', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); delete_lines(blk); if (ram_bits == 0), clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting delay_bram_prog_dp_init', {log_group, 'trace'}); return; end reuse_block(blk, 'din', 'built-in/Inport', 'Port', '1', 'Position', [235 43 265 57]); reuse_block(blk, 'delay', 'built-in/Inport', 'Port', '2', 'Position', [115 83 145 97]); if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/Inport', 'Port', '3', 'Position', [15 28 45 42]); end reuse_block(blk, 'wr_addr', 'xbsIndex_r4/Counter', ... 'n_bits', 'ram_bits', 'use_behavioral_HDL', 'on', 'use_rpm', 'on', ... 'en', async, 'Position', [75 18 110 52]); if strcmp(async, 'on'), add_line(blk, 'en/1', 'wr_addr/1'); end reuse_block(blk, 'AddSub', 'xbsIndex_r4/AddSub', ... 'mode', 'Subtraction', 'latency', '1', ... 'precision', 'User Defined', 'n_bits', 'ram_bits', 'bin_pt', '0', ... 'use_behavioral_HDL', 'on', 'use_rpm', 'on', ... 'Position', [175 52 225 103]); add_line(blk, 'delay/1', 'AddSub/2'); add_line(blk, 'wr_addr/1', 'AddSub/1'); reuse_block(blk, 'Constant2', 'xbsIndex_r4/Constant', ... 'arith_type', 'Boolean', 'n_bits', '1', 'bin_pt', '0', ... 'explicit_period', 'on', 'Position', [285 56 300 74]); reuse_block(blk, 'Constant4', 'xbsIndex_r4/Constant', ... 'const', '0', 'arith_type', 'Boolean', 'n_bits', '1', 'bin_pt', '0', ... 'explicit_period', 'on', 'Position', [285 102 300 118]); reuse_block(blk, 'Dual Port RAM', 'xbsIndex_r4/Dual Port RAM', ... 'depth', '2^ram_bits', 'initVector', '0', ... 'latency', 'bram_latency', 'write_mode_B', 'Read Before Write', ... 'optimize', 'Area', 'Position', [315 26 385 119]); add_line(blk, 'din/1', 'Dual Port RAM/2'); add_line(blk, 'din/1', 'Dual Port RAM/5'); add_line(blk, 'wr_addr/1', 'Dual Port RAM/1'); add_line(blk, 'AddSub/1', 'Dual Port RAM/4'); add_line(blk, 'Constant2/1', 'Dual Port RAM/3'); add_line(blk, 'Constant4/1', 'Dual Port RAM/6'); reuse_block(blk, 'Terminator', 'built-in/Terminator', 'Position', [420 40 440 60]); add_line(blk,'Dual Port RAM/1', 'Terminator/1'); reuse_block(blk, 'dout', 'built-in/Outport', 'Port', '1', 'Position', [415 88 445 102]); add_line(blk, 'Dual Port RAM/2', 'dout/1'); % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting delay_bram_prog_dp_init', {log_group, 'trace'}); end % delay_bram_prog_dp_init
github
mstrader/mlib_devel-master
cmult_init.m
.m
mlib_devel-master/casper_library/cmult_init.m
15,367
utf_8
ebc6efcdec67117f0f322f39cf8b1e56
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function cmult_init(blk, varargin) % Configure a cmult block. % % cmult_init(blk, n_bits_b, bin_pt_b, n_bits_w, bin_pt_w, ... % n_bits_bw, bin_pt_bw, quantization, overflow, ... % mult_latency, add_latency) % % blk = Block to configure % n_bits_X = Number of bits for port X. % Assumed equal for both components. % bin_pt_X = Binary Point for port X. % Assumed equal for both components. % quantization = Quantization mode % 1 = 'Truncate' % 2 = 'Round (unbiased: +/- Inf)' % 3 = 'Round (unbiased: Even Values)' % overflow - Overflow mode % 1 = 'Wrap' % 2 = 'Saturate' % mult_latency = Latency to use for the underlying real multipliers. % add_latency = Latency to use for the underlying real adders. % conjugated = Whether or not to conjugate the 'a' input. % Set default vararg values. % reg_retiming is not an actual parameter of this block, but it is included % in defaults so that same_state will return false for blocks drawn prior to % adding reg_retiming='on' to some of the underlying Delay blocks. defaults = { ... 'n_bits_a', 18, ... 'bin_pt_a', 17, ... 'n_bits_b', 18, ... 'bin_pt_b', 17, ... 'n_bits_ab', 37, ... 'bin_pt_ab', 14, ... 'quantization', 'Truncate', ... 'overflow', 'Wrap', ... 'mult_latency', 3, ... 'add_latency', 1, ... 'conv_latency', 1, ... 'in_latency', 0, ... 'conjugated', 'off', ... 'async', 'off', ... 'pipelined_enable', 'on', ... 'multiplier_implementation', 'behavioral HDL', ... 'reg_retiming', 'on', ... }; if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk,varargin); n_bits_a = get_var('n_bits_a','defaults',defaults,varargin{:}); n_bits_b = get_var('n_bits_b','defaults',defaults,varargin{:}); n_bits_ab = get_var('n_bits_ab','defaults',defaults,varargin{:}); bin_pt_a = get_var('bin_pt_a','defaults',defaults,varargin{:}); bin_pt_b = get_var('bin_pt_b','defaults',defaults,varargin{:}); bin_pt_ab = get_var('bin_pt_ab','defaults',defaults,varargin{:}); quantization = get_var('quantization','defaults',defaults,varargin{:}); overflow = get_var('overflow','defaults',defaults,varargin{:}); mult_latency = get_var('mult_latency','defaults',defaults,varargin{:}); add_latency = get_var('add_latency','defaults',defaults,varargin{:}); conv_latency = get_var('conv_latency','defaults',defaults,varargin{:}); in_latency = get_var('in_latency','defaults',defaults,varargin{:}); conjugated = get_var('conjugated','defaults',defaults,varargin{:}); async = get_var('async','defaults',defaults,varargin{:}); pipelined_enable = get_var('pipelined_enable','defaults',defaults,varargin{:}); multiplier_implementation = get_var('multiplier_implementation','defaults',defaults,varargin{:}); delete_lines(blk); if n_bits_a == 0 || n_bits_b == 0, clean_blocks(blk); set_param(blk,'AttributesFormatString',''); save_state(blk, 'defaults', defaults, varargin{:}); return; end if (n_bits_a < bin_pt_a), errordlg('Number of bits for a input must be greater than binary point position.'); return; end if (n_bits_b < bin_pt_b), errordlg('Number of bits for b input must be greater than binary point position.'); return; end if (n_bits_ab < bin_pt_ab), errordlg('Number of bits for ab input must be greater than binary point position.'); return; end %ports reuse_block(blk, 'a', 'built-in/Inport', 'Port', '1', 'Position', [5 148 35 162]); reuse_block(blk, 'b', 'built-in/Inport', 'Port', '2', 'Position', [5 333 35 347]); if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/Inport', 'Port', '3', 'Position', [5 478 35 492]); end %replication layer if strcmp(async, 'off') || strcmp(pipelined_enable, 'on'), latency = in_latency; else, latency = 0; end reuse_block(blk, 'a_replicate', 'casper_library_bus/bus_replicate', ... 'replication', '2', 'latency', num2str(latency), 'misc', 'off', ... 'Position', [90 143 125 167]); add_line(blk, 'a/1', 'a_replicate/1'); reuse_block(blk, 'b_replicate', 'casper_library_bus/bus_replicate', ... 'replication', '2', 'latency', num2str(latency), 'misc', 'off', ... 'Position', [90 328 125 352]); add_line(blk, 'b/1', 'b_replicate/1'); if strcmp(async, 'on'), reuse_block(blk, 'en_replicate0', 'casper_library_bus/bus_replicate', ... 'replication', '5', 'latency', num2str(latency), 'misc', 'off', ... 'Position', [90 473 125 497]); add_line(blk, 'en/1', 'en_replicate0/1'); reuse_block(blk, 'en_expand0', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', '5', ... 'outputWidth', mat2str(ones(1, 5)), 'outputBinaryPt', mat2str(zeros(1, 5)), ... 'outputArithmeticType', mat2str(2*ones(1, 5)), ... 'Position', [180 436 230 534]); add_line(blk, 'en_replicate0/1', 'en_expand0/1'); end %bus_expand layer reuse_block(blk, 'a_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', '4', ... 'outputWidth', mat2str(repmat(n_bits_a, 1, 4)), ... 'outputBinaryPt', mat2str(repmat(bin_pt_a, 1, 4)), ... 'outputArithmeticType', mat2str(ones(1,4)), ... 'Position', [180 106 230 199]); add_line(blk, 'a_replicate/1', 'a_expand/1'); reuse_block(blk, 'b_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', '4', ... 'outputWidth', mat2str(repmat(n_bits_b, 1, 4)), ... 'outputBinaryPt', mat2str(repmat(bin_pt_b, 1, 4)), ... 'outputArithmeticType', mat2str(ones(1,4)), ... 'Position', [180 291 230 384]); add_line(blk, 'b_replicate/1', 'b_expand/1'); %multipliers if strcmp(multiplier_implementation, 'behavioral HDL'), use_behavioral_HDL = 'on'; use_embedded = 'off'; else use_behavioral_HDL = 'off'; if strcmp(multiplier_implementation, 'embedded multiplier core'), use_embedded = 'on'; elseif strcmp(multiplier_implementation, 'standard core'), use_embedded = 'off'; else, end end reuse_block(blk, 'rere', 'xbsIndex_r4/Mult', ... 'use_behavioral_HDL', use_behavioral_HDL, 'use_embedded', use_embedded, ... 'en', async, 'latency', num2str(mult_latency), 'precision', 'Full', ... 'Position', [290 102 340 153]); add_line(blk, 'a_expand/1', 'rere/1'); add_line(blk, 'b_expand/1', 'rere/2'); reuse_block(blk, 'imim', 'xbsIndex_r4/Mult', ... 'use_behavioral_HDL', use_behavioral_HDL, 'use_embedded', use_embedded, ... 'en', async, 'latency', num2str(mult_latency), 'precision', 'Full', ... 'Position', [290 172 340 223]); add_line(blk, 'a_expand/2', 'imim/1'); add_line(blk, 'b_expand/2', 'imim/2'); reuse_block(blk, 'imre', 'xbsIndex_r4/Mult', ... 'use_behavioral_HDL', use_behavioral_HDL, 'use_embedded', use_embedded, ... 'en', async, 'latency', num2str(mult_latency), 'precision', 'Full', ... 'Position', [290 267 340 318]); add_line(blk, 'a_expand/4', 'imre/1'); add_line(blk, 'b_expand/3', 'imre/2'); reuse_block(blk, 'reim', 'xbsIndex_r4/Mult', ... 'use_behavioral_HDL', use_behavioral_HDL, 'use_embedded', use_embedded, ... 'en', async, 'latency', num2str(mult_latency), 'precision', 'Full', ... 'Position', [290 337 340 388]); add_line(blk, 'a_expand/3', 'reim/1'); add_line(blk, 'b_expand/4', 'reim/2'); if strcmp(async, 'on'), add_line(blk, 'en_expand0/1', 'rere/3'); add_line(blk, 'en_expand0/2', 'imim/3'); add_line(blk, 'en_expand0/3', 'imre/3'); add_line(blk, 'en_expand0/4', 'reim/3'); if strcmp(pipelined_enable, 'on'), latency = mult_latency; else, latency = 0; end reuse_block(blk, 'en_replicate1', 'casper_library_bus/bus_replicate', ... 'replication', '3', 'latency', num2str(latency), 'misc', 'off', ... 'Position', [295 523 330 547]); add_line(blk, 'en_expand0/5', 'en_replicate1/1'); reuse_block(blk, 'en_expand1', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', '3', ... 'outputWidth', mat2str(ones(1, 3)), 'outputBinaryPt', mat2str(zeros(1, 3)), ... 'outputArithmeticType', mat2str(2*ones(1, 3)), ... 'Position', [355 499 405 571]); add_line(blk, 'en_replicate1/1', 'en_expand1/1'); end %add/subs reuse_block(blk, 'addsub_re', 'xbsIndex_r4/AddSub', ... 'en', async, 'use_behavioral_HDL', 'on', 'pipelined', 'on', ... 'latency', num2str(add_latency), 'use_rpm', 'on', 'precision', 'Full', ... 'Position', [445 94 495 236]); add_line(blk, 'rere/1', 'addsub_re/1'); add_line(blk, 'imim/1', 'addsub_re/2'); reuse_block(blk, 'addsub_im', 'xbsIndex_r4/AddSub', ... 'en', async, 'use_behavioral_HDL', 'on', 'pipelined', 'on', ... 'latency', num2str(add_latency), 'use_rpm', 'on', 'precision', 'Full', ... 'Position', [445 259 495 401]); add_line(blk, 'imre/1', 'addsub_im/1'); add_line(blk, 'reim/1', 'addsub_im/2'); % Set conjugation mode. if strcmp(conjugated, 'on'), set_param([blk, '/addsub_re'], 'mode', 'Addition'); set_param([blk, '/addsub_im'], 'mode', 'Subtraction'); else, set_param([blk, '/addsub_re'], 'mode', 'Subtraction'); set_param([blk, '/addsub_im'], 'mode', 'Addition'); end if strcmp(async, 'on'), add_line(blk, 'en_expand1/1', 'addsub_re/3'); add_line(blk, 'en_expand1/2', 'addsub_im/3'); if strcmp(pipelined_enable, 'on'), latency = add_latency; replication = 3; else, latency = 0; replication = 2; end reuse_block(blk, 'en_replicate2', 'casper_library_bus/bus_replicate', ... 'replication', '3', 'latency', num2str(latency), 'misc', 'off', ... 'Position', [450 548 485 572]); add_line(blk, 'en_expand1/3', 'en_replicate2/1'); reuse_block(blk, 'en_expand2', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', num2str(replication), ... 'outputWidth', mat2str(ones(1, replication)), 'outputBinaryPt', mat2str(zeros(1, replication)), ... 'outputArithmeticType', mat2str(2*ones(1, replication)), ... 'Position', [515 524 565 596]); add_line(blk, 'en_replicate2/1', 'en_expand2/1'); end %code below taken from original cmult_init script but unsure of what is supposed to happen % % If overflow mode is "wrap", do the wrap for free in the multipliers % % and post-multiply adders to save bits. % wrapables={'rere', 'imim', 'imre', 'reim', 'addsub_re', 'addsub_im'}; % if overflow == 1, % bin_pt_wrap=bin_pt_b+bin_pt_a; % n_bits_wrap=(n_bits_ab-bin_pt_ab)+bin_pt_wrap; % for name=wrapables % set_param([blk,'/',name{1}], ... % 'precision', 'User Defined', ... % 'arith_type', 'Signed (2''s comp)', ... % 'n_bits', num2str(n_bits_wrap), ... % 'bin_pt', num2str(bin_pt_wrap), ... % 'quantization', 'Truncate', ... % 'overflow', 'Wrap'); % end % else % for name=wrapables % set_param([blk, '/', name{1}], 'precision', 'Full'); % end % end %convert reuse_block(blk, 'convert_re', 'xbsIndex_r4/Convert', ... 'en', async, 'n_bits', num2str(n_bits_ab), 'bin_pt', num2str(bin_pt_ab), ... 'quantization', quantization, 'overflow', overflow, 'pipeline', 'on', ... 'latency', num2str(conv_latency), 'Position', [595 152 640 183]); add_line(blk, 'addsub_re/1', 'convert_re/1'); reuse_block(blk, 'convert_im', 'xbsIndex_r4/Convert', ... 'en', async, 'n_bits', num2str(n_bits_ab), 'bin_pt', num2str(bin_pt_ab), ... 'quantization', quantization, 'overflow', overflow, 'pipeline', 'on', ... 'latency', num2str(conv_latency), 'Position', [595 317 640 348]); add_line(blk,'addsub_im/1','convert_im/1'); if strcmp(async, 'on'), add_line(blk, 'en_expand2/1', 'convert_re/2'); add_line(blk, 'en_expand2/2', 'convert_im/2'); if strcmp(pipelined_enable, 'on'), reuse_block(blk, 'den', 'xbsIndex_r4/Delay', ... 'latency', num2str(latency), 'reg_retiming', 'on', ... 'Position', [600 574 635 596]); add_line(blk, 'en_expand2/3', 'den/1'); latency = conv_latency; else, latency = mult_latency + add_latency + conv_latency; end end %output ports reuse_block(blk, 'ri_to_c', 'casper_library_misc/ri_to_c', ... 'Position', [660 229 700 271]); add_line(blk,'convert_re/1','ri_to_c/1'); add_line(blk,'convert_im/1','ri_to_c/2'); reuse_block(blk, 'ab', 'built-in/Outport', ... 'Port', '1', ... 'Position', [745 243 775 257]); add_line(blk,'ri_to_c/1','ab/1'); if strcmp(async, 'on') && strcmp(pipelined_enable, 'on'), reuse_block(blk, 'dvalid', 'built-in/Outport', ... 'Port', '2', ... 'Position', [745 438 775 452]); add_line(blk, 'den/1', 'dvalid/1'); end clean_blocks(blk); % Set attribute format string (block annotation) annotation=sprintf('%d_%d * %d_%d ==> %d_%d\n%s, %s\nLatency=%d', ... n_bits_a,bin_pt_a,n_bits_b,bin_pt_b,n_bits_ab,bin_pt_ab,quantization,overflow,latency); set_param(blk,'AttributesFormatString',annotation); % Save and back-populate mask parameter values save_state(blk, 'defaults', defaults, varargin{:});
github
mstrader/mlib_devel-master
propagate_vars.m
.m
mlib_devel-master/casper_library/propagate_vars.m
2,403
utf_8
554d3ff7095f1958d659d4526bdb56b6
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006-2007 Terry Filiba, David MacMahon, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function propagate_vars(blk, varargin) % Propagates values from varargin to parameters in blk of the same name. % If varname is not found, looks for 'defaults' and tries to find varname % in there. % % value = get_var(varname, varargin) % % blk = the block to propagate to. % varargin = {'varname', value, ...} pairs params = fieldnames(get_param(blk, 'DialogParameters')); % loop through the block parameters for i=1:length(params), % find that parameter in the current block or defaults found = get_var(params{i},varargin{:}); % if parameter of the same name is found, copy if ~isnan(found), set_param(blk, params{i}, tostring(found)); end end
github
mstrader/mlib_devel-master
twiddle_general_3mult_init.m
.m
mlib_devel-master/casper_library/twiddle_general_3mult_init.m
15,210
utf_8
1274f1b5c8cdef1a8d3ad7f931f58f27
% twiddle_general_3mult_init(blk, varargin) % % blk = The block to configure % varargin = {'varname', 'value, ...} pairs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Karoo Array Telesope % % http://www.kat.ac.za % % Copyright (C) 2009 Andrew Martens % % % % Radio Astronomy Lab % % University of California, Berkeley % % http://ral.berkeley.edu/ % % Copyright (C) 2010 David MacMahon % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function twiddle_general_3mult_init(blk, varargin) clog('entering twiddle_general_3mult_init', 'trace'); defaults = {'Coeffs', [0, j], 'StepPeriod', 0, 'input_bit_width', 18, ... 'coeff_bit_width', 18,'add_latency', 1, 'mult_latency', 2, ... 'conv_latency', 1, 'bram_latency', 2, 'arch', 'Virtex5', ... 'coeffs_bram', 'off', 'use_hdl', 'off', 'use_embedded', 'off', ... 'quantization', 'Round (unbiased: +/- Inf)', 'overflow', 'Wrap'}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end clog('twiddle_general_3mult_init post same_state','trace'); check_mask_type(blk, 'twiddle_general_3mult'); munge_block(blk, varargin{:}); Coeffs = get_var('Coeffs', 'defaults', defaults, varargin{:}); StepPeriod = get_var('StepPeriod', 'defaults', defaults, varargin{:}); input_bit_width = get_var('input_bit_width', 'defaults', defaults, varargin{:}); coeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:}); add_latency = get_var('add_latency', 'defaults', defaults, varargin{:}); mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:}); arch = get_var('arch', 'defaults', defaults, varargin{:}); coeffs_bram = get_var('coeffs_bram', 'defaults', defaults, varargin{:}); use_hdl = get_var('use_hdl', 'defaults', defaults, varargin{:}); use_embedded = get_var('use_embedded', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); clog(flatstrcell(varargin),'twiddle_general_3mult_init_debug'); if( strcmp(arch,'Virtex2Pro') ), elseif( strcmp(arch,'Virtex5') ), else, clog(['twiddle_general_3mult_init: unknown target architecture ',arch],'error'); error('twiddle_general_3mult_init.m: Unknown target architecture'); return; end delete_lines(blk); %default case, leave clean block with nothing for storage in the libraries if isempty(Coeffs) clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting twiddle_general_3mult_init', 'trace'); return; end %a input signal path reuse_block(blk, 'a', 'built-in/inport', 'Port', '1', 'Position',[225 28 255 42]); reuse_block(blk, 'delay0', 'xbsIndex_r4/Delay', ... 'latency','mult_latency + 2*add_latency + bram_latency + conv_latency', ... 'Position', [275 15 315 55]); add_line(blk, 'a/1', 'delay0/1'); reuse_block(blk, 'c_to_ri1', 'casper_library_misc/c_to_ri', ... 'n_bits', num2str(input_bit_width), 'bin_pt', num2str(input_bit_width-1), ... 'Position', [340 14 380 56]); add_line(blk,'delay0/1','c_to_ri1/1'); reuse_block(blk, 'a_re', 'built-in/outport', 'Port', '1', 'Position', [405 13 435 27]); reuse_block(blk, 'a_im', 'built-in/outport', 'Port', '2', 'Position', [405 43 435 57]); add_line(blk, 'c_to_ri1/1', 'a_re/1'); add_line(blk, 'c_to_ri1/2', 'a_im/1'); %sync input signal path reuse_block(blk, 'sync', 'built-in/inport', 'Port', '3', 'Position',[40 463 70 477]); reuse_block(blk, 'delay2', 'xbsIndex_r4/Delay', ... 'latency','mult_latency + 2*add_latency + bram_latency + conv_latency', ... 'Position', [280 450 320 490]); add_line(blk, 'sync/1', 'delay2/1'); reuse_block(blk, 'sync_out', 'built-in/outport', 'Port', '5', 'Position', [340 463 370 477]); add_line(blk, 'delay2/1', 'sync_out/1'); %coefficient generator reuse_block(blk, 'coeff_gen', 'casper_library_ffts_twiddle_coeff_gen/coeff_gen', ... 'Coeffs', tostring(Coeffs), ... 'StepPeriod', tostring(StepPeriod), 'coeff_bit_width', num2str(coeff_bit_width-1), ... 'bram_latency', 'bram_latency', 'coeffs_bram', coeffs_bram, ... 'Position', [100 319 145 361]); add_line(blk, 'sync/1', 'coeff_gen/1'); reuse_block(blk, 'c_to_ri2', 'casper_library_misc/c_to_ri', ... 'n_bits', num2str(coeff_bit_width-1), 'bin_pt', num2str(coeff_bit_width-3), ... 'Position', [180 319 220 361]); add_line(blk, 'coeff_gen/1', 'c_to_ri2/1'); reuse_block(blk, 'AddSub2', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ... 'use_behavioral_HDL', 'on', ... 'mode', 'Addition', 'Position', [255 318 300 362]); add_line(blk, 'c_to_ri2/1', 'AddSub2/1'); add_line(blk, 'c_to_ri2/2', 'AddSub2/2'); reuse_block(blk, 'AddSub3', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ... 'use_behavioral_HDL', 'on', ... 'mode', 'Subtraction', 'Position', [255 388 300 432]); add_line(blk, 'c_to_ri2/2', 'AddSub3/1'); add_line(blk, 'c_to_ri2/1', 'AddSub3/2'); reuse_block(blk, 'delay5', 'xbsIndex_r4/Delay', 'latency', 'add_latency', ... 'reg_retiming', 'on', ... 'Position', [260 255 300 295]); add_line(blk, 'c_to_ri2/1', 'delay5/1'); %b input signal path reuse_block(blk, 'b', 'built-in/inport', 'Port', '2', 'Position',[50 98 80 112]); reuse_block(blk, 'delay1', 'xbsIndex_r4/Delay', 'latency', 'bram_latency', ... 'Position', [105 85 145 125]); add_line(blk, 'b/1', 'delay1/1'); reuse_block(blk, 'c_to_ri3', 'casper_library_misc/c_to_ri', ... 'n_bits', 'input_bit_width', 'bin_pt', 'input_bit_width-1', ... 'Position', [175 84 215 126]); add_line(blk,'delay1/1', 'c_to_ri3/1'); reuse_block(blk, 'AddSub1', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ... 'use_behavioral_HDL', 'on', ... 'mode', 'Addition', 'Position', [255 83 300 127]); add_line(blk,'c_to_ri3/1', 'AddSub1/1'); add_line(blk,'c_to_ri3/2', 'AddSub1/2'); reuse_block(blk, 'delay3', 'xbsIndex_r4/Delay', 'latency', 'add_latency', ... 'reg_retiming', 'on', ... 'Position', [260 145 300 185]); add_line(blk, 'c_to_ri3/1','delay3/1'); reuse_block(blk, 'delay4', 'xbsIndex_r4/Delay', 'latency', 'add_latency', ... 'reg_retiming', 'on', ... 'Position', [260 200 300 240]); add_line(blk, 'c_to_ri3/2','delay4/1'); %mult0 reuse_block(blk, 'mult0', 'xbsIndex_r4/Mult', ... 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ... 'latency', 'mult_latency', ... 'Position', [380 93 425 137]); add_line(blk, 'AddSub1/1', 'mult0/1'); add_line(blk, 'delay5/1', 'mult0/2'); %mult1 reuse_block(blk, 'mult1', 'xbsIndex_r4/Mult', ... 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ... 'latency', 'mult_latency', ... 'Position', [380 308 425 352]); add_line(blk, 'delay4/1', 'mult1/1'); add_line(blk, 'AddSub2/1', 'mult1/2'); %mult2 reuse_block(blk, 'mult2', 'xbsIndex_r4/Mult', ... 'use_embedded', use_embedded, 'use_behavioral_HDL', use_hdl, ... 'latency', 'mult_latency', ... 'Position', [380 378 425 422]); add_line(blk, 'delay3/1', 'mult2/1'); add_line(blk, 'AddSub3/1', 'mult2/2'); %post mult adders reuse_block(blk, 'AddSub', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ... 'use_behavioral_HDL', 'on', ... 'mode', 'Subtraction', 'Position', [525 103 570 147]); reuse_block(blk, 'AddSub4', 'xbsIndex_r4/AddSub', 'latency', 'add_latency', ... 'use_behavioral_HDL', 'on', ... 'mode', 'Addition', 'Position', [525 303 570 347]); reuse_block(blk, 'bw_re', 'built-in/outport', 'Port', '3', 'Position', [740 118 780 132]); reuse_block(blk, 'bw_im', 'built-in/outport', 'Port', '4', 'Position', [740 318 780 332]); % First delete any convert blocks that exist so that different architectures % can use different convert blocks. For Virtex2Pro, use CASPER convert blocks. % For Virtex5 blocks, use Xilinx convert blocks (for "historical" % compatibility; recommend changing V5 to use CASPER convert blocks, too). % Deleting beforehand is needed so that reuse_block for V2P will not try to % configure Xilinx convert blocks (left over from code for V5) as CASPER % convert blocks and vice versa. % % It would probably be better to simply change the block in % casper_library_ffts_twiddle.mdl to use CASPER converts always regardless of % architecture (e.g. V5 vs V2P), but changing the .mdl file is riskier in that % it could lead to merges that tend not to be pleasant. for k=2:4 conv_name = sprintf('convert%d', k); conv_blk = find_system(blk, ... 'LookUnderMasks','all', 'FollowLinks','on', ... 'SearchDepth',1, 'Name',conv_name); if ~isempty(conv_blk) delete_block(conv_blk{1}); end end %architecture specific logic if( strcmp(arch,'Virtex2Pro') ), %add convert blocks to reduce logic in adders % Multiplication by a complex twiddle factor is nothing more than a % rotation in the complex plane. The bit width of the input value being % twiddled can grow no more than one non-fractional bit. The input value % does not gain more precision by being twiddled so therefore it need not % grow any fractional bits. % % Since the growth by one non-fractional bit provides sufficient dynamic % range for the twiddle operation, any "overflow" can (and should!) be % ignored (i.e. set to "Wrap"; *not* set to "Saturate"). reuse_block(blk, 'convert2', 'casper_library_misc/convert', ... 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-3)', ... 'n_bits_out', 'input_bit_width+1', ... 'bin_pt_out', 'input_bit_width-1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', 'Wrap', ... 'Position', [445 100 485 130]); add_line(blk, 'mult0/1', 'convert2/1'); reuse_block(blk, 'convert3', 'casper_library_misc/convert', ... 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-3)', ... 'n_bits_out', 'input_bit_width+1', ... 'bin_pt_out', 'input_bit_width-1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', 'Wrap', ... 'Position', [445 315 485 345]); add_line(blk, 'mult1/1', 'convert3/1'); reuse_block(blk, 'convert4', 'casper_library_misc/convert', ... 'bin_pt_in', '(input_bit_width-1)+(coeff_bit_width-3)', ... 'n_bits_out', 'input_bit_width+1', ... 'bin_pt_out', 'input_bit_width-1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', 'Wrap', ... 'Position', [445 385 485 415]); add_line(blk, 'mult2/1', 'convert4/1'); %join convert blocks to adders add_line(blk, 'convert2/1', 'AddSub/1'); add_line(blk, 'convert3/1', 'AddSub/2'); add_line(blk, 'convert2/1', 'AddSub4/1'); add_line(blk, 'convert4/1', 'AddSub4/2'); %join adders to ouputs add_line(blk, 'AddSub/1', 'bw_re/1'); add_line(blk, 'AddSub4/1', 'bw_im/1'); % Set output precision on adder outputs set_param([blk,'/AddSub'], ... 'precision', 'User Defined', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', 'input_bit_width+1', ... 'bin_pt', 'input_bit_width-1', ... 'quantization', 'Truncate', ... 'overflow', 'Wrap'); set_param([blk,'/AddSub4'], ... 'precision', 'User Defined', ... 'arith_type', 'Signed (2''s comp)', ... 'n_bits', 'input_bit_width+1', ... 'bin_pt', 'input_bit_width-1', ... 'quantization', 'Truncate', ... 'overflow', 'Wrap'); elseif( strcmp(arch,'Virtex5') ) %add convert blocks to after adders to ensure adders absorbed into multipliers add_line(blk, 'mult0/1', 'AddSub/1'); add_line(blk, 'mult1/1', 'AddSub/2'); add_line(blk, 'mult0/1', 'AddSub4/1'); add_line(blk, 'mult2/1', 'AddSub4/2'); reuse_block(blk, 'convert2', 'xbsIndex_r4/Convert', ... 'pipeline', 'on', ... 'n_bits', 'input_bit_width+5', ... 'bin_pt', 'input_bit_width+1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', tostring(overflow), ... 'Position', [600 105 650 140]); add_line(blk, 'AddSub/1', 'convert2/1'); add_line(blk, 'convert2/1', 'bw_re/1'); reuse_block(blk, 'convert3', 'xbsIndex_r4/Convert', ... 'pipeline', 'on', ... 'n_bits', 'input_bit_width+5', ... 'bin_pt', 'input_bit_width+1', ... 'latency', 'conv_latency', 'quantization', tostring(quantization), ... 'overflow', tostring(overflow), ... 'Position', [600 305 650 340]); add_line(blk, 'AddSub4/1', 'convert3/1'); add_line(blk, 'convert3/1', 'bw_im/1'); else return; end clean_blocks(blk); fmtstr = sprintf('data=(%d,%d)\ncoeffs=(%d,%d)\n%s\n(%s,%s)', ... input_bit_width, input_bit_width-1, coeff_bit_width-1, coeff_bit_width-3, arch, quantization, overflow); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting twiddle_general_3mult_init','trace');
github
mstrader/mlib_devel-master
first_tap_init.m
.m
mlib_devel-master/casper_library/first_tap_init.m
3,182
utf_8
50e9b43589ff76f954942548c2469f51
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2007 Terry Filiba, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function first_tap_init(blk, varargin) % Initialize and configure the first tap of the Polyphase Filter Bank. % % first_tap_init(blk, varargin) % % blk = The block to configure. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % PFBSize = The size of the PFB % CoeffBitWidth = Bitwidth of Coefficients. % TotalTaps = Total number of taps in the PFB % BitWidthIn = Input Bitwidth % WindowType = The type of windowing function to use. % mult_latency = Latency through each multiplier % bram_latency = Latency through each BRAM. % n_inputs = The number of parallel inputs % fwidth = Scaling of the width of each PFB channel % Declare any default values for arguments you might like. defaults = {}; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'first_tap'); munge_block(blk, varargin{:}); TotalTaps = get_var('TotalTaps', 'defaults', defaults, varargin{:}); use_hdl = get_var('use_hdl','defaults', defaults, varargin{:}); use_embedded = get_var('use_embedded','defaults', defaults, varargin{:}); set_param([blk,'/Mult'],'use_embedded', use_embedded); set_param([blk,'/Mult'],'use_behavioral_HDL', use_hdl); set_param([blk,'/Mult1'],'use_embedded', use_embedded); set_param([blk,'/Mult1'],'use_behavioral_HDL', use_hdl) fmtstr = sprintf('taps=%d', TotalTaps); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:});
github
mstrader/mlib_devel-master
butterfly_direct_init.m
.m
mlib_devel-master/casper_library/butterfly_direct_init.m
22,175
utf_8
4874f5db36e43f539e5f319cc57d131b
% Initialize and configure a butterfly_direct block. % % butterfly_direct_init(blk, varargin) % % blk = the block to configure % varargin = {'varname', 'value', ...} pairs % % Valid varnames: % * biplex = Make biplex. % * FFTSize = Size of the FFT (2^FFTSize points). % * Coeffs = Coefficients for twiddle blocks. % * StepPeriod = Coefficient step period. % * coeffs_bram = Store coefficients in BRAM. % * coeff_bit_width = Bitwdith of coefficients. % * input_bit_width = Bitwidth of input data. % * bin_pt_in = Binary point position of input data. % * bitgrowth = Option to grow non-fractional bits by so don't have to shift. % * downshift = Explicitly downshift output data if shifting. % * bram_latency = Latency of BRAM blocks. % * add_latency = Latency of adders blocks. % * mult_latency = Latency of multiplier blocks. % * conv_latency = Latency of cast blocks. % * quantization = Quantization behavior. % * overflow = Overflow behavior. % * use_hdl = Use behavioral HDL for multipliers. % * use_embedded = Use embedded multipliers. % * hardcode_shifts = If not using bit growth, option to hardcode downshift setting. % * dsp48_adders = Use DSP48-based adders. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://casper.berkeley.edu % % Copyright (C) 2007 Terry Filiba, Aaron Parsons % % Copyright (C) 2010 William Mallard, David MacMahon % % % % SKASA radio telescope project % % www.kat.ac.za % % Copyright (C) 2013 Andrew Martens % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function butterfly_direct_init(blk, varargin) clog('entering butterfly_direct_init', {'trace', 'butterfly_direct_init_debug'}); % Set default vararg values. defaults = { ... 'n_inputs', 1, ... 'biplex', 'on', ... 'FFTSize', 6, ... 'Coeffs', bit_rev([0:2^5-1],5), ... 'StepPeriod', 1, ... 'coeff_bit_width', 18, ... 'input_bit_width', 18, ... 'bin_pt_in', 17, ... 'bitgrowth', 'off', ... 'downshift', 'off', ... 'async', 'off', ... 'add_latency', 1, ... 'mult_latency', 2, ... 'bram_latency', 2, ... 'conv_latency', 1, ... 'quantization', 'Truncate', ... 'overflow', 'Wrap', ... 'coeffs_bit_limit', 8, ... 'coeff_sharing', 'on', ... 'coeff_decimation', 'on', ... 'coeff_generation', 'on', ... 'cal_bits', 1, ... 'n_bits_rotation', 25, ... 'max_fanout', 4, ... 'use_hdl', 'off', ... 'use_embedded', 'off', ... 'hardcode_shifts', 'off', ... 'dsp48_adders', 'off', ... }; % Skip init script if mask state has not changed. if same_state(blk, 'defaults', defaults, varargin{:}), return; end clog('butterfly_direct_init post same_state', {'trace', 'butterfly_direct_init_debug'}); % Verify that this is the right mask for the block. check_mask_type(blk, 'butterfly_direct'); % Disable link if state changes from default. munge_block(blk, varargin{:}); % Retrieve values from mask fields. n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:}); biplex = get_var('biplex', 'defaults', defaults, varargin{:}); FFTSize = get_var('FFTSize', 'defaults', defaults, varargin{:}); Coeffs = get_var('Coeffs', 'defaults', defaults, varargin{:}); StepPeriod = get_var('StepPeriod', 'defaults', defaults, varargin{:}); coeff_bit_width = get_var('coeff_bit_width', 'defaults', defaults, varargin{:}); input_bit_width = get_var('input_bit_width', 'defaults', defaults, varargin{:}); bin_pt_in = get_var('bin_pt_in', 'defaults', defaults, varargin{:}); bitgrowth = get_var('bitgrowth', 'defaults', defaults, varargin{:}); downshift = get_var('downshift', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); bram_latency = get_var('bram_latency', 'defaults', defaults, varargin{:}); add_latency = get_var('add_latency', 'defaults', defaults, varargin{:}); mult_latency = get_var('mult_latency', 'defaults', defaults, varargin{:}); conv_latency = get_var('conv_latency', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); coeffs_bit_limit = get_var('coeffs_bit_limit', 'defaults', defaults, varargin{:}); coeff_sharing = get_var('coeff_sharing', 'defaults', defaults, varargin{:}); coeff_decimation = get_var('coeff_decimation', 'defaults', defaults, varargin{:}); coeff_generation = get_var('coeff_generation', 'defaults', defaults, varargin{:}); cal_bits = get_var('cal_bits', 'defaults', defaults, varargin{:}); n_bits_rotation = get_var('n_bits_rotation', 'defaults', defaults, varargin{:}); max_fanout = get_var('max_fanout', 'defaults', defaults, varargin{:}); use_hdl = get_var('use_hdl', 'defaults', defaults, varargin{:}); use_embedded = get_var('use_embedded', 'defaults', defaults, varargin{:}); hardcode_shifts = get_var('hardcode_shifts', 'defaults', defaults, varargin{:}); dsp48_adders = get_var('dsp48_adders', 'defaults', defaults, varargin{:}); %default case for library storage, delete everything if n_inputs == 0 | FFTSize == 0, delete_lines(blk); clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting butterfly_direct_init', 'trace'); return; end % bin_pt_in == -1 is a special case for backwards compatibility if bin_pt_in == -1 bin_pt_in = input_bit_width - 1; set_mask_params(blk, 'bin_pt_in', num2str(bin_pt_in)); end use_dsp48_mults = strcmp(use_embedded, 'on'); use_dsp48_adders = strcmp(dsp48_adders, 'on'); % Validate input fields. if strcmp(bitgrowth, 'on') || strcmp(hardcode_shifts, 'on'), mux_latency = 0; else mux_latency = 2; end %TODO if use_dsp48_adders, set_param(blk, 'add_latency', '2'); add_latency = 2; end % Optimize twiddle for coeff = 0, 1, or alternating 0-1 if length(Coeffs) == 1, if Coeffs(1) == 0, %if used in biplex core and first stage if(strcmp(biplex, 'on')), twiddle_type = 'twiddle_pass_through'; else, %otherwise do same but make sure have correct delay twiddle_type = 'twiddle_coeff_0'; end elseif Coeffs(1) == 1, twiddle_type = 'twiddle_coeff_1'; else twiddle_type = 'twiddle_general'; end elseif length(Coeffs)==2 && Coeffs(1)==0 && Coeffs(2)==1 && StepPeriod==FFTSize-2, twiddle_type = 'twiddle_stage_2'; else twiddle_type = 'twiddle_general'; end clog([twiddle_type, ' for twiddle'], 'butterfly_direct_init_debug'); clog(['Coeffs = ', mat2str(Coeffs)], 'butterfly_direct_init_debug'); % Compute bit widths into addsub and convert blocks. bw = input_bit_width + 3; bd = bin_pt_in+1; if strcmp(twiddle_type, 'twiddle_stage_2') ... || strcmp(twiddle_type, 'twiddle_coeff_0') ... || strcmp(twiddle_type, 'twiddle_coeff_1') ... || strcmp(twiddle_type, 'twiddle_pass_through'), bw = input_bit_width + 2; bd = bin_pt_in+1; end addsub_b_bitwidth = bw - 2; addsub_b_binpoint = bd - 1; n_bits_addsub_out = addsub_b_bitwidth+1; bin_pt_addsub_out = addsub_b_binpoint; if strcmp(bitgrowth, 'off') if strcmp(hardcode_shifts, 'on'), if strcmp(downshift, 'on'), convert_in_bitwidth = n_bits_addsub_out; convert_in_binpoint = bin_pt_addsub_out+1; else convert_in_bitwidth = n_bits_addsub_out; convert_in_binpoint = bin_pt_addsub_out; end else convert_in_bitwidth = n_bits_addsub_out+1; convert_in_binpoint = bin_pt_addsub_out+1; end else convert_in_bitwidth = n_bits_addsub_out; convert_in_binpoint = bin_pt_addsub_out; end %%%%%%%%%%%%%%%%%% % Start drawing! % %%%%%%%%%%%%%%%%%% % Delete all lines. delete_lines(blk); % % Add inputs and outputs. % reuse_block(blk, 'a', 'built-in/Inport', 'Port', '1', 'Position', [45 63 75 77]); reuse_block(blk, 'b', 'built-in/Inport', 'Port', '2', 'Position', [45 123 75 137]); reuse_block(blk, 'sync_in', 'built-in/Inport', 'Port', '3', 'Position', [45 183 75 197]); reuse_block(blk, 'shift', 'built-in/Inport', 'Port', '4', 'Position', [380 63 410 77]); if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/Inport', 'Port', '5','Position', [45 243 75 257]); end reuse_block(blk, 'a+bw', 'built-in/Outport', 'Port', '1', 'Position', [880 58 910 72]); reuse_block(blk, 'a-bw', 'built-in/Outport', 'Port', '2', 'Position', [880 88 910 102]); reuse_block(blk, 'of', 'built-in/Outport', 'Port', '3', 'Position', [880 143 910 157]); reuse_block(blk, 'sync_out', 'built-in/Outport', 'Port', '4', 'Position', [880 183 910 197]); if strcmp(async, 'on'), reuse_block(blk, 'dvalid', 'built-in/Outport', 'Port', '5', 'Position', [880 243 910 257]); end % % Add twiddle block. % params = {'n_inputs', num2str(n_inputs), 'async', async}; if ~strcmp(twiddle_type, 'twiddle_pass_through'), params = { params{:}, ... 'add_latency', num2str(add_latency), ... 'mult_latency', num2str(mult_latency), ... 'bram_latency', num2str(bram_latency), ... 'conv_latency', num2str(conv_latency)}; end if strcmp(twiddle_type, 'twiddle_coeff_1'), params = { params{:}, ... 'input_bit_width', num2str(input_bit_width), ... 'bin_pt_in', num2str(bin_pt_in)}; elseif strcmp(twiddle_type, 'twiddle_stage_2'), params = { params{:}, ... 'FFTSize', num2str(FFTSize), ... 'input_bit_width', num2str(input_bit_width), ... 'bin_pt_in', num2str(bin_pt_in)}; elseif strcmp(twiddle_type, 'twiddle_general'), params = { params{:}, ... 'FFTSize', num2str(FFTSize), ... 'Coeffs', mat2str(Coeffs), ... 'StepPeriod', num2str(StepPeriod), ... 'coeff_bit_width', num2str(coeff_bit_width), ... 'input_bit_width', num2str(input_bit_width), ... 'bin_pt_in', num2str(bin_pt_in), ... 'coeffs_bit_limit', num2str(coeffs_bit_limit), ... 'coeff_sharing', coeff_sharing, ... 'coeff_decimation', coeff_decimation, ... 'coeff_generation', coeff_generation, ... 'cal_bits', num2str(cal_bits), ... 'n_bits_rotation', num2str(n_bits_rotation), ... 'max_fanout', num2str(max_fanout), ... 'use_hdl', use_hdl, ... 'use_embedded', use_embedded, ... 'quantization', quantization, ... 'overflow', overflow}; end reuse_block(blk, 'twiddle', ['casper_library_ffts_twiddle/', twiddle_type], ... params{:}, 'Position', [120 37 205 283]); add_line(blk, 'a/1', 'twiddle/1'); add_line(blk, 'b/1', 'twiddle/2'); add_line(blk, 'sync_in/1', 'twiddle/3'); % % Add complex add/sub blocks. % if strcmp(dsp48_adders, 'on'), add_implementation = 'DSP48 core'; else add_implementation = 'behavioral HDL'; end reuse_block(blk, 'bus_add', 'casper_library_bus/bus_addsub', ... 'opmode', '0', 'latency', num2str(add_latency), ... 'n_bits_a', mat2str(repmat(input_bit_width, 1, n_inputs)), ... 'bin_pt_a', mat2str(bin_pt_in), ... 'misc', 'off', ... 'n_bits_b', mat2str(repmat(addsub_b_bitwidth, 1, n_inputs)), ... 'bin_pt_b', num2str(addsub_b_binpoint), ... 'n_bits_out', num2str(addsub_b_bitwidth+1), ... 'bin_pt_out', num2str(addsub_b_binpoint), ... 'add_implementation', add_implementation, ... 'Position', [270 64 310 91]); add_line(blk, 'twiddle/1', 'bus_add/1'); add_line(blk, 'twiddle/2', 'bus_add/2'); reuse_block(blk, 'bus_sub', 'casper_library_bus/bus_addsub', ... 'opmode', '1', 'latency', num2str(add_latency), ... 'n_bits_a', mat2str(repmat(input_bit_width, 1, n_inputs)), ... 'bin_pt_a', mat2str(bin_pt_in), ... 'misc', 'off', ... 'n_bits_b', mat2str(repmat(addsub_b_bitwidth, 1, n_inputs)), ... 'bin_pt_b', num2str(addsub_b_binpoint), ... 'n_bits_out', num2str(addsub_b_bitwidth+1), ... 'bin_pt_out', num2str(addsub_b_binpoint), ... 'add_implementation', add_implementation, ... 'Position', [270 109 310 136]); add_line(blk, 'twiddle/1', 'bus_sub/1'); add_line(blk, 'twiddle/2', 'bus_sub/2'); reuse_block(blk, 'Concat', 'xbsIndex_r4/Concat', ... 'num_inputs', '2', ... 'Position', [340 59 370 146]); add_line(blk, 'bus_add/1', 'Concat/1'); add_line(blk, 'bus_sub/1', 'Concat/2'); % % Convert % if strcmp(quantization, 'Truncate'), quant = '0'; elseif strcmp(quantization, 'Round (unbiased: +/- Inf)'), quant = '1'; elseif strcmp(quantization, 'Round (unbiased: Even Values)'), quant = '2'; else %TODO end if strcmp(overflow, 'Wrap'), of = '0'; elseif strcmp(overflow, 'Saturate'), of = '1'; elseif strcmp(overflow, 'Flag as error'), of = '2'; else %TODO end if strcmp(bitgrowth, 'on'), n_bits_out = input_bit_width+1; else n_bits_out = input_bit_width; end reuse_block(blk, 'bus_convert', 'casper_library_bus/bus_convert', ... 'n_bits_in', mat2str(repmat(convert_in_bitwidth, 1, n_inputs*2)), ... 'bin_pt_in', mat2str(repmat(convert_in_binpoint, 1, n_inputs*2)), ... 'cmplx', 'on', ... 'n_bits_out', num2str(n_bits_out), ... 'bin_pt_out', num2str(bin_pt_in), ... 'quantization', quant, 'overflow', of, ... 'misc', 'off', 'of', 'on', 'latency', 'conv_latency', ... 'Position', [635 86 690 119]); % % Add scale % fan_latency = max(1, ceil(log2((n_inputs*2*2)/max_fanout))); if strcmp(bitgrowth, 'off') && strcmp(hardcode_shifts, 'off'), reuse_block(blk, 'shift_replicate', 'casper_library_bus/bus_replicate', ... 'replication', num2str(n_inputs*2*2), 'latency', num2str(fan_latency), 'misc', 'off', 'Position', [455 59 485 81]); add_line(blk, 'shift/1', 'shift_replicate/1'); %required to add padding to match bit width of other stream (from bus_scale) reuse_block(blk, 'bus_norm0', 'casper_library_bus/bus_convert', ... 'n_bits_in', mat2str(repmat(addsub_b_bitwidth+1, 1, n_inputs*2)), ... 'bin_pt_in', mat2str(repmat(addsub_b_binpoint, 1, n_inputs*2)), ... 'cmplx', 'on', ... 'n_bits_out', num2str(addsub_b_bitwidth+2), ... 'bin_pt_out', num2str(addsub_b_binpoint+1), ... 'quantization', '0', 'overflow', '0', ... 'misc', 'off', 'of', 'off', 'latency', '0', ... 'Position', [500 92 545 118]); add_line(blk, 'Concat/1', 'bus_norm0/1'); reuse_block(blk, 'bus_scale', 'casper_library_bus/bus_scale', ... 'n_bits_in', mat2str(repmat(addsub_b_bitwidth+1, 1, n_inputs*2)), ... 'bin_pt_in', num2str(addsub_b_binpoint), ... 'cmplx', 'on', ... 'scale_factor', '-1', ... 'misc', 'off', ... 'Position', [405 127 450 153]); add_line(blk, 'Concat/1', 'bus_scale/1'); %scaling causes binary point to be moved up by one place reuse_block(blk, 'bus_norm1', 'casper_library_bus/bus_convert', ... 'n_bits_in', mat2str(repmat(addsub_b_bitwidth+1, 1, n_inputs*2)), ... 'bin_pt_in', mat2str(repmat(addsub_b_binpoint+1, 1, n_inputs*2)), ... 'cmplx', 'on', ... 'n_bits_out', num2str(addsub_b_bitwidth+2), ... 'bin_pt_out', num2str(addsub_b_binpoint+1), ... 'quantization', '0', 'overflow', '0', ... 'misc', 'off', 'of', 'off', 'latency', '0', ... 'Position', [500 127 545 153]); add_line(blk, 'bus_scale/1', 'bus_norm1/1'); reuse_block(blk, 'mux', 'casper_library_bus/bus_mux', ... 'n_inputs', '2', 'n_bits', mat2str(repmat(convert_in_bitwidth, 1, n_inputs*2*2)), ... 'cmplx', 'off', 'misc', 'off', 'mux_latency', num2str(mux_latency), ... 'Position', [580 53 610 157]); add_line(blk, 'shift_replicate/1', 'mux/1'); add_line(blk, 'bus_norm0/1', 'mux/2'); add_line(blk, 'bus_norm1/1', 'mux/3'); add_line(blk, 'mux/1', 'bus_convert/1'); else reuse_block(blk, 'Terminator', 'built-in/terminator', 'Position', [430 59 460 81], 'ShowName', 'off'); add_line(blk, 'shift/1', 'Terminator/1'); %if we are not growing bits and need to downshift if strcmp(bitgrowth, 'off') && strcmp(downshift, 'on'), reuse_block(blk, 'bus_scale', 'casper_library_bus/bus_scale', ... 'n_bits_in', mat2str(repmat(addsub_b_bitwidth+1, 1, n_inputs*2)), ... 'bin_pt_in', num2str(addsub_b_binpoint), ... 'cmplx', 'on', ... 'scale_factor', '-1', ... 'misc', 'off', ... 'Position', [405 127 450 153]); add_line(blk, 'Concat/1', 'bus_scale/1'); add_line(blk, 'bus_scale/1', 'bus_convert/1'); else add_line(blk, 'Concat/1', 'bus_convert/1'); end end %if hardcode_shifts % % bus_expand % reuse_block(blk, 'bus_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', ... 'outputNum', '2', 'outputWidth', mat2str(repmat(n_inputs*n_bits_out*2,1,2)), ... 'outputBinaryPt', '[0,0]', 'outputArithmeticType', '[0,0]', ... 'Position', [715 51 765 109]); add_line(blk, 'bus_convert/1', 'bus_expand/1'); add_line(blk, 'bus_expand/1', 'a+bw/1'); add_line(blk, 'bus_expand/2', 'a-bw/1'); % % overflow detection for different input streams % %need to move a and b input streams next to each other for each input reuse_block(blk, 'munge', 'casper_library_flow_control/munge', ... 'divisions', num2str(n_inputs * 2), ... 'div_size', mat2str(repmat(2, 1, n_inputs*2)), ... 'order', mat2str(reshape([[0:n_inputs-1];[n_inputs:n_inputs*2-1]],1,n_inputs*2)), ... 'arith_type_out', 'Unsigned', 'bin_pt_out', '0', ... 'Position', [720 147 760 173]); add_line(blk, 'bus_convert/2', 'munge/1'); reuse_block(blk, 'constant', 'xbsIndex_r4/Constant', ... 'const', '0', 'arith_type', 'Unsigned', 'n_bits', '4', 'bin_pt', '0', ... 'explicit_period', 'on', 'period', '1', 'Position', [775 127 790 143]); reuse_block(blk, 'bus_relational', 'casper_library_bus/bus_relational', ... 'n_bits_a', '4', 'bin_pt_a', '0', 'type_a', '0', ... 'n_bits_b', mat2str(repmat(4, 1, n_inputs)), 'bin_pt_b', '0', 'type_b', '0', ... 'mode', 'a!=b', 'misc', 'off', 'en', 'off', 'latency', '0', ... 'Position', [820 123 850 172]); add_line(blk, 'constant/1', 'bus_relational/1'); add_line(blk, 'munge/1', 'bus_relational/2'); add_line(blk, 'bus_relational/1', 'of/1'); % % sync delay. % reuse_block(blk, 'delay0', 'xbsIndex_r4/Delay'); set_param([blk,'/delay0'], ... 'latency', ['add_latency+',num2str(mux_latency),'+conv_latency'], ... 'reg_retiming', 'on', ... 'Position', [580 179 610 201]); add_line(blk, 'twiddle/3', 'delay0/1'); add_line(blk, 'delay0/1', 'sync_out/1'); % % dvalid delay. % if strcmp(async, 'on'), add_line(blk, 'en/1', 'twiddle/4'); reuse_block(blk, 'delay1', 'xbsIndex_r4/Delay', ... 'latency', ['add_latency+',num2str(mux_latency),'+conv_latency'], ... 'reg_retiming', 'on', ... 'Position', [580 239 610 261]); add_line(blk, 'twiddle/4', 'delay1/1'); add_line(blk, 'delay1/1', 'dvalid/1'); end % Delete all unconnected blocks. clean_blocks(blk); %%%%%%%%%%%%%%%%%%% % Finish drawing! % %%%%%%%%%%%%%%%%%%% % Set attribute format string (block annotation). fmtstr = sprintf('%s', twiddle_type); set_param(blk, 'AttributesFormatString', fmtstr); % Save block state to stop repeated init script runs. save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting butterfly_direct_init', {'trace', 'butterfly_direct_init_debug'}); end %function
github
mstrader/mlib_devel-master
casper_library_bus_init.m
.m
mlib_devel-master/casper_library/casper_library_bus_init.m
44,036
utf_8
6051a65f926951968b15924edc2de8b5
function casper_library_bus_init() warning off Simulink:Engine:MdlFileShadowing; close_system('casper_library_bus', 0); mdl = new_system('casper_library_bus', 'Library'); blk = get(mdl,'Name'); warning on Simulink:Engine:MdlFileShadowing; add_block('built-in/SubSystem', [blk,'/bus_addsub']); bus_addsub_gen([blk,'/bus_addsub']); set_param([blk,'/bus_addsub'], ... 'opmode', sprintf('0'), ... 'n_bits_a', sprintf('0'), ... 'bin_pt_a', sprintf('3'), ... 'type_a', sprintf('1'), ... 'n_bits_b', sprintf('4'), ... 'bin_pt_b', sprintf('3'), ... 'type_b', sprintf('1'), ... 'cmplx', sprintf('on'), ... 'misc', sprintf('on'), ... 'async', sprintf('off'), ... 'n_bits_out', sprintf('8'), ... 'bin_pt_out', sprintf('3'), ... 'type_out', sprintf('1'), ... 'quantization', sprintf('0'), ... 'overflow', sprintf('1'), ... 'add_implementation', sprintf('fabric core'), ... 'latency', sprintf('1'), ... 'Position', sprintf('[20 17 95 93]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_register']); bus_register_gen([blk,'/bus_register']); set_param([blk,'/bus_register'], ... 'reset', sprintf('on'), ... 'enable', sprintf('on'), ... 'cmplx', sprintf('on'), ... 'n_bits', sprintf('[]'), ... 'misc', sprintf('on'), ... 'Position', sprintf('[120 17 195 93]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_mux']); bus_mux_gen([blk,'/bus_mux']); set_param([blk,'/bus_mux'], ... 'n_inputs', sprintf('0'), ... 'n_bits', sprintf('8'), ... 'mux_latency', sprintf('0'), ... 'cmplx', sprintf('off'), ... 'misc', sprintf('off'), ... 'Position', sprintf('[20 129 95 211]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_mult']); bus_mult_gen([blk,'/bus_mult']); set_param([blk,'/bus_mult'], ... 'n_bits_a', sprintf('0'), ... 'bin_pt_a', sprintf('4'), ... 'type_a', sprintf('1'), ... 'cmplx_a', sprintf('on'), ... 'n_bits_b', sprintf('4'), ... 'bin_pt_b', sprintf('3'), ... 'type_b', sprintf('1'), ... 'cmplx_b', sprintf('on'), ... 'n_bits_out', sprintf('12'), ... 'bin_pt_out', sprintf('7'), ... 'type_out', sprintf('1'), ... 'quantization', sprintf('0'), ... 'overflow', sprintf('0'), ... 'mult_latency', sprintf('3'), ... 'add_latency', sprintf('1'), ... 'conv_latency', sprintf('1'), ... 'max_fanout', sprintf('2'), ... 'fan_latency', sprintf('0'), ... 'multiplier_implementation', sprintf('behavioral HDL'), ... 'misc', sprintf('on'), ... 'Position', sprintf('[120 132 195 208]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_replicate']); bus_replicate_gen([blk,'/bus_replicate']); set_param([blk,'/bus_replicate'], ... 'replication', sprintf('0'), ... 'latency', sprintf('0'), ... 'misc', sprintf('on'), ... 'implementation', sprintf('core'), ... 'Position', sprintf('[220 17 295 93]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_logical']); bus_logical_gen([blk,'/bus_logical']); set_param([blk,'/bus_logical'], ... 'logical_function', sprintf('AND'), ... 'align_bp', sprintf('on'), ... 'latency', sprintf('1'), ... 'n_bits_a', sprintf('[]'), ... 'bin_pt_a', sprintf('3'), ... 'type_a', sprintf('1'), ... 'n_bits_b', sprintf('4'), ... 'bin_pt_b', sprintf('3'), ... 'type_b', sprintf('1'), ... 'cmplx', sprintf('on'), ... 'en', sprintf('on'), ... 'misc', sprintf('on'), ... 'n_bits_out', sprintf('8'), ... 'bin_pt_out', sprintf('3'), ... 'type_out', sprintf('1'), ... 'Position', sprintf('[20 252 95 328]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_convert']); bus_convert_gen([blk,'/bus_convert']); set_param([blk,'/bus_convert'], ... 'n_bits_in', sprintf('[]'), ... 'bin_pt_in', sprintf('8'), ... 'cmplx', sprintf('off'), ... 'n_bits_out', sprintf('8'), ... 'bin_pt_out', sprintf('4'), ... 'quantization', sprintf('1'), ... 'overflow', sprintf('1'), ... 'latency', sprintf('2'), ... 'of', sprintf('on'), ... 'misc', sprintf('on'), ... 'Position', sprintf('[220 132 295 208]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_negate']); bus_negate_gen([blk,'/bus_negate']); set_param([blk,'/bus_negate'], ... 'n_bits_in', sprintf('0'), ... 'bin_pt_in', sprintf('8'), ... 'cmplx', sprintf('off'), ... 'overflow', sprintf('1'), ... 'latency', sprintf('2'), ... 'misc', sprintf('off'), ... 'Position', sprintf('[120 252 195 328]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_accumulator']); bus_accumulator_gen([blk,'/bus_accumulator']); set_param([blk,'/bus_accumulator'], ... 'reset', sprintf('on'), ... 'enable', sprintf('on'), ... 'n_bits_in', sprintf('[]'), ... 'bin_pt_in', sprintf('3'), ... 'type_in', sprintf('1'), ... 'cmplx', sprintf('on'), ... 'n_bits_out', sprintf('16'), ... 'overflow', sprintf('1'), ... 'misc', sprintf('on'), ... 'Position', sprintf('[320 17 395 93]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_relational']); bus_relational_gen([blk,'/bus_relational']); set_param([blk,'/bus_relational'], ... 'n_bits_a', sprintf('0'), ... 'bin_pt_a', sprintf('0'), ... 'type_a', sprintf('1'), ... 'n_bits_b', sprintf('8'), ... 'bin_pt_b', sprintf('0'), ... 'type_b', sprintf('1'), ... 'en', sprintf('off'), ... 'misc', sprintf('off'), ... 'mode', sprintf('a=b'), ... 'latency', sprintf('1'), ... 'Position', sprintf('[220 252 295 328]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_scale']); bus_scale_gen([blk,'/bus_scale']); set_param([blk,'/bus_scale'], ... 'n_bits_in', sprintf('[]'), ... 'bin_pt_in', sprintf('8'), ... 'type_in', sprintf('1'), ... 'cmplx', sprintf('off'), ... 'scale_factor', sprintf('2'), ... 'misc', sprintf('on'), ... 'Position', sprintf('[320 132 395 208]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_single_port_ram']); bus_single_port_ram_gen([blk,'/bus_single_port_ram']); set_param([blk,'/bus_single_port_ram'], ... 'n_bits', sprintf('0'), ... 'bin_pts', sprintf('17'), ... 'init_vector', sprintf('[[-2:1/(2^10):2-(1/(2^10))]'']'), ... 'max_fanout', sprintf('4'), ... 'mem_type', sprintf('Block RAM'), ... 'bram_optimization', sprintf('Speed'), ... 'async', sprintf('off'), ... 'misc', sprintf('off'), ... 'bram_latency', sprintf('2'), ... 'fan_latency', sprintf('1'), ... 'addr_register', sprintf('on'), ... 'addr_implementation', sprintf('core'), ... 'din_register', sprintf('on'), ... 'din_implementation', sprintf('core'), ... 'we_register', sprintf('on'), ... 'we_implementation', sprintf('core'), ... 'en_register', sprintf('on'), ... 'en_implementation', sprintf('core'), ... 'Position', sprintf('[20 372 95 448]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_maddsub']); bus_maddsub_gen([blk,'/bus_maddsub']); set_param([blk,'/bus_maddsub'], ... 'n_bits_a', sprintf('0'), ... 'bin_pt_a', sprintf('7'), ... 'type_a', sprintf('1'), ... 'cmplx_a', sprintf('on'), ... 'n_bits_b', sprintf('[18 18]'), ... 'bin_pt_b', sprintf('17'), ... 'type_b', sprintf('1'), ... 'mult_latency', sprintf('3'), ... 'multiplier_implementation', sprintf('behavioral HDL'), ... 'replication_ab', sprintf('on'), ... 'opmode', sprintf('Addition'), ... 'n_bits_c', sprintf('[4 4 4 4]'), ... 'bin_pt_c', sprintf('3'), ... 'type_c', sprintf('0'), ... 'add_implementation', sprintf('behavioral HDL'), ... 'add_latency', sprintf('1'), ... 'async_add', sprintf('on'), ... 'align_c', sprintf('off'), ... 'replication_c', sprintf('off'), ... 'n_bits_out', sprintf('26'), ... 'bin_pt_out', sprintf('24'), ... 'type_out', sprintf('1'), ... 'quantization', sprintf('0'), ... 'overflow', sprintf('0'), ... 'max_fanout', sprintf('2'), ... 'Position', sprintf('[120 372 195 448]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_dual_port_ram']); bus_dual_port_ram_gen([blk,'/bus_dual_port_ram']); set_param([blk,'/bus_dual_port_ram'], ... 'n_bits', sprintf('0'), ... 'bin_pts', sprintf('17'), ... 'init_vector', sprintf('[[-2:1/(2^10):2-(1/(2^10))]'']'), ... 'max_fanout', sprintf('4'), ... 'mem_type', sprintf('Block RAM'), ... 'bram_optimization', sprintf('Area'), ... 'async_a', sprintf('off'), ... 'async_b', sprintf('off'), ... 'misc', sprintf('off'), ... 'bram_latency', sprintf('2'), ... 'fan_latency', sprintf('1'), ... 'addra_register', sprintf('off'), ... 'addra_implementation', sprintf('core'), ... 'dina_register', sprintf('off'), ... 'dina_implementation', sprintf('core'), ... 'wea_register', sprintf('off'), ... 'wea_implementation', sprintf('core'), ... 'ena_register', sprintf('off'), ... 'ena_implementation', sprintf('core'), ... 'addrb_register', sprintf('off'), ... 'addrb_implementation', sprintf('core'), ... 'dinb_register', sprintf('off'), ... 'dinb_implementation', sprintf('core'), ... 'web_register', sprintf('off'), ... 'web_implementation', sprintf('core'), ... 'enb_register', sprintf('off'), ... 'enb_implementation', sprintf('core'), ... 'Position', sprintf('[320 254 395 330]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_delay']); bus_delay_gen([blk,'/bus_delay']); set_param([blk,'/bus_delay'], ... 'n_bits', sprintf('8'), ... 'latency', sprintf('-1'), ... 'cmplx', sprintf('off'), ... 'enable', sprintf('off'), ... 'reg_retiming', sprintf('on'), ... 'misc', sprintf('off'), ... 'Position', sprintf('[220 372 295 448]'), ... 'Tag', sprintf('')); add_block('built-in/SubSystem', [blk,'/bus_constant']); bus_constant_gen([blk,'/bus_constant']); set_param([blk,'/bus_constant'], ... 'values', sprintf('[]'), ... 'n_bits', sprintf('[8]'), ... 'bin_pts', sprintf('[7]'), ... 'types', sprintf('[1]'), ... 'Position', sprintf('[320 372 395 448]'), ... 'Tag', sprintf('')); set_param(blk, ... 'Name', sprintf('casper_library_bus'), ... 'LibraryType', sprintf('BlockLibrary'), ... 'Lock', sprintf('off'), ... 'PreSaveFcn', sprintf('mdl2m(gcs, ''library'', ''on'');'), ... 'SolverName', sprintf('ode45'), ... 'SolverMode', sprintf('Auto'), ... 'StartTime', sprintf('0.0'), ... 'StopTime', sprintf('10.0')); filename = save_system(mdl,[getenv('MLIB_DEVEL_PATH'), '/casper_library/', 'casper_library_bus']); if iscell(filename), filename = filename{1}; end; fileattrib(filename, '+w'); end % casper_library_bus_init function bus_addsub_gen(blk) bus_addsub_mask(blk); bus_addsub_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_addsub_init(gcb, ...\n ''opmode'', opmode, ...\n ''n_bits_a'', n_bits_a, ...\n ''bin_pt_a'', bin_pt_a, ...\n ''type_a'', type_a, ...\n ''n_bits_b'', n_bits_b, ...\n ''bin_pt_b'', bin_pt_b, ...\n ''type_b'', type_b, ...\n ''n_bits_out'', n_bits_out, ...\n ''bin_pt_out'', bin_pt_out, ...\n ''type_out'', type_out, ...\n ''overflow'', overflow, ... \n ''quantization'', quantization, ...\n ''add_implementation'', add_implementation, ...\n ''latency'', latency, ...\n ''cmplx'', cmplx, ...\n ''misc'', misc, ...\n ''async'', async);')); end % bus_addsub_gen function bus_addsub_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_addsub'), ... 'MaskDescription', sprintf('Add/subtract components of two busses'), ... 'MaskPromptString', sprintf('mode (Addition=0, Subtraction=1)|a input bit widths|a input binary points |a input type (Unsigned=0, Signed=1)|b input bit widths|b input binary points|b input type (Unsigned=0, Signed=1)|complex|misc support|asynchronous operation|output bit widths|output binary points|output type (Unsigned=0, Signed=1)|quantization strategy (Truncate=0, Round (unbiased: +/- Inf)=1)|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|adder implementation|latency'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,edit,checkbox,checkbox,checkbox,edit,edit,edit,edit,edit,popup(behavioral HDL|fabric core|DSP48 core),edit'), ... 'MaskTabNameString', sprintf('input,input,input,input,input,input,input,input,input,input,output,output,output,implementation,implementation,implementation,latency'), ... 'MaskCallbackString', sprintf('||||||||||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('opmode=@1;n_bits_a=@2;bin_pt_a=@3;type_a=@4;n_bits_b=@5;bin_pt_b=@6;type_b=@7;cmplx=&8;misc=&9;async=&10;n_bits_out=@11;bin_pt_out=@12;type_out=@13;quantization=@14;overflow=@15;add_implementation=&16;latency=@17;'), ... 'MaskValueString', sprintf('0|0|3|1|4|3|1|on|on|off|8|3|1|0|1|fabric core|1'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_addsub_mask function bus_addsub_init(blk) end % bus_addsub_init function bus_register_gen(blk) bus_register_mask(blk); bus_register_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_register_init(gcb, ...\n ''reset'', reset, ...\n ''enable'', enable, ...\n ''cmplx'', cmplx, ...\n ''n_bits'', n_bits, ...\n ''misc'', misc);')); end % bus_register_gen function bus_register_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_register'), ... 'MaskDescription', sprintf('Register components of bus'), ... 'MaskPromptString', sprintf('reset port|enable port|complex data|input bit widths|misc support'), ... 'MaskStyleString', sprintf('checkbox,checkbox,checkbox,edit,checkbox'), ... 'MaskCallbackString', sprintf('||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on'), ... 'MaskVariables', sprintf('reset=&1;enable=&2;cmplx=&3;n_bits=@4;misc=&5;'), ... 'MaskValueString', sprintf('on|on|on|[]|on'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_register_mask function bus_register_init(blk) end % bus_register_init function bus_mux_gen(blk) bus_mux_mask(blk); bus_mux_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_mux_init(gcb, ...\n ''n_inputs'', n_inputs, ...\n ''n_bits'', n_bits, ...\n ''cmplx'', cmplx, ...\n ''misc'', misc, ...\n ''mux_latency'', mux_latency);')); end % bus_mux_gen function bus_mux_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_mux'), ... 'MaskDescription', sprintf('Mux components of bus'), ... 'MaskPromptString', sprintf('number of inputs|input bit widths|mux latency|complex data|misc support'), ... 'MaskStyleString', sprintf('edit,edit,edit,checkbox,checkbox'), ... 'MaskTabNameString', sprintf('input,input,latency,input,input'), ... 'MaskCallbackString', sprintf('||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on'), ... 'MaskVariables', sprintf('n_inputs=@1;n_bits=@2;mux_latency=@3;cmplx=&4;misc=&5;'), ... 'MaskValueString', sprintf('0|8|0|off|off'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_mux_mask function bus_mux_init(blk) end % bus_mux_init function bus_mult_gen(blk) bus_mult_mask(blk); bus_mult_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_mult_init(gcb, ...\n ''n_bits_a'', n_bits_a, ...\n ''bin_pt_a'', bin_pt_a, ...\n ''type_a'', type_a, ...\n ''cmplx_a'', cmplx_a, ...\n ''n_bits_b'', n_bits_b, ...\n ''bin_pt_b'', bin_pt_b, ...\n ''type_b'', type_b, ...\n ''cmplx_b'', cmplx_b, ...\n ''n_bits_out'', n_bits_out, ...\n ''bin_pt_out'', bin_pt_out, ...\n ''type_out'', type_out, ...\n ''quantization'', quantization, ...\n ''overflow'', overflow, ...\n ''mult_latency'', mult_latency, ...\n ''add_latency'', add_latency, ...\n ''conv_latency'', conv_latency, ...\n ''max_fanout'', max_fanout, ...\n ''fan_latency'', fan_latency, ...\n ''multiplier_implementation'', multiplier_implementation, ...\n ''misc'', misc);')); end % bus_mult_gen function bus_mult_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_mult'), ... 'MaskDescription', sprintf('Multiply components of two busses'), ... 'MaskPromptString', sprintf('a input bit widths|a input binary points |a input type (Unsigned=0, Signed=1)|a input complex|b input bit widths|b input binary points|b input type (Unsigned=0, Signed=1)|b input complex|output bit widths|output binary points|output type (Unsigned=0, Signed=1)|quantization strategy (Truncate=0, Round (unbiased: +/- Inf)=1)|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|multiplier latency|adder latency|convert latency|limit fanout to ?|fanout register latency|multiplier implementation|misc support'), ... 'MaskStyleString', sprintf('edit,edit,edit,checkbox,edit,edit,edit,checkbox,edit,edit,edit,edit,edit,edit,edit,edit,edit,edit,popup(behavioral HDL|standard core|embedded multiplier core),checkbox'), ... 'MaskTabNameString', sprintf('input,input,input,input,input,input,input,input,output,output,output,output,output,latency,latency,latency,implementation,implementation,implementation,input'), ... 'MaskCallbackString', sprintf('|||||||||||||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits_a=@1;bin_pt_a=@2;type_a=@3;cmplx_a=&4;n_bits_b=@5;bin_pt_b=@6;type_b=@7;cmplx_b=&8;n_bits_out=@9;bin_pt_out=@10;type_out=@11;quantization=@12;overflow=@13;mult_latency=@14;add_latency=@15;conv_latency=@16;max_fanout=@17;fan_latency=@18;multiplier_implementation=&19;misc=&20;'), ... 'MaskValueString', sprintf('0|4|1|on|4|3|1|on|12|7|1|0|0|3|1|1|2|0|behavioral HDL|on'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_mult_mask function bus_mult_init(blk) end % bus_mult_init function bus_replicate_gen(blk) bus_replicate_mask(blk); bus_replicate_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_replicate_init(gcb, ...\n ''replication'', replication, ...\n ''latency'', latency, ...\n ''implementation'', implementation, ...\n ''misc'', misc);')); end % bus_replicate_gen function bus_replicate_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_replicate'), ... 'MaskDescription', sprintf('Output bus formed by replicating input bus a number of times'), ... 'MaskPromptString', sprintf('replication factor|latency|misc support|delay implementation'), ... 'MaskStyleString', sprintf('edit,edit,checkbox,popup(core|behavioral)'), ... 'MaskCallbackString', sprintf('|||'), ... 'MaskEnableString', sprintf('on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on'), ... 'MaskVariables', sprintf('replication=@1;latency=@2;misc=&3;implementation=&4;'), ... 'MaskValueString', sprintf('0|0|on|core'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_replicate_mask function bus_replicate_init(blk) end % bus_replicate_init function bus_logical_gen(blk) bus_logical_mask(blk); bus_logical_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_logical_init(gcb, ...\n ''logical_function'', logical_function, ...\n ''en'', en, ...\n ''n_bits_a'', n_bits_a, ...\n ''bin_pt_a'', bin_pt_a, ...\n ''type_a'', type_a, ...\n ''n_bits_b'', n_bits_b, ...\n ''bin_pt_b'', bin_pt_b, ...\n ''type_b'', type_b, ...\n ''n_bits_out'', n_bits_out, ...\n ''bin_pt_out'', bin_pt_out, ...\n ''type_out'', type_out, ...\n ''latency'', latency, ...\n ''cmplx'', cmplx, ...\n ''align_bp'', align_bp, ...\n ''misc'', misc);')); end % bus_logical_gen function bus_logical_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_logical'), ... 'MaskDescription', sprintf('Form the logical product of two busses'), ... 'MaskPromptString', sprintf('logical function|align binary point|latency|a input bit widths|a input binary points |a input type (Unsigned=0, Signed=1)|b input bit widths|b input binary points|b input type (Unsigned=0, Signed=1)|complex|en port|misc support|output bit widths|output binary points|output type (Unsigned=0, Signed=1)'), ... 'MaskStyleString', sprintf('popup(AND|NAND|OR|NOR|XOR|XNOR),checkbox,edit,edit,edit,edit,edit,edit,edit,checkbox,checkbox,checkbox,edit,edit,edit'), ... 'MaskTabNameString', sprintf('operation,operation,operation,input,input,input,input,input,input,input,input,input,output,output,output'), ... 'MaskCallbackString', sprintf('||||||||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('logical_function=&1;align_bp=&2;latency=@3;n_bits_a=@4;bin_pt_a=@5;type_a=@6;n_bits_b=@7;bin_pt_b=@8;type_b=@9;cmplx=&10;en=&11;misc=&12;n_bits_out=@13;bin_pt_out=@14;type_out=@15;'), ... 'MaskValueString', sprintf('AND|on|1|[]|3|1|4|3|1|on|on|on|8|3|1'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_logical_mask function bus_logical_init(blk) end % bus_logical_init function bus_convert_gen(blk) bus_convert_mask(blk); bus_convert_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_convert_init(gcb, ...\n ''n_bits_in'', n_bits_in, ...\n ''bin_pt_in'', bin_pt_in, ...\n ''cmplx'', cmplx, ...\n ''n_bits_out'', n_bits_out, ...\n ''bin_pt_out'', bin_pt_out, ...\n ''quantization'', quantization, ...\n ''overflow'', overflow, ...\n ''latency'', latency, ...\n ''misc'', misc, ...\n ''of'', of);')); end % bus_convert_gen function bus_convert_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_convert'), ... 'MaskDescription', sprintf('Convert components of busses'), ... 'MaskPromptString', sprintf('input bit widths|input binary points |input complex|output bit widths|output binary points|quantization strategy (Truncate=0, Round (unbiased: +/- Inf)=1, Round (unbiased: Even Values)=2)|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|latency|overflow indication|misc support'), ... 'MaskStyleString', sprintf('edit,edit,checkbox,edit,edit,edit,edit,edit,checkbox,checkbox'), ... 'MaskTabNameString', sprintf('input,input,input,output,output,output,output,operation,operation,input'), ... 'MaskCallbackString', sprintf('|||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits_in=@1;bin_pt_in=@2;cmplx=&3;n_bits_out=@4;bin_pt_out=@5;quantization=@6;overflow=@7;latency=@8;of=&9;misc=&10;'), ... 'MaskValueString', sprintf('[]|8|off|8|4|1|1|2|on|on'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_convert_mask function bus_convert_init(blk) end % bus_convert_init function bus_negate_gen(blk) bus_negate_mask(blk); bus_negate_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_negate_init(gcb, ...\n ''n_bits_in'', n_bits_in, ...\n ''bin_pt_in'', bin_pt_in, ...\n ''cmplx'', cmplx, ...\n ''overflow'', overflow, ...\n ''latency'', latency, ...\n ''misc'', misc);')); end % bus_negate_gen function bus_negate_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_negate'), ... 'MaskDescription', sprintf('Negate components of busses'), ... 'MaskPromptString', sprintf('input bit widths|input binary points |input complex|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|latency|misc support'), ... 'MaskStyleString', sprintf('edit,edit,checkbox,edit,edit,checkbox'), ... 'MaskTabNameString', sprintf('input,input,input,operation,operation,input'), ... 'MaskCallbackString', sprintf('|||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits_in=@1;bin_pt_in=@2;cmplx=&3;overflow=@4;latency=@5;misc=&6;'), ... 'MaskValueString', sprintf('0|8|off|1|2|off'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_negate_mask function bus_negate_init(blk) end % bus_negate_init function bus_accumulator_gen(blk) bus_accumulator_mask(blk); bus_accumulator_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_accumulator_init(gcb, ...\n ''reset'', reset, ...\n ''enable'', enable, ...\n ''n_bits_in'', n_bits_in, ...\n ''bin_pt_in'', bin_pt_in, ...\n ''type_in'', type_in, ...\n ''cmplx'', cmplx, ...\n ''n_bits_out'', n_bits_out, ...\n ''overflow'', overflow, ...\n ''misc'', misc);')); end % bus_accumulator_gen function bus_accumulator_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_accumulator'), ... 'MaskDescription', sprintf('Accumulate components of bus'), ... 'MaskPromptString', sprintf('reset port|enable port|input bit widths|input binary points|input types (Unsigned=0, Signed=1)|complex inputs|output bit widths|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|misc support'), ... 'MaskStyleString', sprintf('checkbox,checkbox,edit,edit,edit,checkbox,edit,edit,checkbox'), ... 'MaskCallbackString', sprintf('||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('reset=&1;enable=&2;n_bits_in=@3;bin_pt_in=@4;type_in=@5;cmplx=&6;n_bits_out=@7;overflow=@8;misc=&9;'), ... 'MaskValueString', sprintf('on|on|[]|3|1|on|16|1|on'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_accumulator_mask function bus_accumulator_init(blk) end % bus_accumulator_init function bus_relational_gen(blk) bus_relational_mask(blk); bus_relational_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_relational_init(gcb, ...\n ''n_bits_a'', n_bits_a, ...\n ''bin_pt_a'', bin_pt_a, ...\n ''type_a'', type_a, ...\n ''n_bits_b'', n_bits_b, ...\n ''bin_pt_b'', bin_pt_b, ...\n ''type_b'', type_b, ...\n ''en'', en, ...\n ''misc'', misc, ...\n ''mode'', mode, ...\n ''latency'', latency);')); end % bus_relational_gen function bus_relational_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_relational'), ... 'MaskDescription', sprintf('Find the relational product of two busses'), ... 'MaskPromptString', sprintf('a input bit widths|a input binary points |a input type (Unsigned=0, Signed=1)|b input bit widths|b input binary points|b input type (Unsigned=0, Signed=1)|en port|misc support|comparison:|latency'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,edit,edit,checkbox,checkbox,popup(a=b|a!=b|a<b|a>b|a<=b|a>=b),edit'), ... 'MaskTabNameString', sprintf('input,input,input,input,input,input,input,input,operation,operation'), ... 'MaskCallbackString', sprintf('|||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits_a=@1;bin_pt_a=@2;type_a=@3;n_bits_b=@4;bin_pt_b=@5;type_b=@6;en=&7;misc=&8;mode=&9;latency=@10;'), ... 'MaskValueString', sprintf('0|0|1|8|0|1|off|off|a=b|1'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_relational_mask function bus_relational_init(blk) end % bus_relational_init function bus_scale_gen(blk) bus_scale_mask(blk); bus_scale_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_scale_init(gcb, ...\n ''n_bits_in'', n_bits_in, ...\n ''bin_pt_in'', bin_pt_in, ...\n ''type_in'', type_in, ...\n ''cmplx'', cmplx, ...\n ''scale_factor'', scale_factor, ...\n ''misc'', misc);')); end % bus_scale_gen function bus_scale_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_scale'), ... 'MaskDescription', sprintf('Convert components of busses'), ... 'MaskPromptString', sprintf('input bit widths|input binary points |input types|input complex|scale factor (2^?)|misc support'), ... 'MaskStyleString', sprintf('edit,edit,edit,checkbox,edit,checkbox'), ... 'MaskTabNameString', sprintf('input,input,input,input,output,input'), ... 'MaskCallbackString', sprintf('|||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits_in=@1;bin_pt_in=@2;type_in=@3;cmplx=&4;scale_factor=@5;misc=&6;'), ... 'MaskValueString', sprintf('[]|8|1|off|2|on'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_scale_mask function bus_scale_init(blk) end % bus_scale_init function bus_single_port_ram_gen(blk) bus_single_port_ram_mask(blk); bus_single_port_ram_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_single_port_ram_init(gcb, ...\n ''n_bits'', n_bits, ...\n ''bin_pts'', bin_pts, ...\n ''init_vector'', init_vector, ...\n ''max_fanout'', max_fanout, ...\n ''mem_type'', mem_type, ...\n ''bram_optimization'', bram_optimization, ...\n ''async'', async, ...\n ''misc'', misc, ...\n ''bram_latency'', bram_latency, ...\n ''fan_latency'', fan_latency, ...\n ''addr_register'', addr_register, ...\n ''addr_implementation'', addr_implementation, ...\n ''din_register'', din_register, ...\n ''din_implementation'', din_implementation, ...\n ''we_register'', we_register, ...\n ''we_implementation'', we_implementation, ...\n ''en_register'', en_register, ...\n ''en_implementation'', en_implementation);')); end % bus_single_port_ram_gen function bus_single_port_ram_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_single_port_ram'), ... 'MaskDescription', sprintf('RAM for a bus allowing fanout control'), ... 'MaskPromptString', sprintf('data word bit widths|data word binary points|initial value vector|limit fanout to ?|memory type|memory optimization|asynchronous |misc support|bram latency|input register latency|addr input register|addr register implementation|din input register|din register implementation|we input register|we register implementation|en input register|en register implementation'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,popup(Distributed memory|Block RAM),popup(Area|Speed),checkbox,checkbox,edit,edit,checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral)'), ... 'MaskTabNameString', sprintf('basic,basic,basic,basic,basic,basic,basic,basic,latency,latency,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation'), ... 'MaskCallbackString', sprintf('|||||||||||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits=@1;bin_pts=@2;init_vector=@3;max_fanout=@4;mem_type=&5;bram_optimization=&6;async=&7;misc=&8;bram_latency=@9;fan_latency=@10;addr_register=&11;addr_implementation=&12;din_register=&13;din_implementation=&14;we_register=&15;we_implementation=&16;en_register=&17;en_implementation=&18;'), ... 'MaskValueString', sprintf('0|17|[[-2:1/(2^10):2-(1/(2^10))]'']|4|Block RAM|Speed|off|off|2|1|on|core|on|core|on|core|on|core'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_single_port_ram_mask function bus_single_port_ram_init(blk) end % bus_single_port_ram_init function bus_maddsub_gen(blk) bus_maddsub_mask(blk); bus_maddsub_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_maddsub_init(gcb, ...\n ''n_bits_a'', n_bits_a, ...\n ''bin_pt_a'', bin_pt_a, ...\n ''type_a'', type_a, ...\n ''cmplx_a'', cmplx_a, ...\n ''n_bits_b'', n_bits_b, ...\n ''bin_pt_b'', bin_pt_b, ...\n ''type_b'', type_b, ...\n ''mult_latency'', mult_latency, ...\n ''multiplier_implementation'', multiplier_implementation, ...\n ''replication_ab'', replication_ab, ...\n ''opmode'', opmode, ...\n ''n_bits_c'', n_bits_c, ...\n ''bin_pt_c'', bin_pt_c, ...\n ''type_c'', type_c, ...\n ''add_implementation'', add_implementation, ...\n ''add_latency'', add_latency, ...\n ''async_add'', async_add, ...\n ''align_c'', align_c, ...\n ''replication_c'', replication_c, ...\n ''n_bits_out'', n_bits_out, ...\n ''bin_pt_out'', bin_pt_out, ...\n ''type_out'', type_out, ...\n ''quantization'', quantization, ...\n ''overflow'', overflow, ...\n ''max_fanout'', max_fanout);')); end % bus_maddsub_gen function bus_maddsub_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_maddsub'), ... 'MaskDescription', sprintf('Multiply and add/subtract components of two busses'), ... 'MaskPromptString', sprintf('a input bit widths|a input binary points |a input type (Unsigned=0, Signed=1)|a complex|b input bit widths|b input binary points|b input type (Unsigned=0, Signed=1)|multiplier latency|multiplier implementation|a and b input replication support|mode|c input bit widths|c input binary points|c input type (Unsigned=0, Signed=1)|adder implementation|adder latency|asynchronous addition|align c path with a and b|c input replication support|output bit widths|output binary points|output type (Unsigned=0, Signed=1)|quantization strategy (Truncate=0, Round (unbiased: +/- Inf)=1)|overflow strategy (Wrap=0, Saturate=1, Flag as error=2)|limit fanout to ?'), ... 'MaskStyleString', sprintf('edit,edit,edit,checkbox,edit,edit,edit,edit,popup(behavioral HDL|standard core|embedded multiplier core),checkbox,popup(Addition|Subtraction),edit,edit,edit,popup(behavioral HDL|fabric core|DSP48 core),edit,checkbox,checkbox,checkbox,edit,edit,edit,edit,edit,edit'), ... 'MaskTabNameString', sprintf('multiplication,multiplication,multiplication,multiplication,multiplication,multiplication,multiplication,multiplication,multiplication,multiplication,addsub,addsub,addsub,addsub,addsub,addsub,addsub,addsub,addsub,output,output,output,output,output,implementation'), ... 'MaskCallbackString', sprintf('||||||||||||||||||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits_a=@1;bin_pt_a=@2;type_a=@3;cmplx_a=&4;n_bits_b=@5;bin_pt_b=@6;type_b=@7;mult_latency=@8;multiplier_implementation=&9;replication_ab=&10;opmode=&11;n_bits_c=@12;bin_pt_c=@13;type_c=@14;add_implementation=&15;add_latency=@16;async_add=&17;align_c=&18;replication_c=&19;n_bits_out=@20;bin_pt_out=@21;type_out=@22;quantization=@23;overflow=@24;max_fanout=@25;'), ... 'MaskValueString', sprintf('0|7|1|on|[18 18]|17|1|3|behavioral HDL|on|Addition|[4 4 4 4]|3|0|behavioral HDL|1|on|off|off|26|24|1|0|0|2'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_maddsub_mask function bus_maddsub_init(blk) end % bus_maddsub_init function bus_dual_port_ram_gen(blk) bus_dual_port_ram_mask(blk); bus_dual_port_ram_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_dual_port_ram_init(gcb, ...\n ''n_bits'', n_bits, ...\n ''bin_pts'', bin_pts, ...\n ''init_vector'', init_vector, ...\n ''max_fanout'', max_fanout, ...\n ''mem_type'', mem_type, ...\n ''bram_optimization'', bram_optimization, ...\n ''async_a'', async_a, ...\n ''async_b'', async_b, ...\n ''misc'', misc, ...\n ''bram_latency'', bram_latency, ...\n ''fan_latency'', fan_latency, ...\n ''addra_register'', addra_register, ...\n ''addra_implementation'', addra_implementation, ...\n ''dina_register'', dina_register, ...\n ''dina_implementation'', dina_implementation, ...\n ''wea_register'', wea_register, ...\n ''wea_implementation'', wea_implementation, ...\n ''ena_register'', ena_register, ...\n ''ena_implementation'', ena_implementation, ...\n ''addrb_register'', addrb_register, ...\n ''addrb_implementation'', addrb_implementation, ...\n ''dinb_register'', dinb_register, ...\n ''dinb_implementation'', dinb_implementation, ...\n ''web_register'', web_register, ...\n ''web_implementation'', web_implementation, ...\n ''enb_register'', enb_register, ...\n ''enb_implementation'', enb_implementation);')); end % bus_dual_port_ram_gen function bus_dual_port_ram_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_dual_port_ram'), ... 'MaskDescription', sprintf('RAM for a bus allowing fanout control'), ... 'MaskPromptString', sprintf('data word bit widths|data word binary points|initial value vector|limit fanout to ?|memory type|memory optimization|a asynchronous |b asynchronous|misc support|bram latency|input register latency|addra input register|addra register implementation|dina input register|dina register implementation|wea input register|wea register implementation|ena input register|ena register implementation|addrb input register|addrb register implementation|dinb input register|dinb register implementation|web input register|web register implementation|enb input register|enb register implementation'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit,popup(Distributed memory|Block RAM),popup(Area|Speed),checkbox,checkbox,checkbox,edit,edit,checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral),checkbox,popup(core|behavioral)'), ... 'MaskTabNameString', sprintf('basic,basic,basic,basic,basic,basic,basic,basic,basic,latency,latency,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation,implementation'), ... 'MaskCallbackString', sprintf('||||||||||||||||||||||||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits=@1;bin_pts=@2;init_vector=@3;max_fanout=@4;mem_type=&5;bram_optimization=&6;async_a=&7;async_b=&8;misc=&9;bram_latency=@10;fan_latency=@11;addra_register=&12;addra_implementation=&13;dina_register=&14;dina_implementation=&15;wea_register=&16;wea_implementation=&17;ena_register=&18;ena_implementation=&19;addrb_register=&20;addrb_implementation=&21;dinb_register=&22;dinb_implementation=&23;web_register=&24;web_implementation=&25;enb_register=&26;enb_implementation=&27;'), ... 'MaskValueString', sprintf('0|17|[[-2:1/(2^10):2-(1/(2^10))]'']|4|Block RAM|Area|off|off|off|2|1|off|core|off|core|off|core|off|core|off|core|off|core|off|core|off|core'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_dual_port_ram_mask function bus_dual_port_ram_init(blk) end % bus_dual_port_ram_init function bus_delay_gen(blk) bus_delay_mask(blk); bus_delay_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_delay_init(gcb, ...\n ''enable'', enable, ...\n ''cmplx'', cmplx, ...\n ''n_bits'', n_bits, ...\n ''latency'', latency, ...\n ''reg_retiming'', reg_retiming, ...\n ''misc'', misc);')); end % bus_delay_gen function bus_delay_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_delay'), ... 'MaskDescription', sprintf('Delay components of a bus'), ... 'MaskPromptString', sprintf('input bit widths|latency|complex data|enable port|implement using behavioral HDL|misc support'), ... 'MaskStyleString', sprintf('edit,edit,checkbox,checkbox,checkbox,checkbox'), ... 'MaskCallbackString', sprintf('|||||'), ... 'MaskEnableString', sprintf('on,on,on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on,on,on'), ... 'MaskVariables', sprintf('n_bits=@1;latency=@2;cmplx=&3;enable=&4;reg_retiming=&5;misc=&6;'), ... 'MaskValueString', sprintf('8|-1|off|off|on|off'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_delay_mask function bus_delay_init(blk) end % bus_delay_init function bus_constant_gen(blk) bus_constant_mask(blk); bus_constant_init(blk); set_param(blk, ... 'MaskInitialization', sprintf('bus_constant_init(gcb, ...\n ''values'', values, ...\n ''n_bits'', n_bits, ...\n ''bin_pts'', bin_pts, ...\n ''types'', types);')); end % bus_constant_gen function bus_constant_mask(blk) set_param(blk, ... 'Mask', sprintf('on'), ... 'MaskSelfModifiable', sprintf('on'), ... 'MaskType', sprintf('bus_constant'), ... 'MaskDescription', sprintf('Combine constants into a bus'), ... 'MaskPromptString', sprintf('values|bit widths|binary points|data type'), ... 'MaskStyleString', sprintf('edit,edit,edit,edit'), ... 'MaskCallbackString', sprintf('|||'), ... 'MaskEnableString', sprintf('on,on,on,on'), ... 'MaskVisibilityString', sprintf('on,on,on,on'), ... 'MaskToolTipString', sprintf('on,on,on,on'), ... 'MaskVariables', sprintf('values=@1;n_bits=@2;bin_pts=@3;types=@4;'), ... 'MaskValueString', sprintf('[]|[8]|[7]|[1]'), ... 'BackgroundColor', sprintf('[0.501961, 1.000000, 0.501961]')); end % bus_constant_mask function bus_constant_init(blk) end % bus_constant_init
github
mstrader/mlib_devel-master
square_transposer_init.m
.m
mlib_devel-master/casper_library/square_transposer_init.m
6,020
utf_8
961ec46a987dd5eaa5ef2f8a8eab46ec
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2007 Terry Filiba, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function square_transposer_init(blk, varargin) % Initialize and configure the square transposer. % % square_transposer_init(blk, varargin) % % blk = The block to configure. % varargin = {'varname', 'value', ...} pairs % % Valid varnames for this block are: % n_inputs = The number of inputs to be transposed. % Declare any default values for arguments you might like. defaults = { ... 'n_inputs', 1, ... 'async', 'on', ... }; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'square_transposer'); munge_block(blk, varargin{:}); n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); ytick = 50; if n_inputs < 0, error('Number of inputs must be 2^0 or greater.'); end delete_lines(blk); if n_inputs == 0, clean_blocks(blk); set_param(blk, 'AttributesFormatString', ''); save_state(blk, 'defaults', defaults, varargin{:}); return; end % Add ports reuse_block(blk, 'sync', 'built-in/inport', 'Position', [15 103 45 117], 'Port', '1'); reuse_block(blk, 'sync_out', 'built-in/outport', 'Position', [415 58 445 72], 'Port', '1'); if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/inport', 'Port', num2str(2+2^n_inputs), ... 'Position', [15 ((2^n_inputs)+1)*ytick+153 45 167+ytick*((2^n_inputs)+1)]); reuse_block(blk, 'dvalid', 'built-in/outport', 'Port', num2str(2+2^n_inputs), ... 'Position', [415 113+((2^n_inputs)*ytick) 445 127+(ytick*(2^n_inputs))]); end for p=0:2^n_inputs-1, reuse_block(blk, ['in',num2str(p)], 'built-in/inport', 'Port', num2str(2+p),... 'Position', [15 (p*ytick)+153 45 167+(ytick*p)]); reuse_block(blk, ['out',num2str(p)], 'built-in/outport', 'Port', num2str(2+p),... 'Position', [415 113+(p*ytick) 445 127+(ytick*p)]); end % Add blocks reuse_block(blk, 'counter', 'xbsIndex_r4/Counter', ... 'Position', [180 44 220 76], 'cnt_type', 'Free Running', 'n_bits', 'n_inputs', ... 'arith_type', 'Unsigned', 'rst', 'on', 'en', async, 'operation', 'Down'); add_line(blk, 'sync/1', 'counter/1'); reuse_block(blk, 'dsync', 'casper_library_delays/delay_slr', ... 'DelayLen', num2str(2^n_inputs - 1), 'async', async, 'Position', [370 52 400 78]); add_line(blk, 'dsync/1', 'sync_out/1'); reuse_block(blk, 'barrel_switcher', 'casper_library_reorder/barrel_switcher', ... 'async', async, 'n_inputs', num2str(n_inputs), 'Position', [245 22 305 22+(2^n_inputs+2)*ytick]); add_line(blk, 'sync/1', 'barrel_switcher/2'); add_line(blk, 'counter/1', 'barrel_switcher/1'); add_line(blk, 'barrel_switcher/1', 'dsync/1'); for q=0:2^n_inputs-1, dport = mod(2^n_inputs - q, 2^n_inputs) + 3; if q ~= 0, df = ['df', num2str(q)]; reuse_block(blk, df, 'casper_library_delays/delay_slr', ... 'DelayLen', num2str(q), 'async', async, 'Position', [70 (q*ytick)+148 100 (q*ytick)+172]); add_line(blk, ['in', num2str(q),'/1'], [df,'/1']); add_line(blk, [df, '/1'], ['barrel_switcher/', num2str(dport)]); if strcmp(async, 'on'), add_line(blk, 'en/1', [df,'/2']); end else, add_line(blk, ['in', num2str(q), '/1'], ['barrel_switcher/', num2str(dport)]); end if (2^n_inputs)-(q+1) ~= 0, db = ['db', num2str(q)]; reuse_block(blk, db, 'casper_library_delays/delay_slr', ... 'DelayLen', num2str((2^n_inputs)-(q+1)), 'async', async, 'Position', [370 (q*ytick)+108 400 (q*ytick)+132]); add_line(blk, ['barrel_switcher/',num2str(q+2)], [db,'/1']); add_line(blk, [db,'/1'], ['out',num2str(q),'/1']); if strcmp(async, 'on'), add_line(blk, ['barrel_switcher/',num2str(2^n_inputs+2)], [db,'/2']); end else, add_line(blk, ['barrel_switcher/',num2str(q+2)], ['out',num2str(q),'/1']); end end if strcmp(async, 'on'), add_line(blk, 'en/1', 'counter/2'); add_line(blk, 'en/1', ['barrel_switcher/',num2str(2^n_inputs+3)]); add_line(blk, ['barrel_switcher/',num2str(2^n_inputs+2)], 'dvalid/1'); add_line(blk, ['barrel_switcher/',num2str(2^n_inputs+2)], 'dsync/2'); end clean_blocks(blk); fmtstr = sprintf('n_inputs=%d', n_inputs); set_param(blk, 'AttributesFormatString', fmtstr); save_state(blk, 'defaults', defaults, varargin{:});
github
mstrader/mlib_devel-master
fft_callback_arch.m
.m
mlib_devel-master/casper_library/fft_callback_arch.m
2,182
utf_8
a0497bc714337ac06795551eb88844ce
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://casper.berkeley.edu % % Copyright (C) 2010 William Mallard % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function fft_callback_arch(cursys) % Dialog callback for arch parameter in all fft blocks. % if arch is Virtex5, allow dsp48 adders. % otherwise: disable them, disallow them, % and ensure that add_latency is enabled. arch = get_param(gcb, 'arch'); if strcmp(arch, 'Virtex5'), set_param_state(gcb, 'dsp48_adders', 'on'); else set_param(gcb, 'dsp48_adders', 'off'); set_param_state(gcb, 'dsp48_adders', 'off'); set_param_state(gcb, 'add_latency', 'on'); end end
github
mstrader/mlib_devel-master
complex_conj_init.m
.m
mlib_devel-master/casper_library/complex_conj_init.m
5,644
utf_8
4d08063798a1c7e3ec925039cbe7b691
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKASA % % www.kat.ac.za % % Copyright (C) Andrew Martens 2013 % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function complex_conj_init(blk, varargin) clog('entering complex_conj_init', {'trace', 'complex_conj_init_debug'}); % Set default vararg values. % reg_retiming is not an actual parameter of this block, but it is included % in defaults so that same_state will return false for blocks drawn prior to % adding reg_retiming='on' to some of the underlying Delay blocks. defaults = { ... 'n_inputs', 1, ... 'n_bits', 18, ... 'bin_pt', 17, ... 'latency', 1, ... 'overflow', 'Wrap', ... 'reg_retiming', 'on', ... }; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'complex_conj'); munge_block(blk, varargin{:}); % Retrieve values from mask fields. n_inputs = get_var('n_inputs', 'defaults', defaults, varargin{:}); n_bits = get_var('n_bits', 'defaults', defaults, varargin{:}); bin_pt = get_var('bin_pt', 'defaults', defaults, varargin{:}); latency = get_var('latency', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); delete_lines(blk); %default setup for library if n_inputs == 0, clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting complex_conj_init',{'trace','complex_conj_init_debug'}); return; end reuse_block(blk, 'z', 'built-in/Inport', 'Port', '1', 'Position', [10 92 40 108]); %move real and imaginary parts from multiple streams to be next to each other reuse_block(blk, 'munge_in', 'casper_library_flow_control/munge', ... 'divisions', num2str(2*n_inputs), ... 'div_size', mat2str(repmat(n_bits, 1, 2*n_inputs)), ... 'order', mat2str([[0:2:(n_inputs-1)*2],[1:2:(n_inputs-1)*2+1]]), ... 'Position', [70 87 110 113]); add_line(blk,'z/1','munge_in/1'); reuse_block(blk, 'bus_expand', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of equal size', 'outputNum', '2', 'outputWidth', num2str(n_bits*n_inputs), ... 'outputBinaryPt', '0', 'outputArithmeticType', '0', ... 'Position', [140 52 190 148]); add_line(blk,'munge_in/1','bus_expand/1'); reuse_block(blk, 'real_delay', 'xbsIndex_r4/Delay', ... 'latency', num2str(latency), ... 'reg_retiming', 'on', ... 'Position', [230 59 290 91]); add_line(blk,'bus_expand/1','real_delay/1'); if strcmp(overflow, 'Wrap'), of = '0'; elseif strcmp(overflow, 'Saturate'), of = '1'; elseif strcmp(overflow, 'Flag as error'), of = '2'; else %TODO end reuse_block(blk, 'imag_negate', 'casper_library_bus/bus_negate', ... 'n_bits_in', mat2str(repmat(n_bits, 1, n_inputs)), 'bin_pt_in', num2str(bin_pt), ... 'cmplx', 'off', 'overflow', of, 'misc', 'off', 'latency', num2str(latency), ... 'Position', [230 109 290 141]); add_line(blk,'bus_expand/2','imag_negate/1'); reuse_block(blk, 'bus_create', 'casper_library_flow_control/bus_create', ... 'inputNum', '2', 'Position', [330 51 380 149]); add_line(blk,'real_delay/1','bus_create/1'); add_line(blk,'imag_negate/1','bus_create/2'); % move real and imaginary parts from multiple streams back reuse_block(blk, 'munge_out', 'casper_library_flow_control/munge', ... 'divisions', num2str(n_inputs*2), ... 'div_size', mat2str(repmat(n_bits, 1, n_inputs*2)), ... 'order', mat2str(reshape([[0:(n_inputs-1)];[n_inputs:(n_inputs*2)-1]], 1, n_inputs*2)), ... 'Position', [410 87 450 113]); add_line(blk,'bus_create/1','munge_out/1'); reuse_block(blk, 'z*', 'built-in/Outport', 'Port', '1', 'Position', [480 92 510 108]); add_line(blk,'munge_out/1','z*/1'); % Delete all unconnected blocks. clean_blocks(blk); % Save block state to stop repeated init script runs. save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting complex_conj_init',{'trace','complex_conj_init_debug'}); end %complex_conj_init
github
mstrader/mlib_devel-master
delay_srl_init.m
.m
mlib_devel-master/casper_library/delay_srl_init.m
3,979
utf_8
1f53316360552c35a274dbd4c08e6552
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKASA % % www.kat.ac.za % % Copyright (C) Andrew Martens 2013 % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function delay_srl_init(blk, varargin) clog('entering delay_srl_init', {'trace', 'delay_srl_init_debug'}); % Set default vararg values. defaults = { ... 'DelayLen', 1, ... 'async', 'off', ... }; if same_state(blk, 'defaults', defaults, varargin{:}), return, end check_mask_type(blk, 'delay_srl'); munge_block(blk, varargin{:}); % Retrieve values from mask fields. DelayLen = get_var('DelayLen', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); delete_lines(blk); %default setup for library if DelayLen < 0, clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); clog('exiting delay_srl_init',{'trace','delay_srl_init_debug'}); return; end if (DelayLen > 0), ff_delay = 1; srl_delay = DelayLen - 1; else ff_delay = 0; srl_delay = 0; end if strcmp(async, 'on'), reuse_block(blk, 'en', 'built-in/Inport', 'Port', '1', 'Position', [25 92 55 108]); %terminate if no delay if ~(DelayLen > 0), reuse_block(blk, 'arnold', 'built-in/Terminator', 'Position', [80 90 100 110]); add_line(blk, 'en/1', 'arnold/1'); end end reuse_block(blk, 'in', 'built-in/Inport', 'Port', '1', 'Position', [25 38 55 52]); prev_blk = 'in'; if ff_delay > 0, reuse_block(blk, 'delay_ff', 'xbsIndex_r4/Delay', ... 'en', async, 'latency', num2str(ff_delay), 'Position', [80 22 125 68]); add_line(blk, [prev_blk,'/1'], 'delay_ff/1'); prev_blk = 'delay_ff'; if strcmp(async, 'on'), add_line(blk, 'en/1', 'delay_ff/2'); end end if srl_delay > 0, reuse_block(blk, 'delay_sr', 'xbsIndex_r4/Delay', ... 'en', async, 'latency', num2str(srl_delay), 'reg_retiming', 'on', ... 'Position', [150 22 195 68]); add_line(blk, [prev_blk,'/1'], 'delay_sr/1'); prev_blk = 'delay_sr'; if strcmp(async, 'on'), add_line(blk, 'en/1', 'delay_sr/2'); end end reuse_block(blk, 'out', 'built-in/Outport', 'Port', '1', 'Position', [220 38 250 52]); add_line(blk, [prev_blk,'/1'], 'out/1'); % Delete all unconnected blocks. clean_blocks(blk); % Save block state to stop repeated init script runs. save_state(blk, 'defaults', defaults, varargin{:}); end % delay_srl_init
github
mstrader/mlib_devel-master
clean_blocks.m
.m
mlib_devel-master/casper_library/clean_blocks.m
2,807
utf_8
1262b3dca13b1b2051b0b227e10f9cfb
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2006 David MacMahon, Aaron Parsons % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function clean_blocks(cursys) % Remove any blocks from a subsystem which are not connected % to the rest of the system. % % clean_blocks(cursys) try blocks = get_param(cursys, 'Blocks'); for i=1:length(blocks), blk = [cursys,'/',blocks{i}]; ports = get_param(blk, 'PortConnectivity'); if ~isempty(ports), flag = 0; for j=1:length(ports), if ports(j).SrcBlock == -1, clog(['block ' cursys '/' get_param(blk,'Name') ... ' input port ' num2str(j) ... ' undriven (block will be deleted)'], ... 'clean_blocks_debug'); flag = 0; break elseif ~flag && (~isempty(ports(j).SrcBlock) || ~isempty(ports(j).DstBlock)), flag = 1; end end if flag == 0, clog(['deleting block ' cursys '/' get_param(blk,'Name')], ... 'clean_blocks_debug'); delete_block(blk); end end end catch ex dump_and_rethrow(ex); end % try/catch
github
mstrader/mlib_devel-master
bus_addsub_init.m
.m
mlib_devel-master/casper_library/bus_addsub_init.m
13,544
utf_8
1d514e3e96c6c12d5ac218209757b168
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % SKA Africa % % http://www.kat.ac.za % % Copyright (C) 2013 Andrew Martens ([email protected]) % % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function bus_addsub_init(blk, varargin) clog('entering bus_addsub_init', {'trace', 'bus_addsub_init_debug'}); defaults = { ... 'opmode', [0], ... 'n_bits_a', [8] , 'bin_pt_a', [3], 'type_a', 1, ... 'n_bits_b', [4 ] , 'bin_pt_b', [3], 'type_b', [1], ... 'n_bits_out', 8 , 'bin_pt_out', [3], 'type_out', [1], ... 'overflow', [1], 'quantization', [0], 'add_implementation', 'fabric core', ... 'latency', 1, 'async', 'off', 'cmplx', 'on', 'misc', 'on' }; check_mask_type(blk, 'bus_addsub'); if same_state(blk, 'defaults', defaults, varargin{:}), return, end munge_block(blk, varargin{:}); xpos = 50; xinc = 80; ypos = 50; yinc = 50; port_w = 30; port_d = 14; bus_expand_w = 50; bus_create_w = 50; add_w = 50; add_d = 60; del_w = 30; del_d = 20; opmode = get_var('opmode', 'defaults', defaults, varargin{:}); n_bits_a = get_var('n_bits_a', 'defaults', defaults, varargin{:}); bin_pt_a = get_var('bin_pt_a', 'defaults', defaults, varargin{:}); type_a = get_var('type_a', 'defaults', defaults, varargin{:}); n_bits_b = get_var('n_bits_b', 'defaults', defaults, varargin{:}); bin_pt_b = get_var('bin_pt_b', 'defaults', defaults, varargin{:}); type_b = get_var('type_b', 'defaults', defaults, varargin{:}); n_bits_out = get_var('n_bits_out', 'defaults', defaults, varargin{:}); bin_pt_out = get_var('bin_pt_out', 'defaults', defaults, varargin{:}); type_out = get_var('type_out', 'defaults', defaults, varargin{:}); overflow = get_var('overflow', 'defaults', defaults, varargin{:}); quantization = get_var('quantization', 'defaults', defaults, varargin{:}); add_implementation = get_var('add_implementation', 'defaults', defaults, varargin{:}); latency = get_var('latency', 'defaults', defaults, varargin{:}); misc = get_var('misc', 'defaults', defaults, varargin{:}); cmplx = get_var('cmplx', 'defaults', defaults, varargin{:}); async = get_var('async', 'defaults', defaults, varargin{:}); delete_lines(blk); %default state, do nothing if (n_bits_a == 0) | (n_bits_b == 0), clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_add_init',{'trace', 'bus_addsub_init_debug'}); return; end lenba = length(n_bits_a); lenpa = length(bin_pt_a); lenta = length(type_a); a = [lenba, lenpa, lenta]; lenbb = length(n_bits_b); lenpb = length(bin_pt_b); lentb = length(type_b); b = [lenbb, lenpb, lentb]; lenbo = length(n_bits_out); lenpo = length(bin_pt_out); lento = length(type_out); lenm = length(opmode); lenq = length(quantization); leno = length(overflow); o = [lenbo, lenpo, lento, lenm, lenq, leno]; comps = unique([a, b, o]); %if have more than 2 unique components or have two but one isn't 1 if ((length(comps) > 2) | (length(comps) == 2 && comps(1) ~= 1)), clog('conflicting component sizes',{'bus_addsub_init_debug', 'error'}); return; end %determine number of components from clues compa = max(a); compb = max(b); compo = max(o); comp = max(compa, compb); %need to specify at least one set of input components if compo > comp, clog('more output components than inputs',{'bus_addsub_init_debug','error'}); return; end %replicate items if needed for a input n_bits_a = repmat(n_bits_a, 1, compa/lenba); bin_pt_a = repmat(bin_pt_a, 1, compa/lenpa); type_a = repmat(type_a, 1, compa/lenta); %replicate items if needed for b input n_bits_b = repmat(n_bits_b, 1, compb/lenbb); bin_pt_b = repmat(bin_pt_b, 1, compb/lenpb); type_b = repmat(type_b, 1, compb/lentb); %need to pad output if need more than one n_bits_out = repmat(n_bits_out, 1, comp/lenbo); bin_pt_out = repmat(bin_pt_out, 1, comp/lenpo); type_o = repmat(type_out, 1, comp/lento); overflow = repmat(overflow, 1, comp/leno); opmode = repmat(opmode, 1, comp/lenm); quantization = repmat(quantization, 1, comp/leno); %if complex we need to double down on some of these if strcmp(cmplx, 'on'), compa = compa*2; n_bits_a = reshape([n_bits_a; n_bits_a], 1, compa); bin_pt_a = reshape([bin_pt_a; bin_pt_a], 1, compa); type_a = reshape([type_a; type_a], 1, compa); compb = compb*2; n_bits_b = reshape([n_bits_b; n_bits_b], 1, compb); bin_pt_b = reshape([bin_pt_b; bin_pt_b], 1, compb); type_b = reshape([type_b; type_b], 1, compb); comp = comp*2; n_bits_out = reshape([n_bits_out; n_bits_out], 1, comp); bin_pt_out = reshape([bin_pt_out; bin_pt_out], 1, comp); type_o = reshape([type_o; type_o], 1, comp); overflow = reshape([overflow; overflow], 1, comp); opmode = reshape([opmode; opmode], 1, comp); quantization = reshape([quantization; quantization], 1, comp); end %input ports ypos_tmp = ypos + add_d*compa/2; reuse_block(blk, 'a', 'built-in/inport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + add_d*(compa/2 + compb/2); reuse_block(blk, 'b', 'built-in/inport', ... 'Port', '2', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); ypos_tmp = ypos_tmp + yinc + add_d*compb/2; port_no = 3; if strcmp(misc, 'on'), reuse_block(blk, 'misci', 'built-in/inport', ... 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); port_no = port_no+1; end ypos_tmp = ypos_tmp + yinc; xpos = xpos + xinc + port_w/2; if strcmp(async, 'on'), xpos = xpos + xinc + port_w/2; reuse_block(blk, 'en', 'built-in/inport', ... 'Port', num2str(port_no), 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); end % bus expand ypos_tmp = ypos + add_d*compa/2; %reset ypos reuse_block(blk, 'a_debus', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', ... 'outputWidth', ['[',num2str(n_bits_a),']'], ... 'outputBinaryPt', ['[',num2str(bin_pt_a),']'], ... 'outputArithmeticType', ['[',num2str(type_a),']'], ... 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-add_d*compa/2 xpos+bus_expand_w/2 ypos_tmp+add_d*compa/2]); add_line(blk, 'a/1', 'a_debus/1'); ypos_tmp = ypos_tmp + add_d*(compa/2+compb/2) + yinc; reuse_block(blk, 'b_debus', 'casper_library_flow_control/bus_expand', ... 'mode', 'divisions of arbitrary size', ... 'outputWidth', ['[',num2str(n_bits_b),']'], ... 'outputBinaryPt', ['[',num2str(bin_pt_b),']'], ... 'outputArithmeticType', ['[',num2str(type_b),']'], ... 'show_format', 'on', 'outputToWorkspace', 'off', ... 'variablePrefix', '', 'outputToModelAsWell', 'on', ... 'Position', [xpos-bus_expand_w/2 ypos_tmp-add_d*compb/2 xpos+bus_expand_w/2 ypos_tmp+add_d*compb/2]); add_line(blk, 'b/1', 'b_debus/1'); ypos_tmp = ypos_tmp + add_d*compa + yinc; %addsub xpos = xpos + xinc + add_w/2; ypos_tmp = ypos; %reset ypos %need addsub per component a_src = repmat([1:compa], 1, comp/compa); b_src = repmat([1:compb], 1, comp/compb); clog(['making ',num2str(comp),' AddSubs'],{'bus_addsub_init_debug'}); for index = 1:comp switch type_o(index), case 0, arith_type = 'Unsigned'; case 1, arith_type = 'Signed'; end switch quantization(index), case 0, quant = 'Truncate'; case 1, quant = 'Round (unbiased: +/- Inf)'; end switch overflow(index), case 0, of = 'Wrap'; case 1, of = 'Saturate'; case 2, of = 'Flag as error'; end switch opmode(index), case 0, m = 'Addition'; symbol = '+'; case 1, m = 'Subtraction'; symbol = '-'; end clog(['output ',num2str(index),': ', ... ' a[',num2str(a_src(index)),'] ',symbol,' b[',num2str(b_src(index)),'] = ', ... '(',num2str(n_bits_out(index)), ' ', num2str(bin_pt_out(index)),') ' ... ,arith_type,' ',quant,' ', of], ... {'bus_addsub_init_debug'}); if strcmp(add_implementation, 'behavioral HDL'), use_behavioral_HDL = 'on'; hw_selection = 'Fabric'; elseif strcmp(add_implementation, 'fabric core'), use_behavioral_HDL = 'off'; hw_selection = 'Fabric'; elseif strcmp(add_implementation, 'DSP48 core'), use_behavioral_HDL = 'off'; hw_selection = 'DSP48'; end add_name = ['addsub',num2str(index)]; reuse_block(blk, add_name, 'xbsIndex_r4/AddSub', ... 'mode', m, 'latency', num2str(latency), ... 'en', async, 'precision', 'User Defined', ... 'n_bits', num2str(n_bits_out(index)), 'bin_pt', num2str(bin_pt_out(index)), ... 'arith_type', arith_type, 'quantization', quant, 'overflow', of, ... 'pipelined', 'on', 'use_behavioral_HDL', use_behavioral_HDL, 'hw_selection', hw_selection, ... 'Position', [xpos-add_w/2 ypos_tmp xpos+add_w/2 ypos_tmp+add_d-20]); ypos_tmp = ypos_tmp + add_d; add_line(blk, ['a_debus/',num2str(a_src(index))], [add_name,'/1']); add_line(blk, ['b_debus/',num2str(b_src(index))], [add_name,'/2']); if strcmp(async, 'on') add_line(blk, 'en/1', [add_name,'/3']); end end %for ypos_tmp = ypos + add_d*(compb+compa) + 2*yinc; if strcmp(misc, 'on'), reuse_block(blk, 'dmisc', 'xbsIndex_r4/Delay', ... 'latency', num2str(latency), ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); add_line(blk, 'misci/1', 'dmisc/1'); end ypos_tmp = ypos_tmp + yinc; if strcmp(async, 'on'), reuse_block(blk, 'den', 'xbsIndex_r4/Delay', ... 'latency', num2str(latency), ... 'Position', [xpos-del_w/2 ypos_tmp-del_d/2 xpos+del_w/2 ypos_tmp+del_d/2]); add_line(blk, 'en/1', 'den/1'); end xpos = xpos + xinc + add_d/2; %bus create ypos_tmp = ypos + add_d*comp/2; %reset ypos reuse_block(blk, 'op_bussify', 'casper_library_flow_control/bus_create', ... 'inputNum', num2str(comp), ... 'Position', [xpos-bus_create_w/2 ypos_tmp-add_d*comp/2 xpos+bus_create_w/2 ypos_tmp+add_d*comp/2]); for index = 1:comp, add_line(blk, ['addsub',num2str(index),'/1'], ['op_bussify/',num2str(index)]); end %output port/s ypos_tmp = ypos + add_d*comp/2; xpos = xpos + xinc + bus_create_w/2; reuse_block(blk, 'dout', 'built-in/outport', ... 'Port', '1', 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, ['op_bussify/1'], ['dout/1']); ypos_tmp = ypos_tmp + yinc + port_d; ypos_tmp = ypos + add_d*(compb+compa) + 2*yinc; port_no = 2; if strcmp(misc, 'on'), reuse_block(blk, 'misco', 'built-in/outport', ... 'Port', num2str(port_no), ... 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, 'dmisc/1', 'misco/1'); port_no = port_no+1; end ypos_tmp = ypos_tmp + yinc; if strcmp(async, 'on'), reuse_block(blk, 'dvalid', 'built-in/outport', ... 'Port', num2str(port_no), ... 'Position', [xpos-port_w/2 ypos_tmp-port_d/2 xpos+port_w/2 ypos_tmp+port_d/2]); add_line(blk, 'den/1', 'dvalid/1'); end % When finished drawing blocks and lines, remove all unused blocks. clean_blocks(blk); save_state(blk, 'defaults', defaults, varargin{:}); % Save and back-populate mask parameter values clog('exiting bus_addsub_init', {'bus_addsub_init_debug', 'trace'}); end %function bus_addsub_init
github
mstrader/mlib_devel-master
dump_and_rethrow.m
.m
mlib_devel-master/casper_library/dump_and_rethrow.m
1,710
utf_8
ef2f9cadf917f9417f31f10faeea525b
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2013 David MacMahon % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function dump_and_rethrow(ex) dump_exception(ex); rethrow(ex); end
github
mstrader/mlib_devel-master
dump_exception.m
.m
mlib_devel-master/casper_library/dump_exception.m
2,194
utf_8
04c5177f30c57e32a81eea872633101f
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % Center for Astronomy Signal Processing and Electronics Research % % http://seti.ssl.berkeley.edu/casper/ % % Copyright (C) 2013 David MacMahon % % % 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function dump_exception(ex) persistent last_dumped; % An empty ex means to clear last_dumped if isempty(ex) last_dumped = []; % Do not re-dump ex if it has already been dumped elseif ~isa(last_dumped, 'MException') || last_dumped ~= ex last_dumped = ex; fprintf('%s: %s\n', ex.identifier, ex.message); stack = ex.stack; for k=1:length(stack) fprintf('Backtrace %d: <a href="matlab: opentoline(''%s'',%d,0)">%s:%d</a>\n', ... k, stack(k).file, stack(k).line, stack(k).name, stack(k).line); end end end