You are on page 1of 480

JuliaPro v0.6.2.

1 API Manual

December 19, 2017

Julia Computing Inc.
info@juliacomputing.com

Contents

1 Distributions 1

2 StatsBase 46

3 QuantEcon 80

4 PyPlot 125

5 IndexedTables 152

6 Images 180

7 DataFrames 195

8 JDBC 209

9 NNlib 220

10 ImageCore 226

11 Reactive 235

12 Knet 242

13 Combinatorics 250

14 DataStructures 256

15 CategoricalArrays 264

16 HypothesisTests 270

17 DataArrays 276

18 GLM 284

19 Documenter 290

I

II CONTENTS

20 ColorTypes 295

21 Primes 300

22 ImageTransformations 306

23 Roots 310

24 PyCall 315

25 Gadfly 320

26 IterTools 325

27 Iterators 333

28 Polynomials 341

29 Colors 345

30 FileIO 349

31 Interact 353

32 FFTW 357

33 AxisArrays 361

34 QuadGK 365

35 JavaCall 368

36 Dagger 372

37 Interpolations 375

38 ShowItLikeYouBuildIt 377

39 CoordinateTransformations 380

40 Graphics 382

41 BusinessDays 385

42 OnlineStats 388

43 MacroTools 391

44 ImageMorphology 394

CONTENTS III

45 Contour 396

46 Compose 398

47 CoupledFields 401

48 AxisAlgorithms 403

49 Libz 405

50 NullableArrays 408

51 ImageMetadata 410

52 LegacyStrings 412

53 BufferedStreams 414

54 MbedTLS 416

55 DataValues 418

56 NearestNeighbors 420

57 IJulia 421

58 WebSockets 423

59 AutoGrad 425

60 ComputationalResources 427

61 Clustering 429

62 JuliaWebAPI 431

63 DecisionTree 433

64 Blosc 435

65 Parameters 437

66 HDF5 439

67 HttpServer 441

68 MappedArrays 443

69 TextParse 444

IV CONTENTS

70 LossFunctions 446

71 LearnBase 447

72 Juno 449

73 HttpParser 451

74 ImageAxes 452

75 IntervalSets 453

76 Media 454

77 Rotations 455

78 Mustache 456

79 TiledIteration 457

80 Distances 458

81 HttpCommon 459

82 StaticArrays 460

83 SweepOperator 461

84 NLSolversBase 462

85 PaddedViews 463

86 Flux 464

87 SpecialFunctions 465

88 NamedTuples 466

89 Loess 467

90 Nulls 468

91 WoodburyMatrices 469

92 Requests 470

93 MemPool 471

94 SimpleTraits 472

CONTENTS V

95 BinDeps 473

VI CONTENTS

Chapter 1

Distributions

1.1 Base.LinAlg.scale!
Base.LinAlg.scale! — Method.

scale!{D<:AbstractMvLogNormal}(::Type{D},s::Symbol,m::AbstractVector,S::AbstractMatrix,::Abstract

Calculate the scale parameter, as defined for the location parameter above
and store the result in .
source

1.2 Base.mean
Base.mean — Method.

mean(d::Union{UnivariateMixture, MultivariateMixture})

Compute the overall mean (expectation).
source

1.3 Base.mean
Base.mean — Method.

mean(d::MatrixDistribution)

Return the mean matrix of d.
source

1

2 CHAPTER 1. DISTRIBUTIONS

1.4 Base.mean
Base.mean — Method.

mean(d::MultivariateDistribution)

Compute the mean vector of distribution d.
source

1.5 Base.mean
Base.mean — Method.

mean(d::UnivariateDistribution)

Compute the expectation.
source

1.6 Base.median
Base.median — Method.

median(d::UnivariateDistribution)

Return the median value of distribution d.
source

1.7 Base.median
Base.median — Method.

median(d::MvLogNormal)

Return the median vector of the lognormal distribution. which is strictly
smaller than the mean.
source

1.8 Base.quantile
Base.quantile — Method.

quantile(d::UnivariateDistribution, q::Real)

Evaluate the inverse cumulative distribution function at q.
See also: cquantile, invlogcdf, and invlogccdf.
source

TruncatedNormal(mu. std. var(d::UnivariateMixture) Compute the overall variance (only for U nivariateM ixture).var — Method. var(d::UnivariateDistribution) Compute the variance. source 1. source 1. sigma).var Base.TruncatedNormal Distributions. std(d::UnivariateDistribution) Return the standard deviation of distribution d. sigma. mode. source 1.std — Method.12 Base. We provide additional support for this type with TruncatedNormal which calls Truncated(Normal(mu.10 Base. u). truncated normal distributions support mean.var — Method. var(d::MultivariateDistribution) Compute the vector of element-wise variances for distribution d.TruncatedNormal — Method.13 Distributions. source .var Base.var Base. i.var — Method.11 Base.9. sqrt(var(d)). l. var.e. Unlike the general case. and entropy.9 Base. l.std Base. (A generic std is provided as std(d) = sqrt(var(d))) source 1. u) The truncated normal distribution is a particularly important one in the fam- ily of truncated distributions. BASE.1. modes.STD 3 1.

i.cquantile Distributions.cdf(d. See also ccdf.17 Distributions. quantile(d. 1 .18 Distributions. cf(d::UnivariateDistribution. and logccdf.e. components(d::AbstractMixtureModel) Get a list of components of the mixture model d. t) Evaluate the characteristic function of distribution d. x). cdf(d::UnivariateDistribution. x::Real) Evaluate the cumulative probability at x. x::Real) The complementary cumulative function evaluated at x.cf Distributions. logcdf. DISTRIBUTIONS 1.15 Distributions. source 1.cdf — Method. source . source 1.4 CHAPTER 1.cquantile — Method. ccdf(d::UnivariateDistribution.cf — Method.components — Method.16 Distributions. source 1. 1-q).e. source 1.cdf Distributions.ccdf Distributions.components Distributions. cquantile(d::UnivariateDistribution. i.ccdf — Method. q::Real) The complementary quantile value.14 Distributions.

19 Distributions.21 Distributions.fit mle — Method. with weights given by w. fit_mle(D. DISTRIBUTIONS. x.20 Distributions. where each column is a sample. • For multivariate distribution. where n is the number of samples contained in x.insupport — Method. w should be an array with length n. x) Fit a distribution of type D to a given data set x. x) Evaluate whether x is within the support of mixture distribution d.1.failprob — Method. source 1.insupport Distributions.FAILPROB 5 1. source 1. source 1.failprob Distributions. source . x should be a matrix.fit mle — Method. fit_mle(D. failprob(d::UnivariateDistribution) Get the probability of failure.19. w) Fit a distribution of type D to a weighted data set x.fit mle Distributions.22 Distributions. • For univariate distribution.fit mle Distributions. insupport(d::MultivariateMixture. Here. x can be an array of arbitrary size.

invcov(d::AbstractMvNormal) Return the inversed covariance matrix of d. When x is an array. it returns whether x is within the support of d (e. If x is a matrix. DISTRIBUTIONS 1. x) = minimum(d) <= x <= maximum(d)).invlogccdf Distributions.25 Distributions.6 CHAPTER 1. x::AbstractArray) If x is a vector. and a specialized insupport is thus desirable. invlogcdf(d::UnivariateDistribution. it returns whether every element in x is within the support of d. source 1. source . it returns whether x is within the support of d.invlogccdf — Method.g. Generic fallback methods are provided.24 Distributions. You should also override this function if the support is composed of multiple disjoint intervals. insupport(d::MultivariateDistribution. x::Any) When x is a scalar.invcov Distributions.insupport — Method.invcov — Method.23 Distributions. lp::Real) The inverse function of logcdf.insupport Distributions. insupport(d::UnivariateDistribution. it returns whether every column in x is within the support of d.insupport Distributions.26 Distributions. source 1.. insupport(d. source 1.insupport — Method. but it is often the case that insupport can be done more efficiently.

invlogcdf Distributions.ismesokurtic Distributions.ismesokurtic — Method. lp::Real) The inverse function of logcdf.isleptokurtic Distributions.location! — Method. isplatykurtic(d) Return whether d is platykurtic (i. ismesokurtic(d) Return whether d is mesokurtic (i. source 1.31 Distributions. location!{D<:AbstractMvLogNormal}(::Type{D}.invlogcdf — Method.S::AbstractMatrix. invlogcdf(d::UnivariateDistribution.INVLOGCDF 7 1.e kurtosis(d) == 0).28 Distributions.e kurtosis(d) < 0).m::AbstractVector.isplatykurtic — Method. source 1.27 Distributions.isleptokurtic — Method. DISTRIBUTIONS.30 Distributions.isplatykurtic Distributions.location! Distributions.::Abstr Calculate the location vector (as above) and store the result in source .s::Symbol.e kurtosis(d) > 0). source 1. source 1.1.27. isleptokurtic(d) Return whether d is leptokurtic (i.29 Distributions.

source .logccdf — Method.8 CHAPTER 1. source 1. me- dian + covariance. location(d::UnivariateDistribution) Get the location parameter.location Distributions. DISTRIBUTIONS 1.32 Distributions. i.location — Method.m::AbstractVector.location — Method.33 Distributions. location{D<:AbstractMvLogNormal}(::Type{D}. logccdf(d::UnivariateDistribution. then m is taken as the mean.S::AbstractMatri Calculate the location vector (the mean of the underlying normal distribu- tion). source 1. and S is interpreted as the scale matrix (the covariance of the underlying normal distribution). • If s == :mean | :median | :mode. source 1.g. • If s == :meancov. then m is taken as the mean. location(d::MvLogNormal) Return the location vector of the distribution (the mean of the underlying normal distribution). and S the covariance matrix of a lognormal distribution.34 Distributions.logccdf Distributions. or from mode + covariance.location Distributions. It is not possible to analytically calculate the location vector from e.e.35 Distributions.location Distributions.location — Method. x::Real) The logarithm of the complementary cumulative function values evaluated at x. log(ccdf(x)).s::Symbol.. median or mode of the lognormal respectively.

x can be a single sample or an array of multiple samples. x::AbstractArray) Return the logarithm of probability density evaluated at x. source .38 Distributions. MultivariateMixture}. logpdf(d::MultivariateDistribution. source 1. i. where r[i] corresponds to x[:. log(cdf(x)). source 1.logcdf — Method.logpdf Distributions.36 Distributions. logpdf(d::Union{UnivariateMixture. x) Evaluate the logarithm of the (mixed) probability density function over x. • If x is a matrix with n columns.39 Distributions. x) will write the results to a pre-allocated array r. it returns the result as a scalar. Here.logcdf Distributions.logdetcov Distributions. • If x is a vector. logdetcov(d::AbstractMvNormal) Return the log-determinant value of the covariance matrix.LOGCDF 9 1. DISTRIBUTIONS.e. logpdf!(r. d.logpdf — Method. it returns a vector r of length n. source 1.36. x::Real) The logarithm of the cumulative function value(s) evaluated at x.logpdf Distributions.logpdf — Method.37 Distributions.1.i]. logcdf(d::UnivariateDistribution.logdetcov — Method.

source 1.ncategories Distributions.mgf — Method. x::Real) Evaluate the logarithm of probability density (mass) at x. AbstractMatrix) Compute the logarithm of the probability density at the input matrix x.nsamples — Method. Relying on this fallback is not recommended in general.ncategories — Method.42 Distributions.43 Distributions.logpdf — Method. as it is prone to overflow or underflow. source .10 CHAPTER 1.logpdf — Method. logpdf(d::MatrixDistribution. mgf(d::UnivariateDistribution.41 Distributions.nsamples Distributions. source 1. ncategories(d::UnivariateDistribution) Get the number of categories. source 1. x)). x) = log(pdf(d. logpdf(d::UnivariateDistribution.40 Distributions.logpdf Distributions.logpdf Distributions. source 1. t) Evaluate the moment generating function of distribution d. depending on the variate form.mgf Distributions.44 Distributions. DISTRIBUTIONS 1. nsamples(s::Sampleable) The number of samples contained in A. Whereas there is a fallback implemented logpdf(d. Multiple samples are often organized into an array.

where r[i] corresponds to x[:. Here.NTRIALS 11 1. source . it returns the result as a scalar. d. x::AbstractArray) Return the probability density of distribution d evaluated at x.45.46 Distributions. pdf(d::MultivariateDistribution. x) will write the results to a pre-allocated array r.pdf — Method.1.ntrials — Method.pdf Distributions. x::Real) Evaluate the probability density (mass) at x.e. DISTRIBUTIONS. • If x is a vector. See also: logpdf. treating each column as a sample). it returns a vector r of length n. source 1.pdf Distributions. x can be a single sample or an array of multiple samples.pdf — Method.45 Distributions. x) Evaluate the (mixed) probability density function over x.i] (i.ntrials Distributions. pdf!(r. source 1. pdf(d::Union{UnivariateMixture. • If x is a matrix with n columns. ntrials(d::UnivariateDistribution) Get the number of trials.47 Distributions. pdf(d::UnivariateDistribution.48 Distributions. MultivariateMixture}. source 1.pdf Distributions.pdf — Method.

The general fallback is sampler(d::Distribution) = d.52 Distributions. probs(d::AbstractMixtureModel) Get the vector of prior probabilities of all components of d.51 Distributions. which would be used for batch sampling.probs Distributions.sampler — Method.rate Distributions.50 Distributions. DISTRIBUTIONS 1.scale Distributions.pdf — Method.12 CHAPTER 1. source 1.scale — Method. rate(d::UnivariateDistribution) Get the rate parameter.rate — Method.probs — Method.53 Distributions.49 Distributions. source 1. source 1. scale(d::UnivariateDistribution) Get the scale parameter. source . sampler(d::Distribution) -> Sampleable Samplers can often rely on pre-computed quantities (that are not parameters themselves) to improve efficiency. source 1. If such a sampler exists. x::AbstractArray) Compute the probability density at the input matrix x. pdf(d::MatrixDistribution. it can be provide with this sampler method.pdf Distributions.sampler Distributions.

55 Distributions. as defined for the location parameter above.57 Distributions. the covariance. it returns a scalar value. succprob(d::UnivariateDistribution) Get the probability of success.2). When x is a vector.SCALE 13 1. x) with write the results to a pre-allocated array r.56 Distributions.s::Symbol. When x is a matrix. source . w.shape — Method.m::AbstractVector. scale(d::MvLogNormal) Return the scale matrix of the distribution (the covariance matrix of the underlying normal distribution). source 1. source 1.shape Distributions. sqmahal!(r.58 Distributions.succprob Distributions.54 Distributions.54. shape(d::UnivariateDistribution) Get the shape parameter. it returns a vector of length size(x.sqmahal — Method.t.1. DISTRIBUTIONS.sqmahal Distributions.scale — Method.succprob — Method.scale Distributions. source 1. x) Return the squared Mahalanobis distance from x to the center of d. d. sqmahal(d.scale — Method.S::AbstractMatrix) Calculate the scale parameter.scale Distributions.r. scale{D<:AbstractMvLogNormal}(::Type{D}. source 1.

entropy StatsBase. dof(d::UnivariateDistribution) Get the degrees of freedom.entropy — Method.entropy — Method. entropy(d::MultivariateDistribution.entropy StatsBase.dof StatsBase. entropy(d::MultivariateDistribution) Compute the entropy value of distribution d.59 StatsBase. source 1.entropy StatsBase.t. w. entropy(d::UnivariateDistribution) Compute the entropy value of distribution d. source 1.63 StatsBase. DISTRIBUTIONS 1. source .14 CHAPTER 1.t.entropy StatsBase.r. a given base. source 1.60 StatsBase.61 StatsBase. w. a given base.dof — Method. source 1. b::Real) Compute the entropy value of distribution d.entropy — Method.entropy — Method.r.62 StatsBase. entropy(d::UnivariateDistribution. b::Real) Compute the entropy value of distribution d.

KURTOSIS 15 1.loglikelihood — Method.loglikelihood StatsBase.64. source 1. source 1. correction::Bool) Computes excess kurtosis by default. loglikelihood(d::UnivariateDistribution.kurtosis StatsBase. X::AbstractArray) The log-likelihood of distribution d w. kurtosis(d::Distribution.kurtosis — Method.67 StatsBase. all columns contained in matrix x.kurtosis — Method. loglikelihood(d::MultivariateDistribution.65 StatsBase.66 StatsBase. STATSBASE.t.loglikelihood — Method. source .1.r. kurtosis(d::UnivariateDistribution) Compute the excessive kurtosis.t. x::AbstractMatrix) The log-likelihood of distribution d w.mode — Method. all samples contained in array x.mode StatsBase. Proper kurtosis can be returned with correction=false source 1.loglikelihood StatsBase.64 StatsBase. mode(d::UnivariateDistribution) Returns the first mode.kurtosis StatsBase. source 1.68 StatsBase.r.

DISTRIBUTIONS 1. modes(d::UnivariateDistribution) Get all modes (if this makes sense).mode StatsBase.m::AbstractVector.params! — Method. source 1. mode(d::MvLogNormal) Return the mode vector of the lognormal distribution.16 CHAPTER 1.70 StatsBase.S::AbstractMatrix) Return (scale.mode — Method.location) for a given mean and covariance source .73 StatsBase.69 StatsBase.::Abstrac Calculate (scale. and store the results in and source 1. which is strictly smaller than the mean and median. then D(params(d). source 1.params — Method.) will construct exactly the same distribution as d. params!{D<:AbstractMvLogNormal}(::Type{D}.params StatsBase. Let d be a distribution of type D.params StatsBase. params(d::UnivariateDistribution) Return a tuple of parameters..modes StatsBase.71 StatsBase.m::AbstractVector..modes — Method.params — Method.S::AbstractMatrix.72 StatsBase.params! StatsBase. source 1. params{D<:AbstractMvLogNormal}(::Type{D}.location) for a given mean and covariance.

and ScalMat for the isotropic covariance – those in the form of σI.SKEWNESS 17 1. Vector{Float64}} const DiagNor- mal = MvNormal{PDiagMat. ZeroVector{Float64}} source . We also define a set of alias for the types using different combinations of mean vectors and covariance: [] const IsoNormal = MvNormal{ScalMat. ZeroVector{Float64}} const ZeroMeanDiagNormal = MvNormal{PDiagMat. which allows users to specify the special structure of the mean and covariance. skewness(d::UnivariateDistribution) Compute the skewness.74 StatsBase. the mean vector is sometimes just a zero vector. the mean vector can be an instance of either Vector or ZeroVector. defined as below. The Multivariate normal distribution is a multidimensional generalization of the normal distribution.1. PDiagMat for diagonal covariance. we introduce a parametric type MvNormal.AbstractMvNormal — Type.AbstractMvNormal Distributions. STATSBASE. ZeroVector{Float64}} const ZeroMeanFullNormal = MvNormal{PDMat. (See the Julia package PDMats for details).skewness — Method. Vector{Float64}} const ZeroMeanIsoNormal = MvNormal{ScalMat.Mean¡:Union{Vector. Σ) = exp − (x − µ)T Σ−1 (x − µ) (2π)d/2 |Σ|1/2 2 We realize that the mean vector and the covariance often have special forms in practice. Particularly.74. For example. The probability density function of a d-dimensional multivariate normal distribution with mean vector µ and covariance matrix Σ is:   1 1 f (x. The covariance can be of any subtype of AbstractPDMat.skewness StatsBase. while the covariance matrix can be a diagonal matrix or even in the form of σI. source 1.75 Distributions. where the latter is simply an empty type indicating a vector filled with zeros. To take advantage of such special cases. µ. one can use PDMat for full covariance. Vector{Float64}} const FullNormal = MvNor- mal{PDMat. which can be exploited to simplify the computation. [] immutable MvNormal{Cov¡:AbstractPDMat.ZeroVector}} ¡: AbstractMvNormal ::Mean ::Cov end Here.

b] params(d) Get the parameters.e. i. x ∈ [a. i. p failprob(d) Get the failure rate.5 Bernoulli(p) Bernoulli distribution with success rate p params(d) Get the parameters.76 Distributions. b .e. b location(d) Get the left bound.b) The Arcsine distribution has probability density function 1 f (x) = p . b] π (x − a)(b − x) [] Arcsine() Arcsine distribution with support [0. i.e. a maximum(d) Get the upper bound.p External links: • Bernoulli distribution on Wikipedia source . a scale(d) Get the span of the support.77 Distributions.a External links • Arcsine distribution on Wikipedia source 1. DISTRIBUTIONS 1. ( 1−p for k = 0. Arcsine(a. P (X = k) = p for k = 1.e. Bernoulli(p) A Bernoulli distribution is parameterized by a success rate p. (a.e. b] Arcsine(a.e. b) Arcsine distribution with support [a.e. i. i.e. (p. i.Arcsine — Type. which takes value 1 with probability p and 0 with probability 1-p. [] Bernoulli() Bernoulli distribution with p = 0. 1] Arcsine(b) Arcsine distribution with support [0. b) minimum(d) Get the lower bound.18 CHAPTER 1.Bernoulli — Type.) succprob(d) Get the success rate. 1 .Arcsine Distributions.Bernoulli Distributions. i. i.

the number of trials and two shape parameters . β). Beta(. b) External links • Beta distribution on Wikipedia source 1. for k = 0. (a. a.e. (n. i. DISTRIBUTIONS. i. β) The Beta distribution is related to the Gamma distribution via the property that if X ∼ Gamma(α) and Y ∼ Gamma(β) independently.   n P (X = k) = B(k + α. a) Beta(a. β). a. .. n. α.78 Distributions.Beta Distributions. 1) Beta(a) equivalent to Beta(a. x ∈ [0. n − k + β)/B(α. b) Beta distribution with shape parameters a and b params(d) Get the parameters. . 1] B(α. b) ntrials(d) Get the number of trials. then X/(X + Y ) ∼ Beta(α.BETA 19 1.1. b params(d) Get the parameters.78. b) BetaBinomial distribution with n trials and shape parameters a.79 Distributions. BetaBinomial(n.BetaBinomial Distributions.BetaBinomial — Type. i. . . n External links: • Beta-binomial distribution on Wikipedia source .e. It has three parameters: n. β) = xα−1 (1 − x)β−1 . 2.e. 1.) The Beta distribution has probability density function 1 f (x. [] Beta() equivalent to Beta(1. k [] BetaBinomial(n.) A Beta-binomial distribution is the compound distribution of the Binomial distribution where the probability of success p is distributed according to the Beta.Beta — Type.

i. 2. DISTRIBUTIONS 1. (n. the probability of success in an individual trial.Binomial Distributions. b) External links • Beta prime distribution on Wikipedia source 1. α. and p.p) A Binomial distribution characterizes the number of successes in a sequence of independent trials.) The Beta prime distribution has probability density function 1 f (x. β) = xα−1 (1 + x)−(α+β) . n succprob(d) Get the success rate. It has two parameters: n. 1) BetaPrime(a) equivalent to BetaPrime(a.5 Binomial(n. 1 . p) Binomial distribution for n trials with success rate p params(d) Get the parameters. p failprob(d) Get the failure rate. i.e. β) then 1−X ∼ BetaPrime(α.e. i. . b) Beta prime distribution with shape parame- ters a and b params(d) Get the parameters.Binomial — Type.81 Distributions.BetaPrime Distributions.e. for k = 0. BetaPrime(.20 CHAPTER 1. i.e. p) ntrials(d) Get the number of trials. β) [] BetaPrime() equivalent to BetaPrime(1. .BetaPrime — Type.e. . a) BetaPrime(a. k [] Binomial() Binomial distribution with n = 1 and p = 0. . n. 1. (a.5 Binomial(n) Binomial distribution for n trials with success rate p = 0. β) The Beta prime distribution is related to the Beta distribution via the rela- X tion ship that if X ∼ Beta(α. i. with the distribution:   n k P (X = k) = p (1 − p)n−k . Binomial(n.80 Distributions. x>0 B(α. the number of trials.p External links: • Binomial distribution on Wikipedia source .

P (X = k) = p[k] for k = 1.Cauchy — Type.82.e. K. . p ncate- gories(d) Get the number of categories.BIWEIGHT 21 1.82 Distributions. p must be a real vector.e.Categorical — Type. 1) Cauchy(u.84 Distributions. Biweight(. without being copied. . i. b External links • Cauchy distribution on Wikipedia source .e. b) location(d) Get the location parameter. i. i. External links: • Categorical distribution on Wikipedia source 1. .Biweight Distributions. [] Categorical(p) Categorical distribution with probability vector p params(d) Get the parameters. i.Cauchy Distributions.e. 1) Cauchy(u) Cauchy distribution with location u and unit scale. Cauchy(0. Cauchy(. of which all components are nonnegative and sum to one. i.e.1. b) Cauchy distribution with location u and scale b params(d) Get the parameters. Categorical(p) A Categorical distribution is parameterized by a probability vector p (of length K).e. i. ) source 1. (u.e. µ. σ) =   x−µ 2  πσ 1 + σ [] Cauchy() Standard Cauchy distribution. K Here.Categorical Distributions.e.) probs(d) Get the probability vector. (p. DISTRIBUTIONS.83 Distributions.Biweight — Type. ) The Cauchy distribution with location and scale has probability density function 1 f (x. . i. Note: The input vector p is directly used as a field of the constructed distribution. 2. u scale(d) Get the scale parameter. i. Cauchy(u.

Chisq() The Chi squared distribution (typically written ) with degrees of freedom has the probability density function xk/2−1 e−x/2 f (x.) dof(d) Get the degrees of freedom. i. DISTRIBUTIONS 1.22 CHAPTER 1. 2k/2 Γ(k/2) If is an integer. then it is the distribution of the sum of squares of inde- pendent standard Normal variates.) dof(d) Get the degrees of freedom.Chi — Type.Chi Distributions. (k. i.e. i.e. (k.85 Distributions.Chisq — Type. k) = 21−k/2 xk−1 e−x /2 .Chisq Distributions. x > 0. k External links • Chi distribution on Wikipedia source 1.86 Distributions. [] Chi(k) Chi distribution with k degrees of freedom params(d) Get the parameters.e. i. Chi() The Chi distribution degrees of freedom has probability density function 1 2 f (x. k) = .e. k External links • Chi-squared distribution on Wikipedia source . x>0 Γ(k/2) It is the distribution of the square-root of a Chisq variate. [] Chisq(k) Chi-squared distribution with k degrees of freedom params(d) Get the parameters.

DiscreteUniform Distributions. [] DiscreteUniform(a.COSINE 23 1.1. . a+1. b) a uniform distribution over {a. . . DISTRIBUTIONS. b. . x1 + · · · + xk = 1 B(α) i=1 i Γ Pk α i=1 i [] Let alpha be a vector Dirichlet(alpha) Dirichlet distribution with param- eter vector alpha Let a be a positive scalar Dirichlet(k.87 Distributions.DiscreteUniform — Type. a) Dirichlet distribution with param- eter a * ones(k) source 1. . Cosine(.89 Distributions.88 Distributions. i. i. ) A raised Cosine distribution.Cosine Distributions.87. a + 1..a + 1) minimum(d) Return a maximum(d) Return b External links ... αk ) is: k Qk 1 Y αi −1 Γ(αi ) f (x.b) A Discrete uniform distribution is a uniform distribution over a consecutive sequence of integers between a and b.a + 1) probval(d) Get the probability value. (b . inclusive.e.e. External link: • Cosine distribution on wikipedia source 1.Dirichlet Distributions. . . . b} params(d) Get the parameters. P (X = k) = 1/(b − a + 1) for k = a. . α) = x . Dirichlet The Dirichlet distribution is often used the conjugate prior for Categorical or Multinomial distributions. with B(α) = i=1 . DiscreteUniform(a. i. 1 / (b .Dirichlet — Type.Cosine — Type. (a. b) span(d) Get the span of the support. The probability density function of a Dirichlet distribution with parameter α = (α1 .e.

x > 0 θ [] Exponential() Exponential distribution with unit scale. i.90 Distributions. [] Erlang() Erlang distribution with unit shape and unit scale.91 Distributions.e.Exponential Distributions. Epanechnikov(.Epanechnikov Distributions. i.Epanechnikov — Type. Erlang(a. Erlang(1.Exponential — Type. 1) Erlang(a) Erlang distribution with shape parameter a and unit scale. i.) scale(d) Get the scale parameter.e.24 CHAPTER 1.e. θ) = e θ.) The Erlang distribution is a special case of a Gamma distribution with integer shape parameter.e. DISTRIBUTIONS • Discrete uniform distribution on Wikipedia source 1. 1 / b External links • Exponential distribution on Wikipedia source . i. (b. 1) Erlang(a.Erlang — Type. i.e. s) Erlang distribution with shape parameter a and scale b External links • Erlang distribution on Wikipedia source 1. b rate(d) Get the rate parameter. ) source 1.92 Distributions. Exponen- tial(1) Exponential(b) Exponential distribution with scale b params(d) Get the parameters. i.e.Erlang Distributions. Erlang(. Exponential() The Exponential distribution with scale parameter has probability density function 1 −x f (x.

1. i.94 Distributions. i. i. FDist(1. ν2 /2) (ν1 x + ν2 )ν1 +ν2 It is related to the Chisq distribution via the property that if X1 ∼ Chisq(ν1 ) and X2 ∼ Chisq(ν2 ). x>0 θ θ [] Frechet() Frchet distribution with unit shape and unit scale.e. DISTRIBUTIONS. (a.e. 1) Frechet(a. Frechet(1. then (X1 /ν1 )/(X2 /ν2 ) ∼ FDist(ν1 .Frechet — Type. 1) Frechet(a) Frchet distribution with shape a and unit scale. (1. x>0 xB(ν1 /2. b External links • Frchet distribution on Wikipedia source . Frechet(a. b) shape(d) Get the shape param- eter.Frechet Distributions. 2) F-Distribution with parameters 1 and 2 params(d) Get the parameters. α. i. b) Frchet distribution with shape a and scale b params(d) Get the parameters. ν1 .e.e. i.e.FDIST 25 1. ν2 ).e. ν2 ) = . i. a scale(d) Get the scale parameter.) The Frchet distribution with shape and scale has probability density func- tion α  x −α−1 −(x/θ)−α f (x.93 Distributions. 2) External links • F distribution on Wikipedia source 1. [] FDist(1. θ) = e .FDist — Type.93. 2) The F distribution has probability density function s 1 (ν1 x)ν1 · ν2ν2 f (x. Frechet(.FDist Distributions.

scale and location has probability density function −1/ξ−1  −1/ξ o (  n  x−µ 1 exp − 1 + x−µ   σ 1+ σ ξ σ ξ for ξ 6= 0 f (x. s. .e. µ − σ  for ξ < 0 ξ [] GeneralizedExtremeValue(m.GeneralizedExtremeValue Distributions. i.Gamma — Type. ξ. m scale(d) Get the scale parameter. (m. µ) = x−µ  x−µ  1   σ exp − σ exp − exp − σ for ξ = 0 for h  σ    µ − ξ . +∞)  i for ξ = 0  −∞. ) The Generalized extreme value distribution with shape parameter .GeneralizedExtremeValue — Type.e. scale s and location m.e. GeneralizedExtremeValue(. (. i. ) Gamma distribution with shape and scale params(d) Get the parameters. k) location(d) Get the location parameter. External links • Gamma distribution on Wikipedia source 1. k (sometimes called c) External links . 1) Gamma() Gamma distribution with shape and unit scale. σ.e. Gamma(.26 CHAPTER 1. s.95 Distributions. +∞ for ξ > 0 x ∈ (−∞. i. ) shape(d) Get the shape parameter.e. i. params(d) Get the parameters. i. 1) Gamma(. scale(d) Get the scale parameter. k) Generalized Pareto distribution with shape k. x>0 Γ(α)θα [] Gamma() Gamma distribution with unit shape and unit scale. Gamma(1. α. s shape(d) Get the shape parameter. Gamma(.e.Gamma Distributions. i. DISTRIBUTIONS 1.e. θ) = . i.) The Gamma distribution with shape parameter and scale has probability density function xα−1 e−x/θ f (x.96 Distributions.e. i. i.e.

i. . k External links • Generalized Pareto distribution on Wikipedia source 1.GeneralizedPareto — Type. P (X = k) = p(1 − p)k . i.e. scale and loca- tion has probability density function x−µ − ξ1 −1 ( ( 1 σ (1 + ξ σ ) for ξ 6= 0 [µ.1.e. . (p.GENERALIZEDPARETO 27 • Generalized extreme value distribution on Wikipedia source 1. s. . µ − σ/ξ] for ξ < 0 [] GeneralizedPareto() Generalized Pareto distribution with unit shape and unit scale. i. ) The Generalized Pareto distribution with shape parameter . params(d) Get the parameters. σ. i. 2. i.Geometric — Type. GeneralizedPareto(0. GeneralizedPareto(. p failprob(d) Get the failure rate. . ξ) = 1 − (x−µ) . GeneralizedPareto(0.e. µ. s) Generalized Pareto distribution with shape k and scale s. [] Geometric() Geometric distribution with success rate 0. scale s and location m. ∞] for ξ ≥ 0 f (x. m scale(d) Get the scale parameter. 1) GeneralizedPareto(k. . 1.e. s) GeneralizedPareto(m.GeneralizedPareto Distributions.Geometric Distributions. i.e.98 Distributions.p External links • Geometric distribution on Wikipedia source . s shape(d) Get the shape parameter.e.5 Geometric(p) Geometric distribution with success rate p params(d) Get the parameters. i.) succprob(d) Get the success rate. i. (m. x∈ σe σ for ξ = 0 [µ.97 Distributions. k) location(d) Get the location parameter.e. DISTRIBUTIONS.e. for k = 0.e. 1. 1 . Geometric(p) A Geometric distribution characterizes the number of failures before the first success in a sequence of independent Bernoulli trials with success rate p. k.97. i. s) Generalized Pareto distribution with shape k. k.

min(n. . . θ) = e . b) Gumbel distribution with location u and scale b params(d) Get the parameters. n) Hypergeometric distribution for a population with s successes and f failures. u scale(d) Get the scale parameter. b) location(d) Get the location parameter. ) The Gumbel distribution with location and scale has probability density function 1 −(z+ez ) x−µ f (x. µ. 1) Gumbel(u) Gumbel distribution with location u and unit scale. b External links • Gumbel distribution on Wikipedia source 1. i.e.99 Distributions.Gumbel Distributions. Hypergeometric(s.e. Gumbel(u. and a sequence of n trials. i. n − f ). s). f. 1) Gumbel(u. i. s f   k n−k P (X = k) = s+f  .e. for k = max(0.e.e.e. . n) External links • Hypergeometric distribution on Wikipedia source .Hypergeometric — Type.28 CHAPTER 1. (u.Hypergeometric Distributions. with z = θ θ [] Gumbel() Gumbel distribution with zero location and unit scale. params(d) Get the parameters. DISTRIBUTIONS 1.Gumbel — Type. i. i. . Gumbel(0. i. Gumbel(.100 Distributions. (s. f. f. n [] Hypergeometric(s. n) A Hypergeometric distribution describes the number of successes in n draws without replacement from a finite population containing s successes and f fail- ures.

b) shape(d) Get the shape param- eter. a scale(d) Get the scale parameter.INVERSEGAMMA 29 1. θ) = e x. 1) InverseGaussian(mu). (mu.e. then ‘1 / X ∼ InverseGamma(α. ) The inverse gamma distribution with shape parameter and scale has prob- ability density function θα x−(α+1) − θ f (x.InverseGaussian — Type. β).101 Distributions. x>0 Γ(α) It is related to the Gamma distribution: if X ∼ Gamma(α. Inverse Gaussian distri- bution with mean mu and unit shape. i. mu shape(d) Get the shape parameter.e.e.e. i. InverseGamma(. 1) InverseGaus- sian(mu. InverseGaussian(. i. i.e. [] InverseGamma() Inverse Gamma distribution with unit shape and unit scale. b) Inverse Gamma distribution with shape a and scale b params(d) Get the parameters. x>0 2πx3 2µ2 x [] InverseGaussian() Inverse Gaussian distribution with unit mean and unit shape. InverseGamma(a.) The inverse Gaussian distribution with mean and shape has probability density function r −λ(x − µ)2   λ f (x. DISTRIBUTIONS. b External links • Inverse gamma distribution on Wikipedia source 1.102 Distributions. InverseGamma(1. lambda) Inverse Gaussian distribution with mean mu and shape lambda params(d) Get the parameters. 1) InverseGamma(a.e. µ.InverseGaussian Distributions. InverseGaussian(u. InverseGaussian(1. 1) InverseGamma(a) Inverse Gamma distribution with shape a and unit scale.e. i. (a. λ) = exp .101. i. i.InverseGamma Distributions. i. lambda External links • Inverse Gaussian distribution on Wikipedia source .e. i.1.e. α.InverseGamma — Type. βˆ{−1})“. i.e. lambda) mean(d) Get the mean parameter.

InverseWishart — Type.105 Distributions. source 1. P) The [Inverse Wishart distribution](http://en. Kolmogorov() Kolmogorov distribution defined as sup |B(t)| t∈[0.Kolmogorov — Type.30 CHAPTER 1. DISTRIBUTIONS 1.KSDist Distributions. to the Kolmogorov distribution.wikipedia.KSOneSided Distributions. and a base matrix . InverseWishart(nu.KSDist — Type.KSOneSided — Type.1] where B(t) is a Brownian bridge used in the Kolmogorov–Smirnov test for large n. source .104 Distributions.InverseWishart Distributions. KSOneSided(n) Distribution of the one-sided Kolmogorov-Smirnov test statistic: Dn+ = sup(F̂n (x) − F (x)) x source 1.Kolmogorov Distributions. which is characterized by a degree of freedom . KSDist(n) Distribution of the (two-sided) Kolmogorov-Smirnoff statistic p Dn = sup |F̂n (x) − F (x)| (n) x Dn converges a.s. source 1.103 Distributions.106 Distributions.org/wiki/Inverse-Wishart distribution is usually used a the conjugate prior for the covariance matrix of a multivariate normal distribution.

) The Laplace distribution with location and scale has probability density function   1 |x − µ| f (x.e.e. 1) Laplace(u.e. i.e. u scale(d) Get the scale parameter. Levy(. i. i. i.e.e. i.108 Distributions. 1) Levy(u.Levy Distributions.e. b) location(d) Get the location parameter.LAPLACE 31 1. c) location(d) Get the location parameter.e. 1) Levy(u) Levy distribution with location u and unit scale. i. b External links • Laplace distribution on Wikipedia source 1. c) Levy distribution with location u ans scale c params(d) Get the parameters.Levy — Type. (u.1. Levy(u. µ. x>µ 2π(x − µ)3 2(x − µ) [] Levy() Levy distribution with zero location and unit scale. i.Laplace — Type. 1) Laplace(u) Laplace distribution with location u and unit scale. i.e. (u.107 Distributions. DISTRIBUTIONS. Laplace(0.107. ) The Lvy distribution with location and scale has probability density func- tion r   σ σ f (x.Laplace Distributions. Levy(0. u External links • Lvy distribution on Wikipedia source . µ. β) = exp − 2β β [] Laplace() Laplace distribution with zero location and unit scale. σ) = exp − . i. Laplace(u. b) Laplace distribution with location u ans scale b params(d) Get the parameters. Laplace(.

e. DISTRIBUTIONS 1.e. (mu..) location-scale transformed distribution params(d) Get the parameters. σ). mu varlogx(d) Get the variance of log(X).LogNormal — Type. and the base distribution) location(d) Get the location parameter scale(d) Get the scale parameter External links Location-Scale family on Wikipedia source 1.   1 x− f (x) = [] LocationScale(. LogNormal(. (. . i. sig) Log-normal distribution with log-mean mu and scale sig params(d) Get the parameters. sig2 stdlogx(d)Getthestandarddeviationof log(X External links • Log normal distribution on Wikipedia source .LocationScale Distributions.e.32 CHAPTER 1..) The log normal distribution is the distribution of the exponential of a Normal variate: if X ∼ Normal(µ. i. x>0 x 2πσ 2 2σ 2 [] LogNormal() Log-normal distribution with zero log-mean and unit scale LogNormal(mu) Log-normal distribution with log-mean mu and unit scale Log- Normal(mu. sig) meanlogx(d) Get the mean of log(X).e.109 Distributions.LocationScale — Type.LogNormal Distributions. scale parameter . and given distribution . i.) A location-scale transformed distribution with location parameter . σ) = √ exp − . σ) then exp(X) ∼ LogNormal(µ. LocationScale(. µ. i. The probability density function is (log(x) − µ)2   1 f (x.110 Distributions.

1) Logistic(u) Logistic distribution with location u and unit scale.e.111 Distributions.Logistic — Type.) The Logistic distribution with location and scale has probability density function   1 2 x−µ f (x.MixtureModel — Method. i.e. MixtureModel(components. b External links • Logistic distribution on Wikipedia source 1. Logistic(u.112 Distributions. source . θ) = sech 4θ 2θ [] Logistic() Logistic distribution with zero location and unit scale. and a prior probability vector. µ. 1) Logistic(u. MixtureModel(C. b) location(d) Get the location parameter. i. [prior]) Construct a mixture model with component type C.Logistic Distributions. params. b) Logistic distribution with location u ans scale b params(d) Get the parameters. Logistic(0.e. If no prior is provided then all components will have the same prior probabilities. If no prior is provided then all components will have the same prior probabilities.MixtureModel — Method.113 Distributions. source 1. i.MixtureModel Distributions.e. a vector of parame- ters for constructing the components given by params.e. i. (u. DISTRIBUTIONS. [prior]) Construct a mixture model with a vector of components and a prior prob- ability vector. u scale(d) Get the scale parameter.LOGISTIC 33 1. i.1.MixtureModel Distributions.111. Logistic(.

k) Multinomial distribution for n trials with equal probabilities over 1:k source 1..Multinomial — Type.34 CHAPTER 1. users don’t have to worry about these internal details..MvNormal Distributions. The probability mass function is given by k n! Y f (x. MvNormal(sig) Construct a multivariate normal distribution with zero mean and covariance represented by sig. We pro- vide a common constructor MvNormal.114 Distributions.116 Distributions. p) Multinomial distribution for n trials with probability vector p Multinomial(n. Σ) has a multivariate normal distribution then Y = exp(X) has a multivariate lognormal distribution. Mean vector µ and covariance matrix Σ of the underlying normal distri- bution are known as the location and scale parameters of the corresponding lognormal distribution. Consider n independent draws from a Categorical distribution over a finite set of size k. x1 + · · · + xk = n x1 ! · · · xk ! i=1 i [] Multinomial(n. then the distribution of X is a multinomial distribution..MvNormal — Type.MvLogNormal Distributions.MvLogNormal — Type. . p) = pxi . which will construct a distribution of appropriate type depending on the input arguments. . Xk ) where Xi represents the number of times the element i occurs.Multinomial Distributions. source 1. MvNormal Generally.115 Distributions. MvLogNormal(d::MvNormal) The Multivariate lognormal distribution is a multidimensional generalization of the lognormal distribution. The Multinomial distribution generalizes the binomial distribution. and let X = (X1 . DISTRIBUTIONS 1. Each sample of a multinomial distribution is a k-dimensional integer vector that sums to n. If X ∼ N (µ. n.

117 Distributions. inv() end . DISTRIBUTIONS. MvNormalCanon Multivariate normal distribution is an exponential family distribution.MVNORMALCANON 35 MvNormal(mu. We pro- vide a type MvNormalCanon. real-valued number: indicating an isotropic covariance as abs2(sig) * eye(d). symmetric matrix of type Matrix{T} 3. Par- ticularly.MvNormalCanon — Type. sig) Construct a multivariate normal distribution of dimension d.e. which is also a subtype of AbstractMvNormal to represent a multivariate normal distribution using canonical parameters. inv() * J::P precision matrix.MvNormalCanon Distributions. • d::Real: dimension of distribution. MvNormalCanon is defined as: [] immutable MvNormalCanon{P¡:AbstractPDMat. so that special structure of the covariance can be exploited.117.V¡:Union{Vector. with zero mean.ZeroVector}} ¡: AbstractMvNormal ::V the mean vector h::V potential vector. Note: The constructor will choose an appropriate covariance form inter- nally. which can in of either of the following forms (with T<:Real): 1. vector of type Vector{T}: indicating a diagonal covariance as diagm(abs2(sig)). the one using mean µ and covariance Σ) is: h = Σ−1 µ. The relation between these parameters and the conventional representation (i.e. and an isotropic covariance as abs2(sig) * eye(d). • sig: The covariance. sig) Construct a multivariate normal distribution with mean mu and covariance represented by sig. i.1. i. Arguments • mu::Vector{T<:Real}: The mean vector. with two canonical parameters: the potential vector h and the precision matrix J. MvNormal(d. subtype of AbstractPDMat 2. and J = Σ−1 The canonical parameterization is widely used in Bayesian analysis.e. source 1. 4.

Vector{Float64}} const IsoNormalCanon = MvNormalCanon{ScalMat. source . J) Construct a multivariate normal distribution of dimension d. Vector{Float64}} const DiagNormalCanon = MvNormalCanon{PDiagMat. of type Vector{T} with T<:Real. DISTRIBUTIONS We also define aliases for common specializations of this parametric type: [] const FullNormalCanon = MvNormalCanon{PDMat. Arguments • d::Int: dimension of distribution • h::Vector{T<:Real}: the potential vector. which can be in either of the following forms (T<:Real): 1. a vector of type Vector{T}: indicating a diagonal precision matrix as diagm(J). an instance of a subtype of AbstractPDMat 2. J) Construct a multivariate normal distribution with potential vector h and precision matrix represented by J.36 CHAPTER 1. 4. with zero mean and a precision matrix as J * eye(d). a real number: indicating an isotropic precision matrix as J * eye(d). a square matrix of type Matrix{T} 3. ZeroVector{Float64}} A multivariate distribution with canonical parameterization can be con- structed using a common constructor MvNormalCanon as: MvNormalCanon(h. Vector{Float64}} const ZeroMeanFullNormalCanon = MvNormalCanon{PDMat. MvNormalCanon(J) Construct a multivariate normal distribution with zero mean (thus zero po- tential vector) and precision matrix represented by J. Note: MvNormalCanon share the same set of methods as MvNormal. ZeroVector{Float64}} const ZeroMeanDiagNormalCanon = MvNormalCanon{PDiagMat. • J: the representation of the precision matrix. MvNormalCanon(d. ZeroVector{Float64}} const ZeroMeanIsoNormalCanon = MvNormalCanon{ScalMat.

λ) = e Iν/2−1 ( λx). . i.e. . p) succprob(d) Get the success rate. i. . and p. NegativeBinomial(r. ) The noncentral chi-squared distribution with degrees of freedom and non- centrality parameter has the probability density function 1 −(x+λ)/2  x ν/4−1/2 √ f (x. k!Γ(r) [] NegativeBinomial() Negative binomial distribution with r = 1 and p = 0. 2.NoncentralChisq Distributions. . in which case Γ(k + r) r P (X = k) = p (1 − p)k . the probability of success in an individual trial.e.NegativeBinomial — Type.5 NegativeBinomial(r. 1.e. p failprob(d) Get the failure rate.NEGATIVEBINOMIAL 37 1.NoncentralBeta Distributions. for k = 0. . (r. p) Negative binomial distribution with r successes and success rate p params(d) Get the parameters.p) A Negative binomial distribution describes the number of failures before the rth success in a sequence of independent Bernoulli trials.NegativeBinomial Distributions. . . NoncentralBeta(. ) source 1. 2.NoncentralBeta — Type. 1.119 Distributions.118 Distributions.p External links: • Negative binomial distribution on Wikipedia source 1.1.118.   k+r−1 r P (X = k) = p (1 − p)k . k The distribution remains well-defined for any positive r.120 Distributions. 1 . NoncentralChisq(. It is parameterized by r. . i. the number of successes. x>0 2 λ . ν. for k = 0.NoncentralChisq — Type. . DISTRIBUTIONS.

i.38 CHAPTER 1.NoncentralT Distributions. ) source 1. NoncentralT(. ) source 1.e. i. ) Noncentral chi-squared distribution with degrees of freedom and noncentrality parameter params(d) Get the parameters.123 Distributions.) The Normal distribution with mean and standard deviation has probability density function (x − µ)2   1 f (x. DISTRIBUTIONS It is the distribution of the sum of squares of independent Normal variates with individual means µi and ν X λ= µ2i i=1 [] NoncentralChisq(. ) External links • Noncentral chi-squared distribution on Wikipedia source 1. Normal(. 2.122 Distributions.NoncentralT — Type.e.NoncentralF Distributions.Normal Distributions. (. sig External links . i.Normal — Type.e. sig) mean(d) Get the mean. σ) = √ exp − 2πσ 2 2σ 2 [] Normal() standard Normal distribution with zero mean and unit variance Normal(mu) Normal distribution with mean mu and unit variance Normal(mu. i. NoncentralF(1.e. (mu. mu std(d) Get the standard deviation.NoncentralF — Type.121 Distributions. µ. sig) Normal distribution with mean mu and variance sig2 params(d) Get the parameters.

Pareto(a.) The Pareto distribution with shape and scale has probability density func- tion αθα f (x.e.Pareto — Type. α. b) shape(d) Get the shape param- eter. tail heaviness . θ) = .124 Distributions.126 Distributions.NormalCanon Distributions.NORMALCANON 39 • Normal distribution on Wikipedia source 1. δ) = p eδγ+β(x−µ) π δ 2 + (x − µ)2 where Kj denotes a modified Bessel function of the third kind. i. DISTRIBUTIONS.e. b) Pareto distribution with shape a and scale b params(d) Get the parameters. a scale(d) Get the scale parameter. i. Pareto(. i. NormalCanon(..NormalCanon — Type. i. Pareto(1.NormalInverseGaussian Distributions. β. asymmetry parameter and scale has probability density function  p  αδK1 α δ 2 + (x − µ)2 f (x..1. b External links . 1) Pareto(a) Pareto distribution with shape a and unit scale.NormalInverseGaussian — Type. (a. External links • Normal-inverse Gaussian distribution on Wikipedia source 1.Pareto Distributions.e. i. x≥θ xα+1 [] Pareto() Pareto distribution with unit shape and unit scale. NormalInverseGaussian(. ) Canonical Form of Normal distribution source 1.) The Normal-inverse Gaussian distribution with location . µ. 1) Pareto(a.124.e.125 Distributions.e. α.

. p failprob(d) Get the vector of failure rates.e.128 Distributions. wherein each trial has a different success rate. Poisson() A Poisson distribution descibes the number of independent events occurring within a unit time interval. 2.Poisson — Type. for k = 0. i. given the average rate of occurrence . i. k! [] Poisson() Poisson distribution with rate parameter 1 Poisson(lambda) Poisson distribution with rate parameter lambda params(d) Get the parameters.. A∈Fk i∈A j∈Ac where Fk is the set of all subsets of k integers that can be selected from {1. .Poisson Distributions.e. . . i. 1. for k = 0.e. λk −λ P (X = k) = e . 2. i. [] PoissonBinomial(p) Poisson Binomial distribution with success rate vector p params(d) Get the parameters. . (p.. 1-p External links: • Poisson-binomial distribution on Wikipedia source .e.PoissonBinomial — Type.) succprob(d) Get the vector of success rates. External links: • Poisson distribution on Wikipedia source 1. 2. It is parameterized by a vector p (of length K). where K is the total number of trials and p[i] corresponds to the probability of success of the ith trial. . . K}. K.) mean(d) Get the mean arrival rate. i.. PoissonBinomial(p) A Poisson-binomial distribution describes the number of successes in a se- quence of independent trials. 1.e. DISTRIBUTIONS • Pareto distribution on Wikipedia source 1.127 Distributions. 3. X Y Y P (X = k) = p[i] (1 − p[j]).PoissonBinomial Distributions. (. . .40 CHAPTER 1.

Semicircle Distributions. πr2 [] Semicircle(r) Wigner semicircle distribution with radius r params(d) Get the radius parameter. (r.129. Rayleigh(1) Rayleigh(s) Rayleigh distribution with scale s params(d) Get the parameters. i.e.129 Distributions. then X 2 + Y 2 ∼ Rayleigh(σ).e. x ∈ [−r.Semicircle — Type. DISTRIBUTIONS. r) = r − x2 . [] Rayleigh() Rayleigh distribution with unit scale. i. Y ∼ Normal(0.130 Distributions.e. σ). σ) = e 2σ .RAYLEIGH 41 1.1.e.) External links • Wigner semicircle distribution on Wikipedia source . i. (s. independently. i. x>0 σ2 It is related to the Normal distribution √ via the property that if X. s External links • Rayleigh distribution on Wikipedia source 1. Rayleigh() The Rayleigh distribution with scale has probability density function x − x22 f (x. Semicircle(r) The Wigner semicircle distribution with radius parameter r has probability density function 2 p 2 f (x. r].Rayleigh Distributions.) scale(d) Get the scale parameter.Rayleigh — Type.

mu2) Skellam distribution for the difference between two Poisson variables.131 Distributions. (mu1.42 CHAPTER 1. Skellam(1.Skellam — Type.  k/2 µ1 √ P (X = k) = e−(µ1 +µ2 ) Ik (2 µ1 µ2 ) for integer k µ2 where Ik is the modified Bessel function of the first kind.SymTriangularDist — Type.SymTriangularDist Distributions. DISTRIBUTIONS 1. params(d) Get the parameters.e.) The Symmetric triangular distribution with location and scale has proba- bility density function  .132 Distributions. SymTriangularDist(. 2) A Skellam distribution describes the difference between two independent Poisson variables. mu2) External links: • Skellam distribution on Wikipedia source 1. [] Skellam(mu1.Skellam Distributions. respectively with expected values mu1 and mu2. respectively with rate 1 and 2. i.

.

 1 .

x − µ.

σ) = 1−. µ. f (x.

.

.

µ−σ ≤x≤µ+σ σ σ . .

TDist() . i.e.TDist Distributions. u scale(d) Get the scale parameter. (u. i. i.e.e. s) Symmetric triangular distribution with location u and scale s params(d) Get the parameters.TDist — Type. s source 1. [] SymTriangularDist() Symmetric triangular distribution with zero loca- tion and unit scale SymTriangularDist(u) Symmetric triangular distribution with location u and unit scale SymTriangularDist(u.133 Distributions. s) location(d) Get the location parameter.

e. b.Triweight Distributions. DISTRIBUTIONS. b. b. i. c) = 2(b−x)    (b−a)(b−c) for c < x ≤ b. [] TriangularDist(a. d/2) d [] TDist(d) t-distribution with d degrees of freedom params(d) Get the parameters. ) source . Triweight(. i.TriangularDist — Type. c) minimum(d) Get the lower bound. upper limit b. i.b.e. and mode c params(d) Get the parameters.TRIANGULARDIST 43 The Students T distribution with degrees of freedom has probability density function − d+1 x2  1 2 f (x.   0 for b < x.134 Distributions. b mode(d) Get the mode. b) Triangular distribution with lower limit a.    (b−a)(c−a) f (x. i.135 Distributions. i. TriangularDist(a. c) Triangular distribution with lower limit a. upper limit b and mode c has probability density function    0 for x < a.c) The triangular distribution with lower limit a. c External links • Triangular distribution on Wikipedia source 1. a. upper limit b. and mode (a+b)/2 TriangularDist(a.Triweight — Type.e.e.) dof(d) Get the degrees of freedom. (d.1.e. d External links Student’s T distribution on Wikipedia source 1. 2(x−a) for a ≤ x ≤ c.134.e. d) = √ 1+ dB(1/2.TriangularDist Distributions. (a. a maximum(d) Get the upper bound. i.

e. which can be a finite value or -Inf. DISTRIBUTIONS 1. a scale(d) Get the scale parameter.b) The continuous uniform distribution over an interval [a.e.Uniform Distributions.e. b location(d) Get the location parameter. b . Truncated(d. a≤x≤b b−a [] Uniform() Uniform distribution over [0.138 Distributions. a maximum(d) Get the upper bound. • l::Real: The lower bound of the truncation.a External links • Uniform distribution (continuous) on Wikipedia source 1. i. i. u): Construct a truncated distribution. i. i. which can be a finite value of Inf. i. ) .e.Truncated — Type. a. b) minimum(d) Get the lower bound. Uniform(a. • u::Real: The upper bound of the truncation. b] has probability density function 1 f (x.44 CHAPTER 1. (a.Uniform — Type. VonMises(. l.e.136 Distributions. b) = . b] params(d) Get the parameters. source 1. 1] Uniform(a.Truncated Distributions. Arguments • d::UnivariateDistribution: The original distribution.137 Distributions.VonMises Distributions.VonMises — Type. b) Uniform distri- bution over [a.

Wishart(nu. source . i. ) von Mises distribution with mean and concentration External links • von Mises distribution on Wikipedia source 1.1. θ) = e . S) The Wishart distribution is a multidimensional generalization of the Chi- square distribution.e.139.e. Weibull(1.Weibull — Type. and a base matrix S. µ.WEIBULL 45 The von Mises distribution with mean and concentration has probability density function 1 f (x. Weibull(a. DISTRIBUTIONS. i.e. i. α. 1) Weibull(a. i. Weibull(. (a. b) Weibull distribution with shape a and scale b params(d) Get the parameters. κ) = exp (κ cos(x − µ)) 2πI0 (κ) [] VonMises() von Mises distribution with zero mean and unit concentration VonMises() von Mises distribution with zero mean and concentration Von- Mises(. 1) Weibull(a) Weibull distribution with shape a and unit scale. b) shape(d) Get the shape param- eter. which is characterized by a degree of freedom . b External links • Weibull distribution on Wikipedia source 1.Weibull Distributions.e.140 Distributions. x≥0 θ θ [] Weibull() Weibull distribution with unit shape and unit scale.e.Wishart — Type.139 Distributions.) The Weibull distribution with shape and scale has probability density function α  x α−1 −(x/θ)α f (x.Wishart Distributions. a scale(d) Get the scale parameter. i.

1 Base.stdm — Method. corrected=false) Compute the standard deviation of a real-valued array x with a known mean m. The unbiased estimate (when corrected=true) of the population standard deviation is computed by replacing P1w with a factor dependent on the type of weights used: • AnalyticWeights: P P1 2 P w− w / w • FrequencyWeights: P1 w−1 nP • ProbabilityWeights: (n−1) w where n equals count(!iszero. w) • Weights: ArgumentError (bias correction not supported) source 46 . optionally over a dimension dim. stdm(v.Chapter 2 StatsBase 2.stdm Base. [dim]. w::AbstractWeights. The uncorrected (when corrected=false) sample standard deviation is defined as: v u n u 1 X 2 tP wi (xi − m) w i=1 where n is the length of the input. m. Observations in x are weighted using weight vector w.

b) pPn Compute the L2 distance between two arrays: i=1 |ai − bi |2 . L1dist(a. L2dist(a. m. Efficient equivalent of sqrt(sumabs2(a .4 StatsBase. corrected=false) Compute the variance of a real-valued array x with a known mean m.VARM 47 2.L1dist StatsBase. w::AbstractWeights.b).L1dist — Method. a . option- ally over a dimension dim.b)). [dim].varm Base. The uncorrected (when corrected=false) sample variance is defined as: n 1 X 2 P wi (xi − m) w i=1 where n is the length of the input. varm(x.varm — Method. BASE. b) Pn Compute the L1 distance between two arrays: i=1 |ai −bi |.3 StatsBase.L2dist — Method. source 2.2.L2dist StatsBase. Efficient equiv- alent of sum(abs. w) • Weights: ArgumentError (bias correction not supported) source 2.2. The unbiased estimate (when corrected=true) of the population variance is computed by replacing P1w with a factor dependent on the type of weights used: • AnalyticWeights: P P1 2 P w− w / w • FrequencyWeights: P1 w−1 nP • ProbabilityWeights: (n−1) w where n equals count(!iszero.2 Base. source . Observations in x are weighted using weight vector w.

addcounts!(r. New entries will be added if new values come up. addcounts!(dict. source 2. source 2.6 StatsBase. levels::UnitRange{<:Int}. adjr2(obj::StatisticalModel. This definition is generally known as the Wherry Formula I.Linfdist — Method. n the number of observations.Linfdist StatsBase. x. [wv::AbstractWeights]) Add the number of occurrences in x of each value in levels to an existing array r. If a weighting vector wv is specified. For other models.48 CHAPTER 2. The only currently supported variant is :MacFadden. variant::Symbol) Adjusted coefficient of determination (adjusted R-squared).addcounts! — Method. also called the Chebyshev distance. source 2. Efficient equivalent of maxabs(a . between two arrays: maxi∈1:n |ai − bi |. STATSBASE 2. the sum of weights is used rather than the raw counts. x[.adjr2 StatsBase. For linear models. one of the several pseudo R definitions must be chosen via variant. with R2 the coefficient of determination. and p the number of coefficients (including the intercept).adjr2 — Method.addcounts! — Method. If a weighting vector wv is specified. Linfdist(a. the sum of the weights is used rather than the raw counts.addcounts! StatsBase.addcounts! StatsBase. variant::Symbol) adjr(obj::StatisticalModel. wv]) Add counts based on x to a count map.8 StatsBase.7 StatsBase.b). the adjusted R is defined as 1−(1−(1−R2 )(n−1)/(n−p)).5 StatsBase. defined as . b) Compute the L distance.

k its number of consumed degrees of freedom (as returned by dof). x. aicc(obj::StatisticalModel) Corrected Akaike’s Information Criterion for small sample sizes (Hurvich and Tsai 1989). k is the number of consumed degrees of freedom of the model (as returned by dof). source . defined as −2 log L+2k +2k(k −1)/(n−k −1). See autocov! for the unnormalized form. source 2. defined as −2 log L+2k.e. demean denotes whether the mean of x should be subtracted from x before computing the ACF.autocor! StatsBase. demean=true) Compute the autocorrelation function (ACF) of a vector or matrix x at lags and store the result in r. These two quantities are taken to be minus half deviance of the corresponding models.aic StatsBase. In this formula. r must be a matrix of size (length(lags).aic — Method.aicc StatsBase.2)). size(x. source 2. and where each column in the result will correspond to a column in x.aicc — Method. r must be a vector of the same length as x. i.11 StatsBase. with L the likelihood of the model. STATSBASE. autocor!(r.2. If x is a matrix. L is the likelihood of the model.9 StatsBase. L0 that of the null model (the model including only the intercept).10 StatsBase. with L the likelihood of the model. If x is a vector. so that the lag 0 auto- correlation is 1.autocor! — Method. The output is normalized by the variance of x.9. and n the number of observations (as returned by nobs). lags.AIC 49 1 − (log L − k)/ log L0. and k its number of consumed degrees of freedom (as returned by dof). source 2. aic(obj::StatisticalModel) Akaike’s Information Criterion.

[lags].2)). source 2.2)). demean denotes whether the mean of x should be subtracted from x before computing the autocovariance. demean=true) Compute the autocovariance of a vector or matrix x at lags and store the result in r. and where each column in the result will correspond to a column in x. [lags]. 10*log10(size(x. source 2. return a matrix of size (length(lags). demean denotes whether the mean of x should be subtracted from x before computing the ACF. The output is not normalized. autocor(x. size(x.50 CHAPTER 2. If x is a matrix. If x is a matrix. size(x. size(x.autocor StatsBase.1))). STATSBASE 2. The output is normalized by the variance of x. return a vector of the same length as x. op- tionally specifying the lags. demean=true) Compute the autocorrelation function (ACF) of a vector or matrix x. If x is a vector. lags.autocov! StatsBase.2)). i. See autocor! for a method with normaliza- tion. x.autocov! — Method. so that the lag 0 auto- correlation is 1. return a matrix of size (length(lags). autocov(x. r must be a vector of the same length as x. When left unspecified. demean denotes whether the mean of x should be subtracted from x before computing the autocovariance. If x is a vector. . r must be a matrix of size (length(lags).13 StatsBase. return a vector of the same length as x.12 StatsBase.autocov StatsBase. where each column in the result corresponds to a column in x. If x is a matrix.e. demean=true) Compute the autocovariance of a vector or matrix x. autocov!(r. If x is a vector.14 StatsBase. optionally specifying the lags at which to compute the autocovariance. See autocov for the unnormalized form.autocov — Method. the lags used are the integers from 0 to min(size(x.autocor — Method.1)-1. where each column in the result corresponds to a column in x.

coefnames — Method.15 StatsBase.1))). coefnames(obj::StatisticalModel) Return the names of the coefficients.aweights — Method. coef(obj::StatisticalModel) Return the coefficients of the model.17 StatsBase.15. k its number of consumed degrees of freedom (as returned by dof).2. bic(obj::StatisticalModel) Bayesian Information Criterion. source 2.coef — Method.16 StatsBase.aweights StatsBase. source . defined as −2 log L+k log n. source 2. source 2. the lags used are the integers from 0 to min(size(x.bic — Method.coefnames StatsBase. source 2. and n the number of observations (as returned by nobs). aweights(vs) Construct an AnalyticWeights vector from array vs.AWEIGHTS 51 When left unspecified. See the documenta- tion for AnalyticWeights for more details.bic StatsBase. with L the like- lihood of the model. 10*log10(size(x.coef StatsBase. See autocor for a function with normaliza- tion. STATSBASE.1)-1.18 StatsBase. The output is not normalized.

source 2. y=x) Compute Kendall’s rank correlation coefficient.1. source 2. STATSBASE 2. source 2.52 CHAPTER 2. competerank(x) Return the standard competition ranking (“1224” ranking) of a real-valued array.cor2cov — Method. Use StatsBase. source 2.19 StatsBase. source .confint — Method.coeftable — Method. x and y must both be either matrices or vectors.cor2cov! for an in-place version. then a gap is left in the rankings the size of the number of tied items . coeftable(obj::StatisticalModel) Return a table of class CoefTable with coefficients and related statistics.22 StatsBase.corkendall StatsBase. confint(obj::StatisticalModel) Compute confidence intervals for coefficients. .coeftable StatsBase. Items that compare equal are given the same rank.confint StatsBase. s) Compute the covariance matrix from the correlation matrix C and a vector of standard deviations s.21 StatsBase.competerank — Method.corkendall — Method.20 StatsBase.cor2cov StatsBase. cor2cov(C. corkendall(x.23 StatsBase.competerank StatsBase.

countne StatsBase. STATSBASE. countmap(x) Return a dictionary mapping each unique value in x to its number of occur- rences. the output is a float.countmap StatsBase.counteq — Method.counteq StatsBase. otherwise it’s a matrix corresponding to the pairwise correlations of the columns of x and y.26 StatsBase.27 StatsBase.2. source . y=x) Compute Spearman’s rank correlation coefficient.25 StatsBase.CORSPEARMAN 53 2.24 StatsBase. b) Count the number of indices at which the elements of the arrays a and b are not equal. b) Count the number of indices at which the elements of the arrays a and b are equal. source 2.24.corspearman — Method.countmap — Method. corspearman(x. countne(a. If x and y are vectors. source 2.corspearman StatsBase.countne — Method. source 2. counteq(a.

See crosscov! for the unnormalized form. x. s) Compute the correlation matrix from the covariance matrix C and a vector of standard deviations s.28 StatsBase.crosscor! — Method. r must be a matrix of size (length(lags). If a weighting vector wv is specified.54 CHAPTER 2. r must be a vector of the same length as lags. y. only values falling in that range will be considered (the others will be ignored without raising an error or a warning). source 2.counts StatsBase. if x is a vector and y is a matrix. size(y. 2)). the sum of the weights is used rather than the raw counts. If levels is provided. [wv::AbstractWeights]) counts(x.29 StatsBase. lags. size(y. k::Integer. 2). STATSBASE 2. [wv::AbstractWeights]) counts(x. The output is a vector of length length(levels). If both x and y are matrices. crosscor!(r. cov2cor(C. 2)). source 2. levels::UnitRange{<:Integer}.cov2cor StatsBase. only values in the range 1:k will be considered. demean=true) Compute the cross correlation between real-valued vectors or matrices x and y at lags and store the result in r.cov2cor! for an in-place version. Use Base. counts(x. [wv::AbstractWeights]) Count the number of times each value in x occurs.counts — Function. size(x. The output is normalized by sqrt(var(x)*var(y)). size(x.30 StatsBase. demean specifies whether the respective means of x and y should be subtracted from them before computing their cross correlation. If an integer k is provided. r must be a three-dimensional array of size (length(lags). If either x is a matrix and y is a vector. 2)). If both x and y are vectors.cov2cor — Method.crosscor! StatsBase. source . r must be a matrix of size (length(lags).

If both x and y are matrices. demean=true) Compute the cross correlation between real-valued vectors or matrices x and y. demean=true) .31. r must be a vector of the same length as lags.CROSSCOR 55 2. demean=true) Compute the cross covariance function (CCF) between real-valued vectors or matrices x and y at lags and store the result in r. 2). if x is a vector and y is a matrix. STATSBASE.1)-1. If both x and y are vectors. crosscov!(r. If both x and y are vectors. [lags]. Otherwise. return a vector of the same length as lags. r must be a matrix of size (length(lags).crosscov! StatsBase.2. x. demean specifies whether the respective means of x and y should be subtracted from them before computing their CCF. [lags]. crosscor(x. crosscov(x.crosscov — Method. demean specifies whether the respective means of x and y should be subtracted from them before computing their cross correlation. 2)). size(y. y. lags. When left unspecified. compute cross covariances between each pairs of columns in x and y. optionally specifying the lags.crosscor — Method. The output is not normalized. source 2. r must be a three-dimensional array of size (length(lags). r must be a matrix of size (length(lags).crosscov! — Method. If either x is a matrix and y is a vector. the lags used are the integers from -min(size(x.31 StatsBase.1).32 StatsBase. 2)).1))) to min(size(x. See crosscov for the unnormalized form. size(y. See crosscor! for a function with normal- ization. size(x.33 StatsBase. 10*log10(size(x.1))). source 2. The output is normalized by sqrt(var(x)*var(y)). y.crosscor StatsBase.crosscov StatsBase. y. size(x. 2)). 10*log10(size(x.

crossentropy(p. source . 25th percentile.describe StatsBase.crossentropy — Method.crossentropy StatsBase. and the next subsequent rank is assigned with no gap. source 2. source 2.35 StatsBase. 75th percentile. minimum. STATSBASE Compute the cross covariance function (CCF) between real-valued vectors or matrices x and y. Otherwise. q.34 StatsBase.1))) to min(size(x.36 StatsBase. optionally specifying the lags. 10*log10(size(x. describe(a) Pretty-print the summary statistics provided by summarystats: the mean.1))). denserank(x) Return the dense ranking (“1223” ranking) of a real-valued array. When left unspecified. return a vector of the same length as lags.denserank StatsBase. 10*log10(size(x. median.1)-1. source 2.56 CHAPTER 2. The output is not normalized. Items that compare equal receive the same ranking. demean specifies whether the respective means of x and y should be subtracted from them before computing their CCF. and maximum. the lags used are the integers from -min(size(x. [b]) Compute the cross entropy between p and q.denserank — Method.describe — Method. optionally specifying a real number b such that the result is scaled by 1/log(b).1). If both x and y are vectors. See crosscor for a function with normaliza- tion. compute cross covariances between each pairs of columns in x and y.

with L the likelihood of the model. Note: this is a higher-level function that returns a function. source 2. including when applicable the intercept and the distribution’s dispersion parameter. source 2. which is usually when applicable the saturated model. source 2. STATSBASE.DEVIANCE 57 2.dof residual — Method. to −2 log L.37 StatsBase.deviance — Method.dof — Method.38 StatsBase. dof(obj::StatisticalModel) Return the number of degrees of freedom consumed in the model. source .37. deviance(obj::StatisticalModel) Return the deviance of the model relative to a reference.dof StatsBase.deviance StatsBase.dof residual StatsBase.2.ecdf StatsBase.39 StatsBase. which can then be applied to evaluate CDF values on other samples. ecdf(X) Return an empirical cumulative distribution function (ECDF) based on a vector of samples given in X.40 StatsBase. It is equal. dof_residual(obj::RegressionModel) Return the residual degrees of freedom of the model.ecdf — Method. up to a constant.

44 StatsBase. Fit a statistical model.entropy StatsBase. Fit a statistical model in-place. source 2. closed=:right.findat — Method. data[.fit — Method.findat StatsBase. source 2.fit StatsBase.45 StatsBase.41 StatsBase.fit! StatsBase. find its first index in a. weight][. the corresponding index is 0. source 2.42 StatsBase. .fit StatsBase. If the value does not occur in a.entropy — Method.43 StatsBase. [b]) Compute the entropy of an array p.fit — Method. entropy(p. or a tuple of vectors of equal length (for an n-dimensional histogram).58 CHAPTER 2.fit! — Method. source 2. findat(a. fit(Histogram. edges]. nbins) Fit a histogram to data. optionally specifying a real number b such that the entropy is scaled by 1/log(b). b) For each element in b. Arguments • data: either a vector (for a 1-dimensional histogram). STATSBASE 2.

If no edges are provided. intervals are right-closed (a. STATSBASE.rand(100))) h = fit(Histogram. (rand(100). each observation has weight 1.1:1. (rand(100).0) h = fit(Histogram. or a tuple of integers). rand(100).b). rand(100). these are determined from the data.46 StatsBase. • edges: a vector (typically an AbstractRange object). See the docu- mentation for FrequencyWeights for more details.47 StatsBase. [20]. closed=:left) Multivariate h = fit(Histogram.nbins=10) source 2.FITTED 59 • weight: an optional AbstractWeights (of the same length as the data vectors).fweights — Method. denoting the weight each observation contributes to the bin.0) h = fit(Histogram. fitted(obj::RegressionModel) Return the fitted values of the model. 0:20:100) h = fit(Histogram. rand(100)) h = fit(Histogram.fitted StatsBase.fitted — Method. Keyword arguments • closed=:right: if :left. • nbins: if no edges argument is supplied.46. rand(100). that gives the edges of the bins along each dimension. fweights(vs) Construct a FrequencyWeights vector from a given array. If no weight vector is supplied. if :right (the default). the approximate number of bins to use along each dimension (can be either a single integer.b]. or tuple of vectors.rand(100)).fweights StatsBase. 0:20:100. [20].1:1.2. source . source 2. the bin intervals are left-closed [a. 0:0. weights(rand(100)). 0:0. nbins=10) h = fit(Histogram. Examples [] Univariate h = fit(Histogram.

indexmap — Method.genmean — Method. Pn 1 i. indexmap(a) Construct a dictionary that maps each unique value in a to the index of its first occurrence in a. source 2.52 StatsBase.50 StatsBase. Efficient equivalent of sum(a*log(a/b)-a+b).geomean — Method.genmean StatsBase.60 CHAPTER 2. gkldiv(a. genmean(a.harmmean — Method. source 2. where n = length(a).indexmap StatsBase.gkldiv — Method. geomean(a) Return the geometric mean of a real-valued array. b) PnCompute the generalized Kullback-Leibler divergence between two arrays: i=1 (ai log(ai /bi ) − ai + bi ). n1 i=1 api p . harmmean(a) Return the harmonic mean of a real-valued array.harmmean StatsBase. source . STATSBASE 2. p) Return the generalized/power mean with exponent p of a real-valued array.gkldiv StatsBase.51 StatsBase.48 StatsBase. source 2.e.geomean StatsBase.49 StatsBase. It is taken to be the geometric mean when p == 0. source 2.

source . i] = true and all other elements are false. k::Integer.56 StatsBase. Then I[ci. If sparse is true.iqr StatsBase. Examples julia> using StatsBase julia> indicatormat([1 2 2].55 StatsBase.indicatormat — Method. lens) Reconstruct a vector from its run-length encoding (see rle). indicatormat(x.53 StatsBase. sparse=false) Construct a boolean matrix I of size (k.INDICATORMAT 61 2. length(x)). the output will be a sparse matrix. the 75th percentile minus the 25th percentile.2}: true false false false true true source 2. source 2.54 StatsBase. Let ci be the index of x[i] in c.53. vals is a vector of the values and lens is a vector of the corresponding run lengths.inverse rle — Method. i. otherwise it will be dense (default). indicatormat(x.indicatormat — Method.inverse rle StatsBase.indicatormat StatsBase. inverse_rle(vals. i] = true and all other elements are set to false.indicatormat StatsBase. source 2. sparse=false) Construct a boolean matrix I of size (length(c). length(x)) such that I[x[i].2.iqr — Method. c=sort(unique(x)). 2) 23 Array{Bool. STATSBASE.e. iqr(v) Compute the interquartile range (IQR) of an array.

57 StatsBase. STATSBASE 2. kldivergence(p. source 2. optionally specifying a real number b such that the divergence is scaled by 1/log(b). source 2. levelsmap(a) Construct a dictionary that maps each of the n unique values in a to a number between 1 and n. [wv::AbstractWeights].60 StatsBase. loglikelihood(obj::StatisticalModel) Return the log-likelihood of the model. source 2. source . m=mean(v)) Compute the excess kurtosis of a real-valued array v.kurtosis StatsBase.58 StatsBase. mad(v) Compute the median absolute deviation of v. source 2.levelsmap StatsBase.kurtosis — Method.62 CHAPTER 2. kurtosis(v.61 StatsBase. [b]) Compute the Kullback-Leibler divergence of q from p.loglikelihood — Method.loglikelihood StatsBase.levelsmap — Method.kldivergence StatsBase.mad — Method.mad StatsBase. q.59 StatsBase.kldivergence — Method. optionally specifying a weighting vector wv and a center m.

Finally. cov) Return the mean and covariance matrix as a tuple. var) Return the mean and variance of a real-valued array x.63 StatsBase. optionally over a dimension dim. [w::AbstractWeights]. maxad(a. [dim]. A weighting vector wv can be specified.mean and std — Method. std) Return the mean and standard deviation of a real-valued array x.MAXAD 63 2. mean_and_std(x. vardim=1.mean and cov — Function. Observations in x can be weighted using weight vector w.mean and var — Method. source 2. corrected=false) -> (mean.62. as a tuple. optionally over a dimension dim.mean and var StatsBase. bias correction is applied to the standard deviation calculation if corrected=true. See cov documentation for more details. Finally. Finally. See std documentation for more details. corrected=false) -> (mean. [w::AbstractWeights].62 StatsBase. STATSBASE. corrected=false) -> (mean. mean_and_cov(x.maxad — Method. source 2.maxad StatsBase. [dim]. [wv::AbstractWeights]. b) Return the maximum absolute deviation between two arrays: maxabs(a - b). mean_and_var(x.2.mean and std StatsBase.mean and cov StatsBase. vardim that designates whether the variables are columns in the matrix (1) or rows (2).65 StatsBase. source . source 2. A weighting vector w can be specified to weight the estimates. as a tuple. See var documentation for more details. bias correction is applied to the covariance calculation if corrected=true. bias correction is be applied to the variance calculation if corrected=true.64 StatsBase.

source 2.70 StatsBase. the design matrix). modes(a.mode — Method.meanad StatsBase. [r]) Return the mode (most common number) of an array.modes — Method. If several modes exist.modelmatrix StatsBase. meanad(a.a. b) Return the mean absolute deviation between two arrays: mean(abs(a - b)). optionally over a specified range r.mode StatsBase.k. source 2.modelmatrix — Method. optionally over a specified range r. the first one (in order of appearance) is returned. STATSBASE 2.64 CHAPTER 2. source 2. modelmatrix(obj::RegressionModel) Return the model matrix (a.a. source .66 StatsBase. the dependent variable). source 2. mode(a.68 StatsBase.meanad — Method.69 StatsBase.67 StatsBase. [r])::Vector Return all modes (most common numbers) of an array.k.modes StatsBase.model response — Method.model response StatsBase. model_response(obj::RegressionModel) Return the model response (a.

0.msd StatsBase. as the definition of an independent observation may vary depending on the model. nquantile(v. [0:n]/n).71. on the format used to pass the data.73 StatsBase. b) Return the mean squared deviation between two arrays: mean(abs2(a - b)). 0. source 2.msd — Method.moment — Method.2.nobs — Method.0].6. k. 5) re- turns a vector of quantiles. STATSBASE.74 StatsBase.nobs StatsBase. nobs(obj::StatisticalModel) Return the number of independent observations on which the model was fit- ted. etc. on the sampling plan (if specified).nquantile — Method.72 StatsBase.nquantile StatsBase. msd(a. m=mean(v)) Return the kth order central moment of a real-valued array v. moment(v. nquantiles(x.4. For example. 0.moment StatsBase. [wv::AbstractWeights]. Be careful when using this information. n) Return the n-quantiles of a real-valued array.71 StatsBase. source 2. Equivalent to quantile(v. source . i. source 2.8. 1.e.0. optionally specifying a weighting vector wv and a center m.MOMENT 65 2. 0. the values which partition v into n subsets of nearly equal size.2. respectively at [0.

nullloglikelihood — Method.75 StatsBase. successive ranks based on their position in sort(x).76 StatsBase.77 StatsBase. nulldeviance(obj::StatisticalModel) Return the deviance of the null model. STATSBASE 2.78 StatsBase. method=:regression) Compute the partial autocorrelation function (PACF) of a matrix X at lags and store the result in r. pacf!(r. method designates the estimation method. r must be a matrix of size (length(lags). All items in x are given distinct.ordinalrank — Method. source 2.pacf ! StatsBase. source 2.nulldeviance — Method. which computes the partial autocorrelations via successive regression models. source . and :yulewalker. source 2. lags. which computes the partial autocorrelations using the Yule-Walker equations. 2)).ordinalrank StatsBase. size(x. This is usually the model containing only the intercept. Rec- ognized values are :regression. ordinalrank(x) Return the ordinal ranking (“1234” ranking) of a real-valued array.pacf! — Method. loglikelihood(obj::StatisticalModel) Return the log-likelihood of the null model corresponding to model obj. that is the one including only the intercept.nulldeviance StatsBase.nullloglikelihood StatsBase. X.66 CHAPTER 2.

79. quantile(x. for a GLM it would generally be a DataFrame with the same variable names as the original predictors.79 StatsBase. return a vector of the same length as lags. [newX]) Form the predicted response of model obj. pacf(X. source 2.pacf StatsBase. return a matrix of size (length(lags).predict StatsBase. which computes the partial autocorrelations via successive regression models. i. predict(obj::RegressionModel. source 2. STATSBASE. percentile(v. p / 100). p) Return the pth percentile of a real-valued array v.82 StatsBase. If x is a matrix. e. If x is a vector. An object with new covariate values newX can be supplied. method=:regression) Compute the partial autocorrelation function (PACF) of a real-valued vector or matrix X at lags. and :yulewalker.percentile — Method.PACF 67 2.predict! StatsBase. source .e. size(x. 2)). method designates the estimation method.g. Recognized val- ues are :regression.predict! — Function. which should have the same type and structure as that used to fit obj.predict — Function. predict! In-place version of predict. where each column in the result corresponds to a column in x.81 StatsBase.pacf — Method. lags. source 2. which computes the partial autocorrela- tions using the Yule-Walker equations.percentile StatsBase.80 StatsBase.2.

levels=span(x).pweights — Method. If a weighting vector wv is specified. [wv::AbstractWeights]) Return the proportion of values in the range levels that occur in x. STATSBASE 2. proportions(x.proportions — Method. [wv::AbstractWeights]) Return the proportion of integers in 1 to k that occur in x.proportionmap StatsBase. maxv) Compute the peak signal-to-noise ratio between two arrays a and b.psnr StatsBase.psnr — Method. The PSNR is computed as 10 * log10(maxv^2 / msd(a. k::Integer. source 2. pweights(vs) Construct a ProbabilityWeights vector from a given array. Equiva- lent to counts(x. maxv is the maximum possible value either array can take. source 2. source 2.proportions StatsBase. b)).86 StatsBase.proportions — Method.85 StatsBase.84 StatsBase.68 CHAPTER 2.87 StatsBase. psnr(a.83 StatsBase. source . source 2. See the docu- mentation for ProbabilityWeights for more details. proportions(x.pweights StatsBase. the sum of the weights is used rather than the raw counts. levels) / length(x). proportionmap(x) Return a dictionary mapping each unique value in x to its proportion in x.proportionmap — Method.proportions StatsBase. b.

source 2.residuals StatsBase.a. defined as 1 − (L0/L)2/n • :Nagelkerke.R2 69 2.k. ) Compute the Rnyi (generalized) entropy of order of an array p. These two quantities are taken to be minus half deviance of the corresponding models. likelihood ratio index).residuals — Method. variant::Symbol) Coefficient of determination (R-squared).r2 StatsBase. defined as (1 − (L0/L)2/n )/(1 − L02/n ). • :CoxSnell. source . residuals(obj::RegressionModel) Return the residuals of the model. Supported variants are: • :MacFadden (a. one of several pseudo R definitions must be chosen via variant.88 StatsBase. with ESS the explained sum of squares and T SS the total sum of squares. with n the number of observations (as returned by nobs). source 2. the R is defined as ESS/T SS. variant::Symbol) r(obj::StatisticalModel.renyientropy StatsBase. In the above formulas. r2(obj::StatisticalModel. renyientropy(p. and variant can be omitted.2. For other models.renyientropy — Method. defined as 1 − log L/ log L0.88. For a linear model.r2 — Method. STATSBASE. L0 that of the null model (the model including only the intercept). L is the likelihood of the model.90 StatsBase.89 StatsBase.

2. x.3.rmsd StatsBase. Optionally specify a random number generator rng as the first argument (defaults to Base.2]) ([1. a.70 CHAPTER 2. Examples julia> using StatsBase julia> rle([1.sample! — Method. also called a sequential sample. source . replace dictates whether sampling is performed with replacement and order dictates whether an ordered sample.2. 3]) source 2.3. The first element of the tuple is a vector of values of the input and the second is the number of consecutive occurrences of each element.1. if provided. [wv::AbstractWeights]. b.91 StatsBase.2.3. source 2. normalize=false) Return the root mean squared deviation between two optionally normalized arrays. 4. sample!([rng].rle StatsBase. [3. rmsd(a. 3.1.3.rle — Method. 2. A polyalgorithm is used for sampling. 2. rle(v) -> (vals. 2]. ordered=false) Draw a random sample of length(x) elements from an array a and store the result in x.sample! StatsBase.rmsd — Method. should be taken. lens) Return the run-length encoding of a vector as a tuple.92 StatsBase.93 StatsBase. STATSBASE 2. The root mean squared deviation is computed as sqrt(msd(a. replace=true. Sampling probabilities are proportional to the weights given in wv. b)).2.GLOBAL RNG).

[wv::AbstractWeights]) Select a single random element of a.GLOBAL RNG). wv::AbstractWeights) Select a single random integer in 1:length(wv) with probabilities propor- tional to the weights given in wv. optionally weighted sample of size n from an array a using a polyalgorithm. if provided.sample StatsBase. Optionally specify a random number generator rng as the first argument (defaults to Base. sample([rng]. ordered=false) .GLOBAL RNG). [wv::AbstractWeights]. Optionally specify a random number generator rng as the first argument (defaults to Base.95 StatsBase. should be taken.94.sample — Method. a. Sampling probabilities are proportional to the weights given in wv.97 StatsBase.SAMPLE 71 2.sample StatsBase. ordered=false) Select a random.sample — Method. [wv::AbstractWeights]. also called a sequential sample. a. a. sample([rng]. sample([rng].sample — Method.sample — Method. replace dictates whether sampling is performed with replace- ment and order dictates whether an ordered sample. replace=true.96 StatsBase. n::Integer. replace=true.sample StatsBase. Sampling probabilities are proportional to the weights given in wv. dims::Dims. source 2.94 StatsBase. Optionally specify a random number generator rng as the first argument (defaults to Base.sample StatsBase. source 2. source 2.2. STATSBASE.GLOBAL RNG). if provided. sample([rng].

n) Draw a pair of distinct integers between 1 and n without replacement. scattermat(X.GLOBAL RNG). Optionally specify a random number generator rng as the first argument (defaults to Base.samplepair — Method. Arguments • mean=nothing: a known mean value. if provided. STATSBASE Select a random. source 2. mean=nothing. also called a sequential sample. replace dictates whether sampling is performed with replacement and order dictates whether an ordered sample.scattermat — Function.GLOBAL RNG). . samplepair([rng]. should be taken. optionally weighted sample from an array a specifying the dimensions dims of the output array. which is an unnormalized covariance matrix. Optionally specify a random number generator rng as the first argument (defaults to Base.GLOBAL RNG). source 2. a) Draw a pair of distinct elements from the array a without replacement.samplepair StatsBase.72 CHAPTER 2. Specifying mean=0 indicates that the data are centered and hence there’s no need to subtract the mean. Sampling probabilities are proportional to the weights given in wv. [wv::AbstractWeights].98 StatsBase. source 2. samplepair([rng].scattermat StatsBase.99 StatsBase. vardim=1) Compute the scatter matrix. nothing indicates that the mean is unknown. and the function will compute the mean. Optionally specify a random number generator rng as the first argument (defaults to Base.samplepair — Method.100 StatsBase.samplepair StatsBase. A weighting vector wv can be specified to weight the estimate.

104 StatsBase.sem StatsBase. i. Ef- ficient equivalent of sumabs2(a .102 StatsBase. source 2. skewness(v. variables are in rows with observations in columns. m=mean(v)) Compute the standardized skewness of a real-valued array v.SEM 73 • vardim=1: the dimension along which the variables are organized. when vardim = 2.e.b). STATSBASE. the range minimum(x):maximum(x).101.e. the variables are considered columns with observations in rows.span StatsBase.span — Method. sqL2dist(a. source 2. i.sqL2dist StatsBase.101 StatsBase. source .sqL2dist — Method. The minimum and maximum of x are computed in one-pass using extrema.skewness StatsBase.sem — Method.skewness — Method. optionally spec- ifying a weighting vector wv and a center m. sqrt(var(a) / length(a)). sem(a) Return the standard error of the mean of a. b) Pn Compute the squared L2 distance between two arrays: i=1 |ai − bi |2 . When vardim = 1. span(x) Return the span of an integer array.103 StatsBase. [wv::AbstractWeights]. source 2.2. source 2.

stderr StatsBase.108 StatsBase.107 StatsBase.stderr — Method. 75th percentile. summarystats(a) Compute summary statistics for a real-valued array a. of a real-valued array.summarystats StatsBase. median.5 4” ranking. stderr(obj::StatisticalModel) Return the standard errors for the coefficients of the model. also called fractional or “1 2.tiedrank StatsBase.trim! — Method.106 StatsBase. minimum.5 2.trim! StatsBase. trim!(x. source 2. source .0. count=0) A variant of trim that modifies x in place. STATSBASE 2.summarystats — Method. Returns a SummaryStats object containing the mean.tiedrank — Method. prop=0.74 CHAPTER 2. and maxmimum. 25th percentile.105 StatsBase. source 2. source 2. Items that compare equal receive the mean of the rankings they would have been assigned under ordinal ranking. tiedrank(x) Return the tied ranking.

trim StatsBase. trimvar(x.0.109. count=0) Compute the variance of the trimmed mean of x. This function uses the Winsorized variance.trim — Method. STATSBASE. To compute the trimmed mean of x use mean(trim(x)).1}: 2 3 4 source 2.vcov StatsBase.trimvar StatsBase. Example [] julia¿ trim([1.2.111 StatsBase. The coefficient of variation is the ratio of the standard deviation to the mean.109 StatsBase.TRIM 75 2. trim(x.0.112 StatsBase.vcov — Method. as described in Wilcox (2010). prop=0.4. variation(x. optionally specifying a precomputed mean m.trimvar — Method. m=mean(x)) Return the coefficient of variation of an array x. source 2.variation StatsBase. count=0) Return a copy of x with either count or proportion prop of the high- est and lowest elements removed.variation — Method.2.3.110 StatsBase. prop=0. prop=0. to compute the variance use trimvar(x) (see trimvar). source 2.2) 3-element Array{Int64. source . vcov(obj::StatisticalModel) Return the variance-covariance matrix for the coefficients of the model.5].

prop=0. source 2. STATSBASE 2.76 CHAPTER 2. and an equal number of the highest elements replaced with the previous-highest. w::AbstractVector) Compute the weighted mean of an array v with weights w.113 StatsBase.0.winsor! — Method.1}: 2 2 3 4 4 source 2.2) 5-element Array{Int64. weights(vs) Construct a Weights vector from array vs.winsor — Method. prop=0.5]. source .2.weights — Method.weights StatsBase.115 StatsBase. prop=0. count=0) Return a copy of x with either count or proportion prop of the lowest elements of x replaced with the next-lowest. To compute the Winsorized mean of x use mean(winsor(x)). source 2. winsor(x.4.114 StatsBase.116 StatsBase. winsor!(x.wmean StatsBase.winsor! StatsBase.wmean — Method. count=0) A variant of winsor that modifies vector x in place.3. See the documentation for Weights for more details. Example [] julia¿ winsor([1.0. wmean(v.winsor StatsBase.

source 2. p) Compute the pth quantile(s) of v with weights w.wsample StatsBase. given as either a vector or an AbstractWeights vector. should be taken. wsample([rng]. also called a sequential sample.wmedian — Method.wsample! StatsBase. w.120 StatsBase. wmedian(v. w. select a random weight from w. a.118 StatsBase.117.wsample! — Method. If a is not present. STATSBASE.GLOBAL RNG). x. w) Compute the weighted median of an array v with weights w. ordered=false) Select a weighted sample from an array a and store the result in x. Optionally specify a random number generator rng as the first argument (defaults to Base. source 2. Optionally specify a random number generator rng as the first argument (defaults to Base. source .wsample — Method.119 StatsBase. replace dictates whether sampling is performed with replacement and order dictates whether an ordered sample. source 2.117 StatsBase.wquantile — Method. w) Select a weighted random sample of size 1 from a with probabilities propor- tional to the weights given in w. [a].GLOBAL RNG).wmedian StatsBase. given as either a vector or an AbstractWeights vector. replace=true.2. Sam- pling probabilities are proportional to the weights given in w.WMEDIAN 77 2.wquantile StatsBase. wsample!([rng]. wquantile(v.

wsum! StatsBase. otherwise select a random sample of size n of the weights given in w.123 StatsBase. Optionally specify a random number generator rng as the first argument (defaults to Base.wsample StatsBase.wsample — Method. replace=true. also called a sequential sample. dim. w.wsample StatsBase.122 StatsBase.121 StatsBase. wsum(v. init=true) Compute the weighted sum of A with weights w over the dimension dim and store the result in R.wsample — Method. otherwise select a random sample of size n of the weights given in w. ordered=false) Select a weighted random sample from a with probabilities proportional to the weights given in w if a is present. the sum is added to R rather than starting from zero. source 2.GLOBAL RNG). n::Integer.wsum StatsBase. wsample([rng]. source 2. source 2. wsum!(R. w. should be taken. [a]. A.wsum — Method. replace=true. ordered=false) Select a weighted random sample of size n from a with probabilities pro- portional to the weights given in w if a is present. wsample([rng].124 StatsBase.GLOBAL RNG). STATSBASE 2. [dim]) Compute the weighted sum of an array v with weights w. If init=false. dims::Dims. replace dictates whether sampling is performed with replacement and order dictates whether an ordered sample. Optionally specify a random number generator rng as the first argument (defaults to Base. w.wsum! — Method. The dimensions of the output are given by dims. [a]. source . optionally over the dimension dim. w::AbstractVector.78 CHAPTER 2.

Otherwise X is overwritten.e. The computation is broadcast- ing.zscore StatsBase.2. and size(. In particular.e. If a destination array Z is provided. source . optionally specifying a precomputed mean and standard deviation . zscore!([Z]. the scores are stored in Z and it must have the same shape as X. i) == size(X. (x − )/. [. .126 StatsBase. z-scores are the signed number of standard deviations above the mean that an observation lies. STATSBASE. i. i. they should have the same size.ZSCORE! 79 2. z-scores are the signed number of standard deviations above the mean that an observation lies. ]) Compute the z-scores of X.zscore! — Method. ) Compute the z-scores of an array X with mean and standard deviation . when and are arrays. zscore(X. (x − )/.zscore — Method. i) for each dimension. source 2.125. i) == 1 || size(. and should be both scalars or both arrays.zscore! StatsBase.125 StatsBase. X.

Chapter 3 QuantEcon 3.1 LightGraphs. Compute agent 2’s best cost-minimizing response K. Arguments • rlq::RBLQ: Instance of RBLQ type • F::Matrix{Float64}: A k x n array representing agent 1’s policy Returns • K::Matrix{Float64} : Agent’s best cost minimizing response correspond- ing to F • P::Matrix{Float64} : The value function corresponding to F source 80 .2 QuantEcon. Arguments • mc::MarkovChain : MarkovChain instance. given F .period — Method. source 3. Return the period of the Markov chain mc.F to K — Method.period LightGraphs. Returns • ::Int : Period of mc.F to K QuantEcon.

4 QuantEcon. given F .RQ sigma — Method.RQ sigma QuantEcon.RQ sigma QuantEcon. of shape (n.K to F — Method.3. Method of RQ sigma that extracts sigma from a DPSolveResult See other docstring for details source 3. • Q sigma::Array{Float64}: Transition probability matrix for sigma.3 QuantEcon. n).K TO F 81 3. QUANTECON.RQ sigma — Method. source . return the reward vector R sigma and the transition probability matrix Q sigma. Parameters • ddp::DiscreteDP : Object that contains the model parameters • sigma::Vector{Int}: policy rule vector Returns • R sigma::Array{Float64}: Reward vector for sigma. of length n.5 QuantEcon.K to F QuantEcon. Given a policy sigma. Compute agent 1’s best cost-minimizing response K. Arguments • rlq::RBLQ: Instance of RBLQ type • K::Matrix{Float64}: A k x n array representing the worst case matrix Returns • F::Matrix{Float64} : Agent’s best cost minimizing response correspond- ing to K • P::Matrix{Float64} : The value function corresponding to K source 3.3.

Compute the autocovariance function from the ARMA parameters over the integers range(num autocov) using the spectral density and the inverse Fourier transform.7 QuantEcon. QUANTECON 3. Compute periodogram from data x.6 QuantEcon. Possible values are flat. smoothing and re- coloring.ar periodogram QuantEcon. using prewhitening. Arguments • arma::ARMA: Instance of ARMA type • . hanning. mapping P into B(P ) := R − β 2 A0 P B(Q + βB 0 P B)−1 B 0 P A + βA0 P A and also returning . The D operator. Arguments • x::Array: An array containing the data to smooth • window len::Int(7): An odd integer giving the length of the window • window::AbstractString("hanning"): A string giving the window type.b operator QuantEcon.autocovariance — Method.b operator — Method. The data is fitted to an AR(1) model for prewhitening.8 QuantEcon. and the resid- uals are used to compute a first-pass periodogram with smoothing.ar periodogram — Function.autocovariance QuantEcon. or blackman Returns • w::Array{Float64}: Fourier frequencies at which the periodogram is evaluated • I w::Array{Float64}: The periodogram at frequences w source 3.82 CHAPTER 3. bartlett. hamming. The fitted coefficients are then used for recoloring.num autocov::Integer(16) : The number of autocovariances to calcu- late source 3.

9 QuantEcon. The Bellman operator.10 QuantEcon.9. Tv=ddpr.sigma Notes Updates ddpr. Apply the Bellman operator using v=ddpr.sigma inplace source .Tv and ddpr. Initial values not used and will be overwritten Returns • Tv::Vector : Updated value function vector • sigma::Vector : Updated policiy function vector source 3.v.Tv.bellman operator! — Method.BELLMAN OPERATOR! 83 F := (Q + βB 0 P B)−1 βB 0 P A Arguments • rlq::RBLQ: Instance of RBLQ type • P::Matrix{Float64} : size is n x n Returns • F::Matrix{Float64} : The F matrix as defined above • new p::Matrix{Float64} : The matrix P after applying the B operator source 3. which computes and returns the updated value func- tion T v for a value function v.bellman operator! QuantEcon. Initial value not used and will be overwritten • sigma::Vector: A buffer array to hold the policy function.3. Parameters • ddp::DiscreteDP : Object that contains the model parameters • v::Vector{T<:AbstractFloat}: The current guess of the value function • Tv::Vector{T<:AbstractFloat}: A buffer array to hold the updated value function. and sigma=ddpr.bellman operator! QuantEcon.bellman operator! — Method. QUANTECON.

bellman operator! QuantEcon.11 QuantEcon. This function will fill the input v with Tv and the input sigma with the corresponding policy rule. Parameters • ddp::DiscreteDP: The ddp model • v::Vector: The current guess of the value function Returns • Tv::Vector : Updated value function vector source 3. Arguments .84 CHAPTER 3. x2] via bisection.bellman operator — Method. which computes and returns the updated value func- tion T v for a given value function v.12 QuantEcon.bisect — Method. This array will be overwritten • sigma::Vector: A buffer array to hold the policy function.bisect QuantEcon. Parameters • ddp::DiscreteDP: The ddp model • v::Vector{T<:AbstractFloat}: The current guess of the value function. Initial values not used and will be overwritten Returns • Tv::Vector: Updated value function vector • sigma::Vector{T<:Integer}: Policy rule source 3.13 QuantEcon. Find the root of the f on the bracketing inverval [x1. The Bellman operator. which computes and returns the updated value func- tion T v for a given value function v.bellman operator! — Method.bellman operator QuantEcon. The Bellman operator. QUANTECON 3.

brent — Method.xtol::Float64(1e-12): The routine converges when a root is known to lie within xtol of the value return.c source 3. x2] does not form a bracketing interval • Throws a ConvergenceError if the maximum number of iterations is ex- ceeded References Matches bisect function from scipy/scipy/optimize/Zeros/bisect. Find the root of the f on the bracketing inverval [x1. Should be 0 Returns • x::T: The found root Exceptions • Throws an ArgumentError if [x1.14.rtol::Float64(2*eps()):The routine converges when a root is known to lie within rtol times the value returned of the value returned. Should be >= 0.maxiter::Int(500): Maximum number of bisection iterations • . The routine modifies this to take into account the relative precision of doubles. Arguments • f::Function: The function you want to bracket • x1::T: Lower border for search interval • x2::T: Upper border for search interval • .brent QuantEcon. . • .14 QuantEcon. The routine modifies this to take into account the relative precision of doubles.BRENT 85 • f::Function: The function you want to bracket • x1::T: Lower border for search interval • x2::T: Upper border for search interval • . QUANTECON.maxiter::Int(500): Maximum number of bisection iterations • . Should be >= 0.3.xtol::Float64(1e-12): The routine converges when a root is known to lie within xtol of the value return. x2] via brent’s algo.

rtol::Float64(2*eps()):The routine converges when a root is known to lie within rtol times the value returned of the value returned. Otherwise it is the original Brent’s algorithm. Should be >= 0.15 QuantEcon.brenth — Method. Should be 0 Returns • x::T: The found root Exceptions .maxiter::Int(500): Maximum number of bisection iterations • .rtol::Float64(2*eps()):The routine converges when a root is known to lie within rtol times the value returned of the value returned. x2] does not form a bracketing interval • Throws a ConvergenceError if the maximum number of iterations is ex- ceeded References Matches brentq function from scipy/scipy/optimize/Zeros/bisectq. • . x2] via modified brent This routine uses a hyperbolic extrapolation formula instead of the standard inverse quadratic formula. Should be 0 Returns • x::T: The found root Exceptions • Throws an ArgumentError if [x1. QUANTECON • . The routine modifies this to take into account the relative precision of doubles. Find a root of the f on the bracketing inverval [x1. Arguments • f::Function: The function you want to bracket • x1::T: Lower border for search interval • x2::T: Upper border for search interval • .brenth QuantEcon. as implemented in the brent function.c source 3.xtol::Float64(1e-12): The routine converges when a root is known to lie within xtol of the value return.86 CHAPTER 3.

a j x n array • x0::Vector{Float64} : The initial condition for state . Returns • ::Vector{Vector{Int}} : Vector of vectors that describe the communi- cation classes of mc.. Equilvalent to reduce(kron. ckron(arrays::AbstractArray. source 3.. Find the communication classes of the Markov chain mc. which is t β t x0t K 0 Kxt P with xt+1 = (A − BF + CK)xt .ckron QuantEcon. Arguments • mc::MarkovChain : MarkovChain instance.compute deterministic entropy QuantEcon. compute the value of deterministic entropy.communication classes QuantEcon.ckron — Function.16. arrays) source 3. Given K and F . Arguments • rlq::RBLQ: Instance of RBLQ type • F::Matrix{Float64} The policy function.c source 3.18 QuantEcon.16 QuantEcon.) Repeatedly apply kronecker products to the arrays.compute deterministic entropy — Method. x2] does not form a bracketing interval • Throws a ConvergenceError if the maximum number of iterations is ex- ceeded References Matches brenth function from scipy/scipy/optimize/Zeros/bisecth.17 QuantEcon. a k x n array • K::Matrix{Float64} The worst case matrix.communication classes — Method.CKRON 87 • Throws an ArgumentError if [x1.3. QUANTECON.

QUANTECON Returns • e::Float64 The deterministic entropy source 3. 2 for warning and convergence messages during iteration) • . Arguments • T: A function representing the operator T • v::TV: The initial condition.88 CHAPTER 3.0. Provided that T is a contraction mapping or similar. 0.verbose(2): Level of feedback (0 for no output. ) = 4.compute greedy! — Method.0 * * x * (1.19 QuantEcon.20 QuantEcon. Compute the v-greedy policy Parameters .3).print skip(10) : if verbose == 2.x) xs tar = computef ixedp oint(x− > T (x.compute fixed point QuantEcon.err tol(1e-3): Stopping tolerance for iterations • .T^k v < err tol or max iter iterations has been exceeded. An object of type T V • .4)(4 − 1)/(4) source 3. Will terminate either when T^{k+1}(v) .compute greedy! QuantEcon.max iter(50): Maximum number of iterations • .0 .compute fixed point — Method. the return value will be an approximation to the fixed point of T . Has type T V Example [] using QuantEcon T(x. where T is an operator (function) and v is an initial guess for the fixed point. 1 for warnings only. Repeatedly apply a function to search for a fixed point Approximates T v. how many iterations to apply be- tween print messages Returns • ‘::TV’: The fixed point of the operator T .

compute greedy QuantEcon.compute sequence — Function. lq. of lengthn‘ source 3. If lq instance is finite horizon type.capT) Returns • x path::Matrix{Float64} : An n x T+1 matrix. assuming in- novation N (0. the sequenes are returned only for min(ts length. 1) Arguments • lq::LQ : instance of LQ type • x0::ScalarOrArray: initial state • ts length::Integer(100) : maximum number of periods for which to return process. Compute the v-greedy policy.21 QuantEcon.3. Arguments • v::Vector Value function vector of length n • ddp::DiscreteDP Object that contains the model parameters Returns • sigma:: v-greedy policy vector.compute greedy — Method. QUANTECON.sigma and ddpr.21.compute sequence QuantEcon. Compute and return the optimal state and control sequence.Tv in place source 3. where the t-th column represents xt .22 QuantEcon.COMPUTE GREEDY 89 • ddp::DiscreteDP : Object that contains the model parameters • ddpr::DPSolveResult : Object that contains result variables Returns • sigma::Vector{Int} : Array containing v-greedy policy rule Notes modifies ddpr.

C*N(0.90 CHAPTER 3.23 QuantEcon.d operator QuantEcon. Compute a finite-state Markov chain approximation to a VAR(1) process of the form 1 yt+1 = b + Byt + Ψ 2 t+1 where t+1 is an vector of independent standard normal innovations of length M [] P. AbstractMatrix} : M x M matrix of impact coefficients • Psi::Union{Real. X = discretev ar(b. QUANTECON • u path::Matrix{Float64} : A k x T matrix.1) source 3. N m. The D operator.discrete var — Function. mapping P into D(P ) := P + P C(θI − C 0 P C)−1 C 0 P Arguments • rlq::RBLQ: Instance of RBLQ type • P::Matrix{Float64} : size is n x n Returns • dP::Matrix{Float64} : The matrix P after applying the D operator source 3. AbstractVector} : constant vector of length M.discrete var QuantEcon. where the t-th column rep- resents ut • w path::Matrix{Float64} : A n x T+1 matrix.d operator — Method. P si. nm oments. AbstractMatrix} : M x M variance-covariance ma- trix of the innovations . ns igmas) Arguments • b::Union{Real. method. M=1 corresponds scalar case • B::Union{Real. B.24 QuantEcon. where the t-th column represents lq.

651-683. Each row corresponds to a discrete conditional probability distribution over the state M-tuples in X • X : M x Nm^M matrix of states. • Future updates will allow for singular variance-covariance matrices and sparse grid specifications. n sigmas is used to determine the number of unconditional standard deviations used to set the endpoints of the grid. & Toda. For this reason it is recommended that this code not be used for problems of more than about 4 or 5 dimen- sions due to curse of dimensionality issues.3. NOTE: Quantile() and Quadrature() are not supported now. QUANTECON. Accepted inputs are Even().24. • n sigmas::Real : If the Even() option is specified. Each column corresponds to an M-tuple of values which correspond to the state associated with each row of P NOTES • discrete var only constructs tensor product grids where each dimension contains the same number of points. A.DISCRETE VAR 91 – discrete var only accepts non-singular variance-covariance matri- ces. (2017).” Quantitative Economics. source . Reference • Farmer. Returns • P : Nm^M x Nm^M probability transition matrix. A. The default is 2. nonGaus- sian Markov processes with exact conditional moments. Psi. “Discretizing nonlinear. L. • Nm::Integer > 3 : Desired number of discrete points in each dimension Optional • n moments::Integer : Desired number of moments to match. Please see the paper for more details.. The default is sqrt(Nm-1). • method::VAREstimationMethod : Specify the method used to determine the grid points. 8(2). E.

. • nodes::Array: Quadrature nodes • weights::Array: Quadrature nodes • args..kwargs. Approximate the integral of f. Arguments • f::Function: The function you want to bracket • x1::T: Lower border for search interval • x2::T: Upper border for search interval • n::Int(50): The number of sub-intervals to divide [x1.(Void): additional keyword arguments to pass to f Returns • out::Float64 : The scalar that approximates integral of f on the hyper- cube formed by [a.divide bracket — Method. nroot will be set to the number of bracketing pairs found.26 QuantEcon. given quadrature nodes and weights Arguments • f::Function: A callable function that is to be approximated over the domain spanned by nodes.do quad QuantEcon. subdivide the interval into n equally spaced segments.25 QuantEcon. Given a function f defined on the interval [x1.nroot] and xb2[1.nroot] will be filled sequentially with any bracketing pairs that are found.. the arrays xb1[1. If it is positive.(Void): additional positional arguments to pass to f • .. QUANTECON 3. x2] into Returns • x1b::Vector{T}: Vector of lower borders of bracketing intervals • x2b::Vector{T}: Vector of upper borders of bracketing intervals References This is zbrack from Numerical Recepies Recepies in C++ source 3.92 CHAPTER 3. b] source .divide bracket QuantEcon. and search for zero crossings of the function. x2]..do quad — Method..

edu/˜cshalizi/462/lectures/06/markov-mle. .evaluate F QuantEcon. only states that are ob- served in the history appear in the estimated Markov chain.3.cmu. Note: Because of the estimation procedure used. For more info. Given a fixed policy F . .estimate mc discrete QuantEcon.com/questions/47685/calculating-log-likelihood- for-given-mle-markov-chains Arguments • X::Vector{T} : Simulated history of Markov states Returns • mc::MarkovChain{T} : A Markov chain holding the state values and tran- sition matrix source 3. s2 . . QUANTECON. sN with s1 < s2 < . Given a history of observations. For xt = si and xt−1 = sj . Furthermore.evaluate F — Method. {X}Tt=0 with xt ∈ S∀t.j element of the stochastic matrix. .27 QuantEcon.pdf • https://stats.ESTIMATE MC DISCRETE 93 3. let P (xt |xt−1 ) be defined as pi.27. . .stat. . Accepts the simulation of a discrete state Markov chain and estimates the transition probabilities Let S = s1 . Arguments . . we would like to estimate the transition probabilities in P with pij as the ith row and jth column of P . < sN be the discrete states of a Markov chain.estimate mc discrete — Method. let P be the corresponding stochastic transition matrix. refer to: • http://www. P ) = Prob(x1 ) P (xt |xt−1 ) t=2 The maximum likelihood estimate is then just given by the number of times a transition from si to sj is observed divided by the number of times si was observed.stackexchange. with the interpretation u = −F x. The likelihood function is then given by T Y L({X}t . It can’t divine whether there are unobserved states in the original Markov chain. this function com- putes the matrix PF and constant dF associated with discounted cost JF (x) = x0 PF x + dF .28 QuantEcon.

Parameters • ddp::DiscreteDP : Object that contains the model parameters • sigma::Vector{T<:Integer} : Policy rule vector Returns • v sigma::Array{Float64} : Value vector of sigma.evaluate policy — Method. a k x n array Returns • P F::Matrix{Float64} : Matrix for discounted cost • d F::Float64 : Constant for discounted cost • K F::Matrix{Float64} : Worst case policy • O F::Matrix{Float64} : Matrix for discounted entropy • o F::Float64 : Constant for discounted entropy source 3.29 QuantEcon.evaluate policy — Method.30 QuantEcon. QUANTECON • rlq::RBLQ: Instance of RBLQ type • F::Matrix{Float64} : The policy function. source .evaluate policy QuantEcon.94 CHAPTER 3.evaluate policy QuantEcon. of length n. Method of evaluate policy that extracts sigma from a DPSolveResult See other docstring for details source 3. Compute the value of a policy.

expand bracket — Method. which becomes the time t + 1 prior Arguments • k::Kalman An instance of the Kalman filter source . Updates the moments of the time t filtering distribution to the moments of the predictive distribution.32 QuantEcon.filtered to forecast! — Method.fac::Float64(1.3.EXPAND BRACKET 95 3. QUANTECON.31.31 QuantEcon. the routine expands the range geometrically until a root is bracketed by the returned values x1 and x2 (in which case zbrac returns true) or until the range becomes unacceptably large (in which case a ConvergenceError is thrown).ntry::Int(50): The maximum number of expansion iterations • .filtered to forecast! QuantEcon.expand bracket QuantEcon.6): Expansion factor (higher larger interval size jumps) Returns • x1::T: The lower end of an actual bracketing interval • x2::T: The upper end of an actual bracketing interval References This method is zbrac from numerical recipies in C++ Exceptions • Throws a ConvergenceError if the maximum number of iterations is ex- ceeded source 3. Given a function f and an initial guessed range x1 to x2. Arguments • f::Function: The function you want to bracket • x1::T: Initial guess for lower border of bracket • x2::T: Initial guess ofr upper border of bracket • .

wikipedia. gridmake!(out::AbstractMatrix.gridmake — Function.gridmake QuantEcon. out must have size prod(map(length. Applies Golden-section search to search for the maximum of a function in the interval (a.) Expand one or more vectors (or matrices) into a matrix where rows span the cartesian product of combinations of the input arrays.gridmake! QuantEcon. gridmake(arrays::Union{AbstractVector.96 CHAPTER 3. but fills a pre-populated array.35 QuantEcon. arrays). Each column of the input arrays will correspond to one column of the output matrix. 20]. arrays::AbstractVector.AbstractMatrix}.golden method — Method..gridmake! — Method. z = [100. 3].) Like gridmake. The first array varies the fastest (see example) Example julia> x = [1.org/wiki/Golden-section search source 3.golden method QuantEcon. QUANTECON 3..2}: 1 10 100 2 10 100 3 10 100 1 20 100 2 20 100 3 20 100 1 10 200 2 10 200 3 10 200 1 20 200 2 20 200 3 20 200 source 3. length(arrays)) source . 200]. z) 12x3 Array{Int64. y... julia> gridmake(x.34 QuantEcon. b) https://en.33 QuantEcon. y = [10. 2.

impulse response — Method. Taksar and D. and in par- ticular. if A is irreducible. where only the off-diagonal entries of A are used as the input data. Stewart.. Dii = j Aij for all i). up to normalization) nonzero solution exists corresponding to each reccurent class of A. Get the impulse response corresponding to our model. I. Probability.36 QuantEcon. Must be of shape n x n. One (and only one. Chapter 10. For a nice exposition of the algorithm. This routine implements the Grassmann-Taksar-Heyman (GTH) algorithm (Grassmann.gth solve — Method. given a Metzler matrix (square matrix whose off-diagonal entries are all nonnegative) A. there is a unique solution. Arguments • arma::ARMA: Instance of ARMA type .36. This routine computes the stationary distribution of an irreducible Markov transition matrix (stochastic matrix) or transition rate matrix (generator ma- trix) A. J. Markov Chains. source 3.37 QuantEcon.” Operations Re- search (1985). Grassmann. Princeton University Press. Queues. References • W. Arguments • A::Matrix{T} : Stochastic matrix or generator matrix. The solu- tion is normalized so that its 1-norm equals one. see Stewart (2009). when there are more than one solution. QUANTECON. the routine returns the solution that contains in its support the first index i such that no path connects i to any index larger than i. M. “Regenerative Anal- ysis and Steady State Distributions for Markov Chains. 2009. K. a numerically stable variant of Gaussian elimination. and Hey- man 1985). 1107-1116.e. More generally. wherePD is the diagonal matrix for which the rows of A − D sum to zero (i. and Simulation.gth solve QuantEcon. Heyman.impulse response QuantEcon.3. this routine solves for a nonzero solution x to x(A − D) = 0. Returns • x::Vector{T} : Stationary distribution of A. Taksar. • W. P.GTH SOLVE 97 3.

is aperiodic QuantEcon. Returns • ::Bool source . Returns • ::Bool source 3.* sin.1.is aperiodic — Method.1 .is irreducible — Method.interp QuantEcon. Indicate whether the Markov chain mc is irreducible.98 CHAPTER 3. 0.39 QuantEcon. function_vals::AbstractVector) Linear interpolation in one dimension Examples [] breaks = cumsum(0.2.interp — Method. QUANTECON • . Arguments • mc::MarkovChain : MarkovChain instance.* rand(20)) vals = 0.impulse length::Integer(30): Length of horizon for calcluating im- pulse reponse.3]) source 3.40 QuantEcon. vals) Do interpolation by treating ‘li‘ as a function you can pass scalars to li(0.2) use broadcasting to evaluate at multiple points li. 0.1 . Must be at least as long as the p fields of arma Returns • psi::Vector{Float64}: psi[j] is the response at lag j of the impulse response. interp(grid::AbstractVector.([0.38 QuantEcon.is irreducible QuantEcon. We take psi[1] as unity. Indicate whether the Markov chain mc is aperiodic. source 3. Arguments • mc::MarkovChain : MarkovChain instance.(breaks) li = in- terp(breaks.

is stable QuantEcon.IS STABLE 99 3. Test for stability of linear state space system. Just checks that eigenvalues are less than 1 in absolute value.p(l.3.is stable — Method. A vectorized function that returns the value of the look ahead estimate at the values in the array y. y) Returns • psi vals::Vector: Density at (x. Arguments • l::LAE: Instance of LAE type • y::Array: Array that becomes the y in l.lae est — Method.41 QuantEcon. First removes the constant row and column. Arguments • lss::LSS The linear state space system Returns • stable::Bool Whether or not the system is stable source 3. Arguments • A::Matrix The matrix we want to check Returns • stable::Bool Whether or not the matrix is stable source 3. General function for testing for stability of matrix A. QUANTECON.42 QuantEcon. y) source .43 QuantEcon.lae est QuantEcon.41.x.is stable QuantEcon.is stable — Method.

m quadratic sum — Method. Create an iterator to calculate the population mean and variance-convariance matrix for both xt and yt . Computes the quadratic sum ∞ X 0 V = Aj BAj j=0 V is computed by solving the corresponding discrete lyapunov equation using the doubling algorithm. mu y.moment sequence QuantEcon.mu 0.m quadratic sum QuantEcon.46 QuantEcon. See the documentation of solve discrete lyapunov for more information. Number of states in the Markov chain mc source .Sigma 0). Sigma x. Arguments • lss::LSS An instance of the Gaussian linear state space model source 3.n states QuantEcon.45 QuantEcon.n states — Method. Arguments • A::Matrix{Float64} : An n x n matrix as described above. Sigma y) for the next period.moment sequence — Method.100 CHAPTER 3. QUANTECON 3. Each iteration produces a 4-tuple of items (mu x. We assume in order for convergence that the eigenvalues of B have moduli bounded by unity • max it::Int(50) : Maximum number of iterations Returns • gamma1::Matrix{Float64} : Represents the value V source 3. starting at the initial condition (self. self.44 QuantEcon. We assume in order for convergence that the eigenvalues of A have moduli bounded by unity • B::Matrix{Float64} : An n x n matrix as described above.

size (n. Compute the limit of a Nash linear quadratic dynamic game. k 1) • M2 : As above. k 2) • S1 : As above. size (k 2.nnash QuantEcon. n) • R2 : As above. k 2) • R1 : As above. size (n.tol::Float64(1e-8) : Tolerance level for convergence • .NNASH 101 3.0) Discount rate • . size (n. n) • Q1 : As above.3. k 2) • W1 : As above. k 1) • B2 : As above. size (k 2. QUANTECON.beta::Float64(1.47. k 2) • . size (k 1. n) • B1 : As above. k 1) • S2 : As above. k 1) • W2 : As above. size (k 2. size (k 1.nnash — Method. k 2) • M1 : As above. size (n. Player i minimizes ∞ X (x0t ri xt + 2x0t wi uit + u0it qi uit + u0jt si ujt + 2u0jt mi uit ) t=1 subject to the law of motion xt+1 = Axt + b1 u1t + b2 u2t and a perceived control law uj (t) = −fj xt for the other player. The solution computed in this routine is the fi and pi of the associated double optimal linear regulator problem.max iter::Int(1000) : Maximum number of iterations allowed Returns . Arguments • A : Corresponds to the above equation. size (n. size (k 1. size (n.47 QuantEcon. k 1) • Q2 : As above. should be of size (n.

n) matrix representing the steady-state so- lution to the associated discrete matrix riccati equation for agent 2 source 3. Arguments • x::Array: An array containing the data to smooth • window len::Int(7): An odd integer giving the length of the window • window::AbstractString("hanning"): A string giving the window type. QUANTECON • F1::Matrix{Float64}: (k 1.48 QuantEcon. Computes the periodogram n−1 1 X I(w) = | xt eitw |2 n t=0 at the Fourier frequences wj := 2 πj n . j = 0.102 CHAPTER 3. using the fast Fourier transform. n − 1. bartlett. hanning. Possible values are flat. If a window type is given then smoothing is performed. or blackman Returns • w::Array{Float64}: Fourier frequencies at which the periodogram is evaluated • I w::Array{Float64}: The periodogram at frequences w source . . n) matrix representing feedback law for agent 2 • P1::Matrix{Float64}: (n. Only the frequences wj in [0. hamming. n) matrix representing the steady-state so- lution to the associated discrete matrix ticcati equation for agent 1 • P2::Matrix{Float64}: (n.periodogram QuantEcon. . π] and corresponding values I(wj ) are returned. . .periodogram — Function. n) matrix representing feedback law for agent 1 • F2::Matrix{Float64}: (k 2.

References Miranda. Mario J. Arguments • n::Union{Int.qnwbeta QuantEcon.49 QuantEcon. source .50 QuantEcon. Applied Computational Economics and Finance. cur sigma) of the time t prior to the time t filtering distribution.49. Vector{Real}} : First parameter of the beta distribu- tion. QUANTECON.qnwbeta — Method.prior to filtered! — Method.prior to filtered! QuantEcon. the the scalar parameter is repeated n times. Vector{Int}} : Number of desired nodes along each di- mension • a::Union{Real.3.\Sigma G’ (G \Sigma G’ + R)^{-1} G \Sigma $$ Arguments • k::Kalman An instance of the Kalman filter • y The current measurement source 3. The updates are according to $$ ˆF = + ΣG0 (GΣG0 + R)ˆ{−1}(y − Gx̂)n \Sigma^F = \Sigma . Computes nodes and weights for beta distribution. and Paul L Fackler. MIT Press. along each dimension • b::Union{Real. along each dimension Returns • nodes::Array{Float64} : An array of quadrature nodes • weights::Array{Float64} : An array of corresponding quadrature weights Notes If any of the parameters to this function are scalars while others are vectors of length n. Vector{Real}} : Second parameter of the beta distri- bution.PRIOR TO FILTERED! 103 3. using current measurement yt . Updates the moments (cur x hat. 2002.

Computes multivariate Guass-Checbychev quadrature nodes and weights. MIT Press. Applied Computational Economics and Finance. Vector{Real}} : Lower endpoint along each dimension • b::Union{Real. Vector{Real}} : Upper endpoint along each dimension • kind::AbstractString("N"): One of the following: – N . Vector{Real}} : Upper endpoint along each dimension Returns • nodes::Array{Float64} : An array of quadrature nodes • weights::Array{Float64} : An array of corresponding quadrature weights Notes If any of the parameters to this function are scalars while others are vectors of length n.qnwequi QuantEcon. Vector{Real}} : Lower endpoint along each dimension • b::Union{Real. 2002.qnwcheb QuantEcon.Haber – R .pseudo Random . Vector{Int}} : Number of desired nodes along each di- mension • a::Union{Real.52 QuantEcon. and Paul L Fackler. Vector{Int}} : Number of desired nodes along each di- mension • a::Union{Real. the the scalar parameter is repeated n times. Mario J. Arguments • n::Union{Int.Weyl – H . QUANTECON 3.qnwequi — Function. References Miranda. source 3.qnwcheb — Method. Generates equidistributed sequences with property that averages value of integrable function evaluated over the sequence converges to the integral as n goes to infinity.Neiderreiter (default) – W . Arguments • n::Union{Int.51 QuantEcon.104 CHAPTER 3.

qnwgamma — Function. 2002. Vector{Real}} : Shape parameter of the gamma dis- tribution. Mario J. Vector{Real}} : Scale parameter of the gamma distri- bution. 2002. the the scalar parameter is repeated n times. and Paul L Fackler.QNWGAMMA 105 Returns • nodes::Array{Float64} : An array of quadrature nodes • weights::Array{Float64} : An array of corresponding quadrature weights Notes If any of the parameters to this function are scalars while others are vectors of length n. Default is 1 • b::Union{Real.53. References Miranda. Must be positive.qnwgamma QuantEcon.3.53 QuantEcon. References Miranda. Default is 1 Returns • nodes::Array{Float64} : An array of quadrature nodes • weights::Array{Float64} : An array of corresponding quadrature weights Notes If any of the parameters to this function are scalars while others are vectors of length n. source . Must be positive. MIT Press. Vector{Int}} : Number of desired nodes along each di- mension • a::Union{Real. along each dimension. and Paul L Fackler. along each dimension. Mario J. Applied Computational Economics and Finance. Computes nodes and weights for beta distribution Arguments • n::Union{Int. Applied Computational Economics and Finance. QUANTECON. source 3. the the scalar parameter is repeated n times. MIT Press.

MIT Press. Arguments • n::Union{Int. References Miranda.qnwlogn — Method. the the scalar parameter is repeated n times. Vector{Int}} : Number of desired nodes along each di- mension • mu::Union{Real. 2002.54 QuantEcon. QUANTECON 3. Mario J.qnwlege — Method. Computes quadrature nodes and weights for multivariate uniform distribu- tion Arguments • n::Union{Int.55 QuantEcon. Applied Computational Economics and Finance. Vector{Real}} : Mean along each dimension • sig2::Union{Real. Vector{Real}} : Lower endpoint along each dimension • b::Union{Real. Computes multivariate Guass-Legendre quadrature nodes and weights. Vector{Real}. and Paul L Fackler.106 CHAPTER 3. source 3. Vector{Real}} : Upper endpoint along each dimension Returns • nodes::Array{Float64} : An array of quadrature nodes • weights::Array{Float64} : An array of corresponding quadrature weights Notes If any of the parameters to this function are scalars while others are vectors of length n.qnwlogn QuantEcon.qnwlege QuantEcon. Vector{Int}} : Number of desired nodes along each di- mension • a::Union{Real. Matrix{Real}}(eye(length(n))) : Covariance structure Returns • nodes::Array{Float64} : An array of quadrature nodes • weights::Array{Float64} : An array of corresponding quadrature weights .

I try to describe them here. source 3. n or mu can be a vector or a scalar. then the number of repeats is inferred from sig2. Applied Computational Economics and Finance.56.56 QuantEcon. vector or scalar. it is treated as the covariance matrix. Mario J. and Paul L Fackler. then 1d nodes are computed. Mario J. 2002. it is considered the diagonal of a diagonal covariance matrix. If it is a matrix.qnwnorm QuantEcon. and Paul L Fackler.3. MIT Press. source . sig2 can be a matrix. MIT Press.qnwnorm — Method. Vector{Real}. 2002. If just one is a scalar the other is repeated to match the length of the other. If all 3 are scalars. Vector{Int}} : Number of desired nodes along each di- mension • mu::Union{Real. QUANTECON. If it is a scalar it is repeated along the diagonal as many times as necessary. Computes nodes and weights for multivariate normal distribution. Vector{Real}} : Mean along each dimension • sig2::Union{Real. If it is a vector. Matrix{Real}}(eye(length(n))) : Covariance structure Returns • nodes::Array{Float64} : An array of quadrature nodes • weights::Array{Float64} : An array of corresponding quadrature weights Notes This function has many methods.QNWNORM 107 Notes See also the documentation for qnwnorm References Miranda. If both are scalars. Applied Computational Economics and Finance. Arguments • n::Union{Int. mu and sig2 are treated as the mean and variance of a 1d normal distribution References Miranda. where the number of repeats is determined by the length of either n and/or mu (which ever is a vector).

Applied Computational Economics and Finance. Vector{Real}} : Lower endpoint along each dimension • b::Union{Real. References Miranda. the the scalar parameter is repeated n times.qnwsimp — Method. QUANTECON 3. Computes multivariate Simpson quadrature nodes and weights.qnwtrap QuantEcon. Computes multivariate trapezoid quadrature nodes and weights. Applied Computational Economics and Finance. Vector{Real}} : Lower endpoint along each dimension • b::Union{Real. Vector{Int}} : Number of desired nodes along each di- mension • a::Union{Real. References Miranda. Mario J. MIT Press. source 3.58 QuantEcon. 2002.qnwtrap — Method. Vector{Real}} : Upper endpoint along each dimension Returns • nodes::Array{Float64} : An array of quadrature nodes • weights::Array{Float64} : An array of corresponding quadrature weights Notes If any of the parameters to this function are scalars while others are vectors of length n. Arguments • n::Union{Int. Vector{Real}} : Upper endpoint along each dimension Returns • nodes::Array{Float64} : An array of quadrature nodes • weights::Array{Float64} : An array of corresponding quadrature weights Notes If any of the parameters to this function are scalars while others are vectors of length n.qnwsimp QuantEcon. and Paul L Fackler. MIT Press.108 CHAPTER 3. Vector{Int}} : Number of desired nodes along each di- mension • a::Union{Real. source . the the scalar parameter is repeated n times.57 QuantEcon. Mario J. Arguments • n::Union{Int. and Paul L Fackler. 2002.

using n[i] points.59.quadrect — Function. .59 QuantEcon. Arguments • n::Union{Int. Mario J. This should be a function that accepts as its first argument a matrix representing points along each dimension (each dimension is a column). Computes quadrature nodes and weights for multivariate uniform distribu- tion. Other arguments that need to be passed to the function are caught by args. .60 QuantEcon. Applied Computational Economics and Finance.quadrect QuantEcon. and ‘kwargs. Integrate the d-dimensional function f on a rectangle with lower and upper bound for dimension i defined by a[i] and b[i].qnwunif QuantEcon. Vector{Int}} : Number of desired nodes along each di- mension • a::Union{Real. Vector{Real}} : Lower endpoint along each dimension • b::Union{Real. “ • n::Union{Int. QUANTECON. Vector{Real}} : Upper endpoint along each dimension • kind::AbstractString("lege") Specifies which type of integration to perform. the the scalar parameter is repeated n times. Valid values are: .qnwunif — Method. source 3.3. Vector{Int}} : Number of desired nodes along each di- mension • a::Union{Real.. Vector{Real}} : Upper endpoint along each dimension Returns • nodes::Array{Float64} : An array of quadrature nodes • weights::Array{Float64} : An array of corresponding quadrature weights Notes If any of the parameters to this function are scalars while others are vectors of length n. 2002. and Paul L Fackler. References Miranda. MIT Press. respectively. Vector{Real}} : Lower endpoint along each dimension • b::Union{Real..QNWUNIF 109 3. Arguments • f::Function The function to integrate over.

.random discrete dp — Function. • num actions::Integer : Number of actions.. b] References Miranda.110 CHAPTER 3. source .k::Union{Integer. • beta::Union{Float64.. Generate a DiscreteDP randomly.. Mario J. • scale::Real(1) : Standard deviation of the normal distribution for the reward values. Void}(nothing) : Discount factor. 2002. source 3. Applied Computational Economics and Finance.kwargs. Equal to num states if not specified. and Paul L Fackler. Randomly chosen from [0. MIT Press. • . Void}(nothing) : Number of possible next states for each state-action pair. Arguments • num states::Integer : Number of states. QUANTECON – "lege" : Gauss-Legendre – "cheb" : Gauss-Chebyshev – "trap" : trapezoid rule – "simp" : Simpson rule – "N" : Neiderreiter equidistributed sequence – "W" : Weyl equidistributed sequence – "H" : Haber equidistributed sequence – "R" : Monte Carlo – args.(Void): additional keyword arguments to pass to f Returns • out::Float64 : The scalar that approximates integral of f on the hyper- cube formed by [a. 1) if not specified. Returns • ddp::DiscreteDP : An instance of DiscreteDP.random discrete dp QuantEcon.(Void): additional positional arguments to pass to f – . The reward values are drawn from the normal distribution with mean 0 and standard deviation scale.61 QuantEcon.

Return a randomly sampled MarkovChain instance with n states. Returns • mc::MarkovChain : MarkovChain instance. Arguments • n::Integer : Number of states. . where each state has k states with positive transition probability. Examples [] julia¿ using QuantEcon julia¿ mc = randomm arkovc hain(3. • k::Union{Integer.random markov chain QuantEcon.2} :0.RANDOM MARKOV CHAIN 111 3.random markov chain — Method. Returns • mc::MarkovChain : MarkovChain instance.2)DiscreteM arkovChainstochasticmatrix :3x3Array{F loat64.2} :0. Return a randomly sampled n x n stochastic matrix with k nonzero entries for each row.62. Set to n if none specified.63 QuantEcon. QUANTECON.random markov chain QuantEcon.62 QuantEcon. Void}(nothing) : Number of nonzero entries in each column of the matrix.random markov chain — Method. Arguments • n::Integer : Number of states.random stochastic matrix QuantEcon.2811880. Arguments • n::Integer : Number of states. Examples [] julia¿ using QuantEcon julia¿ mc = randomm arkovc hain(3)DiscreteM arkovChainstochasticmatrix :3x3Array{F loat64.3691240.64 QuantEcon. source 3.random stochastic matrix — Function.61 source 3. Return a randomly sampled MarkovChain instance with n states.3.

• t::Int = 10 The period that we want to replicate values for. .66 QuantEcon. QUANTECON Returns • p::Array : Stochastic matrix.replicate — Function.remove constants — Method. Find the recurrent classes of the Markov chain mc.65 QuantEcon. source 3. Arguments • lss::LSS The linear state space system Returns • A::Matrix The matrix A with constant row and column removed source 3.112 CHAPTER 3. Simulate num reps observations of xT and yT given x0 ∼ N (µ0 . source 3.recurrent classes — Method. that correspond to the constant term in a LSS system and removes them to get the matrix that needs to be checked for stability.67 QuantEcon. Arguments • mc::MarkovChain : MarkovChain instance. Arguments • lss::LSS An instance of the Gaussian linear state space model. Σ0 ). Returns • ::Vector{Vector{Int}} : Vector of vectors that describe the recurrent classes of mc.replicate QuantEcon. Finds the row and column.recurrent classes QuantEcon.remove constants QuantEcon. if any.

where the j-th column is the j th observation of yT source 3. QUANTECON. x2] does not form a bracketing interval • Throws a ConvergenceError if the maximum number of iterations is ex- ceeded References Matches ridder function from scipy/scipy/optimize/Zeros/ridder.68 QuantEcon. Find a root of the f on the bracketing inverval [x1.ridder — Method. The routine modifies this to take into account the relative precision of doubles.68.c source . • . where the j-th column is the j th observation of xT • y::Matrix An k x num reps matrix.3.maxiter::Int(500): Maximum number of bisection iterations • . Should be >= 0. x2] via ridder algo Arguments • f::Function: The function you want to bracket • x1::T: Lower border for search interval • x2::T: Upper border for search interval • .xtol::Float64(1e-12): The routine converges when a root is known to lie within xtol of the value return.ridder QuantEcon.RIDDER 113 • num reps::Int = 100 The number of replications we want Returns • x::Matrix An n x num reps matrix.rtol::Float64(2*eps()):The routine converges when a root is known to lie within rtol times the value returned of the value returned. Should be 0 Returns • x::T: The found root Exceptions • Throws an ArgumentError if [x1.

tol::Real(1e-8) The tolerance for convergence . based around straightforward iteration with the robust Bellman operator. QUANTECON 3.robust rule simple QuantEcon. For more information see the docstring of that method.n)) : The initial guess for the value function matrix • .max iter::Int(80): Maximum number of iterations that are allowed • . The algorithm here tricks the problem into a stacked LQ problem. The optimal con- trol with observed state is ut = −F xt 0 And the value function is −x P x Arguments • rlq::RBLQ: Instance of RBLQ type Returns • F::Matrix{Float64} : The optimal control matrix from above • P::Matrix{Float64} : The positive semi-definite matrix defining the value function • K::Matrix{Float64} : the worst-case shock matrix K.114 CHAPTER 3.robust rule simple — Function. where wt+1 = Kxt is the worst case shock source 3. This function is easier to understand but one or two orders of magnitude slower than self.Sargent’s text “Robustness”. as de- scribed in chapter 2 of Hansen.69 QuantEcon. Solves the robust control problem.n.robust rule().70 QuantEcon. Arguments • rlq::RBLQ: Instance of RBLQ type • P init::Matrix{Float64}(zeros(rlq. Solve the robust LQ problem A simple algorithm for computing the robust policy F and the correspond- ing value function P .robust rule — Method. rlq.robust rule QuantEcon.

72 QuantEcon. Arguments • X::Matrix : Preallocated matrix to be filled with sample paths of the Markov chain mc. Fill X with sample paths of the Markov chain mc as columns.ROUWENHORST 115 Returns • F::Matrix{Float64} : The optimal control matrix from above • P::Matrix{Float64} : The positive semi-definite matrix defining the value function • K::Matrix{Float64} : the worst-case shock matrix K.0) : Mean of AR(1) process Returns • mc::MarkovChain{Float64} : Markov chain holding the state values and transition matrix source 3.71.3.71 QuantEcon. The process follows yt = µ + ρyt−1 + t 2 where t ∼ N (0. The element types in X should be the same as the type of the state values of mc . σ ) Arguments • N::Integer : Number of points in markov process • ::Real : Persistence parameter in AR(1) process • ::Real : Standard deviation of random component of AR(1) process • ::Real(0. QUANTECON. The resulting matrix has the state values of mc as elements. Rouwenhorst’s method to approximate AR(1) processes.rouwenhorst — Function.simulate! QuantEcon.simulate! — Method. where wt+1 = Kxt is the worst case shock source 3.rouwenhorst QuantEcon.

74 QuantEcon. Simulate one sample path of the Markov chain mc. with length ts length source 3.init=rand(1:n states(mc)) : Can be one of the following – blank: random initial condition for each chain – scalar: same initial condition for each chain – vector: cycle through the elements. Fill X with sample paths of the Markov chain mc as columns. • . Arguments • X::Matrix{Int} : Preallocated matrix to be filled with indices of the sample paths of the Markov chain mc. • .simulate QuantEcon.init=rand(1:n states(mc)) : Can be one of the following – blank: random initial condition for each chain . Arguments • mc::MarkovChain : MarkovChain instance.116 CHAPTER 3.simulate — Method. The resulting vector has the state values of mc as elements. The resulting matrix has the indices of the state values of mc as elements.simulate indices! QuantEcon.simulate indices! — Method. applying each as an initial con- dition until all columns have an initial condition (allows for more columns than initial conditions) source 3. QUANTECON • mc::MarkovChain : MarkovChain instance.73 QuantEcon. • ts length::Int : Length of simulation • .init::Int=rand(1:n states(mc)) : Initial state Returns • X::Vector : Vector containing the sample path. • mc::MarkovChain : MarkovChain instance.

The resulting vector has the indices of the state values of mc as elements. Arguments • mc::MarkovChain : MarkovChain instance.impulse length::Integer(30): Horizon for calculating impulse response (see also docstring for impulse response) Returns • X::Vector{Float64}: Simulation of the ARMA model arma source .simulate indices — Method. applying each as an initial con- dition until all columns have an initial condition (allows for more columns than initial conditions) source 3.75.76 QuantEcon. Compute a simulated sample path assuming Gaussian shocks.75 QuantEcon.SIMULATE INDICES 117 – scalar: same initial condition for each chain – vector: cycle through the elements.simulation QuantEcon. Arguments • arma::ARMA: Instance of ARMA type • .simulate indices QuantEcon. • ts length::Int : Length of simulation • .ts length::Integer(90): Length of simulation • . Simulate one sample path of the Markov chain mc. with length ts length source 3.init::Int=rand(1:n states(mc)) : Initial state Returns • X::Vector{Int} : Vector containing the sample path. QUANTECON.simulation — Method.3.

source . Only used if method is VFI • .79 QuantEcon.118 CHAPTER 3.78 QuantEcon. bartlett. Acceptable arguments are VFI for value function iteration or PFI for policy function iteration or MPFI for modified policy function iteration • . QUANTECON 3.smooth QuantEcon.k::Int(20) : Number of iterations for partial policy evaluation in mod- ified policy iteration (irrelevant for other methods).solve — Method.smooth — Function. Returns • ddpr::DPSolveResult{Algo} : Optimization result represented as a DPSolveResult. Smooth the data in x using convolution with a window of requested size and type.smooth QuantEcon. hanning.smooth — Method.epsilon::Float64(1e-3) : Value for epsilon-optimality. or blackman Returns • out::Array: The array of smoothed data source 3. hamming. Possible values are flat. Solve the dynamic programming problem.max iter::Int(250) : Maximum number of iterations • . Parameters • ddp::DiscreteDP : Object that contains the Model Parameters • method::Type{T<Algo}(VFI): Type name specifying solution method. Version of smooth where window len and window are keyword arguments source 3.77 QuantEcon. Arguments • x::Array: An array containing the data to smooth • window len::Int(7): An odd integer giving the length of the window • window::AbstractString("hanning"): A string giving the window type. See DPSolveResult for details.solve QuantEcon.

2.SOLVE DISCRETE LYAPUNOV 119 3.80. We assume in order for convergence that the eigenvalues of B have moduli bounded by unity • max it::Int(50) : Maximum number of iterations Returns • gamma1::Matrix{Float64} Represents the value X source 3. QUANTECON. starting from X0 = B. • B : k x n array .solve discrete lyapunov QuantEcon.3.solve discrete riccati QuantEcon.solve discrete riccati — Function. An explanation of the algo- rithm can be found in the reference below. we iterate to convergence on Xj with the following recursions for j = 1.80 QuantEcon. . . We assume in order for convergence that the eigenvalues of A have moduli bounded by unity • B::Matrix{Float64} : An n x n matrix as described above.81 QuantEcon.solve discrete lyapunov — Function. . Solves the discrete-time algebraic Riccati equation The prolem is defined as X = A0 XA − (N + B 0 XA)0 (B 0 XB + R)−1 (N + B 0 XA) + Q via a modified structured doubling algorithm. Arguments • A : k x k array. The problem is given by AXA0 − X + B = 0 X is computed by using a doubling algorithm. Solves the discrete lyapunov equation. a0 = A: $$ a j = a {j-1} a {j-1} \ X_j = X_{j-1} + a_{j-1} X_{j-1} a_{j-1}’ $$ Arguments • A::Matrix{Float64} : An n x n matrix as described above. In particular.

size(Q. Chun-Yueh. 1).spectral density — Method. π] if false and [0. no. 1))) : n x k array • tolerance::Float64(1e-10) Tolerance level for convergence • max iter::Int(50) : The maximum number of iterations allowed Note that A.” Tai- wanese Journal of Mathematics 14. source 3. The spectral density is the discrete time Fourier transform of the autoco- variance function. “STRUCTURED DOUBLING ALGORITHM FOR DISCRETE-TIME ALGEBRAIC RICCATI EQUATIONS WITH SINGULAR CONTROL WEIGHTING MATRICES.spectral density QuantEcon.120 CHAPTER 3. 3A (2010): pp-935. should be symmetric and positive definite • Q : k x k. X f (w) = γ(k) exp(−ikw) k where γ is the autocovariance function and the sum is over the set of all integers. Returns • X::Matrix{Float64} The fixed point of the Riccati equation. but if res is an array then the function computes the response at the frequencies given by the array Returns . a k x k array representing the approximate solution References Chiang. 2π] otherwise. R. • . Q can either be real (i. B. QUANTECON • R : n x n.res(1200) : If res is a scalar then the spectral density is computed at res frequencies evenly spaced around the unit circle. Arguments • arma::ARMA: Instance of ARMA type • .82 QuantEcon.two pi::Bool(true): Compute the spectral density function over [0. Compute the spectral density function. Hung-Yuan Fan. and Wen-Wei Lin. k. n = 1) or matrices. In particular. should be symmetric and non-negative definite • N::Matrix{Float64}(zeros(size(R.e.

starting from the initial conditions lss.mu 0 and lss. Compute stationary distributions of the Markov chain mc.tol::Float64 = 1e-5 The tolerance level one wishes to achieve Returns • mu x::Vector Represents the stationary mean of xt • mu y::Vector Represents the stationary mean of yt • Sigma x::Matrix Represents the var-cov matrix • Sigma y::Matrix Represents the var-cov matrix source .stationary distributions QuantEcon. source 3.83 QuantEcon.Sigma 0 Arguments • lss::LSS An instance of the Guassian linear state space model • .83.stationary distributions — Function. Returns • stationary dists::Vector{Vector{T1}} : Vector of vectors that repre- sent stationary distributions.STATIONARY DISTRIBUTIONS 121 • w::Vector{Float64}: The normalized frequencies at which h was com- puted. one for each re- current class. Compute the moments of the stationary distributions of xt and yt if possible.stationary distributions — Method. Arguments • mc::MarkovChain{T} : MarkovChain instance.3. Computation is by iteration. in radians/sample • spect::Vector{Float64} : The frequency response source 3.stationary distributions QuantEcon.max iter::Int = 200 The maximum number of iterations allowed • . where the element type T1 is Rational if T is Int (and equal to T otherwise).84 QuantEcon. QUANTECON.

87 QuantEcon. and F fields on the lq instance in addition to returning them source 3.tauchen QuantEcon. Non-mutating routine for solving for P. and F in infinite horizon model See docstring for stationary values! for more explanation source 3.stationary values — Method. Tauchen’s (1996) method for approximating AR(1) process with finite markov chain The process follows yt = µ + ρyt−1 + t where t ∼ N (0. σ 2 ) Arguments • N::Integer: Number of points in markov process • ::Real : Persistence parameter in AR(1) process • ::Real : Standard deviation of random component of AR(1) process .stationary values QuantEcon. Arguments • lq::LQ : instance of LQ type Returns • P::ScalarOrArray : n x n matrix in value function representation V (x) = x0 P x + d • d::Real : Constant in value function representation • F::ScalarOrArray : Policy rule that specifies optimal control in each period Notes This function updates the P.stationary values! QuantEcon.86 QuantEcon. d.tauchen — Function.122 CHAPTER 3. QUANTECON 3. d.85 QuantEcon. Computes value and policy functions in infinite horizon model.stationary values! — Method.

3.88. QUANTECON.UPDATE! 123

• ::Real(0.0) : Mean of AR(1) process

• n std::Integer(3) : The number of standard deviations to each side the
process should span

Returns

• mc::MarkovChain{Float64} : Markov chain holding the state values and
transition matrix

source

3.88 QuantEcon.update!
QuantEcon.update! — Method.
Updates cur x hat and cur sigma given array y of length k. The full update,
from one period to the next
Arguments

• k::Kalman An instance of the Kalman filter

• y An array representing the current measurement

source

3.89 QuantEcon.update values!
QuantEcon.update values! — Method.
Update P and d from the value function representation in finite horizon case
Arguments

• lq::LQ : instance of LQ type

Returns

• P::ScalarOrArray : n x n matrix in value function representation V (x) =
x0 P x + d

• d::Real : Constant in value function representation

Notes
This function updates the P and d fields on the lq instance in addition to
returning them
source

124 CHAPTER 3. QUANTECON

3.90 QuantEcon.var quadratic sum
QuantEcon.var quadratic sum — Method.
Computes the expected discounted quadratic sum

X
q(x0 ) = E β t x0t Hxt
t=0

Here xt is the VAR process xt+1 = Axt + Cwt with wt standard normal and
x0 the initial condition.
Arguments

• A::Union{Float64, Matrix{Float64}} The n x n matrix described above
(scalar) if n = 1
• C::Union{Float64, Matrix{Float64}} The n x n matrix described above
(scalar) if n = 1
• H::Union{Float64, Matrix{Float64}} The n x n matrix described above
(scalar) if n = 1

• beta::Float64: Discount factor in (0, 1)
• x 0::Union{Float64, Vector{Float64}} The initial condtion. A con-
formable array (of length n) or a scalar if n = 1

Returns

• q0::Float64 : Represents the value q(x0 )

Notes
The formula for computing q(x0 ) is q(x0 ) = x00 Qx0 + v where

• Q is the solution to Q = H + βA0 QA and
trace(C 0 QC)β
• v= 1−β

source

Chapter 4

PyPlot

4.1 Base.step
Base.step — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“step”,))
source

4.2 PyPlot.Axes3D
PyPlot.Axes3D — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x00000001418c6248),
(“Axes3D”,))
source

4.3 PyPlot.acorr
PyPlot.acorr — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“acorr”,))
source

4.4 PyPlot.annotate
PyPlot.annotate — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“annotate”,))
source

125

126 CHAPTER 4. PYPLOT

4.5 PyPlot.arrow
PyPlot.arrow — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“arrow”,))
source

4.6 PyPlot.autoscale
PyPlot.autoscale — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“autoscale”,))
source

4.7 PyPlot.autumn
PyPlot.autumn — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“autumn”,))
source

4.8 PyPlot.axes
PyPlot.axes — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“axes”,))
source

4.9 PyPlot.axhline
PyPlot.axhline — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“axhline”,))
source

4.10 PyPlot.axhspan
PyPlot.axhspan — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“axhspan”,))
source

4.11. PYPLOT.AXIS 127

4.11 PyPlot.axis
PyPlot.axis — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“axis”,))
source

4.12 PyPlot.axvline
PyPlot.axvline — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“axvline”,))
source

4.13 PyPlot.axvspan
PyPlot.axvspan — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“axvspan”,))
source

4.14 PyPlot.bar
PyPlot.bar — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“bar”,))
source

4.15 PyPlot.bar3D
PyPlot.bar3D — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x00000001418c6248),
(“Axes3D”, “bar3d”))
source

4.16 PyPlot.barbs
PyPlot.barbs — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“barbs”,))
source

128 CHAPTER 4. PYPLOT

4.17 PyPlot.barh
PyPlot.barh — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“barh”,))
source

4.18 PyPlot.bone
PyPlot.bone — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“bone”,))
source

4.19 PyPlot.box
PyPlot.box — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“box”,))
source

4.20 PyPlot.boxplot
PyPlot.boxplot — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“boxplot”,))
source

4.21 PyPlot.broken barh
PyPlot.broken barh — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“broken barh”,))
source

4.22 PyPlot.cla
PyPlot.cla — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“cla”,))
source

4.23. PYPLOT.CLABEL 129

4.23 PyPlot.clabel
PyPlot.clabel — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“clabel”,))
source

4.24 PyPlot.clf
PyPlot.clf — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“clf”,))
source

4.25 PyPlot.clim
PyPlot.clim — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“clim”,))
source

4.26 PyPlot.cohere
PyPlot.cohere — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“cohere”,))
source

4.27 PyPlot.colorbar
PyPlot.colorbar — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“colorbar”,))
source

4.28 PyPlot.colors
PyPlot.colors — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“colors”,))
source

130 CHAPTER 4. PYPLOT

4.29 PyPlot.contour
PyPlot.contour — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“contour”,))
source

4.30 PyPlot.contour3D
PyPlot.contour3D — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x00000001418c6248),
(“Axes3D”, “contour3D”))
source

4.31 PyPlot.contourf
PyPlot.contourf — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“contourf”,))
source

4.32 PyPlot.contourf3D
PyPlot.contourf3D — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x00000001418c6248),
(“Axes3D”, “contourf3D”))
source

4.33 PyPlot.cool
PyPlot.cool — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“cool”,))
source

4.34 PyPlot.copper
PyPlot.copper — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“copper”,))
source

4.35. PYPLOT.CSD 131

4.35 PyPlot.csd
PyPlot.csd — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“csd”,))
source

4.36 PyPlot.delaxes
PyPlot.delaxes — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“delaxes”,))
source

4.37 PyPlot.disconnect
PyPlot.disconnect — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“disconnect”,))
source

4.38 PyPlot.draw
PyPlot.draw — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“draw”,))
source

4.39 PyPlot.errorbar
PyPlot.errorbar — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“errorbar”,))
source

4.40 PyPlot.eventplot
PyPlot.eventplot — Method.
PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248),
(“eventplot”,))
source

PYPLOT 4. PyPlot.PyObject struct} @0x000000014189d9b0).43 PyPlot. PyPlot.figlegend PyPlot.)) source 4.46 PyPlot.)) source 4.42 PyPlot. PyPlot.PyObject struct} @0x0000000141899248).)) source 4.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall. PyPlot. (“figlegend”.44 PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.figure PyPlot.LazyHelp(PyCall. (“fill between”.)) source .figure — Method. PyPlot.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.figtext — Method.41 PyPlot.PyObject struct} @0x0000000141899248).figaspect — Method.LazyHelp(PyCall.PyObject(Ptr{PyCall.132 CHAPTER 4.figimage PyPlot.LazyHelp(PyCall.LazyHelp(PyCall.45 PyPlot.figtext PyPlot.)) source 4. ()) source 4.fill between PyPlot. PyPlot.PyObject(Ptr{PyCall.figimage — Method.PyObject struct} @0x0000000141899248).figlegend — Method.fill between — Method. (“figimage”.LazyHelp(PyCall.figaspect PyPlot. (“figaspect”.PyObject(Ptr{PyCall. (“figtext”.

gci — Method.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.gca — Method.)) source .fill betweenx — Method.LazyHelp(PyCall.LazyHelp(PyCall.gcf — Method.47. (“fill betweenx”.flag — Method.)) source 4.PyObject struct} @0x0000000141899248).47 PyPlot.4. PyPlot.PyObject struct} @0x000000014189da28).51 PyPlot. ()) source 4. (“flag”.PyObject(Ptr{PyCall.gci PyPlot. (“gca”.gca PyPlot.flag PyPlot.50 PyPlot. PyPlot.49 PyPlot.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.gcf PyPlot.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248).LazyHelp(PyCall.)) source 4.LazyHelp(PyCall. PyPlot. PyPlot. PyPlot. PYPLOT.findobj PyPlot.FILL BETWEENX 133 4.PyObject(Ptr{PyCall.)) source 4. (“gci”.)) source 4.52 PyPlot. PyPlot.PyObject(Ptr{PyCall. (“findobj”.fill betweenx PyPlot.PyObject struct} @0x0000000141899248).findobj — Method.LazyHelp(PyCall.LazyHelp(PyCall.48 PyPlot.

LazyHelp(PyCall.PyObject(Ptr{PyCall. PyPlot.get fignums PyPlot.)) source .LazyHelp(PyCall.)) source 4.54 PyPlot.PyObject struct} @0x000000014123c2a8).56 PyPlot.get current fig manager PyPlot. PyPlot.)) source 4.)) source 4.get figlabels — Method.PyObject struct} @0x0000000141899248). (“get fignums”.57 PyPlot.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248).LazyHelp(PyCall.LazyHelp(PyCall.get plot commands PyPlot.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248). PYPLOT 4.get fignums — Method.PyObject(Ptr{PyCall.get plot commands — Method.55 PyPlot.)) source 4. PyPlot. (“get plot commands”.get current fig manager — Method.get figlabels PyPlot.53 PyPlot.ginput — Method.LazyHelp(PyCall. PyPlot.ginput PyPlot. ()) source 4.get cmap — Method.PyObject struct} @0x0000000141899248).LazyHelp(PyCall. PyPlot.134 CHAPTER 4.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall.58 PyPlot.get cmap PyPlot. (“get current fig manager”. (“get figlabels”. PyPlot. (“ginput”.

PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248).hist2D PyPlot.PyObject struct} @0x0000000141899248). PyPlot.PyObject struct} @0x0000000141899248).60 PyPlot.LazyHelp(PyCall.PyObject struct} @0x0000000141899248).59.hold PyPlot. (“hold”.)) source 4.)) source 4.gray — Method.PyObject struct} @0x0000000141899248).59 PyPlot.4. PyPlot.PyObject(Ptr{PyCall.hexbin PyPlot.)) source 4. PYPLOT.)) source 4. (“hexbin”.PyObject(Ptr{PyCall. (“hlines”.gray PyPlot.hlines — Method.64 PyPlot.)) source 4.PyObject(Ptr{PyCall. PyPlot. PyPlot.PyObject struct} @0x0000000141899248).LazyHelp(PyCall.62 PyPlot.LazyHelp(PyCall.GRAY 135 4.hold — Method.hlines PyPlot.61 PyPlot.hexbin — Method. (“grid”.63 PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.hist2D — Method.LazyHelp(PyCall.grid — Method.LazyHelp(PyCall. (“gray”.grid PyPlot. (“hist2d”.PyObject(Ptr{PyCall.)) source . PyPlot. PyPlot.

)) source 4.PyObject struct} @0x0000000141899248).)) source 4.PyObject(Ptr{PyCall. PyPlot.)) source 4.hot — Method.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall. PyPlot.)) source .imshow — Method.68 PyPlot. (“hot”.PyObject struct} @0x0000000141899248). PyPlot.imsave — Method. (“hsv”.136 CHAPTER 4.ioff — Method.imread — Method.LazyHelp(PyCall.70 PyPlot.ioff PyPlot. PyPlot.)) source 4.imshow PyPlot.)) source 4.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall. (“imshow”.67 PyPlot. PyPlot.69 PyPlot.66 PyPlot.LazyHelp(PyCall. (“ioff”.imsave PyPlot.imread PyPlot. (“imread”.hsv — Method. (“imsave”.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248).hot PyPlot.hsv PyPlot.LazyHelp(PyCall. PyPlot.LazyHelp(PyCall.LazyHelp(PyCall.PyObject struct} @0x0000000141899248).PyObject struct} @0x0000000141899248). PYPLOT 4.65 PyPlot.

)) source 4.72 PyPlot.75 PyPlot.LazyHelp(PyCall. (“ion”.)) source 4.76 PyPlot.PyObject struct} @0x0000000141899248).PyObject struct} @0x0000000141899248).LazyHelp(PyCall. (“loglog”. PyPlot.LazyHelp(PyCall.)) source 4.PyObject(Ptr{PyCall.legend PyPlot. PyPlot. PyPlot.73 PyPlot.PyObject(Ptr{PyCall.ion — Method. (“locator params”. (“ishold”.ishold — Method.locator params — Method.legend — Method.PyObject(Ptr{PyCall.)) source 4.jet PyPlot.locator params PyPlot.PyObject struct} @0x0000000141899248).PyObject struct} @0x0000000141899248).PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.loglog PyPlot. PyPlot.4. PyPlot.74 PyPlot.)) source 4.)) source .PyObject(Ptr{PyCall. (“legend”.LazyHelp(PyCall. PYPLOT.LazyHelp(PyCall.LazyHelp(PyCall.jet — Method.ishold PyPlot.71.loglog — Method. (“jet”.71 PyPlot. PyPlot.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.ion PyPlot.ION 137 4.

PyPlot.mesh PyPlot.LazyHelp(PyCall.81 PyPlot.margins — Method.minorticks on PyPlot.LazyHelp(PyCall.minorticks on — Method. (“Axes3D”.PyObject struct} @0x0000000141899248). PYPLOT 4.)) source .)) source 4. (“margins”.minorticks off PyPlot. PyPlot. PyPlot.matshow — Method.mesh — Method.)) source 4.PyObject struct} @0x0000000141899248).80 PyPlot.78 PyPlot.margins PyPlot.matshow PyPlot.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.)) source 4. (“minorticks on”.PyObject(Ptr{PyCall.minorticks off — Method. PyPlot. (“over”.over — Method. PyPlot.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall. (“matshow”.LazyHelp(PyCall.PyObject struct} @0x0000000141899248).PyObject struct} @0x00000001418c6248).)) source 4. “plot wireframe”)) source 4.PyObject(Ptr{PyCall. (“minorticks off”.79 PyPlot. PyPlot.LazyHelp(PyCall.82 PyPlot.over PyPlot.138 CHAPTER 4.77 PyPlot.LazyHelp(PyCall.LazyHelp(PyCall.

(“pcolormesh”.LazyHelp(PyCall.88 PyPlot.PyObject struct} @0x0000000141899248).PyObject struct} @0x0000000141899248).PyObject struct} @0x0000000141899248).pie PyPlot.86 PyPlot.)) source 4.PyObject(Ptr{PyCall. PyPlot. (“pink”.)) source 4. PyPlot. (“plot”.pcolor PyPlot.PyObject struct} @0x0000000141899248).LazyHelp(PyCall.)) source 4.LazyHelp(PyCall.)) source 4.pcolor — Method.pink — Method. PyPlot.PyObject struct} @0x0000000141899248).plot — Method. (“pause”.85 PyPlot. (“pcolor”. PYPLOT.84 PyPlot.PyObject(Ptr{PyCall.pcolormesh — Method. PyPlot.PyObject(Ptr{PyCall. PyPlot. PyPlot.83.PyObject(Ptr{PyCall.pink PyPlot.)) source 4.pause — Method.)) source .PyObject struct} @0x0000000141899248). (“pie”.4.plot PyPlot.87 PyPlot.PAUSE 139 4.LazyHelp(PyCall.pie — Method.pcolormesh PyPlot.LazyHelp(PyCall.LazyHelp(PyCall.PyObject(Ptr{PyCall.83 PyPlot.PyObject(Ptr{PyCall.pause PyPlot.

PyObject struct} @0x0000000141899248).plot date PyPlot.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall. (“Axes3D”.LazyHelp(PyCall. PyPlot.)) source .PyObject struct} @0x00000001418c6248).plot trisurf PyPlot.PyObject struct} @0x00000001418c6248).plot surface — Method. PYPLOT 4. PyPlot.plot wireframe — Method.plot trisurf — Method. PyPlot.plot3D PyPlot.)) source 4.91 PyPlot. “plot surface”)) source 4.PyObject struct} @0x0000000141899248).PyObject struct} @0x00000001418c6248).93 PyPlot.plot3D — Method. (“Axes3D”. PyPlot.PyObject struct} @0x00000001418c6248).94 PyPlot. (“plot date”.LazyHelp(PyCall.plot date — Method. (“plotfile”.LazyHelp(PyCall.plotfile PyPlot.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall.90 PyPlot.140 CHAPTER 4. “plot wireframe”)) source 4. PyPlot.plotfile — Method.LazyHelp(PyCall.92 PyPlot. PyPlot. (“Axes3D”. (“Axes3D”. “plot trisurf”)) source 4.89 PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.plot surface PyPlot. “plot3D”)) source 4.LazyHelp(PyCall.PyObject(Ptr{PyCall.plot wireframe PyPlot.

)) source .95.prism — Method.100 PyPlot. PyPlot. PyPlot.LazyHelp(PyCall.96 PyPlot.polar — Method.LazyHelp(PyCall. PyPlot.rc PyPlot.95 PyPlot. (“psd”.quiver PyPlot.PyObject(Ptr{PyCall.polar PyPlot.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall.4. PYPLOT.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall. (“rc”.PyObject struct} @0x0000000141899248). PyPlot. (“quiver”.psd PyPlot.)) source 4.PyObject struct} @0x0000000141899248).98 PyPlot.)) source 4.PyObject struct} @0x0000000141899248).quiverkey PyPlot.PyObject(Ptr{PyCall. PyPlot.97 PyPlot.POLAR 141 4.PyObject struct} @0x0000000141899248). (“polar”.quiverkey — Method. (“prism”.quiver — Method.LazyHelp(PyCall.LazyHelp(PyCall.)) source 4.psd — Method.99 PyPlot. PyPlot.rc — Method.LazyHelp(PyCall.PyObject struct} @0x0000000141899248). (“quiverkey”.)) source 4.prism PyPlot.)) source 4.PyObject(Ptr{PyCall.LazyHelp(PyCall.

(“rc context”. (“sca”. PYPLOT 4. (“rgrids”. PyPlot.LazyHelp(PyCall.savefig — Method.rc context — Method.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall. PyPlot.register cmap PyPlot.PyObject(Ptr{PyCall.rcdefaults PyPlot.)) source 4.PyObject struct} @0x0000000141899248).PyObject struct} @0x0000000141899248). (“rcdefaults”.PyObject struct} @0x0000000141899248).104 PyPlot.rgrids PyPlot.)) source 4.rc context PyPlot.)) source 4.PyObject struct} @0x0000000141899248).106 PyPlot.102 PyPlot.PyObject(Ptr{PyCall.LazyHelp(PyCall.LazyHelp(PyCall.142 CHAPTER 4.PyObject struct} @0x0000000141899248).)) source 4.101 PyPlot. PyPlot. (“savefig”.LazyHelp(PyCall.LazyHelp(PyCall.PyObject struct} @0x000000014123c230).rcdefaults — Method. PyPlot. PyPlot.register cmap — Method.105 PyPlot.LazyHelp(PyCall. ()) source 4.103 PyPlot.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall.sca PyPlot.rgrids — Method. PyPlot.sca — Method.savefig PyPlot.)) source .

PyObject(Ptr{PyCall.107 PyPlot.sci — Method.set cmap — Method. (“semilogy”.scatter3D PyPlot.)) source 4.PyObject struct} @0x00000001418c6248).PyObject(Ptr{PyCall. PyPlot.PyObject(Ptr{PyCall.scatter — Method.semilogx — Method.set cmap PyPlot.4.109 PyPlot.PyObject(Ptr{PyCall.)) source 4. PyPlot.108 PyPlot.LazyHelp(PyCall. PYPLOT.111 PyPlot. (“semilogx”. “scatter3D”)) source 4. PyPlot.semilogy PyPlot.SCATTER 143 4.PyObject(Ptr{PyCall.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248).scatter3D — Method.sci PyPlot.110 PyPlot.112 PyPlot.LazyHelp(PyCall. PyPlot. PyPlot.)) source . (“set cmap”.)) source 4.PyObject struct} @0x0000000141899248).)) source 4.semilogx PyPlot.LazyHelp(PyCall. (“Axes3D”.PyObject struct} @0x0000000141899248). (“sci”.107. (“scatter”.PyObject struct} @0x0000000141899248).PyObject struct} @0x0000000141899248).LazyHelp(PyCall.scatter PyPlot. PyPlot.semilogy — Method.LazyHelp(PyCall.

118 PyPlot.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248). (“spy”. PyPlot.PyObject(Ptr{PyCall.LazyHelp(PyCall.116 PyPlot.114 PyPlot.setp — Method.)) source 4.spectral — Method.specgram — Method. PyPlot. PyPlot.)) source 4.115 PyPlot.setp PyPlot.144 CHAPTER 4.spectral PyPlot.)) source 4. PyPlot.LazyHelp(PyCall.spring — Method.specgram PyPlot.PyObject struct} @0x0000000141899248).stackplot — Method.spring PyPlot.)) source 4. (“specgram”.)) source 4.117 PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall.LazyHelp(PyCall.PyObject(Ptr{PyCall. (“setp”.)) source . PyPlot. PYPLOT 4. (“spring”.113 PyPlot.PyObject struct} @0x0000000141899248).PyObject struct} @0x0000000141899248).spy — Method.LazyHelp(PyCall. (“stackplot”.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.LazyHelp(PyCall. PyPlot. (“spectral”.spy PyPlot.stackplot PyPlot.PyObject struct} @0x0000000141899248).

PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.subplot2grid PyPlot.PyObject struct} @0x0000000141899248).124 PyPlot. PYPLOT. (“subplot”.PyObject struct} @0x0000000141899248). (“subplot2grid”. PyPlot.subplot PyPlot. (“subplots”.subplot2grid — Method.)) source 4. (“streamplot”.STEM 145 4.)) source 4.subplot — Method.)) source 4. PyPlot.PyObject(Ptr{PyCall.123 PyPlot. PyPlot. PyPlot.PyObject(Ptr{PyCall.streamplot PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.120 PyPlot.121 PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248). PyPlot. (“stem”.)) source 4.)) source .LazyHelp(PyCall.subplot tool — Method.subplots PyPlot.LazyHelp(PyCall.)) source 4.subplot tool PyPlot.stem — Method.LazyHelp(PyCall.119 PyPlot.PyObject struct} @0x0000000141899248).PyObject struct} @0x0000000141899248).subplots — Method.122 PyPlot. (“subplot tool”.streamplot — Method.LazyHelp(PyCall. PyPlot.PyObject(Ptr{PyCall.stem PyPlot.119.4.

subplots adjust PyPlot. (“subplots adjust”.table — Method.LazyHelp(PyCall.)) source .PyObject struct} @0x00000001418c6248).table PyPlot.suptitle — Method.127 PyPlot. (“table”.surf PyPlot. PyPlot.LazyHelp(PyCall.LazyHelp(PyCall.)) source 4. “plot surface”)) source 4.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.146 CHAPTER 4.text — Method. (“suptitle”.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.129 PyPlot. PyPlot.128 PyPlot.PyObject struct} @0x0000000141899248).)) source 4.130 PyPlot. (“summer”.suptitle PyPlot.PyObject struct} @0x0000000141899248).surf — Method.summer PyPlot.125 PyPlot.subplots adjust — Method.summer — Method.)) source 4. (“Axes3D”.LazyHelp(PyCall. PYPLOT 4.PyObject(Ptr{PyCall.)) source 4.LazyHelp(PyCall.LazyHelp(PyCall.text PyPlot. PyPlot. (“text”.PyObject struct} @0x0000000141899248). PyPlot.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall. PyPlot.PyObject(Ptr{PyCall.126 PyPlot. PyPlot.

LazyHelp(PyCall.PyObject struct} @0x0000000141899248).131.tight layout PyPlot.PyObject(Ptr{PyCall. PyPlot.thetagrids — Method. (“Axes3D”. PyPlot.)) source 4.LazyHelp(PyCall.LazyHelp(PyCall.PyObject struct} @0x0000000141899248).LazyHelp(PyCall.133 PyPlot.PyObject struct} @0x0000000141899248).PyObject struct} @0x00000001418c6248).PyObject struct} @0x0000000141899248).text3D — Method. PYPLOT.LazyHelp(PyCall. PyPlot.LazyHelp(PyCall.text2D — Method.text2D PyPlot.tick params — Method.135 PyPlot.PyObject(Ptr{PyCall.ticklabel format — Method.tight layout — Method.PyObject(Ptr{PyCall.4.ticklabel format PyPlot. “text3D”)) source 4.tick params PyPlot. (“tick params”.)) source 4.)) source 4.136 PyPlot. (“Axes3D”.text3D PyPlot. PyPlot.thetagrids PyPlot. (“tight layout”.PyObject(Ptr{PyCall.TEXT2D 147 4. PyPlot.)) source . “text2D”)) source 4. (“ticklabel format”.134 PyPlot.PyObject struct} @0x00000001418c6248). PyPlot. (“thetagrids”.131 PyPlot.132 PyPlot.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall.

tricontourf — Method.139 PyPlot. (“tricontourf”.PyObject struct} @0x0000000141899248).)) source .PyObject struct} @0x0000000141899248).triplot PyPlot.LazyHelp(PyCall.LazyHelp(PyCall.tripcolor PyPlot.PyObject struct} @0x0000000141899248).LazyHelp(PyCall. (“tricontour”.140 PyPlot. PyPlot.148 CHAPTER 4.141 PyPlot.title PyPlot.triplot — Method.PyObject struct} @0x0000000141899248).PyObject(Ptr{PyCall.PyObject(Ptr{PyCall.LazyHelp(PyCall. (“twinx”.tripcolor — Method.)) source 4. PyPlot. PyPlot.LazyHelp(PyCall.PyObject(Ptr{PyCall. (“title”.138 PyPlot. PyPlot.tricontour — Method.twinx — Method.tricontour PyPlot. (“tripcolor”.137 PyPlot.PyObject(Ptr{PyCall.PyObject(Ptr{PyCall. PyPlot.PyObject(Ptr{PyCall.)) source 4.142 PyPlot.tricontourf PyPlot.title — Method.PyObject struct} @0x0000000141899248).)) source 4.)) source 4.PyObject struct} @0x0000000141899248).twinx PyPlot. PyPlot.LazyHelp(PyCall. (“triplot”.)) source 4. PYPLOT 4.

LazyHelp(PyCall.4. PyPlot.xlabel PyPlot.PyObject(Ptr{PyCall. (“xkcd”.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248). PyPlot.PyObject(Ptr{PyCall.PyObject struct} @0x0000000141899248).winter PyPlot.twiny — Method.waitforbuttonpress PyPlot.LazyHelp(PyCall. PyPlot.145 PyPlot.xkcd PyPlot.winter — Method.LazyHelp(PyCall.PyObject(Ptr{PyCall.144 PyPlot.143. (“waitforbuttonpress”.waitforbuttonpress — Method.147 PyPlot.143 PyPlot.)) source 4.)) source 4.)) source .TWINY 149 4. (“vlines”.vlines PyPlot.LazyHelp(PyCall.twiny PyPlot.vlines — Method.PyObject struct} @0x0000000141899248).LazyHelp(PyCall.)) source 4.PyObject(Ptr{PyCall.)) source 4. PyPlot.xlabel — Method.PyObject struct} @0x0000000141899248).146 PyPlot.PyObject(Ptr{PyCall. (“winter”.PyObject struct} @0x0000000141899248). PYPLOT.148 PyPlot. (“twiny”. (“xlabel”.xkcd — Method. PyPlot.LazyHelp(PyCall.PyObject struct} @0x0000000141899248).)) source 4. PyPlot.

yscale PyPlot.xscale — Method.)) source 4. (“xticks”.149 PyPlot. (“ylabel”.LazyHelp(PyCall.ylim — Method. (“yscale”. PyPlot.PyObject struct} @0x0000000141899248).LazyHelp(PyCall.xticks — Method.PyObject(Ptr{PyCall.ylabel PyPlot.xticks PyPlot.PyObject(Ptr{PyCall.151 PyPlot.xlim PyPlot.PyObject struct} @0x0000000141899248).)) source 4.ylim PyPlot.ylabel — Method.PyObject(Ptr{PyCall.LazyHelp(PyCall. PyPlot.PyObject(Ptr{PyCall.152 PyPlot. PYPLOT 4.)) source 4.LazyHelp(PyCall.yscale — Method.PyObject struct} @0x0000000141899248).150 CHAPTER 4.xscale PyPlot.PyObject(Ptr{PyCall. (“ylim”. PyPlot.xlim — Method.LazyHelp(PyCall.PyObject(Ptr{PyCall. (“xlim”.PyObject struct} @0x0000000141899248).150 PyPlot.)) source 4.PyObject struct} @0x0000000141899248). PyPlot. (“xscale”.)) source .PyObject struct} @0x0000000141899248).LazyHelp(PyCall.154 PyPlot. PyPlot.)) source 4.153 PyPlot. PyPlot.

PyObject struct} @0x0000000141899248).YTICKS 151 4. PYPLOT.PyObject(Ptr{PyCall. “set zlim”)) source 4. PyPlot.159 PyPlot. (“Axes3D”.156 PyPlot.zticks — Method.LazyHelp(PyCall. “set zticks”)) source .PyObject struct} @0x00000001418c6248).LazyHelp(PyCall.155 PyPlot.zlabel — Method.zlabel PyPlot.PyObject(Ptr{PyCall. (“Axes3D”.157 PyPlot.PyObject(Ptr{PyCall.yticks — Method.PyObject struct} @0x00000001418c6248).zlim PyPlot.zticks PyPlot. “set zscale”)) source 4.PyObject(Ptr{PyCall. PyPlot.LazyHelp(PyCall. (“yticks”.PyObject struct} @0x00000001418c6248).155.PyObject struct} @0x00000001418c6248).)) source 4.4. PyPlot. PyPlot.zscale PyPlot.PyObject(Ptr{PyCall. “set zlabel”)) source 4.zscale — Method. PyPlot.158 PyPlot.LazyHelp(PyCall.LazyHelp(PyCall.yticks PyPlot.zlim — Method. (“Axes3D”. (“Axes3D”.

[3. 2. :y]. 3 columns: t x y 0. Integer – returns the column at this position. 4. AbstractArray – returns the array itself. 3. Selection}.Chapter 5 IndexedTables 5.Sort. julia> tbl = table([0.4]. Selection is a type union of many types that can select from a table. select(t::Table. :x. Tuple of Selection – returns a table containing a column for every se- lector in the tuple. The tuple may also contain the type Pair{Symbol.select — Method. 5. names=[:t.Sort. pkey=:t) Table with 2 rows. Symbol – returns the column with this name.05]. Pair{Selection => Function} – selects and maps a function over the selection. It can be: 1. [2.05 1 4 152 . which::Selection) Select all or a subset of columns. which the selection a name.select Base. This must be the same length as the table. Examples: Selection with Integer – returns the column at this position. or a single column from the table. returns the result.01. The most useful form of this when introducing a new column.1 Base.01 2 3 0.1]. 0.

0 julia> select(tbl. julia> select(tbl.1}: 0.1)) Table with 2 rows. :t=>t->1/t) 2-element Array{Float64.1}: 2 1 Selection with Symbol – returns the column with this name.x/p.4]) 2-element Array{Int64.:t=>-)) Table with 2 rows.SORT. :t)=>p->p.1. (:x. :t) 2-element Array{Float64.05 julia> vx = select(tbl. [3.1}: 100.05 2 -0. then returns the mapped column.0 Selection with AbstractArray – returns the array itself.01 .t) 2-element Array{Float64. BASE.1}: 3 4 Selection with Tuple– returns a table containing a column for every selector in the tuple. (2.0 20. julia> select(tbl. julia> select(tbl.01 0. 2) 2-element Array{Int64.01 1 0. 2 columns: x t 1 -0. julia> select(tbl. (:x.1}: 200.05 Selection with Pair{Selection => Function} – selects some columns and maps a function over it.0 20. 2 columns: x t 2 0.5.SELECT 153 julia> select(tbl.

. To specify a new name to a custom column.05 20.05 4 This is because the third column’s name is unknown. Selection with a custom array in the tuple will cause the name of the columns to be removed and replaced with integers.dropna DataValues. [3. it strips column names.01 -0. The same applies when multiple key columns are selected.:t)=>p->p.01 200.:t. (:x. (:x. julia> select(tbl. se- lections that retain the key column will retain its status as a key.01 3 1 0. :vx=>(:x.4])) Table with 2 rows. (:x. then selection returns an iterable of tuples rather than named tuples. 3 columns: 1 2 3 2 0.0 1 0.x/p. dropna(t[.t)) Table with 2 rows. (:x. :t.0 source 5. 3 columns: x t z 2 0.05 4 julia> select(tbl. select]) Drop rows which contain NA values.01 1 0. you can use Symbol => Selection selector.05 julia> select(tbl. :t. :t.2 DataValues.01 3 1 0. julia> select(tbl.05 -0. 3 columns: x t minust 2 0.dropna — Function. 3 columns: x t vx 2 0.154 CHAPTER 5. INDEXEDTABLES Note that since tbl was initialized with t as the primary key column. In other words. In general if a column’s name cannot be determined.4])) Table with 2 rows. :minust=>:t=>-)) Table with 2 rows.:z=>[3.

0.7]. :x)) Array{Int64. NA.7 5 7 julia> t1 = dropna(t.1 2 #NA 0.NA.aggregate! — Method.:y]) Table with 4 rows.1 2 #NA 0. 3 columns: t x y 0. [NA.:x.5.7 5 7 Any columns whose NA rows have been dropped will be converted to non- na array type.7 5 7 julia> dropna(t) Table with 1 rows. :y) Table with 2 rows. In our last example.aggregate! IndexedTables. (:t.7].NA. source . 3 columns: t x y 0. in place.1} source 5. columns t and x got converted from Array{DataValue{Int}} to Array{Int}.5.0.6.5 #NA 6 0. 3 columns: t x y 0.7 5 7 Optionally select can be speicified to limit columns to look for NAs in.3 IndexedTables.5 #NA 6 #NA 4 #NA 0. :x)) Table with 2 rows. 3 columns: t x y 0. arr::NDSparse) Combine adjacent rows with equal indices using the given 2-argument re- duction function.4. [] julia¿ typeof(column(dropna(t.AGGREGATE! 155 julia> t = table([0.5].:x). julia> dropna(t. [2. Similarly if the vectors are of type DataValueArray{T} (default for loadtable) they will be converted to Array{T}. INDEXEDTABLES. names=[:t. aggregate!(f::Function.3.1.

3].2.4 IndexedTables.colnames — Function."ko". julia> x = ndsparse((["ko". [5.6. Examples: julia> colnames([1. "xrx". [1.2.5])) 2-element Array{Int64.156 CHAPTER 5.2."xrx"].3.1}: 1 2 julia> colnames(table([1.1}: 1 julia> colnames(Columns([1. "2017-11-12"])). [3. "2017-11-13"])).1}: .(["2017-11-11". julia> y = ndsparse((["ko".3]. Date.4. right::NDSparse) asofjoin is most useful on two time-series. "2017-11-13". "2017-11-11". "2017-11-10".4. asofjoin(left::NDSparse.(["2017-11-12".5 IndexedTables. colnames(itr) Returns the names of the “columns” in itr."ko".3]) 1-element Array{Int64. "2017-11-12".y) 2-d NDSparse with 4 values (Int64): 1 2 "ko" 2017-11-11 1 "ko" 2017-11-12 5 "xrx" 2017-11-11 7 "xrx" 2017-11-12 7 source 5.asofjoin — Method. [3. "xrx".asofjoin IndexedTables.colnames IndexedTables.2.4]).5])) 2-element Array{Int64. Date.8]) julia> asofjoin(x.7. INDEXEDTABLES 5."xrx"]. It joins rows from left with the “most recent” value from right.

4.1}: 1 2 :x julia> colnames(ndsparse(Columns(x=[1.2.6 IndexedTables. Columns(x=[6.5])) 2-element Array{Any.1}: :x 1 2 julia> colnames(ndsparse(Columns(x=[1.2.5]))) 2-element Array{Symbol.3]).4. [4.:y])) 2-element Array{Symbol.1}: :x :y julia> colnames(ndsparse(Columns(x=[1. [3.4.6]).4.3]. . [3.6.3].3]).8]))) 3-element Array{Any.4. [3.5.2.columns — Function.4.3]).3]).3].1}: :x :y julia> colnames(table([1.5])) 2-element Array{Any.5])) 2-element Array{Symbol.5]. y=[3.[6.1}: :x 2 3 source 5. names=[:x.2. INDEXEDTABLES.COLUMNS 157 1 2 julia> colnames(Columns(x=[1. Columns(y=[3.2.1}: :x 2 julia> colnames(ndsparse(Columns([1.7.7.8]))) 3-element Array{Any.2.columns IndexedTables.1}: :x :y julia> colnames(ndsparse(Columns(x=[1. Columns([3.2.5.5].

7 IndexedTables. select specifies which columns to select. 4].[3. xlate. names=[:x. See Selection convention for possible values. name) Apply function or dictionary xlate to each index in the specified dimension. Columns and AbstractVector.columns IndexedTables. vecagg::Function.2]. convertdim(x::NDSparse. If unspecified. which) Returns a vector or a tuple of vectors from the iterator. . 4]) julia> columns(t. If the mapping is many-to-one. 2]. returns all columns. INDEXEDTABLES columns(itr[. d::DimName. y = [3. agg::Function. x = [-1.convertdim IndexedTables.)) (x = [1. 2 columns: x y 1 3 2 4 julia> columns(t) (x = [1.158 CHAPTER 5. (:x. select::Selection]) Select one or more columns from an iterable of rows as a tuple of vectors.1}: 1 2 julia> columns(t. agg or vecagg is used to aggregate the results. -2]) source 5.4].:x=>-)) (y = [3. 2]) julia> columns(t. columns(itr. and their distributed counterparts.:y]) Table with 2 rows.columns — Method. source 5. Examples julia> t = table([1.8 IndexedTables. itr can be NDSparse. :x) 2-element Array{Int64. (:y.convertdim — Method.

9 IndexedTables. ndims(t) == length(dimlabels(t)). [9.10].8].flatten IndexedTables.2].dimlabels IndexedTables. names=[:a. names=[:a.DIMLABELS 159 If agg is passed.10 IndexedTables. 6] julia> flatten(x.:b]). julia> flatten(x. INDEXEDTABLES.dimlabels — Method. [5. :y) Table with 4 rows. 4] 2 [5. col) Flatten col column which may contain a vector of vectors while repeating the other fields. Examples: julia> x = table([1.:b])]. it is used as a vector-to-scalar function to aggregate the data.9. :y]). 3 columns: x a b 1 3 5 . 2 columns: x y 1 [3. [[3.5. table([7. 2 columns: x y 1 3 1 4 2 5 2 6 julia> x = table([1.flatten — Method.2]. source 5. flatten(t::Table.4]. it is used as a 2-argument reduction function over the data.6]. dimlabels(t::NDSparse) Returns an array of integers or symbols giving the labels for the dimensions of t.[5. :y]) Table with 2 rows.4]. If vecagg is passed. [table([3. 2) Table with 4 rows.6]]. source 5. name optionally specifies a new name for the translated dimension. names=[:x. names=[:x.

flatten) Group rows by by.160 CHAPTER 5.flush! IndexedTables. t. t[. julia> groupby(mean. 3 columns: . :y).groupby IndexedTables.0 julia> groupby(identity.:y. groupby(f. 3 columns: x y identity 1 1 [1.1]. [1. :y).4. 2] 1 2 [3] 2 1 [5.5. and apply f to each group. [1.1. t. select=:z) Table with 4 rows. names=[:x.6].12 IndexedTables. source 5. (:x.2. select=:z) Table with 2 rows.:z]).2].1. by::Selection]. t. by sorting and merging the internal temporary buffer. The result of f on each group is put in a table keyed by unique by values. :x.groupby — Function.2.1. INDEXEDTABLES 1 4 6 2 7 9 2 8 10 source 5.2. 6] 2 2 [4] julia> groupby(mean.2. flush!(arr::NDSparse) Commit queued assignment operations. select=:z) Table with 4 rows. select::Selection. flatten will flatten the result and can be used when f returns a vector instead of a single scalar value.3.1. (:x.flush! — Method. 2 columns: x mean 1 2. Examples julia> t=table([1.2. f can be a function or a tuple of functions.11 IndexedTables.0 2 5.

75 3. 0.4.1.5 0. 3 columns: x xmean ystd 1 2.5 5.5 .0 0. ystd=(:y=>-)=>std). var). t. q75=z->quantile(z.75 Finally. 4 columns: y mean std var 1 3.707107 0.12. select=:y.25). the result of groupby when f returns a vector or iterator of values will not be expanded.5 julia> groupby(@NT(q25=z->quantile(z. length(x)).0 multiple aggregates can be computed by passing a tuple of functions: julia> groupby((mean.6]. std.57735 2 5.38048 5.5 1 3. t. INDEXEDTABLES.GROUPBY 161 x y mean 1 1 1. 2 columns: x normy 1 3.5 2 2 4.5 2.5 1 2 3.25 2 3. 4 columns: y q25 q50 q75 1 1. :y. select=:z) Table with 2 rows. t. q50=median.5 2 5. Pass the flatten option as true to flatten the grouped column: julia> t = table([1.). :x.:y]) julia> groupby((:normy => x->Iterators.5.2. t.2].repeated(mean(x). [3. names=[:x. :y.66667 2 3. it’s possible to select different inputs for different functions by using a named tuple of slector => function pairs: julia> groupby(@NT(xmean=:z=>mean. 0.5 3.5 2 5. select=:z) Table with 2 rows.57735 By default.0 2 1 5.5.25 3.0 0.75)). :x) Table with 2 rows. flatten=true) Table with 4 rows.

2. d = 2). [1. m and n times respectively). each row with a key from left is matched with each row from right with that key. This generates the “intersection” of keys from left and right.1.3. 3 columns: a b groups 1 2 NamedTuples.13 IndexedTables. INDEXEDTABLES source 5.2]. 3 columns: a b d 0 1 1 1 2 2 1 2 3 2 1 4 julia> groupjoin(l. ] left. names=[:a. The resulting group has mn output elements. julia> l = table([1.3.2. d = 4)] Left join .1. (c = 2.Int64}[(c = 2. [1. names=[:a. pkey=(:a.162 CHAPTER 5.4]. :b)) Table with 4 rows. It looks up keys from left in right and only joins them when there is a match. d = 3).:c]._NT_c_d{Int64. right. 2 1 NamedTuples.2. how. [1._NT_c_d{Int64.:b.1].groupjoin IndexedTables.4].1. pkey=(:a. Inner join Inner join is the default join (when how is unspecified). groupjoin([f.r) Table with 2 rows.Int64}[(c = 4. <options>) Join left and right creating groups of values with matching keys.1].1.2. (c = 3.2.2. :b)) Table with 4 rows. 3 columns: a b c 1 1 1 1 2 2 1 2 3 2 1 4 julia> r = table([0.:b. [1. d = 2).:d]. One-to-many and many-to-many matches If the same key appears multiple times in either table (say.2].groupjoin — Method.

By default. By default. • lkey::Selection – fields from left to match on • rkey::Selection – fields from right to match on • lselect::Selection – fields from left to use as input to use as output columns._NT_c_d{Int64. d = 2). (c = 3.Int64}[] 1 2 NamedTuples.5. The output is guarranteed to contain julia> groupjoin(l. d = 4)] Options • how::Symbol – join method to use. • rselect::Selection – fields from left to use as input to use as output columns. how=:outer) Table with 3 rows.Int64}[(c = 2. d = 4)] Outer join Outer (aka Union) join looks up rows from right where keys match that in left. a tuple of NA values is used.Int64}[(c = 2.Int64}[(c = 4.Int64}[(c = 4. rkey=:a.GROUPJOIN 163 Left join looks up rows from right where keys match that in left. julia> groupjoin(l. (c = 3. an NA value is used for every selected field from right. (c = 2.13. 3 columns: a b groups 1 1 NamedTuples. lkey=:a.r. d 2 1 NamedTuples. rselect=:d._NT_c_d{Int64.Int64}[] 1 1 NamedTuples.Int64}[] 1 2 NamedTuples. d = 2). if there are no matches on either side. 3 columns: a b groups 0 1 NamedTuples. (c = 2. INDEXEDTABLES. or input to f if it is specified. how=:left) Table with 3 rows. this is all fields not selected in lkey._NT_c_d{Int64. julia> groupjoin(l. (c = 3. d = 2). lselect=:c. d = 3)._NT_c_d{Int64. or input to f if it is specified. If there are no such rows in right._NT_c_d{Int64. (c = 3. d = 3). how=:outer) Table with 4 rows. Described above. and also rows from left where keys match those in left. 2 columns: a groups . this is all fields not selected in rkey. d = 2). d 2 1 NamedTuples.r.r._NT_c_d{Int64._NT_c_d{Int64.

14 IndexedTables. 5 columns: x y + min max 1 1 3 1 2 1 2 3 3 3 2 1 11 5 6 2 2 4 4 4 . by::Selection]. [1. Examples julia> t=table([1. [1. select=:z) Table with 4 rows.groupreduce — Function. t. names=[:x. 3 columns: x y + 1 1 3 1 2 3 2 1 11 2 2 4 julia> groupreduce((+.2. select=:z) Table with 4 rows.1.4. t.2].1]. julia> groupreduce(+._NT_c_d{Int64.6]. (:x.3. t. d = 4)] source 5.1.Int64}[(c = 4._NT_c_d{Int64.:y.groupreduce IndexedTables. (c = 2.Int64}[(c = 1. Recommended: see documentation for reduce first. d = 2). 2 columns: x + 1 6 2 15 julia> groupreduce(+. and apply f to reduce each group. t[.5. The result of reducing each group is put in a table keyed by unique by values.2._NT_c_d{Int64.2. groupreduce(f.Int64}[] 1 NamedTuples. (:x. INDEXEDTABLES 0 NamedTuples. min. :y). OnlineStat or a struct of these as described in reduce.2. select::Selection) Group rows by by. max). (c 2 NamedTuples. the names of the output columns are the same as the names of the fields of the reduced tuples.2. f can be a function. d = 3). (c = 1.164 CHAPTER 5. select=:z) Table with 2 rows. :x. d = 2).:z]).1.1. :y).

insertcol IndexedTables. t.15 IndexedTables. 4 columns: t w x y 0.15. names=[:t. the output columns will be named the same as the functions themselves. :y). [3. it’s possible to select different inputs for different reducers by using a named tuple of slector => function pairs: julia> groupreduce(@NT(xsum=:x=>+. [0. 3 columns: t x y 0. 2. :w. [2.05 1 4 julia> insertcol(t.05]. t. select=:z) Table with 4 rows. 5 columns: x y zsum zmin zmax 1 1 3 1 2 1 2 3 3 3 2 1 11 5 6 2 2 4 4 4 Finally.01 0 2 3 0.01 2 3 0.5. Returns a new table.insertcol — Method. To change the name.05 1 1 4 source . x) Insert a column x named name at position.1]) Table with 2 rows. zmin=min. insertcol(t. :x) Table with 2 rows.INSERTCOL 165 If f is a single function or a tuple of functions. zmax=max). name. 3 columns: x xsum negysum 1 3 -4 2 6 -4 source 5. 0. position::Integer.01. pass a named tuple: julia> groupreduce(@NT(zsum=+. (:x.4]. :x. julia> t = table([0. negysum=(:y=>-)=>+). pkey=:t) Table with 2 rows.1]. INDEXEDTABLES. :y].

:x.insertcolbefore IndexedTables.05 1 1 4 source .05].05]. 3 columns: t x y 0. :y]. name. insertcolafter(t. [3. name. [2. before.1]. 4 columns: t w x y 0. [3. after.insertcolbefore — Method.05 1 1 4 source 5. 0. col) Insert a column col named name after after.01. Returns a new table. pkey=:t) Table with 2 rows.4]. pkey=:t) Table with 2 rows. :x. :y]. names=[:t.1]) Table with 2 rows.1]) Table with 2 rows.166 CHAPTER 5. col) Insert a column col named name before before. 0.1]. julia> t = table([0.insertcolafter IndexedTables.01 0 2 3 0.01 2 3 0.16 IndexedTables.01. INDEXEDTABLES 5.4]. :x.insertcolafter — Method.01 2 3 0. [0. [2. :w. names=[:t. :w. julia> t = table([0.17 IndexedTables. [0.05 1 4 julia> insertcolafter(t. 3 columns: t x y 0. insertcolbefore(t.05 1 4 julia> insertcolbefore(t. 4 columns: t w x y 0. :t. Returns a new table.01 0 2 3 0.

the indices and data are sorted in lexicographic order of the indices. the corresponding data items are reduced using this 2-argument function.8.ndsparse IndexedTables. Not distributed by default. Examples: 1-dimensional NDSparse can be constructed with a single array as index.6]))) 2 julia> ncols(table(@NT(x=[1. agg.9])) 3 source 5.[4.2.ndsparse — Function. If false (the default). See Distributed docs. the passed arrays will be copied only if necessary for sorting. the indices are assumed to already be sorted and no sorting is done. The only way to guarantee sharing of data is to pass presorted=true.18 IndexedTables. copy. ncols(itr) Returns the number of columns in itr.2.5. • chunks::Integer: distribute the table into chunks (Integer) chunks (a safe bet is nworkers()).3]) 1 julia> d = ncols(rows(([1.18.19 IndexedTables.5. INDEXEDTABLES. • copy::Bool: If true.ncols IndexedTables. the storage for the new array will not be shared with the passed indices and data.5.y=[4. data.6]))) 2 julia> ncols(ndsparse(d.6]))) 2 julia> ncols(table(([1. chunks) Construct an NDSparse array with the given indices and data. Arguments: • agg::Function: If indices contains duplicate entries. [7.5. ndsparse(indices. On construction.[4. .2.2.ncols — Function. presorted.NCOLS 167 5.3]. Each vector in indices represents the index values for one dimension.3]. • presorted::Bool: If true. julia> ncols([1.3].

eltype(x) (Tuple{String. INDEXEDTABLES julia> x = ndsparse(["a"."b"].4]) 1-d NDSparse with 2 values (Int64): 1 "a" 3 "b" 4 julia> keytype(x). eltype(x) (Tuple{String}. Int64) julia> x["a".[3. Int64) A dimension will be named if constructed with a named tuple of columns as index.[3.6]) 2-d NDSparse with 2 values (Int64): 1 2 "a" 3 5 "b" 4 6 julia> keytype(x).Int64}. just like in table.4]). julia> x = ndsparse(@NT(date=Date.]) 1-d NDSparse with 4 values (Int64): date 2014-01-01 4 2015-01-01 5 2016-01-01 6 2017-01-01 7 julia> x[Date("2015-01-01")] 5 julia> keytype(x).(2014:2017)). [4:7."b"]. 3] 5 The data itself can also contain tuples (these are stored in columnar format. eltype(x) (Tuple{Date}. [5.) . Int64) Multi-dimensional NDSparse can be constructed by passing a tuple of index columns: julia> x = ndsparse((["a".168 CHAPTER 5.

.10.19. or constructing with a distributed array will cause the result to be distributed.0 julia> x = ndsparse(@NT(x=["a".0 2016-01-01 6.0 "b" 4 7 10.5.].. @NT(p=[5. [7.0 julia> x = ndsparse(@NT(date=Date..])) 2-d NDSparse with 2 values (2-tuples): 1 2 3 4 "a" 3 5 7.4]). Use distribute function to dis- tribute an array.y=[3. eltype(x) (Tuple{String.0 2016-01-01 6. 2)) 1-d Distributed NDSparse with 4 values (Float64) in 2 chunks: date 2014-01-01 4.0 julia> keytype(x).0 "b" 4 6 8.(2014:2017)).0 2015-01-01 5.Float64}) julia> x["a".9. ([5.0 2015-01-01 5.0 "a" 4 6 9. :] 2-d NDSparse with 2 values (2 field named tuples): x y p q "a" 3 5 8.[3."b"].(2014:2017)).Int64}. INDEXEDTABLES.4]). q=[8.0 2017-01-01 7.]."b"].0 .])) 2-d NDSparse with 3 values (2 field named tuples): x y p q "a" 3 5 8.0 "a" 4 6 9. NamedTuples.. julia> x = ndsparse(@NT(date=Date.0 Passing a chunks option to ndsparse.6."a".7]._NT_p_q{Int64.0 2017-01-01 7.8.4.0. [4:7. distribute([4:7. chunks=2) 1-d Distributed NDSparse with 4 values (Float64) in 2 chunks: date 2014-01-01 4.NDSPARSE 169 julia> x = ndsparse((["a".6].

22 IndexedTables.[1. Example julia> t = table([1.) julia> t = table([2.2]. source 5.pkeynames — Method.4]. [3.Columns{NamedTuples. pkeynames(t::Table) Names of the primary key columns in t.20 IndexedTables. names=[:x.) Similar to where.:z]. indices.pairs — Method. pkey=(1.1].Int64}. julia> pkeynames(t) (1.[4. but returns an iterator giving index=>value pairs. source 5._NT_x_y{Int64. pkeynames(t::NDSparse) .pkeynames IndexedTables.NamedTuples.5]. index will be a tuple.pairs IndexedTables. pkey=1).170 CHAPTER 5.2]. y = 3) (x = 2._NT_x_y{Ar (x = 1. pairs(arr::NDSparse.pkeynames — Method.:y.2)).3].. INDEXEDTABLES Distribution is done to match the first distributed column from left to right.4]). julia> pkeys(t) 2-element IndexedTables.pkeynames IndexedTables. julia> pkeynames(t) () julia> t = table([1. Specify chunks to override this. y = 1) source 5.21 IndexedTables.. [3.

pkeys(itr::Table) Primary keys of the table.) source 5.) julia> a = table(["a". Example julia> a = table(["a".PKEYS 171 Names of the primary key columns in t.) is generated. 2 columns: 1 2 "a" 3 "b" 4 .23 IndexedTables.4]) # no pkey Table with 2 rows."b"]. pkey=1) Table with 2 rows. Example julia> x = ndsparse([1.):(n."b"].4]) 1-d NDSparse with 2 values (Int64): 1 1 3 2 4 julia> pkeynames(x) (1.23. [3.) (2.[3. If Table doesn’t have any designated primary key columns (constructed without pkey argument) then a default key of tuples (1.pkeys — Method.4].pkeys IndexedTables. INDEXEDTABLES. [3.2].5. 2 columns: 1 2 "a" 3 "b" 4 julia> pkeys(a) 2-element Columns{Tuple{Int64}}: (1.

01 3 0.172 CHAPTER 5. names=[:t. :x) Table with 2 rows.01.05 4 source 5. 3 columns: t x y 0. pushcol(t. :x.24 IndexedTables.05 1 4 . pkey=:t) Table with 2 rows. 2 columns: t y 0. name is the name for the new column.01.popcol IndexedTables.01 2 3 0. name. Returns a new table.1]. [3.4]. x) Push a column x to the end of the table. Example: julia> t = table([0. [2.05].4].05 1 4 julia> popcol(t. names=[:t. :y]. 0. popcol(t.05]. julia> t = table([0.popcol — Method.01 2 3 0.pushcol IndexedTables.1].25 IndexedTables. :y]. [2.) ("b". Returns a new table. pkey=:t) Table with 2 rows. [3. col) Remove the column col from the table.) source 5. INDEXEDTABLES julia> pkeys(a) 2-element Columns{Tuple{String}}: ("a". 0. 3 columns: t x y 0. :x.pushcol — Method.

pkey=(1.26 IndexedTables. reindex(t::Table.26.:y.[4. arr::NDSparse.[1.REDUCEDIM VEC 173 julia> pushcol(t. :z) julia> reindex(t. 4 columns: w z x y 4 5 1 3 5 4 2 1 julia> pkeynames(t) . Keeps columns selected by select as non-indexed columns. except uses a function mapping a vector of values to a scalar instead of a 2-argument scalar function. source 5.:z].3]. julia> t = table([2.reducedim vec — Method.27 IndexedTables. Use selectkeys to reindex and NDSparse object. reducedim vec(f::Function. dims) Like reducedim.reindex — Function. 3//4]) Table with 2 rows.2)) julia> reindex(t. (:y. select]) Reindex t by columns selected in by. :z)) Table with 2 rows.5]. (:w=>[4.reducedim vec IndexedTables. By default all columns not mentioned in by are kept. INDEXEDTABLES.5].5.05 1 4 3//4 source 5.01 2 3 1//2 0. names=[:x. [1//2.1]. :z)) Table with 2 rows.reindex IndexedTables. :z. 3 columns: y z x 1 4 2 3 5 1 julia> pkeynames(t) (:y. 4 columns: t x y z 0. by[.

[3. :time) Table with 2 rows. itr can be NDSparse.rows — Function.05]. Examples julia> t = table([1.174 CHAPTER 5. Returns a new table. rows(itr[.01 2 0.01 2 0. newname) Set newname as the new name for column col in t. INDEXEDTABLES (:w.29 IndexedTables.1]. Columns and AbstractVector. :x]) Table with 2 rows. returns all columns. 0. col.rows IndexedTables.renamecol IndexedTables. julia> t = table([0. :t. If unspecified. select specifies which fields to select.05 1 source 5. 2 columns: x y 1 3 2 4 julia> rows(t) . names=[:t. and their distributed counterparts. renamecol(t. 2 columns: time x 0. [2. See Selection convention for pos- sible values.renamecol — Method.4]. 2 columns: t x 0.2]. select::Selection]) Select one or more fields from an iterable of rows as a vector of their values.05 1 julia> renamecol(t.01.28 IndexedTables. names=[:x.:y]) Table with 2 rows. :z) source 5.

30 IndexedTables. [3._NT_x{Int64}.4]. :y]) Table with 2 rows._NT_x_y{Int64. x = -1) (y = 4.Int64}..1}}}: (x = 1) (x = 2) julia> rows(t._NT_x_y{Array{Int64. map::Pair. 2.NamedTuples. Returns a new table.)) 2-element IndexedTables. (:y.Columns{NamedTuples.SETCOL 175 2-element IndexedTables. INDEXEDTABLES. Int}. (x = 1. :x) 2-element Array{Int64. x::Selection) Sets a x as the column identified by col. (:x. x = -2) Note that vectors of tuples returned are Columns object and have columnar internal storage._NT_x{Array{Int64. names=[:x.:x=>-)) 2-element IndexedTables.setcol IndexedTables. source 5._NT_y_x{Int64. Examples: julia> t = table([1.setcol — Method. (y = 3.Columns{NamedTuples.. setcol(t::Table.) Set many columns at a time. 2 columns: x y 1 5 2 6 .6]) Table with 2 rows.2]. [5. y = 4) julia> rows(t.Columns{NamedTuples. col::Union{Symbol.5. setcol(t::Table.NamedTuples.1}: 1 2 julia> rows(t.30.NamedTuples._NT_y_x{Array{Int64. y = 3) (x = 2.Int64}. 2 columns: x y 1 3 2 4 julia> setcol(t.

2].4]..5.05 2 4 0. 3 columns: t x y 0. julia> t = table([0. :x => x->1/x) Table with 2 rows.01 1 3 0. [4. INDEXEDTABLES x can be any selection that transforms existing columns.05]. the table will be an iterator of named tuples.. :x.05]) Table with 2 rows. julia> a = table([1.6]) Table with 3 rows. pkey=:t) Table with 2 rows.0 5 0.5 6 setcol will result in a re-sorted copy if a primary key column is replaced.0.table — Function. :t.3].31 IndexedTables. names=[:t.table IndexedTables. 3 columns: t x y 0. names. 0.05 2 4 julia> t2 = setcol(t. table(cols::AbstractVector.2. [0.176 CHAPTER 5. julia> setcol(t.1. . <options>) Create a table with columns given by cols. [1. 2 columns: x y 1.01. :x.. :y]. If specified. 2 columns: 1 2 1 4 2 5 3 6 names specify names for columns. [3.1 1 3 julia> t == t2 false source 5.

• chunks: distribute the table into chunks (Integer) chunks (a safe bet is nworkers()).3].3]. NamedTuple}. true by default. <options>) Construct a table from an iterable table. Table is not distributed by default. INDEXEDTABLES. [4.3].31. julia> table(([1. <options>) Copy a Table or NDSparse to create a new table.6]. By default. The same primary keys as the input are used.2.3].3]. [4.TABLE 177 julia> b = table([1.6])) == a true julia> table(@NT(x=[1. Options: • pkey: select columns to act as the primary key.2. y=[4.6])) == a true julia> table(Columns(x=[1.6])) == b true table(t::Union{Table. no columns are used as primary key. y=[4.5. Irrelevant if chunks is specified.2.2. See rows. [4. NDSparse}. julia> b == table(b) true table(iter. julia> table(Columns([1.5. Irrela- vant if chunks is specified. <options>) Construct a table from a vector of tuples.5. :y]) Table with 3 rows. names=[:x.2. false by default.5.5.6])) == b true table(cols::Columns. See Distributed docs. • copy: creates a copy of the input vectors if true.5. • presorted: is the data pre-sorted by primary key columns? If so. skip sorting. . <options>) Convert a struct of columns to a table of structs. 2 columns: x y 1 4 2 5 3 6 table(cols::Union{Tuple.

INDEXEDTABLES Examples: Specifying pkey will cause the table to be sorted by the columns named in pkey: julia> b = table([2. 3.3.5. pkey=(:x.3. i.5. :y. julia> t = table([2. An integer – number of chunks to create 2.6]. pkey=:x.[2.[4. 3 columns: x y z 1 3 5 1 3 7 2 1 6 2 2 4 Note that the keys do not have to be unique. The distribution of another array.1]. :y].2.e. [4. names=[:x.1.6.:y)) Table with 4 rows.5. names=[:x.1. names=[:x.3].3. :z].1.178 CHAPTER 5. A distributed Array can be constructed using distribute: . chunks=2) Distributed Table with 4 rows in 2 chunks: x y 1 6 2 4 3 5 4 7 A distributed table will be constructed if one of the arrays passed into table constructor is a distributed array.subdomains where vec is a distributed array. An vector of k integers – number of elements in each of the k chunks.7]. pkey=:x) Table with 3 rows. vec.4].6. 2 columns: x y 1 6 2 4 3 5 julia> b = table([2.1]. chunks can be: 1. [4.7]. :y]. chunks option creates a distributed table.

UPDATE! 179 julia> x = distribute([1. indices. [9.4].update! — Method.:y]) Distributed Table with 4 rows in 2 chunks: x y 1 5 2 6 3 7 4 8 julia> table(columns(t). [5.update! IndexedTables. source 5.where IndexedTables.:y.11. INDEXEDTABLES... source . names=[:x.33 IndexedTables.) Returns an iterator over data items where the given indices match. names=[:x. Accepts the same index arguments as getindex.) Replace data values x with f(x) at each location that matches the given indices..:z]) Distributed Table with 4 rows in 2 chunks: x y z 1 5 9 2 6 10 3 7 11 4 8 12 Distribution is done to match the first distributed column from left to right. Specify chunks to override this. arr::NDSparse.12].10. indices.8].3. where(arr::NDSparse. source 5...where — Method.32. update!(f::Function. julia> t = table(x.32 IndexedTables.5.2...6.7. 2).

r = red(img) extracts the red channel from an RGB image img source 6.blue ColorTypes.Chapter 6 Images 6. g = green(img) extracts the green channel from an RGB image img source 6.adjust gamma Images. If the input is an Image then the resulting image is of the same type and has the same properties. gamma_corrected_img = adjust_gamma(img.blue — Function. The adjust gamma function can handle a variety of input types. b = blue(img) extracts the blue channel from an RGB image img source 6.red ColorTypes. gamma) Returns a gamma corrected image.adjust gamma — Method.4 Images.red — Function. 180 .green — Function.1 ColorTypes. The re- turned image depends on the input type.green ColorTypes.3 ColorTypes.2 ColorTypes.

IMAGES. tl_y. source 6. 79–116.blob LoG — Method.7 Images. xtop:xbot) sum = boxdiff(integral_image.boxdiff — Method. the input is converted to YIQ type and the Y channel is gamma corrected. source 6. c) Bilinear Interpolation is used to interpolate functions of two variables on a rectilinear 2D grid.5. By default. where is scales[i] * shape for some i. [edges]. The optional edges argument controls whether peaks on the edges are in- cluded. sum = boxdiff(integral_image. The interpolation is done in one direction first and then the values obtained are used to do the interpolation in the second direction.6. br_x)) sum = boxdiff(integral_image. br_y. and the remaining N entries control each of the N dimensions of img. ytop:ybot. The algorithm searches for places where the filtered image (for a particular ) is at a peak compared to all spatially. CartesianIndex(tl_y.bilinear interpolation — Method. source 6. shape is an ntuple of 1s.bilinear interpolation Images. or a N+1-tuple in which the first entry controls whether edge.values are eligible to serve as peaks.5 Images. International Journal of Computer Vision. r. P = bilinear_interpolation(img. tl_x). blob_LoG(img. Citation: Lindeberg T (1998). 30(2).and -adjacent voxels. “Feature Detection with Automatic Scale Selection”. scales. [shape]) -> Vector{BlobLoG} Find “blobs” in an N-D image using the negative Lapacian of Gaussians with the specifed vector or tuple of values. See also: BlobLoG.boxdiff Images. br_x) . CartesianIndex(br_y.6 Images. This is the combined with the I and Q channels and the resulting image converted to the same type as the input.blob LoG Images. tl_x. edges can be true or false.BILINEAR INTERPOLATION 181 For coloured images.

clip = 3) Performs Contrast Limited Adaptive Histogram Equalisation (CLAHE) on the input image. . (upper. Parameters : (upper. . * * * * * * * - . B - . . . irrespective of the size of the window. lower) : Bounds for hysteresis thresholding sigma : Specifies the standard deviation of the gaussian filter Example [] imgedg = canny(img. sigma=1. xblocks = 8. yblocks = 8.8 Images.B . lower).clahe Images. given the yrange and xrange of the window.C. It is therefore suitable for improving the local contrast and enhancing the definitions of edges in each region of an image.182 CHAPTER 6. hist_equalised_img = clahe(img. source 6. The sum of a window in an image can be directly calculated using four array references of the integral image. . . nbins. IMAGES An integral image is a data structure which helps in efficient calculation of sum of pixels in a rectangular subset of an image. . * * * * * * * - C * * * * * * D - . It stores at each pixel the sum of all pixels above it and to its left. (Percentile(80). * * * * * * * - . and uses them to redistribute the lightness values of the image. . - The sum of pixels in the area denoted by * is given by S = D + A . . . Percentile(20))) source 6.clahe — Method. . . Given an integral image - A . * * * * * * * - . canny_edges = canny(img.canny — Method. each corresponding to a distinct section of the image. It differs from ordinary histogram equalization in the respect that the adaptive method computes several histograms. . * * * * * * * - .4) Performs Canny Edge Detection on the input image.canny Images.9 Images.

source 6. Then.11 Images.component boxes Images. CLAHE is done by calculation a histogram of a window around each pixel and using the transformation function of the equalised histogram to rescale the pixel. we use interpolation which gives a significant rise in efficiency without compromising the result. If x is a color with an alpha channel.10 Images. clip) Clips the histogram above a certain value clip. y = complement(x) Take the complement 1-x of x.CLIPHIST 183 In the straightforward form.12 Images.complement — Method. source 6.component boxes — Method.cliphist — Method.6.cliphist Images. including the background label 0 source . the alpha channel is left untouched. The image is divided into a grid and equalised his- tograms are calculated for each block. IMAGES. The xblocks and yblocks specify the number of blocks to divide the input image into in each direction. Since this is computationally expen- sive. component boxes(labeled array) -> an array of bounding boxes for each label. nbins specifies the granularity of histogram cal- culation of each local region. clipped_hist = cliphist(hist. clip specifies the value at which the histogram is clipped. each pixel is interpolated using the closest histograms. The excess left in the bins exceeding clip is redistributed among the remaining bins. The excess in the histogram bins with value exceeding clip is redis- tributed among the other bins.complement Images. source 6.10.

[kind=:shannon]) .component subscripts Images.convexhull — Method. etc. component lengths(labeled array) -> an array of areas (2D). component subscripts(labeled array) -> an array of pixels for each la- bel.14 Images. for each label.18 Images. source 6.component centroids Images.16 Images.convexhull Images.entropy Images.component indices — Method.184 CHAPTER 6. including the background label 0 source 6.17 Images.component subscripts — Method.component indices Images. chull = convexhull(img) Computes the convex hull of a binary image and returns the vertices of convex hull as a CartesianIndex array. img) entropy(img.15 Images. component indices(labeled array) -> an array of pixels for each label.component lengths Images.component centroids — Method. including the background label 0 source 6. including the background label 0 source 6. IMAGES 6.component lengths — Method. entropy(log. including the background label 0 source 6. volumes (3D). component centroids(labeled array) -> an array of centroids for each label.13 Images.entropy — Method.

[region.findlocalminima Images. or use log = log10 source 6. or use log = log2 • :nat (log base e). source 6. source 6. entropy unit) is one of the following: • :shannon (log base 2. pyramid = gaussian_pyramid(img. threshold) -> corners Performs FAST Corner Detection.19.22 Images.findlocalminima — Function.findlocalmaxima — Function. findlocalmaxima(img. region is a list of dimensions to consider.21 Images. downsample.19 Images. n. default). Like findlocalmaxima. or a tuple-of-Bool specifying edge behavior for each dimension separately.*log(p)). fastcorners(img. The base of the logarithm (a.fastcorners — Method. each downsampled by a factor downsample and sigma for the gaussian kernel. edges]) -> Vector{CartesianIndex} Returns the coordinates of elements whose value is larger than all of their immediate neighbors. source .findlocalmaxima Images.threshold) for a pixel to be marked as a corner. The default value for n is 12. n is the number of contiguous pixels which need to be greater (lesser) than intensity + threshold (intensity .gaussian pyramid — Method. n_scales. source 6.20 Images. sigma) Returns a gaussian pyramid of scales n scales. or use log = log • :hartley (log base 10).FASTCORNERS 185 Compute the entropy of a grayscale image defined as -sum(p. but returns the coordinates of the smallest elements.a.fastcorners Images.gaussian pyramid Images. edges is a boolean specifying whether to include the first and last elements of each dimen- sion.k. IMAGES.6.

nbins. [k]. The histeq function can handle a variety of input types. imgB) is the modified Hausdorff distance be- tween binary images (or point sets). This is the combined with the I and Q channels and the resulting image converted to the same type as the input.histeq — Method. maxval). maxval) Returns a histogram equalised image with a granularity of approximately nbins number of bins.hausdorff distance — Method. source 6. hausdorff distance(imgA. Jain. If minval and maxval are specified then intensities are equalized to the range (minval. harris_response = harris(img.24 Images.harris — Method.23 Images.25 Images. minval. hist_matched_img = histmatch(img.histeq Images.186 CHAPTER 6. oimg. hist_equalised_img = histeq(img. the input is converted to YIQ type and the Y channel is equalised. M-P. IMAGES 6. 1994. source 6.harris Images. nbins) hist_equalised_img = histeq(img. The returned image depends on the input type. A Modified Hausdorff Distance for Object-Matching.histmatch Images. A. References Dubuisson. [border]. nbins) . source 6. K. The default values are 0 and 1. For coloured images.histmatch — Function.hausdorff distance Images. If the input is an Image then the resulting image is of the same type and has the same properties. [weights]) Performs Harris corner detection..26 Images. The covariances can be taken using either a mean weighted filter or a gamma kernel.

minval. source 6. and iterations is the number of relaxation iterations taken. [method]) Performs corner detection using one of the following methods - 1. threshold.6.maxval)]) -> Image Map intensities over the interval (minval. corners = imcorner(img.imROF — Method.imcorner Images. See https://en.imadjustintensity — Method.maxval) to the interval [0. [method]) corners = imcorner(img. Journal of Mathematical Imaging and Vision. kitchen_rosenfeld The parameters of the individual methods are described in their documen- tation.29 Images.imROF Images. img is the image to be matched and oimg is the image having the desired histogram to be matched to.wikipedia. iterations) Perform Rudin-Osher-Fatemi (ROF) filtering. source 6. harris 2. maxval). more commonly known as To- tal Variation (TV) denoising or TV regularization. shi_tomasi 3. (minval.1]. . (2004).maxval) defaults to extrema(img).imadjustintensity Images. A. 2d only.imcorner — Method. This is equivalent to map(ScaleMinMax(eltype(img). img). “An algorithm for total variation minimization and applications”.28 Images.27 Images.org/wiki/Total variation denoising and Chambolle. 20: 89–97 source 6. IMAGES.IMROF 187 Returns a grayscale histogram matched image with a granularity of nbins number of bins. (minval. imgr = imROF(img. The maxima values of the resultant responses are taken as corners. imadjustintensity(img [. percentile. is the regularization coeffi- cient for the derivative.27. If a .

The threshold is assumed to be a percentile value unless percentile is set to false.ando3. source 6. orient). defaulting to KernelFactors.31 Images.imedge Images. vertical gradient. orient = imedge(img. maxval]. count[1] is the number satisfying x < edges[1]. count[i+1] is the number of values x that satisfy edges[i] <= x < edges[i+1]. respectively. minval.imedge — Function. the new intensity is 1/(1+(m/(p+eps))^slope). Returns a tuple (grad y. mag. and the magnitude and orientation of the strongest edge. and count[end] is the number satisfying x >= edges[end]. which are the horizontal gradient. source 6. nbins. nbins) edges. grad x. maxval) Generates a histogram for the image over nbins spread between (minval. This is essentially a symmetric gamma-correction.imhist — Method.imhist Images. border is any of the boundary conditions specified in padarray. mag. source .30 Images.ando3. respectively) the contrast near saturation (0 and 1). For a pixel of brightness p. border="replic Edge-detection filtering. If minval and maxval are not given. then the minimum and maximum values present in the image are taken.imstretch — Method.32 Images.imstretch Images. count = imhist(img. source 6. count = imhist(img. edges is a vector that specifies how the range is divided. length(count) == length(edges)+1. Consequently. the values of the responses are thresholded to give the cor- ner pixels. m. IMAGES threshold is specified. grad_x. kernelfun is a valid kernel function for imgradients. This assumes the input img has intensities between 0 and 1. imgs = imstretch(img. kernelfun=KernelFactors. edges. grad_y. slope) enhances or reduces (for slope > 1 or < 1.188 CHAPTER 6.

6.33. IMAGES.INTEGRAL IMAGE 189

6.33 Images.integral image
Images.integral image — Method.
integral_img = integral_image(img)
Returns the integral image of an image. The integral image is calculated
by assigning to each pixel the sum of all pixels above it and to its left, i.e. the
rectangle from (1, 1) to the pixel. An integral image is a data structure which
helps in efficient calculation of sum of pixels in a rectangular subset of an image.
See boxdiff for more information.
source

6.34 Images.kitchen rosenfeld
Images.kitchen rosenfeld — Method.
kitchen_rosenfeld_response = kitchen_rosenfeld(img; [border])
Performs Kitchen Rosenfeld corner detection. The covariances can be taken
using either a mean weighted filter or a gamma kernel.
source

6.35 Images.label components
Images.label components — Function.
label = label_components(tf, [connectivity])
label = label_components(tf, [region])
Find the connected components in a binary array tf. There are two forms
that connectivity can take:
• It can be a boolean array of the same dimensionality as tf, of size 1 or 3
along each dimension. Each entry in the array determines whether a given
neighbor is used for connectivity analyses. For example, connectivity = trues(3,3)
would use 8-connectivity and test all pixels that touch the current one, even the
corners.
• You can provide a list indicating which dimensions are used to
determine connectivity. For example, region = [1,3] would not test neigh-
bors along dimension 2 for connectivity. This corresponds to just the nearest
neighbors, i.e., 4-connectivity in 2d and 6-connectivity in 3d.
The default is region = 1:ndims(A).
The output label is an integer array, where 0 is used for background pixels,
and each connected region gets a different integer index.
source

190 CHAPTER 6. IMAGES

6.36 Images.magnitude
Images.magnitude — Method.

m = magnitude(grad_x, grad_y)

Calculates the magnitude of the gradient images given by grad x and grad y.
Equivalent to sqrt(gradx .2 + grady .2 ).
Returns a magnitude image the same size as grad x and grad y.
source

6.37 Images.magnitude phase
Images.magnitude phase — Method.

magnitude_phase(grad_x, grad_y) -> m, p

Convenience function for calculating the magnitude and phase of the gradient
images given in grad x and grad y. Returns a tuple containing the magnitude
and phase images. See magnitude and phase for details.
source

6.38 Images.maxabsfinite
Images.maxabsfinite — Method.
m = maxabsfinite(A) calculates the maximum absolute value in A, ignoring
any values that are not finite (Inf or NaN).
source

6.39 Images.maxfinite
Images.maxfinite — Method.
m = maxfinite(A) calculates the maximum value in A, ignoring any values
that are not finite (Inf or NaN).
source

6.40 Images.meanfinite
Images.meanfinite — Method.
M = meanfinite(img, region) calculates the mean value along the dimen-
sions listed in region, ignoring any non-finite values.
source

6.41. IMAGES.MINFINITE 191

6.41 Images.minfinite
Images.minfinite — Method.
m = minfinite(A) calculates the minimum value in A, ignoring any values
that are not finite (Inf or NaN).
source

6.42 Images.ncc
Images.ncc — Method.
C = ncc(A, B) computes the normalized cross-correlation of A and B.
source

6.43 Images.orientation
Images.orientation — Method.

orientation(grad_x, grad_y) -> orient

Calculate the orientation angle of the strongest edge from gradient images
given by grad x and grad y. Equivalent to atan2(grad x, grad y). When
both grad x and grad y are effectively zero, the corresponding angle is set to
zero.
source

6.44 Images.otsu threshold
Images.otsu threshold — Method.

thres = otsu_threshold(img)
thres = otsu_threshold(img, bins)

Computes threshold for grayscale image using Otsu’s method.
Parameters:

• img = Grayscale input image

• bins = Number of bins used to compute the histogram. Needed for
floating-point images.

source

192 CHAPTER 6. IMAGES

6.45 Images.phase
Images.phase — Method.

phase(grad_x, grad_y) -> p

Calculate the rotation angle of the gradient given by grad x and grad y.
Equivalent to atan2(-grad y, grad x), except that when both grad x and
grad y are effectively zero, the corresponding angle is set to zero.
source

6.46 Images.sad
Images.sad — Method.
s = sad(A, B) computes the sum-of-absolute differences over arrays/images
A and B
source

6.47 Images.sadn
Images.sadn — Method.
s = sadn(A, B) computes the sum-of-absolute differences over arrays/images
A and B, normalized by array size
source

6.48 Images.shepp logan
Images.shepp logan — Method.

phantom = shepp_logan(N,[M]; highContrast=true)

output the NxM Shepp-Logan phantom, which is a standard test image usu-
ally used for comparing image reconstruction algorithms in the field of computed
tomography (CT) and magnetic resonance imaging (MRI). If the argument M
is omitted, the phantom is of size NxN. When setting the keyword argument
highConstrast to false, the CT version of the phantom is created. Otherwise,
the high contrast MRI version is calculated.
source

6.49 Images.shi tomasi
Images.shi tomasi — Method.

shi_tomasi_response = shi_tomasi(img; [border], [weights])

6.50. IMAGES.SSD 193

Performs Shi Tomasi corner detection. The covariances can be taken using
either a mean weighted filter or a gamma kernel.
source

6.50 Images.ssd
Images.ssd — Method.
s = ssd(A, B) computes the sum-of-squared differences over arrays/images
A and B
source

6.51 Images.ssdn
Images.ssdn — Method.
s = ssdn(A, B) computes the sum-of-squared differences over arrays/images
A and B, normalized by array size
source

6.52 Images.thin edges
Images.thin edges — Method.

thinned = thin_edges(img, gradientangle, [border])
thinned, subpix = thin_edges_subpix(img, gradientangle, [border])
thinned, subpix = thin_edges_nonmaxsup(img, gradientangle, [border]; [radius::Float64=1.35], [the
thinned, subpix = thin_edges_nonmaxsup_subpix(img, gradientangle, [border]; [radius::Float64=1.35

Edge thinning for 2D edge images. Currently the only algorithm available
is non-maximal suppression, which takes an edge image and its gradient angle,
and checks each edge point for local maximality in the direction of the gradient.
The returned image is non-zero only at maximal edge locations.
border is any of the boundary conditions specified in padarray.
In addition to the maximal edge image, the subpix versions of these func-
tions also return an estimate of the subpixel location of each local maxima, as a
2D array or image of Graphics.Point objects. Additionally, each local maxima
is adjusted to the estimated value at the subpixel location.
Currently, the nonmaxsup functions are identical to the first two function
calls, except that they also accept additional keyword arguments. radius indi-
cates the step size to use when searching in the direction of the gradient; values
between 1.2 and 1.5 are suggested (default 1.35). theta indicates the step size
to use when discretizing angles in the gradientangle image, in radians (default:
1 degree in radians = pi/180).
Example:

194 CHAPTER 6. IMAGES

g = rgb2gray(rgb_image)
gx, gy = imgradients(g)
mag, grad_angle = magnitude_phase(gx,gy)
mag[mag .< 0.5] = 0.0 # Threshold magnitude image
thinned, subpix = thin_edges_subpix(mag, grad_angle)

source

Chapter 7

DataFrames

7.1 DataFrames.aggregate
DataFrames.aggregate — Method.
Split-apply-combine that applies a set of functions over columns of an Ab-
stractDataFrame or GroupedDataFrame
[] aggregate(d::AbstractDataFrame, cols, fs) aggregate(gd::GroupedDataFrame,
fs)
Arguments

• d : an AbstractDataFrame

• gd : a GroupedDataFrame

• cols : a column indicator (Symbol, Int, Vector{Symbol}, etc.)

• fs : a function or vector of functions to be applied to vectors within
groups; expects each argument to be a column vector

Each fs should return a value or vector. All returns must be the same
length.
Returns

• ::DataFrame

Examples
[] df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]), b = repeat([2, 1],
outer=[4]), c = randn(8)) aggregate(df, :a, sum) aggregate(df, :a, [sum, mean])
aggregate(groupby(df, :a), [sum, mean]) df —¿ groupby(:a) —¿ [sum, mean]
equivalent
source

195

196 CHAPTER 7. DATAFRAMES

7.2 DataFrames.by
DataFrames.by — Method.
Split-apply-combine in one step; apply f to each grouping in d based on
columns col
[] by(d::AbstractDataFrame, cols, f::Function) by(f::Function, d::AbstractDataFrame,
cols)
Arguments

• d : an AbstractDataFrame

• cols : a column indicator (Symbol, Int, Vector{Symbol}, etc.)

• f : a function to be applied to groups; expects each argument to be an
AbstractDataFrame

f can return a value, a vector, or a DataFrame. For a value or vector, these
are merged into a column along with the cols keys. For a DataFrame, cols are
combined along columns with the resulting DataFrame. Returning a DataFrame
is the clearest because it allows column labeling.
A method is defined with f as the first argument, so do-block notation can
be used.
by(d, cols, f) is equivalent to combine(map(f, groupby(d, cols))).
Returns

• ::DataFrame

Examples
[] df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]), b = repeat([2, 1],
outer=[4]), c = randn(8)) by(df, :a, d -¿ sum(d[:c])) by(df, :a, d -¿ 2 * d[:c]) by(df,
:a, d -¿ DataFrame(cs um = sum(d[: c]), cm ean = mean(d[: c])))by(df, : a, d− > DataF rame(c = d[: c], cm

source

7.3 DataFrames.coefnames
DataFrames.coefnames — Method.

coefnames(mf::ModelFrame)

Returns a vector of coefficient names constructed from the Terms member
and the types of the evaluation columns.
source

7.4. DATAFRAMES.COLWISE 197

7.4 DataFrames.colwise
DataFrames.colwise — Method.
Apply a function to each column in an AbstractDataFrame or Grouped-
DataFrame
[] colwise(f::Function, d) colwise(d)
Arguments

• f : a function or vector of functions

• d : an AbstractDataFrame of GroupedDataFrame

If d is not provided, a curried version of groupby is given.
Returns

• various, depending on the call

Examples
[] df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]), b = repeat([2, 1],
outer=[4]), c = randn(8)) colwise(sum, df) colwise(sum, groupby(df, :a))
source

7.5 DataFrames.combine
DataFrames.combine — Method.
Combine a GroupApplied object (rudimentary)
[] combine(ga::GroupApplied)
Arguments

• ga : a GroupApplied

Returns

• ::DataFrame

Examples
[] df = DataFrame(a = repeat([1, 2, 3, 4], outer=[2]), b = repeat([2, 1],
outer=[4]), c = randn(8)) combine(map(d -¿ mean(d[:c]), gd))
source

7.6 DataFrames.completecases!
DataFrames.completecases! — Method.
Delete rows with NA’s.
[] completecases!(df::AbstractDataFrame)
Arguments

x = rand(10).198 CHAPTER 7. Indexes of complete cases (rows without NA’s) [] completecases(df::AbstractDataFrame) Arguments • df : the AbstractDataFrame Result • ::Vector{Bool} : indexes of complete cases See also completecases!. y = rand([”a”. :x] = NA df[[9. ”b”.4. ”c”]. 10)) eltypes(df) source . ”b”. :x] = NA df[[9.10]. ”c”].completecases — Method. Column elemental types [] eltypes(df::AbstractDataFrame) Arguments • df : the AbstractDataFrame Result • ::Vector{Type} : the elemental type of each column Examples [] df = DataFrame(i = 1:10. ”b”.7 DataFrames.5].completecases DataFrames. y = rand([”a”. DATAFRAMES • df : the AbstractDataFrame Result • ::AbstractDataFrame : the updated version See also completecases. ”c”].8 DataFrames. x = rand(10). Examples [] df = DataFrame(i = 1:10.10].eltypes — Method. Examples [] df = DataFrame(i = 1:10. y = rand([”a”.4. 10)) df[[1. 10)) df[[1. :y] = NA completecases(df) source 7. x = rand(10). :y] = NA completecases!(df) source 7.eltypes DataFrames.5].

. 2. outer=[4]). outer=[2]). applies functions in the form of a cross product • combine : combine (obviously) • colwise : apply a function to each column in an AbstractDataFrame or GroupedDataFrame Piping methods |> are also provided. DATAFRAMES. gd)) df —¿ groupby(:a) —¿ [sum. r::Int = 6) Arguments . a curried version of groupby is given. 3. length] df —¿ groupby([:a. length] source 7. :a) gd[1] last(gd) vcat([g[:b] for g in gd].9. A GroupedDataFrame also supports indexing by groups and map. See the DataFramesMeta package for more operations on GroupedDataFrames.10 DataFrames. cols) groupby(cols) Arguments • d : an AbstractDataFrame • cols : an If d is not provided. See the following for additional split-apply-combine operations: • by : split-apply-combine using functions • aggregate : split-apply-combine..GROUPBY 199 7. 1].9 DataFrames. 4].head — Function.head DataFrames. b = repeat([2. Show the first or last part of an AbstractDataFrame [] head(df::AbstractDataFrame.7.groupby DataFrames.groupby — Method. gd) returns a GroupApplied object combine(map(d -¿ mean(d[:c]). Returns • ::GroupedDataFrame : a grouped view into d Details An iterator over a GroupedDataFrame returns a SubDataFrame view for each grouping into d. c = randn(8)) gd = groupby(df. Examples [] df = DataFrame(a = repeat([1.) for g in gd println(g) end map(d -¿ mean(d[:c]). :b]) —¿ [sum. r::Int = 6) tail(df::AbstractDataFrame. A view of an AbstractDataFrame split into row groups [] groupby(d::AbstractDataFrame.

an error will be raised if duplicate names are found. ”b”.11 DataFrames.names! DataFrames.200 CHAPTER 7. :c]) names!(df. normally a Vector{Symbol} the same length as the number of columns in df • allow duplicates : if false (the default). :a]) throws ArgumentError names!(df. A stacked view of a DataFrame (long format). y = rand([”a”.names! — Method. ”c”]. Set column names [] names!(df::AbstractDataFrame.12 DataFrames. DATAFRAMES • df : the AbstractDataFrame • r : the number of rows to show Result • ::AbstractDataFrame : the first or last part of df Examples [] df = DataFrame(i = 1:10. vals) Arguments • df : the AbstractDataFrame • vals : column names. ”b”. Stacks a DataFrame. ”c”]. :b. [:a. see stackdf source 7. Result • ::AbstractDataFrame : the updated result Examples [] df = DataFrame(i = 1:10.melt — Method.13 DataFrames. 10)) names!(df. :a]. :b. 10)) head(df) tail(df) source 7. y = rand([”a”.meltdf DataFrames. allowd uplicates = true)renamessecond : ato : a1 source . convert from a wide to long format.melt DataFrames. see stack. if true. x = rand(10). source 7. x = rand(10). :b.meltdf — Method. duplicate names will be suffixed with i (i starting at 1 for the first duplicate). [:a. [:a.

NONUNIQUE 201 7. Set to Char[] to disable this feature and slightly improve performance. DATAFRAMES. . ) [] readtable(filename.15 DataFrames.14 DataFrames. If not specified. Defaults to true. . y = rand([”a”.wsv defaults to .csv defaults to .7. Read data from a tabular-file format (CSV. [keyword options]) Arguments • filename::AbstractString : the filename to be read Keyword Arguments • header::Bool – Use the information from the file’s header line to deter- mine column names. it will be guessed from the filename: . TSV. • quotemark::Vector{Char} – Assume that fields contained inside of two quotemark characters are quoted. Vector{Symbol}.readtable — Method. . ”b”. x = rand(10). which disables processing of separators and linebreaks. etc. Defaults to ["]. .nonunique DataFrames. .tsv defaults to . Examples [] df = DataFrame(i = 1:10. • decimal::Char – Assume that the decimal place in numbers is written using the decimal character. 1) source 7. ”c”].) specifying the column(s) to compare Result • ::Vector{Bool} : indicates whether the row is a duplicate of some prior row See also unique and unique!.. df) nonunique(df) nonunique(df. . Defaults to .nonunique — Method. • separator::Char – Assume that fields are split by the separator char- acter. Int. Indexes of complete cases (rows without NA’s) [] nonunique(df::AbstractDataFrame) nonunique(df::AbstractDataFrame.14. 10)) df = vcat(df. cols) Arguments • df : the AbstractDataFrame • cols : a column indicator (Symbol.readtable DataFrames..

• eltypes::Vector – Specify the types of all columns. • skipstart::Int – Specify the number of initial rows to skip. • encoding::Symbol – Specify the file’s encoding as either :utf8 or :latin1. Defaults to false. Defaults to 0. • skipblanks::Bool – Skip any blank lines in input. which indi- cates that the entire file should be read. • ignorepadding::Bool – Ignore all whitespace on left and right sides of a field. Defaults to :utf8. "f". Defaults to []. Defaults to []. Defaults to ["". "TRUE".202 CHAPTER 7. • commentmark::Char – Specify the character that starts comments. Defaults to ["T". Defaults to -1. • truestrings::Vector{String} – Translate any of the strings into this vector into a Boolean true. De- faults to #. "false"]. • skiprows::Vector{Int} – Specify the indices of lines in the input to ignore. Defaults to true. • falsestrings::Vector{String} – Translate any of the strings into this vector into a Boolean false. For instance this renames a column named "a b" to "a b" which can then be accessed with :a b instead of Symbol("a b"). "FALSE". Defaults to true. Defaults to true. • nrows::Int – Read only nrows from the file. • normalizenames::Bool – Ensure that column names are valid Julia iden- tifiers. "NA"]. • names::Vector{Symbol} – Use the values in this array as the names for all columns instead of or in lieu of the names in the file’s header. • allowcomments::Bool – Ignore all text inside comments. Defaults to ["F". which indicates that the header should be used if present or that numeric names should be invented if there is no header. Defaults to []. Result • ::DataFrame . "true"]. • makefactors::Bool – Convert string columns into PooledDataVector’s for use as factors. "t". Defaults to false. DATAFRAMES • nastrings::Vector{String} – Translate any of the strings into this vec- tor into an NA.

df::AbstractDataFrame) Arguments • df : the AbstractDataFrame • d : an Associative type that maps the original name to a new name • f : a function that has the old column name (a symbol) as input and new column name (a symbol) as output .rename — Function. from::Symbol. df) rename(df. :x=¿:X)) rename(df. y = rand([”a”. d::Associative) rename!(f::Function. Dict(:i=¿:A. from::Symbol.16 DataFrames. Rename columns [] rename!(df::AbstractDataFrame. to::Symbol) rename(f::Function.17 DataFrames. header = false) source 7.tsv”) df = readtable(”data. ”c”]. from::Symbol. df::AbstractDataFrame) rename(df::AbstractDataFrame. Rename columns [] rename!(df::AbstractDataFrame.txt”.wsv”) df = readtable(”data. DATAFRAMES. to::Symbol) rename!(df::AbstractDataFrame.7. df::AbstractDataFrame) rename(df::AbstractDataFrame.16.txt”. d::Associative) rename!(f::Function. to::Symbol) rename!(df::AbstractDataFrame. from::Symbol. x = rand(10). to::Symbol) rename(f::Function. :x=¿:X)) source 7. separator = ’ ’) df = readtable(”data.RENAME 203 Examples [] df = readtable(”data.rename! DataFrames.rename! — Function. 10)) re- name(x -¿ Symbol(uppercase(string(x))). df::AbstractDataFrame) Arguments • df : the AbstractDataFrame • d : an Associative type that maps the original name to a new name • f : a function that has the old column name (a symbol) as input and new column name (a symbol) as output Result • ::AbstractDataFrame : the updated result Examples [] df = DataFrame(i = 1:10.csv”) df = readtable(”data. ”b”. Dict(:i=¿:A.rename DataFrames. :y. :Y) rename!(df.

Int. Vector{Symbol}. See also stackdf and meltdf for stacking methods that return a view into the original DataFrame. Result • ::DataFrame : the long-format dataframe with column :value holding the values of the stacked columns (measure vars). Examples [] d1 = DataFrame(a = repeat([1:3. x = rand(10). Dict(:i=¿:A. like a Symbol. 10)) re- name(x -¿ Symbol(uppercase(string(x))).204 CHAPTER 7. a normal column indexing type. :b. d = randn(12). convert from a wide to long format [] stack(df::AbstractDataFrame. :d]. etc. ’a’:’l’)) d1s = stack(d1. y = rand([”a”. ”b”. :y. df) rename(df. e = map(string. idv ars)stack(df :: AbstractDataF rame. See unstack for converting from long to wide format. Dict(:i=¿:A. measurev ars. Stacks a DataFrame. inner = [3]). :d]) d1s2 = stack(d1. and with columns for each of the id vars. :x=¿:X)) source 7.]. a normal column indexing type. measure vars defaults to all floating point columns.. [:c.18 DataFrames. defaults to all variables that are not id vars • id vars : the identifier columns that are repeated during stacking. [:a. DATAFRAMES Result • ::AbstractDataFrame : the updated result Examples [] df = DataFrame(i = 1:10.stack DataFrames.]. [:a]) d1m = melt(d1. b = repeat([1:4. :Y) rename!(df. with column :variable a Vector of Symbols with the measure vars name. c = randn(12). measurev ars) Arguments • df : the AbstractDataFrame to be stacked • measure vars : the columns to be stacked (the measurement variables). [:c. for stack defaults to all variables that are not measure vars If neither measure vars or id vars are given. ”c”]. :e]) source . :x=¿:X)) rename(df.stack — Method. for melt. inner = [4]).

measurev ars)meltdf (d Arguments • df : the wide AbstractDataFrame • measure vars : the columns to be stacked (the measurement variables). r::Int = 6) Arguments • df : the AbstractDataFrame • r : the number of rows to show Result .. idv ars)stackdf (df :: AbstractDataF rame. Show the first or last part of an AbstractDataFrame [] head(df::AbstractDataFrame. :b. like a Symbol. a normal column indexing type. measurev ars. Int. d = randn(12). for melt. etc.stackdf DataFrames. :d]) d1s2 = stackdf(d1. DATAFRAMES. a normal column indexing type.].19. inner = [4]). Vector{Symbol}. [] stackdf(df::AbstractDataFrame. [:c. Examples [] d1 = DataFrame(a = repeat([1:3. [:a]) d1m = meltdf(d1.20 DataFrames. c = randn(12). r::Int = 6) tail(df::AbstractDataFrame. ’a’:’l’)) d1s = stackdf(d1.tail — Function. :e]) source 7. A stacked view of a DataFrame (long format) Like stack and melt.tail DataFrames. [:a.7. e = map(string. b = repeat([1:4.stackdf — Method.]. The result is a view because the columns are special AbstractVectors that return indexed views into the original DataFrame. with column :variable a Vector of Symbols with the measure vars name. and with columns for each of the id vars. inner = [3]).STACKDF 205 7.19 DataFrames. [:c. defaults to all variables that are not id vars • id vars : the identifier columns that are repeated during stacking. :d]. for stack defaults to all variables that are not measure vars Result • ::DataFrame : the long-format dataframe with column :value holding the values of the stacked columns (measure vars). but a view is returned rather than data copies.

22 DataFrames. cols) Arguments • df : the AbstractDataFrame • cols : column indicator (Symbol. convert from a long to wide format [] unstack(df::AbstractDataFrame.unique! DataFrames. x = rand(10). cols) unique!(df::AbstractDataFram unique!(df::AbstractDataFrame. Vector{Symbol}. Unstacks a DataFrame.unique! — Function.unstack — Method. df) unique(df) doesn’t modify df unique(df. DATAFRAMES • ::AbstractDataFrame : the first or last part of df Examples [] df = DataFrame(i = 1:10. y = rand([”a”. See also nonunique. re- taining in each case the first instance for which df[cols] is unique. etc. ”c”]. 1) unique!(df) modifies df source 7. x = rand(10). ”c”]. Int. y = rand([”a”.) specifying the column(s) to compare. value) unstack(df::AbstractDataFrame) Arguments • df : the AbstractDataFrame to be unstacked • rowkey : the column with a unique key for each row. value) unstack(df::AbstractDataFrame.206 CHAPTER 7. colkey. colkey. rowkey. if not given. ”b”. the return DataFrame contains complete rows. find a key by grouping on anything not a colkey or value . 10)) head(df) tail(df) source 7.unstack DataFrames. ”b”. Result • ::AbstractDataFrame : the updated version of df with unique rows. 10)) df = vcat(df.21 DataFrames. Examples [] df = DataFrame(i = 1:10. When cols is specified. Delete duplicate rows [] unique(df::AbstractDataFrame) unique(df::AbstractDataFrame.

23. quotemark = ”. DATAFRAMES. d = randn(12)) long = stack(wide) wide0 = unstack(long) wide1 = unstack(long. defaults to :variable • value : the value column.writetable DataFrames. separator = ’.csv. df. • nastring::AbstractString – What to write in place of missing data. df) writetable(”output. inner = [3]). defaults to :value Result • ::DataFrame : the wide-format dataframe Examples [] wide = DataFrame(id = 1:12. :id.wsv.].dat”. . header = false) writetable(”output.]. • quotemark::Char – The character used to delimit string fields. separator = ’. Defaults to the output of getseparator(filename). Defaults to ". header = false) source . tabs for files that end in . • header::Bool – Should the file contain a header that specifies the column names from df. df.dat”. inner = [4]). ) [] writetable(filename.dat”.csv”. TSV. :value) wide2 = unstack(long. which uses commas for files that end in .’) writetable(”output. Result • ::DataFrame Examples [] df = DataFrame(A = 1:10) writetable(”output.7.’. [keyword options]) Arguments • filename::AbstractString : the filename to be created • df::AbstractDataFrame : the AbstractDataFrame to be written Keyword Arguments • separator::Char – The separator character that you would like to use.23 DataFrames. source 7. a = repeat([1:3. . :variable.WRITETABLE 207 • colkey : the column holding the column names in wide format. df. Defaults to true.writetable — Method. c = randn(12). b = re- peat([1:4. . df.tsv and a single space for files that end in . Defaults to "NA". Write data to a tabular-file format (CSV. :variable. :value) Note that there are some differences between the widened results above.

if present.25 StatsBase.model response — Method. Examples [] df = DataFrame(i = 1:10. show column characteristics and number of NAs. falses. Summarize the columns of an AbstractDataFrame [] describe(df::AbstractDataFrame) describe(io. report trues. For boolean columns. DataVector or PooledDataVector columns are converted to Arrays source . and NAs. df::AbstractDataFrame) Arguments • df : the AbstractDataFrame • io : optional output descriptor Result • nothing Details If the column’s base type derives from Number. median. ”b”. For other types.model_response(mf::ModelFrame) Extract the response column. first quantile. x = rand(10). DATAFRAMES 7. NA’s are filtered and reported separately. mean. ”c”]. 10)) describe(df) source 7. StatsBase.describe StatsBase.24 StatsBase.describe — Method. and maximum. third quantile.model response StatsBase. compute the minimum. y = rand([”a”.208 CHAPTER 7.

Throws a JDBCError if connection is null. Close the JDBCCursor csr. Open a JDBC Connection to the specified host.4 Base.Chapter 8 JDBC 8. if it is not added to the java class path.3 Base.close — Method. "passwd" => "password"). 209 . Returns a boolean indicating whether connection conn is open.1 Base.isopen Base. The username and password can be optionally passed as a Dictionary props of the form Dict("user" => "username". source 8. Closes the JDBCConnection conn. Returns nothing.isopen — Method. The JDBC connector location can be optionally passed as connectorpath.close — Method.2 Base.close Base.close Base. Returns nothing. source 8. Returns a JDBCConnection instance. Throws a JDBCError if cursor is not initialized. source 8.connect — Method.connect Base.

.7 DBAPI. JDBC source 8.DBAPIBase.9 JDBC. source 8.execute! — Method. Returns nothing.commit JDBC.6 DBAPI. source 8.connection — Method.DBAPIBase.execute! DBAPI. Return the corresponding connection for a given cursor.connection DBAPI.DBAPIBase.210 CHAPTER 8.5 DBAPI. This method returns an instance of an iterator type which returns one row on each iteration. Returns a JDBCRowIterator instance. source 8. cursor is not initialized or connection is null. . The results of the query are not returned by this function but are accessible through the cursor. Create a new database cursor. Run a query on a database. Create a row iterator. Throws a JDBCError if execute! was not called on the cursor or connection is null.cursor — Method. parameters can be any iterable of positional parameters. Each row returnes a Tuple{. Returns a JDBCCursor instance.rows DBAPI. or of some T<:Associative for keyword/named parameters. source 8.DBAPIBase.DBAPIBase.rows — Method. }.cursor DBAPI.8 DBAPI.commit — Method. Throws a JDBCError if query caused an error.DBAPIBase.DBAPIBase.DBAPIBase. .

createStatement(connection::JConnection) Initializes a Statement Args • connection: The connection object Returns The JStatement object source 8.commit — Method.10.createStatement — Method. source 8. Throws a JDBCError if connection is null.execute JDBC.11 JDBC. query::AbstractString) Executes the auery based on JStatement or any of its sub-types Args • stmt: The JStatement object or any of its sub-types • query: The query to be executed Returns A boolean indicating whether the execution was successful or not source .commit JDBC. Returns nothing. JDBC.8.10 JDBC.createStatement JDBC.12 JDBC. execute(stmt::JStatement. commit(connection::JConnection) Commits the transaction Args • connection: The connection object Returns None source 8.execute — Method.COMMIT 211 Commit any pending transaction to the database.

executeQuery JDBC.14 JDBC. JCallableStatement})) Executes the auery based on the Prepared Statement or Callable Statement Args • stmt: The Prepared Statement or the Callable Statement object Returns A boolean indicating whether the execution was successful or not source 8.15 JDBC. JCallableStatement})) Executes the auery based on a JPreparedStatement object or a JCallableState- ment object Args • stmt: The JPreparedStatement object or JCallableStatement object Returns The result set as a JResultSet object source . Args • stmt: The Statement object • query: The query to be executed Returns The result set as a JResultSet object source 8. query::AbstractString) Executes the auery and returns the results as a JResultSet object.executeQuery JDBC.212 CHAPTER 8. executeQuery(stmt::JStatement. executeQuery(stmt::@compat(Union{JPreparedStatement.executeQuery — Method. execute(stmt::@compat(Union{JPreparedStatement.execute JDBC.executeQuery — Method.execute — Method. JDBC 8.13 JDBC.

executeUpdate — Method.8. executeUpdate(stmt::JStatement.executeUpdate JDBC.16.EXECUTEUPDATE 213 8.17 JDBC.18 JDBC.executeUpdate — Method. JDBC. query::AbstractString) Executes the update auery and returns the status of the execution of the query Args • stmt: The Statement object • query: The query to be executed Returns An integer representing the status of the execution source 8.16 JDBC.getColumnCount — Method.getColumnCount JDBC. source . executeUpdate(stmt::@compat(Union{JPreparedStatement. getColumnCount(rsmd::JResultSetMetaData) Returns the number of columns based on the JResultSetMetaData object Args • rsmd: The JResultSetMetaData object Returns The number of columns.executeUpdate JDBC. JCallableStatement})) Executes the update auery based on a JPreparedStatement object or a JCallableStatement object Args • stmt: The JPreparedStatement object or JCallableStatement object Returns An integer indicating the status of the execution of the query source 8.

fld::AbstractString) Returns the Date object based on the result set or a callable statement.getColumnName — Method. col::Integer) Returns the column’s name based on the JResultSetMetaData object and the column number Args • rsmd: The JResultSetMetaData object • col: The column number Returns The column name source 8. source .getDate JDBC.getColumnType — Method.214 CHAPTER 8. JDBC 8. getColumnName(rsmd::JResultSetMetaData.20 JDBC. Args • stmt: The JResultSet or JCallableStatement object • fld: The column name Returns The Date object.19 JDBC.getColumnType JDBC.21 JDBC.getColumnName JDBC. JCallableStatement}).getDate — Method. getColumnType(rsmd::JResultSetMetaData. col::Integer) Returns the column’s data type based on the JResultSetMetaData object and the column number Args • rsmd: The JResultSetMetaData object • col: The column number Returns The column type as an integer source 8. The value is extracted based on the column name. getDate(rs::@compat(Union{JResultSet.

22 JDBC.24 JDBC.getDate JDBC.getDate — Method. getMetaData(rs::JResultSet) Returns information about the types and properties of the columns in the ResultSet object Args • stmt: The JResultSet object Returns The JResultSetMetaData object.getMetaData JDBC.getResultSet — Method.getMetaData — Method. source 8. JDBC. getDate(rs::@compat(Union{JResultSet. source . Args • stmt: The JResultSet or JCallableStatement object • fld: The column number Returns The Date object. fld::Integer) Returns the Date object based on the result set or a callable statement. The value is extracted based on the column number. getResultSet(stmt::JStatement) Returns the result set based on the previous execution of the query based on a JStatement Args • stmt: The JStatement object Returns The JResultSet object.22.GETDATE 215 8.23 JDBC. JCallableStatement}). source 8.8.getResultSet JDBC.

source .getTableMetaData — Method. The value is extracted based on the column number.getTableMetaData JDBC.26 JDBC. The value is extracted based on the column name.getTime — Method.216 CHAPTER 8. source 8.getTime JDBC. JCallableStatement}). Get the metadata (column name and type) for each column of the table in the result set rs. getTime(rs::@compat(Union{JResultSet.getTime JDBC. column type) tuples. Returns an array of (column name.27 JDBC. fld::Integer) Returns the Time object based on the result set or a callable statement. Args • stmt: The JResultSet or JCallableStatement object • fld: The column name Returns The Time object. JDBC 8. JCallableStatement}).25 JDBC. source 8.getTime — Method. Args • stmt: The JResultSet or JCallableStatement object • fld: The column number Returns The Time object. fld::AbstractString) Returns the Time object based on the result set or a callable statement. getTime(rs::@compat(Union{JResultSet.

fld::AbstractString) Returns the Timestamp object based on the result set or a callable state- ment. JCallableStatement}). The value is extracted based on the column number. JDBC.28.28 JDBC. query::AbstractString) Prepares the Callable Statement for the given query Args • connection: The connection object • query: The query string Returns The JCallableStatement object source .getTimestamp — Method. Args • stmt: The JResultSet or JCallableStatement object • fld: The column number Returns The Timestamp object. getTimestamp(rs::@compat(Union{JResultSet. The value is extracted based on the column name. source 8.getTimestamp — Method. getTimestamp(rs::@compat(Union{JResultSet.GETTIMESTAMP 217 8.29 JDBC.getTimestamp JDBC.8. prepareCall(connection::JConnection. fld::Integer) Returns the Timestamp object based on the result set or a callable state- ment.getTimestamp JDBC.30 JDBC.prepareCall — Method.prepareCall JDBC. Args • stmt: The JResultSet or JCallableStatement object • fld: The column name Returns The Timestamp object. source 8. JCallableStatement}).

setAutoCommit — Method. Returns nothing. rollback(connection::JConnection) Rolls back the transactions.prepareStatement — Method. JDBC 8.rollback JDBC.218 CHAPTER 8.rollback — Method. x::Bool) . source 8. query::AbstractString) Prepares the Statement for the given query Args • connection: The connection object • query: The query string Returns The JPreparedStatement object source 8.32 JDBC. Throws a JDBCError if connection is null.rollback JDBC.34 JDBC. prepareStatement(connection::JConnection.31 JDBC.33 JDBC.rollback — Method.setAutoCommit JDBC. Args • connection: The connection object Returns None source 8.prepareStatement JDBC. Roll back to the start of any pending transaction. setAutoCommit(connection::JConnection.

8. commit has to be called explicitly Args • connection: The connection object Returns None source 8.setFetchSize JDBC. The number of records that are returned in subse- quent query executions are determined by what is set here. setFetchSize(stmt::@compat(Union{JStatement. JCallableStatement }). If set to false.SETFETCHSIZE 219 Set the Auto Commit flag to either true or false. JPreparedStatement.setFetchSize — Method. JDBC. x::Intege Sets the fetch size in a JStatement or a JPreparedStatement object or a JCallableStatement object. Args • stmt: The JPreparedStatement object or JCallableStatement object • x: The number of records to be returned Returns None source .35 JDBC.35.

See Fast and Accurate Deep Network Learning by Exponential Linear Units. elu(x. e. = 1) = x > 0 ? x : * (exp(x) .Chapter 9 NNlib 9.g.1) Exponential Linear Unit activation function.1 NNlib.elu — Function. 3 -1 -3 0 3 source 220 .elu NNlib. elu(x. 1). You can also specify the coef- ficient explicitly.

leakyrelu(x.9.3 NNlib. 3 . relu(x) = max(0. x) Rectified Linear Unit activation function.leakyrelu — Function. You can also specify the coefficient explicitly.LEAKYRELU 221 9.relu — Method. NNLIB. 0.2. x) Leaky Rectified Linear Unit activation function.relu NNlib. e.g. 3 -1 -3 0 3 source 9.01). leakyrelu(x) = max(0.leakyrelu NNlib.01x.2 NNlib.

softmax — Function. See Self-Normalizing Neural Networks.3.(xs) . with each column independent./ sum(exp. .4 NNlib.(xs)) Softmax takes log-probabilities (any real vector) and returns a probability distribution that sums to 1.6733 Scaled exponential linear units. softmax(xs) = exp.0900306 0.244728 0. julia> softmax([1. softplus(x) = log(exp(x) + 1) See Deep Sparse Rectifier Neural Networks.1)) 1.222 CHAPTER 9.softmax NNlib.softplus — Method.selu — Method.5 NNlib.selu NNlib. NNLIB 0 -3 0 3 source 9.6 NNlib.0507 1. selu(x) = * (x 0 ? x : * (exp(x) .1}: 0. If given a matrix it will treat it as a batch of vectors.2.665241 source 9. 4 -2 -3 0 3 source 9.]) 3-element Array{Float64.softplus NNlib.

softsign NNlib.softsign — Method.7.7 NNlib. 1 -1 -3 0 3 source . softsign(x) = x / (1 + |x|) See Quadratic Polynomials Learn Better Image Features.9.SOFTSIGN 223 4 0 -3 0 3 source 9. NNLIB.

3 -1 -3 0 3 source 9. (x) = 1 / (1 + exp(-x)) Classic sigmoid activation function.swish NNlib.swish — Method. swish(x) = x * (x) Self-gated actvation function.8 NNlib. See Swish: a Self-Gated Activation Function.9 NNlib. — Method. NNlib. NNLIB 9. 1 .224 CHAPTER 9.

225 0 -3 0 3 source .9. NNLIB.9.

Chapter 10 ImageCore 10. Of relevance for types like RGB and BGR. splitting out (if necessary) the color channels of A into a new first dimension.3 ImageCore.assert timedim last — Method.channelview — Method.1 ImageCore.assert timedim last ImageCore. not memory order (see reinterpret if you want to use memory order). assert_timedim_last(img) Throw an error if the image has a time dimension that is not the last di- mension. source 10. This is almost identical to ChannelView(A). source 10. channelview(A) returns a view of A.channelview ImageCore. Consequently. it will simply return the parent of A.clamp01 ImageCore.2 ImageCore. the output may not be a ChannelView array.clamp01 — Method. except that if A is a ColorView. the channels of the returned array will be in constructor-argument order. clamp01(x) -> y 226 . or will use reinterpret when appropriate.

. The default colors are: • colorcenter: white • colorneg: green1 • colorpos: magenta See also: scalesigned. colorpos) -> f colorsigned(colorneg.colorview ImageCore. See also: clamp01nan. gray2. except that any NaN values are changed to 0. 1) for numeric values. colorcenter. and equal to x when x is already in this range. .) -> imgC . For colors.colorsigned ImageCore. colorview(C.CLAMP01NAN 227 Produce a value y that lies between 0 and 1.4 ImageCore.colorsigned — Method. colorsigned() colorsigned(colorneg.5 ImageCore. colorpos) -> f Define a function that maps negative values (in the range [-1.6 ImageCore. 0. source 10. source 10..1]) to the linear colormap between colorcenter and colorpos. gray1. IMAGECORE.10.clamp01nan ImageCore. this function is applied to each color channel separately.colorview — Method.4. source 10.0]) to the linear colormap between colorneg and colorcenter. and positive values (in the range [0. clamp01nan(x) -> y Similar to clamp01.clamp01nan — Method. Equivalent to clamp(x. See also: clamp01.

except that if A is a ChannelView.float32 ImageCore. This is almost identical to ColorView{C}(A). Of relevance for types like RGB and BGR.8 ImageCore. A) returns a view of the numeric array A. 10.228 CHAPTER 10. it will simply return the parent of A. See also: StackedView.colorview — Method. and nothing in the green channel. source 10. zeroarray. float32. Note that a better strategy may be to use ImagesAxes and take slices along the time axis.colorview ImageCore.9 ImageCore.(img) . or use reinterpret when appropriate. Example [] imgC = colorview(RGB. 10) img = colorview(RGB. As a convenience. Consequently. r. coords spatial(img) Return a tuple listing the spatial dimensions of img. gray2. IMAGECORE Combine numeric/grayscale images gray1. the output may not be a ColorView array. colorview(C.coords spatial ImageCore..coords spatial — Method. b) creates an image with r in the red chanel.7 ImageCore.float32 — Function. the constant zeroarray fills in an array of matched size with all zeros. A) source 10. Example [] A = rand(3. source 10. etc. the elements of A are interpreted in constructor-argument order. interpreting successive elements of A as if they were channels of Colorant C. not memory order (see reinterpret if you want to use memory order). into the separate color channels of an array imgC with element type C<:Colorant. b in the blue channel.

12 ImageCore. without changing the color space.10.n0f8 — Function. source 10.11 ImageCore.13 ImageCore.FLOAT64 229 converts the raw storage type of img to Float32.(img) converts the raw storage type of img to Float64. source 10. float64. without changing the color space. indices_spatial(img) Return a tuple with the indices of the spatial dimensions of the image.float64 — Function.10 ImageCore. De- faults to the same as indices. IMAGECORE. but using ImagesAxes you can mark some axes as being non-spatial.n0f16 ImageCore. without changing the color space. source 10. without changing the color space.(img) converts the raw storage type of img to N0f8. n0f16.(img) converts the raw storage type of img to N0f16. n0f8. source 10.indices spatial — Method.indices spatial ImageCore.n0f16 — Function.float64 ImageCore. source .n0f8 ImageCore.10.

n6f10 ImageCore.(img) converts the raw storage type of img to N6f10.(img) converts the raw storage type of img to N2f14. source . without changing the color space. without changing the color space.15 ImageCore.nimages — Method.n4f12 ImageCore. Use ImagesAxes if you want to use an explicit time dimension.n4f12 — Function. n6f10.16 ImageCore. nimages(img) Return the number of time-points in the image array. n2f14.n2f14 ImageCore.n6f10 — Function. Defaults to 1. without changing the color space. source 10. n4f12. source 10.n2f14 — Function.(img) converts the raw storage type of img to N4f12.nimages ImageCore. IMAGECORE 10.14 ImageCore. source 10.17 ImageCore.230 CHAPTER 10.

permuteddimsview — Method.. . source 10.18. source 10. This is like permutedims. source 10.18 ImageCore. normedview([T]. Use ImagesAxes for images with anisotropic spacing or to encode the spacing using physical units. N2f14.normedview ImageCore. Compared to the copy.permuteddimsview ImageCore.19 ImageCore. ). the view will act like an Array{UInt8}. Supply T if the element type of img is UInt16. consequently. to specify whether you want a N6f10.NORMEDVIEW 231 10.rawview ImageCore. if img is an Array{UInt8}.) Return a tuple representing the separation between adjacent pixels along each axis of the image. For example. pixelspacing(img) -> (sx. source .21 ImageCore.normedview — Method. any manipulations you make to the output will be mirrored in A. rawview(img::AbstractArray{FixedPoint}) returns a “view” of img where the values are interpreted in terms of their raw underlying storage. or N0f16 result. . if img is an Array{N0f8}.1. IMAGECORE.rawview — Method. the view will act like an Array{N0f8}. img::AbstractArray{Unsigned}) returns a “view” of img where the values are interpreted in terms of Normed number types. perm) returns a “view” of A with its dimensions permuted as specified by perm. Defaults to (1...pixelspacing — Method. but generally slower to use. N4f12. For example.pixelspacing ImageCore.10. the view is much faster to create. permuteddimsview(A. except that it produces a view rather than a copy of A. .20 ImageCore. sy.

source .0. See also: colorsigned.0 julia¿ f(-10) 0.0. 1].5019607843137255. max) -> f scaleminmax(T. Examples Example 1 [] julia¿ f = scaleminmax(-10.0 julia¿ f(5) 0.23 ImageCore. and uses a linear scale in between. maxabs] (clamping values that lie outside this range) to the range [-1. RGB).0] and [center. respectively. values greater than or equal to max to 1. then scaling is applied to each color channel. scalesigned(min. source 10.max] to [0. See also: colorsigned. max) -> f Return a function f which maps values less than or equal to min to 0. If T is a colorant (e.0. source 10. scalesigned(maxabs) -> f Return a function f which scales values in the range [-maxabs. center] to [-1.1].scaleminmax — Method. min and max should be real values.0.0. Optionally specify the return type T. min.128. 255) (::13) (generic function with 1 method) julia¿ f(c) RGB{Float64}(1.0. 0.scalesigned — Method.128.24 ImageCore.0.scaleminmax ImageCore. Values smaller than min/max get clamped to min/max.232 CHAPTER 10.g. scaleminmax(min.scalesigned — Method.0) julia¿ f = scaleminmax(RGB.75 Example 2 [] julia¿ c = RGB(255. max) -> f Return a function f which scales values in the range [min.0. 10) (::9) (generic function with 1 method) julia¿ f(10) 1.. center.scalesigned ImageCore. IMAGECORE 10.0) See also: takemap.22 ImageCore.0) RGB{Float64}(255.scalesigned ImageCore.0.

26 ImageCore. axis2. fnew should return valid values for storage or display. source 10. A) -> fnew takemap(f.. size_spatial(img) Return a tuple listing the sizes of the spatial dimensions of the image.spacedirections ImageCore. but using ImagesAxes you can mark some axes as being non-spatial.sdims — Method.. takemap(f.takemap — Function.takemap ImageCore. but with ImagesAxes you can specify that some axes correspond to other quantities (e..) Return a tuple-of-tuples.28 ImageCore. source 10. relative to some external coordinate system (“physical coordinates”). A) -> fnew Given a value-mapping function f and an array A. .spacedirections — Method. return a “concrete” map- ping function fnew.size spatial ImageCore.10.27 ImageCore. for example in the range from 0 to 1 (for grayscale) .25. Defaults to the same as ndims.sdims ImageCore. spacedirections(img) -> (axis1. De- faults to the same as size. IMAGECORE.size spatial — Method. each axis[i] representing the displacement vector between adjacent pixels along spatial axis i of the image array. T. source 10.25 ImageCore. but you can set this man- ually using ImagesMeta. sdims(img) Return the number of spatial dimensions in the image.SDIMS 233 10.g. time) and thus not included by sdims. By default this is computed from pixelspacing. When applied to elements of A.

Example: [] julia¿ A = [0. Optionally one can specify the output type T that fnew should produce. 1000]. julia¿ f = takemap(scaleminmax.001 1.1}: 0.(A) 3-element Array{Float64.0 source . 1. A) (::7) (generic function with 1 method) julia¿ f. and may not produce valid values for any inputs not in A.234 CHAPTER 10. fnew may be adapted to the actual values present in A.0 0. IMAGECORE or valid colorants.

map Base.merge Base. source 235 . merge(inputs.merge — Method. filter(f. map(f.) -> signal Transform signal s by applying f to each element. signal) remove updates from the signal where f returns false.map — Method.filter Base..3 Base. source 11..) Merge many signals into one. default..Chapter 11 Reactive 11. Returns a signal which updates when any of the inputs update. s::Signal. the value of the youngest (most recently created) input signal is taken. If many signals update at the same time. The filter will hold the value default until f(value(signal)) returns true. For multiple signal argu- ments. when it will be updated to value(signal). source 11.2 Base. apply f elementwise.filter — Method.1 Base..

node is the Signal whose action triggered the error.async map Reactive. and processed bt which is the backtrace of the exception. is a callback triggered when the update ends in an error. by default it is set to a callback which prints the error to STDERR.bound dests — Method. REACTIVE 11. init. value. results = async_map(f. input. otherwise (if initial is true) both dest and src will take src’s value immediately. and capex is a CapturedException with the fields ex which is the original exception object. val.print error) Queue an update to a signal. dest will only be updated to src’s value when src next updates. The callback receives 4 arguments. if twoway is true. ‘bind!(dest. The third (optional) argument. source 11. onerror is the callback to be called when an error occurs. source 11. node. push!(signal. source 11.bind! — Function. initial=true)‘ for every update to src also update dest with the same value and. onerror=Reactive.push! Base. src. init will be used as the default value of results. capex). onerror. where sig and val are the Signal and value that push! was called with. It’s the same as the onerror argument to push! but is run in the spawned task..6 Reactive. vice-versa. onerror=Reactive. If initial is false..typ=typeof(init).bind! Reactive. .7 Reactive..async map — Method. twoway=true. Returns a signal of tasks and a results signal which updates asynchronously with the results.push! — Function. tasks.5 Reactive. The default error callback will print the error and backtrace to STDERR.bound dests Reactive.236 CHAPTER 11.print_e Spawn a new task to run a function when input signal updates. respectively. onerror(sig.4 Base. The update will be propagated when all currently queued updates are done processing.

name=auto_name!(string("debounce ". source 11. Int[]. default=value(input)) Schedule an update to happen after the current update propagates through- out the signal graph.8 Reactive. that were bound using bind!(dest. that were bound using bind!(dest. x. bound srcs(dest::Signal) returns a vector of all signals that will cause an update to dest when they update. src) source 11.debounce Reactive. the debounce signal holds the last update of the input signal since the debounce signal last updated.2 seconds. input)) Creates a signal that will delay updating until dt seconds have passed since the last time input has updated. reinit is called after the debounce sends an update.debounce — Method. This behavior can be changed by the f. For example y = debounce(0. init=value(input).11.delay Reactive. it gets one argument.9 Reactive. ->Int[]) will accu- mulate a vector of updates to the integer signal x and push it after x is inactive (doesn’t update) for 0.2. the previous accumulated value. init and reinit arguments.10 Reactive.bound srcs Reactive. push!.dt. to reinitialize the initial value for accumulation. Returns the delayed signal. f=(acc.x)->x. delay(input. reinit=x->x.8.BOUND SRCS 237 bound dests(src::Signal) returns a vector of all signals that will update when src updates. src) source 11. typ=typeof(init)."s"). source . By default. The init and f functions are similar to init and f in foldp. debounce(dt.bound srcs — Method. input. REACTIVE.delay — Method.

droprepeats(input) Drop updates to input whenever the new value is the same as the previous value of the signal.flatten Reactive. It is Any by default. input) Keep updates to input only when switch is true. every(dt) A signal that updates every dt seconds to the current timestamp. Consider using fpswhen or fps if you want specify the timing signal by frequency.12 Reactive.14 Reactive. The typ keyword argument specifies the type of the flattened signal. the specified default value is used.droprepeats — Method. source 11.every Reactive. If switch is false initially.filterwhen Reactive. default. source 11. filterwhen(switch::Signal{Bool}. flatten(input::Signal{Signal}.droprepeats Reactive. source .238 CHAPTER 11. rather than delay.every — Method.11 Reactive. REACTIVE 11. typ=Any) Flatten a signal of signals into a signal which holds the value of the current signal.13 Reactive. source 11.flatten — Method.filterwhen — Method.

11. until x goes out of scope.FOLDP 239 11. x)) .fpswhen — Method. rate) returns a signal which when switch signal is true. REACTIVE.16 Reactive..foldp — Method.g. rate) source 11. preserve(map(println.15. foldp(f..fps — Method.fps Reactive. fpswhen(switch.15 Reactive. f will be called when one or more of the inputs updates. init is the initial value of the accumulator. fps(rate) Same as fpswhen(Input(true). foreach is a shorthand for map with preserve. source . source 11.) Fold over past values. inputs.preserve — Method. source 11. It should return the next accumulated value.foldp Reactive. init.fpswhen Reactive.this will continue to print updates to x. the signal will self adjust to provide the best possible rate. e. updates rate times every second. Useful for when you want to do some side effects in a signal. preserve(signal::Signal) prevents signal from being garbage collected as long as any of its parents are around.18 Reactive. If rate is not possible to attain because of slowness in computing dependent signal values.preserve Reactive. f should take 1 + length(inputs) arguments: the first is the current accumulated value and the rest are the current input signal values.17 Reactive. Accumulate a value as the input signals change.

b) Sample the value of b whenever a updates.previous — Method.19 Reactive.remote map — Method. remoterefs. source 11."s").x)->x. source 11. It’s the same as the onerror argument to push! but is run in the spawned task.sampleon Reactive.21 Reactive. input.. input. rename!(s::Signal. results = remote_map(procid.typ=typeof(init). onerror=Re Spawn a new task on process procid to run a function when input signal updates. throttle(dt.throttle — Method.20 Reactive.dt. init=value(input).22 Reactive. reinit=x->x.throttle Reactive.remote map Reactive.previous Reactive.. You can optionally specify a different initial value. Returns a signal of remote refs and a results signal which updates asynchronously with the results. sampleon(a. input). leadi . init. f. init will be used as the default value of results. REACTIVE 11.rename! — Method. source 11.sampleon — Method. name::String) Change a Signal’s name source 11. by default it is set to a callback which prints the error to STDERR. previous(input. typ=typeof(init).rename! Reactive.23 Reactive. f=(acc..240 CHAPTER 11. name=auto_name!(string("throttle ". default=value(input)) Create a signal which holds the previous value of input. onerror is the callback to be called when an error occurs.

unpreserve(signal::Signal) allow signal to be garbage collected. By default.4.2. source 11. Int[].UNBIND! 241 Throttle a signal to update at most once every dt seconds. If leading is true.25 Reactive. src. twoway=true)‘ remove a link set up using bind! source 11. the previous accumulated value. See also preserve. x. The init and f functions are similar to init and f in foldp.1: throttle’s behaviour from previous versions is now available with the debounce signal type.unpreserve Reactive.unpreserve — Method. the throttled signal holds the last update of the input signal during each dt second time window. reinit is called when a new throttle time window opens to reinitialize the initial value for accumulation. the first update from input will be sent immediately by the throttle signal. push!. init and reinit arguments. it gets one argument. For example y = throttle(0. This behavior can be changed by the f. REACTIVE. ‘unbind!(dest. the first update will happen dt seconds after input’s first update New in v0.unbind! Reactive. If it is false.2 second time windows.24. source . ->Int[]) will cre- ate vectors of updates to the integer signal x which occur within 0.24 Reactive.11.unbind! — Function.

. Currently KnetArray{Float32/64. If w has dimensions (W1.com/shelhamer/fcn.Chapter 12 Knet 12.. and Wi..1 Knet.bilinear Knet.W2..bilinear — Method.128) source 12. padding 242 .128.2 Knet.X2. the result y will have dimensions (Y1.N).I. x.py#L33 Arguments: T : Data Type fw: Width upscale factor fh: Height upscale factor IN: Number of input filters ON: Number of output filters Example usage: w = bilinear(Float32...Yi are spatial dimensions. Adapted from https://github.N) where Yi=1+floor((Xi+2*padding[i]-Wi)/stride[i]) Here I is the number of input channels.4/5} and Array{Float32/64.conv4 — Method...) Execute convolutions or cross-correlations using filters specified with w over tensor x. O is the number of output channels..Xi.conv4 Knet..2..Y2.O.berkeleyvision.I. used for initializing deconvolution layers.O) and x has dimensions (X1.4} are sup- ported as w and x.. conv4(w.org/blob/master/surgery.. Bilinear interpolation filter weights..2. N is the number of instances. kwargs.

deconv4 — Method. Deconvolution. • alpha=1: can be used to scale the result.deconv4 Knet. Defaults to a Knet allocated handle. source 12.4 Knet. See (Srivastava et al. source . See the CUDNN User Guide for details.dropout Knet.DECONV4 243 and stride are keyword arguments that can be specified as a single number (in which case they apply to all dimensions). reverse of convolution.dropout — Method.3 Knet.12. Keywords • padding=0: the number of extra zeros implicitly concatenated at the start and at the end of each dimension. 2014) for a reference. • stride=1: the number of elements to slide to reach the next filtering window.3. source 12. p. or an array/tuple with entries for each spatial dimension. • workSpaceSizeInBytes=0: the size in bytes of the provided workSpace. KNET. • upscale=1: upscale factor for each dimension. dropout(x. • algo=0: specifies which convolution algorithm shoud be used to compute the results. Default=0. return an array y in which each element is 0 with probability p or x[i]/(1-p) with probability 1-p. seed=0) Given an array x and probability 0<=p<=1. • handle: handle to a previously created cuDNN context. • mode=0: 0 for convolution and 1 for cross-correlation. • workSpace=C NULL: data pointer to GPU memory to a workspace needed to able to execute the specified algorithm.

then move with multiplicative steps. picking the next step based on estimated gain. It can return NaN for out of range inputs. f is a function from a Vector{Float64} of length n to a Number. gpu(true) resets all GPU devices and activates the one with the most avail- able memory.gaussian Knet. mean=0. .. This will effectively start the search at x0. I designed this algorithm combining ideas from Golden Section Search and Hill Climbing Search.goldensection Knet.6 Knet. goldensection(f. Goldensection will always start with a zero vector as the initial input to f... It essentially runs golden section search concurrently in each dimension. source 12.goldensection — Method.n..5 Knet.. Keyword arguments • dxmin=0.gpu — Function. you can use a transformation such as x0*exp(x) where x is a value goldensection passes to f and x0 is your initial guess for this value. Golden ratio =1.0. and the initial step size will be 1 in each dimension. is best. See Knet.xmin) Find the minimum of f using concurrent golden section search in n dimen- sions.7 Knet. • accel=: acceleration rate. The a arguments are passed to randn.] function evaluations. KNET 12.gpu Knet.618. gpu() returns the id of the active GPU device or -1 if none are active. For positive inputs like learning rate or hidden size. • verbose=false: use true to print individual steps.f(x)).gaussian — Method.. source 12.01) Return a Gaussian array with a given mean and standard deviation.1: smallest step size.244 CHAPTER 12.. The user should define f to scale and shift this input range into a vector meaningful for their application.kwargs) => (fmin. gaussian(a.. std=0. • history=[]: cache of [(x.goldensection demo() for an example.

maxresource=27./x) source 12. source 12.HYPERBAND 245 gpu(false) resets and deactivates all GPU devices. • getloss(c. If there are any allocated KnetArrays their pointers will be left dangling. If you want to suspend GPU use temporarily.invx — Function.[dims]) . 3 is a good value.g.9 Knet.12. hyperband(getconfig. logp(x.invx Knet. source 12. gpu(d::Int) activates the GPU device d if 0 <= d < gpuCount(). Thus gpu(true/false) should only be used during startup. • reduction is an algorithm parameter (see paper). You can select a previous device and find allocated memory preserved. use gpu(-1). invx(x) = (1.hyperband demo().10 Knet.8 Knet. KNET. epochs) n.hyperband — Function.8.logp — Method.logp Knet. gpu(d::Int) does not reset the devices. You can try a simple MNIST example using Knet. 2016).n) returns loss for configuration c and number of resources (e. Arguments • getconfig() returns random configurations with a user defined type and distribution. other- wise deactivates devices. reduction=3) Hyperparameter optimization using the hyperband algorithm from (Lisha et al. gpu(true/false) resets all devices.hyperband Knet. However trying to operate on arrays of an inactive device will result in error. getloss. • maxresource is the maximum number of resources any one configuration should be given.

..XD)..XD)) source 12. otherwise the summation is performed over the given dimensions.pool — Method. (X1*X2*.) Compute pooling of input values (i..I.logsumexp — Method. returns reshape(x. pool(x. logsumexp(x... dims is an optional argument. kwargs.Y2.1)).[dims]) Compute log(sum(exp(x)..... dims is an optional argument.dims)) in a numerically stable manner.246 CHAPTER 12.. If x has dimensions (X1.. For 1-D inputs returns reshape(x. Currently 4 or 5 dimensional KnetArrays with Float32 or Float64 entries are supported. if not specified the normalization is over the whole x.. dims=1 sums columns of x and dims=2 sums rows of x. otherwise the normalization is performed over the given dimensions. mat(x) Reshape x into a two-dimensional matrix.. source 12. In particular. source 12.13 Knet.mat Knet.X2.N).mat — Method. dims=1 normalizes columns of x and dims=2 normalizes rows of x. the maximum or average of several adjacent values) to produce an output with smaller height and/or width..I.12 Knet.X2. For inputs with more than two dimensions of size (X1.e. the result y will have dimensions (Y1. In particular if x is a matrix.N) where . if x is a matrix. This is typically used when turning the output of a 4-D convolution re- sult into a 2-D input for a fully connected layer. KNET Treat entries in x as as unnormalized log probabilities and return normalized log probabilities. if not specified the summation is over the whole x. (length(x)..11 Knet.logsumexp Knet.*X[D-1].pool Knet..

• padding=0: the number of extra zeros implicitly concatenated at the start and at the end of each dimension.Yi are spatial dimensions.setseed — Method.14 Knet.setseed Knet. setseed(n::Integer) Run srand(n) on both cpu and gpu.14. 2 for average excluding padded values. Keywords: • window=2: the pooling window size for each dimension. 1 for average including padded values.16 Knet. source 12. • stride=window: the number of elements to slide to reach the next pooling window. they are propagated if 1. • mode=0: 0 for max. • maxpoolingNanOpt=0: Nan numbers are not propagated if 0. Defaults to a Knet allocated handle.15 Knet. KNET. • handle: Handle to a previously created cuDNN context.sigm — Function.sigm Knet. sigm(x) = (1. • alpha=1: can be used to scale the result. and Xi. padding and stride are keyword argu- ments that can be specified as a single number (in which case they apply to all dimensions).12.RELU 247 Yi=1+floor((Xi+2*padding[i]-window[i])/stride[i]) Here I is the number of input channels. source 12.relu Knet.relu — Function. relu(x) = max(0./(1+exp(-x))) source . or an array/tuple with entries for each spatial dimension. N is the number of instances. window.x) source 12.

gclip=0.17 Knet. • Sgd(.001. The weights and possibly gradients and params are modified in-place. gclip==0 indicates no clipping.lr=0.. gclip=0) Update the weights using their gradients and the optimization algorithm parameters specified by params..).248 CHAPTER 12. gradients. or even different optimization algo- rithms running in parallel.18 Knet.01. gradients should be a similar numeric array of size(weights) and params should be a single object. Individual optimization parameters can be one of the following types. eps=1e-6) • Adadelta(.9. different learning rates. The keyword arguments for each type’s constructor and their default values are listed as well.9.o. beta2=0.001.1. In the collection case.lr=0. gclip=0.9. rho=0.. params) update!(weights. gradients.lr=0. gradients and params should be dictionaries with the same keys as weights.lr=0. lr=0. KNET 12.lr=0. eps=1e-6) • Adam(. gclip=0.) source 12.lr=0. x == pool(unpool(x.unpool Knet. beta1=0. gamma=0. reverse of pooling.9) • Nesterov(. update!(weights.unpool — Method.update! — Function. eps=1e-8) Example: . gradients and params should be iterators of the same length as weights with corresponding elements. gclip=0. The 2-arg version defaults to the Sgd algorithm with learning rate lr and gradient clip gclip.999.lr=0. Unpooling.001.9) • Rmsprop(. This way different weight arrays can have their own optimization state. gclip=0. gclip=0) • Momentum(. weights can be an individual numeric array or a collection of arrays repre- sented by an iterator or dictionary. each individual weight array should have a cor- responding params object. o. gclip=0.001.update! Knet.001. In the dictionary case.. rho=0. In the iterator case. In the individual case.001. eps=1e-6) • Adagrad(. gamma=0.

xavier — Method. KNET. rand(d2)) # a tuple of weight arrays g = lossgradient2(w) # g will also be a tuple p = (Adam().1) update!(w.19 Knet. g) # update w in-place with Sgd() update!(w.) Xavier initialization. :b => rand(d2)) # dictionaries can be used g = lossgradient4(w) p = Dict(:a => Adam().XAVIER 249 w = rand(d) # an individual weight array g = lossgradient(w) # gradient g has the same shape as w update!(w. g. The a arguments are passed to rand.19.p[i] w = Any[rand(d1).. g. Lasagne calls it GlorotUniform. xavier(a. Sgd()] # p should be an iterator of same length update!(w. g. p) # update each w[i] in-place with g[i]. g.12. See (Glorot and Bengio 2010) for a description.xavier Knet. :b => Sgd()) update!(w. source .1) # update w in-place with Sgd(lr=0. g. p) source 12. p) # update each w[i] in-place with g[i]. Caffe implements this slightly differently..p[i] w = Dict(:a => rand(d1).1)) # update w in-place with Sgd(lr=0.1) w = (rand(d1). Sgd(lr=0. rand(d2)] # any iterator can be used g = lossgradient3(w) # g will be similar to w p = Any[Adam(). lr=0. Sgd()) # p has params for each w[i] update!(w.

Returns the n-th Catalan number source 13.character Combinatorics.Chapter 13 Combinatorics 13. Computes character () of the partition in the th irrep of the symmetric group Sn Implements the Murnaghan-Nakayama algorithm as described in: Dan Bern- stein.4 Combinatorics.factorial — Method.001 source 250 .2 Combinatorics.character — Method.2003.jsc.bellnum Combinatorics.bellnum — Method.1016/j.factorial Base.catalannum — Method. “The computational complexity of rules for the character table of Sn”. 37 iss. computes n!/k! source 13. doi:10. Returns the n-th Bell number source 13.11.1 Base. pp 727-748. 6 (2004). Journal of Symbolic Computation.catalannum Combinatorics.3 Combinatorics. vol.

COMBINATORICS.isrimhook Combinatorics. with a to the left of b source .7 Combinatorics.COMBINATIONS 251 13.isrimhook Combinatorics. but sequence at each order is lazy source 13.13.isrimhook — Method. Because the number of combinations can be very large.isrimhook — Method. Lists the partitions of the number n.derangement — Method. The number of permutations of n with no fixed points (subfactorial) source 13.combinations Combinatorics. generate combinations of all orders.8 Combinatorics.combinations Combinatorics. this function returns an iterator object. the order is consistent with GAP source 13.n)) to get an array of all combina- tions. chaining of order iterators is eager.combinations — Method. Checks if skew diagram is a rim hook source 13.10 Combinatorics.5 Combinatorics. source 13.combinations — Method.integer partitions Combinatorics.5.derangement Combinatorics. Takes two elements of a partition sequence.9 Combinatorics. Generate all combinations of n elements from an indexable object.integer partitions — Method.6 Combinatorics. Use collect(combinations(array.

1] [0. For example. 0. 2)) 6-element Array{Any.leglength — Method. the expansion (x + x + x) = x + xx + xx + .13 Combinatorics. Strictly speaking. 0] [1. 2. Returns 1 is the permutation is even. defined for rim hook only. Computes Lassalle’s sequence OEIS entry A180874 source 13. n) Returns the exponents in the multinomial expansion (x + x + . has the exponents: julia> collect(multiexponents(3. 1] [0.multiexponents — Method. + x).levicivita Combinatorics.11 Combinatorics. 0.levicivita — Method.lassallenum — Method. but here we define it for all skew diagrams source 13. 0.252 CHAPTER 13.1}: [2. 2] source .12 Combinatorics.14 Combinatorics.leglength Combinatorics. 1. COMBINATORICS 13. 0] [0. multiexponents(m. source 13.multiexponents Combinatorics. Levi-Civita symbol of a permutation. The parity is computed by using the fact that a permutation is odd if and only if the number of even-length cycles is odd. 0] [1. 1. .lassallenum Combinatorics. -1 if it is odd and 0 otherwise. . . .

19 Combinatorics.multiset permutations — Method. source 13. k)) == k for 1 <= k <= factorial(n).nthperm — Method.nthperm! Combinatorics. generate all combinations of size t from an array a with possibly duplicated elements.nthperm — Method. source 13. Note that nthperm(nthperm([1:n].18 Combinatorics. source 13.nthperm Combinatorics. source 13.multiset combinations — Method.nthperm Combinatorics.MULTINOMIAL 253 13.multiset combinations Combinatorics. In-place version of nthperm.15 Combinatorics.16 Combinatorics.nthperm! — Method.13. Return the k that generated permutation p. generate all permutations of size t from an array a with possibly duplicated elements. COMBINATORICS.multiset permutations Combinatorics.multinomial Combinatorics. Compute the kth lexicographic permutation of the vector a. source .15.17 Combinatorics.20 Combinatorics. Multinomial coefficient where n = sum(k) source 13.multinomial — Method.

partitions — Method.parity Combinatorics.m)) to get an array of all partitions.21 Combinatorics. Use collect(partitions(n. Use collect(partitions(array.24 Combinatorics. Use collect(partitions(n)) to get an array of all partitions.partitions Combinatorics. The number of partitions to generate can be efficiently computed using length(partitions(array)). this function returns an iterator object. . source 13.m)).25 Combinatorics. The number of partitions into m subsets is equal to the Stirling number of the second kind and can be efficiently computed using length(partitions(array. so you can ask iseven(parity(p)). source 13.254 CHAPTER 13. this function returns an iterator object.partitions — Method.m)). Because the number of partitions can be very large. Because the number of partitions can be very large.23 Combinatorics. COMBINATORICS 13. Generate all set partitions of the elements of an array into exactly m subsets. The number of partitions to generate can be efficiently computed using length(partitions(n. Generate all arrays of m integers that sum to n.partitions — Method. source 13. Because the number of partitions can be very large. Computes the parity of a permutation using the levicivita function. this function returns an iterator object.parity — Method. source 13. The number of partitions to generate can be efficiently computed using length(partitions(n)). Use collect(partitions(array)) to get an array of all partitions. represented as arrays of arrays. this function returns an iterator object.partitions Combinatorics. represented as arrays of arrays.22 Combinatorics.m)) to get an array of all partitions.partitions Combinatorics. Generate all integer arrays that sum to n.partitions Combinatorics. If p is not a permutation throws an error. Because the number of partitions can be very large. Generate all set partitions of the elements of an array.partitions — Method.

Previous integer not greater than n that can be written as kipi for integers Q p1 . etc. n2.13. Because the number of permutations can be very large. find the largest i1ˆn1 * i2ˆn2 * i3ˆn3 <= x for integer n1.permutations — Method.prevprod Combinatorics. Computes essential part of the partition sequence of lambda source 13.prevprod — Method.26.with replacement combinations Combinatorics. this function returns an iterator object. p2 .partitionsequence Combinatorics.permutations Combinatorics.permutations — Method. Generate all size t permutations of an indexable object. generate all combinations with replacement of size t from an array a. source .26 Combinatorics.27 Combinatorics.28 Combinatorics. n3 source 13.29 Combinatorics. Use collect(permutations(array)) to get an array of all permutations. source 13.partitionsequence — Method. source 13.with replacement combinations — Method. i2. COMBINATORICS.permutations Combinatorics. Generate all permutations of an indexable object. For a list of integers i1. i3.PARTITIONSEQUENCE 255 source 13.30 Combinatorics.

back — Method.1 DataStructures. source 14. source 256 . source 14.s) precedes (m. s::IntSemiToken.t) in the sorted order. s and t are semitokens for the same container m. back(q::Deque) Returns the last element of the deque q.t).2 DataStructures.s) and (m.3 DataStructures.t).compare DataStructures. counter(seq) Returns an Accumulator object containing the elements from seq.Chapter 14 DataStructures 14.counter — Method.counter DataStructures.compare — Method. The return value is -1 if (m. and 1 if (m. 0 if they are equal.back DataStructures.s) succeeds (m. t::IntSemiToken) Determines the relative positions of the data items indexed by (m. compare(m::SAContainer.

4.Base."c"].Order.1].Order.[2.dequeue! DataStructures. [v=1]) Decrements the count for x by v (defaulting to one) source 14.6 DataStructures.Int64.dec! — Method.dec! DataStructures.5 DataStructures.DEC! 257 14.ForwardOrdering} with 2 entries: "b" => 3 "a" => 2 source 14.dequeue! — Method.3.Base.Base.ForwardOrdering} with 3 entries: "c" => 1 "b" => 3 "a" => 2 julia> dequeue!(a) "c" julia> a PriorityQueue{String.Int64. DATASTRUCTURES.14.deque DataStructures.Order. deque(T) Create a deque of type T.7 DataStructures.Forward) PriorityQueue{String.deque — Method. dequeue!(s::Queue) Removes an element from the front of the queue s and returns it.4 DataStructures. dec!(ct.dequeue! — Method. source 14. source .dequeue! DataStructures. dequeue!(pq) Remove and return the lowest priority key from a priority queue."b". julia> a = PriorityQueue(["a". x.

enqueue!(s::Queue.11 DataStructures.Base.10 DataStructures. x) Inserts the value x to the end of the queue s.1].enqueue! DataStructures.258 CHAPTER 14.dequeue pair! — Method.enqueue! — Method.ForwardOrdering} with 3 entries: "c" => 1 "b" => 3 "a" => 2 julia> dequeue_pair!(a) "c" => 1 julia> a PriorityQueue{String.9 DataStructures.Base.3.enqueue! — Method.enqueue! DataStructures.Order.dequeue pair! DataStructures.enqueue! — Method. v) Insert the a key k into a priority queue pq with priority v. dequeue_pair!(pq) Remove and return a the lowest priority key and value from a priority queue as a pair.Int64. k=>v) .Order. enqueue!(pq. julia> a = PriorityQueue(["a". k.ForwardOrdering} with 2 entries: "b" => 3 "a" => 2 source 14. source 14.Order."c"].Forward) PriorityQueue{String.[2.enqueue! DataStructures.8 DataStructures. source 14.Int64."b".Base. DATASTRUCTURES 14. enqueue!(pq.

find root DataStructures.14 DataStructures.Order. source 14.Base.find root — Method. x::T) Finds the root element of the subset in s which has the element x as a member. "c"=>3)) PriorityQueue{String.front DataStructures.heapify DataStructures.ForwardOrdering} with 4 entries: "c" => 3 "b" => 2 "a" => 1 "d" => 4 source 14.Int64.heapify — Function. heapify(v.13 DataStructures. optionally using the given order- ing.FIND ROOT 259 Insert the a key k into a priority queue pq with priority v.12. DATASTRUCTURES.12 DataStructures. find_root{T}(s::DisjointSets{T}.Base.ForwardOrdering} with 3 entries: "c" => 3 "b" => 2 "a" => 1 julia> enqueue!(a. source 14. "b"=>2. front(q::Deque) Returns the first element of the deque q.Int64.front — Method.14. "d"=>4) PriorityQueue{String. julia> a = PriorityQueue(PriorityQueue("a"=>1. . ord::Ordering=Forward) Returns a new vector in binary heap order.Order.

15 DataStructures.3.2].Reverse) 5-element Array{Int64.heappush! — Function. DATASTRUCTURES julia> a = [1.1}: 1 2 4 5 3 julia> heapify(a.1}: 5 3 4 1 2 source 14. x.heappop! — Function.4. Base. heapify!(v.17 DataStructures. this function does not check that the array is indeed heap-ordered. [ord]) . julia> heapify(a) 5-element Array{Int64.5. source 14.16 DataStructures. [ord]) Given a binary heap-ordered array. ord::Ordering=Forward) In-place heapify.heappush! DataStructures.260 CHAPTER 14. heappop!(v.heappop! DataStructures. source 14. For efficiency. remove and return the lowest ordered element.heapify! DataStructures.Order.heapify! — Function. heappush!(v.

source 14. DATASTRUCTURES. source 14.Order. For efficiency.Base.19 DataStructures.isheap DataStructures.inc! — Method.3] 3-element Array{Int64. x.Forward) true julia> isheap(a. julia> a = [1.isheap — Function. preserving the heap property.1}: 1 2 3 julia> isheap(a.14. y::Integer) Returns true if x and y belong to the same subset in s and false otherwise.Base.IN SAME SET 261 Given a binary heap-ordered array.inc! DataStructures.in same set DataStructures. ord::Ordering=Forward) Return true if an array is heap-ordered according to the given order.18. inc!(ct. push a new element x.2. x::Integer.in same set — Method.Order.Reverse) false source . this function does not check that the array is indeed heap-ordered. [v=1]) Increments the count for x by v (defaulting to one) source 14. isheap(v.20 DataStructures. in_same_set(s::IntDisjointSets.18 DataStructures.

end)] source 14.peek — Method. Equivalent to sort(arr.22 DataStructures. lt = <)[1:min(n. DATASTRUCTURES 14.peek DataStructures. top(h::BinaryHeap) Returns the element at the top of the heap h. Equivalent to sort(arr.reset! DataStructures.23 DataStructures. end)] source 14. source 14. peek(pq) Return the lowest priority key from a priority queue without removing that key from the queue.reset! — Method. Returns the n largest elements of arr.top — Method. lt = >)[1:min(n. source .21 DataStructures.262 CHAPTER 14. x) Resets the count of x to zero. Returns its former count.25 DataStructures. Returns the n smallest elements of arr.nlargest DataStructures.nlargest — Method.24 DataStructures.nsmallest — Method.top DataStructures.nsmallest DataStructures. source 14. reset!(ct::Accumulator.

source 14.top with handle DataStructures. update!{T}(h::MutableBinaryHeap{T}.TOP WITH HANDLE 263 14.26.update! — Method. This is equivalent to h[i]=v.14.update! DataStructures.top with handle — Method.27 DataStructures. i::Int. v::T) Replace the element at index i in heap h with v. source . DATASTRUCTURES.26 DataStructures. top_with_handle(h::MutableBinaryHeap) Returns the element at the top of the heap h and its handle.

categorical{T}(A::CategoricalArray{T}[. categorical{T}(A::AbstractArray{T}[. While this will reduce memory use. compress::Bool].compress CategoricalArrays. ordered::Bool=isordered(A)) categorical{T}(A::NullableCategoricalArray{T}[.categorical — Function. 264 . the same applies to the ordered property. ordered::Bool=false) Construct a categorical array with the values from A.Chapter 15 CategoricalArrays 15. Therefore. else. its levels are preserved. use this option with caution (the one-argument version does not suffer from this problem). If the element type supports it. else. compress::Bool].categorical CategoricalArrays. and to the refer- ence type unless compress is passed. If T<:Nullable.1 CategoricalArrays.2 CategoricalArrays. compress::Bool]. they are kept in their order of appearance in A. If compress is provided and set to true. ordered::Bool=isordere If A is already a CategoricalArray or a NullableCategoricalArray. source 15. levels are sorted in ascending order. return a CategoricalArray{T}. the smallest reference type able to hold the number of unique values in A will be used.compress — Method. return a NullableCategoricalArray{T}. passing this parameter will also introduce a type instability which can affect performance inside the function where the call is made. The ordered keyword argument determines whether the array values can be compared according to the ordering of levels or not (see isordered).

cut(x::AbstractArray. values outside of breaks result in null values. nullok::Bool=false) For nullable arrays. • labels::AbstractVector=[]: a vector of strings giving the names to use for the intervals.cut CategoricalArrays. breaks::AbstractVector.cut — Method. the lower bound is included and the upper bound is ex- cluded. Therefore. labels::AbstractVector=[]). use it with caution.cut — Method. extend::Bool=false. cut(x::AbstractArray{<:Nullable}. If nullok=true.3 CategoricalArrays. which can affect performance inside the function where the call is made.4 CategoricalArrays.15. upper). labels::AbstractVector=[]) Cut a numeric array into intervals and return an ordered CategoricalArray indicating the interval into which each entry falls. i. Arguments • extend::Bool=false: when false. this function is type-unstable. extend::Bool=false. ngroups::Integer. cut(x::AbstractArray. determined using quantile. source 15. return a NullableCategoricalArray.CUT 265 compress(A::CategoricalArray) compress(A::NullableCategoricalArray) Return a copy of categorical array A using the smallest reference type able to hold the number of levels of A.3.cut CategoricalArrays. when true. an error is raised if some values in x fall outside of the breaks. Intervals are of the form [lower. labels::AbstractVector=String[]) Cut a numeric array into ngroups quantiles. CATEGORICALARRAYS. default labels are used. and the upper bound is included in the last interval.e. if empty. breaks::AbstractVector. While this will reduce memory use. source 15. source . breaks are automatically added to include all values in x.

source 15. droplevels!(A::CategoricalArray) droplevels!(A::NullableCategoricalArray) Drop levels which do not appear in categorical array A (so that they will no longer be returned by levels).droplevels! CategoricalArrays. ensure compress is not called when creating the categorical array.decompress CategoricalArrays.levels! — Function. newlevels::Vector. > and similar operators. If A is using a small reference type (such as UInt8 or UInt16) the decompressed array will have room for more levels.7 CategoricalArrays.isordered CategoricalArrays.droplevels! — Function. CATEGORICALARRAYS 15.6 CategoricalArrays. isordered(A::CategoricalArray) isordered(A::NullableCategoricalArray) Test whether entries in A can be compared using <.8 CategoricalArrays. source 15. nullok::Bool=false) .levels! CategoricalArrays.5 CategoricalArrays. using the ordering of levels.decompress — Method. decompress(A::CategoricalArray) decompress(A::NullableCategoricalArray) Return a copy of categorical array A using the default reference type (UInt32).isordered — Method. newlevels::Vector) levels!(A::NullableCategoricalArray. To avoid the need to call decompress. levels!(A::CategoricalArray.266 CHAPTER 15. source 15.

Return the modified A. The type of the array is chosen so that it can hold all recoded elements (but not necessarily original elements from a). unless nullok=false is passed: in that case. using the ordering of levels. replacing elements matching a key of pairs with the corresponding value.ordered! CategoricalArrays. Reordering levels will never affect the values of entries in the array. CATEGORICALARRAYS.levels — Method. recode(a::AbstractArray[..11 CategoricalArrays.9 CategoricalArrays. levels(A::CategoricalArray) levels(A::NullableCategoricalArray) Return the levels of categorical array A.recode — Function.15. If A is a CategoricalArray.ordered! — Method. > and similar operators. ordered!(A::CategoricalArray. The same applies if A is a NullableCategoricalArray. source 15.levels CategoricalArrays.recode CategoricalArrays. if A is ordered (see isordered).. which may affect display of results in some operations. it will also be used for order comparisons using <. source 15. then the corresponding value (second item) .) Return a new categorical array with elements from a. For each Pair in pairs. newlevels must include all levels which appear in the data. entries corresponding to missing levels will be set to null. This may include levels which do not actually appear in the data (see droplevels!). source 15. The order of appearance of levels will be respected by levels.10 CategoricalArrays. if the element is equal to (according to isequal) or in the key (first item of the pair).LEVELS 267 Set the levels categorical array A.9. ordered::Bool) Set whether entries in A can be compared using <. default::Any]. pairs::Pair. > and similar operators. ordered::Bool) ordered!(A::NullableCategoricalArray.

. # Examples jldoctest julia> using NullableArrays julia> recode(NullableArray(1:10). .. default::Any].) Fill dest with elements from src. it is copied as-is. [5. 2:4=>0. it is used in place of the original element. in which case an ‘Array‘ is returned. [5. Examples julia> recode(1:10. CATEGORICALARRAYS is copied to src. pairs::Pair. 6=>Nul- lable()) 10-element NullableArrays.1}: 100 0 0 0 -1 6 7 8 -1 -1 ‘‘‘ recode(a::AbstractArray{<:Nullable}[..recode! — Function.recode! CategoricalArrays.12 CategoricalArrays.1}: 100 0 0 0 -1 #NULL 7 8 -1 -1 “‘ source 15. src::AbstractArray[.) For a nullable array ‘a‘. replacing those matching a key of pairs with the corresponding value. automatic lifting is applied: values are unwrapped before comparing them to the keys of ‘pairs‘ using ‘isequal‘. if default is specified. Null values are never replaced with ‘default‘: use ‘Nullable()‘ in a pair to recode them. pairs::Pair. Return a ‘NullableArray‘ unless ‘default‘ is provided and not nullable. default::Any]. recode!(dest::AbstractArray.. 9:10]=>-1.NullableArray{Int64. 2:4=>0. If the element matches no key and default is not provided or nothing. If an element matches more than one key. the first match is used. 1=>100. 9:10]=>-1) 10-element Array{Int64.268 CHAPTER 15. 1=>100.

source 15. default::Any]. Elements of src as well as values from pairs will be converted when possible on assignment. julia> x 10-element Array{Int64.recode! — Method. pairs::Pair.15. equivalent to recode!(a.) Convenience function for in-place recoding.). default::Any]. it is copied as-is. CATEGORICALARRAYS.) For a nullable array src..recode! CategoricalArrays. src::AbstractArray{<:Nullable}[. a. Null values are never replaced with default: use Nullable() in a pair to recode them. 2:4=>0. dest and src must be of the same length. recode!(a::AbstractArray[.13. If an element matches more than one key.13 CategoricalArrays. julia> recode!(x. recode!(dest::AbstractArray. automatic lifting is applied: values are unwrapped before comparing them to the keys of pairs using isequal. If the element matches no key and default is not provided or nothing.RECODE! 269 For each Pair in pairs. if the element is equal to (according to isequal) or in the key (first item of the pair)... if default is specified.. then the corresponding value (second item) is copied to src. 1=>100. it is used in place of the original element.1}: 100 0 0 0 -1 6 7 8 -1 -1 source . 9:10]=>-1).. the first match is used. . pairs::Pair. [5. but not necessarily of the same type.. Examples jldoctest julia> x = collect(1:10).

2 HypothesisTests.MannWhitneyUTest — Method. If x is a matrix with at least two rows and columns.ChisqTest HypothesisTests.e. y][.ChisqTest — Method. ChisqTest(x[. then a goodness-of-fit test is performed (x is treated as a one-dimensional con- tingency table). Implements: pvalue. The contingency table is calculated using counts function from the StatsBase package. y::AbstractVector{<:Real}) Perform a Mann-Whitney U test of the null hypothesis that the probability that an observation drawn from the same population as x is greater than an ob- servation drawn from the same population as y is equal to the probability that 270 . Otherwise. confint source 16. theta0 = ones(length(x))/length(x)]) Perform a PowerDivergenceTest with = 1.MannWhitneyUTest HypothesisTests. In this case. Then the power divergence test is conducted under the null hypothesis that the joint distribution of the cell counts in a 2-dimensional contingency table is the product of the row and column marginals. Note that the entries of x (and y if provided) must be non-negative integers. or are all equal if theta0 is not given. in the form of Pearson’s chi-squared statistic. the hypothesis tested is whether the population probabilities equal those in theta0. x and y must be vectors of the same length. i.Chapter 16 HypothesisTests 16.1 HypothesisTests. or x is a vector. If y is not given and x is a matrix with one row or column. MannWhitneyUTest(x::AbstractVector{<:Real}. it is taken as a two- dimensional contingency table.

e. Otherwise. Implements: pvalue.MultinomialLRT — Method. In all other cases. . i.SignedRankTest HypothesisTests.3 HypothesisTests.4 HypothesisTests. y][. Then the power divergence test is conducted under the null hypothesis that the joint distribution of the cell counts in a 2-dimensional contingency table is the product of the row and column marginals. Behavior may be further controlled by using ExactMannWhitneyUTest or ApproximateMannWhitneyUTest directly. MannWhitneyUTest performs an approximate Mann-Whitney U test. or x is a vector. or tied ranks and 10 samples. MannWhitneyUTest performs an exact Mann-Whitney U test. the hypothesis tested is whether the population probabilities equal those in theta0. y::AbstractVector{T<:Real}) Perform a Wilcoxon signed rank test of the null hypothesis that the distri- bution of x (or the difference x .y if y is provided) has zero median against the alternative hypothesis that the median is non-zero. Implements: pvalue source 16. HYPOTHESISTESTS. If x is a matrix with at least two rows and columns. If y is not given and x is a matrix with one row or column. or are all equal if theta0 is not given. When there are no tied ranks and 50 samples. SignedRankTest(x::AbstractVector{<:Real}) SignedRankTest(x::AbstractVector{<:Real}. confint source 16. In this case. it is taken as a two- dimensional contingency table.SignedRankTest — Method. The Mann-Whitney U test is sometimes known as the Wilcoxon rank-sum test. The contingency table is calculated using counts function from the StatsBase package.MultinomialLRT HypothesisTests.16. x and y must be vectors of the same length. in the form of the likelihood ratio test statistic.MULTINOMIALLRT 271 an observation drawn from the same population as y is greater than an obser- vation drawn from the same population as x against the alternative hypothesis that these probabilities are not equal. then a goodness-of-fit test is performed (x is treated as a one-dimensional con- tingency table).3. MultinomialLRT(x[. Note that the entries of x (and y if provided) must be non-negative integers. theta0 = ones(length(x))/length(x)]) Perform a PowerDivergenceTest with = 0.

i. confint source 16.e.pvalue — Method. then a one-sided test is performed. tail = :both) Compute the p-value for a given significance test. or tied ranks and 15 sam- ples. pvalue(test::HypothesisTest. Implements: pvalue. HYPOTHESISTESTS When there are no tied ranks and 50 samples. then the p-value for the two-sided test is returned.272 CHAPTER 16. i.6 HypothesisTests. method = :central) Compute the p-value for a given Fisher exact test. The one-sided p-values are based on Fisher’s non-central hypergeometric distribution f(i) with odds ratio : X p (left) = f(i) ia X (right) p = f(i) ia For tail = :both. pvalue(x::FisherExactTest. In all other cases. source 16. the p-value is two times the minimum of the one-sided p-values. • :minlike: Minimum likelihood interval.e.5 HypothesisTests.pvalue HypothesisTests. SignedRankTest performs an approximate signed rank test. possible values for method are: • :central (default): Central interval.pvalue — Function. tail = :both. If tail is :left or :right. If tail is :both (default).pvalue HypothesisTests. SignedRankTest performs an exact signed rank test. the p-value is computed by summing all tables with the same marginals that are equally or less prob- able: X p= f(i) f(i)f(a) References . Behavior may be further controlled by using ExactSignedRankTest or ApproximateSignedRankTest directly.

HYPOTHESISTESTS. Supplementary material to “Confidence intervals that match Fisher’s exact or Blaker’s exact tests”.g. link source 16.7. the confidence interval with coverage 1-alpha does not contain the test statistic under h0 if and only if the corresponding test rejects the null hypothesis h0 : = 0 : $$ C (x. tail = :both.testname HypothesisTests.md#HypothesisTests. 29(1):20-25. source 16.pvalue) of the corresponding test source 16. then a one-sided confidence interval is returned.TESTNAME 273 • Gibbons. !!! note Most of the implemented confidence intervals are strongly consistent.9 StatsBase.confint StatsBase. If tail is :left or :right. Issue 2. alpha = 0. P-values: Interpretation and Methodology. J. 1 ) = \{ : p_ (x) > \}. confint(test::BinomialTest.. Biostatistics.05. alpha = 0. • Fay.W. Pratt. tail = :both) Compute a confidence interval C with coverage 1-alpha.testname — Method.confint — Function..05.confint StatsBase. M. American Statistican. method = :clopper_pearson) .7 HypothesisTests..8 StatsBase. confint(test::HypothesisTest. Volume 11. testname(::HypothesisTest) Returns the string value. that is.16.D. then a two-sided confidence interval is returned. $$ where $p_$ is the [‘pvalue‘](HypothesisTests. If tail is :both (default). J. e. 1 April 2010.confint — Function. Pages 373–374. 1975. “Binomial test” or “Sign Test”.P.

tail=:both.confint — Function.alpha. Statistical Science. alpha::Float64=0. T.05. the corresponding confidence region might not be an interval. it is usually too conservative. The interval is very similar to the Wilson interval.. References • Brown.274 CHAPTER 16. L. resulting in good empirical coverages even for small numbers of draws and extreme success probabilities. • :jeffrey: Jeffreys interval is a Bayesian credible interval obtained by using a non-informative Jeffreys prior.10 StatsBase. Cai. • :arcsine: Confidence interval computed using the arcsine transformation to make var(p) independent of the probability p. The empirical coverage is never less than the nominal coverage of 1-alpha.T. 2001. • :agresti coull: Agresti-Coull interval is a simplified version of the Wil- son interval. For tail = :both. One-sided inter- vals are based on Fisher’s non-central hypergeometric distribution. HYPOTHESISTESTS Compute a confidence interval with coverage 1-alpha for a binomial propor- tion using one of the following methods. • :wald: Wald (or normal approximation) interval relies on the standard approximation of the actual binomial distribution by a normal distribu- tion. confint(x::FisherExactTest. A. method=:central) Compute a confidence interval with coverage 1 . • :wilson: Wilson score interval relies on a normal approximation.D. Coverage can be erratically poor for success probabilities close to zero or one. the standard deviation is not approximated by an empirical estimate. Interval estimation for a bino- mial proportion. External links • Binomial confidence interval on Wikipedia source 16.confint StatsBase.. In con- trast to :wald. 16(2):101–117. Possible values for method are: • :clopper pearson (default): Clopper-Pearson interval is based on the bi- nomial distribution. References . !!! note Since the p-value is not necessarily unimodal. the only method implemented yet is the central interval (:central). both are centered around the same value. and DasGupta. The Agresti Coull interval has higher or equal coverage.

3rd Edition. Supplementary material to “Confidence intervals that match Fisher’s exact or Blaker’s exact tests”. 29(1):20-25. R. Pages 373–374. Annals of Mathematical Statistics. Categorical Data Analysis.confint StatsBase. J.C. Pratt. STATSBASE.CONFINT 275 • Gibbons. 30:56-74. alpha = 0. Large Sample Simultaneous Confi- dence Intervals for Multinational Proportions. J. J. • Sison.P. Simultaneous confidence intervals and sample size determination for multinomial proportions. confint(test::PowerDivergenceTest.. 1975. D.11. source . Technometrics. Journal of the American Statistical Association. Biostatistics. American Statistican. Possible values for method are: • :sison glaz (default): Sison-Glaz intervals • :bootstrap: Bootstrap intervals • :quesenberry hurst: Quesenberry-Hurst intervals • :gold: Gold intervals (asymptotic simultaneous intervals) References • Agresti. • Quesensberry.P and Glaz. M.16.05. Alan. 2013. 1995. C. P-values: Interpretation and Methodology. Issue 2. 1 April 2010. Tests Auxiliary to 2 Tests in a Markov Chain. Z.11 StatsBase.W. and Hurst. C. 90:366-369. 6:191-195. Wiley. method = :sison_glaz) Compute a confidence interval with coverage 1-alpha for multinomial pro- portions using one of the following methods. link source 16.confint — Function. 1963. tail = :both. Volume 11. 1964.P. • Fay. • Gold.D.

i. pda2) Return a tuple of PooledDataArrays created from the data in v1 and v2.UInt32.PooledDataVecs DataArrays.1}: "A" "B" "A" "B" "A" "B" "A" 276 . respectively. compact(d::PooledDataArray) Return a PooledDataArray with the smallest possible reference type for the data in d. v2) -> (pda1.e.PooledDataArray{String. the input array is returned.1 DataArrays.2 DataArrays. outer=4)) 8-element DataArrays. PooledDataVecs(v1. Examples julia> p = @pdata(repeat(["A". !!! note If the reference type is already the smallest possible for the data.PooledDataVecs — Method.compact — Method. "B"]. but sharing a common value pool.Chapter 17 DataArrays 17.compact DataArrays. the function aliases the input. source 17.

3]" "[1. 3]) 4-element DataArrays.data — Method. ngroups::Integer) -> PooledDataArray Divide the range of x into intervals based on the cut points specified in breaks.4 DataArrays. data(a::AbstractArray) -> DataArray Convert a to a DataArray. 3.CUT 277 "B" julia> compact(p) # second type parameter compacts to UInt8 (only need 2 unique values) 8-element DataArrays.1}: "A" "B" "A" "B" "A" "B" "A" "B" source 17.3 DataArrays.3. DATAARRAYS. cut(x::AbstractVector.PooledDataArray{String.cut DataArrays. 4].cut — Method. [1. Examples julia> cut([1.PooledDataArray{String.data DataArrays.1}: "[1.3]" "[1. or into ngroups intervals of approximately equal length.3]" "(3. Examples .UInt32. breaks::Vector) -> PooledDataArray cut(x::AbstractVector.17.4]" source 17. 2.UInt8.

2. getpoolidx(pda::PooledDataArray. 2. NA. dropna(v::AbstractVector) -> AbstractVector Return a copy of v with all NA elements removed. source . DATAARRAYS julia> data([1.getpoolidx — Method.1}: 1 2 3 julia> data(@data [1. If val is not already in the value pool.DataArray{Int64.dropna DataArrays.dropna — Method. Examples julia> dropna(@data [NA. 1. 5. 2]) 2-element Array{Int64.DataArray{Int64.5 DataArrays. 3]) 3-element DataArrays. val) Return the index of val in the value pool for pda.1}: 4 5 6 source 17.6 DataArrays.1}: 1 2 julia> dropna([4. NA]) 3-element DataArrays.1}: 1 2 NA source 17.getpoolidx DataArrays. 6]) 3-element Array{Int64. pda is modified to include it in the pool.278 CHAPTER 17.

7 DataArrays.isna DataArrays.UInt8.1}: 1 2 1 2 source 17. k::Integer.isna — Method. 1) 2-element DataArrays. 1. isna(x) -> Bool Determine whether x is missing. 4) 4-element DataArrays. l::Integer = n*k) -> PooledDataArray Generate a PooledDataArray with n levels and k replications.gl DataArrays.isna DataArrays. NA. gl(n::Integer.PooledDataArray{Int64. optionally specifying an output length l.PooledDataArray{Int64.isna — Method. i.7.GL 279 17.UInt8. isna(a::AbstractArray. l must be a multiple of n*k.gl — Method.8 DataArrays.e.1}: 1 2 julia> gl(2.9 DataArrays. Examples julia> isna(1) false julia> isna(NA) true source 17. Examples julia> gl(2. DATAARRAYS. If specified. i) -> Bool .17.

Examples julia> levels(@data [1. 3) true source 17. NA]. front is an integer number of NAs to add at the beginning of the array and back is the number of NAs to add at the end. excluding any NAs. i. Examples julia> padna(@data([1. 2. julia> isna(X.DataArray{Int64.280 CHAPTER 17.padna DataArrays. 3]).padna — Method.DataArray{Int64. 2) 6-element DataArrays. 2) false julia> isna(X. NA]) 2-element DataArrays.1}: 1 2 source 17.1}: NA 1 . 2.levels — Method.levels DataArrays. 1. 2.e. padna(dv::AbstractDataVector. back::Integer) -> DataVector Pad dv with NA values.10 DataArrays. DATAARRAYS Determine whether the element of a at index i is missing. levels(da::DataArray) -> DataVector Return a vector of the unique values in da. levels(a::AbstractArray) -> Vector Equivalent to unique(a). front::Integer. Examples julia> X = @data [1. NA.11 DataArrays.

but it cannot be reduced to exclude present values. "B"].UInt32. inner=3) 6-element DataArrays. source 17.reorder DataArrays. setlevels!(x::PooledDataArray.12 DataArrays. reorder(x::PooledDataArray) -> PooledDataArray Return a PooledDataArray containing the same data as x but with the value pool sorted. modifying x in place. Examples julia> p = @pdata repeat(["A".12. The values can be replaced using a mapping specified in a Dict or with an array. to) Replace all occurrences of from in x with to.replace! DataArrays. replace!(x::PooledDataArray.17.1}: "A" "A" "A" "B" "B" .REORDER 281 2 3 NA NA source 17.replace! — Method.setlevels! — Method.14 DataArrays. Dict}) Set the value pool for the PooledDataArray x to newpool. since the order of the levels is used to identify values. from. source 17. newpool::Union{AbstractVector. modifying x in place.reorder — Method. DATAARRAYS.13 DataArrays.setlevels! DataArrays.PooledDataArray{String. The pool can be enlarged to contain values not present in the data.

282 CHAPTER 17.PooledDataArray{String. Examples julia> p = @pdata repeat(["A". newpool::Union{AbstractVector.15 DataArrays. ["C".1}: "C" "C" "C" "D" "D" "D" . Dict}) Create a new PooledDataArray based on x but with the new value pool specified by newpool.PooledDataArray{String. inner=3) 6-element DataArrays. "D"]) # could also be Dict("A"=>"C".setlevels — Method. "B"]. but it cannot be reduced to exclude present values. julia> p # has been modified 6-element DataArrays.PooledDataArray{String.1}: "C" "C" "C" "B" "B" "B" source 17. DATAARRAYS "B" julia> setlevels!(p. The values can be replaced using a mapping specified in a Dict or with an array. "B"=>"D") 6-element DataArrays. Dict("A"=>"C")).1}: "A" "A" "A" "B" "B" "B" julia> p2 = setlevels(p. since the order of the levels is used to identify values.UInt32.UInt32.UInt32. setlevels(x::PooledDataArray.setlevels DataArrays. The pool can be enlarged to contain values not present in the data.

pool # the pool can contain values not in the array 3-element Array{String.1}: "C" "C" "C" "D" "D" "D" julia> p3.UInt32.SETLEVELS 283 julia> p3 = setlevels(p2.PooledDataArray{String.1}: "C" "D" "E" source . DATAARRAYS. "E"]) 6-element DataArrays. "D". ["C".17.15.

say for plotting. which must be in the exponential family.1 GLM. ) Return the squared deviance residual of from y for distribution D The deviance of a GLM can be evaluated as the sum of the squared de- viance residuals. 1. )) Examples julia> showcompact(devresid(Normal(). is the signed square root of this value [] sign(y . 0. devresid(D. Examples julia> canonicallink(Bernoulli()) GLM.devresid GLM. This is the principal use for these values.devresid — Method.2 GLM. The actual deviance residual.25)) # abs2(y .canonicallink — Function.) 0.) * sqrt(devresid(D.LogitLink() source 18. canonicallink(D::Distribution) Return the canonical link for distribution D.75)) # -2log() when y == 1 0.0625 julia> showcompact(devresid(Bernoulli().Chapter 18 GLM 18.575364 284 .canonicallink GLM. y. 0. 0. y.

1008 0.18. 1.2. 1. julia> mod = lm(@formula(Result ~ 1 + Treatment). atol=0::Real) For each sequential pair of linear predictors in mod.0000 0.3. nullmod.model) Res. julia> nullmod = lm(@formula(Result ~ 1).3 GLM. Other=[1. julia> ft = ftest(mod.ftest GLM. julia> bigmod = lm(@formula(Result ~ 1 + Treatment + Other). 2. DOF DOF DOF SSR SSR R R F* p(>F) Model 1 10 3 0. 2.]. difference in SSR from the preceding model. 2. dat). 2.. difference in DOF from the preceding model.9. DOF DOF DOF SSR SSR R R F* p(>F) Model 1 9 4 0. R. and F-statistic and p-value for the comparison between the two models. .2. dat). degrees of freedom.9603 Model 2 11 2 -1 3. 1. 2.model.25)) # -2log1p(-) = -2log(1-) when y == 0 0.FTEST 285 julia> showcompact(devresid(Bernoulli(). 1. 2. sum of squared residuals (SSR). ftest(mod::LinearModel. difference in R from the preceding model.2.6234 <1e-7 julia> ftest(bigmod. 1.model. 2.1. 2..2292 -3. 1.model) Res. 2.1283 0. 2. 1. A table is returned containing residual degrees of freedom (DOF). GLM. 2. julia> dat = DataFrame(Treatment=[1. Result=[1.model.1038 0. !!! note This function can be used to perform an ANOVA by testing the relative fit of two models to the data Optional keyword argument atol controls the numerical tolerance when test- ing whether the models are nested. perform an F-test to determine if the first one fits significantly better than the next. 2]. 1. 1. 1.9. 2. our null hypothesis is that Result ~ 1 fits the data as well as Result ~ 1 + Treatment.9678 . 0. 2. Because this is an ANOVA. 1]). nullmod.ftest — Method. 2. 3. 1. Examples Suppose we want to compare the effects of two or more treatments on some result. 1. dat).. mod. 1.575364 source 18. 1. 1.9603 241. 0.

inverselink GLM.).1283 -0.1790 Model 3 11 2 -1 3. )) # * (1 . the variance function *(1 . NaN) source .0)) (7. 0.5.5. 0. the derivative of the inverse link.1008 0. 0. 0.9603 0.glmvar — Function.) for Bernoulli() [0. 1. )) # constant for Normal() [1.2292 -3. 7.5 GLM.0] julia> showcompact(glmvar.1236 0.(Bernoulli().0000 0.38906.833333] source 18.(Poisson(). ) Return a 3-tuple of the inverse link. The variance function is returned as NaN unless the range of is (0. 2.0076 2.6234 <1e-7 source 18.0)) (0. 0.138889] julia> showcompact(glmvar. and when appropriate. 0.(Normal().25.632121. 1.0)) (0. . 0.138889.367879.25. 1) Examples julia> showcompact(inverselink(LogitLink(). )) # for Poisson() [0. 0.25) julia> showcompact(inverselink(CloglogLink().4 GLM. ) Return the value of the variance function for D at The variance of D at is the product of the dispersion parameter. In other words glmvar returns the factor of the variance that depends on . 0.0245 0.glmvar GLM. showcompact(collect()) [0.0. 0.inverselink — Function. inverselink(L::Link. 0. glmvar(D::Distribution.232544) julia> showcompact(inverselink(LogLink().0. GLM Model 2 10 3 -1 0.833333] julia> showcompact(glmvar.9603 241.286 CHAPTER 18.5.38906. Examples julia> = inv(6):inv(3):1.166667. which does not depend on and the value of glmvar.166667. 0.

0. 2. 0. GLM. 0.0)) 0.847298.2:0. -0.0. 0. 0. Examples julia> = inv(10):inv(5):1 0. 0. 0.1:0.3.5. for link L at linear predictor value .1.19722] source 18.367879 julia> showcompact(mueta(LogLink().19722] julia> showcompact(linkinv. linkfun(L::Link.6 GLM.0)) 7. 0. ) Return the derivative of linkinv.0)) 0.9] julia> = logit.mueta — Function.8 GLM.7. Examples julia> = inv(10):inv(5):1. the value of the linear predictor for link L at mean . 0. showcompact() [-2.847298.25 julia> showcompact(mueta(CloglogLink(). the mean value. ) Return .38906 source .6.847298. 0.18. ) Return . -0.0.19722. linkinv(L::Link.(LogitLink().LINKFUN 287 18.5.7. d/d.linkfun — Function. 0.847298.().9] source 18. 0. 2.1.linkinv — Function.mueta GLM. 2.(LogitLink().7 GLM. showcompact(collect()) [0.3. )) [0.linkfun GLM.19722. 0. for link L at linear predictor value .9 julia> show(linkfun. Examples julia> showcompact(mueta(LogitLink(). 0.linkinv GLM. mueta(L::Link. )) [-2.

deviance — Method.wrkresp GLM. GLM 18. 0. 1)) 0.deviance StatsBase. 1.11 GLM. 0. source 18.0.75 julia> showcompact(mustart(Binomial().0454545 julia> showcompact(mustart(Normal(). 1)) 0.wrkresp — Method. the values of y are not allowed as values of and must be modified. mustart(D::Distribution. notably the Bernoulli.9 GLM. Examples julia> showcompact(mustart(Bernoulli().25 julia> showcompact(mustart(Bernoulli(). update!{T<:FPVector}(r::GlmResp{T}.wrkresid . 10)) 0. wrkresp(r::GlmResp) The working response. linPr::T) Update the mean.0.eta + r.12 StatsBase. deviance(obj::LinearModel) For linear models.0.0. For some distributions it is appropriate to set = y to initialize the IRLS algorithm but for others. source 18.mustart — Function. linPr.offset. in r given a value of the linear predictor.update! — Method. 1)) 0. 0. working weights and working residuals. y.288 CHAPTER 18. r. the deviance is equal to the residual sum of squares (RSS).r.10 GLM. source .mustart GLM. wt) Return a starting value for .0 source 18.update! GLM.

source 18. or. Valid values of interval type are :confint delimiting the uncertainty of the predicted relationship.nobs — Method.predict StatsBase. predict(mm::LinearModel. nobs(obj::LinearModel) nobs(obj::GLM) For linear and generalized linear models. newX::AbstractMatrix. offset::FPVector=Vector{eltype(newX)}(0)) Form the predicted response of model mm from covariate values newX and.95) Specifying interval type will return a 3-column matrix with the prediction and the lower and upper confidence bounds for a given level (0. source . and :predint delimiting estimated bounds for new data points.13 StatsBase. source 18. optionally.predict StatsBase. nulldeviance(obj::LinearModel) For linear models. predict(mm::AbstractGLM.nulldeviance — Method. returns the number of rows. newx::AbstractMatrix.18.predict — Function. source 18. STATSBASE.14 StatsBase. when prior weights are specified.16 StatsBase.nobs StatsBase.15 StatsBase.nulldeviance StatsBase. the sum of weights. level::Real = 0. an offset.13.05).NOBS 289 18.predict — Method. interval_type::Symbol. the deviance of the null model is equal to the total sum of squares (TSS).95 equates alpha = 0.

“https://” or “git@” should not be present..jl. repo is the remote repository where generated HTML content should be pushed to. repo = "<required>". osname = "linux". deploydocs( root = "<current-directory>". branch = "gh-pages".)deploydocs(repo =”github.git” 290 .gitignore file.”) Keywords root has the same purpose as the root keyword for makedocs. latest = "master".deploydocs — Method.deploydocs Documenter.. For example this package uses the following repo value: [] repo = ”github. PACKAGEN AM Emakedocs(options.Chapter 19 Documenter 19. ) Converts markdown files generated by makedocs to HTML and pushes them to repo. target = "site".com/JuliaDocs/Documenter. This keyword must be set and will throw an error when left undefined. The default value is "site". julia = "nightly". make = <Function>.jl file after the call to makedocs. Do not specify any protocol . relative to root. deps = <Function>.1 Documenter.. like so [] using Documenter. This directory must be added to the repository’s . target is the directory.com/. where generated HTML content should be written to. This function should be called from within a package’s docs/make..

2 Documenter. [”hidden1.HIDE 291 branch is the branch where the generated documentation is pushed.. It will only show up if it happens to be the current page.... It defaults to "gh-pages"..yml configuration file.hide Documenter.yml configuration file. By default this just runs mkdocs build which populates the target directory.”Hidden2”=>”hidden2 source 19.hide — Method.hide Documenter. See Also The Hosting Documentation section of the manual provides a step-by-step guide to using the deploydocs function to automatically generate docs and push then to GitHub.md”.travis. root will be linked to in the navigation menu. children should be a list of pages (note that it can not be hierarchical). Usage . This value must be one of those specified in the os: section of the .md”.. ”mkdocs”) make is the function used to convert the markdown files to HTML. By default this function installs pygments and mkdocs using the Deps. with the title determined as usual. a new orphaned branch is created automatically. children) Allows a subsection of pages to be hidden from the navigation menu.3 Documenter.hide — Method.2. This defaults to "linux". DOCUMENTER. This value must be one of those specified in the julia: section of the . pages = [ .19. osname is the operating system which will be used to deploy generated docu- mentation. latest is the branch that “tracks” the latest generated documentation.pip function: [] deps = Deps. deps is the function used to install any dependencies needed to build the documentation. The title of the hidden page can be overriden using the => operator as usual. If the branch does not exist. By default this value is set to "master".pip(”pygments”. This defaults to "nightly". hide(”Hidden section” =¿ ”hiddeni ndex. [] hide(root. The hidden page will still be present in the linear page list that can be accessed via the previous and next page links. source 19. Usage [] makedocs( . [] hide(page) Allows a page to be hidden in the navigation menu.travis. julia is the version of Julia that will be used to deploy generated documen- tation.

clean = true. "docs")) source is the directory. repo = "".. . hide(”Title” =¿ ”page2.4 Documenter. where the markdown source files are read from.md”). relative to root. It is. called build. source = "src".md”) ]) source 19. like with source. Note that any non- markdown files stored in source are copied over to the build directory when makedocs is run.jl Keywords root is the directory from which makedocs should run. modules = Module[].jl file: [] using Documenter makedocs( keywords. build is the directory. needed when repeatedly running makedocs from the Julia REPL like so: julia> makedocs(root = Pkg.292 CHAPTER 19.makedocs Documenter. ) which is then run from the command line with: [] juliamake. though.jl The folder structure that makedocs expects looks like: docs/ build/ src/ make. by convention.dir("MyPackage". The name of the build directory is. makedocs( root = "<current-directory>". users are free to change this to anything else to better suit their project needs..jl file this keyword does not need to be set. ) Combines markdown files and inline docstrings into an interlinked document.. In most cases makedocs should be run from a make. DOCUMENTER [] makedocs( ... By convention this folder is called src.. hide(”page1. doctest = true.makedocs — Method. build = "build". relative to root.. into which generated files and folders are written when makedocs is run. When run from a make. for the most part. pages = [ ..

Doctesting should only ever be disabled when initially setting up a newly developed package where the developer is just trying to get their package and documentation structure correct. For example Documenter’s make. repo specifies a template for the “link to source” feature. . except in patch releases). it’s encouraged to always make sure that documentation examples are runnable and produce the expected results. this is automatically generated from the remote.4. After that. there’s a @docs blocks with that doc- string). ) and so any docstring from the module Documenter that is not spliced into the generated documentation in build will raise a warning.com/user/project/blob/{commit}{path}L{line}”) Experimental keywords In addition to standard arguments there is a set of non-finalized experimental keyword arguments.g.jl file contains: [] makedocs( modules = [Documenter]. By default this keyword is set to true.. or commit hash • {path} Path to the file in the repository • {line} Line (or range of lines) in the source file For example if you are using GitLab. See the Doctests manual section for details about running doctests. By default this is set to true. modules specifies a vector of modules that should be documented in source.com. If you are using GitHub.19. checkdocs instructs makedocs to check whether all names within the mod- ules defined in the modules keyword that have a docstring attached have the docstring also listed in the manual (e. The default value is :none. The behaviour of these may change or they may be removed without deprecation when a minor version changes (i. DOCUMENTER. This setting can be used as an indicator of the “coverage” of the generated documentation.. you can use this option to tell Documenter how URLs should be generated. If you are using a different host. in which case no checks are per- formed.MAKEDOCS 293 clean tells makedocs whether to remove all the content from the build folder prior to generating new content from source. doctest instructs makedocs on whether to try to test Julia code blocks that are encountered in the generated document. The following placeholders will be replaced with the respective value of the generated link: • {commit} Git branch or tag name. you could use [] makedocs(repo = ”https://gitlab.e. If any inline docstrings from those modules are seen to be missing from the generated content then a warning will be printed during execution of makedocs. If strict is also enabled then the build will fail if any missing docstrings are encountered. By default no modules are passed to modules and so no warnings will appear. Possible values are :all (check all names) and :exports (check only exported names). .

294 CHAPTER 19. DOCUMENTER linkcheck – if set to true makedocs uses curl to check the status codes of external-pointing links. source . sitename. :latex and :markdown (default).HTMLWriter. version) should be documented at the respective *Writer modules (Writers. analytics.LaTeXWriter). The values should be a list of strings (which get matched exactly) or Regex objects. Other keywords related to non-MkDocs builds (assets. format allows the output format to be specified. linkcheck ignore allows certain URLs to be ignored in linkcheck. authors. Writers. Default: false. See Also A guide detailing how to document a package using Documenter’s makedocs is provided in the Usage section of the manual. These can be enabled using the format keyword and they generally re- quire additional keywords be defined. Possible values are :html. If strict is also enabled then the build will fail if there are any broken (400+ status code) links. to make sure that they are up-to-date. depending on the format. Non-MkDocs builds Documenter also has (experimental) support for native HTML and LaTeX builds. pages. These keywords are also currently considered experimental. The links and their status codes are printed to the standard output. By default nothing is ignored. strict – makedocs fails the build right before rendering if it encountered any errors with the document in the previous build phases.

For a color without an alpha channel. except it “strips off” the element type. source 20.alpha ColorTypes.Chapter 20 ColorTypes 20.e. source 20.1 ColorTypes. color_type(RGB{N0f8}) == RGB{N0f8} base_color_type(RGB{N0f8}) == RGB This can be very handy if you want to switch element types.. color). the corresponding transparent color type with storage order (alpha.base color type ColorTypes. base color type is similar to color type. For example. For example: c64 = base_color_type(c){Float64}(color(c)) converts c into a Float64 representation (potentially discarding any alpha- channel information).alphacolor ColorTypes.3 ColorTypes.alpha — Method.alphacolor — Function. alphacolor(RGB) returns ARGB. alpha(p) extracts the alpha component of a color.2 ColorTypes. source 295 . it will always return 1. i.base color type — Method.

source 20. this is the safest default and the easiest to use: c64 = base_colorant_type(c){Float64}(c) source 20. base_color_type(ARGB{N0f8}) == RGB base_colorant_type(ARGB{N0f8}) == ARGB If you just want to switch element types.6 ColorTypes. base colorant type is similar to base color type. COLORTYPES 20. srctype) -> concrete desttype Example: convert{C<:Colorant}(::Type{C}. A) without specifying the element type explicitly (e..” However.4 ColorTypes.296 CHAPTER 20.g. but it preserves the “alpha” portion of the type. The idea is that users may write convert(HSV. c) or even convert(Array{HSV}.blue ColorTypes.base colorant type — Method. when the source object has FixedPoint element type.base colorant type ColorTypes. p::Colorant) = cnvt(ccolor(C. convert(Array{HSV{Float32}}.ccolor — Method. we choose Float32.blue — Method.5 ColorTypes. p) where cnvt is the function that performs explicit conversion. and the destination only supports AbstractFloat.typeof(p)). ccolor implements the logic “choose the user’s eltype if specified. otherwise retain the eltype of the source object. ccolor (“concrete color”) helps write flexible methods. source .ccolor ColorTypes. blue(c) returns the blue component of an AbstractRGB opaque or trans- parent color. Usage: ccolor(desttype. For example. A)).

i.color — Method. source 20. This. and ccolor are useful for manipulating types for writing generic code.color type ColorTypes.g.e.comp1 — Method. and related functions like base color type.7 ColorTypes. For example. COLORTYPES.comp1 ColorTypes.8 ColorTypes.7.coloralpha — Function. alpha).20. color type(c) or color type(C) (c being a color instance and C being the type) returns the type of the Color object (without alpha channel). if present). color_type(RGB) == RGB color_type(RGB{Float32}) == RGB{Float32} color_type(ARGB{N0f8}) == RGB{N0f8} source 20. but for types like BGR that reverse the internal storage order this provides the value that you’d use to reconstruct the color. source . omits the alpha channel. coloralpha(RGB) returns RGBA.color ColorTypes. base colorant type. comp2(c). c == typeof(c)(comp1(c). color(c) extracts the opaque color component from a Colorant (e. source 20. the corresponding transparent color type with storage order (color.9 ColorTypes.. comp3(c)) returns true.coloralpha ColorTypes. For most color types without an alpha channel.color type — Method.3}.10 ColorTypes.COLOR 297 20. comp1(c) extracts the first component you’d pass to the constructor of the corresponding object. for any Color{T.. Specifically. this is just the first field.

1.6.1.0.0) julia> mapc(max.0.0.5.mapc ColorTypes.0.0.0. source 20.mapc — Method. source 20.gray ColorTypes.3.13 ColorTypes.5)) RGB{Float64}(0.green ColorTypes.15 ColorTypes.8. mapc(f. rgb) -> rgbf mapc(f. comp3(c) extracts the third constructor argument (see comp1).comp2 — Method.298 CHAPTER 20.8.1.0. RGB(0.comp2 ColorTypes. RGB(0. green(c) returns the green component of an AbstractRGB opaque or trans- parent color.5.5)) RGB{Float64}(0.comp3 — Method.5.8) . source 20.0.0.green — Method.comp3 ColorTypes. source 20. RGB(0.5) julia> mapc(+. Examples: julia> mapc(x->clamp(x.3).1.11 ColorTypes.2.3.8.0. gray(c) returns the gray component of a grayscale opaque or transparent color. COLORTYPES 20.0.0.3).14 ColorTypes.3.1. RGB(-0. rgb2) -> rgbf mapc applies the function f to each color channel of the input color(s).0.0.5. RGB(0. re- turning an output color in the same colorspace. comp2(c) extracts the second constructor argument (see comp1).0.5.1).12 ColorTypes.gray — Method.2)) RGB{Float64}(0. rgb1.

source 20.mapreducec ColorTypes. op(comp2(c). op(f(comp2(c)). f(comp1(c))) whereas for RGB mapreducec(f. op.mapreducec — Method. mapreducec(f. op(v0. v0.red — Method.17 ColorTypes. v0. f(comp1(c))))) If c has an alpha channel. c::Gray) = op(v0.18 ColorTypes. first applying f to each channel. op. c::RGB) = op(comp3(c).20. comp1(c)) whereas for RGB reducec(op. v0 is the neutral element used to initiate the reduction. it is always the last one to be folded into the reduction. red(c) returns the red component of an AbstractRGB opaque or transparent color.16 ColorTypes. it is always the last one to be folded into the reduction. source 20.reducec ColorTypes. source . op. v0. c::RGB) = op(f(comp3(c)). For grayscale. For grayscale. c::Gray) = op(v0.MAPREDUCEC 299 source 20. v0. reducec(op.reducec — Method.red ColorTypes. v0 is the neutral element used to initiate the reduction. c) Reduce across color channels of c with the binary operator op. mapreducec(f. v0. COLORTYPES. comp1(c)))) If c has an alpha channel.16. op(v0. v0. c) Reduce across color channels of c with the binary operator op. reducec(op.

factor Primes.Base.1 Primes. [] julia¿ factor(Set. this returns the list of all prime factors of n with multiplicities. a Set.Factorization Compute the prime factorization of an integer n. this returns the distinct prime factors as a set.factor — Method. factor(n::Integer) -> Primes. 100) Set([2.SortedDict{Int64.e. [] julia¿ factor(100) 2252 300 . 100)) == 100 true When ContainerType == Set.5]) source 21.Chapter 21 Primes 21.2 Primes.factor Primes. in sorted order. of type Factorization. 100) 4-element Array{Int64.Order. the number of times the factor appears in the factorization). factor(ContainerType.factor — Method. which must be a subtype of Associative or AbstractArray.Fo with 2 entries: 2 =¿ 2 5 =¿ 2 When ContainerType <: AbstractArray. The returned object. is an associative container whose keys correspond to the factors.SortedDict. n::Integer) -> ContainerType Return the factorization of n stored in a ContainerType. 100) DataStructures. in sorted order. [] julia¿ factor(DataStructures. [] julia¿ factor(Vector.Int64. The value associated with each key indicates the mul- tiplicity (i.1}: 2 2 5 5 julia¿ prod(factor(Vector. or an IntSet.

[reps = 25]) -> Bool Probabilistic primality test. [] julia¿ isprime(big(3)) true source 21.ISMERSENNEPRIME 301 For convenience.e. Seminumerical Algorithms).isprime Primes.21.1) true source 21. and false otherwise.1}: 0=¿1 source 21.5 Primes. Use the key- word argument check to enable/disable checking whether M is a valid Mersenne number. a negative number n is factored as -1*(-n) (i.isprime Primes.4 Primes. isprime(x::BigInt. and false otherwise.ismersenneprime — Method.3 Primes. isprime(n::Integer) -> Bool Returns true if n is prime. PRIMES. Returns true if x is prime with high probability (pseudoprime). reps = 25 is considered safe for cryptographic applications (Knuth.1. [check::Bool = true]) -> Bool Lucas-Lehmer deterministic test for Mersenne primes. -1 is considered to be a factor). The false positive rate is about 0.1) false julia> ismersenneprime(2^13 .isprime — Function. and false if x is composite (not prime).ismersenneprime Primes. where p is a prime number.isprime — Method. and 0 is factored as 0^1: [] julia¿ factor(-9) -1 32 julia¿ factor(0) 0 julia¿ collect(factor(0)) 1-element Array{Pair{Int64. julia> ismersenneprime(2^11 . M must be a Mersenne number. [] julia¿ isprime(3) true source . Return true if the given Mersenne number is prime.e. to be used with caution. of the form M = 2^p .3.25^reps.Int64}. i. ismersenneprime(M::Integer.

2^607 . 2) 7 julia> nextprime(5. the returned number is only a pseudo-prime (the function isprime is used internally). Returns true if R is prime. Note that for n::BigInt. PRIMES 21.isrieselprime Primes. julia> isrieselprime(1. i::Integer=1) The i-th smallest prime not less than n (in particular. julia> nextprime(4) 5 julia> nextprime(5) 5 julia> nextprime(4.nextprime — Function. -i). this is equivalent to prevprime(n. nextprime(n::Integer. also known as Riesel primes.302 CHAPTER 21. See also prevprime. with 0 < k < Q. Q::Integer) -> Bool Lucas-Lehmer-Riesel deterministic test for N of the form N = k * Q.1) false julia> isrieselprime(3.isrieselprime — Method.1) true source 21. 2) 7 source .7 Primes. nextprime(p) == p if p is prime).6 Primes. 2^11 . and false otherwise or if the combination of k and n is not supported. Q = 2^n .1 and n > 0.1) # == ismersenneprime(2^11 . If i < 0. isrieselprime(k::Integer.nextprime Primes.

prevprime(n::Integer.21.prevprime — Function.PREVPRIME 303 21.primes — Method. julia> prevprime(4) 3 julia> prevprime(5) 5 julia> prevprime(5. this is equivalent to nextprime(n. i::Integer) The i-th prime number. See also nextprime. If i < 0.10 Primes. julia> prime(1) 2 julia> prime(3) 5 source 21.8. the returned number is only a pseudo-prime (the function isprime is used internally).prime — Method.prime Primes. primes([lo.8 Primes.primes Primes. i::Integer=1) The i-th largest prime not greater than n (in particular prevprime(p) == p if p is prime). source . if specified) up to hi. Note that for n::BigInt. -i). 2) 3 source 21. PRIMES.prevprime Primes.9 Primes.] hi) Returns a collection of the prime numbers (from lo. prime{T}(::Type{T}=Int.

primesmask — Method.prodfactors Primes.13 Primes. Useful when working with either primes or composite numbers. i. of the positive integers (from lo. Note that if factors is of type AbstractArray or Primes.e.prod.radical Primes.] hi) Returns a prime sieve. prodfactors(factors) Compute n (or the radical of n when factors is of type Set or IntSet) where factors is interpreted as the result of factor(typeof(factors). julia> prodfactors(factor(100)) 100 source 21.12 Primes. primesmask([lo.prodfactors — Function.Factorization.11 Primes. This is equal to the product of the distinct prime numbers dividing n.304 CHAPTER 21. if specified) up to hi. julia> radical(2*2*3) 6 source .primesmask Primes. n). as a BitArray. source 21. PRIMES 21. then prodfactors is equivalent to Base.radical — Method. the largest square-free divisor of n. radical(n::Integer) Compute the radical of n.

15 Primes. the number of positive integers m n with gcd(m. source . source 21. totient(f::Factorization{T}) -> T Compute the Euler totient function of the number whose prime factorization is given by f.totient — Method.totient Primes. PRIMES. The totient function of n when n is negative is defined to be totient(abs(n)).14.totient — Method.14 Primes.TOTIENT 305 21.totient Primes.21. n) == 1). which counts the number of positive integers less than or equal to n that are relatively prime to n (that is. This method may be preferable to totient(::Integer) when the factorization can be reused for other purposes. totient(n::Integer) -> Integer Compute the Euler totient function (n).

[indices].imresize ImageTransformations.invwarpedview — Method. inds) -> imgr Change img to be of size sz (or to have indices inds). tinv. size(img). When invoking wv[I]. If you are shrinking the image. [fill = NaN]) -> wv Create a view of img that lazily transforms any given index I passed to wv[I] to correspond to img[inv(tinv)(I)].gaussian() # from ImageFiltering imgr = imresize(imfilter(img. values for img must be reconstructed at arbitrary lo- cations inv(tinv)(I). imresize(img.imresize — Method. invwarpedview(img.invwarpedview ImageTransformations. sz) kern = KernelFactors.jl. This interpolates the values at sub-pixel locations.2 ImageTransformations. A useful package to create a wide variety of such transformations is CoordinateTransformations. For example: = map((o. [degree = Linear()]. sz) See also restrict. note that InvWarpedView is created by supplying the forward transformation. sz) -> imgr imresize(img. The given transformation tinv must accept a SVector as input and support inv(tinv).1 ImageTransformations. kern.75*o/n. source 22. you risk aliasing unless you low-pass filter img first.n)->0.Chapter 22 ImageTransformations 22. InvWarpedView serves as a wrapper around WarpedView 306 . While technically this approach is known as backward mode warping. NA()).

The transformation tform must accept a SVector as input. The optional parameter indices can be used to specify the domain of the resulting wv. Periodic() or Reflect(). The parameters degree and fill can be used to specify the b-spline degree and the extrapolation scheme respectively. When img is a plain array. tform. See also imresize.3 ImageTransformations. and 0 otherwise). source 22. It is possible to configure what degree of b-spline to use with the parameter degree.3. values for img must be reconstructed at arbitrary locations tform(I) which do not lie on to the lattice of pixels. .jl. Reconstruction scheme During warping.22. [degree = Linear()].restrict ImageTransformations. or all spatial coordinates if region is not specified. restrict(img[. How this reconstruction is done depends on the type of img and the optional parameter degree.warp — Method. then on-grid b-spline interpolation will be used. degree = Constant() for nearest neighbor interpolation. IMAGETRANSFORMATIONS. region]) -> imgr Reduce the size of img by two-fold along the dimensions listed in region. so is better than a naive summation over 2x2 blocks. The parameter fill also accepts extrapolation schemes.restrict — Method.RESTRICT 307 which takes care of interpolation and extrapolation. such as Flat(). or degree = Quadratic(Flat()) for quadratic interpolation. In the case tform(I) maps to indices outside the original img. It anti-aliases the image as it goes. A useful package to create a wide variety of such transformations is CoordinateTransformations. [fill = NaN]) -> imgw Transform the coordinates of img. By default the indices are computed in such a way that wv contains all the original pixels in img. [indices].4 ImageTransformations. those locations are set to a value fill (which defaults to NaN if the element type supports it. For example one can use degree = Linear() for linear interpola- tion.jl.warp ImageTransformations. For more control over the reconstruction scheme — and how beyond-the-edge points are handled — pass img as an AbstractInterpolation or AbstractExtrapolation from Interpolations. returning a new imgw satisfying imgw[I] = img[tform(I)]. source 22. warp(img. This approach is known as backward mode warping.

707107 -0.Base.707107. julia> indices(img) (Base. CoordinateTransformations.707107].707107 0. rot).755.308 CHAPTER 22. julia> indices(imgr) (Base.OneTo(512). julia> indices(imgw) (-196:709. julia> indices(imgw) (-293:612. you can “strip” the custom indices with parent(imgw). If you just want a plain array.OneTo(905)) source 22. 0.707107]) julia> imgw = warp(img0.-68:837) # Alternatively.707107. This can be very handy for keeping track of how pixels in imgw line up with pixels in img.-293:611) julia> imgr = parent(imgw). IMAGETRANSFORMATIONS The meaning of the coordinates The output array imgw has indices that would result from applying inv(tform) to the indices of img.99]) julia> imgw = warp(img.707107 0. [-196. . TestImages.warpedview ImageTransformations. # origin near top of image julia> rot = LinearMap(RotMatrix(-pi/4)) LinearMap([0.707107 0.warpedview — Method. -384:383). center(img)) AffineMap([0. tfm).Base.OneTo(906).293.5 ImageTransformations. OffsetArrays julia> img = testimage("lighthouse"). -0. specify the origin in the image itself julia> img0 = OffsetArray(img. Examples: a 2d rotation (see JuliaImages documentation for pic- tures) julia> using Images. -30:481.OneTo(768)) # Rotate around the center of ‘img‘ julia> tfm = recenter(RotMatrix(-pi/4).

It is possible to configure what degree of b-spline to use with the parameter degree. IMAGETRANSFORMATIONS. A useful package to create a wide variety of such transformations is CoordinateTransformations. tform. the two functions share the same interface.5.jl. [indices]. parent(warpedview(img. The given transformation tform must accept a SVector as input. Additionally.22. In the case tform(I) maps to indices outside the domain of img. By default the indices are computed in such a way that the resulting WarpedView contains all the original pixels in img. such as Flat(). Consequently. .. or degree = Constant() for nearest neighbor interpolation. [fill = NaN]) -> wv Create a view of img that lazily transforms any given index I passed to wv[I] to correspond to img[tform(I)]. the parameter fill also accepts extrapolation schemes. [degree = Linear()]. The optional parameter indices can be used to specify the domain of the resulting WarpedView. then on-grid b-spline interpolation will be used. To do this inv(tform) has to be computed. lazy version of warp. then the parameter indices has to be specified manually. where the pixel of img will serve as the coeficients. warpedview will insist that the resulting WarpedView will be a view of img (i. This approach is known as backward mode warping. When invoking wv[I]. with one important difference. and 0 otherwise). When img is a plain array. As such. If the given transformation tform does not support inv. The two possible values are degree = Linear() for linear interpolation.e.)) === img). values for img must be reconstructed at arbitrary locations tform(I) which do not lie on to the lattice of pixels..WARPEDVIEW 309 warpedview(img. source . How this re- construction is done depends on the type of img and the optional parameter degree. Periodic() or Reflect(). warpedview restricts the parameter degree to be either Linear() or Constant(). those locations are set to a value fill (which defaults to NaN if the element type supports it. warpedview is essentially a non-coping.

Wrapper around derivative function in ForwardDiff source 23. • x0 an initial starting value. Some (Newton. as desired. Positional arugments: • f a function. Values larger than 8 can be slow to compute. |x n|) * xreltol) 310 .D — Function. Take derivative of order k of a function. callable object. Find a zero of a univariate function using one of several different methods.x {n-1}| <= max(xabstol.1 Roots.Chapter 23 Roots 23. or tuple of same. Halley) may have derivative(s) computed using the ForwardDiff pacakge. max(1.2 Roots. but may be an array for bisection methods. Arguments: • f::Function: a mathematical function from R to R.find zero Roots. see below.D Roots. The value float(x0) is passed on. • method one of several methods. Most methods are derivative free. • k::Int=1: A non-negative integer specifying the order of the derivative. Keyword arguments: • xabstol=zero(): declare convergence if |x n . Typically a scalar.find zero — Method. A tuple is used to pass in derivatives.

Steffensen()) # also Order2() source 23. Order0() (heuristic.0. Order5() (KSS). Order1() (also Secant()). |x n|) * reltol) • reltol: • bracket: Optional.3 Roots. Not exported: Secant(). but can utilize many more function calls. Returns: Returns xn if the algorithm converges.‘ Examples: f(x) = x^5 . 1. If the algorithm stops.fzero Roots. ROOTS. a hybrid algorithm may be used where bisection is utilized for steps that would go out of bounds.1 find_zero(f. returns xn if |f(xn)| ˆ(2/3).0.FZERO 311 • xreltol=eps(): • abstol=zero(): declare convergence if |f(x n)| <= max(abstol. • maxevals::Int=40: stop trying after maxevals steps • maxfnevals::Int=typemax(Int): stop trying after maxfnevals function evaluations • verbose::Bool=false: If true show information about algorithm and a trace.23. Order16() (Thukral). 1. If given. Order8() (Thukral). use Order1() Steffensen() use Order2() Newton() (use newton() function) Halley() (use halley() function) The order 0 method is more robust to the initial starting point. Order5()) find_zero(f.3. Exported methods: Bisection(). where = reltol. Order2() (also Steffensen()). Find zero of a function within a bracket Uses a modified bisection method for non big arguments Arguments: • f A scalar function or callable object .fzero — Method. otherwise a ConvergenceFailed error is thrown. A bracketing interval for the sought after root. max(1.x . slow more robust). The higher order methods may be of use when greater precision is desired.

2. it must be that f(a)*f(b) < 0. Set true to trace algorithm • order: Can specify order of algorithm.5. abs(x1)*xtolrel). source . and Shi. 8. Find zero of a function using an iterative algorithm • f: a scalar function or callable object • x0: an initial guess. Keyword arguments: • ftol: tolerance for a guess abs(f(x)) < ftol • xtol: stop if abs(xold . If a==-Inf it is replaced with nextfloat(a). 5. This is a polyalgorithm redirecting different algorithms based on the value of order. |xnew|)*xtolrel • xtolrel: see xtol • maxeval: maximum number of steps • verbose: Boolean. Example: ‘fzero(sin. There are maxfneval when order is 1.8. 16. 3. a default tolerance is used for the sub-bracket length that can be enlarged with xtol. 0 is most robust. or 16 and beta for orders 2. For Big values.fzero Roots. For a bracket to be valid.2. For Float64 values.4 Roots.8.fzero — Method. if b==Inf it is replaced with prevfloat(b). [big(3). it stops when the sub-bracketing produces an bracket with length less than max(xtol. 4]) find pi with more digits source 23. 4)‘ # find pi ‘fzero(sin. also 1.16. passed on to different algorithms.5. which defaults to the algorithm of Alefeld. • kwargs. ROOTS • a left endpont of interval • b right endpont of interval • xtol optional additional tolerance on sub-bracket size. finite valued.312 CHAPTER 23. the answer is such that f(prevfloat(x)) * f(nextfloat(x)) < 0 unless a non-zero value of xtol is specified in which case.xnew) <= xtol + max(1.. Potra..

the number of subintervals is increased and the process is re-run. source 23.FZERO 313 23. source 23. Implementation of Halley’s method.b]. Otherwise.4]). Defaults to automatic derivative • fpp:Function=D(f.b].8 Roots.fzero Roots.halley Roots.fzero Roots.23. fzeros(f.9 Roots. xn1 = xn . source 23. There are possible issues with close-by zeros and zeros which do not cross the origin (non-simple zeros).2) – second derivative of f. For bracketing subintervals. Find a zero within a bracket with an initial guess to possibly speed things along.6 Roots.7 Roots.5.fzeros Roots. Find zero using Newton’s method.halley — Method.fzeros — Method. if possible. as fzero(sin. If there are a large number of zeros found relative to the number of subintervals. bisection is used.b] into subintervals and checks each for a root. . a derivative- free method is used. [3.fzero — Method.2f(xn)*f(xn) / (2*f(xn)^2 .fzero — Method. Simple algorithm that splits [a. Find a zero with bracket specified via [a.5 Roots. b) Attempt to find all zeros of f within an interval [a.fzero — Method. ROOTS. source 23.f(xn) * f(xn)) Arguments: • f::Function – function to find zero of • fp::Function=D(f) – derivative of f.fzero Roots. Answers should be confirmed graphically. a.

|xn|) * ftol. • xtol.10 Roots.newton — Method. Stop iterating if more than this many function calls. |xn|) * xtolrel • maxeval.314 CHAPTER 23. |xn|) * xtolrel • maxeval.newton Roots. Stop iterating when |xn+1 . Defaults to automatic derivative • x0::Real – initial guess Keyword arguments: • ftol. Implementation of Newton’s method: x n1 = x n . Stop iterating when |f(xn)| <= max(1. Stop iterating when |xn+1 . secant method: solve for zero of f(x) = 0 using the secant method source .xn| <= xtol + max(1. Stop iterating when |xn+1 . ROOTS • x0::Real – initial guess Keyword arguments: • ftol. |xn|) * xtolrel • xtolrel. • verbose::Bool=false Set to true to see trace. source 23.xn| <= xtol + max(1. throw error. Stop iterating when |xn+1 . throw error.11 Roots. |xn|) * xtolrel • xtolrel.xn| <= xtol + max(1. throw error.secant method Roots. • verbose::Bool=false Set to true to see trace. • xtol. Stop iterating when |f(xn)| <= max(1. |xn|) * ftol. source 23.secant method — Method. Stop iterating if more than this many steps. Stop iterating if more than this many steps.f(x n)/ f(x n) Arguments: • f::Function – function to find zero of • fp::Function=D(f) – derivative of f.xn| <= xtol + max(1. • maxfneval.

PyNULL — Method.PyTextIO — Method. This is useful for initializing PyObject global variables and array elements before an actual Python object is available.PyReverseDims — Method. source 24. someobject).PyReverseDims PyCall. PyNULL() Return a PyObject that has a NULL underlying pointer. PyReverseDims(array) Passes a Julia array to Python as a NumPy row-major array (rather than Julia’s native column-major order) with the dimensions reversed (e.1 PyCall. it doesn’t actually refer to any Python object. This is useful for Python libraries that expect row-major data. i. This procedure will properly handle Python’s reference counting (so that the Python object will not be freed until you are done with myglobal).PyTextIO PyCall. reas- sign myglobal to point to an actual object with copy!(myglobal. 315 .PyNULL PyCall. you might do const myglobal = PyNULL() and later on (e.Chapter 24 PyCall 24. a 234 Julia array is passed as a 432 NumPy row-major array).3 PyCall. For example. in a module init function).g.2 PyCall.e. source 24.g.

PyPtr}.Vector{UInt8}}) Convert b to a Python bytes object. kwargs. or of PyAny to request an automated conversion) source . converting the return value to returntype (use a returntype of PyObject to return the unconverted Python object reference.pybuiltin PyCall. returntype::TypeTuple.pybytes PyCall.. pybuiltin(s::AbstractString) Look up a string or symbol s among the global Python builtins. This differs from the default PyObject(b) conversion of String to a Python string (which may fail if b does not con- tain valid Unicode)..pycall — Method.4 PyCall. while if s is a symbol it returns the builtin converted to PyAny. pybytes(b::Union{String.5 PyCall. If s is a string it returns a PyObject. so they can be used for binary I/O in Python source 24..) Call the given Python function (typically looked up from a module) with the given args.. source 24. or from the default conversion of a Vector{UInt8} to a bytearray object (which is mutable. pycall(o::Union{PyObject. PYCALL PyTextIO(io::IO) PyObject(io::IO) Julia IO streams are converted into Python objects implementing the Raw- IOBase interface. args.316 CHAPTER 24.pybuiltin — Method. source 24. .pybytes — Method.6 PyCall.pycall PyCall. unlike bytes).. (of standard Julia types which are converted automatically to the corresponding Python types if possible). .

The remaining arguments are keywords that define local variables to be used in the expression. but it could be :wx. source 24. PyObject}().pygui — Method. :tk. kwargs.. pygui() Return the current GUI toolkit as a symbol..8 PyCall. :gtk.9 PyCall. For example. The argument gui defaults to the current default GUI.pygui stop — Function. pyeval("x + y".24. returntype::TypeTuple=PyAny.pygui stop PyCall. or :qt. :gtk3.pygui PyCall. source 24. The gui argument defaults to current default GUI.pyeval — Function.pygui start PyCall. PYCALL. pygui_stop(gui::Symbol = pygui()) Stop any running event loop for gui. pyeval(s::AbstractString. y=2) returns 3. x=1. source 24.10 PyCall.) This evaluates s as a Python string and returns the result converted to rtype (which defaults to PyAny). locals=PyDict{AbstractString.7.pyeval PyCall.7 PyCall.PYEVAL 317 24. input_type=Py_eval_input. source . pygui_start(gui::Symbol = pygui()) Start the event loop of a certain toolkit.pygui start — Function.

13 PyCall. throws an exception with an error message telling the user how to configure PyCall to use Conda for automated installation of the module. channel is an optional Anaconda “channel” to use for installing the package. If PyCall is not using Conda and the pyimport fails. [channel]) Returns the result of pyimport(modulename) if possible.pytype mapping — Method.318 CHAPTER 24. this is useful for packages that are not included in the default Anaconda package listing. Other Anaconda-based Python installations are also supported as long as their conda program is functioning. jltype) Given a Python type object pytype.pytype mapping PyCall. pyimport(s::AbstractString) Import the Python module s (a string or symbol) and return a pointer to it (a PyObject). PYCALL 24.pyimport conda — Function.11 PyCall.name source 24. pyimport_conda(modulename. source 24.add(condapkg) and then re-try the pyimport. Functions or other symbols in the module may then be looked up by s[name] where name is a string (for the raw PyObject) or symbol (for automatic type-conversion). If the module is not found. tell PyCall to convert it to jltype in PyAny(object) conversions. The third argument.pyimport conda PyCall. and PyCall is configured to use the Conda Python distro (via the Julia Conda package). then automatically install condapkg via Conda. source . pytype_mapping(pytype. this does not define a Julia module and members cannot be accessed with s. condapkg.12 PyCall. Unlike the @pyimport macro.pyimport — Method.pyimport PyCall.

source 24. PYCALL.14.pytype query PyCall.14 PyCall.PYTYPE QUERY 319 24.24.member. source .pytype query — Function.15 PyCall.member. @pyimport module as name is equivalent to const name = pywrap(pyimport("module")) If the Python module contains identifiers that are reserved words in Julia (e. return the corresponding native Julia type (de- faulting to default) that we convert o to in PyAny(o) conversions.pymember(:member) (for the PyAny conversion) or w. they cannot be accessed as w.pymember(“member”) (for the raw PyObject).pywrap — Function. function). For example.g. one must instead use w. pywrap(o::PyObject) This returns a wrapper w that is an anonymous module which provides (read) access to converted versions of o’s members as w. default=PyObject) Given a Python object o.pywrap PyCall. pytype_query(o::PyObject.

Backend. Geom.Compose.Backend object • p: The Plot object source 25. p2) hstack(Union{Plot..draw Compose.line). hstack(ps::Union{Plot. gridstack. subplot grid.Context}. Examples “‘ p1 = plot(x=[1. Use context() as a placeholder for an empty panel. p2]) source 320 . y=[3. Heterogeneous vectors must be typed.) hstack(ps::Vector) Arrange plots into a horizontal row.4].hstack Compose.1 Compose.Chapter 25 Gadfly 25.hstack — Method.2]. p2 = Compose. See also vstack.2 Compose. draw(backend::Compose. p::Plot) A convenience version of Compose.draw without having to call render Args • backend: The Compose.context().draw — Method. hstack(p1..Context}[p1.

plot — Method. y=[3.layer — Method. vs- tack(p1. subplot grid. elements::ElementOrFunctionOrLayers.line).Context}.vstack Compose..vstack — Method. function plot(data_source::@compat(Union{(@compat Void). elements::ElementOrFunction.. Geom.4]..4 Gadfly. . mapping::Dict. This version takes an explicit mapping dictionary.. gridstack. AbstractMatrix. See also hstack.context().) The old fashioned (pre named arguments) version of plot.2]. vstack(ps::Union{Plot. COMPOSE.plot Gadfly....Context}[p1. (@compat Void)}). p2 = Compose.layer Gadfly. mapping.VSTACK 321 25. Examples “‘ p1 = plot(x=[1. Args: • data source: Data to be bound to aesthetics. layer(data_source::@compat(Union{AbstractDataFrame.5 Gadfly.Compose. p2) vstack(Union{Plot..) Creates layers based on elements Args • data source: The data source as a dataframe • elements: The elements • mapping: mapping Returns An array of layers source 25.3 Compose.3. mapping aesthetics sym- bols to expressions or columns in the data frame.. Use context() as a placeholder for an empty panel. AbstractDataFrame}).) vstack(ps::Vector) Arrange plots into a vertical column. p2]) source 25. Heterogeneous vectors must be typed.25.

:x. statistics. Returns A Compose context containing the rendered plot. For example. :y. statistics. etc. Returns: A Plot object.. Args: • data source: Data to be bound to aesthetics. • elements: Geometries. y=“price”) Where “time” and “price” are the names of columns in my data. AbstractDataFrame}).. :color) mapped to names of columns in the data frame or other expressions...g. Grammar of graphics style plotting consists of specifying a dataset. :x. and binding of aesthetics to columns or expressions of the dataset.point. :y. Geom. • elements: Geometries.. GADFLY • mapping: Dictionary of aesthetics symbols (e. :color) to names of columns in the data frame or other expressions.322 CHAPTER 25. elements::ElementOrFunctionOrLayers. etc). source 25.g.render Gadfly. a simple scatter plot would look something like: plot(my data.) Create a new plot.6 Gadfly. x=“time”. render(plot::Plot) Render a plot based on the Plot object Args • plot: Plot to be rendered. geometries.7 Gadfly. source . coordinates. etc. • mapping: Aesthetics symbols (e. source 25.plot — Method. function plot(data_source::@compat(Union{AbstractMatrix. one or more plot elements (scales.render — Method.plot Gadfly. mapping.

SET DEFAULT PLOT FORMAT 323 25. spy(M::AbstractMatrix. set_default_plot_format(fmt::Symbol) Sets the default plot format source 25. . 1.set default plot format — Method. because the first row/column is drawn to (0.MeasureOrNumber..25. It is a wrapper around the plot() function using the rectbin geometry.9 Gadfly. N+0. spy leaves “holes” instead into the heatmap.10 Gadfly. so that the rectangles become squares • the axes run from 0.8 Gadfly. as is customary • NaNs are not drawn.set default plot size Gadfly.set default plot size — Method.1] of a matrix is in the top left corner. set_default_plot_size(width::Compose... GADFLY.. so that the [1. Specifically • the aspect ratio of the coordinate system is fixed Coord.) Simple heatmap plots of matrices.MeasureOrNumber) Sets preferred canvas size when rendering a plot without an explicit call to draw source 25.5.5 to N+0.8. height::Compose.cartesian(fixed=true).set default plot format Gadfly..spy Gadfly. Args: • M: A matrix.spy — Method. mapping. • the y-direction is flipped.5). elements::ElementOrFunction.5) and the last one to (N-0. It also applies a sane set of defaults to make sure that the plots look nice by default.5.5.

source 25. Geom.2].. y=[3. title(hstack(p1.fontsize(18pt).line).line). source 25.324 CHAPTER 25.3]. title(ctx::Context.style Gadfly. Known bugs: • If the matrix is only NaNs.title Gadfly. hstack. or gridstack.12 Gadfly. because an empty collection gets passed to the plot function / rectbin geometry.style — Method. str::String. Examples p1 = plot(x=[1.p2). Geom. typically created with vstack.2].11 Gadfly. "my latest data". p2 = plot(x=[1.) -> Context Add a title string to a group of plots. Compose. GADFLY Returns: A plot object. See Theme for available field. y=[4.title — Method. fill(colorant"red")) source . Set some attributes in the current Theme. then it throws an ArgumentError.4].. props::Property.

.1.1..3.distinct — Method.1 IterTools.chain — Method. distinct(xs) Iterate through values skipping over those already encountered.2. ’c’]) @show i end i = 1 i = 2 i = 3 i = ’a’ i = ’b’ i = ’c’ source 26. [’a’.2 IterTools.1.Chapter 26 IterTools 26.) Iterate through any number of iterators in sequence.distinct IterTools.chain IterTools. chain(xs. julia> for i in distinct([1. ’b’.2.4.2.4]) @show i end i = 1 325 . julia> for i in chain(1:3.

.5 IterTools. xs1.groupby — Method.3 IterTools. "book".5. ["face".imap — Method. ."book".groupby IterTools.3].iterate — Method.6]) @show i end i = 5 i = 7 i = 9 source 26. [4.2. [1.326 CHAPTER 26. julia> for i in imap(+. imap(f. ITERTOOLS i = 2 i = 4 i = 3 source 26. [xs2. iterate(f. "bar".iterate IterTools. "zzz"]) @show i end i = String["face"."baz"] i = String["zzz"] source 26. "baz"."foo"] i = String["bar".imap IterTools. "foo"..]) Iterate over values of a function applied to successive values from one or more iterators. julia> for i in groupby(x -> x[1]. xs) Group consecutive values that share the same result of applying f. x) . groupby(f.4 IterTools.

6) @show i end i = 100 i = 10.6. n) Cycle through iter n times. f(f(x)). 100). 2) @show i end i = 1 i = 2 i = 3 i = 1 i = 2 i = 3 source . .take() to obtain the required number of elements. 1).7782794100389228 i = 1.26. as in f(x).NCYCLE 327 Iterate over successive applications of f.1622776601683795 i = 1.1547819846894583 source 26.ncycle IterTools. f(f(f(x))).333521432163324 i = 1.6 IterTools. Use Base.. julia> for i in ncycle(1:3.. 5) @show i end i = 1 i = 2 i = 4 i = 8 i = 16 julia> for i in take(iterate(sqrt.. ITERTOOLS. julia> for i in take(iterate(x -> 2x.0 i = 3. ncycle(xs.ncycle — Method.

2) @show i end i = (1.8.9) If the step parameter is set. n) Return the nth element of xs.3) i = (3.9) julia> for i in partition(1:9. This is mostly useful for non-indexable col- lections.6) i = (7. julia> for i in partition(1:9.5. ITERTOOLS 26. 3.7) i = (7.6.8 IterTools.7 IterTools.3) i = (4. 127]) Set([7. each tuple is separated by step values. 31. julia> mersenne = Set([3. nth(xs. 3.3.127]) julia> nth(mersenne. 3) 3 source 26.nth IterTools.3) i = (4.nth — Method. n.partition — Method.6) .2.5.4. julia> for i in partition(1:9.2.8. partition(xs.31.partition IterTools. 3) @show i end i = (1. 7. [step]) Group values into n-tuples.328 CHAPTER 26.5) i = (5. 3) @show i end i = (1.2.

PeekIter{Array{String. 3) @show i end i = (1.1}}(String["face".Nullable{String}("face")) julia> @show peek(it."book".5) i = (7. "zzz"]) IterTools.peekiter IterTools.8) source 26. peekiter(xs) Lets you peek at the head element of an iterator without updating the state. julia> it = peekiter(["face". s = next(it. "baz".s) = Nullable{String}("face") Nullable{String}("face") julia> x.peekiter — Method.9) julia> for i in partition(1:9. s) peek(it. "foo". s) ("face"."zzz"]) julia> s = start(it) (2.false)) julia> @show x x = "face" "face" julia> @show peek(it.2) i = (4.26."bar".8. s) peek(it. "bar". "book". s) peek(it.9.(3.PEEKITER 329 i = (7."baz".s) = Nullable{String}("face") Nullable{String}("face") julia> @show peek(it."foo". ITERTOOLS.9 IterTools.s) = Nullable{String}("foo") Nullable{String}("foo") source .Nullable{String}("foo"). 2.

1}: 993 97 200 303 408 source 26.repeatedly — Method.4:5) @show p end p = (1. 3]) @show i end i = Int64[] i = [1] .millisecond(now())) t (generic function with 1 method) julia¿ collect(repeatedly(t. Dates.4) p = (3.product IterTools. 2. You can restrict the subsets to a specific size k.4) p = (2. k) Iterate over every subset of the collection xs. or infinitely if n is omitted.subsets IterTools.4) p = (1. julia> for i in subsets([1. subsets(xs) subsets(xs.5) source 26. repeatedly(f.product — Method..subsets — Method..1). 5)) 5-element Array{Any. julia> for p in product(1:3.330 CHAPTER 26.repeatedly IterTools.5) p = (2. [] julia¿ t() = (sleep(0. n) Call function f n times.10 IterTools. ITERTOOLS 26.) Iterate over all combinations in the Cartesian product of the inputs. product(xs.12 IterTools.5) p = (3.11 IterTools.

4] i = [3.4] source 26.takenth IterTools.TAKENTH 331 i = [2] i = [1.takenth — Method. an iterator that generates at most the first n elements of xs. takenth(xs.3] i = [2. ITERTOOLS. takestrict(xs.takestrict — Method. .13 IterTools.3)) 3-element Array{Int64. julia> collect(takenth(5:15.1}: 7 10 13 source 26.4] i = [2. n::Int) Like take(). 2) @show i end i = [1.2] i = [1.2] i = [3] i = [1.2. n) Iterate through every nth element of xs.takestrict IterTools.3] i = [1.3] i = [2.26. but throws an exception if fewer than n items are encountered in xs.3] i = [1.13.3] julia> for i in subsets(1:4.14 IterTools.

332 CHAPTER 26. ITERTOOLS julia> a = :1:2:11 1:2:11 julia> collect(takestrict(a. 3)) 3-element Array{Int64.1}: 1 3 5 source .

2. ’b’..chain Iterators.1.1.1 Iterators.1. julia> for i in distinct([1.4.3.distinct Iterators. ’c’]) @show i end i = 1 i = 2 i = 3 i = ’a’ i = ’b’ i = ’c’ source 27.4]) @show i end i = 1 333 .2.) Iterate through any number of iterators in sequence.Chapter 27 Iterators 27. [’a’.distinct — Method. chain(xs.chain — Method.. distinct(xs) Iterate through values skipping over those already encountered.2 Iterators.2. julia> for i in chain(1:3.

iterate(f.groupby Iterators. "book".334 CHAPTER 27.iterate — Method. imap(f. [1. "foo". julia> for i in groupby(x -> x[1].imap — Method. xs) Group consecutive values that share the same result of applying f. xs1.]) Iterate over values of a function applied to successive values from one or more iterators.iterate Iterators. "bar". [xs2."foo"] i = String["bar".4 Iterators. [4."book". groupby(f.groupby — Method. ["face".3 Iterators.."baz"] i = String["zzz"] source 27. ..5 Iterators.3]. "zzz"]) @show i end i = String["face". julia> for i in imap(+.5. "baz".imap Iterators.6]) @show i end i = 5 i = 7 i = 9 source 27. ITERATORS i = 2 i = 4 i = 3 source 27.2. x) .

1622776601683795 i = 1. ITERATORS. 6) @show i end i = 100 i = 10.0 i = 3.6.ncycle Iterators. as in f(x).7782794100389228 i = 1.ncycle — Method.. 100). f(f(f(x))).6 Iterators. 2) @show i end i = 1 i = 2 i = 3 i = 1 i = 2 i = 3 source . ncycle(xs. 5) @show i end i = 1 i = 2 i = 4 i = 8 i = 16 julia> for i in take(iterate(sqrt.NCYCLE 335 Iterate over successive applications of f.. . f(f(x)).1547819846894583 source 27. julia> for i in take(iterate(x -> 2x. julia> for i in ncycle(1:3. Use Base.take() to obtain the required number of elements.27. 1).333521432163324 i = 1. n) Cycle through iter n times..

julia> for i in partition(1:9. 3. julia> mersenne = Set([3.127]) julia> nth(mersenne.4.8.6) i = (7. partition(xs.nth — Method.336 CHAPTER 27. This is mostly useful for non-indexable col- lections.9) julia> for i in partition(1:9. n.5.3) i = (3.partition — Method. 127]) Set([7. 3) @show i end i = (1.7 Iterators.8. 31.8 Iterators. 3) 3 source 27.9) If the step parameter is set.7) i = (7.6.partition Iterators. 2) @show i end i = (1. 3.2.nth Iterators. nth(xs. ITERATORS 27. each tuple is separated by step values. 3) @show i end i = (1.2. 7. julia> for i in partition(1:9.3) i = (4.3.5) i = (5. [step]) Group values into n-tuples. n) Return the nth element of xs.5.6) .3) i = (4.2.31.

s) ("face". "book". "bar"."zzz"]) julia> s = start(it) (2.8.27. s) peek(it.peekiter — Method. 2.Nullable{String}("foo"). "zzz"]) Iterators.9. s) peek(it.s) = Nullable{String}("face") Nullable{String}("face") julia> @show peek(it.2) i = (4.9) julia> for i in partition(1:9."baz".1}}(String["face".(3.s) = Nullable{String}("foo") Nullable{String}("foo") source .9 Iterators.false)) julia> @show x x = "face" "face" julia> @show peek(it. s = next(it. peekiter(xs) Lets you peek at the head element of an iterator without updating the state. 3) @show i end i = (1. julia> it = peekiter(["face".Nullable{String}("face")) julia> @show peek(it."bar". "foo".PeekIter{Array{String.5) i = (7. "baz".peekiter Iterators. ITERATORS."book".8) source 27."foo".PEEKITER 337 i = (7. s) peek(it.s) = Nullable{String}("face") Nullable{String}("face") julia> x.

subsets — Method. 5)) 5-element Array{Any.4) p = (1.1}: 993 97 200 303 408 source 27..4:5) @show p end p = (1.millisecond(now())) t (generic function with 1 method) julia¿ collect(repeatedly(t..11 Iterators. ITERATORS 27. repeatedly(f.338 CHAPTER 27.5) p = (3. Dates.4) p = (2. subsets(xs) subsets(xs.repeatedly — Method. n) Call function f n times. You can restrict the subsets to a specific size k.subsets Iterators.product Iterators.5) source 27.5) p = (2.repeatedly Iterators. product(xs. 3]) @show i end i = Int64[] i = [1] .) Iterate over all combinations in the Cartesian product of the inputs. julia> for p in product(1:3.12 Iterators. julia> for i in subsets([1.product — Method. or infinitely if n is omitted. [] julia¿ t() = (sleep(0. k) Iterate over every subset of the collection xs.4) p = (3.10 Iterators.1). 2.

27. but throws an exception if fewer than n items are encountered in xs. takestrict(xs. ITERATORS.3] i = [2.3] julia> for i in subsets(1:4.2] i = [3] i = [1.3] i = [2.takenth — Method.takenth Iterators.takestrict — Method. n) Iterate through every nth element of xs.TAKENTH 339 i = [2] i = [1. julia> collect(takenth(5:15.3] i = [1.2] i = [1.4] source 27.takestrict Iterators. an iterator that generates at most the first n elements of xs.4] i = [2.3)) 3-element Array{Int64. takenth(xs.1}: 7 10 13 source 27.3] i = [1. n::Int) Like take().2.13 Iterators.13.14 Iterators.4] i = [3. 2) @show i end i = [1. .

ITERATORS julia> a = :1:2:11 1:2:11 julia> collect(takestrict(a. 3)) 3-element Array{Int64.340 CHAPTER 27.1}: 1 3 5 source .

poly Polynomials. . poly(r) Construct a polynomial from its roots.2 Polynomials... where ei is the ith eigenvalue of r. the highest exponent in the polynomial that has a nonzero coefficient.Chapter 28 Polynomials 28. Compare this to the Poly type constructor.coeffs Polynomials. i.coeffs — Method. If r is a matrix. If r is a vector.e.1 Polynomials. the constructed polynomial is (x − e1 ) · · · (x − en ). source 28. which constructs a polynomial from its coefficients. source 28. the constructed polynomial is (x − r1 )(x − r2 ) · · · (x − rn ).poly — Method.3 Polynomials. coeffs(p::Poly) Return the coefficient vector [a 0..degree Polynomials. degree(p::Poly) Return the degree of the polynomial p. Examples 341 . a 1. a n] of a polynomial p.degree — Method.

polyder — Method.polyint — Method.6 Polynomials. -1]). 2) Poly(-0. n=length(x)-1. 3]) The polynomial (x . y. 3.2x) julia¿ polyder(Poly([1.0x2) source 28. Examples [] julia¿ xs = linspace(0. 0.polyint Polynomials. xs). 3.polyfit — Function. 5).polyder Polynomials. julia¿ polyfit(xs.5.37228)(x + 0. sym=:x) Fit a polynomial of degree n through the points specified by x and y.242031920509868x . polyder(p::Poly.5. When n=length(x)-1 (the de- fault). 2) Poly(-2) source 28. polyint(p::Poly.37228) Poly(- 1. ys.39535103925413095x2) source 28.3) Poly(-6 + 11x - 6x2+x3) julia¿ poly([1 2.1)(x . 3 4]) The polynomial (x . -1])) Poly(3 .0. -1]).0x + 1. The optional fourth argument can be used to specify the symbol for the returned polynomial.9999999999999998 .6666666666666667 source . polyfit(x. Examples [] julia¿ polyder(Poly([1. the interpolating polynomial is returned. a::Number. 1) 0.5 Polynomials.342 CHAPTER 28. pi.polyfit Polynomials.b]. b::Number) Compute the definite integral of the polynomial p over the interval [a. using least squares fit.004902082150108854 + 1. 0. where n <= length(x) . Examples [] julia¿ polyint(Poly([1. julia¿ ys = map(sin.4 Polynomials.2)(x . 2.1. k=1) Compute the kth derivative of the polynomial p. POLYNOMIALS [] julia¿ poly([1.

-1]) Poly(1 .polyval — Method. :y).3]. POLYNOMIALS. 2) Poly(2.0.3333333333333333x3) julia¿ polyint(Poly([1. :y)) 1 + 2*y + 3*y^2 julia> printpoly(STDOUT.3]. printpoly(io::IO. using this function.POLYINT 343 28.7 Polynomials.polyval Polynomials. mimetype = MIME"text/plain"(). -1]). the terms are in order of ascending powers. k::Number=0) Integrate the polynomial p term by term. “text/latex”. Poly([1. Examples [] julia¿ p = Poly([1. 0. x::Number) Evaluate the polynomial p at x using Horner’s method. By default.28.7. 0.0 + 1. Poly([1. descending_powers=false) Print a human-readable representation of the polynomial p to io.8 Polynomials.3333333333333333x3) source 28.printpoly Polynomials. descending_powers=true) 3*y^2 + 2*y + 1 source .2. p::Poly. 1) 0 julia¿ p(1) 0 source 28.polyint Polynomials. Examples [] julia¿ polyint(Poly([1. polyint(p::Poly.0x . optionally adding a constant term k.x2) julia¿ polyval(p. and “text/html” are supported.9 Polynomials.polyint — Method. The order of the resulting polynomial is one higher than the order of p.printpoly — Method. The MIME types “text/plain” (default).2. 0. Examples julia> printpoly(STDOUT. matching the order in coeffs(p). Poly objects are callable. polyval(p::Poly.0. -1])) Poly(1.0x . specifying descending powers=true reverses the order.

0f0x) source .0 source 28. its variable.0y) julia¿ variable() Poly(1.1}: 0. The returned roots may be real or complex.1}: 0. with multiplicity.0x) julia¿ variable(Float32. :x)) Poly(x) julia¿ variable(:y) Poly(1. POLYNOMIALS 28.0-1. as a Poly object.11 Polynomials.roots Polynomials.] var) variable() Return the indeterminate of a polynomial. 0.0im 0.0+1.10 Polynomials.variable Polynomials. i.1}: 4. roots(p::Poly) Return the roots (zeros) of p.0 1.0 3.0 2. -1])) 2-element Array{Float64.1}: -1. 2].344 CHAPTER 28.4])) 4-element Array{Float64.0im julia¿ roots(Poly([0. 1])) 2-element Array{Float64.roots — Method.2. :x). 1])) 2-element Array{Complex{Float64}. 0. 0.0 0. Examples [] julia¿ variable(Poly([1. this is equivalent to variable(Float64.3.0 1.0 julia¿ roots(poly([1. variable(p::Poly) variable([T::Type. The number of roots re- turned is equal to the order of p.e. When passed no arguments. Examples [] julia¿ roots(Poly([1.variable — Method. :x) Poly(1.0 julia¿ roots(Poly([1.

source 29. metric) 345 .hex — Method.colordiff — Method. Optionally. the lightness l may also be specified.1 Base.2 Colors. colordiff(a.hex Base.Chapter 29 Colors 29. b) colordiff(a. l) Calculates the most saturated color for any given hue h by finding the cor- responding corner in LCHuv space. or a transparent paint as an ARGB hex quadruplet.colordiff Colors. MSC(h) MSC(h. source 29.3 Colors. b. hex(c) Print a color as a RGB hex triple.MSC — Method.MSC Colors.

colormatch(wavelength) colormatch(matchingfunction.6 Colors. mid. Choices include CIE1931 CMF (the default. you can specify the number of colors N (default 100). M. source 29. source 29. [N.4 Colors. DE AB. Oranges.5) and the possibility to switch to log scaling with logscale (default false).. DE DIN99o.colormatch Colors.]) Returns a predefined sequential or diverging colormap computed using the algorithm by Wijffelaars. Diverging colormap choices are RdBu. Purples. • wavelen: Wavelength of stimulus in nanometers.deuteranopic — Method.5 Colors. CIE1931JV CMF (Judd- Vos adjustment to CIE1931 CMF). a metric may be supplied. (2008).deuteranopic Colors. DE CMC.colormap — Function. Args: • matchingfunction (optional): a type used to specify the matching func- tion. DE BFD. the CIE 1931 2 match- ing function). CIE1931J CMF (Judd adjustment to CIE1931 CMF). wavelength) Evaluate the CIE standard observer color match function. kvs. chosen among DE 2000 (the default). logscale. et al. COLORS Compute an approximate measure of the perceptual difference between col- ors a and b. Keyword arguments include the position of the middle point mid (default 0. Greens. Optionally. Grays..colormatch — Method. DE JPC79..colormap Colors.346 CHAPTER 29. DE DIN99. colormap(cname. Optionally. source 29. and Reds. . DE DIN99d. DE 94. CIE1964 CMF (the CIE 1964 10 color matching function). Returns: XYZ value of perceived color. Sequential colormaps cname choices are Blues.

De- fault is the identity. distinguishable_colors(n.7 Colors. in the range 0 (no loss) to 1 (complete loss).29.340. the optional argument p is the fraction of photopigment loss.protanopic — Method. source 29. • lchoices: Possible lightness values (default linspace(0. other choices include deuteranopic to simulate color- blindness. and lightness values (in LCHab space). [transform. COLORS.15)) • hchoices: Possible hue values (default linspace(0. Keyword arguments: • transform: Transform applied to colors before measuring distance.100.DISTINGUISHABLE COLORS 347 deuteranopic(c) deuteranopic(c. source 29.100.protanopic Colors.distinguishable colors Colors. Default is Vector{RGB{N0f8}}(0). Args: • n: Number of colors to generate. cchoices. p) Convert a color to simulate deuteranopic color deficiency (lack of the middle- wavelength photopigment). c is the input color. protanopic(c) protanopic(c. chroma. source . Given seed color(s). p) Convert a color to simulate protanopic color deficiency (lack of the long- wavelength photopigment). See the description of protanopic for detail about the arguments. of the type specified in seed.15)) • cchoices: Possible chroma values (default linspace(0. and a set of possible hue. [seed].7.distinguishable colors — Method.8 Colors. • seed: Initial color(s) included in the palette. hchoices]) Generate n maximally distinguishable colors.20)) Returns: A Vector of colors of length n. lchoices. it repeatedly chooses the next color as the one that maximizes the minimum pairwise distance to any of the colors already in the palette. This uses a greedy brute-force approach to choose n colors that are maxi- mally distinguishable.

source . c2) Returns the color w1*c1 + (1-w1)*c2 that is the weighted mean of c1 and c2. source 29.weighted color mean Colors.11 Colors. p) Convert a color to simulate tritanopic color deficiency (lack of the short- wavelength photogiment).10 Colors. COLORS 29.whitebalance — Method. where c1 has a weight 0 w1 1.weighted color mean — Method.9 Colors. Args: • c: An observed color.g. c1. Returns: A whitebalanced color. ref_white) Whitebalance a color. src_white.348 CHAPTER 29. Input a source (adopted) and destination (reference) white.tritanopic — Method. tritanopic(c) tritanopic(c. • src white: Adopted or source white corresponding to c • ref white: Reference or destination white. source 29.whitebalance Colors. you might do something like whitebalance(c. See protanopic for more detail about the arguments. whitebalance(c. weighted_color_mean(w1. WP D65).tritanopic Colors. WP F2.. if you have a photo taken under florencent lighting that you then want to appear correct under regular sunlight. E.

For ex- ample: add_format(format"PNG".0x00]).2 FileIO. (UInt8[0x4d. and format-identifiers are case-sensitive.0x0a]. source 30.0x00.Chapter 30 FileIO 30.0x49. source 30.info — Method. add loader(fmt.3 FileIO. ". magic numbers. magic.0x0d.add format FileIO. [0x89. :Package) triggers using Package before loading format fmt source 349 .0x50.0x4e.tif add_format(format"PNG".png") add_format(format"NRRD".0x1a.add loader FileIO. UInt8[0x49.1 Base.0x4d.nrrd".0x0a.0x2a. "NRRD".info Base. info(fmt) returns the magic bytes/extension information for DataFormat fmt.tiff".0x47.add format — Method. [". [". ". extention) registers a new DataFormat.0x2b]. add format(fmt.".add loader — Function.nhdr"]) Note that extensions.

7 FileIO. filename(file) returns the filename associated with File file.file extension — Method. file extension(file) returns the file extension associated with File file.file extension FileIO.4 FileIO. file extension(file) returns a nullable-string for the file extension asso- ciated with Stream stream. del format(fmt::DataFormat) deletes fmt from the format registry.add saver — Function.6 FileIO. add saver(fmt. source 30.del format FileIO. source 30.9 FileIO.add saver FileIO.filename FileIO. filename(stream) returns a nullable-string of the filename associated with Stream stream.8 FileIO. source 30.5 FileIO. source 30.del format — Method.filename — Method. source . :Package) triggers using Package before saving format fmt source 30.file extension — Method.file extension FileIO.filename FileIO.filename — Method. FILEIO 30.350 CHAPTER 30.

trying to infer the format from filename and/or magic bytes in the file. • save(filename. In this case. • load(f. trying to infer the format from filename.query FileIO. • load(File(format"PNG".11 FileIO.. query(filename) returns a File object with information about the format inferred from the file’s extension and/or magic bytes. source 30.save — Method.load FileIO. source 30. • load(strm) loads from an IOStream or similar object..LOAD 351 30.10. .magic FileIO. the magic bytes are essential.magic — Method. and bypasses inference.13 FileIO.query — Method.10 FileIO. • load(filename) loads the contents of a formatted file.12 FileIO..filename)) specifies the format directly.) saves the contents of a formatted file. options. data. FILEIO.. magic(fmt) returns the magic bytes of format fmt source 30. [filename]) returns a Stream object with information about the format inferred from the magic bytes.load — Method.) passes keyword arguments on to the loader.query FileIO.14 FileIO.30.save FileIO.query — Method. source 30. query(io.

options.16 FileIO.352 CHAPTER 30. • save(f. data.) specifies the format directly. source . skipmagic(s) sets the position of Stream s to be just after the magic bytes.. For a plain IO object.stream FileIO.17 FileIO. source 30.15 FileIO.unknown FileIO. stream(s) returns the stream associated with Stream s source 30.. you can use skipmagic(io.) passes keyword arguments on to the saver...skipmagic FileIO. FILEIO • save(Stream(format"PNG". source 30.skipmagic — Method. unknown(f) returns true if the format of f is unknown. fmt). and bypasses inference.io).unknown — Method.stream — Method... data..

checkbox(value=false. and/or the (Reactive. choices can be a vector of options.dropdown Interact. typ.checkbox — Method. the value emitted when then button is clicked. label="". Optionally specify the label.jl) signal coupled to this button. source 31. value. Optional provide a label for this widget and/or the (Reactive. signal) Create a push button.1 Interact. the typ of elements 353 .button Interact.button — Method. label="". value=nothing. button(label. signal) Provide a checkbox with the specified starting (boolean) value.jl) signal coupled to this widget. dropdown(choices. icons.2 Interact.dropdown — Method.checkbox Interact. source 31. Option- ally specify the starting value (defaults to the first choice).Chapter 31 Interact 31.3 Interact. tooltips. signal) Create a “dropdown” widget.

use syncnearest=false. To disable this behaviour.354 CHAPTER 31.4 Interact. radiobuttons: see the help for dropdown source 31.radiobuttons — Method.5 Interact. source 31. it will update to the nearest value from the range/choices provided.set! Interact. fld::Symbol. so that the widget state will only update if an exact match for signal value is found in the range/choice. and its signal is updated.selection slider Interact. then updates to that signal will be reflected in widget instances/views. If val is a Signal.jl) signal coupled to this widget. use f = dropdown(["turn red"=>colorize_red. signal(f)) source 31.set! — Method. provide tooltips. INTERACT in choices. set!(w::Widget.6 Interact.radiobuttons Interact. val is also push!ed to signal(w) source . selection: see the help for dropdown source 31. val) Set the value of a widget property and update all displayed instances of the widget.selection slider — Method. "turn green"=>colorize_green]) map(g->g(image). If fld is :value. and/or specify the (Re- active. Examples a = dropdown(["one". supply custom icons. "two".selection — Method. selection slider: see the help for dropdown If the slider has numeric (<:Real) values. "three"]) To link a callback to the dropdown.7 Interact.selection Interact.

slider — Method.togglebutton Interact.8 Interact. and/or provide the (Reactive.textbox — Method. specify the allowed range (e. you can constrain the type with typ. provide the (Reactive.31..jl) signal coupled to this text box. the initial state (value=false is off. -10. if you don’t want to provide an initial value. signal) Create a toggle button. Optionally specify the starting value (defaults to the median of range). textarea(value="".jl) signal coupled to this slider.togglebutton — Method.11 Interact.textbox Interact. value. value=false. source 31.slider Interact. source . label="". label="". signal. Optionally specify the label.textarea Interact.SLIDER 355 31.jl) signal coupled to this button. typ=typeof(value). and/or specify a string label for the widget. Optionally provide a label and/or the (Reactive. textbox(value="". togglebutton(label="".jl) signal associated with this widget. source 31. and/or provide the (Reactive. range=nothing. INTERACT.textarea — Method.0) for numeric entries. source 31. The signal updates when you type. slider(range. value=true is on).9 Interact.g. value is the starting value. label="". readout=true.0:10. Optionally pro- vide a label.8. signal) Create a box for entering text.10 Interact. continuous_update=true) Create a slider widget with the specified range. signal) Creates an extended text-entry area.

) Shorthand for selection slider(args. kwargs.vselection slider Interact.. vslider(args..vselection slider — Method....) source 31..togglebuttons — Method. vselection slider(args.. orientation="vertical".vslider — Method. orientation="vertical".) source .14 Interact.356 CHAPTER 31. kwargs.. kwargs..13 Interact.. INTERACT 31....12 Interact... togglebuttons: see the help for dropdown source 31... kwargs..togglebuttons Interact.) Shorthand for slider(args..vslider Interact..

FFTW.1 Base. Most efficient if the size of A along the transformed dimensions is a product of small primes.FFTW.dct! — Function. The optional dims argu- ment specifies an iterable subset of dimensions (e.idct — Function. range. using the unitary normalization of the DCT.dct Base.DFT. dct(A [.FFTW.dct — Function. source 32.FFTW. idct(A [.g.DFT.2 Base. dims]) 357 . See also plan dct for even greater efficiency.idct Base.FFTW. dims]) Performs a multidimensional type-II discrete cosine transform (DCT) of the array A.DFT.3 Base. see nextprod. dct!(A [.Chapter 32 FFTW 32.dct! Base.DFT. source 32. except that it operates in-place on A.FFTW.DFT. an integer. tuple.DFT. which must be an array of real or complex floating-point values. dims]) Same as dct!. or array) to transform along.

FFTW. plan_dct!(A [. dims [.DFT.idct! — Function. Most efficient if the size of A along the transformed dimensions is a product of small primes.4 Base.plan dct Base. timelimit]]]) Same as plan dct.plan dct! — Function.plan dct! Base. The first two argu- ments have the same meaning as for idct.plan idct Base. similar to plan fft except producing a function that computes idct. timelimit]]]) Pre-plan an optimized inverse discrete cosine transform (DCT). flags [. flags [. plan_idct(A [.FFTW. plan_dct(A [.DFT.plan idct — Function. source 32. dims [. similar to plan fft except producing a function that computes dct.FFTW. The optional dims argument specifies an iterable subset of dimensions (e. but operates in-place on A. source 32.FFTW.FFTW. FFTW Computes the multidimensional inverse discrete cosine transform (DCT) of the array A (technically.DFT.FFTW. dims]) Same as idct!.DFT. dims [.plan dct — Function.DFT.FFTW.7 Base. flags [. or array) to transform along. The first two arguments have the same meaning as for dct.DFT. but operates in-place on A. tuple.358 CHAPTER 32. timelimit]]]) Pre-plan an optimized discrete cosine transform (DCT).6 Base. range.DFT. source 32.5 Base. source 32. see nextprod.FFTW.DFT. idct!(A [. a type-III DCT with the unitary normalization).g. source . an inte- ger. See also plan idct for even greater efficiency.idct! Base.

DFT. kind [.FFTW. timelimit]]]) Pre-plan an optimized r2r transform.fftw. BASE.plan idct! Base.DFT. kind [. but corresponds to r2r!. respec- tively.RODFT11). or a discrete Hartley transform (FFTW. plan_r2r(A. plan_idct!(A [.REDFT10.DFT.DFT. but operates in-place on A. or FFTW.r2r Base.DFT. kind[end] is used for any unspecified dimensions.9 Base.DFT.FFTW. FFTW.plan r2r Base. dims [. .HC2R).RODFT00. source 32. similar to plan fft except that the transforms (and the first three arguments) correspond to r2r and r2r!.plan idct! — Function. dims [. flags [. The kind argument may be an array or tuple in order to specify different transform types along the different dimen- sions of A.r2r — Function.PLAN IDCT! 359 32. kind [.DFT.10 Base. dims [.RODFT10.FFTW.R2HC and its inverse FFTW.org/doc.FFTW. flags [. or FFTW. dims]) Performs a multidimensional real-input/real-output (r2r) transform of type kind of the array A. kind specifies either a discrete cosine transform of various types (FFTW. a discrete sine transform of various types (FFTW. source 32.FFTW.8. FFTW. source 32.RODFT01.plan r2r! — Function.FFTW. a real-input DFT with halfcomplex-format output (FFTW.8 Base. timelimit]]]) Similar to plan fft.REDFT01. timelimit]]]) Same as plan idct. as defined in the FFTW manual. FFTW.DHT).FFTW. See the FFTW manual for precise definitions of these transform types.11 Base.plan r2r — Function.FFTW.REDFT11).DFT.plan r2r! Base. at http://www.FFTW.DFT. r2r(A.REDFT00. flags [.32. FFTW. plan_r2r!(A.

or array) to transform along.DFT.12 Base. kind[i] is then the trans- form type for dims[i]. with kind[end] being used for i > length(kind). FFTW The optional dims argument specifies an iterable subset of dimensions (e.FFTW.g. kind [.360 CHAPTER 32. an integer.r2r! — Function. source . tuple. source 32.r2r! Base.DFT. range.FFTW. dims]) Same as r2r. r2r!(A. See also plan r2r to pre-plan optimized r2r transforms. but operates in-place on A. which must be an array of real or complex floating-point numbers.

. then only that axis vector is returned. axes(A. ::Type{Axis}) -> Int Given an AxisArray and an Axis. those that would be produced by AxisArray(A). Note that when extracting a single axis vector.axes AxisArrays. ax::Axis) -> Axis axes(A::AxisArray. Axis{1})) is type-stable and will perform better than axes(A)[1]. source 33.. 361 . i.1 AxisArrays..2 AxisArrays.e. axes returns the default axes. axes(A::AxisArray) -> (Axis.3 AxisArrays.axes — Method. source 33.axisnames — Method.axisnames AxisArrays.axisdim AxisArrays.Chapter 33 AxisArrays 33. return the integer dimension of the Axis within the array. For an AbstractArray without Axis information. dim::Int) -> Axis Returns the tuple of axis vectors for an AxisArray.) axes(A::AxisArray. axisdim(::AxisArray.axisdim — Method. ::Axis) -> Int axisdim(::AxisArray. If an specific Axis is specified.

..) Returns the axis names of an AxisArray or list of Axises as a tuple of Sym- bols.: AxisArrays to be collapsed together... source 33. • ::Type{NewArrayType<:AbstractArray{ ..axisvalues — Method....4 AxisArrays.) -> AxisArray collapse(::Type{Val{N}}.) -> (AbstractVector. The remaining axes are collapsed. As::AxisArray.. All additional axes in any of the arrays are collapsed into a single additional axis of type Axis{:collapsed. at the same dimension.... All N axes must be common to each input array. Values from 0 up to the minimum number of dimensions across all input arrays are allowed.}}) -> (Symbol. ::Type{NewArrayType}.. • As::AxisArray. Arguments • ::Type{Val{N}}: the greatest common dimension to share between all input arrays.. source 33. labels::Tuple.) axisnames(::Type{Axis{.) -> Axis Collapses AxisArrays with N equal leading axes into a single AxisArray. AXISARRAYS axisnames(A::AxisArray) -> (Symbol....) -> (Symbol. ::Type{NewArrayType}.) axisvalues(ax::Axis..collapse AxisArrays.. axisvalues(A::AxisArray) -> (AbstractVector.) axisnames(ax::Axis.}}.5 AxisArrays. As::AxisArray.. labels::Tuple... As::AxisArray.collapse — Method.) Returns the axis values of an AxisArray or list of Axises as a tuple of vectors. Defaults to 1:length(As).. As::AxisArray.) -> AxisArray collapse(::Type{Val{N}}...) -> AxisArray collapse(::Type{Val{N}}.... collapse(::Type{Val{N}}.362 CHAPTER 33. ..) axisnames(::Type{AxisArray{. N+1}}: (optional) the desired underlying array type for the returned AxisArray. • labels::Tuple: (optional) an index for each array in As used as the leading element in the index tuples in the :collapsed axis. CategoricalVector{Tuple}}...axisvalues AxisArrays..) -> (Symbol.

2}: 0..609344 0.43656 0.994697 0.01):Day(1):Date(2016.900526 0.10)). Tuple{Symbol. (:size.885014 0.000922581 0.} with axes: :time.COLLAPSE 363 Examples julia> price_data = AxisArray(rand(10).761714 0.148822 0.455337 0.729311 0.1}: 0.5. a 10-element Array{Float64.72221 0.95104 0.650277 0. :area). a 102 Array{Float64.65954 0.994697 0.418562 0.2.885014 0.456992 0.01.455337 0. price_data. A 2-dimensional AxisArray{Float64. :volume And data. AXISARRAYS..2}: 0. (:size.374623 0.2.840304 0.).522077 0.393801 0... a 103 Array{Float64.. Axis{:time}(Date(2016.43656 0..456992 0.000922581 0.01.2).159434 0.01.1.313256 0.374623 0.344521 0.10))) 1-dimensional AxisArray{Float64..159434 0.72221 0. Axis{:time}(Date(2016.320953 0. (:price.513845 julia> collapsed = collapse(Val{1}.900526 0.135061 0.65954 0..320953 0.522077 0.688773 0.313256 0.418562 0.N} where N}[(:price. 2016-01-01:1 day:2016-01-10 :measure.761714 .01.} with axes: :time.449128 0.921854 0.260207 julia> size_data = AxisArray(rand(10.840304 0. size_data) 2-dimensional AxisArray{Float64. 2016-01-01:1 day:2016-01-10 And data. :size).449128 0.344521 0.Vararg{Symbol. Symbol[:area.921854 0.729311 0.} with axes: :time.01):Day(1):Date(2016.609344 0. :volume] And data. 2016-01-01:1 day:2016-01-10 :collapsed.33.148822 0.95104 0..

AXISARRAYS 0.513845 julia> collapsed[Axis{:collapsed}(:size)] == size_data true source .688773 0.650277 0.393801 0.260207 0.135061 0.364 CHAPTER 33.

1 Base. a maximum number of function evaluations maxevals (defaults to 10^7). More generally. an absolute error tolerance abstol (defaults to 0).b.. and optionally over additional intervals b to c and so on. a. there are many different algorithms 365 .. and the order of the integration rule (defaults to 7).quadgk Base. and a norm (i. !!! note It is advisable to increase the integration order in rough proportion to the precision. !!! note Only one-dimensional integrals are provided by this function. abstol=0.. -.e. then the integration will be performed in BigFloat precision as well. If the endpoints are BigFloat. reltol*norm(I)) will hold. for smooth integrands. or matrix type. Returns a pair (I. For multi-dimensional integration (cubature). multiplication by real values. reltol=sqrt(eps).c. Keyword options include a relative error tolerance reltol (defaults to sqrt(eps) in the precision of the endpoints).E) of the estimated integral I and an estimated up- per bound on the absolute error E.Chapter 34 QuadGK 34. If maxevals is not exceeded then E <= max(abstol. or in fact any type supporting +. The integrand f(x) can return any numeric scalar. norm=vecnorm) Numerically integrate the function f(x) from a to b. Alternatively. the precision is set by the precision of the integration end- points (promoted to floating-point types). maxevals=10^7. (Note that it is useful to specify a positive abstol in cases where norm(I) may be zero. any normed vector space).) The endpoints a et cetera can also be complex (in which case the integral is performed over straight-line segments in the complex plane). vector. order=7. a different norm can be specified by passing a norm-like function as the norm keyword argument (which defaults to vecnorm).quadgk — Method. quadgk(f..

so if your function has a known discontinuity or other singularity.7 and you want to integrate from 0 to 1. source 34. simplified for a=0. gauss([T. 1). Arbitrary precision (BigFloat) is also supported.) source 34.* f.7. a log(x) or 1/sqrt(x) singularity).366 CHAPTER 34. Uses the method described in Trefethen & Bau.gauss QuadGK. for integrating on [-1.3 QuadGK. it is best to subdivide your interval to put the singularity at an endpoint. i. to find the N-point Gaussian quadrature in O(N) operations. 0. w) of N quadrature points x[i] and weights w[i] to integrate functions on the interval (-1.e. you should use quadgk(f. sum(w . The integrand is never evaluated exactly at the endpoints of the intervals.kronrod QuadGK. These quadrature rules work best for smooth functions within each interval.0. the starting and/or ending points may be infinite.] N) Return a pair (x.(x)) approximates the integral.1) to subdivide the interval at the point of discontinuity.gauss — Method. The algorithm is an adaptive Gauss-Kronrod integration technique: the in- tegral in each interval is estimated using a Kronrod rule (2*order+1 points) and the error is estimated using an embedded Gauss rule (order points). kronrod([T. defaulting to Float64. if f has a discontinuity at x=0.kronrod — Method. appendix A. Since the rule is symmetric. so it is possible to integrate functions that diverge at the endpoints as long as the singularity is integrable (for example. See the Julia external-package listing for available algorithms for multidimensional integration or other specialized tasks (such as integrals of highly oscillatory or singular functions).1]. (A coordinate transformation is performed internally to map the infinite interval to a finite one. QUADGK (often much better than simple nested 1d integrals) and the optimal choice tends to be very problem-dependent. The inter- val with the largest error is then subdivided into two intervals and the process is repeated until the desired error tolerance is achieved. Numerical Linear Algebra.] n) Compute 2n+1 Kronrod points x and weights w based on the description in Laurie (1997). For example. The .2 QuadGK. T is an optional parameter specifying the floating-point type. this only returns the n+1 points with x <= 0. For real-valued endpoints.

KRONROD 367 function Also computes the embedded n-point Gauss quadrature weights gw (again for x <= 0).* w[1:end-1]) + fx * w[end] if isodd(n) E = abs(sum(fx[2:2:end] .(x) . Returns (x.w.34. QUADGK.+ f. corresponding to the points x[2:2:end]. the estimated integral I and error E can be computed for an integrand f(x) as follows: x.I) end source . wg = kronrod(n) fx = f(x[end]) # f(0) x = x[1:end-1] # the x < 0 Kronrod points fx = f. defaulting to Float64. Given these points and weights. T is an optional parameter specifying the floating-point type.I) else E = abs(sum(fx[2:2:end] .((-). Arbitrary precision (BigFloat) is also supported.wg) in O(n) operations.* wg[1:end]).(x)) # f(x < 0) + f(x > 0) I = sum(fx . w.* wg[1:end-1]) + fx*wg[end] .3.

Chapter 35 JavaCall 35. isnull(obj::JavaMetaClass) Checks if the passed JavaMetaClass is null or not Args • obj: The object of type JavaMetaClass Returns true if the passed object is null else false source 35.isnull — Method.2 Base.1 Base.isnull — Method. isnull(obj::JavaObject) Checks if the passed JavaObject is null or not Args • obj: The object of type JavaObject Returns true if the passed object is null else false source 368 .isnull Base.isnull Base.

getname — Method.forName(name) in Java) Args • name: The name of a class to instantiate Returns JavaObject Instance of Class<name> source 35.5 JavaCall. JAVACALL.classforname — Method.getname JavaCall.classforname JavaCall.getname JavaCall.getname — Method.4 JavaCall.CLASSFORNAME 369 35.35. getname(method::JMethod) Returns the fully qualified name of the java method Args • cls: The JClass method Returns The fully qualified name of the method source .3. getname(cls::JClass) Returns the fully qualified name of the java class Args • cls: The JClass object Returns The fully qualified name of the java class source 35. classforname(name::String) Create an instance of Class<name> (same as Class.3 JavaCall.

6 JavaCall.370 CHAPTER 35.listmethods JavaCall.8 JavaCall. getreturntype(method::JMethod) Returns the return type of the java method Args • method: The java method object Returns Returns the type of the return object as a JClass source 35. JAVACALL 35.7 JavaCall. getparametertypes(method::JMethod) Returns the parameter types of the java method Args • method: The java method object Returns Vector the parametertypes source 35.listmethods — Method.getparametertypes — Method.getparametertypes JavaCall.getreturntype — Method.getreturntype JavaCall. listmethods(obj::JavaObject) Lists the methods that are available on the java object passed Args • obj: The java object Returns List of methods source .

The methods are filtered based on the name passed Args • obj: The java object • name: The filter (e.10 JavaCall. Given a JavaObject{T} narrows down T to a real class of the underlying ob- ject. listmethods(obj::JavaObject.9.Object} pointing to java.lang.String} source . JAVACALL.LISTMETHODS 371 35.narrow JavaCall. JavaObject{:java. method name) Returns List of methods available on the java object and matching the name passed source 35.listmethods JavaCall.lang.String will be narrowed down to JavaObject{:java.listmethods — Method. For example.9 JavaCall.narrow — Method.35.lang. name::AbstractString) Lists the methods that are available on the java object passed.g.

for example: A = rand(Blocks(100. 1000) compute(A+A’) must not result in computation of A twice.Chapter 36 Dagger 36. (1:80)) source 36.3 Dagger.alignfirst — Method. A DArray object may contain a thunk in it. It is important that the tasks generated for the same DArray have the same identity.compute Dagger.cached stage — Method.100). source 36. A memoized version of stage. For example. alignfirst(ArrayDomain(11:25.1 Dagger.alignfirst Dagger. 21:100)) # => ArrayDomain((1:15).2 Dagger. alignfirst(a) Make a subdomain a standalone domain. source 372 .compute — Method.cached stage Dagger. Float64. 1000. in which case we first turn it into a Thunk object and then compute it.

source .7 Dagger. DAGGER. load(ctx. source 36.domain Dagger. Thunk} from a file.domain Dagger. If no domain method is defined on an object. domain(x::T) Returns metadata about x.domain — Function. A UnitDomain is indivisible.load — Method. source 36.creates the DAG.36.load Dagger. This metadata will be in the domain field of a Chunk object when an object of type T is created as the result of evaluating a Thunk. source 36.8 Dagger.4.domain — Method. file_path) Load an Union{Chunk.domain — Method.4 Dagger.COMPUTE 373 36.5 Dagger. then we use the UnitDomain on it.6 Dagger.compute — Method. Compute a Thunk . assigns ranks to nodes for tie breaking and runs the scheduler. The domain of an array is a ArrayDomain source 36.compute Dagger.domain Dagger.

source . Thunk}.save — Method. chunk::Union{Chunk. special case distmem writing .11 Dagger.load — Method. t::Type. val) Save a value into the IO buffer.save Dagger.save — Method. source 36.374 CHAPTER 36. ::Type{Chunk}.10 Dagger.save Dagger. domain) will load the object given its domain source 36.write to disk on the process with the chunk.load Dagger. save(ctx. In the case of arrays and sparse matrices.12 Dagger. fpath.save Dagger. this will save it in a memory-mappable way. the file path is required for creating a FileReader object source 36.save — Method. load(io::IO. save(io::IO. file_path::AbsractString) Save a chunk to a file at file path. io) Load a Chunk object from a file. DAGGER 36. load(ctx.9 Dagger.

suppose you have a core BSpline object defined on a 5x7x4 grid. 375 .4.Chapter 37 Interpolations 37.20)).eachvalue — Method. linspace(1.extrapolate Interpolations. For example. eachvalue(sitp) constructs an iterator for efficiently visiting each grid point of a ScaledInterpolation object in which a small grid is being “scaled up” to a larger one. linspace(1.120). and you are scaling it to a 100x120x20 grid (via linspace(1.1 Interpolations.100).eachvalue Interpolations.7. sitp) for I in CartesianRange(size(dest)) dest[I] = sitp[I] end dest end source 37. You can per- form interpolation at each of these grid points via function foo!(dest.extrapolate — Method.5. sitp) i = 0 for s in eachvalue(sitp) dest[i+=1] = s end dest end which should be more efficient than function bar!(dest.2 Interpolations.

but use constant etrapolation if it is too large.4 Interpolations.. Flat()) will extrapolate linearly in the first di- mension if the index is too small. extrapolate(itp.x2.scale Interpolations.. For example. INTERPOLATIONS extrapolate(itp. you can specify different extrapolation behavior in different direc- tion.3 Interpolations. scale(itp.throws a BoundsError for out-of-bounds indices • Flat . taking the closest in-bounds value • Linear .extrapolate — Method. source 37. Flat()) will use linear extrapolation in the first dimension.. . For every NoInterp dimension of the interpolation object. The parameters xs etc must be either ranges or linspaces. scheme) adds extrapolation behavior to an interpola- tion object.Flat()). xs. by wrapping the interpolation object and transforming the indices from the provided axes onto unit ranges upon indexing.periodic extrapolation (indices must support mod) You can also combine schemes in tuples. the scheme (Linear(). according to the provided scheme..) scales an existing interpolation object to allow for indexing using other coordinate axes than unit ranges.376 CHAPTER 37. ys.extrapolate Interpolations..linear extrapolation (the wrapped interpolation object must sup- port gradient) • Reflect .] are out-of- bounds. and always use constant extrapolation in the second dimension. ((Linear().for constant extrapolation.scale — Method.reflecting extrapolation (indices must support mod) • Periodic . fillvalue) creates an extrapolation object that re- turns the fillvalue any time the indexes in itp[x1. source . d). and there must be one coordinate range/linspace for each dimension of the interpolation object. source 37. the range must be exactly 1:size(itp. The scheme can take any of these values: • Throw . and constant in the second. Finally.

false} and this type will be printed in the summary. ". showarg(stream::IO.Tuple{Colon.UnitRange{Int64}}.Chapter 38 ShowItLikeYouBuildIt 38. parent(v)) print(io.showarg ShowItLikeYouBuildIt.indexes.Int64.1 ShowItLikeYouBuildIt. ’)’) end 377 . ". However.showarg — Method. you can specialize this function for specific types to customize printing. The fallback definition is to print x as ::$(typeof(x)).2.3}. join(v. "view(") showarg(io. ". 2:5) you could define function ShowItLikeYouBuildIt. v::SubArray) print(io. Colon().3}. x) Show x as if it were an argument to a function. 3. ")) print(io. Example A SubArray created as view(a. representing argu- ment x in terms of its type.Array{Float64. 3. 2:5). This function is used in the printing of “type summaries” in terms of sequences of function calls on objects. has type SubArray{Float64. To change the printing of this object to view(::Array{Float64. :.showarg(io::IO. where a is a 3-dimensional Float64 array.

More generally.Tuple{Colon.false} The optional argument cthresh is a “complexity threshold”. summary_build(A::AbstractArray.summary build ShowItLikeYouBuildIt.2 ShowItLikeYouBuildIt. 3. then the summary of a SubArray might look like this: 34 view(::Array{Float64.Int64. This function should never be called directly. objects with type descriptions that are less complex than the specified threshold will be printed using the traditional type-based summary. along with information about A’s size or indices and element type. 3. The default value is n+1. This printing might be activated any time v is a field in some other container. The complexity is calculated with type complexity.3}. source 38. See also: summary build. you might define Base. if you want to change the summary of SubArray. [cthresh]) Return a string representing A in terms of the sequence of function calls that might be used to create A. type complexity.3} is the fallback behavior. 2:5) with element type Float64 instead of this: 34 SubArray{Float64. or if you specialize Base. assuming no specialized method for Array has been defined. source .summary build — Function. You can choose a cthresh of 0 if you want to ensure that your showarg version is always used. SHOWITLIKEYOUBUILDIT Note that we’re calling showarg recursively for the parent array type. Colon(). For example.2.summary for specific AbstractArray subtypes.summary(v::SubArray) = summary_build(v) This function goes hand-in-hand with showarg. where n is the number of parameters in typeof(A). Print- ing the parent as ::Array{Float64.summary for SubArray to call summary build. See also: showarg. 2:5) where <a> is the output of showarg for a.378 CHAPTER 38. but instead used to specialize Base. this would display as view(<a>.Array{Float64. If you have defined a showarg method for SubArray as in the documentation for showarg.3}.UnitRange{Int64}}. :.

38.3. SHOWITLIKEYOUBUILDIT.TYPE COMPLEXITY 379

38.3 ShowItLikeYouBuildIt.type complexity
ShowItLikeYouBuildIt.type complexity — Method.

type_complexity(T::Type) -> c

Return an integer c representing a measure of the “complexity” of type T.
For unnested types, c = n+1 where n is the number of parameters in type T.
However, type complexity calls itself recursively on the parameters, so if the
parameters have their own parameters then the complexity of the type will be
(potentially much) higher than this.
Examples

# Array{Float64,2}
julia> a = rand(3,5);

julia> type_complexity(typeof(a))
3

julia> length(typeof(a).parameters)+1
3

# Create an object that has type:
# SubArray{Int64,2,Base.ReshapedArray{Int64,2,UnitRange{Int64},Tuple{}},Tuple{StepRange{Int64,
julia> r = reshape(1:9, 3, 3);

julia> v = view(r, 1:2:3, :);

julia> type_complexity(typeof(v))
15

julia> length(typeof(v).parameters)+1
6

The second example indicates that the total complexity of v’s type is con-
siderably higher than the complexity of just its “outer” SubArray type.
source

Chapter 39

CoordinateTransformations

39.1 CoordinateTransformations.cameramap
CoordinateTransformations.cameramap — Method.

cameramap()
cameramap(scale)
cameramap(scale, offset)

Create a transformation that takes points in real space (e.g. 3D) and projects
them through a perspective transformation onto the focal plane of an ideal
(pinhole) camera with the given properties.
The scale sets the scale of the screen. For a standard digital camera, this
would be scale = focal length / pixel size. Non-square pixels are sup-
ported by providing a pair of scales in a tuple, scale = (scale x, scale y).
Positive scales represent a camera looking in the +z axis with a virtual screen
in front of the camera (the x,y coordinates are not inverted compared to 3D
space). Note that points behind the camera (with negative z component) will
be projected (and inverted) onto the image coordinates and it is up to the user
to cull such points as necessary.
The offset = (offset x, offset y) is used to define the origin in the
imaging plane. For instance, you may wish to have the point (0,0) represent the
top-left corner of your imaging sensor. This measurement is in the units after
applying scale (e.g. pixels).
(see also PerspectiveMap)
source

39.2 CoordinateTransformations.compose
CoordinateTransformations.compose — Method.

compose(trans1, trans2)

380

39.3. COORDINATETRANSFORMATIONS.RECENTER 381

trans1 trans2

Take two transformations and create a new transformation that is equivalent
to successively applying trans2 to the coordinate, and then trans1. By default
will create a ComposedTransformation, however this method can be overloaded
for efficiency (e.g. two affine transformations naturally compose to a single affine
transformation).
source

39.3 CoordinateTransformations.recenter
CoordinateTransformations.recenter — Method.

recenter(trans::Union{AbstractMatrix,Transformation}, origin::AbstractVector) -> ctrans

Return a new transformation ctrans such that point origin serves as the
origin-of-coordinates for trans. Translation by origin occurs both before and
after applying trans, so that if trans is linear we have

ctrans(origin) == origin

As a consequence, recenter only makes sense if the output space of trans
is isomorphic with the input space.
For example, if trans is a rotation matrix, then ctrans rotates space around
origin.
source

39.4 CoordinateTransformations.transform deriv
CoordinateTransformations.transform deriv — Method.

transform_deriv(trans::Transformation, x)

A matrix describing how differentials on the parameters of x flow through
to the output of transformation trans.
source

39.5 CoordinateTransformations.transform deriv params
CoordinateTransformations.transform deriv params — Method.

transform_deriv_params(trans::AbstractTransformation, x)

A matrix describing how differentials on the parameters of trans flow through
to the output of transformation trans given input x.
source

Chapter 40

Graphics

40.1 Graphics.aspect ratio
Graphics.aspect ratio — Method.
aspect_ratio(bb::BoundingBox) -> r
Compute the ratio r of the height and width of bb.
source

40.2 Graphics.deform
Graphics.deform — Method.
deform(bb::BoundingBox, l, r, t, b) -> bbnew
Add l (left), r (right), t (top), and b (bottom) to the edges of a Bounding-
Box.
source

40.3 Graphics.inner canvas
Graphics.inner canvas — Method.
inner_canvas(c::GraphicsContext, device::BoundingBox, user::BoundingBox)
inner_canvas(c::GraphicsContext, x, y, w, h, l, r, t, b)
Create a rectangular drawing area inside device (represented in device-
coordinates), giving it user-coordinates user. Any drawing that occurs outside
this box is clipped.
x, y, w, and h are an alternative parametrization of device, and l, r, t, b
parametrize user.
See also: set coordinates.
source

382

40.4. GRAPHICS.ISINSIDE 383

40.4 Graphics.isinside
Graphics.isinside — Method.

isinside(bb::BoundingBox, p::Point) -> tf::Bool
isinside(bb::BoundingBox, x, y) -> tf::Bool

Determine whether the point lies within bb.
source

40.5 Graphics.rotate
Graphics.rotate — Method.

rotate(bb::BoundingBox, angle, o) -> bbnew

Rotate bb around o by angle, returning the BoundingBox that encloses the
vertices of the rotated box.
source

40.6 Graphics.rotate
Graphics.rotate — Method.

rotate(p::Vec2, angle::Real, o::Vec2) -> pnew

Rotate p around o by angle.
source

40.7 Graphics.set coordinates
Graphics.set coordinates — Method.

set_coordinates(c::GraphicsContext, device::BoundingBox, user::BoundingBox)
set_coordinates(c::GraphicsContext, user::BoundingBox)

Set the device->user coordinate transformation of c so that device, ex-
pressed in “device coordinates” (pixels), is equivalent to user as expressed in
“user coordinates”. If device is omitted, it defaults to the full span of c,
BoundingBox(0, width(c), 0, height(c)).
See also get matrix, set matrix.
source

384 CHAPTER 40. GRAPHICS

40.8 Graphics.shift
Graphics.shift — Method.

shift(bb::BoundingBox, x, y) -> bbnew

Shift center by (x,y), keeping width & height fixed.
source

Chapter 41

BusinessDays

41.1 BusinessDays.advancebdays
BusinessDays.advancebdays — Method.

advancebdays(calendar, dt, bdays_count)

Increments given date dt by bdays count. Decrements it if bdays count is
negative. bdays count can be a Int, Vector{Int} or a UnitRange.
Computation starts by next Business Day if dt is not a Business Day.
source

41.2 BusinessDays.bdays
BusinessDays.bdays — Method.

bdays(calendar, dt0, dt1)

Counts the number of Business Days between dt0 and dt1. Returns in-
stances of Dates.Day.
Computation is always based on next Business Day if given dates are not
Business Days.
source

41.3 BusinessDays.isbday
BusinessDays.isbday — Method.

isbday(calendar, dt)

Returns false for weekends or holidays. Returns true otherwise.
source

385

386 CHAPTER 41. BUSINESSDAYS

41.4 BusinessDays.isholiday
BusinessDays.isholiday — Method.

isholiday(calendar, dt)

Checks if dt is a holiday based on a given calendar of holidays.
calendar can be an instance of HolidayCalendar, a Symbol or an AbstractString.
Returns boolean values.
source

41.5 BusinessDays.isweekday
BusinessDays.isweekday — Method.

isweekday(dt)

Returns true for Monday to Friday. Returns false otherwise.
source

41.6 BusinessDays.isweekend
BusinessDays.isweekend — Method.

isweekend(dt)

Returns true for Saturdays or Sundays. Returns false otherwise.
source

41.7 BusinessDays.listbdays
BusinessDays.listbdays — Method.

listbdays(calendar, dt0::Date, dt1::Date) Vector{Date}

Returns the list of business days between dt0 and dt1.
source

41.8 BusinessDays.listholidays
BusinessDays.listholidays — Method.

listholidays(calendar, dt0::Date, dt1::Date) Vector{Date}

Returns the list of holidays between dt0 and dt1.
source

41.9. BUSINESSDAYS.TOBDAY 387

41.9 BusinessDays.tobday
BusinessDays.tobday — Method.

tobday(calendar, dt; [forward=true])

Adjusts dt to next Business Day if it’s not a Business Day. If isbday(dt),
returns dt.
source

Chapter 42

OnlineStats

42.1 LearnBase.value
LearnBase.value — Method.

value(s::Series)

Return a tuple of value mapped to the OnlineStats contained in the Series.
source

42.2 OnlineStats.QuantileMM
OnlineStats.QuantileMM — Function.
Deprecated. See Quantile
source

42.3 OnlineStats.QuantileMSPI
OnlineStats.QuantileMSPI — Function.
Deprecated. See Quantile
source

42.4 OnlineStats.QuantileSGD
OnlineStats.QuantileSGD — Function.
Deprecated. See Quantile
source

388

42.5. ONLINESTATS.MAPBLOCKS 389

42.5 OnlineStats.mapblocks
OnlineStats.mapblocks — Function.

mapblocks(f::Function, b::Int, data, dim::ObsDimension = Rows())

Map data in batches of size b to the function f. If data includes an Ab-
stractMatrix, the batches will be based on rows or columns, depending on dim.
Most usage is through Julia’s do block syntax.
Examples

s = Series(Mean())
mapblocks(10, randn(100)) do yi
fit!(s, yi)
info("nobs: $(nobs(s))")
end

x = [1 2 3 4;
1 2 3 4;
1 2 3 4;
1 2 3 4]
mapblocks(println, 2, x)
mapblocks(println, 2, x, Cols())

source

42.6 OnlineStats.stats
OnlineStats.stats — Method.

stats(s::Series)

Return a tuple of the OnlineStats contained in the Series.
Example

s = Series(randn(100), Mean(), Variance())
m, v = stats(s)

source

42.7 StatsBase.confint
StatsBase.confint — Function.

confint(b::Bootstrap, coverageprob = .95)

Return a confidence interval for a Bootstrap b.
source

390 CHAPTER 42. ONLINESTATS

42.8 StatsBase.fit!
StatsBase.fit! — Method.

fit!(s::Series, data, args...)

Update a Series with more data. Additional arguments can be used to

• override the weight
• use the columns of a matrix as observations (default is rows)

Examples

# Univariate Series
s = Series(Mean())
fit!(s, randn(100))

# Multivariate Series
x = randn(100, 3)
s = Series(CovMatrix(3))
fit!(s, x) # Same as fit!(s, x, Rows())
fit!(s, x’, Cols())

# overriding the weight
fit!(s, x, .1) # use .1 for every observation’s weight
w = rand(100)
fit!(s, x, w) # use w[i] as the weight for observation x[i, :]

# Model Series
x, y = randn(100, 10), randn(100)
s = Series(LinReg(10))
fit!(s, (x, y))

source

42.9 StatsBase.nobs
StatsBase.nobs — Method.

nobs(s::Series)

Return the number of observations the Series has fit!-ted.
source

Chapter 43

MacroTools

43.1 MacroTools.inexpr
MacroTools.inexpr — Method.

inexpr(expr, x)

Simple expression match; will return true if the expression x can be found
inside expr.

inexpr(:(2+2), 2) == true

source

43.2 MacroTools.isdef
MacroTools.isdef — Method.
Test for function definition expressions.
source

43.3 MacroTools.isexpr
MacroTools.isexpr — Method.

isexpr(x, ts...)

Convenient way to test the type of a Julia expression. Expression heads and
types are supported, so for example you can call

isexpr(expr, String, :string)

to pick up on all string-like expressions.
source

391

392 CHAPTER 43. MACROTOOLS

43.4 MacroTools.namify
MacroTools.namify — Method.
An easy way to get pull the (function/type) name out of expressions like
foo{T} or Bar{T} <: Vector{T}.
source

43.5 MacroTools.prettify
MacroTools.prettify — Method.

prettify(ex)

Makes generated code generaly nicer to look at.
source

43.6 MacroTools.rmlines
MacroTools.rmlines — Method.

rmlines(x)

Remove the line nodes from a block or array of expressions.
Compare quote end vs rmlines(quote end)
source

43.7 MacroTools.splitarg
MacroTools.splitarg — Method.

splitarg(arg)

Match function arguments (whether from a definition or a function call) such
as x::Int=2 and return (arg name, arg type, is splat, default). arg name
and default are nothing when they are absent. For example:
[] ¿ map(splitarg, (:(f(a=2, x::Int=nothing, y, args...))).args[2:end]) 4-element
Array{Tuple{Symbol,Symbol,Bool,Any},1}: (:a, :Any, false, 2) (:x, :Int, false,
:nothing) (:y, :Any, false, nothing) (:args, :Any, true, nothing)
source

43.8. MACROTOOLS.SPLITDEF 393

43.8 MacroTools.splitdef
MacroTools.splitdef — Method.

splitdef(fdef)

Match any function definition
[] function name{params}(args; kwargs)::rtype where {whereparams} body
end
and return Dict(:name=>..., :args=>..., etc.). The definition can be
rebuilt by calling MacroTools.combinedef(dict), or explicitly with

rtype = get(dict, :rtype, :Any)
all_params = [get(dict, :params, [])..., get(dict, :whereparams, [])...]
:(function $(dict[:name]){$(all_params...)}($(dict[:args]...);
$(dict[:kwargs]...))::$rtype
$(dict[:body])
end)

source

43.9 MacroTools.unblock
MacroTools.unblock — Method.

unblock(expr)

Remove outer begin blocks from an expression, if the block is redundant
(i.e. contains only a single expression).
source

Chapter 44

ImageMorphology

44.1 ImageMorphology.bothat
ImageMorphology.bothat — Function.
imgbh = bothat(img, [region]) performs bottom hat of an image, which
is defined as its morphological closing minus the original image. region allows
you to control the dimensions over which this operation is performed.
source

44.2 ImageMorphology.closing
ImageMorphology.closing — Function.
imgc = closing(img, [region]) performs the closing morphology oper-
ation, equivalent to erode(dilate(img)). region allows you to control the
dimensions over which this operation is performed.
source

44.3 ImageMorphology.dilate
ImageMorphology.dilate — Function.

imgd = dilate(img, [region])

perform a max-filter over nearest-neighbors. The default is 8-connectivity
in 2d, 27-connectivity in 3d, etc. You can specify the list of dimensions that
you want to include in the connectivity, e.g., region = [1,2] would exclude
the third dimension from filtering.
source

394

44.4. IMAGEMORPHOLOGY.ERODE 395

44.4 ImageMorphology.erode
ImageMorphology.erode — Function.
imge = erode(img, [region])
perform a min-filter over nearest-neighbors. The default is 8-connectivity in
2d, 27-connectivity in 3d, etc. You can specify the list of dimensions that you
want to include in the connectivity, e.g., region = [1,2] would exclude the
third dimension from filtering.
source

44.5 ImageMorphology.morphogradient
ImageMorphology.morphogradient — Function.
imgmg = morphogradient(img, [region]) returns morphological gradient
of the image, which is the difference between the dilation and the erosion of
a given image. region allows you to control the dimensions over which this
operation is performed.
source

44.6 ImageMorphology.morpholaplace
ImageMorphology.morpholaplace — Function.
imgml = morpholaplace(img, [region]) performs Morphological Laplacian
of an image, which is defined as the arithmetic difference between the internal
and the external gradient. region allows you to control the dimensions over
which this operation is performed.
source

44.7 ImageMorphology.opening
ImageMorphology.opening — Function.
imgo = opening(img, [region]) performs the opening morphology oper-
ation, equivalent to dilate(erode(img)). region allows you to control the
dimensions over which this operation is performed.
source

44.8 ImageMorphology.tophat
ImageMorphology.tophat — Function.
imgth = tophat(img, [region]) performs top hat of an image, which is
defined as the image minus its morphological opening. region allows you to
control the dimensions over which this operation is performed.
source

Chapter 45

Contour

45.1 Contour.contour
Contour.contour — Method.
contour(x, y, z, level::Number) Trace a single contour level, indicated
by the argument level.
You’ll usually call lines on the output of contour, and then iterate over
the result.
source

45.2 Contour.contours
Contour.contours — Method.
contours(x,y,z,levels) Trace the contour levels indicated by the levels
argument.
source

45.3 Contour.contours
Contour.contours — Method.
contours returns a set of isolines.
You’ll usually call levels on the output of contours.
source

45.4 Contour.contours
Contour.contours — Method.
contours(x,y,z,Nlevels::Integer) Trace Nlevels contour levels at heights
chosen by the library (using the contourlevels function).
source

396

5 Contour.levels — Method. coordinates(c) Returns the coordinates of the vertices of the contour line as a tuple of lists. source 45. level(c) Indicates the z-value at which the contour level c was traced.5.contours — Method.z) Trace 10 automatically chosen contour levels. Turns the output of contours into an iterable with each of the traced contour levels.45.CONTOURS 397 45. source 45. Use coordinates to get the coordinates of a line.levels Contour.6 Contour. source .lines Contour.contours Contour. source 45.level — Method. source 45.level Contour. CONTOUR.9 Contour.coordinates — Method.8 Contour. Each of the objects support level and coordinates.y. lines(c) Extracts an iterable collection of isolines from a contour level.lines — Method.7 Contour.coordinates Contour. contours(x.

circle Compose.circle — Function.circle — Function.circle Compose. source 398 . ys. source 46.y) and a radius of r. y.circle Compose. circle(x.circle — Method. circle(xs.2 Compose. source 46. r) Define a circle with its center at (x. rs) Arguments can be passed in arrays in order to perform multiple drawing operations.1 Compose. circle() Define a circle in the center of the current context with a diameter equal to the width of the context.Chapter 46 Compose 46.3 Compose.

source 46.valigns::VAlignment [. points is an array of (x.rectangle Compose.rectangle — Method.text Compose. values [. height) Define a rectangle of size widthxheight with its top left corner at the point (x.4. ys.rectangle — Function. y).rectangle Compose. rectangle() Define a rectangle that fills the current context completely.y) tuples that specify the corners of the polygon. rectangle(x0s.6 Compose.text — Function.haligns::HAlignment [.rectangle — Function.POLYGON 399 46. text(xs. source 46.7 Compose.46.polygon Compose. COMPOSE.4 Compose. widths. y0. source 46. source .rots::Rotation]]]) Arguments can be passed in arrays in order to perform multiple drawing operations at once.5 Compose. rectangle(x0.polygon — Method. width. y0s. polygon(points) Define a polygon.rectangle Compose. heights) Arguments can be passed in arrays in order to perform multiple drawing operations at once.8 Compose. source 46.

The default alignment of the text is hleft vbottom. text(x.text — Function.valign::VAlignment [. value [. vcenter or vbottom as values for halgin and valgin respectively.y) relative to the current context.9 Compose. hcenter or hright and vtop.400 CHAPTER 46.halign::HAlignment [.text Compose. source . The vertical and hor- izontal alignment is specified by passing hleft. y.rot::Rotation]]]) Draw the text value at the position (x. COMPOSE 46.

bf CoupledFields.CVfn CoupledFields. X::T. df::Int): Cross-validation metric source 47.Rsq adj CoupledFields. bf(x::Vector{Float64}. CVfn{T<:Matrix{Float64}}(parm::T.3 CoupledFields. Rsq_adj{T<:Array{Float64}}(Tx::T.1 CoupledFields. kerneltype::DataType. df::Int): Compute a piecewise linear basis matrix for the vector x.Rsq adj — Method.Chapter 47 CoupledFields 47.2 CoupledFields. Y::T.bf — Method. Ty::T. verbose::B Cross-validation function source 47.CVfn — Method. modelfn::Function. source 401 .

gKCCA — Method.402 CHAPTER 47.6 CoupledFields.cca CoupledFields. by making use of a kernel feature space. X::T. lat=nothing): Whiten matrix d (0-1) Percentage variance of components to retain.7 CoupledFields. cca{T<:Matrix{Float64}}(v::Array{Float64}. gKCCA(par::Array{Float64}. kpars::KernelPa Compute the gradient vector or gradient matrix at each instance of the X and Y fields.cca — Method.gKCCA CoupledFields.gradvecfield — Method.Y::T): Regularized Canonical Correlation Analysis using SVD. source 47. COUPLEDFIELDS 47.whiten — Method. Y::Matrix{Float64}. source 47. d::Float64. gradvecfield{N<:Float64. Y::T. source 47.gradvecfield CoupledFields. source . kpars::KernelParamet Compute the projection matrices and components for gKCCA. T<:Matrix{Float64}}(par::Array{N}. X::Matrix{Float64}.4 CoupledFields.whiten CoupledFields.5 CoupledFields. whiten(x::Matrix{Float64}. X::T. lat Latitudinal area-weighting.

A mul B md! AxisAlgorithms. source 48. dim) solves F for slices b of src along dimension dim. source 48. storing the result in dest. dim) solves a tridiagonal system along di- mension dim of src.4 AxisAlgorithms. M. dim) computes M*x for slices x of src along dimension dim. src. This uses an in-place naive algorithm. A mul B md!(dest.A ldiv B md! AxisAlgorithms.2 AxisAlgorithms.A mul B md! — Method. If desired. src.A mul B md — Method. source 48.3 AxisAlgorithms. storing the result along the same dimension of the output.A mul B md AxisAlgorithms. Currently. so that this becomes an in-place algorithm. M must be an AbstractMatrix.A ldiv B md — Method. 403 . F must be an LU-factorized tridiagonal matrix or a Woodbury matrix.Chapter 48 AxisAlgorithms 48. F must be an LU- factorized tridiagonal matrix. you may safely use the same array for both src and dest.A ldiv B md! — Method. F. A ldiv B md(F. Currently. storing the result in dest.1 AxisAlgorithms.A ldiv B md AxisAlgorithms. A ldiv B md!(dest. src.

In many cases. This uses an in-place naive algorithm. performs a standard matrix multiplication. source .6 AxisAlgorithms. src. storing the resulting vector along the same dimension of the output. M must be an AbstractMatrix. src. AXISALGORITHMS A mul B md(M. M.A mul B perm — Method.404 CHAPTER 48. source 48. M must be an AbstractMatrix.A mul B perm! — Method. this algorithm exhibits the best cache behavior.A mul B perm! AxisAlgorithms. A mul B perm(M. source 48. src. performs a standard matrix multiplication.A mul B perm AxisAlgorithms. In many cases. This uses permutedims to make dimension dim into the first dimension. storing the result in dest. dim) computes M*x for slices x of src along dimen- sion dim. and restores the original dimension ordering. this algorithm exhibits the best cache behavior.5 AxisAlgorithms. This uses permutedims to make dimension dim into the first dimension. storing the resulting vector along the same dimension of the output. A mul B perm!(dest. M must be an AbstractMatrix. and restores the original dimension ordering. dim) computes M*x for slices x of src along dimension dim. dim) computes M*x for slices x of src along dimension dim.

ZlibDeflateOutputStream(output[. Arguments • input: a byte vector. source 49. IO object. • strategy=Z DEFAULT STRATEGY: compression strategy. • level::Integer=6: compression level in 1-9. data is gzip compressed. ZlibDeflateInputStream(input[. <keyword arguments>]) Construct a zlib deflate input stream to compress gzip/zlib data. if false. • mem level::Integer=8: memory to use for compression in 1-9.Chapter 49 Libz 49. Arguments 405 . • bufsize::Integer=8192: input and output buffer size.ZlibDeflateInputStream Libz.2 Libz.1 Libz. see zlib documen- tation. or BufferedInputStream containing data to compress. <keyword arguments>]) Construct a zlib deflate output stream to compress gzip/zlib data. zlib com- pressed.ZlibDeflateInputStream — Method.ZlibDeflateOutputStream — Method.ZlibDeflateOutputStream Libz. • gzip::Bool=true: if true.

• gzip::Bool=true: if true. • mem level::Integer=8: memory to use for compression in 1-9. or BufferedInputStream to which com- pressed data should be written. data is gzip compressed. IO object. <keyword arguments>]) Construct a zlib inflate input stream to decompress gzip/zlib data. • bufsize::Integer=8192: input and output buffer size.406 CHAPTER 49.4 Libz. source 49.ZlibInflateInputStream Libz.ZlibInflateOutputStream Libz. IO object. ZlibInflateInputStream(input[. source 49. . zlib com- pressed. zlib com- pressed. try to find the start of another stream. Arguments • output: a byte vector. ZlibInflateOutputStream(output[.ZlibInflateInputStream — Method. see zlib documen- tation. <keyword arguments>]) Construct a zlib inflate output stream to decompress gzip/zlib data. • bufsize::Integer=8192: input and output buffer size. IO object. if false. • level::Integer=6: compression level in 1-9. or BufferedInputStream to which de- compressed data should be written. LIBZ • output: a byte vector.3 Libz. Arguments • input: a byte vector. • gzip::Bool=true: if true. • reset on end::Bool=true: on stream end. data is gzip compressed. or BufferedInputStream containing com- pressed data to inflate. • strategy=Z DEFAULT STRATEGY: compression strategy.ZlibInflateOutputStream — Method. if false.

49.5.5 Libz. data is gzip compressed. • gzip::Bool=true: if true. if false. zlib com- pressed. source 49. LIBZ.ADLER32 407 • bufsize::Integer=8192: input and output buffer size. adler32(data) Compute the Adler-32 checksum over the data input. source . data can be BufferedInputStream or Vector{UInt8}.crc32 Libz.6 Libz.adler32 Libz.adler32 — Function.crc32 — Function. source 49. data can be BufferedInputStream or Vector{UInt8}. crc32(data) Compute the CRC-32 checksum over the data input.

dropnull! NullableArrays. source 408 .1 NullableArrays.dropnull! — Method. source 50.Chapter 50 NullableArrays 50.2 NullableArrays.3 NullableArrays. dropnull!(X::NullableVector) Remove null entries of X in-place and return a Vector view of the unwrapped Nullable entries.dropnull NullableArrays. dropnull(X::AbstractVector) Return a vector containing only the non-null entries of X.dropnull! NullableArrays. unwrapping Nullable entries. If no nulls are present. source 50. A copy is always returned. this is a no-op and X is returned. even when X does not contain any null values.dropnull — Method.dropnull! — Method. dropnull!(X::AbstractVector) Remove null entries of X in-place and return a Vector view of the unwrapped Nullable entries.

nullify!(X::NullableArray.nullify! NullableArrays. back::Integer) return a copy of X with front null entries inserted at the beginning of the copy and back null entries inserted at the end. padnull(X::NullableVector.nullify! — Method.NULLIFY! 409 50..padnull NullableArrays. source .5 NullableArrays.4 NullableArrays. source 50. I. front::Integer. NULLABLEARRAYS.4.padnull! NullableArrays.padnull — Method. padnull!(X::NullableVector.6 NullableArrays.50.) This is a convenience method to set the entry of X at index I to be null source 50. Returns X.padnull! — Method.. front::Integer. back::Integer) Insert front null entries at the beginning of X and add back null entries at the end of X.

” copying the properties dictionary of img but using the data of the AbstractArray data.data ImageAxes. See also: shareproperties.properties — Method. See also: data. source 51. so changes to one affect the other. data) -> imgnew Create a new “image. copyproperties(img::ImageMeta. Note that changing the properties of imgnew does not affect the properties of img. source 51. source 410 .copyproperties ImageMetadata. omitting the properties dictionary.Chapter 51 ImageMetadata 51. properties(imgmeta) -> props Extract the properties dictionary props for imgmeta.1 ImageAxes.copyproperties — Method. so changes to one affect the other. data(img::ImageMeta) -> array Extract the data from img.properties ImageMetadata. array shares storage with img.data — Method.2 ImageMetadata. See also: properties. props shares storage with img.3 ImageMetadata.

shareproperties(img::ImageMeta. See also: copyproperties.shareproperties — Method.SHAREPROPERTIES 411 51.4 ImageMetadata. data) -> imgnew Create a new “image. source 51. containing the names of properties that have been declared “spatial” and hence should be permuted when calling permutedims.” reusing the properties dictionary of img but using the data of the AbstractArray data.4.spatialproperties ImageMetadata. Declare such properties like this: img["spatialproperties"] = ["spacedirections"] source .5 ImageMetadata. modifying one also affects the other. IMAGEMETADATA. spatialproperties(img) Return a vector of strings.spatialproperties — Method.51.shareproperties ImageMetadata. The two images have synchronized properties.

the pointer can be safely freed. A copy is made. Conversions of byte arrays check for a byte-order marker in the first two bytes. the string does not have to be NUL-terminated.utf16 LegacyStrings.utf16 — Function. (Data must be valid UTF-16.2 LegacyStrings. utf16(s) Create a UTF-16 string from a byte array. array of UInt16.1 LegacyStrings.Ptr{Int16}} [. utf16(::Union{Ptr{UInt16}. This NUL is appended au- tomatically by the utf16(s) conversion function.utf16 — Method. source 52. this allows the string to be passed directly to external functions requiring NUL-terminated data.utf16 LegacyStrings. then you can instead use UTF16String(A) to construct the string without making a copy of the data and treating the NUL as a terminator rather than as part of the string.Chapter 52 LegacyStrings 52. If length is specified. and do not include it in the resulting string. length]) Create a string from the address of a NUL-terminated UTF-16 string. If you have a UInt16 array A that is already NUL-terminated valid UTF-16 data. which is not treated as a character in the string (so that it is mostly invisible in Julia).) Note that the resulting UTF16String data is terminated by the NUL code- point (16-bit zero). source 412 . or any other string type.

utf32(::Union{Ptr{Char}.52.Ptr{UInt32}.4 LegacyStrings.UTF32 413 52.3 LegacyStrings. This NUL is appended au- tomatically by the utf32(s) conversion function. (Conversions of byte arrays check for a byte-order marker in the first four bytes. utf32(s) Create a UTF-32 string from a byte array.utf32 — Function. LEGACYSTRINGS.3. the string does not have to be NUL-terminated.utf32 LegacyStrings. or any other string type. the pointer can be safely freed.Ptr{Int32}} [. array of Char or UInt32. If you have a Char or UInt32 array A that is already NUL-terminated UTF-32 data. this allows the string to be passed directly to external functions requiring NUL-terminated data.utf32 — Method.utf32 LegacyStrings. source .) Note that the resulting UTF32String data is terminated by the NUL code- point (32-bit zero). If length is specified. length]) Create a string from the address of a NUL-terminated UTF-32 string. then you can instead use UTF32String(A) to construct the string without making a copy of the data and treating the NUL as a terminator rather than as part of the string. which is not treated as a character in the string (so that it is mostly invisible in Julia). and do not include it in the resulting string. source 52. A copy is made.

source 53.2 BufferedStreams. source 53. source 53.1 BufferedStreams.anchor! — Method.fillbuffer! — Method.peek BufferedStreams. Refill the buffer.peekbytes! BufferedStreams.5 BufferedStreams. Fills buffer with bytes from stream’s buffer without advancing the position.peekbytes! — Function.fillbuffer! BufferedStreams. source 53. Return the next byte from the input stream without advancing the position. Set the buffer’s anchor to its current position.anchor! BufferedStreams.isanchored — Method. Return true if the stream is anchored. optionally moving and retaining part of the data.3 BufferedStreams.isanchored BufferedStreams.4 BufferedStreams. 414 .Chapter 53 BufferedStreams 53.peek — Method.

7 BufferedStreams. Remove and return a buffer’s anchor. we do not re-fill it. source 53. Copy and return a byte array from the anchor up to. also removing the anchor.upanchor! — Method. Therefore the number of bytes read is limited to the minimum of nb and the remaining bytes in the buffer.TAKEANCHORED! 415 Unless the buffer is empty. source . BUFFEREDSTREAMS.53. but not including the current position.takeanchored! — Method.takeanchored! BufferedStreams.6 BufferedStreams.upanchor! BufferedStreams.6. source 53.

msg. decrypt(cipher.digest — Function. perform an HMAC digest. return a byte array with the digest. CIPHER AES 256 CBC requires a 32-byte (256-bit) key. It should either be convertible to a String or be a Vector{UInt8}. source 54. If an optional key is given. key. msg::Vector{UInt8}.1 MbedTLS.decrypt — Function. it will be set to all zeros. By default. [iv]) -> Vector{UInt8} Decrypt a message using the given cipher. [key::Vector{UInt8}]) -> Vector{UInt8} Perform a digest of the given type on the given message (a byte array). msg is the message to be encoded. for example.2 MbedTLS.digest MbedTLS.decrypt MbedTLS. It must be the right length for the chosen cipher. 16 bytes for AES) and correspond to the iv used by the encryptor. iv is the initialization vector. The cipher can be specified as • a generic cipher (like CIPHER AES) • a specific cipher (like CIPHER AES 256 CBC) • a Cipher object key is the symmetric key used for cryptography. whose size must match the block size of the cipher (eg. given as either a String or a Vector{UInt8}.Chapter 54 MbedTLS 54. digest(kind::MDKind. source 416 .

digest!(kind::MDKind. For security reasons.digest! — Function.encrypt — Function.54.3. key. msg.encrypt MbedTLS. msg is the message to be encoded. for example. MBEDTLS. By default.DIGEST! 417 54.digest! MbedTLS. The cipher can be specified as • a generic cipher (like CIPHER AES) • a specific cipher (like CIPHER AES 256 CBC) • a Cipher object key is the symmetric key used for cryptography. it should be set to a different value for each encryption operation.4 MbedTLS. 16 bytes for AES). given as either a String or a Vector{UInt8}. it will be set to all zeros. [key::Vector{UInt8}. source . which is not secure. It is the user’s responsibility to ensure that buffer is long enough to contain the digest. get size(kind::MDKind) returns the appropriate size. buffer::Vector{UInt8}) In-place version of digest that stores the digest to buffer. iv is the initialization vector. source 54. It must be the right length for the chosen cipher. [iv]) -> Vector{UInt8} Encrypt a message using the given cipher. It should either be convertible to a String or be a Vector{UInt8}. whose size must match the block size of the cipher (eg. msg::Vector{UInt8}.3 MbedTLS. CIPHER AES 256 CBC requires a 32-byte (256-bit) key. encrypt(cipher. ].

source 55. source 55. dropna!(X::DataValueVector) Remove missing entries of X in-place and return a Vector view of the un- wrapped DataValue entries.dropna! DataValues.2 DataValues. If no missing values are present. this is a no-op and X is returned.3 DataValues. source 418 .dropna! DataValues. dropna!(X::AbstractVector) Remove missing entries of X in-place and return a Vector view of the un- wrapped DataValue entries.dropna! — Method.dropna! — Method. A copy is always returned.dropna DataValues.1 DataValues.Chapter 55 DataValues 55. unwrapping DataValue entries.dropna — Method. even when X does not contain any missing values. dropna(X::AbstractVector) Return a vector containing only the non-missing entries of X.

padna!(X::DataValueVector.4.padna! — Method. front::Integer. source 55.padna! DataValues. source . DATAVALUES.padna — Method.4 DataValues.5 DataValues. back::Integer) Insert front null entries at the beginning of X and add back null entries at the end of X. Returns X. front::Integer. back::Integer) return a copy of X with front null entries inserted at the beginning of the copy and back null entries inserted at the end.PADNA! 419 55.55. padna(X::DataValueVector.padna DataValues.

2 NearestNeighbors. k [.3 NearestNeighbors.knn NearestNeighbors. inrange(tree::NNTree.injectdata NearestNeighbors. source 56. source 420 . data) -> tree Returns the KDTree/BallTree wrapped by datafreetree.inrange NearestNeighbors. sortres=false]) -> indices. radius [. set up to use data for the points data.injectdata — Method. points. If sortres = true the result is sorted such that the results are in the order of increasing distance to the point. knn(tree::NNTree. points. skip is an optional predicate to determine if a point that would be returned should be skipped. injectdata(datafreetree. source 56.inrange — Method.1 NearestNeighbors. sortres=false]) -> indices Find all the points in the tree which is closer than radius to points. distances Performs a lookup of the k nearest neigbours to the points from the data in the tree. If sortres = true the resulting indices are sorted.knn — Method.Chapter 56 NearestNeighbors 56.

converted to lowercase with spaces replaced by hyphens).Chapter 57 IJulia 57. where the given options are passed to the julia executable. the Jupyter name for the kernel (for the jupyter kernelspec command is given by the optional keyword specname (which defaults to name.notebook IJulia..notebook — Method.. options. kernelname = installkernel("Julia O3". Internally. The returned kernelspec command will be something like jupyter kernelspec (perhaps with different path). specname=replace(lowercase(name). and the user-visible kernel name is given by name followed by the Julia version.. Both the kernelspec command (a Cmd object) and the new kernel name are returned by installkernel.6).installkernel IJulia. run(‘$kernelspec remove -f $kernelname‘) source 57. and kernelname will be something like julia-O3-0. You could uninstall the kernel by running e.1 IJulia.2 IJulia.6 (in Julia 0. For example: kernelspec. "-") Install a new Julia kernel. " ". dir=homedir().g. notebook(. installkernel(name.installkernel — Method. detached=false) 421 . followed by the Julia version number. "-O3") creates a new Julia kernel in which julia is launched with the -O3 optimiza- tion flag.

By default. So. Alternatively. (The only way to stop Jupyter will then be to kill it in your operating system’s process manager. notebook(dir=pwd()) to use the current directory. notebook() does not return. but this location can be changed by passing the desired path in the dir keyword argument. The ad- vantage of launching the notebook from Julia is that. depending on how Jupyter was installed. and will continue running even after you quit Julia. which halts Jupyter. e. IJULIA The notebook() function launches the Jupyter notebook. the jupyter notebook will launch in the back- ground. and is equivalent to running jupyter notebook at the operating-system command-line. you must leave the Julia termi- nal open for as long as you want to run Jupyter. the user may not know where to find the jupyter executable. you must hit ctrl-c or quit Ju- lia to interrupt it. if you run notebook(detached=true). the notebook server is launched in the user’s home directory.422 CHAPTER 57.g. By default.) source .

will be sent as one frame.write Base. read(ws::WebSocket) Read one non-control message from a WebSocket. Write binary data.read — Method.1 Base.3 Base. Only the data (contents/body/payload) of the message will be returned from this function.close — Method.Chapter 58 WebSockets 58. source 58. This function will not return until a full non-control message has been read. Any control messages that are read will be handled by the handle control frame function. source 423 . If the other side doesn’t ever complete its message.read Base. close(ws::WebSocket) Send a close message.write — Method. source 58. this function will never return.close Base.2 Base.

424 CHAPTER 58. source 58. WEBSOCKETS 58.write — Method.4 Base. source 58. optionally with data.send pong — Method.send ping — Method.send pong WebSockets.send ping WebSockets.write Base.6 WebSockets. optionally with data.5 WebSockets. Send a ping message. will be sent as one frame. Send a pong message. source . Write text data.

)->Y and return another function gfun(X.. getval(x) Unbox x if it is a boxed value (Rec)..gradcheck AutoGrad. but returns the gradient instead. or Dict...2 AutoGrad. Tuple.)->dXi which computes its gradient with respect to positional argument number argnum. x. The function fun should be scalar-valued. source 59. Array.grad AutoGrad. The returned function gfun takes the same arguments as fun.1 AutoGrad. w. gradcheck(f.Chapter 59 AutoGrad 59.. grad(fun.. argnum=1) Take a function fun(X.. kwargs.getval AutoGrad.gradcheck — Method..3 AutoGrad.grad — Function. otherwise return x..getval — Method. The gradient has the same type and size as the target argument which can be a Number. source 59.) 425 .

value) pair. Array. • delta=atol=rtol=cbrt(eps(w)): tolerance parameters. Only the largest 10 entries in each numerical gradient array are checked by default..) compared to their numerical estimates.. • kwargs=[]: keyword arguments to be passed to f. The argument w can be a Number.) with respect to its first argument w and return a boolean result. argnum=1) Another version of grad where the generated function returns a (gradi- ent.. gradcheck constructs and checks a scalar function by taking its dot product with a random vector.gradloss AutoGrad. source . If the output of f is not a number.426 CHAPTER 59..o. AUTOGRAD Numerically check the gradient of f(w. • verbose=false: print detailed messages if true.o...gradloss — Function....4 AutoGrad. gradloss(fun. Tuple or Dict which in turn can contain other Arrays etc..x. source 59. Keywords • gcheck=10: number of largest entries from each numeric array in gradient dw=(grad(f))(w.x. See isapprox for their meaning.

Chapter 60 ComputationalResources 60..haveresource — Method. addresource(OpenCLLibs) would indicate that you have a GPU and the OpenCL libraries installed. For example. rmresource(T) 427 .3 ComputationalResources.2 ComputationalResources.addresource — Method.. This function is typically used inside a module’s init function. haveresource(OpenCLLibs) tests whether the OpenCLLibs have been added as an available resource. addresource(T) Add T to the list of available resources. source 60.otherinitializationcode.addresource ComputationalResources.rmresource — Method.rmresource ComputationalResources.1 ComputationalResources.possiblysettingtheLOADP AT Hif haveresource(OpenCLLibs)@evalusin ( source 60. For example. Example: [] The i nitf unctionf orM yP ackage: f unctioni nit ) . haveresource(T) Returns true if T is an available resource.haveresource ComputationalResources.

COMPUTATIONALRESOURCES Remove T from the list of available resources. source . rmresource(OpenCLLibs) would indicate that any future package loads should avoid loading their special- izations for OpenCL.428 CHAPTER 60. For example.

dbscan — Method.1 Clustering. 0. minn eighbors = 3.05. minc lusters ize =20)clusterswithlessthan20pointswillbediscarded source 429 .dbscan Clustering.Chapter 61 Clustering 61. dbscan(points. radius . min_neighbors = 1. size core indices and boundary indices Example: [] points = randn(3. 10000) clusters = dbscan(points. min_cluster_size = 1) -> clusters Cluster points using the DBSCAN (density-based spatial clustering of ap- plications with noise) algorithm. leafsize = 20. Arguments • points: matrix of points • radius::Real: query radius Keyword Arguments • leafsize::Int: number of points binned in each leaf node in the KDTree • min neighbors::Int: minimum number of neighbors to be a core point • min cluster size::Int: minimum number of points to be a valid cluster Output • Vector{DbscanCluster}: an array of clusters with the id.

mcl(adj::Matrix.430 CHAPTER 61. [keyword arguments])::MCLResult Identify clusters in the weighted graph using Markov Clustering Algorithm (MCL). Ref: Stijn van Dongen. “Graph clustering by flow simulation”. could be useful if MCL doesn’t converge • max iter::Integer: max number of MCL iterations • tol::Number: MCL adjacency matrix convergence threshold • prune tol::Number: pruning threshold • display::Symbol: :none for no output or :verbose for diagnostic mes- sages See original MCL implementation. Arguments • adj::Matrix{Float64}: adjacency matrix that defines the weighted graph to cluster • add loops::Bool: whether edges of weight 1.mcl — Method.mcl Clustering.0) • save final matrix::Bool: save final equilibrium state in the result. disabled by default.2 Clustering. 2001 source . CLUSTERING 61. oth- erwise leave it empty.0 from the node to itself should be appended to the graph (enabled by default) • expansion::Number: MCL expansion constant (2) • inflation::Number: MCL inflation constant (2.

Chapter 62 JuliaWebAPI 62. construct an HTTP Response object from the API response source 62. start processing as a server source 431 . extract and return the response data as a direct function call would have returned but throw error if the call was not successful.apicall — Method.process — Method. The response is format- ted as specified by the formatter specified in conn. Calls a remote api cmd with args.fnresponse — Method.process JuliaWebAPI. source 62. and data..fnresponse JuliaWebAPI.apicall JuliaWebAPI.1 JuliaWebAPI.2 JuliaWebAPI.....3 JuliaWebAPI.4 JuliaWebAPI. source 62.httpresponse JuliaWebAPI.httpresponse — Method.

432 CHAPTER 62.register JuliaWebAPI. TODO: validate method belongs to module? source .register — Method. Register a function as API call. JULIAWEBAPI 62.5 JuliaWebAPI.

apply adaboost stumps proba DecisionTree. apply_adaboost_stumps_proba(stumps::Ensemble.1 DecisionTree. It specifies the column ordering of the output matrix. [“versicolor”. [“versicolor”. each row summing up to 1. apply_tree_proba(::Node.2 DecisionTree. features.apply tree proba DecisionTree. source 63. coeffs. apply_forest_proba(forest::Ensemble. features. “vir- ginica”. col_labels::Vector) computes P(L=label|X) for each row in features.3 DecisionTree. It returns a N row x n labels matrix of probabilities.Chapter 63 DecisionTree 63. labels::Vector) computes P(L=label|X) for each row in features. col_labels::Vector) 433 .apply forest proba — Method.apply tree proba — Method. source 63. each row summing up to 1. “vir- ginica”. col labels is a vector containing the distinct labels (eg. It returns a N row x n labels matrix of probabilities.apply forest proba DecisionTree. “setosa”]). It specifies the column ordering of the output matrix. col labels is a vector containing the distinct labels (eg. “setosa”]).apply adaboost stumps proba — Method. features.

It specifies the column ordering of the output matrix. col labels is a vector containing the distinct labels (eg. source . DECISIONTREE computes P(L=label|X) for each row in features. “setosa”]). each row summing up to 1. “vir- ginica”. It returns a N row x n labels matrix of probabilities. [“versicolor”.434 CHAPTER 63.

compress Blosc. src.1 Blosc. The return value is the size in bytes of the data written to dest.. The level keyword indicates the compression level (between 0=no compres- sion and 9=max).decompress! — Method. kws. and the shuffling preconditioner is optimized for arrays of binary items of size (in bytes) itemsize (defaults to sizeof(eltype(data)) for arrays and the size of the code units for strings). source 64. src::Vector{UInt8}) 435 . shuffle indicates whether to use Blosc’s shuffling precondi- tioner. decompress!(dest::Vector{T}. shuffle=true. or 0 if the buffer was too small. source 64.2 Blosc.decompress! Blosc.) Like compress(src. compress(data.. kws. itemsize) Return a Vector{UInt8} of the Blosc-compressed data.Chapter 64 Blosc 64. compress!(dest::Vector{UInt8}.compress! — Function.compress! Blosc. where data is an array or a string..). level=5..3 Blosc. but writes to a pre-allocated array dest of bytes.compress — Function.

which is resized as needed to store the decompressed data from src.decompress — Method. source . source 64. BLOSC Like decompress. decompress(T::Type. src::Vector{UInt8}) Return the compressed buffer src as an array of element type T. but uses a pre-allocated destination buffer dest.436 CHAPTER 64.decompress Blosc.4 Blosc.

2 Parameters. 99)]) ==A(3.reconstruct — Method.Chapter 65 Parameters 65.5)) Dict{Symbol.with kw — Function. This function is called by the @with kw macro and does the syntax transfor- mation from: 437 .reconstruct Parameters.99) source 65.4) b = reconstruct(a. Transforms a type-instance into a dictionary. Make a new instance of a type with the same values as the input type except for the fields given in the associative second argument or as keywords. julia> type T a b end julia> type2dict(T(4.Any} with 2 entries: :a => 4 :b => 5 source 65. [(:b. a.type2dict Parameters. b end a = A(3.3 Parameters. [] struct A.type2dict — Method.1 Parameters.with kw Parameters.

a) de- fault outer positional constructor MM(.Any}}) = reconstruct(mm.a) MM{R}(. kws.) = reconstruct(mm. so no type-paras are needed when calling MM(m::MM. di::Union{Associative.a) outer kw. type-paras are required when calling end MM(r::R.a) inner kw..r=1000.aend)endmac source .a :: Rend into [] struct MM{R} r::R a::R MM{R}(r..a=error(”no default for a”)) = MM(r..r=1000.ra = varname.kws) MM(m::MM.a) where {R} = new(r. Tuple{Symbol. di) macro unpackM M (varname)esc(quoter = varname.a::R) where {R} = MM{R}(r.438 CHAPTER 65. a=error(”no default for a”)) where {R} = MM{R}(r. PARAMETERS [] @withk wstructM M {R}r :: R =1000.

.h5open — Method.1 HDF5. mode::AbstractString="r". For example with a do block: h5open("foo.) and close the resulting HDF5File upon completion.. swmr=false) Open or create an HDF5 file where mode is one of: • “r” read only • “r+” read and write • “w” read and write. or SWMR read access for “r”.h5open HDF5.h5". function h5open(f::Function..h5open HDF5. h5open(filename::AbstractString...2. create a new file (destroys any existing contents) Pass swmr=true to enable (Single Writer Multiple Reader) SWMR write access for “w” and “r+”. args.h5open — Function. swmr=false) Apply the function f to the result of h5open(args.kwargs.2 HDF5. source 66..."w") do h5 h5["foo"]=[1.Chapter 66 HDF5 66..3] end source 439 .

source 66. limited by max dims = get dims(dset)[2].ishdf5 — Method. set_dims!(dset::HDF5Dataset. ishdf5(name::AbstractString) Returns true if name is a path to a valid hdf5 file. false otherwise. Reduction is possible and leads to loss of truncated data.set dims! — Method.3 HDF5.4 HDF5.ishdf5 HDF5. HDF5 66.set dims! HDF5. new_dims::Dims) Change the current dimensions of a dataset to new dims. source .440 CHAPTER 66.

SSLConfig object that already has associated certificates. Method accepts following keyword arguments: • host .named pipe/domain socket path.CRT (certificate) and MbedTLS.id pool.binding port • ssl . run starts server Functionality: • Accepts incoming connections and instantiates each Client. • socket . Compatibility: • for backward compatibility use run(server::Server. a configuration with reasonable defaults will be used.binding address • port . or a tuple of an MbedTLS. Network options are ignored.run — Method.1 Base. It’s available only on Unix. • Blocks forever. Can be either an MbedTLS. In the latter case. port::Integer) 441 .PKContext (private key)).SSL configuration.Chapter 67 HttpServer 67. • Spawns a new Task for each connection. Use this argument to enable HTTPS support. Use this argument to enable Unix socket support.run Base. • Manages the client.

0.442 CHAPTER 67.2 Base. value. HTTPSERVER Example: server = Server() do req.setcookie! — Function. 8000) source 67.1).setcookie! HttpServer. Sets a cookie with the given name. host=IPv4(127.write — Method. and attributes on the given re- sponse object. Converts a Response to an HTTP response string source 67.write Base. res "Hello world" end # start server on localhost run(server.0. source . port=8000) # or run(server.3 HttpServer.

mappedarray MappedArrays. A) of_eltype(val::T. correspondingly. The view is read-only (you can get values but not set them). source 443 .2 MappedArrays. finv). A) creates a view of the array A that applies f to every element of A.3 MappedArrays. source 68.mappedarray — Method. source 68.1 MappedArrays. the values in A. mappedarray(f. of_eltype(T. finv.Chapter 68 MappedArrays 68.of eltype — Method. A) creates a view of the array A that applies f to every element of A. allows one to also set values of the view and.mappedarray MappedArrays. mappedarray((f.of eltype MappedArrays. A) creates a view of A that lazily-converts the element type to T.mappedarray — Method. The inverse function.

Chapter 69 TextParse 69. (could be the same as quotechar) • pooledstrings: whether to try and create PooledArray of strings • nrows: number of rows in the file.csvread — Function. csvread(file::Union{String.) Read CSV from file.. • skiplines begin: skips specified number of lines at the beginning of the file • header exists: boolean specifying whether CSV file contains a header 444 .1 TextParse. column names if header exists=true. defaults to " • escapechar: character used to escape quotechar in strings..IO}. <arguments>.’. Defaults to 0 in which case we try to estimate this. delim has no effect if true. • quotechar: character used to quote strings. DataValueArray or PooledArray 2.csvread TextParse. empty array otherwise Arguments: • file: either an IO object or file name string • delim: the delimiter character • spacedelim: (Bool) parse space-delimited files. delim=’. Returns a tuple of 2 elements: 1. A tuple of columns each either a Vector.

Defaults to TextParse.". source ..NA STRINGS • colnames: manually specified column names. see CustomParser if you want to plug in custom pars- ing behavior • type detect rows: number of rows to use to infer the initial colparsers defaults to 20. It can also be a dateformat".. Could be a vector or a dictionary from Int index (the column) to String column name. The simplest parser is a type such as Int.1. TEXTPARSE. • colparsers: Parsers to use for specified columns. Float64. This can be a vector or a dictionary from column name / column index (Int) to a “parser”.69.CSVREAD 445 • nastrings: strings that are to be considered NA.

then this method will poison the type-inference of the calling scope. This is because K will be promoted to a type parameter.weightedloss LossFunctions. This is because weight will be promoted to a type parameter.scaled LearnBase.2 LossFunctions. scaled(loss::SupervisedLoss.1 LearnBase. Val{K}) source 70. For example. Note: If typeof(K) <: Number. For a typestable version use the following signature: weightedloss(loss. weightedloss(loss. weight) Returns a weighted version of loss for which the value of the positive class is changed to be weight times its original. This function dis- patches on the type of loss in order to choose the appropriate type of scaled loss that will be used as the decorator.scaled — Method. if typeof(loss) <: DistanceLoss then the given loss will be boxed into a ScaledDistanceLoss. Note: If typeof(weight) <: Number. then this method will poison the type- inference of the calling scope.Chapter 70 LossFunctions 70. and the negative class 1 .weight times its original respectively. Val{weight}) source 446 .weightedloss — Method. For a typestable version use the following signature: scaled(loss. K) Returns a version of loss that is uniformly scaled by K.

inputdomain — Function.grad! — Function.transform! — Function.grad LearnBase.r. Returns an AbstractSet representing valid input values source 71.5 LearnBase.Chapter 71 LearnBase 71.4 LearnBase. Returns an AbstractSet representing valid output/target values source 71.targetdomain — Function.1 LearnBase.2 LearnBase.grad! LearnBase.targetdomain LearnBase.grad — Function. Do a backward pass. Return the gradient of the learnable parameters w. 447 .3 LearnBase.t.inputdomain LearnBase.transform! LearnBase. updating the gradients of learnable parameters and/or inputs source 71. some objective source 71.

448 CHAPTER 71. and return the output source . LEARNBASE Do a forward pass.

Chapter 72 Juno 72. source 72.3 Juno... selector([xs.input — Function.. source 72." Prompt the user to input some text.]) -> x Allow the user to select one of the xs. and return it.1 Juno. Currently there is no fallback in other environments.. Optionally display a prompt. does nothing otherwise.clearconsole — Method.selector — Method.clearconsole Juno. xs should be an iterator of strings. input(prompt = "") -> ".selector Juno.input Juno. source 449 .2 Juno. clearconsole() Clear the console if Juno is used.

structure(x) Display x’s underlying representation.structure Juno.450 CHAPTER 72. For example. source . JUNO 72. rather than using its normal display method.4 Juno. structure(:(2x+1)) displays the Expr object with its head and args fields instead of printing the expression.structure — Method.

4 HttpParser.parse url — Method.Chapter 73 HttpParser 73.http method str — Method. Parse a URL source 451 . source 73.3 HttpParser.http method str HttpParser. Run a request through a parser with specific callbacks on the settings in- stance. Intializes the Parser object with the correct memory.http parser init — Function. Returns a string version of the HTTP method.1 HttpParser.http parser init HttpParser.http parser execute HttpParser. source 73.parse url HttpParser.http parser execute — Method.2 HttpParser. source 73.

source 74.2 ImageAxes. it is generally better to use timeaxis.1 ImageAxes.timeaxis — Method. source 452 . or 0 if not using an axis for this purpose. source 74. and nothing otherwise.3 ImageAxes.timedim — Method.istimeaxis — Method.timeaxis ImageAxes. istimeaxis(ax) Test whether the axis ax corresponds to time. timeaxis(A) Return the time axis.istimeaxis ImageAxes.timedim ImageAxes. Note: if you want to recover information about the time axis.Chapter 74 ImageAxes 74. if present. of the array A. timedim(img) -> d::Int Return the dimension of the array used for encoding time.

Chapter 75 IntervalSets 75.r) = length(l:r) .:. iv = l. source 453 .: — Method.. — Method. source 75...2 IntervalSets.r Construct a ClosedInterval iv spanning the region from l to r.width IntervalSets.halfwidth to center + halfwidth. IntervalSets.width — Method. w = width(iv) Calculate the width (max-min) of interval iv..3 IntervalSets.:. iv = centerhalfwidth Construct a ClosedInterval iv spanning the region from center .1 IntervalSets. Note that for integers l and r.1.: IntervalSets. width(l. source 75.

getdisplay — Method.2 Media. e.g.3 Media. media(Gadfly.getdisplay Media.Plot or Media.setdisplay — Method.media Media. output) Display T objects using output when produced by input.Plot source 76. getdisplay(T) Find out what output device T will display on.Plot) == Media. Console()) source 454 .1 Media. Gadfly. T is an object type or media type. media(T) gives the media type of the type T. Image.media — Method. source 76. The default is Textual. display(Editor(). T.Chapter 76 Media 76. setdisplay([input].Graphical.setdisplay Media.

2 Rotations. (tol defaults to 1000 * eps(eltype(r)).) source 77. to) Compute the quaternion that rotates vector from so that it aligns with vector to.1 Rotations. tol) Check whether r is a 33 rotation matrix.rotation between Rotations. rotation_between(from. isrotation(r) isrotation(r. where r * r is within tol of the identity matrix (using the Frobenius norm).isrotation — Method.rotation between — Method.isrotation Rotations. source 455 .Chapter 77 Rotations 77. along the geodesic (shortest path).

If it has seen the file before then it finds the compiled MustacheTokens in TEMPLATES rather than calling parse a second time.render from file — Method. or a string to parse into tokens • view: A view provides a context to look up unresolved symbols demar- cated by mustache braces. Arguments • io::IO: Optional IO object. A view may be specified by a dictionary.2 Mustache. • tokens: Either Mustache tokens.1 Mustache. a vector. a module. Renders a template from filepath and view. using optional io object to print or store. a composite type. Render a set of tokens with a view.render from file Mustache.render Mustache. source 456 . source 78.render — Method.Chapter 78 Mustache 78. or keyword arguments.

12) julia> padded tilesize(Float64.padded tilesize — Method.3)) (64.1 TiledIteration. padded_tilesize(T::Type.3).3.18) julia> padded tilesize(Float32. Examples julia> padded tilesize(UInt8. (3.18) julia> padded tilesize(UInt8.6) source 457 . [ncache=2]) -> tilesize::Dims Calculate a suitable tile size to approximately maximize the amount of pro- ductive work. Optionally specify ncache. The element type of the array is T. the number of such arrays that you’d like to have fit simultaneously in L1 cache.3)) (768.3)) (96. given a stencil of size kernelsize.padded tilesize TiledIteration. (3. (3. (3. kernelsize::Dims. since the first dimension cor- responds to individual cache lines.6.Chapter 79 TiledIteration 79. 4) (512. This favors making the first dimension larger.

0. 0. x) 22 Array{Float64.0 source 458 . R1 (P |Q) = sumi:pi >0 (pi log(pi /qi )) At = .577315 0.0 0. Q.renyi divergence — Function. 0.0 0. and is equal to Kullback–Leibler divergence at = 1: At = 0. R0 (P |Q) = −log(sumi:pi >0 (qi )) At = 1.1.0 0. The divergence is not a semimetric as it is not symmetric. It is parameterised by a parameter .0 0.2}: 0.2}: 0.3. RenyiDivergence(::Real) renyi_divergence(P. ::Real) Create a Rnyi premetric of order . x. Rnyi defined a spectrum of divergence measures generalising the Kullback– Leibler divergence (see KLDivergence).0 julia> pairwise(Euclidean(2). 2). x. x) 22 Array{Float64.4.655407 0. 2.1 Distances.Chapter 80 Distances 80. julia> pairwise(RenyiDivergence(0). R(P |Q) = log(supi:pi >0 (pi /qi )) ( Otherwise R(P |Q) = log(sumi:pi >0 ((pi )/(qi − 1)))/( − 1) Example: julia> x = reshape([0.renyi divergence Distances.2].

1 HttpCommon.hackershool. escapeHTML(i::AbstractString) Returns a string with special HTML characters escaped: &.parsequerystring HttpCommon. parsequerystring(query::AbstractString) Convert a valid querystring to a Dict: q = "foo=bar&baz=%3Ca%20href%3D%27http%3A%2F%2Fwww.hackershool.escapeHTML HttpCommon. <. “.2 HttpCommon. >.com%27%3Ehello%20world%21%3C%2Fa%3 parsequerystring(q) # Dict{String.com’>hello world!</a>" # "foo" => "bar" source 459 .parsequerystring — Method.String} with 2 entries: # "baz" => "<a href=’http://www.Chapter 81 HttpCommon 81. ’ source 81.escapeHTML — Method.

T.::Siz if they wish to overload the default behavior.similar type StaticArrays. T) similar_type(array. This differs from similar() in that the resulting array type may not be mutable (or define setindex!()). ::Size) similar_type(array. ::Size) Returns a constructor for a statically-sized array similar to the input array (or type) static array/array. similar_type(static_array) similar_type(static_array. and therefore the returned type may need to be constructed with its data.1 StaticArrays. Note that the (optional) size must be specified as a static Size object (so the compiler can infer the result statically).::Type{T}.similar type — Function. New types should define the signature similar type{A<:MyType.T. source 460 .S}(::Type{A}. If the input array is not a StaticArray then the Size is mandatory.Chapter 82 StaticArrays 82. optionally with different element type T or size Size.

rather than an Integer.1 SweepOperator. Only the upper triangle is read and swept. sweep!(A. sweep!(A. k.sweep! SweepOperator. inv = false) Example: [] x = randn(100. 10) xtx = x’x sweep!(xtx.Chapter 83 SweepOperator 83. 1) sweep!(xtx. inv = false) Providing a Range.sweep! — Method. Symmetric sweep operator Symmetric sweep operator of the matrix A on element k. sweeps on each element in the range. 1. first:last. true) source 461 . inv = true will perform the inverse sweep. A is overwritten.

complex to real NLSolversBase.Chapter 84 NLSolversBase 84. Convert a real array of size 2 x dims to a complex array of size dims source 462 .2 NLSolversBase. Convert a complex array of size dims to a real array of size 2 x dims source 84.real to complex — Method.complex to real — Method.real to complex NLSolversBase.1 NLSolversBase.

2].0 source 463 .) Pad the arrays A1. a2).OneTo{Int64}.1 PaddedViews.2.0 julia¿ a1p.2}: 1 2 julia¿ a2 = [1.0 2. .Tuple{Base.OneTo{Int64}.0 0.0 2.paddedviews — Method. chosen as the span of indices enclosing all of the input arrays.0 0.paddedviews PaddedViews.0. 1) 21 Array{Int64.OneTo{Int64}}.Tuple{Base.OneTo{Int64}}. 2... to a common size or set of indices.Array{Int64. A1.2}: 1.Base.Base. .Chapter 85 PaddedViews 85.Array{Float64 1. Aspad = paddedviews(fillvalue.2. julia¿ a1p 22 PaddedViews. a1. . . A2.PaddedView{Int64. . a2p = paddedviews(0.0]’ 12 Array{Float64.2.2}}: 1020 julia¿ a2p 22 PaddedViews.. A2.PaddedView{Float64. Example: [] julia¿ a1 = reshape([1.

= tanh) Long Short Term Memory recurrent layer. LSTM(in::Integer. but with the output fed back into the input each time step.LSTM Flux. out::Integer. source 86. RNN(in::Integer.RNN — Method. = tanh) The most basic recurrent layer.Chapter 86 Flux 86.LSTM — Method. source 464 .1 Flux. Behaves like an RNN but gener- ally exhibits a longer memory span over sequences. out::Integer.RNN Flux. See this article for a good overview of the internals. essentially acts as a Dense layer.2 Flux.

2 SpecialFunctions.1 SpecialFunctions.sinint — Function. defined by Ci(x) := γ + log x + R x cos t−1 0 t dt for real x > 0.sinint SpecialFunctions. defined by Si(x) := 0 t dt for real x. cosint(x) Compute the cosine integral function of x. source 87. source 465 .Chapter 87 SpecialFunctions 87.cosint SpecialFunctions. sinint(x) Rx sin t Compute the sine integral function of x.cosint — Function. where γ is the Euler-Mascheroni constant.

Create a new NamedTuple with the specified element removed. source 466 . This copies the underlying data. source 88. Create a new NamedTuple with the new value set on it.setindex NamedTuples.1 NamedTuples.Chapter 88 NamedTuples 88.2 NamedTuples.delete — Method.delete NamedTuples.setindex — Method. either overwriting the old value or appending a new value.

ys.1 Loess. Smaller values result in smaller local context in fitting.1]. span=0. typi- cally in [0. source 467 .Chapter 89 Loess 89.loess — Method. normalize: Normalize the scale of each predicitor. degree: Polynomial degree. Returns: A fit LoessModel. degreee=2) Fit a loess model.loess Loess.75. loess(xs. Args: xs: A n by m matrix with n observations from m independent predic- tors ys: A length n response vector. normalize=true. (default true when m > 1) span: The degree of smoothing.

1 Nulls. Contrary to unique.levels Nulls. source 468 . omitting null even if present.Chapter 90 Nulls 90. Values are returned in the preferred order for the collection. and does not preserve their order of appearance in x. with the result of sort as a default.levels — Method. this function may return values which do not actually occur in the data. levels(x) Return a vector of unique values which occur or could occur in collection x.

liftFactor(A)(x) is the same as inv(A)*x. liftFactor(A) More stable version of inv(A).e.Chapter 91 WoodburyMatrices 91.1 WoodburyMatrices. source 469 .liftFactor — Method. i.liftFactor WoodburyMatrices. Returns a function which computs the inverse on evaluation.

save — Function. If the path is a direc- tory.save Requests.") Saves the data in the response in the directory path. source 470 .Chapter 92 Requests 92. save(r::Response.1 Requests. then the filename is automatically chosen based on the response headers. path=". Returns the full pathname of the saved file.

Chapter 93 MemPool 93. nor does it affect size accounting.savetodisk — Method. This does not free the data from memory.1 MemPool. source 471 .savetodisk MemPool. Allow users to specifically save something to disk.

Chapter 94 SimpleTraits 94. This function checks whether a trait is fulfilled by a specific set of types.1 SimpleTraits. istrait(Tr1{Int.Float64}) => return true or false source 472 .istrait SimpleTraits.istrait — Method.

Chapter 95 BinDeps 95. For non-glibc Linux and other platforms. return the version of glibc in use.glibc version BinDeps.glibc version — Method.1 BinDeps. returns nothing. glibc_version() For Linux-based systems. source 473 .