<div dir="ltr"><div>Hi everyone, </div><div><br></div><div>I wanted to generate random lines between two spatial points (random points in polygons). The lines should consist of segments (9 segments), after following suggestions I received to my previous post, I ended up using trajectories. My aim now is to restrict these random trajectories (see points in the attachment as an example) to the extent of a polygon (shown in the attachment in yellow). So the trajectories should lie within the polygon.</div><div>Please find the code I used below:</div><div>I first generated a data frame with my start and end point and used it to generate a trajectory (straight line in attachment). I then generated a random trajectory and shifted it so that the start and endpoints were equal to my first trajectory. I transformed the matrices to a Spatial Data frame to be able to plot it. Does anyone know how I can restrict the extent of the trajectory that I randomly generate?</div><div><br></div><div>#coordinates of start and end point and time steps </div><div>x<-c(1649786,-1636500)</div><div>y<-c(-2902593,738500)</div><div>times<-c(0,9)</div><div>start_end_points<-as.data.frame(cbind(x,y,times))</div><div><br></div><div># generate a trajectory between start and endpoint</div><div>trj<-TrajFromCoords(point_trj,xCol=1,yCol=2,timeCol=3, spatialUnits="m", timeUnits="d")</div><div><br></div><div># generate a random trajectory with 9 segments</div><div>track<-TrajGenerate(n=9, random=T, stepLength=TrajLength(trj)/9)</div><div><br></div><div># To be able to use StartEndTranslate transform trajectories into matrices</div><div>ma1<-as.matrix(trj)</div><div>ma2<-as.matrix(track)</div><div><br></div><div># Translate, rotate and scale the points of traj2 using traj1. The new traj will have the same start and end points as traj1.</div><div>p<-StartEndTranslate(ma1,ma2)</div><div><br></div><div># to check if this worked transform into SpatialDataFrame</div><div># the start and end point of the new matrix are the same as the traj1 which is good, the rest of the points changed as well</div><div>p_df<-as.data.frame(p)</div><div><br></div><div># change lat / longs to nummeric</div><div>p_df$x<-as.numeric(p_df$x)</div><div>p_df$y<-as.numeric(p_df$y)</div><div><br></div><div># generate a spatial dataframe to check if the StartEndTranslate function worked by plotting it</div><div>xy<-p_df[,c(1,2)]</div><div><br></div><div>spdf<-SpatialPointsDataFrame(coords=xy, data=p_df, proj4string = CRS(projection))</div><div><br></div><div>Thank you very much!</div></div><br><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Wed, Feb 6, 2019 at 5:42 PM Barry Rowlingson <<a href="mailto:b.rowlingson@gmail.com">b.rowlingson@gmail.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div dir="ltr"><div dir="ltr"><div dir="ltr"><div dir="ltr"><div>Had another idea which is now implemented...</div><div><br></div><div>Consider any segmented path of segments of lengths L_i at angles A_i. Its endpoint will be the vector sum of those segments, ie at (x,y) = (sum(L_i cos(A_i)), sum(L_i sin(A_i)).</div><div><br></div><div>To create a segmented path to a given (x,y), solve that expression for the angles A_i. In R you can treat this as an optimisation problem - find a set of angles A_i that minimise the distance of the end of the segmented path from the target end point.</div><div><br></div><div>Here's some code that does that for a path from 0,0 to 0,1:<br></div><div><br></div><div>pathit <- function(segments){<br>    obj = function(angles){<br>        dxdy = dxdy(segments, angles)<br>        xerr = dxdy$dx-1<br>        yerr = dxdy$dy<br>        err = sqrt(xerr^2 + yerr^2)<br>        err<br>    }<br>    angles = runif(length(segments), 0 , 2*pi)<br>    optim(angles, obj)<br>}<br><br>dxdy = function(segments, angles){<br>    dx = sum(segments * cos(angles))<br>    dy = sum(segments * sin(angles))<br>    list(dx=dx, dy=dy)<br>}<br><br>plotsegs <- function(segments, angles){<br>    x = rep(NA, length(segments) +1)<br>    y = x<br>    x[1] = 0<br>    y[1] = 0<br>    for(i in 2:(length(segments)+1)){<br>        x[i] = x[i-1] + segments[i-1]*cos(angles[i-1])<br>        y[i] = y[i-1] + segments[i-1]*sin(angles[i-1])<br>    }<br>    cbind(x,y)<br>}<br><br></div><div>This is deliberately written naively for clarity.</div><div><br></div><div>To use, set the segment sizes, optimise, and then plot:<br></div><div><br></div><div> s1 = c(.1,.3,.2,.1,.3,.3,.1)<br> a1 = pathit(s1)<br> plot(plotsegs(s1,a1$par),type="l")<br></div><div><br></div><div>which should show a path of seven segments from 0,0 to 0,1 - since the initial starting values are random the model can find different solutions. Run again for a different path.</div><div><br></div><div>To see what the space of paths looks like, do lots and overplot them:<br></div><div><br></div><div>  lots = lapply(1:1000, function(i)plotsegs(s1,pathit(s1)$par))<br>  plot(c(-.1,1.1),c(-1,1))<br>  p = lapply(lots, function(xy){lines(xy)})<br></div><div><br></div><div>this should show 1000 paths, and illustrates the "ellipse" of path possibles that I mentioned in the previous email.</div><div><br></div><div>Sometimes the optimiser struggles to find a solution and so you should probably test the output from optim for convergence and to make sure the target function is close enough to zero for your purposes.  For the example above most of the time the end point is about 1e-5  from (1,0) but for harder problems such as s = rep(.1, 11) which only has 0.1 of extra "slack" length, the error can be 0.02 and failed convergence. Possibly longer optim runs would help or constraining the angles.</div><div><br></div><div>Anyway, interesting problem....</div><div><br></div><div>Barry</div><div><br></div><div><br></div><div><br> </div><div><br></div><div><br></div><div><br></div></div></div></div></div><br><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Wed, Feb 6, 2019 at 8:23 PM Barry Rowlingson <<a href="mailto:b.rowlingson@gmail.com" target="_blank">b.rowlingson@gmail.com</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div dir="ltr"><div>Do you want to generate these for input into some statistical process, or to generate some test data that looks a bit like real data? I think generating test data isn't too difficult, but anything that you might want to put into a statistical test (eg testing some hypothesis about the birds maximum deviation from the straight line A-B) needs a lot more care in formulating the path generating process.</div><div><br></div><div>Here's some thoughts - if you consider one of the red segments in your map as a piece of string (rather than 10 segments) anchored at the points, then you can stretch it taut with a pencil and draw an ellipse with A and B as the foci. Any path created with that string - taut or slack as in your map - has to strictly lie within the ellipse. Now you can wiggle that string inside that ellipse and create an infinity of paths from A to B of the same length. I'm not sure how you can sample uniformly from that infinity such that any path has an equal sampling probability. Your problem is similar but has the additional rigid segment constraint.<br></div><div><br></div><div>Any two adjacent segments of a chain, eg 1----2-------3, as long as it isn't taut (ie straight) can be perturbed by holding 1 and 3 still and moving 2 to the "mirror image" point over the straight line from 1 to 3. You can also take three segments 1--2--3--4 and hold 1 and 4 still and perturb 2 and 3 fairly easily. In this way you could set up an initial chain and then run multiple perturbations on the chain to get a "random" chain, but quite what set of all chains it would be a sample from is not clear. It could at least generate reasonable looking paths, but I wouldn't want to test a hypothesis against it.</div><div><br></div><div>I'm going to generate a path from my office to my home now.</div><div><br></div><div>Barry</div><div><br></div><div><br></div><div><br></div><div><br></div><div> <br></div></div><br><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Wed, Feb 6, 2019 at 7:50 PM Hannah Justen <<a href="mailto:justen@tamu.edu" target="_blank">justen@tamu.edu</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">



<div>
<div dir="ltr">
<div>Hello everyone,</div>
<div><br>
</div>
<div>Thank you very much for the suggestions.<br>
</div>
<div><br>
</div>
<div>Regarding more details (please also see attached figure): </div>
<div>I would like to simulate a bird's migration between breeding (starting polygon - blue in the figure) and wintering grounds (end polygon - green in the figure). The lines can start from anywhere within the starting polygon and end anywhere in the end polygon.
 The lines shall consist of 10 connected segments with variable length between 300 and 1000 km (see red lines in figure; two examples of possible lines with 10 segments between the polygons). </div>
<div><br>
</div>
<div>Thank you very much for you help,</div>
<div>Hannah</div>
<div><br>
</div>
<div>
<div>---</div>
<div>
<div id="gmail-m_8953074041128193128gmail-m_106539024601673784gmail-m_8008441784220442700gmail-m_-7234974033412031627gmail-m_2312489617594898512divtagdefaultwrapper" style="color:rgb(0,0,0);font-family:Calibri,Helvetica,sans-serif,EmojiFont,"Apple Color Emoji","Segoe UI Emoji",NotoColorEmoji,"Segoe UI Symbol","Android Emoji",EmojiSymbols;font-size:16px">
<font size="3" face="Calibri,Helvetica,sans-serif,EmojiFont,Apple Color Emoji,Segoe UI Emoji,NotoColorEmoji,Segoe UI Symbol,Android Emoji,EmojiSymbols" color="black"><span id="gmail-m_8953074041128193128gmail-m_106539024601673784gmail-m_8008441784220442700gmail-m_-7234974033412031627gmail-m_2312489617594898512divtagdefaultwrapper" style="font-size:12pt">PhD
 Student |</span></font><span style="font-size:12pt">Ecology and Evolutionary Biology</span></div>
</div>
<div id="gmail-m_8953074041128193128gmail-m_106539024601673784gmail-m_8008441784220442700gmail-m_-7234974033412031627gmail-m_2312489617594898512divtagdefaultwrapper" style="color:rgb(0,0,0);font-family:Calibri,Helvetica,sans-serif,EmojiFont,"Apple Color Emoji","Segoe UI Emoji",NotoColorEmoji,"Segoe UI Symbol","Android Emoji",EmojiSymbols;font-size:16px">
<span style="font-size:12pt">Texas A&M University</span></div>
</div>
</div>
<br>
<div class="gmail_quote">
<div dir="ltr" class="gmail_attr">On Wed, Feb 6, 2019 at 5:12 AM Barry Rowlingson <<a href="mailto:b.rowlingson@lancaster.ac.uk" target="_blank">b.rowlingson@lancaster.ac.uk</a>> wrote:<br>
</div>
<blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">
<div dir="ltr">
<div>Interesting, but I think we need more details...</div>
<div><br>
</div>
<div>Do the lines have to start and finish at specific locations in the polygons - like the centroid, or anywhere?
<br>
</div>
<div><br>
</div>
<div>So one line might be 3 segments of 10km each connecting two polygon centroids that are 15km apart? Imagining three rigid rods of length 10 connected at their ends and with the first and last also connected to two fixed points tells me there's an infinite
 number of possible solutions. There's probably also a number of ways of sampling from those solutions. Its going to get very complicated with a larger number of segments.
<br>
</div>
<div><br>
</div>
<div>Hmmmmm.....</div>
<div><br>
</div>
<div>Barry</div>
<div><br>
</div>
<div><br>
</div>
<div><br>
</div>
</div>
<br>
<div class="gmail_quote">
<div dir="ltr" class="gmail_attr">On Tue, Feb 5, 2019 at 11:30 PM Hannah Justen <<a href="mailto:justen@tamu.edu" target="_blank">justen@tamu.edu</a>> wrote:<br>
</div>
<blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">
Hi everyone,<br>
<br>
I am studying migratory tracks of birds for my dissertation and I would<br>
like to model possible pathways between two polygons. Therefore, I would<br>
like to sample random lines between the polygons. These lines can differ in<br>
total length but should consist of x - number of fragments of equal length.<br>
Each fragment can have slightly different orientation but overall the lines<br>
should connect the two polygons.<br>
<br>
I fail to find the appropriate R package that will allow me to do this type<br>
of analysis. Does anyone have a suggestion how to approach analysis?<br>
<br>
Thank you,<br>
Hannah<br>
<br>
---<br>
PhD Student |Ecology and Evolutionary Biology<br>
Texas A&M University<br>
<br>
        [[alternative HTML version deleted]]<br>
<br>
_______________________________________________<br>
R-sig-Geo mailing list<br>
<a href="mailto:R-sig-Geo@r-project.org" target="_blank">R-sig-Geo@r-project.org</a><br>
<a href="https://urldefense.proofpoint.com/v2/url?u=https-3A__stat.ethz.ch_mailman_listinfo_r-2Dsig-2Dgeo&d=DwMFaQ&c=ODFT-G5SujMiGrKuoJJjVg&r=JTKhaSJXwF2BxCfjjnt61w&m=RH21jOLOEbLLudn70kOTH0wnklnKHk-tFm9cxjxAB9k&s=H_HhNMga7aaqbnNsWexqY1jdRFFo7zO_m9xvk2awODo&e=" rel="noreferrer" target="_blank">https://stat.ethz.ch/mailman/listinfo/r-sig-geo</a><br>
</blockquote>
</div>
</blockquote>
</div>
</div>

</blockquote></div>
</blockquote></div>
</blockquote></div>