acer

32328 Reputation

29 Badges

19 years, 317 days
Ontario, Canada

Social Networks and Content at Maplesoft.com

MaplePrimes Activity


These are replies submitted by acer

@Anthrazit Your string collection omitted the opening and closing square brackets, needed so that after parsing a list would be passed to Join.

joinStr_ac.mw

This is an example of what I meant about confusing multiple concatenation, since all the little fiddly strings are wrapped in their own quotes. I think that an sprintf format is more legible and less error-prone.

@Thomas Richard Thanks for the detail.

I mentioned those two particular versions because I believe those are the two that the OP uses.

@Carl Love For the sake of completeness, I'll mention that the collapsed calling sequence for a multiple integral can be more than just a syntactic convenience (versus the iterated calling sequence).

When computing the value, the ranges of the outer variables can be used during the computation of the inner integrals, via assumptions on the relevant names of the outer variables of integration. It turns out that this can quite often be useful, and the collapsed form is used in some VectorCalculus and MultivariateCalculus in Maple 2020.

@mmcdara I think that I didn't understand your original goal. Based on the original code you gave (and with those R commands slightly in mind) I had the impression that you were trying to get a kernel-density-plot based on given Samples, rather than from symbolic RVs.

Hence the suggestions to try surfdata with dimension=2, and direct writing to an Image format, etc. I didn't mention plots:-listdensityplot, which has a possibly useful smooth=false choice but lacks the convenience of surfdata to specify the ranges for the axes. I was working on the presumption that one would be starting from (only) samples of unknown distributions. I suppose there may be room for both goals.

It might be interesting to tune up your scheme for using PDF and the symbolid RVs. As is, each call to KD2D calls the K procedure N times, and each K call generates its own procedure as return value, and each call to those returns call the f procedure twice, and each call to the f procedure generates its own procedure as return value. Alas I don't have any time for that fun these days.

I notice that you bumped down your Sample size to N=10^3, perhaps for time cost and perhaps also because at N=10^4 the points occlude the filled color gradient of the density plot. And they collide so much that the visual gradient is lost. (BTW, you could switch the order of plots in the display, so that at least the black lines of the contours lay in front of the possibly dense scatter-point rendering.)

So here is a quick little thing. In the case of a large Sample there is some visual benefit to plotting a scattering using points smaller than symbolsize=1. By replacing the points with very thin and short lines we can get a more visually distinguishable mist.

restart:

with(plots): with(Statistics):

f := (m, s) -> unapply(PDF(Normal(m, s), t), t):
K := (mx, my, sx, sy) -> (x, y) -> f(mx, sx)(x) * f(my, sy)(y):

N := 10^3:
A := Sample(RandomVariable(BetaDistribution(2, 3)), N*60):
B := Sample(RandomVariable(BetaDistribution(3, 2)), N*60):
h := 0.07:
KD2D := (x, y) -> add(K(A[n], B[n], h, h)(x, y), n=1..N)/N:

CP := contourplot(KD2D(x, y), x=0..1, y=0..1, view=[0..1, 0..1],
                  filled=true, coloring=["MediumBlue", "White"],
                  contourlabels=false, thickness=0):

SP := ScatterPlot(A, B, symbol=point, color="Gold", symbolsize=1):

dat := op([1,1],SP):
newSP := subsop([1,1]=Matrix(3*op([1,1],dat),op([1,2],dat),
                             (i,j)->`if`(irem(i,3)=1,dat[(i+2)/3,j],
                                         `if`(irem(i,3)=2,1e-3+dat[(i+1)/3,j],
                                              Float(undefined)))),
                subsindets(SP,specfunc(anything,STYLE),
                           ()->[STYLE(LINE),THICKNESS(2)][])):

display(Array([display(SP, CP, size=[400,400]),
               display(newSP, CP, size=[400,400])]));

 

 

 

 

 

 

Download 2D_density_plot_with_Kernel_ac0.mw

I made no changes for efficiency to the earlier code. And I would assemble the replacement Matrix of plotting data differently -- using BlockCopy rather than an initializer with nested `if` calls. And one has to be very careful with the scaling of the short, thin lines relative to the plot view, or else weird visual effects can occur. This is not production level code. I'm really just trying to show that I like the idea of symbolsize=0.1 and so on. In these situations the plot may look less like it was drawn with crayons.

 

I don't see any information in your attachment that could be used to restore anything.

You wrote of some "given two dimensional functions" (emphasis mine).

If that means that you have those functions -- either as formulas or as means to compute at arbitrary x-y values -- then you might be able to sensibly use those to solve it as an optimization problem.

If you don't have those functions then note that the largest distance between the two represented curves may very well not occur at any of the known x[i],y[i] points. If the data points are fine enough then you might be satisfied by optimization of the difference of a pair or corresponding spline interpolations. You might be able to estimate error bounds on that (usually requiring some smoothness, etc).

Your Question lacks detail.

@mmcdara The link of your latest attachment isn't accessible for me, perhaps due to using "+" in the filename.

@sand15 If you wish to try smoothing via convolution then (for efficiency) you could look at the Convolution command from ImageTools.

I was also wondering a little about possibly using Threshold as a poor man's 2D bin separator. Of course it might be quite inefficient to perform multiple passes, in the case that one did not want just a few bins. But it's already there, and reasonably quick.

@mmcdara That link to R code showed some functionality involving contours overlaid with a density plot.

I've noticed in the past that neither 2D surfdata (working from 2D data, using dimension=2) nor densityplot (working from a bivariate function) allow for style=contour or style=surfacecontour, in a way similar to how they work for style=surface.

And it's not just the commands; the GUI renderer simply rejects STYLE(CONTOUR) as substructure in this case of a GRID & COLOR within a 2D PLOT structure.

But you can create an interpolant from the data, and generate the 2D contour plot from that.

restart:

interface(version);

`Standard Worksheet Interface, Maple 2020.1, Linux, June 8 2020 Build ID 1474533`

with(Statistics):

UseHardwareFloats := false:
N := 10^5:
A := Sample(RandomVariable(BetaDistribution(2, 6)), N):
B := Sample(RandomVariable(BetaDistribution(6, 2)), N):
nb := 100:
mA := min(A):
hA := Range(A)/(nb-1):
mB := min(B):
hB := Range(B)/(nb-1):
cA := floor~((A-~mA)/~hA)+~1:
cB := floor~((B-~mB)/~hB)+~1:
NP := Matrix(nb$2, 0):
for n from 1 to N do
  NP[cA[n], cB[n]] := NP[cA[n], cB[n]]+1
end do:

DP:=plots:-surfdata(NP, mB..max(B), mA..max(A), dimension=2,
  colorscheme=["Blue", "White", "Red"],
  style=patchnogrid,labels=["A", "B"], size=[475,450],
  axis[1]=[tickmarks=[mB, max(B)]], axis[2]=[tickmarks=[mA, max(A)]]):

UseHardwareFloats := deduced:
H:=Interpolation:-LinearInterpolation([[seq(mA+(i-1)*(max(A)-mA)/(nb-1),i=1..nb)],
                                      [seq(mB+(i-1)*(max(B)-mB)/(nb-1),i=1..nb)]],
                                     NP):

DC := plots:-contourplot((x,y)->H(x,y),mA..max(A),mB..max(B), grid=[120,120],
                         color=black, contours=7, thickness=0):

RAW:=ImageTools:-Rotate(op([2],indets(DP,specfunc(anything,COLOR))[1]),'left'):

DPimg := plot(mA..max(A), mB..max(B),
     background=ImageTools:-Scale(RAW,1..400,method=nearest),
     size=[475,450], axes=boxed, labels=["A", "B"],
     axis[1]=[tickmarks=[mB, max(B)]], axis[2]=[tickmarks=[mA, max(A)]]):

plots:-display(DPimg,DC);

 

Download 2D_density_plot_contour_ac.mw

I think that it would be an improvement if the GUI renderer allowed for this functionality directly, respecting STYLE(CONTOUR) or STYLE(PATCHCONTOUR).

Don't delete the full body of the original question. Here it is below:

Write a set of Maple procedures to perform the standard arithmetic operations on polynomials of a single variable with rational coefficients:

AddPolynomial(<poly1>,<poly2>) returns the sum SubPolynomial(<poly1>,<poly2>) returns the difference MultPolynomial(<poly1>,<poly2>) returns the product DivPolynomial(<poly1>,<poly2>) returns a list [<quotient>,<remainder>] GcdPolynomial(<poly1>,<poly2>), where deg(poly1) ≥ deg(poly2), returns the gcd

Begin by writing a utility procedure called CoeffList that converts a Maple polynomial into a list of its coefficients. For example, CoeffList(1/6*x^3 - 1/2*x^2 + x - 1) should return the list [1/6, -1/2, 1, -1].

Your arithmetic procedures should operate on, and return, lists that are in CoeffList format. Leading zero coefficients should be suppressed.

You can use Maple's facilities for arithmetic on rational numbers, but not for polynomial manipulation.

Following the same convention as Maple, GcdPolynomial should return a polynomial with integer coefficients if both of its arguments have integer coefficients, otherwise return a monic polynomial with rational coefficients.

Feel free to add to the original Question, by editing it or posting a Comment/Reply. Don't delete the full body of the original question. Here it is below:

1. Consider this code line: > a := b; b := c; c := matrix([[1, 2, 3], [3, 4, 5]]);
    • if you ask Maple to return the values assigned to a, b and c, which values will be printed?
    • Are these values the ones you would expect? Why? Which kind of evaluation rule is utilized by Maple to return these values?
   • Show the single steps of the evaluation process and briefly explain the outcome of each evaluation step (hint: use eval (a, 1/2/3), to return each evaluation step).
   • How can you “force” Maple to return the “expected” values for a, b and c? • Extract the first row of the matrix in such a way to have [1, 2, 3] as output. Hint: use the command row/Row and its right syntax (it needs two arguments: the name of the matrix and the number of the row to extract). Be careful to load the linalg/LinearAlgebra package before using the command. Instruction: apply the row/Row command to a, b and c.
  • Can you explain what Maple does in the previous step? Can you explain, in other words, why you get the expected outcome? Hint: remember which are the “drivers” of the evaluation process in Maple (position of the assignment/level of evaluation; type of object / data-structure / datacontainer / procedures / local versus global variables / use of built-in commands, etc.).

Duplicate postings of this in other Question threads will be flagged as such and may be deleted.

How far have you gotten so far with this coursework task?

Have you succeeded in "writing a utility procedure called CoeffList that converts a Maple polynomial into a list of its coefficients"?

@Carl Love In my Answer I used a nontrivial example instead, in which there is a possibility of optimization in computing the entry values. For a Matrix return (in the Maple language) the optimize option does not act, but it does for a listlist. And for both kinds of Maple structure the Matlab return structure is of the same kind. And so there can indeed be merit to passing the option.

@tomleslie Your comment is also about a situation related to need of local declaration, but a different situation, that is quite different from that of the OP which is primarily about the status of procedure parameters.

I just happened to make an aside, in my Answer, about an unused local and which of nm's two procs was "better". But IMO that really wasn't the central topic of the Question. (Joe's Answer also is about unused locals which -- while checking for such relates to the latter, lesser part of the Question in a roundabout causal way -- otherwise doesnt explain the primary Question asked, IMO.)

First 147 148 149 150 151 152 153 Last Page 149 of 591