text:
Question: Is a number within a set of ranges?
0
11.8 years ago by
Daniel Brewer1.9k
Daniel Brewer1.9k wrote:
I have a table with a start and stop column which defines a set of ranges. I have another table with a list of genes with associated position. What I would like to do is subset the gene table so it only contains genes whose position is within any of the ranges. What is the best way to do this? The only way I can think of is to construct a long list of conditions linked by ORs but I am sure there must be a better way. Simple example: Start Stop 1 3 5 9 13 15 Gene Position 1 14 2 4 3 10 4 6 I would like to get out: Gene Position 1 14 4 6 Any ideas? Thanks Dan -- ************************************************************** Daniel Brewer, Ph.D. Institute of Cancer Research Email: daniel.brewer at icr.ac.uk ************************************************************** The Institute of Cancer Research: Royal Cancer Hospital, a charitable Company Limited by Guarantee, Registered in England under Company No. 534147 with its Registered Office at 123 Old Brompton Road, London SW7 3RP. This e-mail message is confidential and for use by the a...{{dropped:2}}
cancer • 738 views
modified 11.8 years ago • written 11.8 years ago by Daniel Brewer1.9k
Answer: Is a number within a set of ranges?
0
11.8 years ago by
Artur Veloso340
Artur Veloso340 wrote:
An embedded and charset-unspecified text was scrubbed... Name: not available Url: https://stat.ethz.ch/pipermail/bioconductor/attachments/20071029/ ed7b606c/attachment.pl
You can use cut (?cut) defining the breaks from your ranges, as they are non-overlapping. Regards, Carlos J. Gil Bellosta http://www.datanalytics.com > On 10/29/07, Daniel Brewer <daniel.brewer at="" icr.ac.uk=""> wrote: > > > > I have a table with a start and stop column which defines a set of > > ranges. I have another table with a list of genes with associated > > position. What I would like to do is subset the gene table so it only > > contains genes whose position is within any of the ranges. What is the > > best way to do this? The only way I can think of is to construct a long > > list of conditions linked by ORs but I am sure there must be a better way. > > > > Simple example: > > > > Start Stop > > 1 3 > > 5 9 > > 13 15 > > > > Gene Position > > 1 14 > > 2 4 > > 3 10 > > 4 6 > > > > I would like to get out: > > Gene Position > > 1 14 > > 4 6 > > > > Any ideas? > > > > Thanks > > > > Dan > > > > -- > > ************************************************************** > > Daniel Brewer, Ph.D. > > Institute of Cancer Research > > Email: daniel.brewer at icr.ac.uk > > ************************************************************** > > > > The Institute of Cancer Research: Royal Cancer Hospital, a charitable > > Company Limited by Guarantee, Registered in England under Company No. 534147 > > with its Registered Office at 123 Old Brompton Road, London SW7 3RP. > > > > This e-mail message is confidential and for use by the...{{dropped:13}} > > _______________________________________________ > Bioconductor mailing list > Bioconductor at stat.math.ethz.ch > https://stat.ethz.ch/mailman/listinfo/bioconductor > Search the archives: http://news.gmane.org/gmane.science.biology.informatics.conductor >
You would like to avoid loops here, especially nested loops: this is what apply, sapply etc are for. Using your syntax: final.presence = apply(gene, 1, function(x) any(x[2]>=place$start & x[2]<=place$end)) - Dr Oleg Sklyar * EMBL-EBI, Cambridge CB10 1SD, UK * +441223494466 On Mon, 2007-10-29 at 12:42 -0500, Artur Veloso wrote: > Hi Daniel, > > I'm very new to R and I'm far from a good programmer, but I think that this > small script should solve your problem. Well, at least for the example you > provided it worked. I hope it helps. > > Cheers, > > Artur > > > start <- c(1,5,13) > > stop <- c(3,9,15) > > place <- data.frame(start,stop) > > > > gene <- c(1,2,3,4) > > position <- c(14,4,10,6) > > position <- data.frame(gene,position) > > > > range <- list() > > for(a in 1:dim(place)[1]) > + range[[a]] <- seq(place$start[a],place$stop[a]) > > > > presence <- NULL > > final.presence <- NULL > > for(b in position$position) > + { > + for(c in 1:length(range)) > + { > + presence <- c(presence,b%in%range[[c]]) > + } > + final.presence <- c(final.presence,as.logical(sum(presence))) > + presence <- NULL > + } > > > > position[final.presence,] > gene position > 1 1 14 > 4 4 6 > > > On 10/29/07, Daniel Brewer <daniel.brewer at="" icr.ac.uk=""> wrote: > > > > I have a table with a start and stop column which defines a set of > > ranges. I have another table with a list of genes with associated > > position. What I would like to do is subset the gene table so it only > > contains genes whose position is within any of the ranges. What is the > > best way to do this? The only way I can think of is to construct a long > > list of conditions linked by ORs but I am sure there must be a better way. > > > > Simple example: > > > > Start Stop > > 1 3 > > 5 9 > > 13 15 > > > > Gene Position > > 1 14 > > 2 4 > > 3 10 > > 4 6 > > > > I would like to get out: > > Gene Position > > 1 14 > > 4 6 > > > > Any ideas? > > > > Thanks > > > > Dan > > > > -- > > ************************************************************** > > Daniel Brewer, Ph.D. > > Institute of Cancer Research > > Email: daniel.brewer at icr.ac.uk > > ************************************************************** > > > > The Institute of Cancer Research: Royal Cancer Hospital, a charitable > > Company Limited by Guarantee, Registered in England under Company No. 534147 > > with its Registered Office at 123 Old Brompton Road, London SW7 3RP. > > > > This e-mail message is confidential and for use by the...{{dropped:13}} > > _______________________________________________ > Bioconductor mailing list > Bioconductor at stat.math.ethz.ch > https://stat.ethz.ch/mailman/listinfo/bioconductor > Search the archives: http://news.gmane.org/gmane.science.biology.informatics.conductor ADD REPLYlink written 11.8 years ago by Oleg Sklyar260 In this case you don't gain much if anything by using apply(), which is just a nice wrapper to a for() loop (and the bad rap that for loops have in R isn't really applicable these days). The real gain to be had is from vectorizing the comparison. Best, Jim Oleg Sklyar wrote: > You would like to avoid loops here, especially nested loops: this is > what apply, sapply etc are for. Using your syntax: > > final.presence = apply(gene, 1, function(x) any(x[2]>=place$start & > x[2]<=place$end)) > > - > Dr Oleg Sklyar * EMBL-EBI, Cambridge CB10 1SD, UK * +441223494466 > > > On Mon, 2007-10-29 at 12:42 -0500, Artur Veloso wrote: >> Hi Daniel, >> >> I'm very new to R and I'm far from a good programmer, but I think that this >> small script should solve your problem. Well, at least for the example you >> provided it worked. I hope it helps. >> >> Cheers, >> >> Artur >> >>> start <- c(1,5,13) >>> stop <- c(3,9,15) >>> place <- data.frame(start,stop) >>> >>> gene <- c(1,2,3,4) >>> position <- c(14,4,10,6) >>> position <- data.frame(gene,position) >>> >>> range <- list() >>> for(a in 1:dim(place)[1]) >> + range[[a]] <- seq(place$start[a],place$stop[a]) >>> presence <- NULL >>> final.presence <- NULL >>> for(b in position$position) >> + { >> + for(c in 1:length(range)) >> + { >> + presence <- c(presence,b%in%range[[c]]) >> + } >> + final.presence <- c(final.presence,as.logical(sum(presence))) >> + presence <- NULL >> + } >>> position[final.presence,] >> gene position >> 1 1 14 >> 4 4 6 >> >> >> On 10/29/07, Daniel Brewer <daniel.brewer at="" icr.ac.uk=""> wrote: >>> I have a table with a start and stop column which defines a set of >>> ranges. I have another table with a list of genes with associated >>> position. What I would like to do is subset the gene table so it only >>> contains genes whose position is within any of the ranges. What is the >>> best way to do this? The only way I can think of is to construct a long >>> list of conditions linked by ORs but I am sure there must be a better way. >>> >>> Simple example: >>> >>> Start Stop >>> 1 3 >>> 5 9 >>> 13 15 >>> >>> Gene Position >>> 1 14 >>> 2 4 >>> 3 10 >>> 4 6 >>> >>> I would like to get out: >>> Gene Position >>> 1 14 >>> 4 6 >>> >>> Any ideas? >>> >>> Thanks >>> >>> Dan >>> >>> -- >>> ************************************************************** >>> Daniel Brewer, Ph.D. >>> Institute of Cancer Research >>> Email: daniel.brewer at icr.ac.uk >>> ************************************************************** >>> >>> The Institute of Cancer Research: Royal Cancer Hospital, a charitable >>> Company Limited by Guarantee, Registered in England under Company No. 534147 >>> with its Registered Office at 123 Old Brompton Road, London SW7 3RP. >>> >>> This e-mail message is confidential and for use by the...{{dropped:13}} >> _______________________________________________ >> Bioconductor mailing list >> Bioconductor at stat.math.ethz.ch >> https://stat.ethz.ch/mailman/listinfo/bioconductor >> Search the archives: http://news.gmane.org/gmane.science.biology.informatics.conductor > > _______________________________________________ > Bioconductor mailing list > Bioconductor at stat.math.ethz.ch > https://stat.ethz.ch/mailman/listinfo/bioconductor > Search the archives: http://news.gmane.org/gmane.science.biology.informatics.conductor -- James W. MacDonald, M.S. Biostatistician Affymetrix and cDNA Microarray Core University of Michigan Cancer Center 1500 E. Medical Center Drive 7410 CCGC Ann Arbor MI 48109 734-647-5623
It's about both, and in fact after scrolling down I noticed that we came up with exactly the same solution :) - Dr Oleg Sklyar * EMBL-EBI, Cambridge CB10 1SD, UK * +441223494466 On Mon, 2007-10-29 at 16:44 -0400, James W. MacDonald wrote: > In this case you don't gain much if anything by using apply(), which is > just a nice wrapper to a for() loop (and the bad rap that for loops have > in R isn't really applicable these days). > > The real gain to be had is from vectorizing the comparison. > > Best, > > Jim > > > > Oleg Sklyar wrote: > > You would like to avoid loops here, especially nested loops: this is > > what apply, sapply etc are for. Using your syntax: > > > > final.presence = apply(gene, 1, function(x) any(x[2]>=place$start & > > x[2]<=place$end)) > > > > - > > Dr Oleg Sklyar * EMBL-EBI, Cambridge CB10 1SD, UK * +441223494466 > > > > > > On Mon, 2007-10-29 at 12:42 -0500, Artur Veloso wrote: > >> Hi Daniel, > >> > >> I'm very new to R and I'm far from a good programmer, but I think that this > >> small script should solve your problem. Well, at least for the example you > >> provided it worked. I hope it helps. > >> > >> Cheers, > >> > >> Artur > >> > >>> start <- c(1,5,13) > >>> stop <- c(3,9,15) > >>> place <- data.frame(start,stop) > >>> > >>> gene <- c(1,2,3,4) > >>> position <- c(14,4,10,6) > >>> position <- data.frame(gene,position) > >>> > >>> range <- list() > >>> for(a in 1:dim(place)[1]) > >> + range[[a]] <- seq(place$start[a],place$stop[a]) > >>> presence <- NULL > >>> final.presence <- NULL > >>> for(b in position$position) > >> + { > >> + for(c in 1:length(range)) > >> + { > >> + presence <- c(presence,b%in%range[[c]]) > >> + } > >> + final.presence <- c(final.presence,as.logical(sum(presence))) > >> + presence <- NULL > >> + } > >>> position[final.presence,] > >> gene position > >> 1 1 14 > >> 4 4 6 > >> > >> > >> On 10/29/07, Daniel Brewer <daniel.brewer at="" icr.ac.uk=""> wrote: > >>> I have a table with a start and stop column which defines a set of > >>> ranges. I have another table with a list of genes with associated > >>> position. What I would like to do is subset the gene table so it only > >>> contains genes whose position is within any of the ranges. What is the > >>> best way to do this? The only way I can think of is to construct a long > >>> list of conditions linked by ORs but I am sure there must be a better way. > >>> > >>> Simple example: > >>> > >>> Start Stop > >>> 1 3 > >>> 5 9 > >>> 13 15 > >>> > >>> Gene Position > >>> 1 14 > >>> 2 4 > >>> 3 10 > >>> 4 6 > >>> > >>> I would like to get out: > >>> Gene Position > >>> 1 14 > >>> 4 6 > >>> > >>> Any ideas? > >>> > >>> Thanks > >>> > >>> Dan > >>> > >>> -- > >>> ************************************************************** > >>> Daniel Brewer, Ph.D. > >>> Institute of Cancer Research > >>> Email: daniel.brewer at icr.ac.uk > >>> ************************************************************** > >>> > >>> The Institute of Cancer Research: Royal Cancer Hospital, a charitable > >>> Company Limited by Guarantee, Registered in England under Company No. 534147 > >>> with its Registered Office at 123 Old Brompton Road, London SW7 3RP. > >>> > >>> This e-mail message is confidential and for use by the...{{dropped:13}} > >> _______________________________________________ > >> Bioconductor mailing list > >> Bioconductor at stat.math.ethz.ch > >> https://stat.ethz.ch/mailman/listinfo/bioconductor > >> Search the archives: http://news.gmane.org/gmane.science.biology.informatics.conductor > > > > _______________________________________________ > > Bioconductor mailing list > > Bioconductor at stat.math.ethz.ch > > https://stat.ethz.ch/mailman/listinfo/bioconductor > > Search the archives: http://news.gmane.org/gmane.science.biology.informatics.conductor > ADD REPLYlink written 11.8 years ago by Oleg Sklyar260 Answer: Is a number within a set of ranges? 0 11.8 years ago by Sean Davis21k United States Sean Davis21k wrote: Daniel Brewer wrote: > I have a table with a start and stop column which defines a set of > ranges. I have another table with a list of genes with associated > position. What I would like to do is subset the gene table so it only > contains genes whose position is within any of the ranges. What is the > best way to do this? The only way I can think of is to construct a long > list of conditions linked by ORs but I am sure there must be a better way. > > Simple example: > > Start Stop > 1 3 > 5 9 > 13 15 > > Gene Position > 1 14 > 2 4 > 3 10 > 4 6 > > I would like to get out: > Gene Position > 1 14 > 4 6 > > Any ideas? Here is a function that I use for finding overlapping segments. It takes two data.frames, x and y. Each must have "Chr", "Position", and "end" columns (often used in conjunction with snapCGH--hence, the Position rather than "start"). The "shift" parameter is a convenience function for doing "random shift" random distributions of genomic segments. The function returns the indexes of x and y that overlap. So, if the first row of the x data.frame overlaps with the first 3 rows of y, the output will be: Xindex Yindex 1 1 1 2 1 3 Note that the data.frames can have more than those three columns, but those three columns MUST be present and named as mentioned. Hope this helps. Sean Attached function below ----------------------- findOverlappingSegments <- function(x,y,shift=0) { swap <- nrow(x)<nrow(y) #="" want="" to="" have="" larger="" set="" first="" for="" speed="" if(swap)="" {="" tmpx="" <-="" x="" x="" <-="" y="" y="" <-="" tmpx="" }="" intersectchrom="" <-="" intersect(x$chr,y$chr)="" ret="" <-="" list()="" for(i="" in="" intersectchrom)="" {="" aindex="" <-="" which(y$chr="=i)" bindex="" <-="" which(x$chr="=i)" a="" <-="" y[aindex,]="" b="" <-="" x[bindex,]="" overlapsbrow="" <-="" mapply(function(astart,="" aend)="" {="" which((astart="" <="b$end" &="" astart="">=b$Position) | (Aend <= b$end & Aend>=b$Position) | (Astart <= b$Position & Aend>=b$end) | (Astart >= b$Position & Aend<=b$end)) },a$Position+shift,a$end+shift) tmp1 <- unlist(overlapsBrow) xindex <- bindex[tmp1] yindex <- aindex[rep(1:nrow(a),sapply(overlapsBrow,length,simplify=TRUE))] if(swap) { ret[[i]]<- cbind(yindex,xindex) } else { ret[[i]] <- cbind(xindex,yindex) } colnames(ret[[i]]) <- c('Xindex','Yindex') } return(do.call(rbind,ret)) } ADD COMMENTlink written 11.8 years ago by Sean Davis21k Or a more simplistic alternative that will work with the data provided: > mat <- matrix(c(1,5,13,3,9,15), ncol=2) > gn <- matrix(c(14,4,10,6), ncol=1) > a <- apply(gn, 1, function(x) any(x > mat[,1] & x < mat[,2])) > gn[a,] [1] 14 6 Best, Jim Sean Davis wrote: > Daniel Brewer wrote: >> I have a table with a start and stop column which defines a set of >> ranges. I have another table with a list of genes with associated >> position. What I would like to do is subset the gene table so it only >> contains genes whose position is within any of the ranges. What is the >> best way to do this? The only way I can think of is to construct a long >> list of conditions linked by ORs but I am sure there must be a better way. >> >> Simple example: >> >> Start Stop >> 1 3 >> 5 9 >> 13 15 >> >> Gene Position >> 1 14 >> 2 4 >> 3 10 >> 4 6 >> >> I would like to get out: >> Gene Position >> 1 14 >> 4 6 >> >> Any ideas? > > Here is a function that I use for finding overlapping segments. It > takes two data.frames, x and y. Each must have "Chr", "Position", and > "end" columns (often used in conjunction with snapCGH--hence, the > Position rather than "start"). The "shift" parameter is a convenience > function for doing "random shift" random distributions of genomic > segments. The function returns the indexes of x and y that overlap. > So, if the first row of the x data.frame overlaps with the first 3 rows > of y, the output will be: > > Xindex Yindex > 1 1 > 1 2 > 1 3 > > Note that the data.frames can have more than those three columns, but > those three columns MUST be present and named as mentioned. > > Hope this helps. > > Sean > > Attached function below > ----------------------- > > findOverlappingSegments <- > function(x,y,shift=0) { > swap <- nrow(x)<nrow(y) #="" want="" to="" have="" larger="" set="" first="" for="" speed=""> if(swap) { > tmpx <- x > x <- y > y <- tmpx > } > intersectChrom <- intersect(x$Chr,y$Chr) > ret <- list() > for(i in intersectChrom) { > aindex <- which(y$Chr==i) > bindex <- which(x$Chr==i) > a <- y[aindex,] > b <- x[bindex,] > overlapsBrow <- mapply(function(Astart, Aend) { > which((Astart <= b$end & Astart>=b$Position) | > (Aend <= b$end & Aend>=b$Position) | > (Astart <= b$Position & Aend>=b$end) | > (Astart >= b$Position & Aend<=b$end)) > },a$Position+shift,a$end+shift) > tmp1 <- unlist(overlapsBrow) > xindex <- bindex[tmp1] > yindex <- > aindex[rep(1:nrow(a),sapply(overlapsBrow,length,simplify=TRUE))] > if(swap) { > ret[[i]]<- cbind(yindex,xindex) > } else { > ret[[i]] <- cbind(xindex,yindex) > } > colnames(ret[[i]]) <- c('Xindex','Yindex') > } > return(do.call(rbind,ret)) > } > > _______________________________________________ > Bioconductor mailing list > Bioconductor at stat.math.ethz.ch > https://stat.ethz.ch/mailman/listinfo/bioconductor > Search the archives: http://news.gmane.org/gmane.science.biology.informatics.conductor -- James W. MacDonald, M.S. Biostatistician Affymetrix and cDNA Microarray Core University of Michigan Cancer Center 1500 E. Medical Center Drive 7410 CCGC Ann Arbor MI 48109 734-647-5623 ADD REPLYlink written 11.8 years ago by James W. MacDonald50k Answer: Is a number within a set of ranges? 0 11.8 years ago by United States James W. MacDonald50k wrote: Hi Dan, Daniel Brewer wrote: > I have a table with a start and stop column which defines a set of > ranges. I have another table with a list of genes with associated > position. What I would like to do is subset the gene table so it only > contains genes whose position is within any of the ranges. What is the > best way to do this? The only way I can think of is to construct a long > list of conditions linked by ORs but I am sure there must be a better way. Are you not telling us something here? Because the problem as stated is very simple. Say your matrix below is called mat: index <- mat[,1] < 6 & mat[,2] < 15 Or do you have a whole bunch of ranges to test? Best, Jim > > Simple example: > > Start Stop > 1 3 > 5 9 > 13 15 > > Gene Position > 1 14 > 2 4 > 3 10 > 4 6 > > I would like to get out: > Gene Position > 1 14 > 4 6 > > Any ideas? > > Thanks > > Dan > -- James W. MacDonald, M.S. Biostatistician Affymetrix and cDNA Microarray Core University of Michigan Cancer Center 1500 E. Medical Center Drive 7410 CCGC Ann Arbor MI 48109 734-647-5623 ADD COMMENTlink written 11.8 years ago by James W. MacDonald50k Answer: Is a number within a set of ranges? 0 11.8 years ago by Christos Hatzis90 wrote: > pos <- matrix(c(1, 5, 13, 3, 9, 15), ncol=2) pos [,1] [,2] [1,] 1 3 [2,] 5 9 [3,] 13 15 > gene.pos <- c(14,4,10,6) > gene.pos [1] 14 4 10 6 > within <- sapply(gene.pos, function(g) any(apply(pos, 1, function(x) findInterval(g, x)) == 1)) > gene.pos[within] [1] 14 6 Look at ?findInterval, which does all the work. It returns 1 if within range in this case. -Christos > -----Original Message----- > From: bioconductor-bounces at stat.math.ethz.ch > [mailto:bioconductor-bounces at stat.math.ethz.ch] On Behalf Of > Daniel Brewer > Sent: Monday, October 29, 2007 12:29 PM > To: bioconductor at stat.math.ethz.ch > Subject: [BioC] Is a number within a set of ranges? > > I have a table with a start and stop column which defines a > set of ranges. I have another table with a list of genes > with associated position. What I would like to do is subset > the gene table so it only contains genes whose position is > within any of the ranges. What is the best way to do this? > The only way I can think of is to construct a long list of > conditions linked by ORs but I am sure there must be a better way. > > Simple example: > > Start Stop > 1 3 > 5 9 > 13 15 > > Gene Position > 1 14 > 2 4 > 3 10 > 4 6 > > I would like to get out: > Gene Position > 1 14 > 4 6 > > Any ideas? > > Thanks > > Dan > > -- > ************************************************************** > Daniel Brewer, Ph.D. > Institute of Cancer Research > Email: daniel.brewer at icr.ac.uk > ************************************************************** > > The Institute of Cancer Research: Royal Cancer Hospital, a > charitable Company Limited by Guarantee, Registered in > England under Company No. 534147 with its Registered Office > at 123 Old Brompton Road, London SW7 3RP. > > This e-mail message is confidential and for use by the...{{dropped:13}} ADD COMMENTlink written 11.8 years ago by Christos Hatzis90 Christos Hatzis wrote: >> pos <- matrix(c(1, 5, 13, 3, 9, 15), ncol=2) pos > [,1] [,2] > [1,] 1 3 > [2,] 5 9 > [3,] 13 15 >> gene.pos <- c(14,4,10,6) >> gene.pos > [1] 14 4 10 6 > >> within <- sapply(gene.pos, function(g) any(apply(pos, 1, function(x) > findInterval(g, x)) == 1)) > >> gene.pos[within] > [1] 14 6 Good to know the existence of findInterval(). Thanks! For this particular case though, I would be tempted to keep things simple by replacing this any(apply(pos, 1, function(x) findInterval(g, x)) == 1) by any(apply(pos, 1, function(x) x[1] <= g && g <= x[2])) Not only is the later easier to understand, but with the former, you'll get wrong results if one of your genes is positioned at one of the Stop positions: gene.pos <- c(14,4,10,6,15) # last gene is at a Stop position # using findInterval() gives: > within [1] TRUE FALSE FALSE TRUE FALSE # using 'x[1] <= g && g <= x[2]' gives: > within [1] TRUE FALSE FALSE TRUE TRUE Note that the "findInterval" method can be fixed by specifying 'rightmost.closed=TRUE' but this doesn't make the code easier to understand, all the contrary... Cheers, H. > > Look at ?findInterval, which does all the work. It returns 1 if within > range in this case. > > -Christos > >> -----Original Message----- >> From: bioconductor-bounces at stat.math.ethz.ch >> [mailto:bioconductor-bounces at stat.math.ethz.ch] On Behalf Of >> Daniel Brewer >> Sent: Monday, October 29, 2007 12:29 PM >> To: bioconductor at stat.math.ethz.ch >> Subject: [BioC] Is a number within a set of ranges? >> >> I have a table with a start and stop column which defines a >> set of ranges. I have another table with a list of genes >> with associated position. What I would like to do is subset >> the gene table so it only contains genes whose position is >> within any of the ranges. What is the best way to do this? >> The only way I can think of is to construct a long list of >> conditions linked by ORs but I am sure there must be a better way. >> >> Simple example: >> >> Start Stop >> 1 3 >> 5 9 >> 13 15 >> >> Gene Position >> 1 14 >> 2 4 >> 3 10 >> 4 6 >> >> I would like to get out: >> Gene Position >> 1 14 >> 4 6 >> >> Any ideas? >> >> Thanks >> >> Dan >> >> -- >> ************************************************************** >> Daniel Brewer, Ph.D. >> Institute of Cancer Research >> Email: daniel.brewer at icr.ac.uk >> ************************************************************** >> >> The Institute of Cancer Research: Royal Cancer Hospital, a >> charitable Company Limited by Guarantee, Registered in >> England under Company No. 534147 with its Registered Office >> at 123 Old Brompton Road, London SW7 3RP. >> >> This e-mail message is confidential and for use by the...{{dropped:13}} > > _______________________________________________ > Bioconductor mailing list > Bioconductor at stat.math.ethz.ch > https://stat.ethz.ch/mailman/listinfo/bioconductor > Search the archives: http://news.gmane.org/gmane.science.biology.informatics.conductor ADD REPLYlink written 11.8 years ago by Hervé Pagès ♦♦ 14k Answer: Is a number within a set of ranges? 0 11.8 years ago by Joern Toedling720 wrote: Hi Daniel, I think you could do something smarter using the "outer" function here. Let's say, your matrix of intervals be "ints" and the Position column of your genes-position matrix be pos, then something like this, should give you only the positions of those genes inside those intervals: pos[which(rowSums(outer(pos,ints[,"Stop"],"<=") & outer(pos,ints[,"Start"],">=") )>0)] Maybe there's even a smarter way that I do not know of. Regards, Joern Daniel Brewer wrote: > I have a table with a start and stop column which defines a set of > ranges. I have another table with a list of genes with associated > position. What I would like to do is subset the gene table so it only > contains genes whose position is within any of the ranges. What is the > best way to do this? The only way I can think of is to construct a long > list of conditions linked by ORs but I am sure there must be a better way. > > Simple example: > > Start Stop > 1 3 > 5 9 > 13 15 > > Gene Position > 1 14 > 2 4 > 3 10 > 4 6 > > I would like to get out: > Gene Position > 1 14 > 4 6 > > Any ideas? > > Thanks > > Dan > > ADD COMMENTlink written 11.8 years ago by Joern Toedling720 Answer: Is a number within a set of ranges? 0 11.8 years ago by Oleg Sklyar260 Oleg Sklyar260 wrote: This is a trivial one-liner: r = data.frame(Start=c(1,5,13), End=c(3,9,15)) g = data.frame(Gene=c(1,2,3,4), Position=c(14,4,10,6)) index = apply(g, 1, function(x) any(x[2]>=r$Start & x[2]<=r\$End)) > index [1] TRUE FALSE FALSE TRUE > g[index,] Gene Position 1 1 14 4 4 6 Best, Oleg - Dr Oleg Sklyar * EMBL-EBI, Cambridge CB10 1SD, UK * +441223494466 On Mon, 2007-10-29 at 16:29 +0000, Daniel Brewer wrote: > I have a table with a start and stop column which defines a set of > ranges. I have another table with a list of genes with associated > position. What I would like to do is subset the gene table so it only > contains genes whose position is within any of the ranges. What is the > best way to do this? The only way I can think of is to construct a long > list of conditions linked by ORs but I am sure there must be a better way. > > Simple example: > > Start Stop > 1 3 > 5 9 > 13 15 > > Gene Position > 1 14 > 2 4 > 3 10 > 4 6 > > I would like to get out: > Gene Position > 1 14 > 4 6 > > Any ideas? > > Thanks > > Dan >
Answer: Is a number within a set of ranges?
0
11.8 years ago by
Daniel Brewer1.9k
Daniel Brewer1.9k wrote:
Daniel Brewer wrote: > I have a table with a start and stop column which defines a set of > ranges. I have another table with a list of genes with associated > position. What I would like to do is subset the gene table so it only > contains genes whose position is within any of the ranges. What is the > best way to do this? The only way I can think of is to construct a long > list of conditions linked by ORs but I am sure there must be a better way. > > Simple example: > > Start Stop > 1 3 > 5 9 > 13 15 > > Gene Position > 1 14 > 2 4 > 3 10 > 4 6 > > I would like to get out: > Gene Position > 1 14 > 4 6 > > Any ideas? > > Thanks > > Dan > Thanks everyone for their ideas. That is marvellous. Dan The Institute of Cancer Research: Royal Cancer Hospital, a charitable Company Limited by Guarantee, Registered in England under Company No. 534147 with its Registered Office at 123 Old Brompton Road, London SW7 3RP. This e-mail message is confidential and for use by the a...{{dropped:2}}


text:
# Project Euler problem 92 (sequences formed by the sum of squares of digits) in Haskell

I made the following program in Haskell to solve Project Euler's problem 92. The program works (i.e. the solution it yields is correct), but it's not exactly the fastest in the world.

The problem is:

A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.

For example,

• 44 → 32 → 13 → 10 → 1 → 1
• 85 → 89 → 145 → 42 → 20 → 4 → 16 → 37 → 58 → 89

Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.

How many starting numbers below ten million will arrive at 89?

My code:

digits :: Int -> [Int]
digits 0 = []
digits x = digits (x div 10) ++ [x mod 10]

squareDigits :: [Int] -> [Int]
squareDigits x =  map (^2) x

sumSquareDigits :: Int -> Int
sumSquareDigits x = sum (squareDigits (digits x))

chainTo89 :: Int -> Bool
chainTo89 89 = True
chainTo89 1 = False
chainTo89 x = chainTo89 (sumSquareDigits x)

main :: IO()
main = print $length$ filter (chainTo89) $[1..9999999]  Any feedback on how this can improved, ranging from advice on good practices to very concrete algorithmic improvements, preferably without using too complicated Haskell concepts (I've only been programming in Haskell for three days) is more than welcome. If you are going to propose rather complex improvements (e.g. state monads?), then that's fine, so long as it's understandable to a beginner. :) Note: I've implemented this in Python too, where I mapped known outcomes to a dictionary, which sped up the process considerably (i.e. the moment the chain function encounters a number already checked, it goes straight to the outcome without chaining further). However, I don't know how to do that in Haskell, if that is good practice in Haskell in the first place. This is exactly one of the reasons I asked this question in the first place; it feels as if it would be good to have some 'global' variable that can be used to map known values to, but that seems to go against Haskell's spirit. • Not a full answer but squareDigits should be named square as it works on any sequence of numbers not only digits. – Caridorc Jul 19 '15 at 20:32 • Have you compiled at -O2 ? The Haskell compiler is pretty good at optimizing. – Caridorc Jul 19 '15 at 20:34 • @Caridorc I did now, and it does seem to make quite a difference. I got it down to 36 secs. I didn't time the non -O2 version, but it definitely was considerably longer (minutes). – Ben Jul 19 '15 at 20:47 • I can't test now but using a lazy range may speed up your code: lenght$ takeWhile (<= 9999999) $filter chainTo89 [1..] – Caridorc Jul 19 '15 at 20:52 • @Caridorc That didn't change anything. Takes exactly the same time (both with -O2, that is). Maybe that's because the Haskell compiler optimised it already? – Ben Jul 19 '15 at 21:06 ## 3 Answers Overall, your solution looks like a reasonable Haskell implementation of the question. Well done. I found some tiny bits to comment about anyway. ### Separate algorithm from IO Part of your algorithm is specified in the main function. To make it easier to play with it, it is better to do all computations in some other function, and only handle input/output in main. In your case: solve :: Int -> Int solve n = length$ filter chainTo89 $[1..n - 1] main = print (solve 1000000)  This allows us, for example, to call solve on various numbers in ghci, in tests, or in benchmarks. ### benchmarks Since you asked about algorithmic improvements, benchmarks are actually a good idea. To use the criterion benchmarking library, we add an import and replace the main function: import Criterion.Main -- code to benchmark main = defaultMain [ bgroup "chain89" [ bench ("solve " ++ show n)$ whnf solve n
| n <- [100000, 200000 .. 1000000]
]
]

This benchmarks the solve function on values below 1 million, in 100k steps. The question asks for 10 million, but i decided to run my benchmarks on the smaller inputs to get more rapid feedback. If you compile this to an executable (say, chain89), run it as chain89 --output chain89.html to produce a nich benchmark report in chain89.html. For your code as given, I get these numbers (in ms):

Looks more or less linear to me. Did you expect it to look linear? Maybe think about it a moment before reading on.

### Linear?!

I didn't expect it to be linear, because we're duplicating the work in the recursive calls. You mentioned that caching the recursive results helped a lot, so I expected the complexity without caching to be clearly worse than linear, and to regain linear complexity by caching, as you would expect from a dynamic programming solution.

After seeing the benchmark results, I realized that for large numbers n, the result of sumSquareDigits n is always much smaller than n. To approximate the result after one step, consider this: if the input is n, it has k = log n / log 10 digits. In the worst case, these digits are all 9. Then the result is k * 9 * 9. For example, sumSquareDigits 999999 is only 486. So even if we multiply an already large input by 10, the result after the first step is not more than 81 bigger, which doesn't translate into too many additional recursive calls. There are additional recursive calls, so this is still slower than linear, but only very little, so we don't see it in the benchmark results.

### Memoization for small inputs

We can memoize the result on small values, where small means that the values can occur after the first step. In other words, if we want to support inputs to n, we want to memoize the results for 1 to 81 * log n / log 10, because that's the biggest number we can see after the first step, see above.

Haskell supports an unusual approach to memoization: We can set up a lazy data structure which maps inputs to outputs, and in the initialization of each entry in the data structure, we access other entries. As long as we're never (directly or indirectly) accessing an entry from itself, the entries will be computed in an appropriate order.

Which data structure do we want here? We're going to use the consecutive numbers from 1 to (81 * log n / log 10) as inputs, so we probably want to use an array. We need to add an import, change chainTo89 to add the memoization and adapt solve to the new variant of chainTo89.

import Data.Array.IArray

-- other code here

makeChainTo89 :: Int -> (Int -> Bool)
makeChainTo89 n = compute where
size = 81 * ceiling (log (fromIntegral n) / log 10)

cache :: Array Int Bool
cache = array (1, size) [(i, compute i) | i <- [1 .. size]]

fetch x = cache ! x

compute 89 = True
compute 1 = False
compute x = fetch (sumSquareDigits x)

solve :: Int -> Int
solve n = length $filter chainTo89$ [1 .. n - 1] where
chainTo89 = makeChainTo89 n

I renamed chainTo89 to makeChainTo89 because makeChainTo89 n returns a function that computes the same values as the old chainTo89 when called with values that are less than or equal to n. The variable size holds the size of the memoization table and is computed as explained above. The cache is the memoization table itself. It contains an entry for all i between 1 and size, mapping i to compute i. The fetch function retrieves an entry from the memoization table, and the compute function does the actual work of computing the next element in the chain. Note that compute looks almost like the old chainTo89 except that it calls fetch instead of the calling itself recursively. But fetch will force a cache entry which contains a call to compute in its thunk, so that the recursion structure is actually the same. Just when the same cache entry is forced again, the result is already there.

This only works if n is big enough (so we never move out of the table after moving into it) and if there are really no other cycles than the cycles involving 1 and 89. Here's how the benchmark results look like for this version of the code:

That's almost 60% faster.

### Avoiding right-associative (++)

Your digits function appends an element to the right of an immutable linked list, which requires copying the whole list. Since the order of the digits is irrelevant for the reset of the algorithm, it would be better to prepend the found digit to the list. (Even if the order is relevant, it is better to first produce the reversed list of digits, and then reverse once).

This is the new digits function:

digits :: Int -> [Int]
digits 0 = []
digits x = x mod 10 : digits (x div 10)

It is another 35% faster:

### More ideas

Some other low-level ideas for speeding this up further:

• explore divMod or quotRem as an alternative to div and mod.
• explore alternatives to (^ 2).

And one high-level idea:

• avoid looping over all permutations of the same selection of digits.

### Further improvements

Also check out Max Taldykin's answer for (impressive) additional improvements on top of what I propose in my answer.

• Excellent answer! Really well researched and helpful! – rubik Aug 19 '15 at 20:09

sumSquareDigits would be better expressed as

sumSquareDigits :: Int -> Int
sumSquareDigits x = sum $map (^2)$ digits x

Note the use of $ instead of nested parentheses to form a chain. I'm also not fond of your squareDigits, since it doesn't strictly require its input to be digits, nor does it transform its input into digits. One simple change to use divMod speeds it up by about 25% (using ghc -O2): digits :: Int -> [Int] digits 0 = [] digits n = digits quotient ++ [remainder] where (quotient, remainder) = n divMod 10  Avoiding ++ saves another 8% (though it reverses the output of digits): digits x = remainder : digits quotient  To get another big performance gain, you should use memoization. Memoizing just the results for 1 to 100 yields another 30% speedup (though memoizing the first 1000 results is actually worse). digits :: Int -> [Int] digits 0 = [] digits n = remainder : digits quotient where (quotient, remainder) = n divMod 10 sumSquareDigits :: Int -> Int sumSquareDigits x = sum$ map (^2) $digits x chainResult :: Int -> Int chainResult n | n < 100 = memo !! n | otherwise = chainResult$ sumSquareDigits n
where
chainResult' 0 = 0
chainResult' 1 = 1
chainResult' 89 = 89
chainResult' n = chainResult' $sumSquareDigits n memo = map (chainResult' . sumSquareDigits) [0..99] main :: IO() main = print$ length $filter (\n -> 89 == chainResult n)$ [1..9999999]

The program above, which includes all of these suggestions, runs in less than half the time of your original.

• Some really, really good advice. Thanks a lot! The speedup was actually even more impressive; it ran almost 3x faster on my system. – Ben Jul 20 '15 at 0:59
• Good answer, but: Don't memoize with a linked list as cache. Also it is hard to see whether your definition of memo is actually shared between calls to chainResult. I guess the compiler would float it out and then it is shared? – Toxaris Jul 20 '15 at 1:26

I tried to elaborate on great answer by Toxaris. After precomputing results for first 81 * log10 n numbers, most of time is spent on extracting digits and squaring them. It is possible to calculate squares of digits for sequential numbers in incremental manner.

If you have list of squared digits for some number n then here is how to calculate list of squared digits for n+1.

inc :: [Int] -> [Int]
inc (81:xs) = 0  : inc xs
inc (x:xs)  = fromJust (lookup x nextSq) : xs
where
sq = [0,1,4,9,16,25,36,49,64,81]
nextSq = zip sq $tail sq inc [] = [1]  To get sequence of all numbers you can iterate this function: > take 20$ iterate inc [1]
> [[1],[4],[9],[16],[25],[36],[49],[64],[81],[0,1],[1,1],[4,1],[9,1],[16,1],[25,1],[36,1],[49,1],[64,1],[81,1],[0,4]]

Now you just sum squares of digits and get index to precomputed cache of chain results.

Here is the full code which on my machine is 15 times faster than the original one:

import qualified Data.Vector.Unboxed as Vector
import Data.List (find, lookup)
import Data.Maybe (fromJust)
import Criterion.Main

main: IO ()
main = defaultMain [ bench "92" $whnf p92$ 10^7 ]

p92 :: Int -> Int
p92 n = length
$filter (==89)$ map ((cache n Vector.!) . sum)
$take n (iterate inc [1]) next :: Int -> Int next = sum . map (^2) . digits digits :: Int -> [Int] digits 0 = [] digits x = let (a,b) = divMod x 10 in b : digits a cache :: Int -> Vector.Vector Int cache n = Vector.fromList$ 0 : map
(fromJust . find (\x -> x == 1 || x == 89) . iterate next)
[1 .. 81 * ceiling (logBase 10 $fromIntegral n)] inc :: [Int] -> [Int] inc [] = [1] inc (81:xs) = 0 : inc xs inc (x:xs) = fromJust (lookup x nextSq) : xs where sq = [0,1,4,9,16,25,36,49,64,81] nextSq = zip sq$ tail sq

format: plain


text:
# Show that $f(x)=\sum_{k=1}^\infty \frac{1}{k}\sin(\frac{x}{k+1})$ converges.

Exercise: Show that $$f(x)=\sum_{k=1}^\infty \frac{1}{k}\sin\left(\frac{x}{k+1}\right)$$ converges, pointwise on $\mathbb{R}$ and uniformly on each bounded interval in $\mathbb{R}$, to a differentiable function $f$ which satisfies $$|f(x)|\leq |x| \text{ and } |f'(x)|\leq 1$$ for all $x\in \mathbb{R}$.

Hint: Dominate, then telescope.

I am unsure how to start this proof. By definition, I know that I need to show that the sequence with the terms $$s_n(x)=\sum_{k=1}^n \frac{1}{k}\sin\left(\frac{x}{k+1}\right)$$ converges pointwise on $\mathbb{R}$ and uniformly on a bounded interval in $\mathbb{R}$, but I am unsure how to show these facts.

-

Let's denote by $$f_n(x)=\frac{1}{n}\sin(\frac{x}{n+1}),$$ so we have $$f(x)=\sum_{n=1}^\infty f_n(x).$$

It's clear that $f$ is defined at $0$ and $$f_n(x)\sim\frac{x}{n^2},\forall x\neq0$$ then we have pointwise convergence by comparaison with the Riemann series.

Now, let $[a,b]$ a bounded interval in $\mathbb{R}$. We have $$|f_n(x)|\leq|\frac{x}{n^2}|\leq \frac{\max(|a|,|b|)}{n^2},$$ so we have normal convergence which implies the uniform convergence of the series on $[a,b]$.

Moreover, from $$|f'_n(x)|=\left|\frac{\cos(\frac{x}{n+1})}{n(n+1)}\right|\leq\frac{1}{n^2},$$ hence, we find the uniform convergence of the series $\sum_nf'_n(x)$ on $\mathbb{R}$ which prove that $f$ is differentiable and $$f'(x)=\sum_{n=1}^\infty f'_n(x).$$ Finally, we have these two inequality $$|f(x)|\leq\sum_{n=1}^\infty \frac{1}{n}|\sin\frac{x}{n+1}|\leq|x|\sum_{n=1}^\infty(\frac{1}{n}-\frac{1}{n+1})=|x|,$$

and $$|f'(x)|\leq\sum_{n=1}^\infty|f'_n(x)|\leq\sum_{n=1}^\infty(\frac{1}{n}-\frac{1}{n+1})=1.$$

-
Compare with $$\sum_{k=1}^\infty \dfrac{x}{k(k+1)}.$$
Since $|\sin(\theta)|\leq |\theta|$ for all $\theta\in \mathbb{R}$, $\left|\frac{1}{k}\sin\left(\frac{x}{k(k+1)}\right)\right|\leq \left|\frac{x}{k(k+1)}\right|$. Then we show that the series $\sum_{k=1}^\infty \frac{x}{k(k+1)}$ converges and so the original series converges uniformly by the Weierstrass M-Test? –  kaiserphellos Mar 7 '13 at 10:33


text:
Thomas' Calculus 13th Edition

Differentiating terms with respect to x, we get $\frac{dx}{dx}= \frac{d}{dx}$(sec y) Or 1= sec y tan y•$\frac{dy}{dx}$ which implies that $\frac{dy}{dx}= \frac{1}{sec y tan y}$= cos y cot y.


text:
Associations to the word «Seventy»

Wiktionary

SEVENTY, proper noun. The translators of the Septuagint

Dictionary definition

SEVENTY, noun. The cardinal number that is the product of ten and seven.
SEVENTY, adjective. Being ten more than sixty.

Wise words

In words, as fashions, the same rule will hold; Alike fantastic, if too new, or old: Be not the first by whom the new are tried, Nor yet the last to lay the old aside.
Alexander Pope


text:
# Identify the Polar Equation r=4-2cos(theta)

This is an equation of a limacon.
Limacon
Identify the Polar Equation r=4-2cos(theta)


text:
# Worksheet on Laws of Inequality

Practice the questions given in the worksheet on laws of inequality.

1. State true or false.

(i) x < - y  ⟹ -x > y

(ii) -5x ≥ 15 ⟹ x ≥ -3

(iii) 2x ≤ -7 ⟹ $$\frac{2x}{-4}$$ ≥ $$\frac{-7}{-4}$$

(iv) 7 > 5 ⟹ $$\frac{1}{7}$$ < $$\frac{1}{5}$$

2. If x ≥ -y then mark each of the following sentences as true or false.

(i) - x ≥ -y

(ii) x + 2 ≤ y + 3

(iii) $$\frac{x}{3}$$ ≤ $$\frac{y}{3}$$

(iv) ax ≥ ay, where a < 0

3. State, whether the following statements are true or false.

(i) If ax + b > c then ax > c - b

(ii) If ax + b > c then x < $$\frac{c - b}{a}$$, where a is a negative number.

(iii) If a > b then a + c > b + c

(iv) If a > b then a - c > b - c

(v) If a < b, then a - c < b - c

(vi) If a < b then ac < bc, c ≠ 0.

(vii) If a < b, then ac > bc

(viii) If a > b then $$\frac{a}{c}$$ > $$\frac{b}{c}$$, c ≠ 0.

(ix) If a - c < b - d then a + d < b + c.

(x) If a < b, and c > 0, then a - c > b - c, where a, b, c and d are real numbers and c ≠ 0.

4. If x > -5, find the least positive and negative integral values of x.

5. (i) If (x - 2)(x - 5) < 0 and x ∈ N then find x.

(ii) If (x + 3)(2 - x) > 0 and x ∈ Z then find x.

6. If 5 – 2x ≥ 1, what is the maximum value of x?

7. If x > y and z < 0, which of the following is correct?

(i) xz > yz

(ii) xz < yz

Answers for the worksheet on laws of inequality are given below:

1. (i) True

(ii) False

(iii) True

(iv) True

2. True

(i) True

(ii) True

(iii) True

(iv) True

3. (i) True

(ii) True

(iii) True

(iv) True

(v) True

(vi) False (when c < 0)

(vii) False

(viii) False (when c < 0)

(ix) True

(x) False

4. Least positive number = 1, least negative number = -4

5. (i) 3, 4

(ii) -2, -1, 0, 1

6. 2

7. xz < yz


text:
# texlive[54659] Master/texmf-dist: euclideangeometry (10apr20)

commits+karl at tug.org commits+karl at tug.org
Sun Apr 12 00:24:25 CEST 2020

Revision: 54659
http://tug.org/svn/texlive?view=revision&revision=54659
Author:   karl
Date:     2020-04-12 00:24:25 +0200 (Sun, 12 Apr 2020)
Log Message:
-----------
euclideangeometry (10apr20)

Modified Paths:
--------------
trunk/Master/texmf-dist/doc/latex/euclideangeometry/euclideangeometry-man.pdf
trunk/Master/texmf-dist/doc/latex/euclideangeometry/euclideangeometry-man.tex
trunk/Master/texmf-dist/doc/latex/euclideangeometry/euclideangeometry.pdf
trunk/Master/texmf-dist/source/latex/euclideangeometry/euclideangeometry.dtx
trunk/Master/texmf-dist/tex/latex/euclideangeometry/euclideangeometry.sty

===================================================================
--- trunk/Master/texmf-dist/doc/latex/euclideangeometry/README.txt	2020-04-11 22:23:52 UTC (rev 54658)
+++ trunk/Master/texmf-dist/doc/latex/euclideangeometry/README.txt	2020-04-11 22:24:25 UTC (rev 54659)
@@ -10,7 +10,7 @@
%%
-        [2020-02-12 v.0.1.5 Extension package for curve2e]
+        [2020-03-30 v.0.1.7 Extension package for curve2e]

The package bundle euclideangeometry is composed of the following files

Modified: trunk/Master/texmf-dist/doc/latex/euclideangeometry/euclideangeometry-man.pdf
===================================================================
(Binary files differ)

Modified: trunk/Master/texmf-dist/doc/latex/euclideangeometry/euclideangeometry-man.tex
===================================================================
--- trunk/Master/texmf-dist/doc/latex/euclideangeometry/euclideangeometry-man.tex	2020-04-11 22:23:52 UTC (rev 54658)
+++ trunk/Master/texmf-dist/doc/latex/euclideangeometry/euclideangeometry-man.tex	2020-04-11 22:24:25 UTC (rev 54659)
@@ -884,7 +884,7 @@
\cs{IntersecionOfLines}\parg{point1}\parg{dir1} and\parg{point2}\parg{dir2}
\end{ttsyntax}
- were each line is identified with its \meta{point} and its direction
+ were each line is identified with its \meta{point} and its \emph{direction}
\meta{dir}; the intersection coordinates go to the output \meta{vector}.

\item A second command\cs{IntersectionOfSegments} does almost the same
@@ -898,7 +898,59 @@
Again the intersection point coordinates go to the output \meta{vector}.
The first segment is between points 11 and 12, and, similarly, the second
segment is between points 21 and 22.
-
+\item Another “intersection” command is \cs{IntersectionsOfLine} to
+ determine the two intersection of a line with a circle. The syntax is:
+ \begin{ttsyntax}
+\end{ttsyntax}
+ where \meta{point} and \meta{dir} identify a line with a given direction
+ and passing through a given point; the circle is identified with its
+ \meta{center} and \meta{radius}; the intersection points \meta{int1} and
+ \meta{int2} are the coordinates of the intersection points; If the line
+ and circle do not intersect, a warning message is issued, shown in the
+ console and written to the \file{.log} file; the intersection points are
+ assigned the default values \texttt{0,0}, which evidently produce strange
+ results in the output document, so as to remind the user to give a look
+ to the \file{.log} file and to review his/her data.
+\item It is difficult to numerically determine the coordinates of the
+ intersection points of two circles; it becomes easier if one of the
+ intersections is known; To this end, a macro to draw a circle with a
+ given center and passing through a given point is handy:
+\begin{ttsyntax}
+ \cs{CircleThrough}\meta{point}WithCenter\marg{center}
+\end{ttsyntax}
+ draws such circumference.
+\item With the above macro it becomes easy to draw two circumferences
+ with different centers and passing through the same point; therefore
+ it becomes determine the other intersection point by means of the
+ following macro:
+\begin{ttsyntax}
+\cs{Segment}\parg{endpoint1}\parg{endpoint2}SymmetricPointOF\meta{p1}
+ to\meta{p2}
+\end{ttsyntax}
+ The computation is simple, because the second intersection is the
+ symmetrical point \meta{p2} of \meta{p1} with respect to the segment
+ that joins the centers of the given circles intersecting one another
+ in \meta{p1}.
+\item It would be interesting to solve the same problem with help of
+ the following macro relating to right triangles identified with their
+ hypothenuse and one of its legs; the other leg is found by means of this
+ macro:
+\begin{ttsyntax}
+\cs{LegFromHypothenuse}\meta{length1} AndOtherLeg\meta{length2}
+ to\marg{length3}
+\end{ttsyntax}
+ since  the intersection points of two circles define their common chord;
+  this chord and the two circle centers define two isosceles triangles
+  with the same base; therefore the segment joining the circle radii,
+  coincides whit the chord axis and divides each isosceles triangle in
+  two right triangles, where the hypotenuse is one of two radii and the
+  first leg is the distance from the chord middle point, intersection of
+  the chord and the segment joining the circle centers; at this point the
+  distance of the second point intersection from the chord middle point
+  and the coordinates of the second intersection may be easily computed;
+  of course this is a much clumsier way to determine the second
+  intersection, but it is useful to solve this right triangle  easy problem.
\item Command \cs{ThreePointCircle} draws a circle that goes through three
given points; the syntax is the following:
\begin{ttsyntax}
@@ -908,7 +960,6 @@
the coordinates of the center of the circle, that might be useful even
if the circle is not drawn; the optional asterisk, if present, does not
draw the circle, but the center is available.
-
\item Alternatively
\begin{ttsyntax}\setfontsize{10.5}
\cs{ThreePointCircleCenter}\parg{point1}\parg{point2}\parg{point3}to\meta{vector}
@@ -931,7 +982,7 @@
\end{ttsyntax}
Apparently these two commands do the same, but, no, they behave
differently: in the former command the \meta{Radius} is a vector the
- modulus of which si computed and used as the radius; in the latter
+ modulus of which is computed and used as the radius; in the latter
command the \meta{radius} is a scalar and (its magnitude) is directly
used.

@@ -1497,6 +1548,64 @@
\end{figure*}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\subsection{ Intersections involving circles}
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Determining the intersection of two circles is difficult; algebraically it requires the solution of second degree equations whose coefficients are sort of complicated expressions of the centers and radii; furthermore such equations might not have real roots. The problems are much simpler even geometrically when one circle is intersected by a line, and when two circles share a common point. In the first case there are two intersections, possibly coincident, if the centers distance is shorter than the sum of their radii; in the second case its easy to determine the chord common to both circles and the problem of finding the second intersection becomes that of finding the second end point of the chord.
+
+Figure~\ref{fig:circle-and-line} shows the simple geometrical construction that leads to the determination of the intersections; one of the lines is tangent to the circle and the intersection points $P_3$ and $P_4$ coincide.
+
+\begin{figure}
+\begin{Esempio}[\setfontsize{9}]
+\unitlength=0.007\linewidth
+\begin{picture}(100,100)
+\AutoGrid
+\IntersectionsOfLine(100,50)(0,20)%
+  WithCircle(40,40){30}to\Puno and\Pdue
+\Pbox(\Puno)[tl]{P_1}[2]
+\Pbox(\Pdue)[t]{P_2}[2]
+\Dotline(\C)(\Pt){2}[1.5]
+\Dotline(\C)(\Pq){2}[1.5]
+\Pbox(\Int)[t]{M}[2]
+\Dotline(\C)(\Int){2}[1.5]
+%
+\IntersectionsOfLine(0,70)(100,70)%
+  WithCircle(40,40){30}to\Ptre and\Pquat
+\Pbox(\Ptre)[bl]{P_3}[2]
+\Pbox(\Pquat)[br]{P_4}[2]
+\IntersectionsOfLine(0,40)(100,100)%
+  WithCircle(40,40){30}to\Pcin and\Psei
+\Pbox(\Pcin)[br]{P_5}[2]
+\Pbox(\Psei)[t]{P_6}[2]
+\end{picture}
+\end{Esempio}
+\caption{Intersection of a circle with several lines}\label{fig:circle-and-line}
+\end{figure}
+
+Figure~\ref{fig:two-intersecting-circles} shows the geometrical construction to determine the second intersection point $P_2$ of two circles that already have a first common point $P_1$. The common chord and the segment joining the centers are not shown, but the code, although with “strange” point names, shows all the steps necessary to find the second intersection point
+
+
+\begin{figure}\centering
+\begin{Esempio}[\setfontsize{9}]
+\unitlength0.007\linewidth
+\begin{picture}(100,100)
+\AutoGrid
+\edef\PCCuno{30,40}
+\edef\PCCdue{70,60}
+\edef\PCCzero{40,55}
+\Pbox(\PCCuno)[t]{C_1}[2]
+\Pbox(\PCCdue)[t]{C_2}[2]
+\Pbox(\PCCzero)[l]{P_1}[2.5]
+\CircleThrough\PCCzero WithCenter\PCCuno
+\CircleThrough\PCCzero WithCenter\PCCdue
+\Segment(\PCCuno)(\PCCdue)%
+  SymmetricPointOf\PCCzero to\PCCquat
+\Pbox(\PCCquat)[l]{P_2}[2.5]
+\end{picture}
+\end{Esempio}
+\caption{Second intersection point $P_2$ of two circles sharing a first intersection point $P_1$}\label{fig:two-intersecting-circles}
+\end{figure}
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{Triangles and their special lines}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@@ -1704,6 +1813,51 @@
\end{figure}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\subsection{The tangent to an ellipse}\label{ssec:diretriz}
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+Ellipses have mani interesting properties. One that I was not able to find anywhere in the documentation I examined (of course not the totality  of available on ellipses, except an on-line document written in Portuguese by Sergio Alvez, \url{https://docplayer.com.br/345411-Elipses-inscritas-num-triangulo.html}, is the \emph{director circumference}, literal translation of the Portuguese definition \emph{circunfência diretriz}.
+
+Consider an ellipse with its foci $F$ en $F'$, and a generic point $P$ on its contour.
+Trace a segment from $F\,P$  and another segment for $P\,F'$; these segments measure the distanced from point $P$ to each focus: their sum is the length of the main ellipse axis $2a$, being $a$ the semi axis. Now lengthen the segment $P\,F'$ to point $S$ by the length of $F\,P$; the length of $S\,F'$ is therefore equal to $2a$; now trace the circumference with center in $F'$ and radius $2a$; this is the \emph{director circumference}, that is labelled with~$\Gamma$.
+
+By construction, then, the circle $\gamma$ centred in $F$ and radius equal to $F\,P$ is tangent to $\Gamma$ in $S$ and passes through $F$. This allows to say that:
+\begin{itemize}[noitemsep]
+\item the ellipse is the locus of the centres of all circles passing through  focus $F$ and internally tangent to the circle $\Gamma$ centred in the other focus $F'$ and with radius $2a$;
+\item the axis of segment $S\,F$ is tangent to the ellipse;
+\item the tangency point is the point $P$;
+\item since this axis  passes through the midpoint $M$ of segment $S\,F$ and it is perpendicular to it, the segment $M\,P$ has the same direction of the tangent to the ellipse;
+\item notice that points $S$ and $F$ are symmetrical with respect to the tangent in point $P$.
+\end{itemize}
+Such properties can be viewed and controlled in figure~\ref{fig:diretriz}.
+
+\begin{figure}[!tb]\centering
+\begin{Esempio}*[\setfontsize{8.2}](0.40)
+\unitlength=0.005\linewidth
+\begin{picture}(170,160)(-60,-80)
+\GraphGrid(-60,-80)(170,160)
+\VECTOR(0,-80)(0,80)\Pbox(0,80)[r]{y}[0]
+\VECTOR(-60,0)(110,0)\Pbox(110,0)[t]{x}[0]
+\edef\A{40}\edef\B{30}\Xellisse{\A}{\B}[\thicklines]
+\edef\X{\fpeval{\A*cosd(120)}}\edef\Y{\fpeval{\B*sind(120)}}
+\edef\P{\X,\Y}\Pbox(\P)[b]{P}[3]
+\edef\C{\fpeval{sqrt(\A**2-\B**2)}}% Inter focal semi distance
+\CopyVect-\C,0 to\F \CopyVect\C,0 to\Fp\Pbox(\Fp)[t]{F'}[3]
+\Pbox(\F)[t]{F}[3]\Pbox(0,0)[tr]{O}[3]
+\segment(\Fp)(\S)\Pbox(\S)[br]{S}[3]
+\segment(\F)(\S)\SegmentCenter(\F)(\S)to\M
+\Pbox(\M)[r]{M}[3]\SegmentArg(\F)(\S)to\Arg
+\end{picture}
+\end{Esempio}
+\caption{The director circumference}\label{fig:diretriz}
+\end{figure}
+
+Of course the geometrical construction of figure~\ref{fig:diretriz} can be used also in reverse order; for example it may be given a line to play the role of the tangent, a point on  this line to play the role of tangency, and a point not belonging to the line to play the role of a focus, then it is possible to find the other focus laying on a horizontal line passing through the given focus. It suffices to find the symmetrical point of the first focus with respect with the given line, and to draw a line passing through this symmetrical point and the point of tangency that intersects the  horizontal line through the first focus, concluding that this is the second focus and that the ellipse major axis length is that of the segment joining this second focus with the above mentioned symmetrical point.
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\subsection{A triangle internally tangent ellipse given one of its foci}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

@@ -1715,6 +1869,8 @@
one point of tangency, because the focal distance and the sum of
distances of that tangency point from the foci, is sufficient to
determine all the parameters required to draw the ellipse.
+
+ As seen in the previous subsection~\ref{ssec:diretriz}, it is sufficient to find the threes symmetrical point of The given focus with respect to to the three sides, i.e. the three lines that pass through the triangle vertices; and the constructions gives simultaneously the major axis length and the three tangency points, therefore all the elements required to draw the ellipse. to draw

\begin{figure}[!tb]\centering
\begin{Esempio}[\setfontsize{7}](0.375)
@@ -1740,27 +1896,27 @@
\end{figure}

- The geometrical construction is rather complicated; the steps to follow
+ The geometrical construction with help of what has been explained in
+ subsection~\ref{ssub:diretriz} is easy; the steps to follow, therefore
are the following:\enlargethispage*{\baselineskip}
\begin{itemize}[noitemsep]

\item draw the triangle and the given focus $\mathsf{F}$;

-\item Find the symmetrical points $\mathsf G_i$ of this focus with
- respect to the sides of the triangle;
+\item Find the symmetrical points $\mathsf S_i$ of this
+focus with respect to the sides of the triangle;

-\item use these three points $\mathsf G_i$ as the vertices of a triangle
- with which to draw its circumcircle, actually only its center is of
+\item use these three points $\mathsf S_i$ as the vertices of a triangle
+ with which to draw its circumcircle that turns to be the \emph{director circumference}; actually only its center is of
interest, because it represents the second focus $\mathsf F'$; the
inter focal distance  $2c$; is just le length of vector $F' -F$;

-\item join with segments each symmetrical point $\mathsf G_i$ with the
+\item join with segments each symmetrical point $\mathsf S_i$ with the
second focus $\mathsf F'$ and find their intersections $\mathsf T_i$
with the triangle sides; they represent the tangency points of the
ellipse to be drawn;

-\item use one of these tangency points to find its distances from the
- foci; their sum gives the ellipse larger axis length $2a$;
+\item the radius of the director circumference is the ellipse major axix;

\item equation~\eqref{equ:axes-foci} allows to find the second axis
length; the segment that joins the foci has the required inclination

Modified: trunk/Master/texmf-dist/doc/latex/euclideangeometry/euclideangeometry.pdf
===================================================================
(Binary files differ)

Modified: trunk/Master/texmf-dist/source/latex/euclideangeometry/euclideangeometry.dtx
===================================================================
--- trunk/Master/texmf-dist/source/latex/euclideangeometry/euclideangeometry.dtx	2020-04-11 22:23:52 UTC (rev 54658)
+++ trunk/Master/texmf-dist/source/latex/euclideangeometry/euclideangeometry.dtx	2020-04-11 22:24:25 UTC (rev 54659)
@@ -45,7 +45,7 @@
%<package>\ProvidesPackage{euclideangeometry}%
-        [2020-02-12 v.0.1.5 Extension package for curve2e]
+        [2020-03-30 v.0.1.7 Extension package for curve2e]
%<*driver>
\documentclass{ltxdoc}\errorcontextlines=100
@@ -154,7 +154,7 @@
% installed with your updated  complete \TeX system installation.

% Please refer to the user manual before using this package.
-% \CheckSum{1108}
+% \CheckSum{1193}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\StopEventually{}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -215,7 +215,8 @@
% is |\Pbox| and it produces a box containing the label in math format. By
% default the point label is typeset with the math font variant produced
% by command |\mathsf|, but the macro is sufficiently versatile to allow
-% other settings; It accepts several optional arguments, therefore it syntax is particular:
+% other settings; it accepts several optional arguments, therefore it
+% syntax is particular:
%\begin{ttsyntax}
%\cs{Pbox}\parg{coordinates}\oarg{alignment}\marg{label}\oarg{diameter}\meta{$\star$}\aarg{angle}
%\end{ttsyntax}
@@ -228,7 +229,9 @@
% specification, the couple \texttt{cc} is assumed; most often than
% not, the label position becomes such that when the user reviews the
% document drafts, s/he understands immediately that s/he forgot to specify
-% some reasonable \meta{alignment} codes. Think of the \meta{alignment}
+% some reasonable \meta{alignment} codes; in any case the \texttt{cc} code
+% works fine to just put the dot of a specified diameter but with an empty
+% label. Think of the \meta{alignment}
% letters as the position of the reference point with respect to the
% the \meta{label} optical center. The optional \meta{angle} argument
% produces a rotation of the whole label by that angle; it may be used
@@ -238,23 +241,27 @@
%
% The optional asterisk draws a frame around the \emph{label}. Notice that
% the separator between the visible or the invisible frame and the box
-% contents varies according the the fact the the \meta{alignment}
+% contents varies according the the fact that the \meta{alignment}
% specification contains just one or two letter codes; this is useful,
% because the diagonal position of the label should be optically equal
-% to the gap that exists between the reference point  and the \meta{label}
+% to the gap that exists between the reference point and the \meta{label}
% box.
%
% If the \meta{diameter} is zero, no dot is drawn, the whole \meta{label}
% is typeset with the |\mathit| math font; otherwise only the first symbol
-% of a math expression si typeset in sans serif. The presence of subscripts
+% of a math expression is typeset in sans serif. The presence of subscripts
% makes the labels appear more distant from their reference point; the same
% is true when math symbols, even without subscripts, are used, because
-% of the oblique nature of the math letters alphabet.
+% of the oblique nature of the math ‘letters’ alphabet.
%
% If some text has to be printed as a label, it suffices to surround it
% with  dollar signs, that switch back to text mode when the default mode
% is the math one. With this kind of textual labels it might be convenient
% to use the optional asterisk to frame the text.
+% The final optional argument \meta{angle} (to be delimited with the
+% \texttt{<~>} signs) specifies the inclination of the label with respect
+% to the horizontal line; it is useful, for example to set a label along
+% a sloping line.
%    \begin{macrocode}
\providecommand\Pbox{}
\newlength\PbDim
@@ -577,6 +584,108 @@
\let\MiddlePointOf\SegmentCenter
%    \end{macrocode}
%
+% Some other macros are needed to solve certain triangle problems;
+% one of such macros is the one allows to determine the length of one
+% leg of a right triangle by knowing the lengths of the hypothenuse
+% and the other leg. The syntax is the following:
+%\begin{ttsyntax}
+%\cs{LegFromHypotenuse}\meta{hypothenuse} AndOtherLeg\meta{leg1} to\meta{leg2}
+%\end{ttsyntax}
+% where the three parameters may be macros, especially the last one;
+% all of them contina scalar values.
+%
+%    \begin{macrocode}
+\def\LegFromHypotenuse#1AndOtherLeg#2to#3{%
+  \edef#3{\fpeval{sqrt(#1**2-#2**2)}}}
+%    \end{macrocode}
+%
+% Another useful macro determines the two intersections of a line with
+% a circumference if they exist; otherwise it issues a warning and sets
+% both output values to vector \texttt{0,0}, which, of course, is wrong,
+% but it allows to go on with typesetting, although with non sense results.
+% Warnings do not stop the compilation program, therefore their message
+% goes to the \file{.log} file and the user might not notice it; but
+% since the results are probably absurd, s/he certainly notice this
+% fact and look for messages; the user, therefore, who has carefully
+% read  this user manual, immediately looks onto the \file{.log} file
+% and realises the reason of the wrong results.
+%
+% The syntax of this macro is the following:
+%\begin{ttsyntax}
+%\end{ttsyntax}
+% where \meta{point} and \meta{direction} are the line parameters
+% that can be explicit complex values or macros; \meta{center} is
+% the circumference explicit complex value, or a macro, containing
+% the center coordinates; \meta{radius} is the scalar explicit or
+% macro radius length; The intersection points \meta{int1} and
+% \meta{ind2} are supposed to be macros that get defined with the
+% intersection point coordinates; \meta{int1} is the first intersection
+% that is determined along the line \emph{direction}. Please notice the
+% different first part of the macro name \texttt{IntersectionsOfLine}
+% compared to the macro that determines the intersection of two lines
+% \texttt{IntersectionOfLines}: two intersections and one line vs. one
+% intersection with two lines.
+%    \begin{macrocode}
+\def\IntersectionsOfLine(#1)(#2)WithCircle(#3)#4to#5and#6{%
+\CopyVect#3 to\C \edef\R{#4}
+\CopyVect#1to\Pu \CopyVect#2to\Pd
+\segment(\Pu)(\Pd)\SegmentArg(\Pu)(\Pd)to\Diru
+\edef\Dird{\fpeval{\Diru+90}}\Pbox(\C)[b]{C}[2]
+\IntersectionOfLines(\Pu)(\Diru:1)and(\C)(\Dird:1)to\Int
+\SegmentLength(\C)(\Int)to\A
+\fptest{\A > \R}{\PackageError{euclideangeometry}%
+{Distance of line \A\space larger than radius \R. No intersections}%
+{Check your data; correct and retry}}{%
+\LegFromHypotenuse\R AndOtherLeg\A to\B
+\SymmetricalPointOf\Pt respect\Int to\Pq \edef#6{\Pq}
+}}
+%    \end{macrocode}
+%
+% Another useful macro determines the point \meta{p2} symmetric
+% to a given point \meta{p1} with respect to a given segment the
+% end points of which are \meta{Segm1} and \meta{Segm2}:
+%\begin{ttsyntax}
+%\cs{Segment}\parg{Segm1}\parg{Segm2}SymmetricPointOf\marg{p1} to\meta{p2}
+%\end{ttsyntax}
+% where, as usual, the input data may be explicit or macro defined
+% coordinates, while the output result should be a macro name.
+%    \begin{macrocode}
+\def\Segment(#1)(#2)SymmetricPointOf#3to#4{%
+\SegmentArg(#1)(#2)to\Sanguno\edef\Sangdue{\fpeval{\Sanguno+90}}
+\IntersectionOfLines(#1)(\Sanguno:1)and(#3)(\Sangdue:1)to\Smed
+\SymmetricalPointOf#3respect\Smed to#4\ignorespaces}
+%    \end{macrocode}
+%
+% Another useful macro draws a circle given its \meta{center}  and the
+% coordinates of the \meta{ponit}  which the circumference should pass
+% through. The syntax is:
+%\begin{ttsyntax}
+%\cs{CircleThrough}\parg{[point}WithCenter\marg{center}
+%\end{ttsyntax}
+% As usual, the parameters are all explicit or macro defined complex
+% numbers.
+%    \begin{macrocode}
+\def\CircleThrough#1WithCenter#2{%
+%    \end{macrocode}
+% The above macro is the building block for a simple macro that draws
+% two circles that cross at a given point; but it is so simple that
+% it is not worth defining a macro: if the user wants to try his/her
+% ability, s/he may define:
+%\begin{flushleft}\obeylines
+%|   \NewDocumentCommand{r() r() r()}{%|
+%|   \CircleThrough#3 WithCenter{#1}|
+%|   \CircleThrough#3 WithCenter{#2}\ignorespaces}|
+%\end{flushleft}
+% where \cs{ignorespaces} may be superfluous, but is always a safety action
+% when defining commands to be used within the \amb{picture} environment.
+% In any case see example~XXX in \file{euclideangeometry-man.pdf}
+%^^A\ref{fig:twocircles-second intersection}.
+%
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% \subsection{Triangle special points}
%^^A%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -1195,7 +1304,7 @@
% The overall macro that executes all the passages described in
% the above enumeration follows; the reader can easily recognise
% the various steps, since the names of the macros are self
-% explanatory; the $G_i$ point names are the symmetrical ones
+% explanatory; the $S_i$ point names are the symmetrical ones
% to the first focus $F$; the $M_i$ points are the centers of
% symmetry; the $F'$ point is the second focus; the $T_i$ points
% are the tangency points. The macro |\EllipseWithFOcus| has the
@@ -1225,26 +1334,26 @@
\IntersectionOfLines(\Pd)(\Au:1)and(\F)(\fpeval{\Au+90}:1)to\Mu
\IfBooleanTF{#1}{\Pbox(\Mt)[br]{M_3}[1.5pt]\Pbox(\Md)[t]{M_2}[1.5pt]
\Pbox(\Mu)[b]{M_1}[1.5pt]}{}
-\SymmetricalPointOf\F respect\Mu to\Gu
-\IfBooleanTF{#1}{\Pbox(\Gu)[l]{G_1}[1.5pt]}{}
-\SymmetricalPointOf\F respect \Md to\Gd
-\IfBooleanTF{#1}{\Pbox(\Gd)[t]{G_2}[1.5pt]}{}
-\SymmetricalPointOf\F respect \Mt to\Gt
-\IfBooleanTF{#1}{\Pbox(\Gt)[r]{G_3}[1.5pt]}{}
-\IfBooleanTF{#1}{\ThreePointCircle*(\Gu)(\Gd)(\Gt)}%
-                {\ThreePointCircle(\Gu)(\Gd)(\Gt)}
+\SymmetricalPointOf\F respect\Mu to\Su
+\IfBooleanTF{#1}{\Pbox(\Su)[l]{S_1}[1.5pt]}{}
+\SymmetricalPointOf\F respect \Md to\Sd
+\IfBooleanTF{#1}{\Pbox(\Sd)[t]{S_2}[1.5pt]}{}
+\SymmetricalPointOf\F respect \Mt to\St
+\IfBooleanTF{#1}{\Pbox(\St)[r]{S_3}[1.5pt]}{}
+\IfBooleanTF{#1}{\ThreePointCircle*(\Su)(\Sd)(\St)}%
+                {\ThreePointCircle(\Su)(\Sd)(\St)}
\CopyVect\C to\Fp \Pbox(\Fp)[l]{F'}[1.5pt]
\IfBooleanTF{#1}{%
-\Dotline(\F)(\Gt){2}[1.5pt]
-\Dotline(\F)(\Gd){2}[1.5pt]
-\Dotline(\F)(\Gu){2}[1.5pt]}{}
-\IntersectionOfSegments(\Pu)(\Pt)and(\Fp)(\Gt)to\Tt
-\IntersectionOfSegments(\Pu)(\Pd)and(\Fp)(\Gd)to\Td
-\IntersectionOfSegments(\Pd)(\Pt)and(\Fp)(\Gu)to\Tu
+\Dotline(\F)(\St){2}[1.5pt]
+\Dotline(\F)(\Sd){2}[1.5pt]
+\Dotline(\F)(\Su){2}[1.5pt]}{}
+\IntersectionOfSegments(\Pu)(\Pt)and(\Fp)(\St)to\Tt
+\IntersectionOfSegments(\Pu)(\Pd)and(\Fp)(\Sd)to\Td
+\IntersectionOfSegments(\Pd)(\Pt)and(\Fp)(\Su)to\Tu
\IfBooleanTF{#1}{\Pbox(\Tu)[l]{T_1}[1.5pt]
\Pbox(\Td)[b]{T_2}[1.5pt]
\Pbox(\Tt)[tl]{T_3}[1.5pt]
-\Dashline(\Fp)(\Gu){1}\Dashline(\Fp)(\Gd){1}\Dashline(\Fp)(\Gt){1}}{}
+\Dashline(\Fp)(\Su){1}\Dashline(\Fp)(\Sd){1}\Dashline(\Fp)(\St){1}}{}
\DistanceAndDirOfVect\Fp minus\Tt to\DFp and\AFu
\DistanceAndDirOfVect\F  minus\Tt to\DF and\AF
\SegmentCenter(\F)(\Fp)to\CE \Pbox(\CE)[b]{C}[1.5pt]

Modified: trunk/Master/texmf-dist/tex/latex/euclideangeometry/euclideangeometry.sty
===================================================================
--- trunk/Master/texmf-dist/tex/latex/euclideangeometry/euclideangeometry.sty	2020-04-11 22:23:52 UTC (rev 54658)
+++ trunk/Master/texmf-dist/tex/latex/euclideangeometry/euclideangeometry.sty	2020-04-11 22:24:25 UTC (rev 54659)
@@ -11,7 +11,7 @@
%%
\NeedsTeXFormat{LaTeX2e}[2019/01/01]
\ProvidesPackage{euclideangeometry}%
-        [2020-02-12 v.0.1.5 Extension package for curve2e]
+        [2020-03-30 v.0.1.7 Extension package for curve2e]

\RequirePackage{curve2e}
\@ifpackagelater{curve2e}{2020/01/18}{}%
@@ -132,6 +132,30 @@
\ScaleVect\Segm by0.5to#3\ignorespaces}

\let\MiddlePointOf\SegmentCenter
+\def\LegFromHypotenuse#1AndOtherLeg#2to#3{%
+  \edef#3{\fpeval{sqrt(#1**2-#2**2)}}}
+\def\IntersectionsOfLine(#1)(#2)WithCircle(#3)#4to#5and#6{%
+\CopyVect#3 to\C \edef\R{#4}
+\CopyVect#1to\Pu \CopyVect#2to\Pd
+\segment(\Pu)(\Pd)\SegmentArg(\Pu)(\Pd)to\Diru
+\edef\Dird{\fpeval{\Diru+90}}\Pbox(\C)[b]{C}[2]
+\IntersectionOfLines(\Pu)(\Diru:1)and(\C)(\Dird:1)to\Int
+\SegmentLength(\C)(\Int)to\A
+\fptest{\A > \R}{\PackageError{euclideangeometry}%
+{Distance of line \A\space larger than radius \R. No intersections}%
+{Check your data; correct and retry}}{%
+\LegFromHypotenuse\R AndOtherLeg\A to\B
+\SymmetricalPointOf\Pt respect\Int to\Pq \edef#6{\Pq}
+}}
+\def\Segment(#1)(#2)SymmetricPointOf#3to#4{%
+\SegmentArg(#1)(#2)to\Sanguno\edef\Sangdue{\fpeval{\Sanguno+90}}
+\IntersectionOfLines(#1)(\Sanguno:1)and(#3)(\Sangdue:1)to\Smed
+\SymmetricalPointOf#3respect\Smed to#4\ignorespaces}
+\def\CircleThrough#1WithCenter#2{%

\def\TriangleMedianBase#1on#2and#3to#4{%
\SubVect#1from#2to\TMBu \SubVect#1from#3to\TMBd
@@ -332,26 +356,26 @@
\IntersectionOfLines(\Pd)(\Au:1)and(\F)(\fpeval{\Au+90}:1)to\Mu
\IfBooleanTF{#1}{\Pbox(\Mt)[br]{M_3}[1.5pt]\Pbox(\Md)[t]{M_2}[1.5pt]
\Pbox(\Mu)[b]{M_1}[1.5pt]}{}
-\SymmetricalPointOf\F respect\Mu to\Gu
-\IfBooleanTF{#1}{\Pbox(\Gu)[l]{G_1}[1.5pt]}{}
-\SymmetricalPointOf\F respect \Md to\Gd
-\IfBooleanTF{#1}{\Pbox(\Gd)[t]{G_2}[1.5pt]}{}
-\SymmetricalPointOf\F respect \Mt to\Gt
-\IfBooleanTF{#1}{\Pbox(\Gt)[r]{G_3}[1.5pt]}{}
-\IfBooleanTF{#1}{\ThreePointCircle*(\Gu)(\Gd)(\Gt)}%
-                {\ThreePointCircle(\Gu)(\Gd)(\Gt)}
+\SymmetricalPointOf\F respect\Mu to\Su
+\IfBooleanTF{#1}{\Pbox(\Su)[l]{S_1}[1.5pt]}{}
+\SymmetricalPointOf\F respect \Md to\Sd
+\IfBooleanTF{#1}{\Pbox(\Sd)[t]{S_2}[1.5pt]}{}
+\SymmetricalPointOf\F respect \Mt to\St
+\IfBooleanTF{#1}{\Pbox(\St)[r]{S_3}[1.5pt]}{}
+\IfBooleanTF{#1}{\ThreePointCircle*(\Su)(\Sd)(\St)}%
+                {\ThreePointCircle(\Su)(\Sd)(\St)}
\CopyVect\C to\Fp \Pbox(\Fp)[l]{F'}[1.5pt]
\IfBooleanTF{#1}{%
-\Dotline(\F)(\Gt){2}[1.5pt]
-\Dotline(\F)(\Gd){2}[1.5pt]
-\Dotline(\F)(\Gu){2}[1.5pt]}{}
-\IntersectionOfSegments(\Pu)(\Pt)and(\Fp)(\Gt)to\Tt
-\IntersectionOfSegments(\Pu)(\Pd)and(\Fp)(\Gd)to\Td
-\IntersectionOfSegments(\Pd)(\Pt)and(\Fp)(\Gu)to\Tu
+\Dotline(\F)(\St){2}[1.5pt]
+\Dotline(\F)(\Sd){2}[1.5pt]
+\Dotline(\F)(\Su){2}[1.5pt]}{}
+\IntersectionOfSegments(\Pu)(\Pt)and(\Fp)(\St)to\Tt
+\IntersectionOfSegments(\Pu)(\Pd)and(\Fp)(\Sd)to\Td
+\IntersectionOfSegments(\Pd)(\Pt)and(\Fp)(\Su)to\Tu
\IfBooleanTF{#1}{\Pbox(\Tu)[l]{T_1}[1.5pt]
\Pbox(\Td)[b]{T_2}[1.5pt]
\Pbox(\Tt)[tl]{T_3}[1.5pt]
-\Dashline(\Fp)(\Gu){1}\Dashline(\Fp)(\Gd){1}\Dashline(\Fp)(\Gt){1}}{}
+\Dashline(\Fp)(\Su){1}\Dashline(\Fp)(\Sd){1}\Dashline(\Fp)(\St){1}}{}
\DistanceAndDirOfVect\Fp minus\Tt to\DFp and\AFu
\DistanceAndDirOfVect\F  minus\Tt to\DF and\AF
\SegmentCenter(\F)(\Fp)to\CE \Pbox(\CE)[b]{C}[1.5pt]


text:
Plant Diversity ›› 2012, Vol. 34 ›› Issue (6): 614-622.

• Articles •

### DNA Barcoding of Economically Important Mushrooms: A Case Study on Lethal Amanitas from China

CA  Qing, TANG  Li-Ping, YANG  Zhu-Liang

1. Key Laboratory of Biodiversity and Biogeography, Kunming Institute of Botany, Chinese Academy of Sciences, Kunming 650201, China
• Received:2012-11-05 Online:2012-12-25 Published:2012-11-09

Abstract:

Some species of the genus Amanita are economically important gourmet mushrooms, while others cause dramatic poisonings or even deaths every year in China and in many other countries. A DNA barcode is a short segment or a combination of short segments of DNA sequences that can distinguish species rapidly and accurately. To establish a standard DNA barcode for poisonous species of Amanita in China, three candidate markers, the large subunit nuclear ribosomal RNA (nLSU), the internal transcribed spacer (ITS), and the translation elongation factor 1alpha (tef1α) were tested using the eukaryotic general primers for their feasibility as barcodes to identify seven species of lethal fungi and two species of edible ones which can easily be confused with the lethal ones known from China. In addition, A.phalloides—a European and North American species closely related to one of the seven taxa, A.subjunquillea was also included. PCR amplification and sequencing success rate, intra and interspecific variation and rate of species identification were considered as main criteria for evaluation of the candidate DNA barcodes. Although the nLSU had high PCR and sequencing success rates (100% and 100% respectively), occasional overlapping occurred between the intra and interspecific variations. The PCR amplification and sequencing success rates of ITS were 100% and 85.7% respectively. ITS showed high sequence variation among species group and low variation within a given species. There was a relatively high PCR amplification and sequencing success rate for tef1α (85.7% and 100% respectively), and its intra and interspecific variation was higher than that of ITS or nLSU. All three candidate markers showed hight species resolution. ITS and tef1α had a more clearly defined barcode gap than nLSU. Our study showed that the tef1α and nLSU can be proposed as supplementary barcodes for the genus Amanita, while ITS can be used as a primary barcode marker considering that the ITS region may become a universal barcode marker for the fungal kingdom.

CLC Number:


text:
# Help with spring rotating around its axis of rotational symm

1. Nov 6, 2015

### starlord37

1. The problem statement, all variables and given/known data
An astronaut on a spacewalk loses her grip on a circular garter spring (pictured below). Looking at the spring she notices that it is rotating around its axis of rotational symmetry at a rate of 300 rpm. The circumference of the rotating garter spring is 1% longer than that of the garter spring when at rest. Calculate the spring constant of the spring if the radius of the rotating garter spring is R = 20 cm and its mass is 1 kg. (We are looking for the spring constant of the spring if it were cut open and stretched along a straight line.)

2. Relevant equations
T= Ia T=dL/dt K=1/2Iw^2 PE=1/2kx^2

3. The attempt at a solution
I tried using energy but then realized I had no initial state to compare it to. Then I tried using forces and torque but got stuck. This problem is problem 2 from the Canadian Physics Olympiad
http://phas-outreach.sites.olt.ubc.ca/files/2015/08/CAP-en-v7.pdf

2. Nov 7, 2015

### Simon Bridge

Welcome to PF.
Did you reason it out? What is the physics at play here?

3. Nov 7, 2015

### starlord37

Thanks. Well I figured since it's being stretched, the restoring force of the spring might be why it's rotating. It has some rotational kinetic energy, and we can find that because we're given omega. It also has some spring potential energy. There's a force radially inward with magnitude mv^2/R. And there's a force from the spring in some direction. I think that's all the physics that's going on.

4. Nov 8, 2015

### Simon Bridge

OK. You have things a little garbled. Consider:
Where does the radially inwards force (the mv^2/r one) come from?
(Aside: is this the rightbequation? I.e what is m in this equation?)
How does stretching a spring cause it to rotate?

You are looking for a narrative like: as the spring spins faster, it's circumference gets ________ until .... (fill in the blanks.)

Once you understand the physics, you can write it out using maths.
If the unstretched circumference is C, then the stretched circumference is what?
What is the formula relating tension T in the spring to the change in circumference $\Delta C$


text:
## An eighteen gauge copper wire has a nominal diameter of 1.02mm. This wire carries a constant current of 1.67A to a 200w lamp. The density of

Question

An eighteen gauge copper wire has a nominal diameter of 1.02mm. This wire carries a constant current of 1.67A to a 200w lamp. The density of free electrons is 8.5 x 1028 electrons per cubic metre. Find the magnitude of:
i. The current density ii. The drift velocity

in progress 0
6 months 2021-07-18T05:15:13+00:00 1 Answers 61 views 0

The current density is

The drift velocity is

Explanation:

From the question we are told that

The nominal diameter of the wire is

The current carried by the wire is

The power rating of the lamp is

The density of electron is

The current density is mathematically represented as

Where A is the area which is mathematically evaluated as

Substituting values

So

The drift velocity is mathematically represented as

Where e is the charge on one electron which has a value

So


text:
# Welcome to grmpy’s documentation!¶

grmpy is an open-source package for the simulation and estimation of the generalized Roy model. It serves as a teaching tool to promote the conceptual framework of the generalized Roy model, illustrate a variety of issues in the econometrics of policy evaluation, and showcase basic software engineering practices.

We build on the following main references:

James J. Heckman and Edward J. Vytlacil. Econometric evaluation of social programs, part I: Causal models, structural models and econometric policy evaluation. In Handbook of Econometrics, volume 6B, chapter 70, pages 4779–4874. Elsevier Science, 2007.

James J. Heckman and Edward J. Vytlacil. Econometric evaluation of social programs, part II: Using the marginal treatment effect to organize alternative econometric estimators to evaluate social programs, and to forecast their effects in new environments. In Handbook of Econometrics, volume 6B, chapter 71, pages 4875–5143. Elsevier Science, 2007.

Jaap H. Abbring and James J. Heckman. Econometric evaluation of social programs, part III: Distributional treatment effects, dynamic treatment effects, dynamic discrete choice, and general equilibrium policy evaluation. Handbook of Econometrics, volume 6B, chapter 72, pages 5145-5303. Elsevier Science, 2007.

The remainder of this documentation is structured as follows. We first present the basic economic model and provide installation instructions. We then illustrate the basic use case of the package in a tutorial and showcase some evidence regarding its reliability. In addition we provide some information on the software engineering tools that are used for transparency and dependability purposes. The documentation concludes with further information on contributing, contact details as well as a listing of the latest releases.

The package is used as a teaching tool for a course on the analysis human capital at the University of Bonn. The affiliated lecture material is available on GitHub .


text:
The development of high-performing planar solid oxide fuel cell (SOFC) stacks operating at intermediate temperature (700–850°C) is based on thin-electrolyte anode supported cells (ASCs) and interconnects made by ferritic stainless steels. These metallic materials match very well the thermal expansion behavior of the ASCs and can be manufactured and formed using cheaper and easier processes than ceramics or chromium alloys. Nevertheless, some problems remain to be solved with these components as the performance degradation due to the oxide scale growth at the cathodic contact surface and the evaporation of volatile Cr-containing species, which poisons the cathodic materials. Both effects strongly limit the stack performance compared to single cells and increase the degradation rate with time. Providing the steel composition is carefully controlled, the above problems can be limited and some special ferritic stainless steels have been developed in the past years for SOFC application. Unfortunately, no commercial alloy is still able to satisfy the limit in degradation rate required for stationary applications (SECA target is $<0.25%$ upon $1000h$ on a minimum service life of $40,000h$). To achieve these goals a further improvement of composition should be required but this cannot be easily obtained in a cost-effective large-scale metallurgical production. An alternative and probably simpler way is to coat the surface of the steel with a protective layer with the twofold aim to limit Cr evaporation and to develop a conductive scale. In the present work, the effect of different oxide coatings on the chromium evaporation rate and on the contact resistance of ferritic stainless steel has been investigated. To obtain a conductive layer, spinel compositions containing Co, Mn, and Cu have been considered. Steels surfaces have been spray-coated using alcoholic suspensions, and the microstructural evolution of the interface between the metallic substrate and oxide layers has been investigated by scanning electron microscopy and energy dispersive X-ray spectroscopy line-scan analysis for exposure at high temperature. The variation with time of the area-specific resistance at 800°C has been recorded up to $1000h$. The evaporation rate of Cr-containing species has been also evaluated by a qualitative method.

1.
U.S. Department of Energy, 2002, “
Fuel Cell Handbook
,” 6th ed., DOE/NETL-2002/1179,
Office of Fossil Energy
,
Morgantown, WV
.
2.
Zhu
,
W. Z.
, and
Deevi
,
S. C.
, 2003, “
Opportunity of Metallic Interconnects for Solid Oxide Fuel Cells: A Status on Contact Resistance
,”
Mater. Res. Bull.
0025-5408,
38
, pp.
957
972
.
3.
Wei-zhong
,
Z.
, and
Mi
,
Y.
, 2004, “
Perspectives on the Metallic Interconnects for Solid Oxide Fuel Cells
,”
J. Zhejiang Univ., Sci.
1009-3095,
12
, pp.
1471
1503
.
4.
,
W. J.
,
Piron-Abellan
,
J.
,
Shemet
,
V.
, and
Singheiser
,
L.
, 2003, “
Metallic Interconnectors for Solid Oxide Fuel Cells—A Review
,”
Mater. High. Temp.
0960-3409,
20
(
2
), pp.
115
127
.
5.
Visco
,
S.
,
Jacobson
,
C.
,
Chen
,
X.
, and
De Jonghe
,
L. C.
, 2004, “
Enhancement of Electrode and Interconnect Performance
,”
Workshop of SECA Core Technology Review
,
May 11-13, Boston, MA.
6.
Colomer
,
M. T.
,
Fumo
,
D. A.
,
,
J. R.
, and
,
A. M.
, 1999, “
Non-Stoichiometric La(1−x)NiO(3−δ) Perovskites Produced by Combustion Synthesis
,”
J. Mater. Chem.
0959-9428,
9
, pp.
2505
2510
.
7.
Ling
,
H.
, and
Petric
,
A.
, 2005, “
Electrical and Thermal Properties of Spinels
,”
Proc. Solid Oxide Fuel Cells IX
,
S. C.
Singhal
, and
M.
Dokiya
eds.,
The Electrochemical Society, Inc.
, Pennington, NJ, pp.
1866
1873
.
8.
Konycheva
,
E.
,
Laatsch
,
J.
,
Wessel
,
E.
,
Tietz
,
F.
,
Christiansen
,
N.
,
Singheiser
,
L.
, and
Hilpert
,
K.
, 2004, “
Contact Resistance Between La0.65Sr0.3MnO3 and Different Steels Using a Perovskite Intermediate Contact Layer
,”
Procs. 6th European SOFC Forum
,
28 June–2 July, Lucerne, Switzerland, pp.
1586
1593
.
9.
Uehara
,
T.
,
Toji
,
A.
, and
Ohno
,
T.
, 2004, “
Improvement of High Temperature Properties of Ferritic Fe-Cr Alloy for SOFC Interconnects
,”
Procs. 6th European SOFC Forum
,
28 June–2 July, Lucerne, Switzerland, pp.
1638
1645
.
10.
Dekker
,
N.
,
Rietveld
,
B.
,
Laatsch
,
J.
, and
Tietz
,
F.
, 2004, “
Evaluation of Interconnect Alloys and Cathode Contact Coatings for SOFC Stacks
,”
Procs. 6th European SOFC Forum
,
28 June–2 July, Lucerne, Switzerland, pp.
319
328
.
11.
Zahid
,
M.
,
Tietz
,
F.
,
Sebold
,
D.
, and
Buchkremer
,
H. P.
, 2004, “
Reactive Coatings Against Chromium Vaporation in Solid Oxide Fuel Cells
,”
Procs. 6th European SOFC Forum
,
28 June–2 July, Lucerne, Switzerland, pp.
820
827
.


text:
This is not designed to be a comprehensive review. There may be items on the exam that are not covered in this review. Similarly, there may be items in this review that are not tested on this exam. You are strongly encouraged to review the readings, homework exercises, and other activities from Unit 1 as you prepare for the exam.

Unit 1 Lesson Outcomes

Show/Hide Outcomes

Unit 1 Lesson Summaries

Show/Hide Summaries

Lesson 01 Recap
• Each lesson follows the same schedule: Individual and Group Preparation, Class Meeting, and Homework Assignment and Quiz. Understanding this layout will help you successfully manage the workload of this class.

• In this class you will use the online textbook that has been written for you by your statistics teachers. All of the assignments and quizzes will be based on the readings, so study it well.

• By doing the work, staying on schedule, and living the Honor Code you can succeed in this class!

Lesson 02 Recap
• The Statistical Process has five steps: Design the study, Collect the data, Describe the data, Make inferences, Take action.

• In a designed experiment, researchers control the conditions of the study. In an observational study, researchers don’t control the conditions but only observe what happens.

• There are many sampling methods used to obtain a sample from a population:

• A simple random sample (SRS) is a random selection taken from a population
• A systematic sample is every kth item in the population, beginning at a random starting point
• A cluster sample is all items in one or more randomly selected clusters, or blocks
• A stratified sample divides data into similar groups and an SRS is taken from each group
• A convenience sample is one easily obtained in a less-than-systematic way and should be avoided whenever possible
• Quantitative variables represent things that are numeric in nature, such as the value of a car or the number of students in a classroom. Categorical variables represent nonnumerical data that can only be considered as labels, such as colors or brands of shoes.

Lesson 03 Recap
• A histogram allows us to visually interpret data. Histograms can be left-skewed, right-skewed, or symmetrical and bell-shaped.

• The mean, median, and mode are measures of the center of a distribution. The mean is the most common measure of center and is computed by adding up the observed data and dividing by the number of observations in the data set.

• The standard deviation is a number that describes how spread out the data are. A larger standard deviation means the data are more spread out than data with a smaller standard deviation.

• A parameter is a true (but usually unknown) number that describes a population. A statistic is an estimate of a parameter obtained from a sample.

• Quartiles/percentiles, Five-Number Summaries, and Boxplots are tools that help us understand data. The five-number summary of a data set contains the minimum value, the first quartile, the median, the third quartile, and the maximum value. A boxplot is a graphical representation of the five-number summary.

Lesson 04 Recap
• The three rules of probability are:
1. A probability is a number between 0 and 1. $0 \leq P(X) \leq 1$

2. If you list all the outcomes of a probability experiment (such as rolling a die) the probability that one of these outcomes will occur is 1. In other words, the sum of the probabilities in any probability is 1. $\sum P(X) = 1$

3. The probability that an outcome will not occur is 1 minus the probability that it will occur. $P(\text{not}~X) = 1 - P(X)$

Lesson 05 Recap
• A normal density curve is symmetric and bell-shaped. The curve lies above the horizontal axis and the total area under the curve is equal to 1.

• A standard normal distribution has a mean of 0 and a standard deviation of 1. The 68-95-99.7% rule states that when data are normally distributed, approximately 68% of the data lie within 1 standard deviation from the mean, approximately 95% of the data lie within 2 standard deviations from the mean, and approximately 99.7% of the data lie within 3 standard deviations from the mean.

• A z-score tells us how many standard deviations away from the mean a given value is. It is calculated as: $$\displaystyle{z = \frac{\text{value}-\text{mean}}{\text{standard deviation}} = \frac{x-\mu}{\sigma}}$$

• The probability applet allows us to use z-scores to calculate proportions, probabilities, and percentiles.

Lesson 06 Recap
• The distribution of sample means is a distribution of all possible sample means ($$\bar x$$) for a particular sample size. It has a mean of $$\mu$$ and a standard deviation of $$\sigma/\sqrt{n}$$.

• The distribution of sample means is normal when $$\bar x$$ is normally distributed or when, thanks to the Central Limit Theorem (CLT), our sample size ($$n$$) is large.

• The Law of Large Numbers states that as the sample size ($$n$$) gets larger, the sample mean ($$\bar x$$) will get closer to the population mean ($$\mu$$).

Lesson 07 Recap
• When the distribution of sample means is normally distributed, we can use z-scores and the probability applet to calculate proportions and probabilities. A z-score is calculated as: $$\displaystyle{z = \frac{\text{value}-\text{mean}}{\text{standard deviation}} = \frac{\bar x-\mu}{\sigma/\sqrt{n}}}$$

• The $$P$$-value is the probability of getting a test statistic at least as extreme as the one you got, assuming $$H_0$$ is true. A $$P$$-value is calculated by finding the area under the normal distribution curve that is more extreme (farther away from the mean) than the z-score.


text:
On the composition of an arbitrary collection of SU (2) spins: an enumerative combinatoric approach

The whole enterprise of spin compositions can be recast as simple enumerative combinatoric problems.
We show here that enumerative combinatorics (Stanley 2011 Enumerative Combinatorics ( Cambridge
Studies in Advanced Mathematics vol 1) (Cambridge: Cambridge University Press)) is a natural setting
for spin composition, and easily leads to very general analytic formulae—many of which hitherto not
present in the literature. Based on it, we propose three general methods for computing spin
multiplicities; namely, (1) the multi-restricted composition, (2) the generalized binomial and (3)
the generating function methods. Symmetric and anti-symmetric compositions of ##IMG##
[http://ej.iop.org/images/1751-8121/51/10/105202/aaaa8faieqn003.gif] {$SU(2)$} spins are also
discussed, using generating functions. Of particular importance is the observation that while the
common Clebsch–Gordan decomposition—which considers the spins as distinguishable—is relate...


text:
# NbAiLab /Wav2Vec-Template

YAML Metadata Error: "language[0]" must only contain lowercase characters
YAML Metadata Error: "language[0]" with value "nb-NO" is not valid. It must be an ISO 639-1, 639-2 or 639-3 code (two/three letters), or a special value like "code", "multilingual". If you want to use BCP-47 identifiers, you can specify them in language_bcp47.

# Norwegian Wav2Vec2 Model - 1B - Bokmål

This achieves the following results on the test set with a 5-gram KenLM:

• WER: 0.0668
• CER: 0.0256

Without using a language model, we are getting these results:

• WER: ???
• CER: ???

## Model description

This is one of several Wav2Vec-models created during the 🤗 hosted Robust Speech Event. In parallell with the event, the team also converted the Norwegian Parliamentary Speech Corpus (NPSC) to the 🤗 Dataset format and used that as the main source for training.

We do release all code developed during the event so that the Norwegian NLP community can build upon this to develop even better Norwegian ASR models. The finetuning of these models are not very compute demanding. You should after following the instructions here, be able to train your own automatic speech recognition system in less than a day with an average GPU.

## Team

The following people contributed to building this model: Rolv-Arild Braaten, Per Egil Kummervold, Andre Kåsen, Javier de la Rosa, Per Erik Solberg, and Freddy Wetjen.

## Training procedure

To reproduce these results, we strongly recommend that you follow the instructions from HuggingFace to train a simple Swedish model.

When you have verified that you are able to do this, create a fresh new repo. You can then start by copying the files run.sh and run_speech_recognition_ctc.py from our repo. Running this will create all the other necessary files, and should let you reproduce our results. With some tweaks to the hyperparameters, you might even be able to build an even better ASR. Good luck!

### Language Model

As you see from the results above, adding even a simple 5-gram language will significantly improve the results. 🤗 has provided another very nice blog about how to add a 5-gram language model to improve the ASR model. You can build this from your own corpus, for instance by extracting some suitable text from the Norwegian Colossal Corpus. You can also skip some of the steps in the guide, and copy the 5-gram model from this repo.

### Parameters

The following parameters were used during training:

--dataset_name="NbAiLab/NPSC"
--dataset_config_name="16K_mp3_bokmaal"
--output_dir="./"
--overwrite_output_dir
--num_train_epochs="40"
--per_device_train_batch_size="12"
--per_device_eval_batch_size="12"
--learning_rate="2e-5"
--warmup_steps="2000"
--length_column_name="input_length"
--evaluation_strategy="steps"
--text_column_name="text"
--save_steps="500"
--eval_steps="500"
--logging_steps="100"
--layerdrop="0.041"
--attention_dropout="0.094"
--activation_dropout="0.055"
--hidden_dropout="0.047"
--save_total_limit="3"
--freeze_feature_encoder
--feat_proj_dropout="0.04"
--min_duration_in_seconds="0.5"
--max_duration_in_seconds="30.0"
--ctc_zero_infinity=True
--use_auth_token
--seed="42"
--fp16
--group_by_length
--do_train --do_eval
--push_to_hub
--preprocessing_num_workers="16"

Following this settings, the training might take 3-4 days on an average GPU. You should however get a decent model and faster results by tweaking these parameters

Parameter Comment
per_device_train_batch_size Adjust this to the maximum of available memory. 16 or 24 might be good settings depending on your system
gradient_accumulation_steps Can be adjusted even further up to increase batch size and speed up training without running into memory issues
learning_rate Can be increased, maybe as high as 1e-4. Speeds up training but might add instability
epochs Can be decreased significantly. This is a huge dataset and you might get a decent result already after a couple of epochs